Files
parsing-service/idp_service/ocr.py
2026-09-21 21:06:49 +07:00

80 lines
3.1 KiB
Python

"""Render one page, call Chandra, and reject incomplete model output."""
import base64
import json
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"}
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"]:
raise InvalidOutput("Empty layout block")
return blocks
def infer_page(settings: Settings, pdf_path: Path, page_no: int, *, penalize_repetition: bool = False) -> dict:
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)}