"""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.error import HTTPError from urllib.parse import quote, urlsplit, urlunsplit 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 .kie import SCHEMA_NAME, empty_answer, extract_document 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.callback_workers < 1: raise ValueError("IDP_CALLBACK_WORKERS must be positive") if settings.ocr_backend not in ("http", "pdf_text"): raise ValueError("IDP_OCR_BACKEND must be http or pdf_text") if bool(settings.callback_basic_user) != bool(settings.callback_basic_password): raise ValueError("Set both IDP_CALLBACK_BASIC_USER and IDP_CALLBACK_BASIC_PASSWORD") 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 extract(self, job: dict): """Bóc các trường cố định cho cả tài liệu, chạy sau khi mọi trang đã OCR xong để dùng block DLA.""" job_id, attempts = job["id"], job["extract_attempts"] if not self.settings.kie_enabled or self.settings.ocr_backend == "pdf_text": self.store.extract_done(job_id, attempts, None, status="skipped") return try: if attempts > self.settings.max_kie_attempts: raise ValueError("Extract lease expired too many times") page_blocks = {r["page_no"]: json.loads(r["result_json"])["blocks"] for r in self.store.page_results(job_id) if r["status"] == "done"} answer = extract_document(self.settings, self.job_dir(job_id) / "source.pdf", job["total_pages"], page_blocks) self.store.extract_done(job_id, attempts, json.dumps(answer, ensure_ascii=False)) log.info("Extracted fields for %s", job_id) except Exception as exc: log.warning("Extract failed: %s attempt %s: %s", job_id, attempts, exc) self.store.extract_failed(job_id, attempts, str(exc), self.settings.max_kie_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}, "extraction": { "schema": SCHEMA_NAME, "status": job["extract_status"], "fields": json.loads(job["extract_json"]) if job["extract_json"] else empty_answer(), "error": job["extract_error"], }, "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 = {**canonical.get("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, }, }, } headers = {"Content-Type": "application/json", "Idempotency-Key": job["id"]} if self.settings.callback_basic_user: credentials = f"{self.settings.callback_basic_user}:{self.settings.callback_basic_password}" headers["Authorization"] = "Basic " + base64.b64encode(credentials.encode("utf-8")).decode("ascii") request = Request(job["callback_url"], data=json.dumps(payload).encode("utf-8"), headers=headers, method="POST") try: with urlopen(request, timeout=10) as response: if not 200 <= response.status < 300: raise RuntimeError(f"Callback HTTP {response.status}") except HTTPError as exc: if exc.code != 409 or not self.airflow_run_matches(job["callback_url"], payload, headers): raise log.info("Airflow DAG run already exists for %s; callback confirmed", job["id"]) 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) @staticmethod def airflow_run_matches(callback_url: str, payload: dict, headers: dict) -> bool: """A 409 confirms delivery only when Airflow has this same job's DAG run.""" parsed = urlsplit(callback_url) path = parsed.path.rstrip("/") segments = path.split("/") if len(segments) != 6 or segments[:4] != ["", "api", "v1", "dags"] or segments[5] != "dagRuns": return False run_url = urlunsplit((parsed.scheme, parsed.netloc, path + "/" + quote(payload["dag_run_id"], safe=""), "", "")) get_headers = {"Authorization": headers["Authorization"]} if "Authorization" in headers else {} with urlopen(Request(run_url, headers=get_headers, method="GET"), timeout=10) as response: existing = json.load(response) conf = existing.get("conf") or {} expected = payload["conf"] return (existing.get("dag_run_id") == payload["dag_run_id"] and conf.get("job_id") == expected["job_id"] and conf.get("request_id") == expected["request_id"]) 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 return did_work def callback_once(self) -> bool: job = self.store.claim_callback(self.settings.lease_seconds) if not job: return False self.callback(job) return True def callback_loop(self): while not self.stop.is_set(): if not self.callback_once(): self.stop.wait(self.settings.poll_seconds) 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) continue job = self.store.claim_extract(self.settings.lease_seconds, self.settings.ocr_workers) if job: self.extract(job) continue 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)] threads.extend(threading.Thread(target=self.callback_loop, name=f"callback-{i}", daemon=True) for i in range(self.settings.callback_workers)) for thread in threads: thread.start() log.info("Worker started with %s OCR threads and %s callback threads", self.settings.ocr_workers, self.settings.callback_workers) 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()