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

111 lines
4.2 KiB
Python

"""Gọi model chandra-ocr-2-dla đang serve và xuất thẳng ra dla-document-bundle JSON.
python infer.py input.pdf -o dla_example_document.json
python infer.py page.png -o dla_example_document.json
"""
import argparse
import base64
import hashlib
import json
import mimetypes
from pathlib import Path
from urllib.request import Request, urlopen
import fitz
from PIL import Image, ImageOps
from idp_service.dla import PROMPT, build_outline, parse_blocks
API_URL = "http://localhost:9222/v1/chat/completions"
MODEL_NAME = "chandra"
def call_model(image_path: Path, max_tokens=16384, timeout=1200) -> str:
mime = mimetypes.guess_type(image_path.name)[0] or "image/png"
data_url = f"data:{mime};base64,{base64.b64encode(image_path.read_bytes()).decode('ascii')}"
payload = {
"model": MODEL_NAME,
"messages": [{"role": "user", "content": [
{"type": "image_url", "image_url": {"url": data_url}},
{"type": "text", "text": PROMPT},
]}],
"max_tokens": max_tokens,
"temperature": 0.0,
"top_p": 0.1,
}
request = Request(API_URL, data=json.dumps(payload).encode("utf-8"),
headers={"Content-Type": "application/json"}, method="POST")
with urlopen(request, timeout=timeout) as response:
result = json.load(response)
return result["choices"][0]["message"]["content"]
def prepare_pages(source: Path, work_dir: Path):
"""Trả về list (page_no, image_path, width, height). Xoay ảnh theo EXIF, PDF tách theo trang."""
work_dir.mkdir(parents=True, exist_ok=True)
if source.suffix.lower() == ".pdf":
pages = []
matrix = fitz.Matrix(200 / 72, 200 / 72)
with fitz.open(source) as doc:
digits = max(2, len(str(doc.page_count)))
for index in range(doc.page_count):
out_path = work_dir / f"page_{index + 1:0{digits}d}.png"
pix = doc.load_page(index).get_pixmap(matrix=matrix)
pix.save(out_path)
pages.append((index + 1, out_path, pix.width, pix.height))
return pages
out_path = work_dir / "page_01.png"
with Image.open(source) as image:
fixed = ImageOps.exif_transpose(image)
if fixed.mode not in ("RGB", "L"):
fixed = fixed.convert("RGB")
fixed.save(out_path, format="PNG")
return [(1, out_path, fixed.width, fixed.height)]
def build_document(source: Path, work_dir: Path) -> dict:
digest = hashlib.sha256(source.read_bytes()).hexdigest()[:16]
document_id = f"doc_{digest}"
page_infos = prepare_pages(source, work_dir)
pages = []
for page_no, image_path, width, height in page_infos:
page_id = f"{document_id}/p{page_no:03d}"
raw = call_model(image_path)
blocks = [
{"block_id": f"{page_id}/b{i:03d}", "label": b["label"], "bbox": b["bbox"], "html": b["html"]}
for i, b in enumerate(parse_blocks(raw))
]
pages.append({"page_id": page_id, "page_no": page_no, "width": width, "height": height, "blocks": blocks})
return {
"schema": "dla-document-bundle",
"version": "1.0",
"document_id": document_id,
"source": {
"filename": source.name,
"media_type": "application/pdf" if source.suffix.lower() == ".pdf" else "image",
"page_count": len(pages),
"render_dpi": 200 if source.suffix.lower() == ".pdf" else None,
},
"outline": build_outline(pages),
"pages": pages,
}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("input", help="file ảnh hoặc PDF")
parser.add_argument("-o", "--out", default="dla_example_document.json")
args = parser.parse_args()
source = Path(args.input)
work_dir = Path(args.out).parent / f".{source.stem}_pages"
bundle = build_document(source, work_dir)
Path(args.out).write_text(json.dumps(bundle, ensure_ascii=False, indent=2), encoding="utf-8")
n_blocks = sum(len(p["blocks"]) for p in bundle["pages"])
print(f"{bundle['document_id']} · {bundle['source']['page_count']} trang · {n_blocks} block → {args.out}")
if __name__ == "__main__":
main()