This commit is contained in:
2026-09-24 14:27:43 +07:00
parent e9d7c6d391
commit 79b70bed12
6 changed files with 83 additions and 11 deletions

1
.gitignore vendored
View File

@@ -8,3 +8,4 @@ idp_parsing_service.egg-info/
build/ build/
chandra-dla-api-v2-20260906-024126.tar chandra-dla-api-v2-20260906-024126.tar
hdfs-kbr.zip hdfs-kbr.zip
.env

View File

@@ -161,6 +161,8 @@ Khi đặt `IDP_API_KEY`, mọi endpoint job cần header `X-API-Key`.
| `KRB5_CONFIG` | `native-hdfs/conf/krb5.conf` | Đường dẫn cấu hình Kerberos | | `KRB5_CONFIG` | `native-hdfs/conf/krb5.conf` | Đường dẫn cấu hình Kerberos |
| `IDP_API_KEY` | rỗng | Khóa API; **bắt buộc cấu hình khi mở API ra mạng** | | `IDP_API_KEY` | rỗng | Khóa API; **bắt buộc cấu hình khi mở API ra mạng** |
| `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_CALLBACK_BASIC_USER` | rỗng | Username Basic Auth khi worker gọi callback |
| `IDP_CALLBACK_BASIC_PASSWORD` | rỗng | Password Basic Auth khi worker gọi callback |
| `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_OCR_BACKEND` | `http` | `http` gọi model; `pdf_text` dựng bundle từ text layer, chỉ để chạy thử |
@@ -169,6 +171,7 @@ Khi đặt `IDP_API_KEY`, mọi endpoint job cần header `X-API-Key`.
| `IDP_KIE_MODEL` | theo `IDP_OCR_MODEL` | Tên model KIE | | `IDP_KIE_MODEL` | theo `IDP_OCR_MODEL` | Tên model KIE |
| `IDP_KIE_MAX_PAGES` | `5` | Số ảnh tối đa gửi một lượt KIE; quá thì lấy các trang đầu và trang cuối | | `IDP_KIE_MAX_PAGES` | `5` | Số ảnh tối đa gửi một lượt KIE; quá thì lấy các trang đầu và trang cuối |
| `IDP_KIE_TIMEOUT` | `300` | Timeout một lượt KIE, giây | | `IDP_KIE_TIMEOUT` | `300` | Timeout một lượt KIE, giây |
| `IDP_KIE_MAX_TOKENS` | `2048` | Giới hạn số token đầu ra của mỗi request KIE; độc lập với `--max-model-len` của vLLM |
| `IDP_MAX_KIE_ATTEMPTS` | `3` | Số lần thử bóc trường mỗi tài liệu | | `IDP_MAX_KIE_ATTEMPTS` | `3` | Số lần thử bóc trường mỗi tài liệu |
| `IDP_RUN_WORKER` | `0` | `1` chạy worker ngay trong process API | | `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 |
@@ -250,6 +253,12 @@ Callback gửi `{ "dag_run_id": "...", "conf": { "request_id": "...", "job_id":
header `Idempotency-Key: job_id`. Nếu không truyền `dag_run_id`, service dùng header `Idempotency-Key: job_id`. Nếu không truyền `dag_run_id`, service dùng
`job_id` làm giá trị ổn định khi retry. Callback được retry độc lập với OCR, tối đa `job_id` làm giá trị ổn định khi retry. Callback được retry độc lập với OCR, tối đa
`IDP_MAX_CALLBACK_ATTEMPTS` lần; Airflow nên xử lý callback lặp idempotently. `IDP_MAX_CALLBACK_ATTEMPTS` lần; Airflow nên xử lý callback lặp idempotently.
Nếu Airflow trả `409` vì DAG run đã tồn tại, worker gọi GET DAG run đó và chỉ
đánh dấu callback đã giao khi `dag_run_id`, `job_id` và `request_id` đều khớp.
Xung đột với job khác vẫn được ghi là lỗi callback.
Nếu Airflow yêu cầu Basic Auth, đặt cả `IDP_CALLBACK_BASIC_USER` và
`IDP_CALLBACK_BASIC_PASSWORD` trong `.env` của API/worker; worker gửi header
`Authorization: Basic ...` cùng request callback.
Trạng thái `callback_state=exhausted` cho biết cần xử lý thủ công; bundle vẫn Trạng thái `callback_state=exhausted` cho biết cần xử lý thủ công; bundle vẫn
đọc được qua `GET /jobs/{job_id}/result`. đọc được qua `GET /jobs/{job_id}/result`.

View File

@@ -11,6 +11,8 @@ class Settings:
hdfs_native_uri: str = os.getenv("IDP_HDFS_NATIVE_URI", "") hdfs_native_uri: str = os.getenv("IDP_HDFS_NATIVE_URI", "")
api_key: str = os.getenv("IDP_API_KEY", "") api_key: str = os.getenv("IDP_API_KEY", "")
callback_hosts: str = os.getenv("IDP_CALLBACK_HOSTS", "") callback_hosts: str = os.getenv("IDP_CALLBACK_HOSTS", "")
callback_basic_user: str = os.getenv("IDP_CALLBACK_BASIC_USER", "")
callback_basic_password: str = os.getenv("IDP_CALLBACK_BASIC_PASSWORD", "")
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 ocr_backend: str = os.getenv("IDP_OCR_BACKEND", "http") # http hoặc pdf_text
@@ -19,6 +21,7 @@ class Settings:
kie_model: str = os.getenv("IDP_KIE_MODEL") or os.getenv("IDP_OCR_MODEL", "chandra") kie_model: str = os.getenv("IDP_KIE_MODEL") or os.getenv("IDP_OCR_MODEL", "chandra")
kie_max_pages: int = int(os.getenv("IDP_KIE_MAX_PAGES", "5")) kie_max_pages: int = int(os.getenv("IDP_KIE_MAX_PAGES", "5"))
kie_timeout: int = int(os.getenv("IDP_KIE_TIMEOUT", "300")) kie_timeout: int = int(os.getenv("IDP_KIE_TIMEOUT", "300"))
kie_max_tokens: int = int(os.getenv("IDP_KIE_MAX_TOKENS", "2048"))
max_kie_attempts: int = int(os.getenv("IDP_MAX_KIE_ATTEMPTS", "3")) max_kie_attempts: int = int(os.getenv("IDP_MAX_KIE_ATTEMPTS", "3"))
run_worker: bool = os.getenv("IDP_RUN_WORKER", "0").lower() in ("1", "true", "yes") 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"))

View File

@@ -140,7 +140,7 @@ def extract_document(settings: Settings, pdf_path: Path, page_count: int) -> dic
payload = { payload = {
"model": settings.kie_model, "model": settings.kie_model,
"messages": [{"role": "user", "content": content}], "messages": [{"role": "user", "content": content}],
"max_tokens": 2048, "max_tokens": settings.kie_max_tokens,
"temperature": 0.0, "temperature": 0.0,
"top_p": 0.1, "top_p": 0.1,
} }

View File

@@ -9,6 +9,8 @@ import threading
import time import time
from dataclasses import replace from dataclasses import replace
from pathlib import Path from pathlib import Path
from urllib.error import HTTPError
from urllib.parse import quote, urlsplit, urlunsplit
from urllib.request import Request, urlopen from urllib.request import Request, urlopen
import pymupdf import pymupdf
@@ -35,6 +37,8 @@ class Worker:
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"): if settings.ocr_backend not in ("http", "pdf_text"):
raise ValueError("IDP_OCR_BACKEND must be http or pdf_text") raise ValueError("IDP_OCR_BACKEND must be http or pdf_text")
if bool(settings.callback_basic_user) != bool(settings.callback_basic_password):
raise ValueError("Set both IDP_CALLBACK_BASIC_USER and IDP_CALLBACK_BASIC_PASSWORD")
if settings.ocr_backend == "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") log.warning("IDP_OCR_BACKEND=pdf_text: bundle dựng từ text layer của PDF, không gọi model")
@@ -179,12 +183,20 @@ class Worker:
}, },
}, },
} }
headers = {"Content-Type": "application/json", "Idempotency-Key": job["id"]}
if self.settings.callback_basic_user:
credentials = f"{self.settings.callback_basic_user}:{self.settings.callback_basic_password}"
headers["Authorization"] = "Basic " + base64.b64encode(credentials.encode("utf-8")).decode("ascii")
request = Request(job["callback_url"], data=json.dumps(payload).encode("utf-8"), request = Request(job["callback_url"], data=json.dumps(payload).encode("utf-8"),
headers={"Content-Type": "application/json", headers=headers, method="POST")
"Idempotency-Key": job["id"]}, method="POST") try:
with urlopen(request, timeout=10) as response: with urlopen(request, timeout=10) as response:
if not 200 <= response.status < 300: if not 200 <= response.status < 300:
raise RuntimeError(f"Callback HTTP {response.status}") raise RuntimeError(f"Callback HTTP {response.status}")
except HTTPError as exc:
if exc.code != 409 or not self.airflow_run_matches(job["callback_url"], payload, headers):
raise
log.info("Airflow DAG run already exists for %s; callback confirmed", job["id"])
self.store.callback_done(job["id"], job["callback_attempts"]) self.store.callback_done(job["id"], job["callback_attempts"])
shutil.rmtree(self.job_dir(job["id"]), ignore_errors=True) shutil.rmtree(self.job_dir(job["id"]), ignore_errors=True)
except Exception as exc: except Exception as exc:
@@ -194,6 +206,25 @@ class Worker:
if job["callback_attempts"] >= self.settings.max_callback_attempts: if job["callback_attempts"] >= self.settings.max_callback_attempts:
shutil.rmtree(self.job_dir(job["id"]), ignore_errors=True) shutil.rmtree(self.job_dir(job["id"]), ignore_errors=True)
@staticmethod
def airflow_run_matches(callback_url: str, payload: dict, headers: dict) -> bool:
"""A 409 confirms delivery only when Airflow has this same job's DAG run."""
parsed = urlsplit(callback_url)
path = parsed.path.rstrip("/")
segments = path.split("/")
if len(segments) != 6 or segments[:4] != ["", "api", "v1", "dags"] or segments[5] != "dagRuns":
return False
run_url = urlunsplit((parsed.scheme, parsed.netloc,
path + "/" + quote(payload["dag_run_id"], safe=""), "", ""))
get_headers = {"Authorization": headers["Authorization"]} if "Authorization" in headers else {}
with urlopen(Request(run_url, headers=get_headers, method="GET"), timeout=10) as response:
existing = json.load(response)
conf = existing.get("conf") or {}
expected = payload["conf"]
return (existing.get("dag_run_id") == payload["dag_run_id"]
and conf.get("job_id") == expected["job_id"]
and conf.get("request_id") == expected["request_id"])
def coordinator_once(self) -> bool: def coordinator_once(self) -> bool:
did_work = False did_work = False
job = self.store.claim_prepare(self.settings.lease_seconds) job = self.store.claim_prepare(self.settings.lease_seconds)

View File

@@ -230,7 +230,8 @@ def test_extract_fixed_schema_end_to_end_and_callback(tmp_path):
thread.start() thread.start()
try: try:
url = f"http://127.0.0.1:{server.server_port}/v1/chat/completions" url = f"http://127.0.0.1:{server.server_port}/v1/chat/completions"
settings = replace(settings_for(tmp_path), ocr_url=url, kie_enabled=True, kie_url=url) settings = replace(settings_for(tmp_path), ocr_url=url, kie_enabled=True, kie_url=url,
kie_max_tokens=4096)
source = tmp_path / "quyet-dinh.pdf" source = tmp_path / "quyet-dinh.pdf"
make_pdf(source, count=2) make_pdf(source, count=2)
app = create_app(settings) app = create_app(settings)
@@ -246,6 +247,7 @@ def test_extract_fixed_schema_end_to_end_and_callback(tmp_path):
assert len(kie_requests) == 1 assert len(kie_requests) == 1
assert len(kie_requests[0]["messages"][0]["content"]) == 3 assert len(kie_requests[0]["messages"][0]["content"]) == 3
assert kie_requests[0]["model"] == settings.kie_model assert kie_requests[0]["model"] == settings.kie_model
assert kie_requests[0]["max_tokens"] == 4096
extraction = client.get(f"/jobs/{job_id}/extraction").json() extraction = client.get(f"/jobs/{job_id}/extraction").json()
assert extraction["status"] == "done" assert extraction["status"] == "done"
@@ -359,6 +361,7 @@ def test_rejects_truncated_plain_text_and_invalid_bbox():
def test_real_http_ocr_and_callback(tmp_path): def test_real_http_ocr_and_callback(tmp_path):
callbacks = [] callbacks = []
auth_headers = []
class Handler(BaseHTTPRequestHandler): class Handler(BaseHTTPRequestHandler):
def do_POST(self): def do_POST(self):
@@ -370,8 +373,20 @@ def test_real_http_ocr_and_callback(tmp_path):
'<div data-label="Paragraph" data-bbox="1 1 500 500">Test</div>'}}]} '<div data-label="Paragraph" data-bbox="1 1 500 500">Test</div>'}}]}
else: else:
callbacks.append(body) callbacks.append(body)
answer = {"ok": True} auth_headers.append(self.headers.get("Authorization"))
answer = {"detail": "DAG Run already exists"}
data = json.dumps(answer).encode() data = json.dumps(answer).encode()
self.send_response(200 if self.path == "/v1/chat/completions" else 409)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
def do_GET(self):
assert self.path == "/api/v1/dags/test/dagRuns/callback_test_001"
assert self.headers.get("Authorization") == auth_headers[0]
data = json.dumps({"dag_run_id": callbacks[0]["dag_run_id"],
"conf": callbacks[0]["conf"]}).encode()
self.send_response(200) self.send_response(200)
self.send_header("Content-Type", "application/json") self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(data))) self.send_header("Content-Length", str(len(data)))
@@ -386,18 +401,21 @@ def test_real_http_ocr_and_callback(tmp_path):
thread.start() thread.start()
try: try:
settings = replace(settings_for(tmp_path), settings = replace(settings_for(tmp_path),
ocr_url=f"http://127.0.0.1:{server.server_port}/v1/chat/completions") ocr_url=f"http://127.0.0.1:{server.server_port}/v1/chat/completions",
callback_basic_user="callback_handler",
callback_basic_password="callback_handler")
source = tmp_path / "input.pdf" source = tmp_path / "input.pdf"
make_pdf(source, count=1) make_pdf(source, count=1)
app = create_app(settings) app = create_app(settings)
with TestClient(app) as client: with TestClient(app) as client:
reply = client.post("/process", json={"request_id": str(uuid4()), "file_path": str(source), reply = client.post("/process", json={"request_id": str(uuid4()), "file_path": str(source),
"dag_run_id": "callback_test_001", "dag_run_id": "callback_test_001",
"callback_url": f"http://127.0.0.1:{server.server_port}/callback"}) "callback_url": f"http://127.0.0.1:{server.server_port}/api/v1/dags/test/dagRuns"})
assert reply.status_code == 202 assert reply.status_code == 202
drain(Worker(settings), settings) drain(Worker(settings), settings)
assert client.get(f"/jobs/{reply.json()['job_id']}").json()["callback_state"] == "delivered" assert client.get(f"/jobs/{reply.json()['job_id']}").json()["callback_state"] == "delivered"
assert callbacks[0]["dag_run_id"] == "callback_test_001" assert callbacks[0]["dag_run_id"] == "callback_test_001"
assert auth_headers == ["Basic " + base64.b64encode(b"callback_handler:callback_handler").decode("ascii")]
assert set(callbacks[0]) == {"dag_run_id", "conf"} assert set(callbacks[0]) == {"dag_run_id", "conf"}
conf = callbacks[0]["conf"] conf = callbacks[0]["conf"]
assert conf["request_id"] == reply.json()["request_id"] assert conf["request_id"] == reply.json()["request_id"]
@@ -410,6 +428,16 @@ def test_real_http_ocr_and_callback(tmp_path):
assert images[0]["page_no"] == 1 assert images[0]["page_no"] == 1
assert images[0]["media_type"] == "image/png" assert images[0]["media_type"] == "image/png"
assert base64.b64decode(images[0]["data_base64"]).startswith(b"\x89PNG\r\n\x1a\n") assert base64.b64decode(images[0]["data_base64"]).startswith(b"\x89PNG\r\n\x1a\n")
# Cùng dag_run_id nhưng job khác phải giữ lỗi 409, không đánh dấu delivered.
second = client.post("/process", json={"request_id": str(uuid4()), "file_path": str(source),
"dag_run_id": "callback_test_001",
"callback_url": f"http://127.0.0.1:{server.server_port}/api/v1/dags/test/dagRuns"})
assert second.status_code == 202
drain(Worker(settings), settings)
second_status = client.get(f"/jobs/{second.json()['job_id']}").json()
assert second_status["callback_state"] == "pending"
assert "409" in second_status["callback_error"]
finally: finally:
server.shutdown() server.shutdown()
server.server_close() server.server_close()