Files
parsing-service/idp_service/worker.py
2026-09-23 11:36:34 +07:00

224 lines
10 KiB
Python

"""Run separately from the API: python -m idp_service.worker."""
import hashlib
import base64
import json
import logging
import shutil
import signal
import threading
import time
from dataclasses import replace
from pathlib import Path
from urllib.request import Request, urlopen
import pymupdf
from .config import Settings
from .db import Store
from .decrypt import prepare_pdf
from .dla import build_outline
from .ocr import InvalidOutput, infer_page, render_page
from .storage import fetch_pdf
log = logging.getLogger(__name__)
class Worker:
def __init__(self, settings: Settings, store: Store | None = None):
self.settings = settings
self.store = store or Store(settings.db_path)
self.stop = threading.Event()
settings.work_dir.mkdir(parents=True, exist_ok=True)
if settings.ocr_workers < 1 or settings.lease_seconds <= settings.ocr_timeout:
raise ValueError("OCR workers must be positive and lease must exceed OCR timeout")
if settings.ocr_backend not in ("http", "pdf_text"):
raise ValueError("IDP_OCR_BACKEND must be http or pdf_text")
if settings.ocr_backend == "pdf_text":
log.warning("IDP_OCR_BACKEND=pdf_text: bundle dựng từ text layer của PDF, không gọi model")
def job_dir(self, job_id: str) -> Path:
return self.settings.work_dir / job_id
def cleanup_source(self, job: dict):
"""Xoá file đã upload khi không còn job nào đang dùng nó."""
if job["source_kind"] != "upload":
return
if not self.store.upload_in_use(job["file_path"], job["id"]):
Path(job["file_path"]).unlink(missing_ok=True)
def prepare(self, job: dict):
job_dir = self.job_dir(job["id"])
downloaded = job_dir / "downloaded.bin"
source = job_dir / "source.pdf"
try:
if job["attempts"] > self.settings.max_job_attempts:
raise ValueError("Preparation lease expired too many times")
settings = replace(self.settings, storage="local") if job["source_kind"] == "upload" else self.settings
fetch_pdf(settings, job["file_path"], downloaded)
decrypted = prepare_pdf(downloaded, source, self.settings.voffice_decrypt_mode,
self.settings.voffice_des_key_hex)
with pymupdf.open(source) as pdf:
if not pdf.is_pdf or not 0 < pdf.page_count <= self.settings.max_pages:
raise ValueError("Invalid PDF or page count exceeds IDP_MAX_PAGES")
count = pdf.page_count
self.store.prepared(job["id"], job["attempts"], count)
log.info("Prepared %s with %s pages (decrypted=%s)", job["id"], count, decrypted)
except Exception as exc:
log.exception("Preparation failed for %s", job["id"])
self.store.prepare_failed(job["id"], job["attempts"], str(exc), self.settings.max_job_attempts)
if job["attempts"] >= self.settings.max_job_attempts:
self.cleanup_source(job)
def process_page(self, page: dict):
job_id, page_no, attempts = page["job_id"], page["page_no"], page["attempts"]
try:
if attempts > self.settings.max_page_attempts:
raise ValueError("Page lease expired too many times")
result = infer_page(self.settings, self.job_dir(job_id) / "source.pdf", page_no,
penalize_repetition=bool(page["penalize_repetition"]))
self.store.page_done(job_id, page_no, attempts, result)
except Exception as exc:
log.warning("Page failed: %s/%s attempt %s: %s", job_id, page_no, attempts, exc)
self.store.page_failed(job_id, page_no, attempts, str(exc),
isinstance(exc, InvalidOutput) and exc.truncated,
self.settings.max_page_attempts)
def finalize(self, job: dict):
job_id = job["id"]
try:
if job["finalize_attempts"] > self.settings.max_job_attempts:
raise ValueError("Finalization lease expired too many times")
source = self.job_dir(job_id) / "source.pdf"
digest = hashlib.sha256()
with source.open("rb") as stream:
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
digest.update(chunk)
document_id = "doc_" + digest.hexdigest()[:16]
records = self.store.page_results(job_id)
pages = []
for record in records:
page_no = record["page_no"]
page_id = f"{document_id}/p{page_no:03d}"
if record["status"] == "done":
result = json.loads(record["result_json"])
blocks = [{"block_id": f"{page_id}/b{i:03d}", **block}
for i, block in enumerate(result["blocks"])]
width, height = result["width"], result["height"]
else:
blocks, width, height = [], None, None
pages.append({"page_id": page_id, "page_no": page_no, "width": width,
"height": height, "status": record["status"],
"error": record["error"], "blocks": blocks})
if len(pages) != job["total_pages"]:
raise ValueError("Page count mismatch while building result")
bundle = {
"schema": "dla-document-bundle", "version": "1.0",
"document_id": document_id,
"source": {"filename": job["filename"] or Path(job["file_path"]).name,
"media_type": "application/pdf",
"page_count": len(pages), "render_dpi": 200},
"outline": build_outline(pages), "pages": pages,
}
result_json = json.dumps(bundle, ensure_ascii=False, separators=(",", ":"))
has_failures = any(p["status"] == "failed" for p in pages)
if self.store.finalized(job_id, job["finalize_attempts"], result_json, has_failures):
if not job["callback_url"]:
shutil.rmtree(self.job_dir(job_id), ignore_errors=True)
self.cleanup_source(job)
log.info("Finalized %s for callback", job_id)
except Exception as exc:
log.exception("Finalization failed for %s", job_id)
self.store.finalize_failed(job_id, job["finalize_attempts"], str(exc), self.settings.max_job_attempts)
def callback(self, job: dict):
try:
canonical = json.loads(job["result_json"]) if job["result_json"] else None
extraction = None
if canonical is not None:
source = self.job_dir(job["id"]) / "source.pdf"
extraction = {"pages": []}
for page_no in range(1, canonical["source"]["page_count"] + 1):
image, _, _ = render_page(source, page_no)
extraction["pages"].append({
"page_no": page_no,
"media_type": "image/png",
"data_base64": base64.b64encode(image).decode("ascii"),
})
payload = {
"dag_run_id": job["dag_run_id"] or job["id"],
"conf": {
"request_id": job["request_id"], "job_id": job["id"],
"status": "done" if job["status"] == "completed" else job["status"],
"output": {
"extraction": extraction,
"canonical": canonical,
},
},
}
request = Request(job["callback_url"], data=json.dumps(payload).encode("utf-8"),
headers={"Content-Type": "application/json",
"Idempotency-Key": job["id"]}, method="POST")
with urlopen(request, timeout=10) as response:
if not 200 <= response.status < 300:
raise RuntimeError(f"Callback HTTP {response.status}")
self.store.callback_done(job["id"], job["callback_attempts"])
shutil.rmtree(self.job_dir(job["id"]), ignore_errors=True)
except Exception as exc:
log.warning("Callback failed for %s: %s", job["id"], exc)
self.store.callback_failed(job["id"], job["callback_attempts"],
str(exc), self.settings.max_callback_attempts)
if job["callback_attempts"] >= self.settings.max_callback_attempts:
shutil.rmtree(self.job_dir(job["id"]), ignore_errors=True)
def coordinator_once(self) -> bool:
did_work = False
job = self.store.claim_prepare(self.settings.lease_seconds)
if job:
self.prepare(job)
did_work = True
job = self.store.claim_finalize(self.settings.lease_seconds)
if job:
self.finalize(job)
did_work = True
job = self.store.claim_callback(self.settings.lease_seconds)
if job:
self.callback(job)
did_work = True
return did_work
def page_loop(self):
while not self.stop.is_set():
page = self.store.claim_page(self.settings.lease_seconds, self.settings.ocr_workers)
if page:
self.process_page(page)
else:
self.stop.wait(self.settings.poll_seconds)
def run(self):
threads = [threading.Thread(target=self.page_loop, name=f"ocr-{i}", daemon=True)
for i in range(self.settings.ocr_workers)]
for thread in threads:
thread.start()
log.info("Worker started with %s OCR threads", len(threads))
try:
while not self.stop.is_set():
if not self.coordinator_once():
self.stop.wait(self.settings.poll_seconds)
finally:
self.stop.set()
for thread in threads:
thread.join(timeout=1)
def main():
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
worker = Worker(Settings())
signal.signal(signal.SIGTERM, lambda *_: worker.stop.set())
signal.signal(signal.SIGINT, lambda *_: worker.stop.set())
worker.run()
if __name__ == "__main__":
main()