Nhận PDF upload trực tiếp qua POST /parse
API trước đây chỉ nhận đường dẫn HDFS từ Airflow. Thêm endpoint
multipart/form-data nhận thẳng file PDF, vẫn chạy bất đồng bộ: trả 202 kèm
job_id và result_url, worker xử lý nền, client lấy dla-document-bundle ở
GET /jobs/{job_id}/result hoặc qua callback.
- File upload ghi xuống IDP_DATA_DIR/uploads theo sha256 nội dung nên gửi lại
cùng request_id trả cùng job_id; file được xoá khi không còn job nào dùng.
- Thêm cột filename/source_kind để bundle giữ đúng tên file gốc thay vì tên
đã băm.
- IDP_RUN_WORKER=1 chạy worker trong process API cho triển khai một host.
- IDP_OCR_BACKEND=pdf_text dựng bundle từ text layer của PDF để chạy thử toàn
bộ luồng khi chưa serve được model.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -1,18 +1,26 @@
|
||||
"""HTTP API. Start with: uvicorn idp_service.api:app --host 0.0.0.0 --port 8080"""
|
||||
import hashlib
|
||||
import hmac
|
||||
from urllib.parse import urlparse
|
||||
from uuid import UUID
|
||||
|
||||
import json
|
||||
import os
|
||||
import threading
|
||||
from contextlib import asynccontextmanager
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlparse
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from fastapi import Depends, FastAPI, Header, HTTPException, Response, status
|
||||
from fastapi import Depends, FastAPI, File, Form, Header, HTTPException, Response, UploadFile, status
|
||||
from fastapi.responses import JSONResponse
|
||||
from pydantic import BaseModel, Field
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
|
||||
from .config import Settings
|
||||
from .db import Store
|
||||
|
||||
|
||||
CHUNK = 1024 * 1024
|
||||
|
||||
|
||||
class ProcessRequest(BaseModel):
|
||||
request_id: UUID
|
||||
file_path: str = Field(min_length=1, max_length=2048)
|
||||
@@ -24,20 +32,56 @@ class ProcessRequest(BaseModel):
|
||||
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")
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(_app: FastAPI):
|
||||
"""IDP_RUN_WORKER=1 chạy worker ngay trong process API, tiện cho một host."""
|
||||
worker = thread = None
|
||||
if settings.run_worker:
|
||||
from .worker import Worker
|
||||
worker = Worker(settings, store)
|
||||
thread = threading.Thread(target=worker.run, name="idp-worker", daemon=True)
|
||||
thread.start()
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
if worker:
|
||||
worker.stop.set()
|
||||
thread.join(timeout=5)
|
||||
|
||||
app = FastAPI(title="IDP Parsing Service", version="0.2.0", lifespan=lifespan)
|
||||
|
||||
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 check_callback(callback_url: str | None):
|
||||
if not callback_url:
|
||||
return
|
||||
parsed = urlparse(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")
|
||||
|
||||
def accepted(job: dict, created: bool, response: Response) -> dict:
|
||||
if not created:
|
||||
response.headers["X-Idempotent-Replay"] = "true"
|
||||
return {"request_id": job["request_id"], "job_id": job["id"], "status": job["status"],
|
||||
"result_url": f"/jobs/{job['id']}/result"}
|
||||
|
||||
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",
|
||||
"id", "request_id", "batch_id", "status", "file_path", "filename", "source_kind",
|
||||
"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
|
||||
|
||||
def discard_upload(path: Path):
|
||||
"""Chỉ xoá khi không còn job nào đang dùng file đã dedupe theo sha256."""
|
||||
if not store.upload_in_use(str(path), ""):
|
||||
path.unlink(missing_ok=True)
|
||||
|
||||
@app.get("/healthz")
|
||||
def healthz():
|
||||
return {"status": "ok"}
|
||||
@@ -51,16 +95,54 @@ def create_app(settings: Settings | None = None) -> FastAPI:
|
||||
raise HTTPException(status_code=503, detail="Job store unavailable") from exc
|
||||
return {"status": "ready"}
|
||||
|
||||
@app.post("/parse", status_code=status.HTTP_202_ACCEPTED, dependencies=[Depends(authorize)])
|
||||
async def parse(response: Response,
|
||||
file: UploadFile = File(...),
|
||||
request_id: UUID | None = Form(default=None),
|
||||
callback_url: str | None = Form(default=None),
|
||||
batch_id: str | None = Form(default=None, max_length=128)):
|
||||
"""Nhận thẳng file PDF qua multipart/form-data và trả job_id ngay."""
|
||||
filename = Path(file.filename or "").name
|
||||
if not filename.lower().endswith(".pdf"):
|
||||
raise HTTPException(status_code=422, detail="Only PDF input is supported")
|
||||
check_callback(callback_url)
|
||||
|
||||
settings.upload_dir.mkdir(parents=True, exist_ok=True)
|
||||
incoming = settings.upload_dir / f".incoming_{uuid4().hex}"
|
||||
digest, size = hashlib.sha256(), 0
|
||||
try:
|
||||
with incoming.open("wb") as handle:
|
||||
while chunk := await file.read(CHUNK):
|
||||
size += len(chunk)
|
||||
if size > settings.max_pdf_bytes:
|
||||
raise HTTPException(status_code=413, detail="PDF exceeds IDP_MAX_PDF_BYTES")
|
||||
digest.update(chunk)
|
||||
await run_in_threadpool(handle.write, chunk)
|
||||
if size == 0:
|
||||
raise HTTPException(status_code=422, detail="Uploaded file is empty")
|
||||
stored = settings.upload_dir / f"{digest.hexdigest()}.pdf"
|
||||
os.replace(incoming, stored)
|
||||
finally:
|
||||
incoming.unlink(missing_ok=True)
|
||||
|
||||
try:
|
||||
job, created = store.create_job(str(request_id or uuid4()), str(stored), callback_url,
|
||||
batch_id, settings.max_queued_jobs, filename, "upload")
|
||||
except ValueError as exc:
|
||||
discard_upload(stored)
|
||||
raise HTTPException(status_code=409, detail=str(exc)) from exc
|
||||
except OverflowError as exc:
|
||||
discard_upload(stored)
|
||||
raise HTTPException(status_code=429, detail=str(exc)) from exc
|
||||
return accepted(job, created, response)
|
||||
|
||||
@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):
|
||||
"""Hợp đồng cũ của Airflow: file đã nằm sẵn trên HDFS hoặc đĩa cục bộ."""
|
||||
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")
|
||||
check_callback(request.callback_url)
|
||||
try:
|
||||
job, created = store.create_job(str(request.request_id), request.file_path,
|
||||
request.callback_url, request.batch_id,
|
||||
@@ -69,9 +151,7 @@ def create_app(settings: Settings | None = None) -> FastAPI:
|
||||
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"]}
|
||||
return accepted(job, created, response)
|
||||
|
||||
@app.get("/jobs/{job_id}", dependencies=[Depends(authorize)])
|
||||
def job_status(job_id: str):
|
||||
|
||||
@@ -12,6 +12,8 @@ class Settings:
|
||||
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_backend: str = os.getenv("IDP_OCR_BACKEND", "http") # http hoặc pdf_text
|
||||
run_worker: bool = os.getenv("IDP_RUN_WORKER", "0").lower() in ("1", "true", "yes")
|
||||
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)))
|
||||
@@ -25,6 +27,10 @@ class Settings:
|
||||
lease_seconds: int = int(os.getenv("IDP_LEASE_SECONDS", "1800"))
|
||||
poll_seconds: float = float(os.getenv("IDP_POLL_SECONDS", "0.5"))
|
||||
|
||||
@property
|
||||
def upload_dir(self) -> Path:
|
||||
return self.data_dir / "uploads"
|
||||
|
||||
@property
|
||||
def db_path(self) -> Path:
|
||||
return self.data_dir / "jobs.sqlite3"
|
||||
|
||||
@@ -31,6 +31,7 @@ class Store:
|
||||
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,
|
||||
filename TEXT, source_kind TEXT NOT NULL DEFAULT 'path',
|
||||
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,
|
||||
@@ -58,6 +59,10 @@ class Store:
|
||||
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")
|
||||
if "filename" not in columns:
|
||||
db.execute("ALTER TABLE jobs ADD COLUMN filename TEXT")
|
||||
if "source_kind" not in columns:
|
||||
db.execute("ALTER TABLE jobs ADD COLUMN source_kind TEXT NOT NULL DEFAULT 'path'")
|
||||
|
||||
@contextmanager
|
||||
def tx(self):
|
||||
@@ -77,21 +82,26 @@ class Store:
|
||||
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):
|
||||
batch_id: str | None, max_queued: int, filename: str | None = None,
|
||||
source_kind: str = "path"):
|
||||
now = time.time()
|
||||
filename = filename or Path(file_path).name
|
||||
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):
|
||||
if (prior["file_path"], prior["callback_url"], prior["batch_id"],
|
||||
prior["filename"]) != (file_path, callback_url, batch_id, filename):
|
||||
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))
|
||||
db.execute("""INSERT INTO jobs(id,request_id,file_path,callback_url,batch_id,filename,
|
||||
source_kind,status,created_at,updated_at)
|
||||
VALUES(?,?,?,?,?,?,?,'queued',?,?)""",
|
||||
(job_id, request_id, file_path, callback_url, batch_id, filename,
|
||||
source_kind, now, now))
|
||||
return self.as_dict(db.execute("SELECT * FROM jobs WHERE id=?", (job_id,)).fetchone()), True
|
||||
|
||||
def get_job(self, job_id: str):
|
||||
@@ -107,6 +117,13 @@ class Store:
|
||||
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 upload_in_use(self, file_path: str, exclude_job_id: str) -> bool:
|
||||
"""Một upload được dedupe theo sha256 nên nhiều job có thể trỏ vào cùng file."""
|
||||
with self.connect() as db:
|
||||
return db.execute("""SELECT count(*) FROM jobs WHERE file_path=? AND id<>?
|
||||
AND status IN ('queued','preparing','processing','finalizing')""",
|
||||
(file_path, exclude_job_id)).fetchone()[0] > 0
|
||||
|
||||
def claim_prepare(self, lease_seconds: int):
|
||||
now = time.time()
|
||||
with self.tx() as db:
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
"""Render one page, call Chandra, and reject incomplete model output."""
|
||||
import base64
|
||||
import html
|
||||
import json
|
||||
import re
|
||||
from pathlib import Path
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
@@ -57,7 +59,39 @@ def validate_response(response: dict) -> list[dict]:
|
||||
return blocks
|
||||
|
||||
|
||||
def extract_text_blocks(pdf_path: Path, page_no: int) -> dict:
|
||||
"""Backend không cần GPU: lấy block văn bản sẵn có trong PDF số hoá.
|
||||
|
||||
Chỉ dùng để chạy thử service khi chưa serve được model; nhãn luôn là
|
||||
Paragraph nên outline sẽ không có section. Trang không có text trả về một
|
||||
block Image phủ toàn trang.
|
||||
"""
|
||||
with pymupdf.open(pdf_path) as doc:
|
||||
page = doc[page_no - 1]
|
||||
rect = page.rect
|
||||
pixels = (rect * pymupdf.Matrix(200 / 72, 200 / 72)).irect
|
||||
blocks = []
|
||||
for x0, y0, x1, y1, text, *_ in page.get_text("blocks"):
|
||||
text = re.sub(r"\s*\n\s*", " ", text).strip()
|
||||
if not text:
|
||||
continue
|
||||
box = [round(1000 * (x0 - rect.x0) / rect.width), round(1000 * (y0 - rect.y0) / rect.height),
|
||||
round(1000 * (x1 - rect.x0) / rect.width), round(1000 * (y1 - rect.y0) / rect.height)]
|
||||
box = [min(1000, max(0, value)) for value in box]
|
||||
if box[0] >= box[2] or box[1] >= box[3]:
|
||||
continue
|
||||
blocks.append({"label": "Paragraph", "bbox": box,
|
||||
"html": f"<p>{html.escape(text)}</p>"})
|
||||
return {"width": pixels.width, "height": pixels.height,
|
||||
"blocks": blocks or [{"label": "Image", "bbox": [0, 0, 1000, 1000],
|
||||
"html": "<p>[no extractable text]</p>"}]}
|
||||
|
||||
|
||||
def infer_page(settings: Settings, pdf_path: Path, page_no: int, *, penalize_repetition: bool = False) -> dict:
|
||||
if settings.ocr_backend == "pdf_text":
|
||||
return extract_text_blocks(pdf_path, page_no)
|
||||
if settings.ocr_backend != "http":
|
||||
raise ValueError(f"Unknown IDP_OCR_BACKEND: {settings.ocr_backend}")
|
||||
image, width, height = render_page(pdf_path, page_no)
|
||||
data_url = "data:image/png;base64," + base64.b64encode(image).decode("ascii")
|
||||
payload = {
|
||||
|
||||
@@ -6,6 +6,7 @@ import shutil
|
||||
import signal
|
||||
import threading
|
||||
import time
|
||||
from dataclasses import replace
|
||||
from pathlib import Path
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
@@ -30,10 +31,21 @@ class Worker:
|
||||
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"
|
||||
@@ -41,7 +53,8 @@ class Worker:
|
||||
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)
|
||||
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:
|
||||
@@ -53,6 +66,8 @@ class Worker:
|
||||
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"]
|
||||
@@ -99,7 +114,8 @@ class Worker:
|
||||
bundle = {
|
||||
"schema": "dla-document-bundle", "version": "1.0",
|
||||
"document_id": document_id,
|
||||
"source": {"filename": Path(job["file_path"]).name, "media_type": "application/pdf",
|
||||
"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,
|
||||
}
|
||||
@@ -107,6 +123,7 @@ class Worker:
|
||||
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)
|
||||
self.cleanup_source(job)
|
||||
log.info("Finalized %s for callback", job_id)
|
||||
except Exception as exc:
|
||||
log.exception("Finalization failed for %s", job_id)
|
||||
|
||||
Reference in New Issue
Block a user