Files
parsing-service/idp_service/ocr.py
VinhNT c79ea9f05f Nhận PDF upload trực tiếp qua POST /parse
API trước đây chỉ nhận đường dẫn HDFS từ Airflow. Thêm endpoint
multipart/form-data nhận thẳng file PDF, vẫn chạy bất đồng bộ: trả 202 kèm
job_id và result_url, worker xử lý nền, client lấy dla-document-bundle ở
GET /jobs/{job_id}/result hoặc qua callback.

- File upload ghi xuống IDP_DATA_DIR/uploads theo sha256 nội dung nên gửi lại
  cùng request_id trả cùng job_id; file được xoá khi không còn job nào dùng.
- Thêm cột filename/source_kind để bundle giữ đúng tên file gốc thay vì tên
  đã băm.
- IDP_RUN_WORKER=1 chạy worker trong process API cho triển khai một host.
- IDP_OCR_BACKEND=pdf_text dựng bundle từ text layer của PDF để chạy thử toàn
  bộ luồng khi chưa serve được model.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-21 14:51:19 +00:00

114 lines
4.7 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"}
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 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)}