feat(라이브): 결과 이미지에서 매출을 읽어 판매금액 칸에 채움

- 방송 창에서 이미지를 고르면 POST /live/broadcasts/read-sales 가 서버 Tesseract 로
  이미지 위 절반의 첫 RM 금액(틱톡 LIVE 결과 화면 Attr. GMV)을 읽어 돌려줌(저장 안 함)
- RM1.2K 같은 줄인 값·못 찾음은 칸을 두고 안내, 사람이 확인 후 저장
- Dockerfile: tesseract-ocr·tesseract-ocr-eng 설치

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-06 11:09:03 +09:00
parent 7e0f7f7642
commit 9c94f70e54
12 changed files with 197 additions and 10 deletions
+68 -2
View File
@@ -21,7 +21,7 @@ from PIL import Image
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
from app.modules.live import i18n, store # noqa: E402
from app.modules.live import i18n, ocr, store # noqa: E402
DSN = os.getenv("LIVE_TEST_DB_URL", "")
DB_ENABLED = bool(DSN) and urlparse(DSN).hostname in ("localhost", "127.0.0.1")
@@ -221,6 +221,39 @@ class StoreTests(unittest.TestCase):
self.assertEqual((im.format, im.size), ("JPEG", (160, 80)))
class OcrTests(unittest.TestCase):
"""결과 이미지 → 매출(2026-11-06). 실제 글자 인식(tesseract)은 서버 이미지에만 — 여기서는 읽은 글자 풀이와 흐름."""
def test_parse_sales(self):
# 틱톡 LIVE 결과 화면을 tesseract --psm 11 로 읽은 모양(단어마다 줄)
screen = "Duration: 2h 5m\n\nCongratulations!\n\nRM672.2\n\n10\n\n16\n\nAttr. GMV\n\nAttr. items sold\n\nPer-LIVE\n\n$0.04"
self.assertEqual(ocr.parse_sales(screen), (Decimal("672.20"), "RM672.2"))
for text, want in (("RM 1,234.50", Decimal("1234.50")), ("R M672,2", Decimal("672.20")), ("RM12,345", Decimal("12345.00")),
("RM0", Decimal("0.00")), ("Attr GMV RM98.75 x", Decimal("98.75"))):
self.assertEqual(ocr.parse_sales(text)[0], want, text)
self.assertEqual(ocr.parse_sales("RM1.2K\nAttr. GMV"), (None, "RM1.2K")) # 줄인 값 = 쓰지 않음
self.assertEqual(ocr.parse_sales("Rewards $0.04 6.5K"), (None, ""))
self.assertEqual(ocr.parse_sales(""), (None, ""))
def test_read_sales_top_half_and_errors(self):
from unittest.mock import patch
raw = io.BytesIO()
Image.new("RGB", (464, 1005), "white").save(raw, format="PNG")
seen = {}
def fake(img):
seen["size"] = img.size
return "RM672.2\nAttr. GMV"
with patch.object(ocr, "_ocr_text", side_effect=fake):
self.assertEqual(ocr.read_sales(raw.getvalue()), (Decimal("672.20"), "RM672.2"))
self.assertEqual(seen["size"], (464, 502)) # 위 절반만
with patch.object(ocr.shutil, "which", return_value=None):
with self.assertRaises(i18n.LiveError):
ocr.read_sales(raw.getvalue())
with self.assertRaises(ValueError):
ocr.read_sales(b"not an image")
class I18nTests(unittest.TestCase):
def test_every_text_has_english(self):
"""템플릿·오류·권한 문구가 모두 영문 표에 있다 — 새 문구를 넣고 빠뜨리면 여기서 걸린다."""
@@ -228,7 +261,7 @@ class I18nTests(unittest.TestCase):
keys = set(i18n.JS_KEYS) | set(store._LABELS.values()) | {"시작 시간", "끝 시간"}
for path in (live / "templates" / "live").glob("*.html"):
keys |= set(re.findall(r"\bt\('([^']+)'\)", path.read_text(encoding="utf-8")))
for name in ("store.py", "db.py", "router.py"):
for name in ("store.py", "db.py", "router.py", "ocr.py"):
text = (live / name).read_text(encoding="utf-8")
keys |= set(re.findall(r'LiveError\("([^"]+)"', text))
keys |= set(re.findall(r'_t\(request, "([^"]+)"\)', text))
@@ -459,6 +492,39 @@ def body(c):
assert c.get("/live/images/1").status_code == 403
print("OK")
run(body)
''')
self.assertEqual(res.returncode, 0, res.stdout + res.stderr)
self.assertIn("OK", res.stdout)
def test_read_sales_endpoint(self):
"""결과 이미지 → 매출 읽기 — 저장 없이 값만, 권한 필요, 못 찾거나 줄인 값이면 amount 없음(DB 없이)."""
res = _run('''
import io
from PIL import Image
from app.modules.live import ocr
raw = io.BytesIO(); Image.new("RGB", (400, 800), "white").save(raw, format="PNG"); png = raw.getvalue()
said = {"text": "RM672.2\\nAttr. GMV"}
def body(c):
send = lambda: c.post("/live/broadcasts/read-sales", files={"image": ("r.png", png, "image/png")})
with patch.object(ocr, "_ocr_text", side_effect=lambda img: said["text"]):
who["u"] = U("s@t.local")
r = send().json()
assert r["ok"] and r["amount"] == "672.20" and "RM672.2" in r["message"], r
said["text"] = "RM1.2K"
r = send().json()
assert r["ok"] and r["amount"] is None and "RM1.2K" in r["message"], r
said["text"] = "nothing"
assert send().json()["amount"] is None
c.cookies.set("live_lang", "en")
assert send().json()["message"].startswith("Couldn't find the sales")
bad = c.post("/live/broadcasts/read-sales", files={"image": ("x.png", b"nope", "image/png")})
assert bad.status_code == 400
who["u"] = U("x@t.local", live=False)
assert send().status_code == 403
print("OK")
run(body)
''')
self.assertEqual(res.returncode, 0, res.stdout + res.stderr)
self.assertIn("OK", res.stdout)