- tx(): chỉ ROLLBACK khi đang có transaction; BEGIN IMMEDIATE hết busy_timeout trước đây ném "cannot rollback - no transaction is active" che mất lỗi gốc. - Luồng OCR/callback/coordinator chạy qua Worker.loop: lỗi được log.exception rồi thử lại, không còn giết luồng vĩnh viễn. - OCR: model trả rỗng (trang trắng) thành trang không có block; output không parse được thì kèm 200 ký tự đầu vào thông báo lỗi. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
118 lines
5.0 KiB
Python
118 lines
5.0 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}")
|
|
if not raw.strip():
|
|
return [] # Trang trắng: model dừng ngay, không có gì để bóc.
|
|
blocks = parse_blocks(raw)
|
|
if not blocks:
|
|
raise InvalidOutput(f"No HTML layout blocks returned: {raw[:200]!r}")
|
|
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)}
|