Spaces:
Sleeping

VOCR / api.py
sirimiri's picture
Report platform and library versions in /health
81181db
Raw History Blame Contribute Delete
55 kB
import os import tempfile from pathlib import Path from contextlib import asynccontextmanager from typing import List, Optional from fastapi import FastAPI, File, UploadFile, HTTPException from fastapi.responses import PlainTextResponse from pydantic import BaseModel import base64 import cv2 from vocr_pipeline import VOCRPipeline from postprocess_v2 import fix_text_v11 # 2 phiên bản model chạy song song trong CÙNG 1 Space để so sánh. # Mỗi version tải từ 1 HF model repo riêng vào thư mục riêng. # Chỉ còn MỘT bản chạy: ppv6_1 + BARTpho bật. Các bản cũ (v4, v11, v11.2, ppv6_2) đã # gỡ khỏi Space sau khi đo xong — chúng chỉ còn giá trị đối chiếu, mà mỗi bản tốn một # model rec, một ViLM (~70s khởi động) và RAM trên cpu-basic. Muốn bật lại để so thì # thêm vào dict này; mã của chúng không bị xoá. # # Vì sao chọn ppv6_1: đo cấp TRANG trên sách thật, ppv6_1 CER 8.06% vs ppv6_2 10.67%. # ppv6_2 chỉ hơn trên bộ 3000 crop cắt kiểu v11, mà bộ đó xếp hạng NGƯỢC với thực tế. # # 2026-10-05: mặc định chuyển sang ppv6_3 (rec v11). Khi train, PPLCNetV4 ép CTC về 40 # bước nên các bản trước không học được dòng dài hơn ~40 ký tự; v11 vá chỗ đó. Bench 15 # ảnh nhãn tay: ppv6_1 + chuỗi luật + BARTpho 6.81% -> ppv6_3 + fix_text_v11 4.58% # (9 ảnh tốt / 5 xấu; trang sách 5.67% -> ~3.8%). ppv6_1 giữ lại làm bản phụ để các # đường /ppv6_1/... không gãy và để so A/B. MODEL_REPOS = { "ppv6_3": os.getenv("HF_MODEL_REPO_PPV6_3", "sirimiri/vocr-models-ppv6-v3"), "ppv6_1": os.getenv("HF_MODEL_REPO_PPV6_1", "sirimiri/vocr-models-ppv6-v1"), } DEFAULT_VER = "ppv6_3" # Bản dùng rec v11: hậu xử lý riêng (postprocess_v2.fix_text_v11), KHÔNG space_fix, # KHÔNG BARTpho — cả hai đều lỗ trên đầu ra v11 (xem docstring fix_text_v11). V11_REC_VERS = {"ppv6_3"} pipelines: dict = {} def _download_repo(repo: str, target: str): """Tải 1 model repo về `target/` (giữ structure models/ dict/ lm_data/). Bỏ qua nếu đã có. Điều kiện "đã có" phải xét CẢ tầng sửa ngữ cảnh khi nó được bật: nếu chỉ kiểm models/inference_rec thì một Space đã cache model cũ sẽ bỏ qua tải mãi mãi và models/corrector/ không bao giờ về — tầng ngữ cảnh im lặng không chạy. """ have_rec = os.path.exists(os.path.join(target, "models", "inference_rec")) need_ctx = os.getenv("VOCR_CONTEXT_FIX", "0") == "1" have_ctx = os.path.exists(os.path.join(target, "models", "corrector", "config.json")) if have_rec and (have_ctx or not need_ctx): print(f"[{repo}] đã có ở {target}, bỏ qua tải.") return if have_rec and need_ctx and not have_ctx: print(f"[{repo}] có model rec nhưng THIẾU models/corrector — tải lại để lấy nó.") try: from huggingface_hub import snapshot_download hf_token = os.getenv("HF_TOKEN", None) # Khi tang ngu canh TAT thi BO QUA models/corrector/ (1.5 GB) — khong loc # thi moi lan khoi dong Space deu tai them 1.5 GB vo ich. ignore = None if need_ctx else ["models/corrector/*"] print(f"Downloading {repo} -> {target} " f"({'kem' if need_ctx else 'KHONG kem'} models/corrector) ...") snapshot_download(repo_id=repo, local_dir=target, token=hf_token, ignore_patterns=ignore) print(f"[{repo}] downloaded.") except Exception as e: print(f"[{repo}] download failed: {e}") @asynccontextmanager async def lifespan(app: FastAPI): # 25 = bật CTC prefix beam search + ViLM tái xếp hạng (0.3453 -> 0.3893 acc, # CER micro 9.54% -> 8.62% trên 3000 dòng test v11). Chạy IN-PROCESS bằng # ctc_beam_rec.BeamRecognizer, nạp thẳng models/inference_rec/ — cùng thư mục # mà đường greedy dùng — nên KHÔNG cần PaddleOCR/ trong image (thư mục đó # nằm trong .gitignore, trước đây là lý do beam tắt lặng lẽ trên Spaces). # Giá: ~230ms/dòng, đo trên trang 18 dòng là 14.5s -> 19.1s. # Đặt VOCR_BEAM_SIZE=0 nếu cần độ trễ thấp hơn độ chính xác. beam = int(os.getenv("VOCR_BEAM_SIZE", "10")) # K=10: đo ở đây, 25 là số của v11 no_enh = os.getenv("VOCR_NO_ENHANCE", "1") == "1" # Thư mục corrector nằm trong repo v11; ppv6 trỏ CHUNG vào đây để khỏi nạp bản thứ hai. # Phải kiểm tồn tại NGAY LÚC dựng từng pipeline, không phải ở đây: lúc này v11 chưa # tải xong nên thư mục chưa có, kiểm sớm thì ppv6 vĩnh viễn không nạp được corrector. # 🔴 Đường dẫn phải TUYỆT ĐỐI theo vị trí api.py. Bản cũ dùng "./hf_v11/..." nên # chạy từ thư mục khác là không thấy corrector -> BARTpho lặng lẽ TẮT, không cảnh báo. # Triệu chứng đã gặp (27/09): prod đọc "nhận ra / cho tôi một / phát hiện" còn local # ra "nận ra / cho tô. một / pht hiện" — cùng model rec, chỉ khác có BARTpho hay không. # Thêm fallback ./models/corrector: từ khi MODEL_REPOS rút còn ppv6_1, repo hf_v11 # KHÔNG còn được tải nữa, mà corrector lại nằm trong đó. _HERE = os.path.dirname(os.path.abspath(__file__)) _CTX_CANDS = [os.path.join(_HERE, "hf_v11", "models", "corrector"), os.path.join(_HERE, "models", "corrector")] _CTX_SHARED = next((d for d in _CTX_CANDS if os.path.isdir(d)), _CTX_CANDS[0]) if not os.path.isdir(_CTX_SHARED) and os.getenv("VOCR_CONTEXT_FIX", "0") == "1": # repo v11 không còn được nạp làm pipeline, nhưng corrector vẫn nằm trong đó try: from huggingface_hub import snapshot_download snapshot_download(repo_id=os.getenv("HF_MODEL_REPO_V11", "sirimiri/vocr-models-v11"), local_dir="./hf_v11", token=os.getenv("HF_TOKEN"), allow_patterns=["models/corrector/*"]) print("[corrector] đã tải models/corrector từ repo v11") except Exception as e: print(f"[corrector] tải thất bại: {e} — tầng BARTpho sẽ không chạy") for ver, repo in MODEL_REPOS.items(): target = f"./hf_{ver}" _download_repo(repo, target) # corpus nằm trong model repo (hf_<ver>/lm_data/), KHÔNG phải /app/lm_data/ — # lm_data/ bị gitignore nên không có trong image. Không truyền đường dẫn này thì # VOCRPipeline không tìm thấy corpus và text post-fix tự tắt trong im lặng. corpus = f"{target}/lm_data/vi_corpus.txt" # Text post-fix CHỈ bật cho v11: mọi số đo của chuỗi 7 phép đều trên chính rec v11. # v4 giữ nguyên trạng làm baseline đối chiếu — và nhờ vậy nó cũng không phải # trả 67s train ViLM lúc khởi động. is_ppv6 = ver.startswith("ppv6") # ppv6: KHÔNG beam (mất ổn định trên đầu ra v6). Cũng TẮT crop_prep (phá crop # v6, conf 0.84->0.91). # # textfix thì ĐÃ BẬT LẠI cho ppv6 (2026-09-20). Trước đây tắt vì chuỗi luật # nhìn cụm chữ DÍNH của v6 thì phá ("iansuynghĩ..." -> "iaữệiê"). Lý do đó # nay không còn: pipeline hoãn chuỗi luật xuống chạy SAU space-fixer, nên nó # nhận vào tiếng Việt đã tách chữ. Đo trên 3 trang sách 'Cách Mầu Nhiệm' có # nhãn gõ tay (2.496 ký tự), rec ppv6_1: # # không chuỗi luật (cũ) CER 7.88% # chuỗi luật sau space-fix CER 7.14% <- bật cái này # chuỗi rút gọn CER 7.29% # cổng theo confidence CER 7.29% (tốt nhất trong các ngưỡng thử) # # Lời trên CẢ trang in mờ/det vỡ (13.21% -> 12.86%) chứ không chỉ trang sạch, # nên không cần cổng chất lượng dòng — áp mọi dòng là cấu hình tốt nhất. # Giá phải trả: ppv6 giờ train ViLM lúc khởi động (~70s, cache pickle). # BEAM: bật cho rec v11 từ 07/10. Đo đầu-cuối 20 trang trên nền chuỗi luật đã # chốt (chỉ fix_tone): acc 0.5090 -> 0.5254, CER 3.98% -> 3.89%, 34 dòng tốt / # 12 xấu, p=0.002; 15 ảnh 4.35% -> 4.03%, 8 ảnh tốt / 1 xấu. alpha 0.30, KHÔNG # phải 0.10 — 0.10 thắng ở cấp dòng nhưng đầu-cuối chỉ 52/46 (p=0.614), vì # crop cắt sẵn không chứa dòng det cắt trượt, nơi alpha nghiêng về LM đổi bừa. # # Lần đo TRƯỚC kết luận ngược (bỏ beam) vì nền bẩn: bench khi đó chạy chuỗi 10 # phép đầy đủ thay vì fix_text_v11, mà chuỗi đó tự phá 45 dòng nên che mất # phần lãi của beam. Beam và fix_tone KHÔNG giẫm chân nhau — beam+tone (0.5254) # hơn beam một mình (0.5180) — vì fix_tone giờ chỉ thêm dấu vào âm tiết TRỐNG, # chỗ CTC không thấy nét nên mọi ứng viên beam cũng trống. # # Giá: thêm một lượt model cho mỗi dòng cộng beam giải mã bằng Python thuần. # Tắt bằng VOCR_BEAM=0 nếu Space quá chậm. is_v11rec = ver in V11_REC_VERS use_beam = is_v11rec and os.getenv("VOCR_BEAM", "1") == "1" use_fix = use_beam or is_ppv6 # chuỗi luật: v11 + ppv6 (sau space-fix) # rec v11 (ppv6_3): textfix vẫn BẬT nhưng thay bằng fix_text_v11 (gán ngay sau # khi dựng pipeline); space_fix và BARTpho TẮT vì cả hai lỗ trên đầu ra v11. if use_fix and not os.path.exists(corpus): print(f"[{ver}] ⚠️ thiếu {corpus} — text post-fix sẽ KHÔNG chạy. " f"Kiểm tra model repo {repo} có lm_data/vi_corpus.txt không.") try: pipelines[ver] = VOCRPipeline( model_dir=f"{target}/models", dict_dir=f"{target}/dict", device="cpu", output_dir=f"./output/api_{ver}", # Beam CHỈ cho v11/v11.2, cùng lý do như textfix: mọi số đo của # beam + ViLM đều trên chính rec v11, và v4 phải GIỮ NGUYÊN TRẠNG # để còn làm baseline đối chiếu. Bật cho v4 là làm bẩn baseline. beam_size=(beam if use_beam else 0), lm_alpha=float(os.getenv("VOCR_BEAM_ALPHA", "0.30")), # v11 : TẮT tiền xử lý mức trang (mặc định hiện tại) # v11.2 : BẬT — dựng lại hành vi cũ để so sánh no_enhance=no_enh, # ppv6 cần corpus cho CẢ space-fixer lẫn ViLM (textfix bật từ 2026-09-20). lm_data=corpus if ((use_fix or is_ppv6) and os.path.exists(corpus)) else None, textfix=use_fix, # ppv6: True từ 2026-09-20 space_fix=is_ppv6 and not is_v11rec, # chèn lại dấu cách cho chữ dính (ppv6_1) no_crop_prep=is_ppv6, # ppv6: TẮT crop_prep (phá crop v6) # BARTpho: ppv6 NẠP SẴN nhưng mặc định TẮT — bật/tắt bằng select trên UI # (?ctx=1). Dùng chung thư mục model với v11 nên chỉ một bản 1.6 GB # trong RAM. Vẫn mặc định tắt vì corrector tune theo lỗi v11, chưa có # số đo nào nói nó lời trên v6. ctx_model_dir=(_CTX_SHARED if (is_ppv6 and not is_v11rec and os.path.isdir(_CTX_SHARED)) else None), # None = BARTpho TẮT (xem cảnh báo bên dưới) # ppv6: BẬT mặc định từ 2026-09-20 và chạy MỌI dòng (ctx_route=False). # Đo trên 3000 dòng đầu ra ppv6: acc 0.2287 -> 0.2843 (+5.57 điểm), # CER 27.98% -> 27.48%, 655 tốt / 159 xấu. v11 giữ route như cũ vì # số của nó là 2.00:1 với route so với 1.32:1 khi áp mọi dòng. ctx_default=True, ctx_route=not is_ppv6, ) if is_v11rec: # fix_text_v11 nhận (text, lm); pipeline có chỗ gọi kèm d_stroke=... nên nuốt kw. pipelines[ver]._fix_text = lambda t, lm, **_kw: fix_text_v11(t, lm) elif is_ppv6 and not os.path.isdir(_CTX_SHARED): print(f"[{ver}] ⚠️ KHÔNG thấy corrector BARTpho ở {_CTX_SHARED} → " "tầng sửa ngữ cảnh TẮT. Đây là khác biệt lớn nhất giữa prod và local: " "có nó thì 'nận ra'→'nhận ra', 'cho tô. một'→'cho tôi một', " "'pht hiện'→'phát hiện'. Bật lại: đặt VOCR_CONTEXT_FIX=1 (tự tải ~1,5GB) " "hoặc copy sẵn thư mục corrector vào ./models/corrector.") _bm = pipelines[ver].beam_rec if beam > 0 and use_beam and (_bm is None or not _bm.available): print(f"[{ver}] ⚠️ ĐÃ YÊU CẦU beam_size={beam} NHƯNG KHÔNG DÙNG ĐƯỢC — " f"trang sẽ chạy greedy, mất khoảng 4.8 điểm accuracy. Kiểm " f"{target}/models/inference_rec/inference.json + .pdiparams và " f"{target}/dict/vi_vietnam.txt (233 dòng) có trong model repo " f"{repo} không. Đặt VOCR_BEAM_SIZE=0 cho khỏi nhập nhằng.") print(f"[{ver}] pipeline sẵn sàng (repo {repo}, " f"textfix={('v11 (tone6+đ)' if is_v11rec else 'ON') if use_fix else 'OFF'}, " f"beam={beam if (beam > 0 and use_beam and _bm is not None and _bm.available) else 'OFF'}).") except Exception as e: print(f"[{ver}] init pipeline failed: {e}") yield app = FastAPI(title="VOCR API", version="1.0.0", lifespan=lifespan) class RegionResult(BaseModel): box: List[List[float]] text: str confidence: float class OCRResponse(BaseModel): full_text: str avg_confidence: float detections: int results: List[RegionResult] # ảnh đã vẽ khung bao, base64 JPEG — chỉ có khi gọi với ?annotate=1 annotated_image: Optional[str] = None from fastapi.responses import HTMLResponse, Response DEMO_HTML = r"""<!doctype html><html lang=vi><head><meta charset=utf-8> <meta name=viewport content="width=device-width,initial-scale=1"> <title>VOCR — đọc chữ trên ảnh sách in cũ</title> <style> :root{--bg:#fbfaf7;--fg:#1c1a17;--mut:#6b655c;--line:#e2ddd3;--card:#fff;--acc:#8a5a2b;--ok:#2f6b3a;--del:#b23b3b} @media(prefers-color-scheme:dark){:root{--bg:#171614;--fg:#eae6df;--mut:#9b948a;--line:#332f2a;--card:#1f1d1a;--acc:#c89b6a;--ok:#7fb98a;--del:#e08585}} *{box-sizing:border-box} body{margin:0;background:var(--bg);color:var(--fg);font:16px/1.6 system-ui,-apple-system,"Segoe UI",sans-serif} .wrap{max-width:1100px;margin:0 auto;padding:32px 20px 60px} h1{font-size:1.6rem;margin:0 0 4px;letter-spacing:-.01em} .sub{color:var(--mut);margin:0 0 24px;font-size:.95rem} .drop{border:2px dashed var(--line);border-radius:12px;padding:36px 20px;text-align:center; background:var(--card);cursor:pointer;transition:border-color .15s,background .15s} .drop:hover,.drop.over{border-color:var(--acc);background:color-mix(in srgb,var(--acc) 6%,var(--card))} .drop b{color:var(--acc)} .row{display:flex;gap:10px;align-items:center;flex-wrap:wrap;margin:16px 0} select,button{font:inherit;padding:8px 14px;border-radius:8px;border:1px solid var(--line); background:var(--card);color:var(--fg)} button{background:var(--acc);color:#fff;border-color:transparent;cursor:pointer;font-weight:600} button:disabled{opacity:.5;cursor:default} .stats{display:flex;gap:22px;flex-wrap:wrap;margin:18px 0;padding:14px 16px; background:var(--card);border:1px solid var(--line);border-radius:10px} .stat b{display:block;font-size:1.35rem;line-height:1.2} .stat span{color:var(--mut);font-size:.8rem} .grid{display:grid;grid-template-columns:1fr 1fr;gap:18px;margin-top:18px; align-items:start} /* mỗi cột cao theo nội dung của nó, không kéo bằng nhau */ @media(max-width:820px){.grid{grid-template-columns:1fr}} .card{background:var(--card);border:1px solid var(--line);border-radius:10px;overflow:hidden} .card h3{margin:0;padding:10px 14px;font-size:.85rem;text-transform:uppercase; letter-spacing:.05em;color:var(--mut);border-bottom:1px solid var(--line);font-weight:600} /* Không chặn chiều cao: khung chữ tự dài theo nội dung, cuộn ở cấp TRANG. Bản cũ để max-height:60vh nên ảnh bên trái cao hết cỡ còn chữ bên phải phải cuộn riêng, đọc đối chiếu hai bên thành ra phải cuộn hai lần. */ .card .body{padding:14px} .card img{display:block;width:100%;height:auto} pre{margin:0;white-space:pre-wrap;word-break:break-word;font:14px/1.65 ui-monospace,Menlo,Consolas,monospace} .chg{margin:0;padding:0;list-style:none;font:13.5px/1.6 ui-monospace,Menlo,Consolas,monospace} .chg li{padding:8px 0;border-bottom:1px solid var(--line)} .chg li:last-child{border:0} .chg .b{color:var(--del)}.chg .a{color:var(--ok)} .chg .b::before{content:"− ";opacity:.6}.chg .a::before{content:"+ ";opacity:.6} .err{color:var(--del);padding:12px 14px;background:var(--card);border:1px solid var(--del);border-radius:8px} .hint{color:var(--mut);font-size:.85rem} #pages{padding:8px 10px;border-radius:8px;border:1px solid var(--line);background:var(--card);color:inherit;font:inherit;min-width:240px} .spin{display:inline-block;width:14px;height:14px;border:2px solid #fff6;border-top-color:#fff; border-radius:50%;animation:s .7s linear infinite;vertical-align:-2px;margin-right:6px} @keyframes s{to{transform:rotate(360deg)}} footer{margin-top:36px;padding-top:18px;border-top:1px solid var(--line);color:var(--mut);font-size:.85rem} footer a{color:var(--acc)} </style></head><body><div class=wrap> <h1>VOCR — đọc chữ trên ảnh sách in cũ</h1> <p class=sub>Đồ án nhận dạng chữ tiếng Việt trên sách quốc ngữ in cũ. Mô hình nhận dạng là PP-OCRv6 tinh chỉnh trên 995.040 dòng cắt từ sách scan. Đọc xong còn chạy thêm một chuỗi 10 phép sửa chính tả dựa trên thống kê âm tiết, và một bước chèn lại dấu cách cho chữ bị dính. Kết quả vẫn sai khá nhiều: sách in mờ, chữ nghiêng và tên riêng là ba chỗ kém nhất.</p> <div class=drop id=drop> <p style="margin:0 0 6px"><b>Chọn ảnh hoặc PDF</b> — kéo thả cũng được, chọn nhiều tệp một lúc cũng được</p> <p class=hint style="margin:0">JPG, PNG, BMP, TIFF, PDF. Chụp cả trang hay cắt lấy vài dòng đều được.</p> <input type=file id=file accept="image/*,application/pdf" multiple hidden> </div> <div class=row> <input id=pages placeholder="Trang PDF: 1-5,8 (bỏ trống = từ đầu)" title="Chỉ áp dụng cho PDF. Bỏ trống thì lấy từ trang 1. Mỗi lần tối đa 20 trang."> <select id=prep title="Tiền xử lý ảnh trước khi nhận dạng. Mặc định làm đậm nét mực thêm ~1px: đo trên 20 trang sách CER 3.55% xuống 2.46% (17 trang tốt / 3 xấu), ăn nhiều nhất ở ảnh chụp mà det hay cắt vụn dòng. Nếu thấy chữ dính nhau thì chọn Không tiền xử lý rồi đọc lại."> <option value="auto">Làm đậm nét (mặc định)</option> <option value="none">Không tiền xử lý</option> </select> <button id=go disabled>Nhận dạng</button> <span class=hint id=fname></span> </div> <div id=out></div> <footer> Chạy trên CPU nên một trang mất khoảng 5–15 giây, lần đầu lâu hơn vì phải nạp mô hình. · <a href="/docs">API (/docs)</a> · <a href="/health">/health</a> </footer> </div> <script> const $=s=>document.querySelector(s), drop=$('#drop'), fi=$('#file'), go=$('#go'), out=$('#out'); let files=[]; drop.onclick=()=>fi.click(); drop.ondragover=e=>{e.preventDefault();drop.classList.add('over')}; drop.ondragleave=()=>drop.classList.remove('over'); drop.ondrop=e=>{e.preventDefault();drop.classList.remove('over');pick(e.dataTransfer.files)}; fi.onchange=e=>pick(e.target.files); function pick(list){ files=Array.from(list||[]); go.disabled=files.length===0; $('#fname').textContent = files.length===0 ? '' : (files.length===1 ? files[0].name : files.length+' tệp đã chọn'); } const esc=t=>t.replace(/[&<>]/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;'}[c])); go.onclick=async()=>{ if(!files.length)return; go.disabled=true; go.innerHTML='<span class=spin></span>Đang chạy…'; out.innerHTML='<p class=hint>Mỗi trang mất 5-15 giây trên CPU, PDF nhiều trang thì phải đợi.</p>'; const fd=new FormData(); files.forEach(f=>fd.append('files',f)); const q='?annotate=1&prep='+encodeURIComponent($('#prep').value) +'&pages='+encodeURIComponent($('#pages').value||''); try{ const r=await fetch('/ocr/batch'+q,{method:'POST',body:fd}); if(!r.ok){out.innerHTML='<p class=err>Lỗi '+r.status+': '+esc(await r.text())+'</p>';return} render(await r.json()); }catch(e){ out.innerHTML='<p class=err>Không gọi được máy chủ: '+esc(e.message)+'</p>'; } finally{ go.disabled=false; go.textContent='Nhận dạng'; } }; function render(d){ const items=d.items||[]; if(!items.length){out.innerHTML='<p class=err>Không có trang nào được xử lý</p>';return} let h=''; if(d.note) h+='<p class=hint style="margin:0 0 10px">'+esc(d.note)+'</p>'; if(items.length>1){ const tong=items.reduce((a,i)=>a+(i.detections||0),0); h+='<div class=stats>'+stat(items.length,'trang đã đọc')+stat(tong,'dòng phát hiện')+'</div>'; } items.forEach(it=>{ if(it.error){ h+='<div class=card style="margin-top:18px"><h3>'+esc(it.name)+'</h3>' +'<div class=body><p class=err>'+esc(it.error)+'</p></div></div>'; return; } h+='<div class=card style="margin-top:18px"><h3>'+esc(it.name)+'</h3><div class=body>' +'<div class=stats>'+stat(it.detections,'dòng') +stat((it.avg_confidence*100).toFixed(1)+'%','tin cậy TB') +stat(it.changed_lines,'dòng đã sửa') +(it.out_of_domain?stat(it.out_of_domain,'dòng ngoài miền'):'')+'</div>'; if(it.out_of_domain>=Math.max(2,it.detections/2)) h+='<p class=hint style="margin:0 0 10px">Phần lớn dòng của ảnh này nằm ngoài loại ' +'dữ liệu mô hình được học (sách quốc ngữ in cũ) — biển hiệu, chữ đánh máy hay ' +'phông hiện đại thường đọc kém. Kết quả bên dưới chỉ nên tham khảo.</p>'; h+='<div class=grid>'; if(it.annotated_image) h+='<div class=card><h3>Phát hiện dòng</h3><img alt="Ảnh với khung bao từng dòng" ' +'src="data:image/jpeg;base64,'+it.annotated_image+'"></div>'; h+='<div class=card><h3>Văn bản</h3><div class=body><pre>' +esc(it.text||'(không đọc được dòng nào)')+'</pre></div></div></div>'; if(it.changes&&it.changes.length){ h+='<div class=card style="margin-top:12px"><h3>Hậu xử lý đã đổi gì</h3><div class=body>' +'<p class=hint style="margin:0 0 8px">Tầng sửa ngữ cảnh đúng phần lớn nhưng không ' +'phải lúc nào cũng đúng. Đối chiếu với ảnh; nếu nó sửa hỏng, chọn Sửa ngữ cảnh = Tắt ' +'rồi đọc lại.</p>'; it.changes.forEach(c=>{ h+='<div style="margin:0 0 10px;font-size:13px">' +'<div style="opacity:.65">'+esc(c.before)+'</div>' +'<div style="color:#8fd19e">'+esc(c.after)+'</div></div>'; }); h+='</div></div>'; } h+='</div></div>'; }); const all=items.filter(i=>i.text).map(i=>'### '+i.name+'\n'+i.text).join('\n\n'); if(all) h+='<div class=card style="margin-top:18px"><h3>Toàn bộ văn bản</h3>' +'<div class=body><pre>'+esc(all)+'</pre></div></div>'; out.innerHTML=h; } const stat=(v,l)=>'<div class=stat><b>'+v+'</b><span>'+l+'</span></div>'; </script></body></html>""" @app.get("/", response_class=HTMLResponse) def home(): return DEMO_HTML def _env_sig(): import platform out = {"python": platform.python_version(), "he": f"{platform.system()}/{platform.machine()}"} for m in ("paddle", "paddleocr", "paddlex", "cv2", "numpy"): try: out[m] = getattr(__import__(m), "__version__", "?") except Exception: out[m] = "khong co" return out def _code_sig(files=("vocr_pipeline.py", "postprocess_v2.py", "api.py")): """12 ky tu dau cua sha256 tung tep nguon, de doi chieu voi ban tai may.""" import hashlib out = {} for f in files: try: with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), f), "rb") as fh: out[f] = hashlib.sha256(fh.read()).hexdigest()[:12] except Exception as e: out[f] = f"loi: {e.__class__.__name__}" return out @app.get("/health") def health(): """Trang thai. Phan `context_fix` de phan biet "TAT" voi "BAT ma im lang khong chay". Tang ngu canh hong theo kieu IM LANG: thieu model, thieu torch, hay het RAM deu chi log mot dong warning roi bo qua, dau ra khong khac gi luc tat. Da gap that: bien da bat, Space chay commit dung, ma dau ra van y het ban tat. """ p11 = pipelines.get(DEFAULT_VER) ctx = getattr(p11, "ctx_fixer", None) if p11 is not None else None ctx_dir = os.path.join("./hf_v11", "models", "corrector") diag = { "env_bat": os.getenv("VOCR_CONTEXT_FIX", "0") == "1", "co_thu_muc_model": os.path.isdir(ctx_dir), "da_khoi_tao": ctx is not None, "dang_chay": bool(ctx is not None and getattr(ctx, "available", False)), } if ctx is not None and getattr(ctx, "error", None): diag["loi"] = ctx.error ctx_files = sorted(os.listdir(ctx_dir))[:8] if os.path.isdir(ctx_dir) else [] diag["tep_trong_thu_muc"] = ctx_files try: mp = os.path.join(ctx_dir, "model.safetensors") diag["kich_thuoc_model_MB"] = round(os.path.getsize(mp)/1e6, 1) if os.path.exists(mp) else None except Exception: pass if not diag["dang_chay"]: try: import torch, transformers # noqa: F401 diag["thu_vien"] = "co" except Exception as e: diag["thu_vien"] = f"THIEU: {e.__class__.__name__}: {e}" return { "status": "ok", # Dau van tay MA NGUON DANG CHAY. Khong co no thi khong phan biet duoc # "Space da deploy" voi "Space bao sha moi nhung container con ban cu": # da gap that, API cua HF bao sha dung ma dau ra van y het ban truoc. # So sanh bang: shasum -a 256 <tep> | cut -c1-12 "ma_nguon": _code_sig(), # Nen tang + phien ban thu vien. Them vi ghim phien ban trong Dockerfile # KHONG doi duoc ket qua tren Space (van 1 dong o anh Cho Ray trong khi may # dev cho 3), nen phai biet chac Space dang chay dung ban nao, va kien truc # CPU co phai la cho khac nhau that su khong. "moi_truong": _env_sig(), "versions": {ver: (ver in pipelines) for ver in MODEL_REPOS}, "repos": MODEL_REPOS, "context_fix": diag, } def _apply_prep(tmp_path: str, prep: str, ver: Optional[str] = None) -> None: """Áp tiền xử lý mức trang LÊN CHÍNH tệp tạm, trước khi đưa vào pipeline. Làm ở đây thay vì tạo thêm pipeline: Space free 16GB không đủ cho nhiều paddle instance. Cách này cũng cho so sánh sạch hơn — cùng mô hình, cùng tham số, chỉ khác đúng ảnh đầu vào. `auto` (mặc định) = cách tốt nhất đã đo cho model đó: `thicken` với rec v11 (V11_REC_VERS), `none` với các bản khác (chưa đo thicken trên chúng). thicken = erode 2x2 cả trang, tức nét mực dày thêm ~1px. Đo trên ppv6_3: bench 15 ảnh nhãn tay 4.58% -> 3.75%, 11 ảnh tốt / 3 xấu 20 trang sách, 5 quyển 3.55% -> 2.46%, 17 trang tốt / 3 xấu Lời phần lớn từ det: ảnh mà det từng cắt vụn dòng thì nét dày cho dòng liền (dep 17 -> 12 box). Chỉ làm dày cho det mà crop rec lấy ảnh gốc thì KÉM hơn (4.97%); 3x3 quá tay (5.27%). whiten/whiten_local trên ppv6_3: 11.29% / 9.12% — hỏng cả ảnh nhạt mực vốn là lý do có chúng. Đo cũ trên 5 trang sách in cũ (OOV âm tiết, model trước v11): none 2.11% | whiten 5.60% | whiten_local 3.74% """ if prep in (None, "", "auto"): prep = "thicken" if ver in V11_REC_VERS else "none" if prep == "none": return # Làm phẳng ảnh chụp trang CONG (UVDoc) trước mọi bước khác, để det, cắt dòng và thứ tự # đọc cùng thấy một trang phẳng. Chỉ chạy khi đo được dòng cong trên ảnh (page_unwarp.py): # bench 15 ảnh không ảnh nào qua ngưỡng; làm phẳng vô điều kiện thì bench 4.20% -> 20.26%. # Trang uốn cong nhân tạo: CER 14-65% -> 2.5-24%. Tắt bằng VOCR_UNWARP_AUTO=0. try: import logging from page_unwarp import maybe_unwarp_file _done, _score = maybe_unwarp_file(tmp_path, logging.getLogger("vocr")) print(f"[UNWARP] độ cong {_score:.2f} -> {'LÀM PHẲNG' if _done else 'giữ nguyên'}") except Exception as e: print(f"[UNWARP] bỏ qua: {e}") if prep == "thicken": import numpy as np from vocr_pipeline import VOCRPipeline img = cv2.imread(tmp_path) if img is None: raise HTTPException(status_code=422, detail="Tiền xử lý thicken thất bại") # 🔴 ĐẢO CỰC TRƯỚC khi làm đậm. erode làm co vùng SÁNG, nên trên trang # thường (chữ đen, nền sáng) nó khiến nét mực dày thêm — đo trên chữ mẫu: # 983 -> 1234 điểm mực. Nhưng trên ảnh âm bản (chữ sáng, nền tối) chính # phép đó BÀO MỎNG chữ: 983 -> 734. Pipeline có tự đảo cực, nhưng đảo ở # TRONG run() còn bước này chạy TRƯỚC đó, nên nếu không xử ở đây thì ảnh # slide bị bào mỏng rồi mới được đảo. if VOCRPipeline.AUTO_INVERT and VOCRPipeline._is_light_on_dark(img): img = 255 - img if not cv2.imwrite(tmp_path, cv2.erode(img, np.ones((2, 2), np.uint8))): raise HTTPException(status_code=422, detail="Tiền xử lý thicken thất bại") return if prep not in ("whiten", "whiten_local"): raise HTTPException(status_code=400, detail=f"prep không hợp lệ: {prep} " f"(chọn auto, none, thicken, whiten, whiten_local)") from preprocess import enhance_whiten_bg if not enhance_whiten_bg(tmp_path, tmp_path, local=(prep == "whiten_local")): raise HTTPException(status_code=422, detail=f"Tiền xử lý {prep} thất bại") async def _run_ocr(ver: str, file: UploadFile, raw: bool = False, annotate: bool = False, prep: str = "auto", ctx: Optional[int] = None) -> OCRResponse: """raw=True: trả chuỗi TRƯỚC hậu xử lý, để so sánh có/không hậu xử lý. Không tạo pipeline thứ ba (3 paddle instance trên Space free 16GB dễ OOM). Mỗi entry đã mang sẵn `text_before_fix` khi hậu xử lý có can thiệp, nên hai bản đến từ CÙNG một lần chạy — cùng det, cùng crop, cùng đầu ra rec. So sánh vì thế sạch hơn chạy hai pipeline riêng. """ pipe = pipelines.get(ver) if pipe is None: raise HTTPException(status_code=503, detail=f"Model {ver} chưa sẵn sàng") ext = Path(file.filename).suffix.lower() if ext not in {".jpg", ".jpeg", ".png", ".bmp", ".tiff"}: raise HTTPException(status_code=400, detail=f"Định dạng không hỗ trợ: {ext}") with tempfile.NamedTemporaryFile(suffix=ext, delete=False) as tmp: tmp.write(await file.read()) tmp_path = tmp.name try: _apply_prep(tmp_path, prep, ver) result = _run_pipe(pipe, tmp_path, (None if ctx is None else bool(ctx))) if "error" in result: raise HTTPException(status_code=422, detail=result["error"]) def pick(r): return r.get("text_before_fix", r["best_text"]) if raw else r["best_text"] regions = [ RegionResult(box=r["box"], text=pick(r), confidence=round(r["confidence"], 4)) for r in result["results"] ] # full_text của pipeline dựng từ best_text nên bản raw phải ghép lại, # theo đúng quy tắc của vocr_pipeline: bỏ dòng rỗng, nối bằng '\n' full = ("\n".join(x.text for x in regions if x.text.strip()) if raw else result["full_text"]) img_b64 = None if annotate: img_b64 = base64.b64encode( _annotate_jpeg(result.get("image_for_boxes") or tmp_path, result["results"])).decode("ascii") return OCRResponse( full_text=full, avg_confidence=round(result["avg_confidence"], 4), detections=result["detections"], results=regions, annotated_image=img_b64, ) finally: os.remove(tmp_path) async def _run_ocr_image(ver: str, file: UploadFile, prep: str = "auto", ctx: Optional[int] = None) -> Response: """Trả THẲNG ảnh JPEG đã vẽ khung bao — mở được ngay trên trình duyệt, không phải giải mã base64. Dùng khi chỉ cần nhìn, không cần text.""" pipe = pipelines.get(ver) if pipe is None: raise HTTPException(status_code=503, detail=f"Model {ver} chưa sẵn sàng") ext = Path(file.filename).suffix.lower() if ext not in {".jpg", ".jpeg", ".png", ".bmp", ".tiff"}: raise HTTPException(status_code=400, detail=f"Định dạng không hỗ trợ: {ext}") with tempfile.NamedTemporaryFile(suffix=ext, delete=False) as tmp: tmp.write(await file.read()) tmp_path = tmp.name try: _apply_prep(tmp_path, prep, ver) result = _run_pipe(pipe, tmp_path, (None if ctx is None else bool(ctx))) if "error" in result: raise HTTPException(status_code=422, detail=result["error"]) return Response(content=_annotate_jpeg(result.get("image_for_boxes") or tmp_path, result["results"]), media_type="image/jpeg", headers={"X-Detections": str(result["detections"])}) finally: os.remove(tmp_path) def _run_pipe(pipe, path, ctx=None): """Gọi pipeline, tự dò hướng trang. Tắt bằng VOCR_AUTO_ORIENT=0. deskew chỉ chữa được góc LẺ (±45°); ảnh xoay 90/180/270 thì nó bó tay — đo được 0 ký tự ở 90/270 và CER 75-81% ở 180. run_oriented() thử 4 hướng theo kiểu bậc thang: ảnh đúng chiều (đa số) đi thẳng, chỉ ảnh đáng ngờ mới trả giá. BẬT MẶC ĐỊNH từ 2026-10-06. Đo 5 ảnh bench × 3 hướng xoay, CER với nhãn gõ tay: xoay 90 91-100% -> 2,4-5,6% xoay 180 75-81% -> 1,8-5,6% xoay 270 100% -> 1,8-5,6% tức 15/15 ca xoay đọc ngang chất lượng ảnh thẳng. Hồi quy trên 15 ảnh THẲNG: 0 ảnh xấu đi, 0 ảnh tốt lên, gộp 3,98% không đổi; thời gian 1:51 -> 1:59 (+6%). ⚠️ Chỉ ăn khi pipeline CÓ mô hình ngôn ngữ (lm_data). Không có LM thì _viet_score rơi về vocab space_fix, vốn KHÔNG phân biệt nổi rác với chữ thật (xem docstring của nó) và ảnh xoay 90/180 sẽ không bao giờ được lật. """ if os.getenv("VOCR_AUTO_ORIENT", "1") == "1" and hasattr(pipe, "run_oriented"): result = pipe.run_oriented(path, save=False, use_ctx=ctx) else: result = pipe.run(path, save=False, use_ctx=ctx) # Bỏ dòng chữ in ngược thấm từ mặt sau (show_through.py): lật ngang crop đọc lại, đọc ra # tiếng Việt thật thì đó là chữ mặt sau. Ảnh 2354: bỏ 10/10 dòng rác, bench không mất dòng nào. try: import logging from show_through import drop_show_through drop_show_through(pipe, result, logging.getLogger("vocr")) except Exception as e: print(f"[SHOW-THROUGH] bỏ qua: {e}") return result def _annotate_jpeg(image_path: str, results: list, quality: int = 85, max_width: int = 1600) -> bytes: """Vẽ khung bao lên ảnh gốc, trả JPEG dạng bytes. Dùng lại VOCRPipeline.draw_boxes để API và bản lưu file cho ra ẢNH GIỐNG NHAU (cùng màu theo độ tin cậy, cùng cách đánh số) — tránh hai đường vẽ lệch nhau. """ from vocr_pipeline import VOCRPipeline img = cv2.imread(image_path) if img is None: raise HTTPException(status_code=422, detail="Không đọc được ảnh để vẽ khung") vis = VOCRPipeline.draw_boxes(img, results) # thu nhỏ TRƯỚC khi mã hóa: ảnh scan gốc 4267px cho JPEG 2.6MB (base64 3.5MB), # quá nặng cho một phản hồi API. Vẽ ở kích thước gốc rồi mới thu để khung bao # vẫn sắc nét và đúng vị trí. if max_width and vis.shape[1] > max_width: sc = max_width / vis.shape[1] vis = cv2.resize(vis, (max_width, int(vis.shape[0] * sc)), interpolation=cv2.INTER_AREA) ok, buf = cv2.imencode(".jpg", vis, [int(cv2.IMWRITE_JPEG_QUALITY), quality]) if not ok: raise HTTPException(status_code=500, detail="Mã hóa JPEG thất bại") return buf.tobytes() # --- v4 (bản cũ) --- @app.post("/v4/ocr", response_model=OCRResponse) async def ocr_v4(file: UploadFile = File(...), annotate: bool = False, prep: str = "auto"): return await _run_ocr("v4", file, annotate=annotate, prep=prep) @app.post("/v4/ocr/text", response_class=PlainTextResponse) async def ocr_v4_text(file: UploadFile = File(...), prep: str = "auto"): return (await _run_ocr("v4", file, prep=prep)).full_text # --- v11 (bản mới) --- @app.post("/v11/ocr", response_model=OCRResponse) async def ocr_v11(file: UploadFile = File(...), annotate: bool = False, prep: str = "auto"): return await _run_ocr("v11", file, annotate=annotate, prep=prep) @app.post("/v11/ocr/text", response_class=PlainTextResponse) async def ocr_v11_text(file: UploadFile = File(...), prep: str = "auto"): return (await _run_ocr("v11", file, prep=prep)).full_text # --- v11 KHÔNG hậu xử lý (cùng model v11, chỉ khác ở tầng post-fix) --- @app.post("/v11raw/ocr", response_model=OCRResponse) async def ocr_v11_raw(file: UploadFile = File(...), prep: str = "auto"): return await _run_ocr("v11", file, raw=True, prep=prep) @app.post("/v11raw/ocr/text", response_class=PlainTextResponse) async def ocr_v11_raw_text(file: UploadFile = File(...), prep: str = "auto"): return (await _run_ocr("v11", file, raw=True, prep=prep)).full_text @app.post("/v11/compare") async def compare_v11(file: UploadFile = File(...), annotate: bool = False, prep: str = "auto", ctx: Optional[int] = None): """Một lần chạy, trả cả hai bản + danh sách dòng mà hậu xử lý đã đổi. `annotate=1` trả kèm ảnh đã vẽ khung bao (base64 JPEG), để trang demo chỉ phải gọi MỘT lần thay vì hai lần chạy cùng một mô hình trên cùng một ảnh. Số tham chiếu trên 3000 dòng crop test, cấu hình production hiện tại (beam K=25 + ViLM.rerank alpha=0.10 + chuỗi 10 phép): dòng đúng 23.37% -> 38.93%, CER micro 10.66% -> 8.62%. Riêng chuỗi 10 phép trên đầu ra tham lam, không dùng beam: 23.37% -> 34.53%, CER 10.66% -> 9.54%. """ pipe = pipelines.get("v11") if pipe is None: raise HTTPException(status_code=503, detail="Model v11 chưa sẵn sàng") ext = Path(file.filename).suffix.lower() if ext not in {".jpg", ".jpeg", ".png", ".bmp", ".tiff"}: raise HTTPException(status_code=400, detail=f"Định dạng không hỗ trợ: {ext}") with tempfile.NamedTemporaryFile(suffix=ext, delete=False) as tmp: tmp.write(await file.read()) tmp_path = tmp.name try: _apply_prep(tmp_path, prep, "v11") result = _run_pipe(pipe, tmp_path, (None if ctx is None else bool(ctx))) if "error" in result: raise HTTPException(status_code=422, detail=result["error"]) rs = result["results"] changed = [{"before": r["text_before_fix"], "after": r["best_text"]} for r in rs if "text_before_fix" in r] raw_lines = [r.get("text_before_fix", r["best_text"]) for r in rs] fix_lines = [r["best_text"] for r in rs] img_b64 = None if annotate: img_b64 = base64.b64encode( _annotate_jpeg(result.get("image_for_boxes") or tmp_path, rs)).decode("ascii") return { "detections": result["detections"], "avg_confidence": round(result["avg_confidence"], 4), "annotated_image": img_b64, "postprocess_enabled": bool(getattr(pipe, "textfix", False)), "ctx_available": bool(getattr(getattr(pipe, "ctx_fixer", None), "available", False)), "ctx_used": (bool(getattr(pipe, "ctx_default", False)) if ctx is None else bool(ctx)), "changed_lines": len(changed), "changes": changed, "text_raw": "\n".join(t for t in raw_lines if t.strip()), "text_fixed": "\n".join(t for t in fix_lines if t.strip()), } finally: os.remove(tmp_path) # --- /ocr mặc định = DEFAULT_VER --- # Trước đây hardcode "v11". Từ khi MODEL_REPOS rút còn {ppv6_3, ppv6_1} thì # pipelines không có khóa "v11" nữa, nên /ocr và /ocr/text trả 503 với MỌI client. # UI không lộ ra vì nó chỉ gọi /ocr/batch, vốn đã dùng DEFAULT_VER. @app.post("/ocr", response_model=OCRResponse) async def ocr(file: UploadFile = File(...), prep: str = "auto"): return await _run_ocr(DEFAULT_VER, file, prep=prep) @app.post("/ocr/text", response_class=PlainTextResponse) async def ocr_text(file: UploadFile = File(...), prep: str = "auto"): return (await _run_ocr(DEFAULT_VER, file, prep=prep)).full_text # --- ảnh đã vẽ khung bao --- @app.post("/v4/ocr/image") async def v4_ocr_image(file: UploadFile = File(...), prep: str = "auto"): return await _run_ocr_image("v4", file, prep=prep) @app.post("/v11/ocr/image") async def v11_ocr_image(file: UploadFile = File(...), prep: str = "auto"): return await _run_ocr_image("v11", file, prep=prep) # --- v11.2: cùng model v11, nhưng BẬT tiền xử lý ảnh mức trang --- # Để so trực tiếp với /v11 (tắt) trên cùng một ảnh. Đo nội bộ trên 11 trang cho # thấy TẮT tốt hơn (âm tiết OOV 5.30% vs 7.31%, lỗi lặp ít hơn 40%), nhưng ảnh # mỗi nguồn mỗi khác nên để người dùng tự đối chiếu. @app.post("/v11.2/ocr", response_model=OCRResponse) async def ocr_v11_2(file: UploadFile = File(...), annotate: bool = False, prep: str = "auto"): return await _run_ocr("v11.2", file, annotate=annotate, prep=prep) @app.post("/v11.2/ocr/text", response_class=PlainTextResponse) async def ocr_v11_2_text(file: UploadFile = File(...), prep: str = "auto"): return (await _run_ocr("v11.2", file, prep=prep)).full_text @app.post("/v11.2/ocr/image") async def v11_2_ocr_image(file: UploadFile = File(...), prep: str = "auto"): return await _run_ocr_image("v11.2", file, prep=prep) # --- Route generic cho version bất kỳ (ppv6_1, ppv6_2, ...) — ĐẶT CUỐI để các # route cụ thể ở trên (v4/v11/v11.2) được ưu tiên khớp trước. _run_ocr tự 503 # nếu ver không có trong pipelines. --- @app.post("/{ver}/ocr", response_model=OCRResponse) async def ocr_generic(ver: str, file: UploadFile = File(...), annotate: bool = False, prep: str = "auto", ctx: Optional[int] = None): return await _run_ocr(ver, file, annotate=annotate, prep=prep, ctx=ctx) @app.post("/{ver}/ocr/text", response_class=PlainTextResponse) async def ocr_generic_text(ver: str, file: UploadFile = File(...), prep: str = "auto"): return (await _run_ocr(ver, file, prep=prep)).full_text @app.post("/{ver}/ocr/image") async def ocr_generic_image(ver: str, file: UploadFile = File(...), prep: str = "auto"): return await _run_ocr_image(ver, file, prep=prep) # --------------------------------------------------------------------------- # Nhận dạng NHIỀU tệp / PDF theo trang # --------------------------------------------------------------------------- MAX_BATCH_PAGES = 20 # trần số trang mỗi lần gọi — mỗi trang 5-15s trên CPU PDF_DPI = 200 # đủ nét cho sách in, 300 chỉ chậm thêm mà không hơn def _parse_pages(spec: str, total: int) -> List[int]: """'1-5,8,12-' -> [1,2,3,4,5,8,12..total]. Rỗng = tất cả (cắt theo trần).""" if not spec or not spec.strip(): return list(range(1, min(total, MAX_BATCH_PAGES) + 1)) out: List[int] = [] for part in spec.replace(' ', '').split(','): if not part: continue if '-' in part: a, _, b = part.partition('-') try: lo = int(a) if a else 1 hi = int(b) if b else total except ValueError: raise HTTPException(status_code=400, detail=f"Khoảng trang không hợp lệ: {part}") out += list(range(max(1, lo), min(total, hi) + 1)) else: try: n = int(part) except ValueError: raise HTTPException(status_code=400, detail=f"Số trang không hợp lệ: {part}") if 1 <= n <= total: out.append(n) seen, uniq = set(), [] for n in out: if n not in seen: seen.add(n) uniq.append(n) return uniq def _pdf_to_images(pdf_path: str, spec: str) -> List[tuple]: """Render các trang đã chọn ra tệp ảnh tạm. Trả [(so_trang, duong_dan)].""" try: import pypdfium2 as pdfium except ImportError: raise HTTPException(status_code=500, detail="Thiếu pypdfium2 trên máy chủ — không đọc được PDF") doc = pdfium.PdfDocument(pdf_path) total = len(doc) pages = _parse_pages(spec, total) if not pages: raise HTTPException(status_code=400, detail=f"PDF có {total} trang, không trang nào khớp") skipped = max(0, len(pages) - MAX_BATCH_PAGES) out = [] for n in pages[:MAX_BATCH_PAGES]: page = doc[n - 1] pil = page.render(scale=PDF_DPI / 72).to_pil() tmp = tempfile.NamedTemporaryFile(suffix='.jpg', delete=False) pil.convert('RGB').save(tmp.name, quality=92) tmp.close() out.append((n, tmp.name)) return out, skipped @app.post("/ocr/batch") async def ocr_batch(files: List[UploadFile] = File(...), prep: str = "auto", pages: str = "", annotate: bool = True, ctx: Optional[int] = None): """Nhận nhiều ảnh, hoặc PDF (chọn trang bằng `pages`, vd '1-5,8'). Mỗi trang mất 5-15 giây trên CPU nên trần là 20 trang/lần gọi; quá số đó thì chia nhiều lần. PDF render ở 200 DPI — đo trên sách in cũ thì 300 DPI không đọc tốt hơn mà chậm gấp rưỡi. """ pipe = pipelines.get(DEFAULT_VER) if pipe is None: raise HTTPException(status_code=503, detail=f"Model {DEFAULT_VER} chưa sẵn sàng") jobs = [] # (ten_hien_thi, duong_dan, co_phai_tam) n_skipped = 0 # số trang bị cắt vì vượt trần — PHẢI báo ra, đừng lặng lẽ bỏ try: for f in files: ext = Path(f.filename or '').suffix.lower() data = await f.read() if ext == '.pdf': tmp = tempfile.NamedTemporaryFile(suffix='.pdf', delete=False) tmp.write(data) tmp.close() try: rendered, skipped = _pdf_to_images(tmp.name, pages) n_skipped += skipped for n, img_path in rendered: jobs.append((f"{f.filename} — trang {n}", img_path, True)) finally: os.remove(tmp.name) elif ext in {'.jpg', '.jpeg', '.png', '.bmp', '.tiff'}: tmp = tempfile.NamedTemporaryFile(suffix=ext, delete=False) tmp.write(data) tmp.close() jobs.append((f.filename, tmp.name, True)) else: raise HTTPException(status_code=400, detail=f"Định dạng không hỗ trợ: {ext or f.filename}") if len(jobs) > MAX_BATCH_PAGES: raise HTTPException(status_code=400, detail=f"{len(jobs)} trang vượt trần {MAX_BATCH_PAGES}/lần. " f"Chia nhỏ hoặc thu hẹp khoảng trang.") items = [] for name, path, _ in jobs: _apply_prep(path, prep, DEFAULT_VER) res = _run_pipe(pipe, path, (None if ctx is None else bool(ctx))) if "error" in res: items.append({"name": name, "error": res["error"]}) continue rs = res["results"] items.append({ "name": name, "detections": res["detections"], "avg_confidence": round(res["avg_confidence"], 4), "text": "\n".join(r["best_text"] for r in rs if r["best_text"].strip()), "annotated_image": (base64.b64encode(_annotate_jpeg(res.get("image_for_boxes") or path, rs)).decode("ascii") if annotate else None), "changed_lines": sum(1 for r in rs if "text_before_fix" in r), # Hiện RÕ từng chỗ hậu xử lý đã đổi. Tầng sửa (BARTpho) có tỉ lệ # 655 tốt / 159 xấu — người dùng KHÔNG thể biết ảnh của mình rơi vào # nhóm nào nếu chỉ thấy con số "N dòng đã sửa". Đưa before/after ra # để tự đối chiếu với ảnh, thấy sai thì bật lại bằng ô "Sửa ngữ cảnh". "changes": [{"before": r["text_before_fix"], "after": r["best_text"]} for r in rs if "text_before_fix" in r], # Bộ kiểm miền của pipeline đã biết crop nào lệch khỏi dữ liệu train # (sách in cũ). Trước đây chỉ ghi vào log; đưa ra đây để người dùng # biết kết quả của ảnh biển hiệu / thư đánh máy là không đáng tin, # thay vì tưởng model đọc sai một cách khó hiểu. "out_of_domain": sum(1 for r in rs if r.get("out_of_domain")), }) out = {"count": len(items), "items": items} if n_skipped: out["skipped"] = n_skipped out["note"] = (f"Đã bỏ {n_skipped} trang vì vượt trần {MAX_BATCH_PAGES} trang/lần. " f"Chạy tiếp phần còn lại bằng khoảng trang khác.") return out finally: for _, path, is_tmp in jobs: if is_tmp: try: os.remove(path) except Exception: pass @app.post("/{ver}/compare") async def compare_generic(ver: str, file: UploadFile = File(...), annotate: bool = False, prep: str = "auto", ctx: Optional[int] = None): """Như /v11/compare nhưng cho version bất kỳ (ppv6_1/ppv6_2/v11.2) — trả cả bản trước và sau hậu xử lý để UI hiện phần hậu xử lý.""" pipe = pipelines.get(ver) if pipe is None: raise HTTPException(status_code=503, detail=f"Model {ver} chưa sẵn sàng") ext = Path(file.filename).suffix.lower() if ext not in {".jpg", ".jpeg", ".png", ".bmp", ".tiff"}: raise HTTPException(status_code=400, detail=f"Định dạng không hỗ trợ: {ext}") with tempfile.NamedTemporaryFile(suffix=ext, delete=False) as tmp: tmp.write(await file.read()) tmp_path = tmp.name try: _apply_prep(tmp_path, prep, ver) result = _run_pipe(pipe, tmp_path, (None if ctx is None else bool(ctx))) if "error" in result: raise HTTPException(status_code=422, detail=result["error"]) rs = result["results"] changed = [{"before": r["text_before_fix"], "after": r["best_text"]} for r in rs if "text_before_fix" in r] raw_lines = [r.get("text_before_fix", r["best_text"]) for r in rs] fix_lines = [r["best_text"] for r in rs] img_b64 = base64.b64encode(_annotate_jpeg(result.get("image_for_boxes") or tmp_path, rs)).decode("ascii") if annotate else None return { "detections": result["detections"], "avg_confidence": round(result["avg_confidence"], 4), "annotated_image": img_b64, "postprocess_enabled": bool(getattr(pipe, "textfix", False)), "ctx_available": bool(getattr(getattr(pipe, "ctx_fixer", None), "available", False)), "ctx_used": (bool(getattr(pipe, "ctx_default", False)) if ctx is None else bool(ctx)), "changed_lines": len(changed), "changes": changed, "text_raw": "\n".join(t for t in raw_lines if t.strip()), "text_fixed": "\n".join(t for t in fix_lines if t.strip()), } finally: os.remove(tmp_path)
import os
import tempfile
from pathlib import Path
from contextlib import asynccontextmanager
from typing import List, Optional
from fastapi import FastAPI, File, UploadFile, HTTPException
from fastapi.responses import PlainTextResponse
from pydantic import BaseModel
import base64
import cv2
from vocr_pipeline import VOCRPipeline
from postprocess_v2 import fix_text_v11
# 2 phiên bản model chạy song song trong CÙNG 1 Space để so sánh.
# Mỗi version tải từ 1 HF model repo riêng vào thư mục riêng.
# Chỉ còn MỘT bản chạy: ppv6_1 + BARTpho bật. Các bản cũ (v4, v11, v11.2, ppv6_2) đã
# gỡ khỏi Space sau khi đo xong — chúng chỉ còn giá trị đối chiếu, mà mỗi bản tốn một
# model rec, một ViLM (~70s khởi động) và RAM trên cpu-basic. Muốn bật lại để so thì
# thêm vào dict này; mã của chúng không bị xoá.
#
# Vì sao chọn ppv6_1: đo cấp TRANG trên sách thật, ppv6_1 CER 8.06% vs ppv6_2 10.67%.
# ppv6_2 chỉ hơn trên bộ 3000 crop cắt kiểu v11, mà bộ đó xếp hạng NGƯỢC với thực tế.
#
# 2026-10-05: mặc định chuyển sang ppv6_3 (rec v11). Khi train, PPLCNetV4 ép CTC về 40
# bước nên các bản trước không học được dòng dài hơn ~40 ký tự; v11 vá chỗ đó. Bench 15
# ảnh nhãn tay: ppv6_1 + chuỗi luật + BARTpho 6.81% -> ppv6_3 + fix_text_v11 4.58%
# (9 ảnh tốt / 5 xấu; trang sách 5.67% -> ~3.8%). ppv6_1 giữ lại làm bản phụ để các
# đường /ppv6_1/... không gãy và để so A/B.
MODEL_REPOS = {
"ppv6_3": os.getenv("HF_MODEL_REPO_PPV6_3", "sirimiri/vocr-models-ppv6-v3"),
"ppv6_1": os.getenv("HF_MODEL_REPO_PPV6_1", "sirimiri/vocr-models-ppv6-v1"),
}
DEFAULT_VER = "ppv6_3"
# Bản dùng rec v11: hậu xử lý riêng (postprocess_v2.fix_text_v11), KHÔNG space_fix,
# KHÔNG BARTpho — cả hai đều lỗ trên đầu ra v11 (xem docstring fix_text_v11).
V11_REC_VERS = {"ppv6_3"}
pipelines: dict = {}
def _download_repo(repo: str, target: str):
"""Tải 1 model repo về `target/` (giữ structure models/ dict/ lm_data/). Bỏ qua nếu đã có.
Điều kiện "đã có" phải xét CẢ tầng sửa ngữ cảnh khi nó được bật: nếu chỉ kiểm
models/inference_rec thì một Space đã cache model cũ sẽ bỏ qua tải mãi mãi và
models/corrector/ không bao giờ về — tầng ngữ cảnh im lặng không chạy.
"""
have_rec = os.path.exists(os.path.join(target, "models", "inference_rec"))
need_ctx = os.getenv("VOCR_CONTEXT_FIX", "0") == "1"
have_ctx = os.path.exists(os.path.join(target, "models", "corrector", "config.json"))
if have_rec and (have_ctx or not need_ctx):
print(f"[{repo}] đã có ở {target}, bỏ qua tải.")
return
if have_rec and need_ctx and not have_ctx:
print(f"[{repo}] có model rec nhưng THIẾU models/corrector — tải lại để lấy nó.")
try:
from huggingface_hub import snapshot_download
hf_token = os.getenv("HF_TOKEN", None)
# Khi tang ngu canh TAT thi BO QUA models/corrector/ (1.5 GB) — khong loc
# thi moi lan khoi dong Space deu tai them 1.5 GB vo ich.
ignore = None if need_ctx else ["models/corrector/*"]
print(f"Downloading {repo} -> {target} "
f"({'kem' if need_ctx else 'KHONG kem'} models/corrector) ...")
snapshot_download(repo_id=repo, local_dir=target, token=hf_token,
ignore_patterns=ignore)
print(f"[{repo}] downloaded.")
except Exception as e:
print(f"[{repo}] download failed: {e}")
@asynccontextmanager
async def lifespan(app: FastAPI):
# 25 = bật CTC prefix beam search + ViLM tái xếp hạng (0.3453 -> 0.3893 acc,
# CER micro 9.54% -> 8.62% trên 3000 dòng test v11). Chạy IN-PROCESS bằng
# ctc_beam_rec.BeamRecognizer, nạp thẳng models/inference_rec/ — cùng thư mục
# mà đường greedy dùng — nên KHÔNG cần PaddleOCR/ trong image (thư mục đó
# nằm trong .gitignore, trước đây là lý do beam tắt lặng lẽ trên Spaces).
# Giá: ~230ms/dòng, đo trên trang 18 dòng là 14.5s -> 19.1s.
# Đặt VOCR_BEAM_SIZE=0 nếu cần độ trễ thấp hơn độ chính xác.
beam = int(os.getenv("VOCR_BEAM_SIZE", "10")) # K=10: đo ở đây, 25 là số của v11
no_enh = os.getenv("VOCR_NO_ENHANCE", "1") == "1"
# Thư mục corrector nằm trong repo v11; ppv6 trỏ CHUNG vào đây để khỏi nạp bản thứ hai.
# Phải kiểm tồn tại NGAY LÚC dựng từng pipeline, không phải ở đây: lúc này v11 chưa
# tải xong nên thư mục chưa có, kiểm sớm thì ppv6 vĩnh viễn không nạp được corrector.
# 🔴 Đường dẫn phải TUYỆT ĐỐI theo vị trí api.py. Bản cũ dùng "./hf_v11/..." nên
# chạy từ thư mục khác là không thấy corrector -> BARTpho lặng lẽ TẮT, không cảnh báo.
# Triệu chứng đã gặp (27/09): prod đọc "nhận ra / cho tôi một / phát hiện" còn local
# ra "nận ra / cho tô. một / pht hiện" — cùng model rec, chỉ khác có BARTpho hay không.
# Thêm fallback ./models/corrector: từ khi MODEL_REPOS rút còn ppv6_1, repo hf_v11
# KHÔNG còn được tải nữa, mà corrector lại nằm trong đó.
_HERE = os.path.dirname(os.path.abspath(__file__))
_CTX_CANDS = [os.path.join(_HERE, "hf_v11", "models", "corrector"),
os.path.join(_HERE, "models", "corrector")]
_CTX_SHARED = next((d for d in _CTX_CANDS if os.path.isdir(d)), _CTX_CANDS[0])
if not os.path.isdir(_CTX_SHARED) and os.getenv("VOCR_CONTEXT_FIX", "0") == "1":
# repo v11 không còn được nạp làm pipeline, nhưng corrector vẫn nằm trong đó
try:
from huggingface_hub import snapshot_download