Files
parsing-service/idp_service/api.py
VinhNT de967a64c2 Bóc 7 trường cơ bản của văn bản sau khi OCR xong
Thêm bước KIE một lượt cho cả tài liệu, chạy sau khi mọi trang đã OCR và trước
khi finalize: document_type, document_number, issued_date, issuing_authority,
title, signer.name, signer.position.

- Prompt trong idp_service/kie.py giống từng byte template lượt 2 của
  IDP-Training-Pipeline (kie_prompts/extract_vi.txt) nên model KIE fine-tune gặp
  đúng định dạng đã train; khác ở chỗ schema cố định, không qua lượt GLM đề xuất
  schema. Quy ước riêng của từng trường nằm trong description của trường đó.
- Kết quả nằm ở "extraction" trong bundle, ở GET /jobs/{id}/extraction và trong
  output.extraction của callback, cạnh ảnh từng trang.
- Bóc trường hỏng không làm hỏng job: fields giữ đủ khoá với giá trị null,
  status là failed/skipped kèm lý do, trạng thái job vẫn do OCR quyết định.
- Bước extract dùng chung hàng đợi và giới hạn IDP_OCR_WORKERS với OCR từng
  trang nên không làm quá tải GPU; retry riêng theo IDP_MAX_KIE_ATTEMPTS.
- Tài liệu dài hơn IDP_KIE_MAX_PAGES chỉ gửi các trang đầu và trang cuối vì
  người ký nằm ở cuối văn bản.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 07:52:41 +00:00

197 lines
8.7 KiB
Python

"""HTTP API. Start with: uvicorn idp_service.api:app --host 0.0.0.0 --port 8080"""
import hashlib
import hmac
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, 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
from .kie import SCHEMA_NAME, empty_answer
CHUNK = 1024 * 1024
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
dag_run_id: str | None = Field(default=None, min_length=1, max_length=250)
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)
@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", "dag_run_id", "batch_id", "status", "file_path", "filename", "source_kind",
"total_pages", "completed_pages", "failed_pages", "error", "extract_status",
"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"}
@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("/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),
dag_run_id: str | None = Form(default=None, min_length=1, max_length=250),
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", dag_run_id)
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")
check_callback(request.callback_url)
try:
job, created = store.create_job(str(request.request_id), request.file_path,
request.callback_url, request.batch_id,
settings.max_queued_jobs, dag_run_id=request.dag_run_id)
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
return accepted(job, created, response)
@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}/extraction", dependencies=[Depends(authorize)])
def job_extraction(job_id: str):
"""Chỉ các trường đã bóc; có ngay khi bước extract xong, không cần đợi finalize."""
job = store.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
if job["extract_status"] in ("pending", "running"):
raise HTTPException(status_code=409, detail="Extraction is not ready")
return {"job_id": job_id, "schema": SCHEMA_NAME, "status": job["extract_status"],
"fields": json.loads(job["extract_json"]) if job["extract_json"] else empty_answer(),
"error": job["extract_error"]}
@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()