2 Commits

Author SHA1 Message Date
king 6ec5485e70 Merge branch 'feat/live-ocr-sales' 2026-11-06 11:09:04 +09:00
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
12 changed files with 197 additions and 10 deletions
+5
View File
@@ -3,6 +3,11 @@ FROM python:3.12-slim
# 작업 디렉토리
WORKDIR /app
# 글자 인식(라이브 커머스 결과 이미지 → 매출, app/modules/live/ocr.py) — 영어 데이터만
RUN apt-get update \
&& apt-get install -y --no-install-recommends tesseract-ocr tesseract-ocr-eng \
&& rm -rf /var/lib/apt/lists/*
# 의존성 먼저 설치 (캐시 활용)
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
+1
View File
@@ -22,6 +22,7 @@
- **한 화면 맞춤**(2026-11-05) — 달력 보기는 넓은 화면(1101px 이상)에서 페이지 세로 스크롤 없음: `.lv-cal-wrap` 이 남은 높이를 쓰고, 풀HD 브라우저(세로 880px 이상)면 방송이 없는 달은 18개 시간 칸·합계 줄이 표 안 스크롤 없이 들어간다(카드가 있는 줄은 카드 높이만큼 커져서 방송이 많으면 표 안에서 스크롤, 페이지는 안 움직임). **방송이 걸친 칸은 합친다**(2026-11-06, `store._covered_slots` → `rowspan`, 가려진 칸 `skip`) — 2시간 방송 = 두 칸, 끝이 정각이 아니면 그 칸까지, 자정 넘김은 그날 마지막 칸까지. 합친 칸 안에서 시작하는 다른 방송은 같은 칸에 들어가고 칸이 더 늘어난다(겹친 방송). 끌어 놓기는 합친 칸의 첫 시간으로. 카드·표 글자·칸 크기를 늘리면 `live_calendar.browser.test.js` 로 다시 확인.
- **오른쪽 달력**(2026-11-05, 달력 보기만, 세로 2분할 `.lv-split`, 240px = 공용 달력의 80%, 예전 날짜로 이동 줄 대신, 공용 `erp-datepop` `mountRange` + `locale` 옵션으로 영문) — 날짜를 누르면 그 날이 표 맨 왼쪽(마지막 날까지 — `endGap` 이 표 끝에 여백), 다른 달이면 그 달 화면으로 가서 맨 왼쪽(sessionStorage `lv_cal_jump`). 표시만 하고 요금·일수에 안 씀. 글자 굵게, **방송 있는 날 = 숫자 오른쪽 위 초록 점**(2026-11-06, `db.broadcast_days` 보는 달 ±1년 → `#lv-live-days`, 공용 `mountRange` 의 `dayClass` 옵션 → `has-live`). 테스트 `tests/js/live_calendar.browser.test.js`(`render_live.py`).
**말레이시아 공휴일 표 = `holidays.py`**(쿠알라룸푸르 기준, 2026·2027, 대체휴일 포함) — 이슬람 명절은 달 관측으로 바뀔 수 있고, 2028 은 공고되면 손으로 추가.
- **결과 이미지 → 매출 자동 입력**(2026-11-06, `ocr.py`, `POST /live/broadcasts/read-sales`) — 창에서 이미지를 고르면 서버의 Tesseract(Dockerfile 에서 설치, 외부 전송 없음)가 이미지 **위 절반**을 읽어 첫 `RM` 금액(틱톡 LIVE 결과 화면의 Attr. GMV)을 판매금액 칸에 채운다(저장 안 함 — 사람이 확인 후 저장, 여러 장이면 찾을 때까지 한 장씩). `RM1.2K` 처럼 줄인 값·못 찾음 = 칸 그대로 + 안내. tesseract 가 없으면(로컬 개발 PC) 안내만.
- **결과 이미지** — 방송 저장과 한 트랜잭션, JPG·PNG·WebP, 한 장 8MB, 방송당 10장(`store.MAX_IMAGES`). `prepare_photo` 가 실제 이미지 확인·긴 변 2400px·EXIF(GPS 등) 제거. BYTEA 저장.
`GET /live/images/{id}`(권한 필요, 하루 private 캐시), `?thumb=1` = 160px JPEG(그때그때 만듦). 올린 뒤 내용이 안 바뀐다는 전제 — 이미지를 고치는 기능을 넣으면 캐시도 바꿀 것.
- 라이브 커머스 화면은 공용 최대 폭(1550px)을 풀어 **화면 전체 너비**를 쓴다(`live.css` 맨 위, 스케줄표·달력·호스트 설정).
+8 -1
View File
@@ -41,6 +41,13 @@ EN: dict[str, str] = {
"계좌번호": "Bank Account Number", "틱톡 핸들": "Tiktok Handle", "상태": "Status", "사용": "Active",
"{name} 호스트를 지울까요?": "Delete host {name}?", "등록한 호스트가 없습니다.": "No hosts registered.",
"사용 (끄면 새 방송에서 고를 수 없습니다)": "Active (when off, the host can't be selected for new broadcasts)",
"이미지 매출이 줄인 값({value})이라 정확하지 않습니다. 판매금액을 직접 입력하세요.": "The sales in the image are abbreviated ({value}), so they're not exact. Please enter the Sales yourself.",
"이미지에서 매출(RM)을 찾지 못했습니다. 판매금액을 직접 입력하세요.": "Couldn't find the sales (RM) in the image. Please enter the Sales yourself.",
"이미지에서 매출 {value} 를 읽었습니다. 확인 후 저장하세요.": "Read sales {value} from the image. Please check it, then save.",
"서버에 글자 인식 프로그램(tesseract)이 없습니다. 판매금액을 직접 입력하세요.": "Text recognition (tesseract) isn't installed on the server. Please enter the Sales yourself.",
"이미지 글자 인식이 너무 오래 걸립니다. 판매금액을 직접 입력하세요.": "Reading the image took too long. Please enter the Sales yourself.",
"이미지 글자를 읽지 못했습니다. 판매금액을 직접 입력하세요.": "Couldn't read the text in the image. Please enter the Sales yourself.",
"이미지에서 매출을 읽는 중…": "Reading sales from the image…",
"쇼핑몰": "Platform", "쇼핑몰(틱톡·쇼피)을 고르세요.": "Choose the platform (TikTok or Shopee).",
"사용으로 바꿨습니다.": "Set to active.", "사용 안 함으로 바꿨습니다.": "Set to inactive.",
# 화면 스크립트(live.js)
@@ -79,7 +86,7 @@ EN: dict[str, str] = {
# 화면 스크립트에 넘기는 문구(window.LV_T)
JS_KEYS = ("확인", "취소", "지우기", "서버에 연결하지 못했습니다. 입력한 값은 그대로 있으니 다시 저장해 보세요.", "이 이미지", "{name} 를 지울까요?",
"{day} 광고비 (RM) — 비우면 지웁니다")
"{day} 광고비 (RM) — 비우면 지웁니다", "이미지에서 매출을 읽는 중…")
_MONTH_NAMES = ("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December")
+71
View File
@@ -0,0 +1,71 @@
"""방송 결과 이미지(틱톡 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))
+16 -1
View File
@@ -25,7 +25,7 @@ from fastapi.responses import HTMLResponse, JSONResponse, Response
from app.modules.asset.media import MAX_PHOTO_BYTES, prepare_photo
from app.timezone import today_kst
from . import holidays, i18n, store
from . import holidays, i18n, ocr, store
router = APIRouter(prefix="/live", tags=["live"])
@@ -228,6 +228,21 @@ def broadcast_save(request: Request, id: str = Form(""), host_id: str = Form("")
return _ok(request, "저장했습니다.")
@router.post("/broadcasts/read-sales")
def broadcast_read_sales(request: Request, image: UploadFile = File(...)) -> JSONResponse:
"""결과 이미지(틱톡 LIVE 결과 화면)에서 매출 읽기 — 저장하지 않고 값만 돌려준다(창이 판매금액 칸에 채움)."""
_user(request)
try:
amount, shown = ocr.read_sales(image.file.read(MAX_PHOTO_BYTES + 1))
except ValueError as exc:
return _fail(request, exc)
if amount is None:
msg = (_t(request, "이미지 매출이 줄인 값({value})이라 정확하지 않습니다. 판매금액을 직접 입력하세요.").format(value=shown) if shown
else _t(request, "이미지에서 매출(RM)을 찾지 못했습니다. 판매금액을 직접 입력하세요."))
return JSONResponse({"ok": True, "amount": None, "message": msg})
return JSONResponse({"ok": True, "amount": str(amount), "message": _t(request, "이미지에서 매출 {value} 를 읽었습니다. 확인 후 저장하세요.").format(value=shown)})
@router.post("/broadcasts/{broadcast_id}/delete")
def broadcast_delete(request: Request, broadcast_id: int) -> JSONResponse:
_user(request)
@@ -1,2 +1,2 @@
<script>window.LV_T = {{ js_text | tojson }};</script>
<script src="/static/live.js?v=20261106b" defer></script>
<script src="/static/live.js?v=20261106c" defer></script>
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %}
{#- 라이브 커머스 달력 보기(2026-11-04) — 줄 = 2시간 칸, 열 = 날짜, 맨 아래 = 날짜별 합계. 카드 머리 = 호스트 간단한 이름 + 그 방송의 틱톡 계정.
카드 머리를 끌어 빈 칸으로 옮기거나 다른 카드 위에 놓아 맞바꾼다(live.js). 문구 = t()(i18n.py), 영문은 CSS 로 대문자(받은 화면과 같게). -#}
{% block head_extra %}<link rel="stylesheet" href="/static/live.css?v=20261106c" />
{% block head_extra %}<link rel="stylesheet" href="/static/live.css?v=20261106d" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
<link rel="stylesheet" href="/static/erp-datepop.css?v=20261102a" />{% endblock %}
+1 -1
View File
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
{#- 라이브 커머스 스케줄표(2026-11-04) — 달마다 방송 목록. 추가·고치기 창은 달력과 공용(_dialog.html, live.js). 문구 = t()(i18n.py). -#}
{% block head_extra %}<link rel="stylesheet" href="/static/live.css?v=20261106c" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/live.css?v=20261106d" />{% endblock %}
{% block content %}
<section class="lv" lang="{{ lang }}">
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
{#- 라이브 커머스 설정(2026-11-04) — 호스트 정보. 계좌 등 개인정보·지우기는 ERP 관리자만(router.settings), 칩 권한자는 이름·상태만 보임 — `live_host` = 새 등록, `live_host_edit` = 고치기(개인정보는 빈칸으로 열림, 비워 두면 그대로). 추가·고치기는 같은 창(live.js). 문구 = t()(i18n.py). -#}
{% block head_extra %}<link rel="stylesheet" href="/static/live.css?v=20261106c" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/live.css?v=20261106d" />{% endblock %}
{% block content %}
{#- 쇼핑몰(005, store.PLATFORMS) — 로고는 말레이시아 배송 모듈 이미지 -#}
+1
View File
@@ -145,4 +145,5 @@
.lv-saved li { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
.lv-saved a { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.lv-msg { margin: 0; padding: 9px 12px; border-radius: 8px; background: #fbe9e6; color: #a1261b; border: 1px solid #efc6bf; font-size: 13px; }
.lv-msg.is-info { background: #e8f1ff; color: #1d4f91; border-color: #c5d8f5; } /* 이미지에서 매출 읽기 안내(오류 아님) */
.lv-foot { display: flex; justify-content: flex-end; gap: 8px; }
+23 -2
View File
@@ -27,16 +27,17 @@
const hostSelect = form.querySelector('select[name="host_id"]');
const fileInput = form.querySelector('input[type="file"]');
function say(text) {
function say(text, info) {
msg.textContent = text || "";
msg.hidden = !text;
msg.classList.toggle("is-info", !!info);
}
async function post(url, body) {
try {
const res = await fetch(url, { method: "POST", body: body, headers: { Accept: "application/json" } });
const data = await res.json().catch(function () { return {}; });
return { ok: res.ok && data.ok !== false, message: data.message || data.detail || "HTTP " + res.status };
return { ok: res.ok && data.ok !== false, message: data.message || data.detail || "HTTP " + res.status, data: data };
} catch (_) {
return { ok: false, message: tr("서버에 연결하지 못했습니다. 입력한 값은 그대로 있으니 다시 저장해 보세요.") };
}
@@ -128,6 +129,26 @@
if (edit) { const row = JSON.parse(edit.dataset.edit); row.is_active = sw.checked; edit.dataset.edit = JSON.stringify(row); }
});
// 결과 이미지를 고르면 서버가 글자 인식으로 매출(틱톡 LIVE 결과 화면의 첫 RM 금액)을 읽어 판매금액 칸에 채운다 — 저장은 사람이 확인 후
const salesInput = form.elements.sales_amount;
if (fileInput && salesInput) fileInput.addEventListener("change", async function () {
const files = Array.from(fileInput.files);
if (!files.length) return;
const save = form.querySelector('button[type="submit"]');
save.disabled = true;
say(tr("이미지에서 매출을 읽는 중…"), true);
let r = null;
for (const f of files) { // 매출을 찾을 때까지 한 장씩
const body = new FormData();
body.set("image", f);
r = await post("/live/broadcasts/read-sales", body);
if (!r.ok || r.data.amount) break;
}
save.disabled = false;
if (r.ok && r.data.amount) salesInput.value = r.data.amount;
say(r.message, r.ok);
});
form.addEventListener("submit", async function (e) {
e.preventDefault();
const save = form.querySelector('button[type="submit"]');
+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)