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>
182 lines
7.7 KiB
Python
182 lines
7.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
|
|
|
|
|
|
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
|
|
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", "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"}
|
|
|
|
@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),
|
|
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")
|
|
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)
|
|
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}/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()
|