Initial commit
This commit is contained in:
1
idp_service/__init__.py
Normal file
1
idp_service/__init__.py
Normal file
@@ -0,0 +1 @@
|
||||
"""Document parsing service."""
|
||||
101
idp_service/api.py
Normal file
101
idp_service/api.py
Normal file
@@ -0,0 +1,101 @@
|
||||
"""HTTP API. Start with: uvicorn idp_service.api:app --host 0.0.0.0 --port 8080"""
|
||||
import hmac
|
||||
from urllib.parse import urlparse
|
||||
from uuid import UUID
|
||||
|
||||
import json
|
||||
|
||||
from fastapi import Depends, FastAPI, Header, HTTPException, Response, status
|
||||
from fastapi.responses import JSONResponse
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from .config import Settings
|
||||
from .db import Store
|
||||
|
||||
|
||||
class ProcessRequest(BaseModel):
|
||||
request_id: UUID
|
||||
file_path: str = Field(min_length=1, max_length=2048)
|
||||
file_type: str = "application/pdf"
|
||||
callback_url: str | None = None
|
||||
batch_id: str | None = Field(default=None, max_length=128)
|
||||
|
||||
|
||||
def create_app(settings: Settings | None = None) -> FastAPI:
|
||||
settings = settings or Settings()
|
||||
store = Store(settings.db_path)
|
||||
app = FastAPI(title="IDP Parsing Service", version="0.1.0")
|
||||
|
||||
def authorize(x_api_key: str | None = Header(default=None)):
|
||||
if settings.api_key and not hmac.compare_digest(x_api_key or "", settings.api_key):
|
||||
raise HTTPException(status_code=401, detail="Invalid API key")
|
||||
|
||||
def public_job(job: dict) -> dict:
|
||||
result = {key: job[key] for key in (
|
||||
"id", "request_id", "batch_id", "status", "file_path", "total_pages",
|
||||
"completed_pages", "failed_pages", "error",
|
||||
"callback_state", "callback_error", "created_at", "updated_at")}
|
||||
result["result_available"] = job["result_json"] is not None
|
||||
return result
|
||||
|
||||
@app.get("/healthz")
|
||||
def healthz():
|
||||
return {"status": "ok"}
|
||||
|
||||
@app.get("/readyz")
|
||||
def readyz():
|
||||
try:
|
||||
with store.connect() as db:
|
||||
db.execute("SELECT 1").fetchone()
|
||||
except Exception as exc:
|
||||
raise HTTPException(status_code=503, detail="Job store unavailable") from exc
|
||||
return {"status": "ready"}
|
||||
|
||||
@app.post("/process", status_code=status.HTTP_202_ACCEPTED, dependencies=[Depends(authorize)])
|
||||
@app.post("/jobs", status_code=status.HTTP_202_ACCEPTED, dependencies=[Depends(authorize)])
|
||||
def submit(request: ProcessRequest, response: Response):
|
||||
if request.file_type != "application/pdf" or not request.file_path.lower().endswith(".pdf"):
|
||||
raise HTTPException(status_code=422, detail="Only PDF input is supported")
|
||||
if request.callback_url:
|
||||
parsed = urlparse(request.callback_url)
|
||||
allowed = {host.strip() for host in settings.callback_hosts.split(",") if host.strip()}
|
||||
if parsed.scheme not in ("http", "https") or not parsed.hostname or (allowed and parsed.hostname not in allowed):
|
||||
raise HTTPException(status_code=422, detail="Callback URL or host is not allowed")
|
||||
try:
|
||||
job, created = store.create_job(str(request.request_id), request.file_path,
|
||||
request.callback_url, request.batch_id,
|
||||
settings.max_queued_jobs)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=409, detail=str(exc)) from exc
|
||||
except OverflowError as exc:
|
||||
raise HTTPException(status_code=429, detail=str(exc)) from exc
|
||||
if not created:
|
||||
response.headers["X-Idempotent-Replay"] = "true"
|
||||
return {"request_id": job["request_id"], "job_id": job["id"], "status": job["status"]}
|
||||
|
||||
@app.get("/jobs/{job_id}", dependencies=[Depends(authorize)])
|
||||
def job_status(job_id: str):
|
||||
job = store.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
return public_job(job)
|
||||
|
||||
@app.get("/jobs/{job_id}/pages", dependencies=[Depends(authorize)])
|
||||
def page_status(job_id: str):
|
||||
if not store.get_job(job_id):
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
return {"job_id": job_id, "pages": store.get_pages(job_id)}
|
||||
|
||||
@app.get("/jobs/{job_id}/result", dependencies=[Depends(authorize)])
|
||||
def job_result(job_id: str):
|
||||
job = store.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
if not job["result_json"]:
|
||||
raise HTTPException(status_code=409, detail="Result is not ready")
|
||||
return JSONResponse(content=json.loads(job["result_json"]))
|
||||
|
||||
return app
|
||||
|
||||
|
||||
app = create_app()
|
||||
34
idp_service/config.py
Normal file
34
idp_service/config.py
Normal file
@@ -0,0 +1,34 @@
|
||||
import os
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Settings:
|
||||
data_dir: Path = Path(os.getenv("IDP_DATA_DIR", "./data")).resolve()
|
||||
storage: str = os.getenv("IDP_STORAGE", "local") # local, hdfs, or hdfs_cli
|
||||
hdfs_url: str = os.getenv("IDP_HDFS_URL", "http://namenode:9870")
|
||||
api_key: str = os.getenv("IDP_API_KEY", "")
|
||||
callback_hosts: str = os.getenv("IDP_CALLBACK_HOSTS", "")
|
||||
ocr_url: str = os.getenv("IDP_OCR_URL", "http://localhost:9222/v1/chat/completions")
|
||||
ocr_model: str = os.getenv("IDP_OCR_MODEL", "chandra")
|
||||
ocr_workers: int = int(os.getenv("IDP_OCR_WORKERS", "64"))
|
||||
max_queued_jobs: int = int(os.getenv("IDP_MAX_QUEUED_JOBS", "1000"))
|
||||
max_pdf_bytes: int = int(os.getenv("IDP_MAX_PDF_BYTES", str(1024**3)))
|
||||
max_pages: int = int(os.getenv("IDP_MAX_PAGES", "5000"))
|
||||
max_page_attempts: int = int(os.getenv("IDP_MAX_PAGE_ATTEMPTS", "3"))
|
||||
max_job_attempts: int = int(os.getenv("IDP_MAX_JOB_ATTEMPTS", "3"))
|
||||
max_callback_attempts: int = int(os.getenv("IDP_MAX_CALLBACK_ATTEMPTS", "10"))
|
||||
voffice_decrypt_mode: str = os.getenv("IDP_VOFFICE_DECRYPT_MODE", "auto").lower()
|
||||
voffice_des_key_hex: str = os.getenv("IDP_VOFFICE_DES_KEY_HEX", "a1e3c21919adeeab")
|
||||
ocr_timeout: int = int(os.getenv("IDP_OCR_TIMEOUT", "180"))
|
||||
lease_seconds: int = int(os.getenv("IDP_LEASE_SECONDS", "1800"))
|
||||
poll_seconds: float = float(os.getenv("IDP_POLL_SECONDS", "0.5"))
|
||||
|
||||
@property
|
||||
def db_path(self) -> Path:
|
||||
return self.data_dir / "jobs.sqlite3"
|
||||
|
||||
@property
|
||||
def work_dir(self) -> Path:
|
||||
return self.data_dir / "work"
|
||||
242
idp_service/db.py
Normal file
242
idp_service/db.py
Normal file
@@ -0,0 +1,242 @@
|
||||
"""SQLite job and page queue. Each claim is an atomic database transaction."""
|
||||
import json
|
||||
import sqlite3
|
||||
import time
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
|
||||
|
||||
def retry_delay(attempt: int) -> int:
|
||||
return min(60, 2 ** min(attempt, 6))
|
||||
|
||||
|
||||
class Store:
|
||||
def __init__(self, path: Path):
|
||||
self.path = path
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
self.init()
|
||||
|
||||
def connect(self):
|
||||
connection = sqlite3.connect(self.path, timeout=30, isolation_level=None)
|
||||
connection.row_factory = sqlite3.Row
|
||||
connection.execute("PRAGMA busy_timeout=30000")
|
||||
connection.execute("PRAGMA foreign_keys=ON")
|
||||
return connection
|
||||
|
||||
def init(self):
|
||||
with self.connect() as db:
|
||||
db.execute("PRAGMA journal_mode=WAL")
|
||||
db.executescript("""
|
||||
CREATE TABLE IF NOT EXISTS jobs (
|
||||
id TEXT PRIMARY KEY, request_id TEXT NOT NULL UNIQUE,
|
||||
file_path TEXT NOT NULL, callback_url TEXT, batch_id TEXT,
|
||||
status TEXT NOT NULL, created_at REAL NOT NULL, updated_at REAL NOT NULL,
|
||||
total_pages INTEGER NOT NULL DEFAULT 0,
|
||||
attempts INTEGER NOT NULL DEFAULT 0,
|
||||
finalize_attempts INTEGER NOT NULL DEFAULT 0,
|
||||
next_at REAL NOT NULL DEFAULT 0, lease_until REAL NOT NULL DEFAULT 0,
|
||||
error TEXT, result_path TEXT, result_json TEXT,
|
||||
callback_state TEXT NOT NULL DEFAULT 'none',
|
||||
callback_attempts INTEGER NOT NULL DEFAULT 0,
|
||||
callback_next_at REAL NOT NULL DEFAULT 0,
|
||||
callback_lease_until REAL NOT NULL DEFAULT 0,
|
||||
callback_error TEXT
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS pages (
|
||||
job_id TEXT NOT NULL REFERENCES jobs(id) ON DELETE CASCADE,
|
||||
page_no INTEGER NOT NULL, status TEXT NOT NULL,
|
||||
attempts INTEGER NOT NULL DEFAULT 0,
|
||||
next_at REAL NOT NULL DEFAULT 0, lease_until REAL NOT NULL DEFAULT 0,
|
||||
penalize_repetition INTEGER NOT NULL DEFAULT 0,
|
||||
error TEXT, result_json TEXT,
|
||||
PRIMARY KEY (job_id, page_no)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS jobs_queue_idx ON jobs(status, next_at);
|
||||
CREATE INDEX IF NOT EXISTS pages_queue_idx ON pages(status, next_at);
|
||||
""")
|
||||
columns = {row[1] for row in db.execute("PRAGMA table_info(jobs)")}
|
||||
if "result_json" not in columns:
|
||||
db.execute("ALTER TABLE jobs ADD COLUMN result_json TEXT")
|
||||
|
||||
@contextmanager
|
||||
def tx(self):
|
||||
db = self.connect()
|
||||
try:
|
||||
db.execute("BEGIN IMMEDIATE")
|
||||
yield db
|
||||
db.execute("COMMIT")
|
||||
except BaseException:
|
||||
db.execute("ROLLBACK")
|
||||
raise
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
@staticmethod
|
||||
def as_dict(row):
|
||||
return dict(row) if row else None
|
||||
|
||||
def create_job(self, request_id: str, file_path: str, callback_url: str | None,
|
||||
batch_id: str | None, max_queued: int):
|
||||
now = time.time()
|
||||
with self.tx() as db:
|
||||
prior = db.execute("SELECT * FROM jobs WHERE request_id=?", (request_id,)).fetchone()
|
||||
if prior:
|
||||
if (prior["file_path"], prior["callback_url"], prior["batch_id"]) != (file_path, callback_url, batch_id):
|
||||
raise ValueError("request_id already exists with different inputs")
|
||||
return self.as_dict(prior), False
|
||||
queued = db.execute("SELECT count(*) FROM jobs WHERE status IN ('queued','preparing','processing','finalizing')").fetchone()[0]
|
||||
if queued >= max_queued:
|
||||
raise OverflowError("Job queue is full")
|
||||
job_id = "job_" + uuid4().hex
|
||||
db.execute("""INSERT INTO jobs(id,request_id,file_path,callback_url,batch_id,status,created_at,updated_at)
|
||||
VALUES(?,?,?,?,?,'queued',?,?)""",
|
||||
(job_id, request_id, file_path, callback_url, batch_id, now, now))
|
||||
return self.as_dict(db.execute("SELECT * FROM jobs WHERE id=?", (job_id,)).fetchone()), True
|
||||
|
||||
def get_job(self, job_id: str):
|
||||
with self.connect() as db:
|
||||
row = db.execute("""SELECT j.*,
|
||||
(SELECT count(*) FROM pages p WHERE p.job_id=j.id AND p.status='done') AS completed_pages,
|
||||
(SELECT count(*) FROM pages p WHERE p.job_id=j.id AND p.status='failed') AS failed_pages
|
||||
FROM jobs j WHERE j.id=?""", (job_id,)).fetchone()
|
||||
return self.as_dict(row)
|
||||
|
||||
def get_pages(self, job_id: str):
|
||||
with self.connect() as db:
|
||||
rows = db.execute("SELECT page_no,status,attempts,error FROM pages WHERE job_id=? ORDER BY page_no", (job_id,)).fetchall()
|
||||
return [self.as_dict(row) for row in rows]
|
||||
|
||||
def claim_prepare(self, lease_seconds: int):
|
||||
now = time.time()
|
||||
with self.tx() as db:
|
||||
row = db.execute("""SELECT * FROM jobs WHERE
|
||||
(status='queued' AND next_at<=?) OR (status='preparing' AND lease_until<=?)
|
||||
ORDER BY created_at LIMIT 1""", (now, now)).fetchone()
|
||||
if not row:
|
||||
return None
|
||||
db.execute("""UPDATE jobs SET status='preparing',attempts=attempts+1,
|
||||
lease_until=?,updated_at=? WHERE id=?""", (now + lease_seconds, now, row["id"]))
|
||||
return self.as_dict(db.execute("SELECT * FROM jobs WHERE id=?", (row["id"],)).fetchone())
|
||||
|
||||
def prepared(self, job_id: str, attempts: int, page_count: int):
|
||||
now = time.time()
|
||||
with self.tx() as db:
|
||||
row = db.execute("SELECT status,attempts FROM jobs WHERE id=?", (job_id,)).fetchone()
|
||||
if not row or row["status"] != "preparing" or row["attempts"] != attempts:
|
||||
return False
|
||||
db.executemany("INSERT OR IGNORE INTO pages(job_id,page_no,status) VALUES(?,?,'queued')",
|
||||
[(job_id, n) for n in range(1, page_count + 1)])
|
||||
db.execute("UPDATE jobs SET status='processing',total_pages=?,lease_until=0,error=NULL,updated_at=? WHERE id=?",
|
||||
(page_count, now, job_id))
|
||||
return True
|
||||
|
||||
def prepare_failed(self, job_id: str, attempts: int, error: str, max_attempts: int):
|
||||
now = time.time()
|
||||
terminal = attempts >= max_attempts
|
||||
with self.tx() as db:
|
||||
db.execute("""UPDATE jobs SET status=?,error=?,next_at=?,lease_until=0,
|
||||
callback_state=CASE WHEN ? AND callback_url IS NOT NULL THEN 'pending' ELSE callback_state END,
|
||||
updated_at=? WHERE id=? AND status='preparing' AND attempts=?""",
|
||||
("failed" if terminal else "queued", error[:1000], now + retry_delay(attempts),
|
||||
int(terminal), now, job_id, attempts))
|
||||
|
||||
def claim_page(self, lease_seconds: int, global_limit: int):
|
||||
now = time.time()
|
||||
with self.tx() as db:
|
||||
active = db.execute("SELECT count(*) FROM pages WHERE status='running' AND lease_until>?", (now,)).fetchone()[0]
|
||||
if active >= global_limit:
|
||||
return None
|
||||
row = db.execute("""SELECT p.*,j.file_path FROM pages p JOIN jobs j ON j.id=p.job_id
|
||||
WHERE j.status='processing' AND ((p.status='queued' AND p.next_at<=?)
|
||||
OR (p.status='running' AND p.lease_until<=?))
|
||||
ORDER BY (SELECT count(*) FROM pages active
|
||||
WHERE active.job_id=p.job_id AND active.status='running' AND active.lease_until>?),
|
||||
p.next_at,j.created_at,p.page_no LIMIT 1""", (now, now, now)).fetchone()
|
||||
if not row:
|
||||
return None
|
||||
db.execute("""UPDATE pages SET status='running',attempts=attempts+1,lease_until=?
|
||||
WHERE job_id=? AND page_no=?""", (now + lease_seconds, row["job_id"], row["page_no"]))
|
||||
return self.as_dict(db.execute("SELECT * FROM pages WHERE job_id=? AND page_no=?",
|
||||
(row["job_id"], row["page_no"])).fetchone())
|
||||
|
||||
def page_done(self, job_id: str, page_no: int, attempts: int, result: dict):
|
||||
with self.tx() as db:
|
||||
return db.execute("""UPDATE pages SET status='done',result_json=?,error=NULL,lease_until=0
|
||||
WHERE job_id=? AND page_no=? AND status='running' AND attempts=?""",
|
||||
(json.dumps(result, ensure_ascii=False), job_id, page_no, attempts)).rowcount == 1
|
||||
|
||||
def page_failed(self, job_id: str, page_no: int, attempts: int, error: str,
|
||||
truncated: bool, max_attempts: int):
|
||||
now = time.time()
|
||||
terminal = attempts >= max_attempts
|
||||
with self.tx() as db:
|
||||
db.execute("""UPDATE pages SET status=?,error=?,next_at=?,lease_until=0,
|
||||
penalize_repetition=CASE WHEN ? THEN 1 ELSE penalize_repetition END
|
||||
WHERE job_id=? AND page_no=? AND status='running' AND attempts=?""",
|
||||
("failed" if terminal else "queued", error[:1000], now + retry_delay(attempts),
|
||||
int(truncated), job_id, page_no, attempts))
|
||||
|
||||
def claim_finalize(self, lease_seconds: int):
|
||||
now = time.time()
|
||||
with self.tx() as db:
|
||||
row = db.execute("""SELECT * FROM jobs j WHERE
|
||||
((j.status='processing' AND j.next_at<=? AND j.total_pages>0 AND NOT EXISTS
|
||||
(SELECT 1 FROM pages p WHERE p.job_id=j.id AND p.status IN ('queued','running')))
|
||||
OR (j.status='finalizing' AND j.lease_until<=?))
|
||||
ORDER BY j.created_at LIMIT 1""", (now, now)).fetchone()
|
||||
if not row:
|
||||
return None
|
||||
db.execute("""UPDATE jobs SET status='finalizing',finalize_attempts=finalize_attempts+1,
|
||||
lease_until=?,updated_at=? WHERE id=?""", (now + lease_seconds, now, row["id"]))
|
||||
return self.as_dict(db.execute("SELECT * FROM jobs WHERE id=?", (row["id"],)).fetchone())
|
||||
|
||||
def page_results(self, job_id: str):
|
||||
with self.connect() as db:
|
||||
return [self.as_dict(row) for row in db.execute("""SELECT page_no,status,error,result_json
|
||||
FROM pages WHERE job_id=? ORDER BY page_no""", (job_id,))]
|
||||
|
||||
def finalized(self, job_id: str, attempts: int, result_json: str, has_failures: bool):
|
||||
now = time.time()
|
||||
with self.tx() as db:
|
||||
return db.execute("""UPDATE jobs SET status=?,result_path=NULL,result_json=?,error=NULL,lease_until=0,updated_at=?,
|
||||
callback_state=CASE WHEN callback_url IS NOT NULL THEN 'pending' ELSE 'none' END
|
||||
WHERE id=? AND status='finalizing' AND finalize_attempts=?""",
|
||||
("partial_failed" if has_failures else "completed", result_json, now, job_id, attempts)).rowcount == 1
|
||||
|
||||
def finalize_failed(self, job_id: str, attempts: int, error: str, max_attempts: int):
|
||||
now = time.time()
|
||||
terminal = attempts >= max_attempts
|
||||
with self.tx() as db:
|
||||
db.execute("""UPDATE jobs SET status=?,error=?,next_at=?,lease_until=0,updated_at=?,
|
||||
callback_state=CASE WHEN ? AND callback_url IS NOT NULL THEN 'pending' ELSE callback_state END
|
||||
WHERE id=? AND status='finalizing' AND finalize_attempts=?""",
|
||||
("failed" if terminal else "processing", error[:1000], now + retry_delay(attempts),
|
||||
now, int(terminal), job_id, attempts))
|
||||
|
||||
def claim_callback(self, lease_seconds: int):
|
||||
now = time.time()
|
||||
with self.tx() as db:
|
||||
row = db.execute("""SELECT * FROM jobs WHERE status IN ('completed','partial_failed','failed')
|
||||
AND ((callback_state='pending' AND callback_next_at<=?)
|
||||
OR (callback_state='sending' AND callback_lease_until<=?))
|
||||
ORDER BY created_at LIMIT 1""", (now, now)).fetchone()
|
||||
if not row:
|
||||
return None
|
||||
db.execute("""UPDATE jobs SET callback_state='sending',callback_attempts=callback_attempts+1,
|
||||
callback_lease_until=? WHERE id=?""", (now + lease_seconds, row["id"]))
|
||||
return self.as_dict(db.execute("SELECT * FROM jobs WHERE id=?", (row["id"],)).fetchone())
|
||||
|
||||
def callback_done(self, job_id: str, attempts: int):
|
||||
with self.tx() as db:
|
||||
db.execute("""UPDATE jobs SET callback_state='delivered',callback_error=NULL,
|
||||
callback_lease_until=0 WHERE id=? AND callback_state='sending' AND callback_attempts=?""",
|
||||
(job_id, attempts))
|
||||
|
||||
def callback_failed(self, job_id: str, attempts: int, error: str, max_attempts: int):
|
||||
now = time.time()
|
||||
with self.tx() as db:
|
||||
db.execute("""UPDATE jobs SET callback_state=?,callback_error=?,callback_next_at=?,
|
||||
callback_lease_until=0 WHERE id=? AND callback_state='sending' AND callback_attempts=?""",
|
||||
("exhausted" if attempts >= max_attempts else "pending", error[:1000],
|
||||
now + retry_delay(attempts), job_id, attempts))
|
||||
73
idp_service/decrypt.py
Normal file
73
idp_service/decrypt.py
Normal file
@@ -0,0 +1,73 @@
|
||||
"""VOffice document decryption compatible with VOfficeSecurity.jar."""
|
||||
from pathlib import Path
|
||||
|
||||
from Crypto.Cipher import DES
|
||||
|
||||
|
||||
PDF_MAGIC = b"%PDF-"
|
||||
DEFAULT_KEY_HEX = "a1e3c21919adeeab"
|
||||
|
||||
|
||||
class DecryptionError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
def is_pdf(path: Path) -> bool:
|
||||
"""PDF permits its header anywhere within the first 1024 bytes."""
|
||||
with path.open("rb") as stream:
|
||||
return PDF_MAGIC in stream.read(1024)
|
||||
|
||||
|
||||
def decrypt_des_file(source: Path, destination: Path, key_hex: str) -> None:
|
||||
"""Decrypt DES/ECB/PKCS5Padding without loading a potentially large PDF in RAM."""
|
||||
try:
|
||||
key = bytes.fromhex(key_hex)
|
||||
except ValueError as exc:
|
||||
raise DecryptionError("IDP_VOFFICE_DES_KEY_HEX is not valid hexadecimal") from exc
|
||||
if len(key) != DES.block_size:
|
||||
raise DecryptionError("VOffice DES key must contain exactly 8 bytes")
|
||||
size = source.stat().st_size
|
||||
if size == 0 or size % DES.block_size:
|
||||
raise DecryptionError("Encrypted VOffice file size is not a multiple of 8 bytes")
|
||||
|
||||
cipher = DES.new(key, DES.MODE_ECB)
|
||||
temporary = destination.with_suffix(destination.suffix + ".decrypting")
|
||||
temporary.unlink(missing_ok=True)
|
||||
last_plain = None
|
||||
try:
|
||||
with source.open("rb") as encrypted, temporary.open("wb") as plain:
|
||||
while chunk := encrypted.read(1024 * 1024):
|
||||
if len(chunk) % DES.block_size:
|
||||
raise DecryptionError("Truncated encrypted VOffice file")
|
||||
decoded = cipher.decrypt(chunk)
|
||||
if last_plain is not None:
|
||||
plain.write(last_plain)
|
||||
if len(decoded) > DES.block_size:
|
||||
plain.write(decoded[:-DES.block_size])
|
||||
last_plain = decoded[-DES.block_size:]
|
||||
if last_plain is None:
|
||||
raise DecryptionError("Encrypted VOffice file is empty")
|
||||
padding = last_plain[-1]
|
||||
if not 1 <= padding <= DES.block_size or last_plain[-padding:] != bytes([padding]) * padding:
|
||||
raise DecryptionError("Invalid VOffice DES padding or key")
|
||||
plain.write(last_plain[:-padding])
|
||||
if not is_pdf(temporary):
|
||||
raise DecryptionError("Decrypted content is not a PDF")
|
||||
temporary.replace(destination)
|
||||
except BaseException:
|
||||
temporary.unlink(missing_ok=True)
|
||||
raise
|
||||
|
||||
|
||||
def prepare_pdf(source: Path, destination: Path, mode: str, key_hex: str) -> bool:
|
||||
"""Return True when decryption occurred; modes: auto, required, off."""
|
||||
if mode not in {"auto", "required", "off"}:
|
||||
raise DecryptionError("IDP_VOFFICE_DECRYPT_MODE must be auto, required, or off")
|
||||
if mode != "required" and is_pdf(source):
|
||||
source.replace(destination)
|
||||
return False
|
||||
if mode == "off":
|
||||
raise DecryptionError("Downloaded file is not a PDF and VOffice decryption is disabled")
|
||||
decrypt_des_file(source, destination, key_hex)
|
||||
source.unlink(missing_ok=True)
|
||||
return True
|
||||
120
idp_service/dla.py
Normal file
120
idp_service/dla.py
Normal file
@@ -0,0 +1,120 @@
|
||||
"""DLA prompt, HTML block parsing, and document outline helpers."""
|
||||
import re
|
||||
from html.parser import HTMLParser
|
||||
|
||||
|
||||
TAG = re.compile(r"<[^>]+>")
|
||||
FURNITURE_LABELS = {"Header", "Footer"}
|
||||
|
||||
PROMPT = """OCR this image to HTML, arranged as layout blocks. Each layout block must be a div with a data-bbox attribute in x0 y0 x1 y1 format. Bounding boxes are normalized to the 0-1000 range. The data-label attribute must contain exactly one of these labels:
|
||||
|
||||
- Title: the main title of the document
|
||||
- Section Header: a heading that introduces a section
|
||||
- Header: repeated or auxiliary content at the top of a page
|
||||
- Footer: repeated or auxiliary content at the bottom of a page
|
||||
- Paragraph: normal textual content that does not belong to another label
|
||||
- Table: a table, preserving rows, columns, colspan, and rowspan in HTML
|
||||
- Barcode: a one-dimensional barcode
|
||||
- QR Code: a QR code
|
||||
- Signature: a handwritten signature
|
||||
- Stamp: an ink or digital stamp/seal
|
||||
- Image: any other image, figure, photo, chart, or diagram
|
||||
|
||||
Preserve the natural reading order. Preserve all visible text accurately. Use HTML inside each block; tables must remain HTML tables. Use the simplest HTML structure that accurately represents the content. Return only the HTML layout blocks, without Markdown fences, explanations, JSON, or a surrounding html/body tag.
|
||||
"""
|
||||
|
||||
|
||||
class LayoutParser(HTMLParser):
|
||||
def __init__(self):
|
||||
super().__init__(convert_charrefs=True)
|
||||
self.blocks, self.depth, self.current = [], 0, None
|
||||
|
||||
def handle_starttag(self, tag, attrs):
|
||||
if tag == "div":
|
||||
self.depth += 1
|
||||
if self.depth == 1:
|
||||
values = dict(attrs)
|
||||
self.current = {"bbox_raw": values.get("data-bbox"),
|
||||
"label": values.get("data-label", "Unknown"), "html": []}
|
||||
return
|
||||
if self.current is not None:
|
||||
attr_str = "".join(f' {k}="{v}"' for k, v in attrs if v is not None)
|
||||
self.current["html"].append(f"<{tag}{attr_str}>")
|
||||
|
||||
def handle_startendtag(self, tag, attrs):
|
||||
if self.current is not None:
|
||||
attr_str = "".join(f' {k}="{v}"' for k, v in attrs if v is not None)
|
||||
self.current["html"].append(f"<{tag}{attr_str}/>")
|
||||
|
||||
def handle_data(self, data):
|
||||
if self.current is not None:
|
||||
self.current["html"].append(data)
|
||||
|
||||
def handle_endtag(self, tag):
|
||||
if tag == "div":
|
||||
if self.depth == 1 and self.current is not None:
|
||||
self._flush()
|
||||
self.depth = 0
|
||||
return
|
||||
self.depth = max(0, self.depth - 1)
|
||||
if self.current is not None:
|
||||
self.current["html"].append(f"</{tag}>")
|
||||
|
||||
def _flush(self):
|
||||
block = self.current
|
||||
self.current = None
|
||||
bbox = None
|
||||
if block["bbox_raw"]:
|
||||
try:
|
||||
parts = [round(float(v)) for v in block["bbox_raw"].replace(",", " ").split()]
|
||||
if len(parts) == 4:
|
||||
bbox = parts
|
||||
except ValueError:
|
||||
pass
|
||||
self.blocks.append({"bbox": bbox, "label": block["label"],
|
||||
"html": "".join(block["html"]).strip()})
|
||||
|
||||
def close(self):
|
||||
super().close()
|
||||
if self.current is not None:
|
||||
self._flush()
|
||||
|
||||
|
||||
def parse_blocks(raw: str):
|
||||
parser = LayoutParser()
|
||||
parser.feed(raw)
|
||||
parser.close()
|
||||
return parser.blocks
|
||||
|
||||
|
||||
def plain_text(html: str) -> str:
|
||||
return re.sub(r"\s+", " ", TAG.sub(" ", html or "")).strip()
|
||||
|
||||
|
||||
def build_outline(pages: list) -> list:
|
||||
sections, current, counter = [], None, 0
|
||||
|
||||
def open_section(header=None):
|
||||
nonlocal counter
|
||||
if header is not None:
|
||||
counter += 1
|
||||
section = {"section_no": str(counter) if header is not None else "0",
|
||||
"heading_block_id": header["block_id"] if header else None,
|
||||
"heading": plain_text(header["html"]) if header else None, "block_ids": []}
|
||||
sections.append(section)
|
||||
return section
|
||||
|
||||
for page in pages:
|
||||
for block in page["blocks"]:
|
||||
if block["label"] in FURNITURE_LABELS:
|
||||
block["outline_no"] = None
|
||||
continue
|
||||
if block["label"] == "Section Header":
|
||||
current = open_section(block)
|
||||
block["outline_no"] = current["section_no"]
|
||||
continue
|
||||
if current is None:
|
||||
current = open_section()
|
||||
current["block_ids"].append(block["block_id"])
|
||||
block["outline_no"] = f"{current['section_no']}.{len(current['block_ids'])}"
|
||||
return sections
|
||||
79
idp_service/ocr.py
Normal file
79
idp_service/ocr.py
Normal file
@@ -0,0 +1,79 @@
|
||||
"""Render one page, call Chandra, and reject incomplete model output."""
|
||||
import base64
|
||||
import json
|
||||
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 infer_page(settings: Settings, pdf_path: Path, page_no: int, *, penalize_repetition: bool = False) -> dict:
|
||||
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)}
|
||||
40
idp_service/storage.py
Normal file
40
idp_service/storage.py
Normal file
@@ -0,0 +1,40 @@
|
||||
"""Input/output storage adapters. The HDFS adapter uses the installed hdfs CLI."""
|
||||
import shutil
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
from .config import Settings
|
||||
|
||||
|
||||
class StorageError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def _hdfs(*args: str) -> None:
|
||||
try:
|
||||
subprocess.run(["hdfs", "dfs", *args], check=True, capture_output=True, text=True, timeout=600)
|
||||
except (OSError, subprocess.CalledProcessError, subprocess.TimeoutExpired) as exc:
|
||||
detail = getattr(exc, "stderr", None) or str(exc)
|
||||
raise StorageError(f"HDFS operation failed: {detail[:500]}") from exc
|
||||
|
||||
|
||||
def fetch_pdf(settings: Settings, source: str, destination: Path) -> None:
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
temporary = destination.with_suffix(".download")
|
||||
temporary.unlink(missing_ok=True)
|
||||
if settings.storage == "hdfs":
|
||||
from .webhdfs import download_pdf
|
||||
download_pdf(settings.hdfs_url, source, temporary, settings.max_pdf_bytes)
|
||||
elif settings.storage == "hdfs_cli":
|
||||
_hdfs("-get", source, str(temporary))
|
||||
elif settings.storage == "local":
|
||||
source_path = Path(source).resolve()
|
||||
if not source_path.is_file():
|
||||
raise StorageError(f"Source file not found: {source}")
|
||||
shutil.copyfile(source_path, temporary)
|
||||
else:
|
||||
raise StorageError(f"Unknown storage mode: {settings.storage}")
|
||||
if temporary.stat().st_size > settings.max_pdf_bytes:
|
||||
temporary.unlink(missing_ok=True)
|
||||
raise StorageError("PDF exceeds IDP_MAX_PDF_BYTES")
|
||||
temporary.replace(destination)
|
||||
27
idp_service/webhdfs.py
Normal file
27
idp_service/webhdfs.py
Normal file
@@ -0,0 +1,27 @@
|
||||
"""WebHDFS adapter based on the repository's original hdfs.py example.
|
||||
|
||||
The original filename shadowed the third-party `hdfs` package it imported.
|
||||
This module streams PDFs to disk instead of loading them fully into memory.
|
||||
"""
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def make_client(url: str):
|
||||
from hdfs import InsecureClient
|
||||
return InsecureClient(url)
|
||||
|
||||
|
||||
def read_hdfs_file(hdfs_url: str, file_path: str) -> bytes:
|
||||
"""Compatibility with the original read-only example."""
|
||||
client = make_client(hdfs_url)
|
||||
with client.read(file_path) as reader:
|
||||
return reader.read()
|
||||
|
||||
|
||||
def download_pdf(hdfs_url: str, hdfs_path: str, destination: Path, max_bytes: int):
|
||||
client = make_client(hdfs_url)
|
||||
metadata = client.status(hdfs_path)
|
||||
if metadata.get("type") != "FILE" or metadata.get("length", 0) > max_bytes:
|
||||
raise ValueError("HDFS source is not a file or exceeds IDP_MAX_PDF_BYTES")
|
||||
client.download(hdfs_path, str(destination), overwrite=True)
|
||||
|
||||
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