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:
2026-09-21 14:51:19 +00:00
parent 939e3bc8c1
commit c79ea9f05f
11 changed files with 343 additions and 31 deletions

View File

@@ -1,9 +1,20 @@
# IDP parsing service # IDP parsing service
Service nhận **một PDF mỗi request**. Airflow ghi file xong rồi gửi đường dẫn qua Service nhận **một PDF mỗi request** và luôn chạy bất đồng bộ: API trả `202` kèm
`POST /process`. API lưu job vào SQLite và trả `202`; worker lấy PDF, chia task `job_id` ngay, worker xử lý nền, client lấy JSON ở `GET /jobs/{job_id}/result`
theo trang, gọi Chandra, validate, lưu bundle vào job và callback. Nhiều PDF cùng hoặc nhận qua `callback_url`. Có hai cách nạp đầu vào:
dùng một hàng đợi trang và một giới hạn tổng số request OCR.
* `POST /parse` — upload thẳng file PDF bằng `multipart/form-data`.
* `POST /process` — Airflow ghi file lên HDFS xong rồi gửi đường dẫn (hợp đồng cũ).
Worker lấy PDF, chia task theo trang, gọi Chandra, validate, lưu bundle vào job
và callback. Nhiều PDF cùng dùng một hàng đợi trang và một giới hạn tổng số
request OCR.
Output là `dla-document-bundle` giống hệt file mẫu `dla_example_document.json`
(`schema`, `version`, `document_id`, `source`, `outline`, `pages[].blocks[]` với
`block_id`/`label`/`bbox` 0–1000/`html`/`outline_no`), thêm `status` và `error`
cho từng trang để biết trang nào lỗi khi job `partial_failed`.
Sau khi tải file, worker tự nhận diện PDF thường hoặc giải mã file VOffice bằng Sau khi tải file, worker tự nhận diện PDF thường hoặc giải mã file VOffice bằng
`DES/ECB/PKCS5Padding` tương thích với `VOfficeSecurity.jar`, rồi mới mở PDF. `DES/ECB/PKCS5Padding` tương thích với `VOfficeSecurity.jar`, rồi mới mở PDF.
@@ -19,6 +30,22 @@ IDP_STORAGE=local uv run uvicorn idp_service.api:app --host 127.0.0.1 --port 808
IDP_STORAGE=local uv run python -m idp_service.worker IDP_STORAGE=local uv run python -m idp_service.worker
``` ```
Khi chỉ chạy trên một host, đặt `IDP_RUN_WORKER=1` để worker chạy luôn trong
process API, khỏi cần terminal thứ hai.
Chưa serve được model thì đặt `IDP_OCR_BACKEND=pdf_text`: bundle được dựng từ
text layer sẵn có trong PDF số hoá, đúng schema nhưng nhãn luôn là `Paragraph`
nên không có section trong `outline`. Chỉ dùng để thử luồng service, không phải
kết quả DLA.
```bash
IDP_STORAGE=local IDP_RUN_WORKER=1 IDP_OCR_BACKEND=pdf_text \
uv run uvicorn idp_service.api:app --port 8080
curl -s -X POST http://127.0.0.1:8080/parse -F 'file=@input.pdf;type=application/pdf'
# {"request_id":"...","job_id":"job_...","status":"queued","result_url":"/jobs/job_.../result"}
curl -s http://127.0.0.1:8080/jobs/JOB_ID/result > out.json
```
`infer.py` là công cụ thử nghiệm độc lập và cần Pillow khi xử lý ảnh. Pillow `infer.py` là công cụ thử nghiệm độc lập và cần Pillow khi xử lý ảnh. Pillow
không nằm trong runtime của service PDF. không nằm trong runtime của service PDF.
@@ -59,7 +86,7 @@ python3.11 -m pip install --no-index --find-links runtime-wheels \
Wheel có native code (`PyMuPDF`, `PyCryptodome`, `pydantic-core`) nên phải tạo Wheel có native code (`PyMuPDF`, `PyCryptodome`, `pydantic-core`) nên phải tạo
lại bộ export nếu máy đích khác kiến trúc hoặc phiên bản Python. lại bộ export nếu máy đích khác kiến trúc hoặc phiên bản Python.
Gửi job sau khi PDF đã ghi xong: Gửi job từ đường dẫn HDFS sau khi PDF đã ghi xong:
```bash ```bash
curl -X POST http://127.0.0.1:8080/process \ curl -X POST http://127.0.0.1:8080/process \
@@ -82,6 +109,8 @@ Khi đặt `IDP_API_KEY`, mọi endpoint job cần header `X-API-Key`.
| `IDP_CALLBACK_HOSTS` | rỗng | Danh sách hostname callback được phép, cách nhau bằng dấu phẩy | | `IDP_CALLBACK_HOSTS` | rỗng | Danh sách hostname callback được phép, cách nhau bằng dấu phẩy |
| `IDP_OCR_URL` | `http://localhost:9222/v1/chat/completions` | API vLLM | | `IDP_OCR_URL` | `http://localhost:9222/v1/chat/completions` | API vLLM |
| `IDP_OCR_MODEL` | `chandra` | Tên model | | `IDP_OCR_MODEL` | `chandra` | Tên model |
| `IDP_OCR_BACKEND` | `http` | `http` gọi model; `pdf_text` dựng bundle từ text layer, chỉ để chạy thử |
| `IDP_RUN_WORKER` | `0` | `1` chạy worker ngay trong process API |
| `IDP_OCR_WORKERS` | `64` | Giới hạn tổng request tới GPU, lưu bằng SQLite | | `IDP_OCR_WORKERS` | `64` | Giới hạn tổng request tới GPU, lưu bằng SQLite |
| `IDP_OCR_TIMEOUT` | `180` | Timeout mỗi request OCR, giây | | `IDP_OCR_TIMEOUT` | `180` | Timeout mỗi request OCR, giây |
| `IDP_LEASE_SECONDS` | `1800` | Lease task; phải lớn hơn timeout và thời gian chuẩn bị/finalize | | `IDP_LEASE_SECONDS` | `1800` | Lease task; phải lớn hơn timeout và thời gian chuẩn bị/finalize |
@@ -104,6 +133,21 @@ không phải PDF làm bước `preparing` retry rồi chuyển job sang `failed
## Hợp đồng API và trạng thái ## Hợp đồng API và trạng thái
```
POST /parse
Content-Type: multipart/form-data
file=@input.pdf # bắt buộc, phần mở rộng .pdf
request_id=<uuid> # optional, mặc định service tự sinh
callback_url=<url> # optional
batch_id=<string> # optional
```
File upload được ghi xuống `IDP_DATA_DIR/uploads` theo sha256 nội dung nên gửi
lại đúng file cũ với cùng `request_id` trả về cùng `job_id`. File được xoá sau
khi job kết thúc và không còn job nào dùng tới. Quá `IDP_MAX_PDF_BYTES` trả
`413`, file rỗng hoặc không phải `.pdf` trả `422`.
```json ```json
POST /process POST /process
{ {
@@ -115,7 +159,7 @@ POST /process
} }
``` ```
`request_id` là idempotency key. Gửi lại cùng nội dung trả cùng `job_id`; Cả hai endpoint dùng `request_id` làm idempotency key. Gửi lại cùng nội dung trả cùng `job_id`;
gửi cùng key nhưng khác nội dung trả `409`. Queue đầy trả `429`. Các trạng thái gửi cùng key nhưng khác nội dung trả `409`. Queue đầy trả `429`. Các trạng thái
job: `queued`, `preparing`, `processing`, `finalizing`, `completed`, job: `queued`, `preparing`, `processing`, `finalizing`, `completed`,
`partial_failed`, `failed`. `GET /jobs/{job_id}` trả số trang thành công/lỗi; `partial_failed`, `failed`. `GET /jobs/{job_id}` trả số trang thành công/lỗi;
@@ -135,6 +179,7 @@ sau. Job chỉ `completed` khi mọi trang hợp lệ. Nếu còn trang lỗi sa
## Giới hạn hiện tại ## Giới hạn hiện tại
HDFS và Chandra chưa chạy ở môi trường này, nên bài test tự động dùng PDF local HDFS và Chandra chưa chạy ở môi trường này, nên bài test tự động dùng PDF local
và OCR giả lập. Chưa có số đo end to end của service. Mức 64 luồng lấy từ báo và OCR giả lập; luồng upload được kiểm end to end bằng `IDP_OCR_BACKEND=pdf_text`.
Chưa có số đo end to end của service với model thật. Mức 64 luồng lấy từ báo
cáo tải vLLM; cần đo lại cùng dữ liệu thật trước khi đặt SLO. Service chưa có cáo tải vLLM; cần đo lại cùng dữ liệu thật trước khi đặt SLO. Service chưa có
quy trình xóa lịch sử SQLite/kết quả; cần đặt thời hạn lưu theo yêu cầu vận hành. quy trình xóa lịch sử SQLite/kết quả; cần đặt thời hạn lưu theo yêu cầu vận hành.

View File

@@ -1,18 +1,26 @@
"""HTTP API. Start with: uvicorn idp_service.api:app --host 0.0.0.0 --port 8080""" """HTTP API. Start with: uvicorn idp_service.api:app --host 0.0.0.0 --port 8080"""
import hashlib
import hmac import hmac
from urllib.parse import urlparse
from uuid import UUID
import json 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 fastapi.responses import JSONResponse
from pydantic import BaseModel, Field from pydantic import BaseModel, Field
from starlette.concurrency import run_in_threadpool
from .config import Settings from .config import Settings
from .db import Store from .db import Store
CHUNK = 1024 * 1024
class ProcessRequest(BaseModel): class ProcessRequest(BaseModel):
request_id: UUID request_id: UUID
file_path: str = Field(min_length=1, max_length=2048) 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: def create_app(settings: Settings | None = None) -> FastAPI:
settings = settings or Settings() settings = settings or Settings()
store = Store(settings.db_path) 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)): 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): 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") 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: def public_job(job: dict) -> dict:
result = {key: job[key] for key in ( result = {key: job[key] for key in (
"id", "request_id", "batch_id", "status", "file_path", "total_pages", "id", "request_id", "batch_id", "status", "file_path", "filename", "source_kind",
"completed_pages", "failed_pages", "error", "total_pages", "completed_pages", "failed_pages", "error",
"callback_state", "callback_error", "created_at", "updated_at")} "callback_state", "callback_error", "created_at", "updated_at")}
result["result_available"] = job["result_json"] is not None result["result_available"] = job["result_json"] is not None
return result 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") @app.get("/healthz")
def healthz(): def healthz():
return {"status": "ok"} 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 raise HTTPException(status_code=503, detail="Job store unavailable") from exc
return {"status": "ready"} 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("/process", status_code=status.HTTP_202_ACCEPTED, dependencies=[Depends(authorize)])
@app.post("/jobs", 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): 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"): 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") raise HTTPException(status_code=422, detail="Only PDF input is supported")
if request.callback_url: check_callback(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: try:
job, created = store.create_job(str(request.request_id), request.file_path, job, created = store.create_job(str(request.request_id), request.file_path,
request.callback_url, request.batch_id, 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 raise HTTPException(status_code=409, detail=str(exc)) from exc
except OverflowError as exc: except OverflowError as exc:
raise HTTPException(status_code=429, detail=str(exc)) from exc raise HTTPException(status_code=429, detail=str(exc)) from exc
if not created: return accepted(job, created, response)
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)]) @app.get("/jobs/{job_id}", dependencies=[Depends(authorize)])
def job_status(job_id: str): def job_status(job_id: str):

View File

@@ -12,6 +12,8 @@ class Settings:
callback_hosts: str = os.getenv("IDP_CALLBACK_HOSTS", "") callback_hosts: str = os.getenv("IDP_CALLBACK_HOSTS", "")
ocr_url: str = os.getenv("IDP_OCR_URL", "http://localhost:9222/v1/chat/completions") ocr_url: str = os.getenv("IDP_OCR_URL", "http://localhost:9222/v1/chat/completions")
ocr_model: str = os.getenv("IDP_OCR_MODEL", "chandra") 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")) ocr_workers: int = int(os.getenv("IDP_OCR_WORKERS", "64"))
max_queued_jobs: int = int(os.getenv("IDP_MAX_QUEUED_JOBS", "1000")) 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_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")) lease_seconds: int = int(os.getenv("IDP_LEASE_SECONDS", "1800"))
poll_seconds: float = float(os.getenv("IDP_POLL_SECONDS", "0.5")) poll_seconds: float = float(os.getenv("IDP_POLL_SECONDS", "0.5"))
@property
def upload_dir(self) -> Path:
return self.data_dir / "uploads"
@property @property
def db_path(self) -> Path: def db_path(self) -> Path:
return self.data_dir / "jobs.sqlite3" return self.data_dir / "jobs.sqlite3"

View File

@@ -31,6 +31,7 @@ class Store:
CREATE TABLE IF NOT EXISTS jobs ( CREATE TABLE IF NOT EXISTS jobs (
id TEXT PRIMARY KEY, request_id TEXT NOT NULL UNIQUE, id TEXT PRIMARY KEY, request_id TEXT NOT NULL UNIQUE,
file_path TEXT NOT NULL, callback_url TEXT, batch_id TEXT, 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, status TEXT NOT NULL, created_at REAL NOT NULL, updated_at REAL NOT NULL,
total_pages INTEGER NOT NULL DEFAULT 0, total_pages INTEGER NOT NULL DEFAULT 0,
attempts 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)")} columns = {row[1] for row in db.execute("PRAGMA table_info(jobs)")}
if "result_json" not in columns: if "result_json" not in columns:
db.execute("ALTER TABLE jobs ADD COLUMN result_json TEXT") 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 @contextmanager
def tx(self): def tx(self):
@@ -77,21 +82,26 @@ class Store:
return dict(row) if row else None return dict(row) if row else None
def create_job(self, request_id: str, file_path: str, callback_url: str | 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() now = time.time()
filename = filename or Path(file_path).name
with self.tx() as db: with self.tx() as db:
prior = db.execute("SELECT * FROM jobs WHERE request_id=?", (request_id,)).fetchone() prior = db.execute("SELECT * FROM jobs WHERE request_id=?", (request_id,)).fetchone()
if prior: 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") raise ValueError("request_id already exists with different inputs")
return self.as_dict(prior), False return self.as_dict(prior), False
queued = db.execute("SELECT count(*) FROM jobs WHERE status IN ('queued','preparing','processing','finalizing')").fetchone()[0] queued = db.execute("SELECT count(*) FROM jobs WHERE status IN ('queued','preparing','processing','finalizing')").fetchone()[0]
if queued >= max_queued: if queued >= max_queued:
raise OverflowError("Job queue is full") raise OverflowError("Job queue is full")
job_id = "job_" + uuid4().hex job_id = "job_" + uuid4().hex
db.execute("""INSERT INTO jobs(id,request_id,file_path,callback_url,batch_id,status,created_at,updated_at) db.execute("""INSERT INTO jobs(id,request_id,file_path,callback_url,batch_id,filename,
VALUES(?,?,?,?,?,'queued',?,?)""", source_kind,status,created_at,updated_at)
(job_id, request_id, file_path, callback_url, batch_id, now, now)) 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 return self.as_dict(db.execute("SELECT * FROM jobs WHERE id=?", (job_id,)).fetchone()), True
def get_job(self, job_id: str): 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() 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] 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): def claim_prepare(self, lease_seconds: int):
now = time.time() now = time.time()
with self.tx() as db: with self.tx() as db:

View File

@@ -1,6 +1,8 @@
"""Render one page, call Chandra, and reject incomplete model output.""" """Render one page, call Chandra, and reject incomplete model output."""
import base64 import base64
import html
import json import json
import re
from pathlib import Path from pathlib import Path
from urllib.request import Request, urlopen from urllib.request import Request, urlopen
@@ -57,7 +59,39 @@ def validate_response(response: dict) -> list[dict]:
return blocks 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: 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) image, width, height = render_page(pdf_path, page_no)
data_url = "data:image/png;base64," + base64.b64encode(image).decode("ascii") data_url = "data:image/png;base64," + base64.b64encode(image).decode("ascii")
payload = { payload = {

View File

@@ -6,6 +6,7 @@ import shutil
import signal import signal
import threading import threading
import time import time
from dataclasses import replace
from pathlib import Path from pathlib import Path
from urllib.request import Request, urlopen from urllib.request import Request, urlopen
@@ -30,10 +31,21 @@ class Worker:
settings.work_dir.mkdir(parents=True, exist_ok=True) settings.work_dir.mkdir(parents=True, exist_ok=True)
if settings.ocr_workers < 1 or settings.lease_seconds <= settings.ocr_timeout: 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") 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: def job_dir(self, job_id: str) -> Path:
return self.settings.work_dir / job_id 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): def prepare(self, job: dict):
job_dir = self.job_dir(job["id"]) job_dir = self.job_dir(job["id"])
downloaded = job_dir / "downloaded.bin" downloaded = job_dir / "downloaded.bin"
@@ -41,7 +53,8 @@ class Worker:
try: try:
if job["attempts"] > self.settings.max_job_attempts: if job["attempts"] > self.settings.max_job_attempts:
raise ValueError("Preparation lease expired too many times") 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, decrypted = prepare_pdf(downloaded, source, self.settings.voffice_decrypt_mode,
self.settings.voffice_des_key_hex) self.settings.voffice_des_key_hex)
with pymupdf.open(source) as pdf: with pymupdf.open(source) as pdf:
@@ -53,6 +66,8 @@ class Worker:
except Exception as exc: except Exception as exc:
log.exception("Preparation failed for %s", job["id"]) log.exception("Preparation failed for %s", job["id"])
self.store.prepare_failed(job["id"], job["attempts"], str(exc), self.settings.max_job_attempts) 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): def process_page(self, page: dict):
job_id, page_no, attempts = page["job_id"], page["page_no"], page["attempts"] job_id, page_no, attempts = page["job_id"], page["page_no"], page["attempts"]
@@ -99,7 +114,8 @@ class Worker:
bundle = { bundle = {
"schema": "dla-document-bundle", "version": "1.0", "schema": "dla-document-bundle", "version": "1.0",
"document_id": document_id, "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}, "page_count": len(pages), "render_dpi": 200},
"outline": build_outline(pages), "pages": pages, "outline": build_outline(pages), "pages": pages,
} }
@@ -107,6 +123,7 @@ class Worker:
has_failures = any(p["status"] == "failed" for p in pages) has_failures = any(p["status"] == "failed" for p in pages)
if self.store.finalized(job_id, job["finalize_attempts"], result_json, has_failures): if self.store.finalized(job_id, job["finalize_attempts"], result_json, has_failures):
shutil.rmtree(self.job_dir(job_id), ignore_errors=True) shutil.rmtree(self.job_dir(job_id), ignore_errors=True)
self.cleanup_source(job)
log.info("Finalized %s for callback", job_id) log.info("Finalized %s for callback", job_id)
except Exception as exc: except Exception as exc:
log.exception("Finalization failed for %s", job_id) log.exception("Finalization failed for %s", job_id)

View File

@@ -1,5 +1,20 @@
## Cấu trúc Airflow → IDP ## Cấu trúc Airflow → IDP
### 0. Request: upload thẳng file PDF
```
POST /parse
Content-Type: multipart/form-data
file=@input.pdf
request_id=550e8400-e29b-41d4-a716-446655440000 # optional
callback_url=http://airflow-webserver:8080/... # optional
batch_id=... # optional
```
Trả `202` như mục 2, thêm `result_url` để lấy JSON. Dùng khi phía gọi có sẵn
file chứ không đẩy qua HDFS.
### 1. Request: Airflow → IDP ### 1. Request: Airflow → IDP
```json ```json
@@ -50,6 +65,8 @@ Content-Type: application/json
} }
``` ```
`output` là `dla-document-bundle`, cùng schema với `GET /jobs/{job_id}/result`.
--- ---
### 4. Mã lỗi ### 4. Mã lỗi

View File

@@ -1,10 +1,11 @@
[project] [project]
name = "idp-parsing-service" name = "idp-parsing-service"
version = "0.1.0" version = "0.2.0"
requires-python = ">=3.11" requires-python = ">=3.11"
dependencies = [ dependencies = [
"fastapi>=0.115,<1", "fastapi>=0.115,<1",
"uvicorn>=0.30,<1", "uvicorn>=0.30,<1",
"python-multipart>=0.0.9,<1",
"pymupdf>=1.24,<2", "pymupdf>=1.24,<2",
"pycryptodome>=3.20,<4", "pycryptodome>=3.20,<4",
] ]

View File

@@ -30,6 +30,8 @@ pydantic-core==2.46.5
# via pydantic # via pydantic
pymupdf==1.28.2 pymupdf==1.28.2
# via idp-parsing-service # via idp-parsing-service
python-multipart==0.0.32
# via idp-parsing-service
requests==2.34.2 requests==2.34.2
# via hdfs # via hdfs
six==1.17.0 six==1.17.0

View File

@@ -68,6 +68,75 @@ def test_api_idempotency_and_end_to_end(tmp_path, monkeypatch):
assert all(page["status"] == "done" for page in bundle["pages"]) assert all(page["status"] == "done" for page in bundle["pages"])
def drain(worker, settings):
"""Chạy hết job đang chờ: prepare, mọi trang, rồi finalize."""
assert worker.coordinator_once()
while True:
page = worker.store.claim_page(settings.lease_seconds, settings.ocr_workers)
if not page:
break
worker.process_page(page)
assert worker.coordinator_once()
def test_upload_pdf_returns_bundle_without_gpu(tmp_path):
settings = replace(settings_for(tmp_path), ocr_backend="pdf_text")
source = tmp_path / "Giấy chứng nhận.pdf"
make_pdf(source, count=2)
app = create_app(settings)
with TestClient(app) as client:
with source.open("rb") as handle:
reply = client.post("/parse", files={"file": (source.name, handle, "application/pdf")})
assert reply.status_code == 202
job_id = reply.json()["job_id"]
assert reply.json()["result_url"] == f"/jobs/{job_id}/result"
assert client.get(f"/jobs/{job_id}/result").status_code == 409
drain(Worker(settings), settings)
assert client.get(f"/jobs/{job_id}").json()["status"] == "completed"
bundle = client.get(f"/jobs/{job_id}/result").json()
assert bundle["schema"] == "dla-document-bundle"
assert bundle["source"] == {"filename": "Giấy chứng nhận.pdf", "media_type": "application/pdf",
"page_count": 2, "render_dpi": 200}
assert bundle["document_id"].startswith("doc_")
page = bundle["pages"][0]
assert page["page_id"] == f"{bundle['document_id']}/p001"
assert page["width"] > 0 and page["height"] > 0
block = page["blocks"][0]
assert block["block_id"] == f"{page['page_id']}/b000"
assert block["label"] in {"Paragraph", "Image"}
assert all(0 <= value <= 1000 for value in block["bbox"])
assert block["outline_no"] == "0.1"
assert bundle["outline"][0]["block_ids"][0] == block["block_id"]
# Upload đã dedupe theo sha256 được dọn sau khi finalize.
assert list(settings.upload_dir.glob("*.pdf")) == []
def test_upload_rejects_non_pdf_and_replays_same_request_id(tmp_path):
settings = settings_for(tmp_path)
source = tmp_path / "input.pdf"
make_pdf(source, count=1)
request_id = str(uuid4())
app = create_app(settings)
with TestClient(app) as client:
assert client.post("/parse", files={"file": ("note.txt", b"hello", "text/plain")}).status_code == 422
assert client.post("/parse", files={"file": ("empty.pdf", b"", "application/pdf")}).status_code == 422
content = source.read_bytes()
first = client.post("/parse", files={"file": ("input.pdf", content, "application/pdf")},
data={"request_id": request_id})
second = client.post("/parse", files={"file": ("input.pdf", content, "application/pdf")},
data={"request_id": request_id})
assert second.json()["job_id"] == first.json()["job_id"]
assert second.headers["X-Idempotent-Replay"] == "true"
conflict = client.post("/parse", files={"file": ("other.pdf", content, "application/pdf")},
data={"request_id": request_id})
assert conflict.status_code == 409
# Job đầu vẫn giữ được file của nó sau khi request xung đột bị từ chối.
assert len(list(settings.upload_dir.glob("*.pdf"))) == 1
def test_page_retry_then_partial_failure(tmp_path, monkeypatch): def test_page_retry_then_partial_failure(tmp_path, monkeypatch):
settings = replace(settings_for(tmp_path), max_page_attempts=2) settings = replace(settings_for(tmp_path), max_page_attempts=2)
source = tmp_path / "bad.pdf" source = tmp_path / "bad.pdf"
@@ -96,6 +165,19 @@ def test_page_retry_then_partial_failure(tmp_path, monkeypatch):
assert bundle["pages"][0]["status"] == "failed" assert bundle["pages"][0]["status"] == "failed"
def test_pdf_text_backend_labels_pages_without_text(tmp_path):
from idp_service.ocr import extract_text_blocks
blank = tmp_path / "blank.pdf"
document = pymupdf.open()
document.new_page()
document.save(blank)
document.close()
result = extract_text_blocks(blank, 1)
assert result["blocks"] == [{"label": "Image", "bbox": [0, 0, 1000, 1000],
"html": "<p>[no extractable text]</p>"}]
def test_rejects_truncated_plain_text_and_invalid_bbox(): def test_rejects_truncated_plain_text_and_invalid_bbox():
def response(content, finish="stop"): def response(content, finish="stop"):
return {"choices": [{"finish_reason": finish, "message": {"content": content}}]} return {"choices": [{"finish_reason": finish, "message": {"content": content}}]}

13
uv.lock generated
View File

@@ -288,12 +288,13 @@ wheels = [
[[package]] [[package]]
name = "idp-parsing-service" name = "idp-parsing-service"
version = "0.1.0" version = "0.2.0"
source = { editable = "." } source = { editable = "." }
dependencies = [ dependencies = [
{ name = "fastapi" }, { name = "fastapi" },
{ name = "pycryptodome" }, { name = "pycryptodome" },
{ name = "pymupdf" }, { name = "pymupdf" },
{ name = "python-multipart" },
{ name = "uvicorn" }, { name = "uvicorn" },
] ]
@@ -314,6 +315,7 @@ requires-dist = [
{ name = "pycryptodome", specifier = ">=3.20,<4" }, { name = "pycryptodome", specifier = ">=3.20,<4" },
{ name = "pymupdf", specifier = ">=1.24,<2" }, { name = "pymupdf", specifier = ">=1.24,<2" },
{ name = "pytest", marker = "extra == 'test'", specifier = ">=8,<10" }, { name = "pytest", marker = "extra == 'test'", specifier = ">=8,<10" },
{ name = "python-multipart", specifier = ">=0.0.9,<1" },
{ name = "uvicorn", specifier = ">=0.30,<1" }, { name = "uvicorn", specifier = ">=0.30,<1" },
] ]
provides-extras = ["test", "hdfs"] provides-extras = ["test", "hdfs"]
@@ -535,6 +537,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/24/25/1de2678b631f5a49215c6c96fff41ba892b0a34df68d6d80292b1b48aa7f/pytest-9.1.1-py3-none-any.whl", hash = "sha256:37a86b45efb9a47a61a36449063e8e18d0cab3161329fc099eb21783169c4f0c", size = 386536, upload-time = "2026-06-19T10:58:31.347Z" }, { url = "https://files.pythonhosted.org/packages/24/25/1de2678b631f5a49215c6c96fff41ba892b0a34df68d6d80292b1b48aa7f/pytest-9.1.1-py3-none-any.whl", hash = "sha256:37a86b45efb9a47a61a36449063e8e18d0cab3161329fc099eb21783169c4f0c", size = 386536, upload-time = "2026-06-19T10:58:31.347Z" },
] ]
[[package]]
name = "python-multipart"
version = "0.0.32"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/5b/42/55c32bb9b12693c092ad250a0e82edb5b31ddeda6eb772de5f308b3804ad/python_multipart-0.0.32.tar.gz", hash = "sha256:be54b7f3fa167bb83e4fcd936b887b708f4e57fe75911c02aebf53efaf8d938e", size = 46881, upload-time = "2026-06-04T16:18:58.647Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/e1/04/e8135ebd1ad02c56ec633277529b2602ff99ff634be76cdba5744cf554fd/python_multipart-0.0.32-py3-none-any.whl", hash = "sha256:ff6d3f776f16878c894e52e107296ffc890e913c611b1a4ec6c44e2821fe2e23", size = 30042, upload-time = "2026-06-04T16:18:57.319Z" },
]
[[package]] [[package]]
name = "requests" name = "requests"
version = "2.34.2" version = "2.34.2"