Initial commit
This commit is contained in:
185
idp_service/worker.py
Normal file
185
idp_service/worker.py
Normal file
@@ -0,0 +1,185 @@
|
||||
"""Run separately from the API: python -m idp_service.worker."""
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import shutil
|
||||
import signal
|
||||
import threading
|
||||
import time
|
||||
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
|
||||
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")
|
||||
|
||||
def job_dir(self, job_id: str) -> Path:
|
||||
return self.settings.work_dir / job_id
|
||||
|
||||
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")
|
||||
fetch_pdf(self.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)
|
||||
|
||||
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": 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):
|
||||
shutil.rmtree(self.job_dir(job_id), ignore_errors=True)
|
||||
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:
|
||||
payload = {
|
||||
"request_id": job["request_id"], "job_id": job["id"],
|
||||
"batch_id": job["batch_id"],
|
||||
"status": "done" if job["status"] == "completed" else job["status"],
|
||||
"output": json.loads(job["result_json"]) if job["result_json"] else None,
|
||||
"error": job["error"],
|
||||
}
|
||||
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"])
|
||||
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)
|
||||
|
||||
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()
|
||||
Reference in New Issue
Block a user