Files
dbx-main/app/modules/live/ocr.py
T
king 9c94f70e54 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>
2026-11-06 11:09:03 +09:00

72 lines
3.2 KiB
Python

"""방송 결과 이미지(틱톡 LIVE 결과 화면)에서 매출 읽기(2026-11-06).
틱톡 화면 맨 위 카드 `RM672.2 / Attr. GMV` 의 첫 `RM` 금액을 판매금액으로 쓴다. 글자 인식 = 서버의 Tesseract(`tesseract`
명령, Dockerfile 에서 설치) — 외부로 보내지 않는다. 읽은 값은 창의 칸에 채워 줄 뿐이고, 사람이 확인한 뒤 저장한다.
"""
from __future__ import annotations
import io
import re
import shutil
import subprocess
from decimal import Decimal, InvalidOperation
from PIL import Image, ImageOps
from app.modules.asset.media import prepare_photo
from .i18n import LiveError
TIMEOUT_SECONDS = 30
# 'RM672.2', 'RM 1,234.50', 'RM1.2K'(줄인 값) — OCR 이 RM 사이에 빈칸을 넣기도 한다
_RM_RE = re.compile(r"R\s?M\s*([0-9][0-9,]*(?:[.,][0-9]+)?)\s*([KkMm](?![A-Za-z]))?")
def parse_sales(text: str) -> tuple[Decimal | None, str]:
"""OCR 글자 → (금액, 읽은 원문). 첫 RM 금액을 쓴다(아래 Rewards 칸은 $). K·M 으로 줄인 값은 정확하지 않아 None."""
m = _RM_RE.search(text or "")
if not m:
return None, ""
raw, suffix = m.group(1), m.group(2)
shown = "RM" + raw + (suffix or "")
if suffix:
return None, shown
num = raw
if "." not in num and "," in num and len(num.rsplit(",", 1)[1]) <= 2: # 'RM672,2' = 점을 쉼표로 읽음
num = num[: num.rfind(",")] + "." + num.rsplit(",", 1)[1]
try:
value = Decimal(num.replace(",", ""))
except InvalidOperation:
return None, shown
return value.quantize(Decimal("0.01")), shown
def _ocr_text(img: Image.Image) -> str:
exe = shutil.which("tesseract")
if not exe:
raise LiveError("서버에 글자 인식 프로그램(tesseract)이 없습니다. 판매금액을 직접 입력하세요.")
gray = ImageOps.grayscale(img)
if gray.width < 1000: # 작은 캡처는 키워야 잘 읽힌다
gray = gray.resize((gray.width * 2, gray.height * 2), Image.LANCZOS)
buf = io.BytesIO()
gray.save(buf, format="PNG")
try:
res = subprocess.run([exe, "stdin", "stdout", "-l", "eng", "--psm", "11"], input=buf.getvalue(),
capture_output=True, timeout=TIMEOUT_SECONDS, check=False)
except subprocess.TimeoutExpired:
raise LiveError("이미지 글자 인식이 너무 오래 걸립니다. 판매금액을 직접 입력하세요.") from None
if res.returncode != 0:
raise LiveError("이미지 글자를 읽지 못했습니다. 판매금액을 직접 입력하세요.")
return res.stdout.decode("utf-8", "replace")
def read_sales(raw: bytes) -> tuple[Decimal | None, str]:
"""이미지 바이트 → (금액, 읽은 원문). 이미지가 아니면 ValueError(prepare_photo 문구)."""
data, _ctype, _w, _h = prepare_photo(raw) # 실제 이미지 확인·크기 제한(저장과 같은 규칙)
with Image.open(io.BytesIO(data)) as img:
img.load()
# 매출 카드는 화면 위쪽 — 위 절반만 읽어 빠르고, 아래 다른 금액을 잘못 잡지 않게
top = img.crop((0, 0, img.width, max(1, img.height // 2)))
return parse_sales(_ocr_text(top))