Files
parsing-service/idp_service/ocr.py
VinhNT e9d7c6d391 Giữ block ảnh, QR, con dấu, chữ ký rỗng của model
validate_response từ chối mọi block có html rỗng, trong khi model trả đúng như
thế cho các vùng không có chữ: xem chính dla_example_document.json, các block
Image, QR Code, Stamp, Signature đều có "html": "". Nghĩa là mọi trang có con
dấu hay QR đều bị coi là output hỏng, retry 3 lần rồi thành trang lỗi.

Chỉ block chữ mà rỗng mới là output hỏng; thông báo lỗi kèm luôn nhãn.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 08:04:36 +00:00

116 lines
4.9 KiB
Python

"""Render one page, call Chandra, and reject incomplete model output."""
import base64
import html
import json
import re
from pathlib import Path
from urllib.request import Request, urlopen
import pymupdf
from .config import Settings
from .dla import PROMPT, parse_blocks
LABELS = {
"Title", "Section Header", "Header", "Footer", "Paragraph", "Table",
"Barcode", "QR Code", "Signature", "Stamp", "Image",
}
LABEL_ALIASES = {"Page-Header": "Header", "Page Header": "Header",
"Page-Footer": "Footer", "Page Footer": "Footer"}
# Vùng không có chữ: model trả div rỗng, không phải output hỏng.
VISUAL_LABELS = {"Image", "QR Code", "Barcode", "Signature", "Stamp"}
class InvalidOutput(Exception):
def __init__(self, message: str, *, truncated: bool = False):
super().__init__(message)
self.truncated = truncated
def render_page(pdf_path: Path, page_no: int) -> tuple[bytes, int, int]:
with pymupdf.open(pdf_path) as doc:
page = doc[page_no - 1]
pix = page.get_pixmap(matrix=pymupdf.Matrix(200 / 72, 200 / 72), alpha=False)
return pix.tobytes("png"), pix.width, pix.height
def validate_response(response: dict) -> list[dict]:
try:
choice = response["choices"][0]
raw = choice["message"]["content"]
finish_reason = choice["finish_reason"]
except (KeyError, IndexError, TypeError) as exc:
raise InvalidOutput("Malformed model response") from exc
if finish_reason == "length":
raise InvalidOutput("Model reached max_tokens", truncated=True)
if finish_reason != "stop" or not isinstance(raw, str):
raise InvalidOutput(f"Unexpected finish_reason: {finish_reason}")
blocks = parse_blocks(raw)
if not blocks:
raise InvalidOutput("No HTML layout blocks returned")
for block in blocks:
block["label"] = LABEL_ALIASES.get(block["label"], block["label"])
if block["label"] not in LABELS:
raise InvalidOutput(f"Unknown block label: {block['label']}")
box = block["bbox"]
if box is None or len(box) != 4 or not (0 <= box[0] < box[2] <= 1000 and 0 <= box[1] < box[3] <= 1000):
raise InvalidOutput(f"Invalid bounding box: {box}")
if not block["html"] and block["label"] not in VISUAL_LABELS:
raise InvalidOutput(f"Empty layout block: {block['label']}")
return blocks
def extract_text_blocks(pdf_path: Path, page_no: int) -> dict:
"""Backend không cần GPU: lấy block văn bản sẵn có trong PDF số hoá.
Chỉ dùng để chạy thử service khi chưa serve được model; nhãn luôn là
Paragraph nên outline sẽ không có section. Trang không có text trả về một
block Image phủ toàn trang.
"""
with pymupdf.open(pdf_path) as doc:
page = doc[page_no - 1]
rect = page.rect
pixels = (rect * pymupdf.Matrix(200 / 72, 200 / 72)).irect
blocks = []
for x0, y0, x1, y1, text, *_ in page.get_text("blocks"):
text = re.sub(r"\s*\n\s*", " ", text).strip()
if not text:
continue
box = [round(1000 * (x0 - rect.x0) / rect.width), round(1000 * (y0 - rect.y0) / rect.height),
round(1000 * (x1 - rect.x0) / rect.width), round(1000 * (y1 - rect.y0) / rect.height)]
box = [min(1000, max(0, value)) for value in box]
if box[0] >= box[2] or box[1] >= box[3]:
continue
blocks.append({"label": "Paragraph", "bbox": box,
"html": f"<p>{html.escape(text)}</p>"})
return {"width": pixels.width, "height": pixels.height,
"blocks": blocks or [{"label": "Image", "bbox": [0, 0, 1000, 1000],
"html": "<p>[no extractable text]</p>"}]}
def infer_page(settings: Settings, pdf_path: Path, page_no: int, *, penalize_repetition: bool = False) -> dict:
if settings.ocr_backend == "pdf_text":
return extract_text_blocks(pdf_path, page_no)
if settings.ocr_backend != "http":
raise ValueError(f"Unknown IDP_OCR_BACKEND: {settings.ocr_backend}")
image, width, height = render_page(pdf_path, page_no)
data_url = "data:image/png;base64," + base64.b64encode(image).decode("ascii")
payload = {
"model": settings.ocr_model,
"messages": [{"role": "user", "content": [
{"type": "image_url", "image_url": {"url": data_url}},
{"type": "text", "text": PROMPT},
]}],
"max_tokens": 16384,
"temperature": 0.0,
"top_p": 0.1,
}
if penalize_repetition:
payload["frequency_penalty"] = 0.3
request = Request(settings.ocr_url, data=json.dumps(payload).encode("utf-8"),
headers={"Content-Type": "application/json"}, method="POST")
with urlopen(request, timeout=settings.ocr_timeout) as response:
result = json.load(response)
return {"width": width, "height": height, "blocks": validate_response(result)}