feat/kie-extraction #1

Merged
annt839 merged 3 commits from feat/kie-extraction into main 2026-09-24 08:17:45 +00:00
10 changed files with 622 additions and 48 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

@@ -14,7 +14,57 @@ request OCR.
Output là `dla-document-bundle` giống hệt file mẫu `dla_example_document.json` 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 (`schema`, `version`, `document_id`, `source`, `outline`, `pages[].blocks[]` với
`block_id`/`label`/`bbox` 0–1000/`html`/`outline_no`), thêm `status` và `error` `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`. cho từng trang để biết trang nào lỗi khi job `partial_failed`, và khối
`extraction` chứa các trường đã bóc.
## Bóc trường (KIE)
Sau khi mọi trang OCR xong, worker gọi model thêm **một lượt cho cả tài liệu** để
bóc các trường cố định dưới đây, rồi mới finalize:
| Trường | Ý nghĩa |
|---|---|
| `document_type` | Loại văn bản |
| `document_number` | Số, ký hiệu văn bản |
| `issued_date` | Ngày ban hành, định dạng `dd/mm/yyyy` |
| `issuing_authority` | Cơ quan ban hành |
| `title` | Tên/trích yếu văn bản |
| `signer.name` | Họ tên người ký |
| `signer.position` | Chức vụ người ký |
Prompt nằm trong `idp_service/kie.py`, giống từng byte template lượt 2 của
`IDP-Training-Pipeline/scripts/data/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. Muốn đổi trường hoặc quy ước của một trường thì sửa `SCHEMA`
trong file đó; quy ước riêng (bỏ nhãn "Số:", định dạng ngày...) nằm trong
`description` của chính trường đó, đúng như quy ước của template.
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; ví dụ tài liệu 20 trang gửi trang 1–4 và 20.
Kết quả nằm ở `extraction` trong bundle và ở `GET /jobs/{job_id}/extraction`
(có ngay sau bước extract, không phải đợi finalize):
```json
{
"schema": "basic-document-v1",
"status": "done",
"fields": {
"document_type": "QUYẾT ĐỊNH",
"document_number": "123/QĐ-UBND",
"issued_date": "09/09/2026",
"issuing_authority": "ỦY BAN NHÂN DÂN TỈNH BẮC NINH",
"title": "Về việc phê duyệt quy hoạch",
"signer": {"name": "Nguyễn Văn A", "position": "KT. CHỦ TỊCH"}
},
"error": null
}
```
`status` là `done`, `failed` (hết lượt thử, `error` ghi lý do) hoặc `skipped`
(tắt bằng `IDP_KIE_ENABLED=0`, hoặc đang chạy `IDP_OCR_BACKEND=pdf_text`). Bóc
trường hỏng **không** làm hỏng job: `fields` giữ đủ khoá với giá trị `null` và
trạng thái job vẫn do kết quả OCR từng trang quyết định.
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.
@@ -111,9 +161,18 @@ 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ử |
| `IDP_KIE_ENABLED` | `1` | `0` để bỏ bước bóc trường |
| `IDP_KIE_URL` | theo `IDP_OCR_URL` | API model KIE nếu serve riêng |
| `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_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_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 |
| `IDP_OCR_TIMEOUT` | `180` | Timeout mỗi request OCR, giây | | `IDP_OCR_TIMEOUT` | `180` | Timeout mỗi request OCR, giây |
@@ -184,18 +243,27 @@ Cả hai endpoint dùng `request_id` làm idempotency key. Gửi lại cùng n
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;
`GET /jobs/{job_id}/pages` trả lỗi từng trang và `GET /jobs/{job_id}/result` `GET /jobs/{job_id}/pages` trả lỗi từng trang, `GET /jobs/{job_id}/extraction`
trả bundle sau khi hoàn tất. trả các trường đã bóc và `GET /jobs/{job_id}/result` trả bundle sau khi hoàn tất.
Callback gửi `{ "dag_run_id": "...", "conf": { "request_id": "...", "job_id": "...", Callback gửi `{ "dag_run_id": "...", "conf": { "request_id": "...", "job_id": "...",
"status": "done", "output": { "extraction": { "pages": [<ảnh PNG Base64>] }, "status": "done", "output": { "extraction": { "schema": "basic-document-v1",
"status": "done", "fields": {...}, "error": null, "pages": [<ảnh PNG Base64>] },
"canonical": <bundle> } } }` và "canonical": <bundle> } } }` và
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`.
Bước bóc trường được retry riêng tối đa `IDP_MAX_KIE_ATTEMPTS` lần và dùng chung
giới hạn `IDP_OCR_WORKERS` với OCR từng trang, nên không làm quá tải GPU.
Trang lỗi được retry riêng; output bị cắt mới bật `frequency_penalty` ở lần thử Trang lỗi được retry riêng; output bị cắt mới bật `frequency_penalty` ở lần thử
sau. Job chỉ `completed` khi mọi trang hợp lệ. Nếu còn trang lỗi sau retry, job sau. Job chỉ `completed` khi mọi trang hợp lệ. Nếu còn trang lỗi sau retry, job
`partial_failed` và bundle vẫn chứa các trang thành công cùng lỗi từng trang. `partial_failed` và bundle vẫn chứa các trang thành công cùng lỗi từng trang.
@@ -204,6 +272,10 @@ sau. Job chỉ `completed` khi mọi trang hợp lệ. Nếu còn trang lỗi sa
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; luồng upload được kiểm end to end bằng `IDP_OCR_BACKEND=pdf_text`. 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 Chưa có số đo end to end của service với model thật. Bước bóc trường chưa được
đo trên dữ liệu thật; schema 7 trường cũng chưa qua vòng nghiệm thu nào nên quy
ước từng trường trong `SCHEMA` còn có thể phải chỉnh sau khi đối chiếu kết quả.
Lượt KIE hiện chỉ gửi ảnh, chưa gửi kèm lớp text của PDF số hoá để đối chiếu
chính tả như `IDP-Prelabel-Pipeline` đang làm. 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

@@ -16,6 +16,7 @@ from starlette.concurrency import run_in_threadpool
from .config import Settings from .config import Settings
from .db import Store from .db import Store
from .kie import SCHEMA_NAME, empty_answer
CHUNK = 1024 * 1024 CHUNK = 1024 * 1024
@@ -73,7 +74,7 @@ def create_app(settings: Settings | None = None) -> FastAPI:
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", "dag_run_id", "batch_id", "status", "file_path", "filename", "source_kind", "id", "request_id", "dag_run_id", "batch_id", "status", "file_path", "filename", "source_kind",
"total_pages", "completed_pages", "failed_pages", "error", "total_pages", "completed_pages", "failed_pages", "error", "extract_status",
"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
@@ -168,6 +169,18 @@ def create_app(settings: Settings | None = None) -> FastAPI:
raise HTTPException(status_code=404, detail="Job not found") raise HTTPException(status_code=404, detail="Job not found")
return {"job_id": job_id, "pages": store.get_pages(job_id)} 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)]) @app.get("/jobs/{job_id}/result", dependencies=[Depends(authorize)])
def job_result(job_id: str): def job_result(job_id: str):
job = store.get_job(job_id) job = store.get_job(job_id)

View File

@@ -11,9 +11,18 @@ 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
kie_enabled: bool = os.getenv("IDP_KIE_ENABLED", "1").lower() in ("1", "true", "yes")
kie_url: str = os.getenv("IDP_KIE_URL") or os.getenv("IDP_OCR_URL", "http://localhost:9222/v1/chat/completions")
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_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"))
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"))
max_queued_jobs: int = int(os.getenv("IDP_MAX_QUEUED_JOBS", "1000")) max_queued_jobs: int = int(os.getenv("IDP_MAX_QUEUED_JOBS", "1000"))

View File

@@ -38,6 +38,11 @@ class Store:
finalize_attempts INTEGER NOT NULL DEFAULT 0, finalize_attempts INTEGER NOT NULL DEFAULT 0,
next_at REAL NOT NULL DEFAULT 0, lease_until REAL NOT NULL DEFAULT 0, next_at REAL NOT NULL DEFAULT 0, lease_until REAL NOT NULL DEFAULT 0,
error TEXT, result_path TEXT, result_json TEXT, error TEXT, result_path TEXT, result_json TEXT,
extract_status TEXT NOT NULL DEFAULT 'pending',
extract_attempts INTEGER NOT NULL DEFAULT 0,
extract_next_at REAL NOT NULL DEFAULT 0,
extract_lease_until REAL NOT NULL DEFAULT 0,
extract_json TEXT, extract_error TEXT,
callback_state TEXT NOT NULL DEFAULT 'none', callback_state TEXT NOT NULL DEFAULT 'none',
callback_attempts INTEGER NOT NULL DEFAULT 0, callback_attempts INTEGER NOT NULL DEFAULT 0,
callback_next_at REAL NOT NULL DEFAULT 0, callback_next_at REAL NOT NULL DEFAULT 0,
@@ -65,6 +70,14 @@ class Store:
db.execute("ALTER TABLE jobs ADD COLUMN source_kind TEXT NOT NULL DEFAULT 'path'") db.execute("ALTER TABLE jobs ADD COLUMN source_kind TEXT NOT NULL DEFAULT 'path'")
if "dag_run_id" not in columns: if "dag_run_id" not in columns:
db.execute("ALTER TABLE jobs ADD COLUMN dag_run_id TEXT") db.execute("ALTER TABLE jobs ADD COLUMN dag_run_id TEXT")
if "extract_status" not in columns:
for statement in ("ADD COLUMN extract_status TEXT NOT NULL DEFAULT 'pending'",
"ADD COLUMN extract_attempts INTEGER NOT NULL DEFAULT 0",
"ADD COLUMN extract_next_at REAL NOT NULL DEFAULT 0",
"ADD COLUMN extract_lease_until REAL NOT NULL DEFAULT 0",
"ADD COLUMN extract_json TEXT",
"ADD COLUMN extract_error TEXT"):
db.execute(f"ALTER TABLE jobs {statement}")
@contextmanager @contextmanager
def tx(self): def tx(self):
@@ -164,8 +177,7 @@ class Store:
def claim_page(self, lease_seconds: int, global_limit: int): def claim_page(self, lease_seconds: int, global_limit: int):
now = time.time() now = time.time()
with self.tx() as db: with self.tx() as db:
active = db.execute("SELECT count(*) FROM pages WHERE status='running' AND lease_until>?", (now,)).fetchone()[0] if self._gpu_busy(db, now, global_limit):
if active >= global_limit:
return None return None
row = db.execute("""SELECT p.*,j.file_path FROM pages p JOIN jobs j ON j.id=p.job_id row = db.execute("""SELECT p.*,j.file_path FROM pages p JOIN jobs j ON j.id=p.job_id
WHERE j.status='processing' AND ((p.status='queued' AND p.next_at<=?) WHERE j.status='processing' AND ((p.status='queued' AND p.next_at<=?)
@@ -180,6 +192,47 @@ class Store:
return self.as_dict(db.execute("SELECT * FROM pages WHERE job_id=? AND page_no=?", return self.as_dict(db.execute("SELECT * FROM pages WHERE job_id=? AND page_no=?",
(row["job_id"], row["page_no"])).fetchone()) (row["job_id"], row["page_no"])).fetchone())
@staticmethod
def _gpu_busy(db, now: float, global_limit: int) -> bool:
running = db.execute("SELECT count(*) FROM pages WHERE status='running' AND lease_until>?",
(now,)).fetchone()[0]
running += db.execute("SELECT count(*) FROM jobs WHERE extract_status='running' AND extract_lease_until>?",
(now,)).fetchone()[0]
return running >= global_limit
def claim_extract(self, lease_seconds: int, global_limit: int):
"""Bóc trường chạy sau khi mọi trang của job đã xong, trước bước finalize."""
now = time.time()
with self.tx() as db:
if self._gpu_busy(db, now, global_limit):
return None
row = db.execute("""SELECT * FROM jobs j WHERE
((j.status='processing' AND j.extract_status='pending' AND j.extract_next_at<=?
AND j.total_pages>0 AND NOT EXISTS
(SELECT 1 FROM pages p WHERE p.job_id=j.id AND p.status IN ('queued','running')))
OR (j.extract_status='running' AND j.extract_lease_until<=?))
ORDER BY j.created_at LIMIT 1""", (now, now)).fetchone()
if not row:
return None
db.execute("""UPDATE jobs SET extract_status='running',extract_attempts=extract_attempts+1,
extract_lease_until=? WHERE id=?""", (now + lease_seconds, row["id"]))
return self.as_dict(db.execute("SELECT * FROM jobs WHERE id=?", (row["id"],)).fetchone())
def extract_done(self, job_id: str, attempts: int, answer_json: str | None, status: str = "done"):
with self.tx() as db:
return db.execute("""UPDATE jobs SET extract_status=?,extract_json=?,extract_error=NULL,
extract_lease_until=0 WHERE id=? AND extract_status='running' AND extract_attempts=?""",
(status, answer_json, job_id, attempts)).rowcount == 1
def extract_failed(self, job_id: str, attempts: int, error: str, max_attempts: int):
now = time.time()
terminal = attempts >= max_attempts
with self.tx() as db:
db.execute("""UPDATE jobs SET extract_status=?,extract_error=?,extract_next_at=?,
extract_lease_until=0 WHERE id=? AND extract_status='running' AND extract_attempts=?""",
("failed" if terminal else "pending", error[:1000], now + retry_delay(attempts),
job_id, attempts))
def page_done(self, job_id: str, page_no: int, attempts: int, result: dict): def page_done(self, job_id: str, page_no: int, attempts: int, result: dict):
with self.tx() as db: with self.tx() as db:
return db.execute("""UPDATE pages SET status='done',result_json=?,error=NULL,lease_until=0 return db.execute("""UPDATE pages SET status='done',result_json=?,error=NULL,lease_until=0
@@ -201,7 +254,8 @@ class Store:
now = time.time() now = time.time()
with self.tx() as db: with self.tx() as db:
row = db.execute("""SELECT * FROM jobs j WHERE row = db.execute("""SELECT * FROM jobs j WHERE
((j.status='processing' AND j.next_at<=? AND j.total_pages>0 AND NOT EXISTS ((j.status='processing' AND j.next_at<=? AND j.total_pages>0
AND j.extract_status IN ('done','failed','skipped') AND NOT EXISTS
(SELECT 1 FROM pages p WHERE p.job_id=j.id AND p.status IN ('queued','running'))) (SELECT 1 FROM pages p WHERE p.job_id=j.id AND p.status IN ('queued','running')))
OR (j.status='finalizing' AND j.lease_until<=?)) OR (j.status='finalizing' AND j.lease_until<=?))
ORDER BY j.created_at LIMIT 1""", (now, now)).fetchone() ORDER BY j.created_at LIMIT 1""", (now, now)).fetchone()

163
idp_service/kie.py Normal file
View File

@@ -0,0 +1,163 @@
"""Bóc 7 trường cơ bản của văn bản hành chính bằng một lượt model trên ảnh trang.
Prompt giữ nguyên từng byte theo template lượt 2 của IDP-Training-Pipeline
(`scripts/data/kie_prompts/extract_vi.txt`, giống `IDP-Prelabel-Pipeline/prompts/
prompt_kie_extract_vi.txt`) nên model fine-tune KIE gặp đúng định dạng đã train.
Khác ở chỗ schema tại đây cố định, không qua lượt GLM đề xuất schema.
Schema chỉ dùng hai kiểu của template: string và object. Thêm list/table/boolean
thì phải mở rộng `render_fields` và `normalize_answer` theo template gốc.
"""
import base64
import json
import re
from pathlib import Path
from urllib.request import Request, urlopen
from .config import Settings
from .ocr import InvalidOutput, render_page
SCHEMA_NAME = "basic-document-v1"
SCHEMA = [
{"key": "document_type",
"description": "Loại văn bản, ví dụ Quyết định, Thông tư, Công văn, Tờ trình; chép đúng như trên văn bản"},
{"key": "document_number",
"description": 'Số, ký hiệu văn bản, ví dụ "123/QĐ-UBND"; bỏ nhãn "Số:" đứng trước'},
{"key": "issued_date",
"description": "Ngày ban hành văn bản. Định dạng dd/mm/yyyy"},
{"key": "issuing_authority",
"description": "Cơ quan ban hành, lấy tên cơ quan trực tiếp ký ban hành ở góc trên bên trái; "
"bỏ tên cơ quan chủ quản cấp trên nếu có dòng riêng"},
{"key": "title",
"description": "Tên hoặc trích yếu nội dung văn bản, nằm dưới tên loại văn bản; "
"chép đúng như trên văn bản, giữ nguyên tiền tố V/v nếu có"},
{"key": "signer", "type": "object",
"description": "Người ký ban hành ở cuối văn bản",
"fields": [
{"key": "name", "description": "Họ tên người ký; bỏ học hàm, học vị"},
{"key": "position",
"description": 'Chức vụ người ký, ví dụ "Giám đốc", "KT. CHỦ TỊCH"; chép đúng như trên văn bản'},
]},
]
# Giống extract_vi.txt của IDP-Training-Pipeline.
PROMPT_TEMPLATE = """Trích xuất thông tin từ ảnh tài liệu{pages} và trả về JSON theo danh sách trường dưới đây.
Trường cần trích xuất (thụt lề là trường con):
{fields}
Quy tắc:
- Chỉ trả về một object JSON hợp lệ, không bọc ```json, không giải thích. Giữ đúng tên khoá, thứ tự và cấu trúc lồng như danh sách trên; không thêm, bớt hay đổi tên khoá.
- Trường không ghi kiểu là chuỗi: chỉ lấy đúng phần thông tin mà tên trường và mô tả hỏi tới, chép đúng từng ký tự như trên tài liệu, kể cả dấu; không sửa chính tả, không suy diễn, không tự điền.
- Trường có mô tả thì làm theo mô tả, kể cả khi mô tả chỉ lấy một phần giá trị hoặc yêu cầu định dạng lại.
- Không có trên tài liệu hoặc không đọc được: chuỗi để null, mảng để []. Object luôn giữ đủ khoá con.
- Mảng object: mỗi dòng hoặc mục trên tài liệu là một phần tử, theo thứ tự xuất hiện, bỏ dòng trống. Mảng chuỗi: mỗi giá trị là một phần tử.
- true/false: true khi điều trường đó hỏi là đúng trên tài liệu, ngược lại false."""
PAGE_HINT = " ({count} trang, ảnh theo thứ tự trang)"
def render_fields(fields: list[dict], depth: int = 0) -> list[str]:
lines = []
for item in fields:
line = " " * depth + "- " + json.dumps(item["key"], ensure_ascii=False)
if item.get("type") == "object":
line += " (object)"
if item.get("description"):
line += ": " + " ".join(item["description"].split())
lines.append(line)
if item.get("fields"):
lines.extend(render_fields(item["fields"], depth + 1))
return lines
def render_prompt(page_count: int) -> str:
pages = PAGE_HINT.format(count=page_count) if page_count > 1 else ""
return PROMPT_TEMPLATE.replace("{pages}", pages).replace("{fields}", "\n".join(render_fields(SCHEMA)))
def empty_answer(fields: list[dict] = SCHEMA) -> dict:
"""Đáp án rỗng: mọi trường null. Dùng khi extract bị lỗi hoặc bỏ qua."""
return {item["key"]: empty_answer(item["fields"]) if item.get("fields") else None for item in fields}
def parse_model_json(text: str) -> dict:
body = re.sub(r"^```(?:json)?|```$", "", text.strip(), flags=re.M).strip()
for candidate in (body, body[body.find("{"):body.rfind("}") + 1]):
try:
payload = json.loads(candidate)
except ValueError:
continue
if isinstance(payload, dict):
return payload
raise InvalidOutput("Model không trả về JSON object")
def normalize_answer(payload: dict, fields: list[dict] = SCHEMA) -> dict:
"""Ép đáp án về đúng hình dạng schema: thiếu khoá thành null, thừa khoá bỏ đi.
Chuỗi rỗng thành null và mảng chuỗi (đoạn bị model tách theo dòng) nối lại,
giống bước làm sạch khi dựng dữ liệu train.
"""
answer = {}
for item in fields:
value = payload.get(item["key"]) if isinstance(payload, dict) else None
if item.get("fields"):
answer[item["key"]] = normalize_answer(value if isinstance(value, dict) else {}, item["fields"])
elif isinstance(value, list) and all(isinstance(v, str) for v in value):
answer[item["key"]] = "\n".join(value).strip() or None
elif isinstance(value, str):
answer[item["key"]] = value.strip() or None
elif isinstance(value, (int, float)) and not isinstance(value, bool):
answer[item["key"]] = str(value)
else:
answer[item["key"]] = None
return answer
def has_any_key(payload: dict, fields: list[dict] = SCHEMA) -> bool:
return any(item["key"] in payload for item in fields)
def select_pages(page_count: int, max_pages: int) -> list[int]:
"""Văn bản dài thì gửi các trang đầu (tên loại, số ký hiệu, trích yếu) và trang cuối (người ký)."""
if page_count <= max_pages:
return list(range(1, page_count + 1))
return list(range(1, max_pages)) + [page_count]
def extract_document(settings: Settings, pdf_path: Path, page_count: int) -> dict:
page_numbers = select_pages(page_count, settings.kie_max_pages)
prompt = render_prompt(len(page_numbers))
content = []
for page_no in page_numbers:
image, _, _ = render_page(pdf_path, page_no)
content.append({"type": "image_url", "image_url": {
"url": "data:image/png;base64," + base64.b64encode(image).decode("ascii")}})
content.append({"type": "text", "text": prompt})
payload = {
"model": settings.kie_model,
"messages": [{"role": "user", "content": content}],
"max_tokens": settings.kie_max_tokens,
"temperature": 0.0,
"top_p": 0.1,
}
request = Request(settings.kie_url, data=json.dumps(payload).encode("utf-8"),
headers={"Content-Type": "application/json"}, method="POST")
with urlopen(request, timeout=settings.kie_timeout) as response:
result = json.load(response)
try:
choice = result["choices"][0]
text, finish_reason = choice["message"]["content"], choice["finish_reason"]
except (KeyError, IndexError, TypeError) as exc:
raise InvalidOutput("Malformed model response") from exc
if finish_reason == "length":
raise InvalidOutput("Model reached max_tokens", truncated=True)
if not isinstance(text, str) or not text.strip():
raise InvalidOutput(f"Empty KIE answer (finish_reason={finish_reason})")
answer = parse_model_json(text)
if not has_any_key(answer):
raise InvalidOutput("Đáp án không có trường nào của schema")
return normalize_answer(answer)

View File

@@ -18,6 +18,8 @@ LABELS = {
} }
LABEL_ALIASES = {"Page-Header": "Header", "Page Header": "Header", LABEL_ALIASES = {"Page-Header": "Header", "Page Header": "Header",
"Page-Footer": "Footer", "Page Footer": "Footer"} "Page-Footer": "Footer", "Page Footer": "Footer"}
# Vùng không có chữ: model trả div rỗng, không phải output hỏng.
VISUAL_LABELS = {"Image", "QR Code", "Barcode", "Signature", "Stamp"}
class InvalidOutput(Exception): class InvalidOutput(Exception):
@@ -54,8 +56,8 @@ def validate_response(response: dict) -> list[dict]:
box = block["bbox"] box = block["bbox"]
if box is None or len(box) != 4 or not (0 <= box[0] < box[2] <= 1000 and 0 <= box[1] < box[3] <= 1000): if box is None or len(box) != 4 or not (0 <= box[0] < box[2] <= 1000 and 0 <= box[1] < box[3] <= 1000):
raise InvalidOutput(f"Invalid bounding box: {box}") raise InvalidOutput(f"Invalid bounding box: {box}")
if not block["html"]: if not block["html"] and block["label"] not in VISUAL_LABELS:
raise InvalidOutput("Empty layout block") raise InvalidOutput(f"Empty layout block: {block['label']}")
return blocks return blocks

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
@@ -17,6 +19,7 @@ from .config import Settings
from .db import Store from .db import Store
from .decrypt import prepare_pdf from .decrypt import prepare_pdf
from .dla import build_outline from .dla import build_outline
from .kie import SCHEMA_NAME, empty_answer, extract_document
from .ocr import InvalidOutput, infer_page, render_page from .ocr import InvalidOutput, infer_page, render_page
from .storage import fetch_pdf from .storage import fetch_pdf
@@ -34,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")
@@ -84,6 +89,22 @@ class Worker:
isinstance(exc, InvalidOutput) and exc.truncated, isinstance(exc, InvalidOutput) and exc.truncated,
self.settings.max_page_attempts) self.settings.max_page_attempts)
def extract(self, job: dict):
"""Một lượt model bóc các trường cố định cho cả tài liệu, chạy sau khi mọi trang đã OCR xong."""
job_id, attempts = job["id"], job["extract_attempts"]
if not self.settings.kie_enabled or self.settings.ocr_backend == "pdf_text":
self.store.extract_done(job_id, attempts, None, status="skipped")
return
try:
if attempts > self.settings.max_kie_attempts:
raise ValueError("Extract lease expired too many times")
answer = extract_document(self.settings, self.job_dir(job_id) / "source.pdf", job["total_pages"])
self.store.extract_done(job_id, attempts, json.dumps(answer, ensure_ascii=False))
log.info("Extracted fields for %s", job_id)
except Exception as exc:
log.warning("Extract failed: %s attempt %s: %s", job_id, attempts, exc)
self.store.extract_failed(job_id, attempts, str(exc), self.settings.max_kie_attempts)
def finalize(self, job: dict): def finalize(self, job: dict):
job_id = job["id"] job_id = job["id"]
try: try:
@@ -118,6 +139,12 @@ class Worker:
"source": {"filename": job["filename"] or Path(job["file_path"]).name, "source": {"filename": job["filename"] or Path(job["file_path"]).name,
"media_type": "application/pdf", "media_type": "application/pdf",
"page_count": len(pages), "render_dpi": 200}, "page_count": len(pages), "render_dpi": 200},
"extraction": {
"schema": SCHEMA_NAME,
"status": job["extract_status"],
"fields": json.loads(job["extract_json"]) if job["extract_json"] else empty_answer(),
"error": job["extract_error"],
},
"outline": build_outline(pages), "pages": pages, "outline": build_outline(pages), "pages": pages,
} }
result_json = json.dumps(bundle, ensure_ascii=False, separators=(",", ":")) result_json = json.dumps(bundle, ensure_ascii=False, separators=(",", ":"))
@@ -137,7 +164,7 @@ class Worker:
extraction = None extraction = None
if canonical is not None: if canonical is not None:
source = self.job_dir(job["id"]) / "source.pdf" source = self.job_dir(job["id"]) / "source.pdf"
extraction = {"pages": []} extraction = {**canonical.get("extraction", {}), "pages": []}
for page_no in range(1, canonical["source"]["page_count"] + 1): for page_no in range(1, canonical["source"]["page_count"] + 1):
image, _, _ = render_page(source, page_no) image, _, _ = render_page(source, page_no)
extraction["pages"].append({ extraction["pages"].append({
@@ -156,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:
@@ -171,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)
@@ -192,8 +246,12 @@ class Worker:
page = self.store.claim_page(self.settings.lease_seconds, self.settings.ocr_workers) page = self.store.claim_page(self.settings.lease_seconds, self.settings.ocr_workers)
if page: if page:
self.process_page(page) self.process_page(page)
else: continue
self.stop.wait(self.settings.poll_seconds) job = self.store.claim_extract(self.settings.lease_seconds, self.settings.ocr_workers)
if job:
self.extract(job)
continue
self.stop.wait(self.settings.poll_seconds)
def run(self): def run(self):
threads = [threading.Thread(target=self.page_loop, name=f"ocr-{i}", daemon=True) threads = [threading.Thread(target=self.page_loop, name=f"ocr-{i}", daemon=True)

View File

@@ -68,6 +68,17 @@ Content-Type: application/json
"status": "done", "status": "done",
"output": { "output": {
"extraction": { "extraction": {
"schema": "basic-document-v1",
"status": "done",
"fields": {
"document_type": "QUYẾT ĐỊNH",
"document_number": "123/QĐ-UBND",
"issued_date": "09/09/2026",
"issuing_authority": "ỦY BAN NHÂN DÂN TỈNH BẮC NINH",
"title": "Về việc phê duyệt quy hoạch",
"signer": { "name": "Nguyễn Văn A", "position": "KT. CHỦ TỊCH" }
},
"error": null,
"pages": [{ "page_no": 1, "media_type": "image/png", "data_base64": "..." }] "pages": [{ "page_no": 1, "media_type": "image/png", "data_base64": "..." }]
}, },
"canonical": { "schema": "dla-document-bundle", "pages": [] } "canonical": { "schema": "dla-document-bundle", "pages": [] }
@@ -76,7 +87,11 @@ Content-Type: application/json
} }
``` ```
`output.extraction.pages` chứa ảnh PNG 200 DPI từng trang, mã hóa Base64. `output.extraction.fields` là các trường đã bóc, cũng nằm trong
`canonical.extraction` và ở `GET /jobs/{job_id}/extraction`. `status` là `done`,
`failed` hoặc `skipped`; khi không phải `done` thì `fields` vẫn đủ khoá nhưng
giá trị `null`, `error` ghi lý do. `output.extraction.pages` chứa ảnh PNG 200 DPI
từng trang, mã hóa Base64.
`output.canonical` là toàn bộ `dla-document-bundle` từ `GET /jobs/{job_id}/result`. `output.canonical` là toàn bộ `dla-document-bundle` từ `GET /jobs/{job_id}/result`.
Callback thất bại trước khi có kết quả có `status: "failed"` và cả hai trường Callback thất bại trước khi có kết quả có `status: "failed"` và cả hai trường
`extraction`, `canonical` là `null`. `extraction`, `canonical` là `null`.

View File

@@ -14,6 +14,7 @@ from idp_service.api import create_app
from idp_service.config import Settings from idp_service.config import Settings
from idp_service.db import Store from idp_service.db import Store
from idp_service.decrypt import DEFAULT_KEY_HEX, DecryptionError, prepare_pdf from idp_service.decrypt import DEFAULT_KEY_HEX, DecryptionError, prepare_pdf
from idp_service import kie
from idp_service.ocr import InvalidOutput, validate_response from idp_service.ocr import InvalidOutput, validate_response
from idp_service.worker import Worker from idp_service.worker import Worker
from idp_service.webhdfs import download_pdf from idp_service.webhdfs import download_pdf
@@ -21,7 +22,7 @@ from idp_service.webhdfs import download_pdf
def settings_for(tmp_path): def settings_for(tmp_path):
return replace(Settings(), data_dir=tmp_path / "data", storage="local", return replace(Settings(), data_dir=tmp_path / "data", storage="local",
ocr_workers=2, poll_seconds=0.01) ocr_workers=2, poll_seconds=0.01, kie_enabled=False)
def make_pdf(path: Path, count=3): def make_pdf(path: Path, count=3):
@@ -33,6 +34,20 @@ def make_pdf(path: Path, count=3):
document.close() document.close()
def drain(worker, settings):
"""Chạy hết job đang chờ: prepare, mọi trang, extract, rồi finalize và callback."""
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)
job = worker.store.claim_extract(settings.lease_seconds, settings.ocr_workers)
if job:
worker.extract(job)
assert worker.coordinator_once()
def test_api_idempotency_and_end_to_end(tmp_path, monkeypatch): def test_api_idempotency_and_end_to_end(tmp_path, monkeypatch):
settings = settings_for(tmp_path) settings = settings_for(tmp_path)
source = tmp_path / "input.pdf" source = tmp_path / "input.pdf"
@@ -53,13 +68,7 @@ def test_api_idempotency_and_end_to_end(tmp_path, monkeypatch):
{"label": "Paragraph", "bbox": [1, 1, 500, 500], "html": f"Page {page_no}"}]} {"label": "Paragraph", "bbox": [1, 1, 500, 500], "html": f"Page {page_no}"}]}
monkeypatch.setattr("idp_service.worker.infer_page", fake_infer) monkeypatch.setattr("idp_service.worker.infer_page", fake_infer)
worker = Worker(settings) drain(Worker(settings), settings)
assert worker.coordinator_once()
for _ in range(3):
page = worker.store.claim_page(settings.lease_seconds, settings.ocr_workers)
assert page
worker.process_page(page)
assert worker.coordinator_once()
status = client.get(f"/jobs/{first.json()['job_id']}").json() status = client.get(f"/jobs/{first.json()['job_id']}").json()
assert status["status"] == "completed" assert status["status"] == "completed"
assert status["completed_pages"] == 3 assert status["completed_pages"] == 3
@@ -67,17 +76,9 @@ def test_api_idempotency_and_end_to_end(tmp_path, monkeypatch):
bundle = client.get(f"/jobs/{first.json()['job_id']}/result").json() bundle = client.get(f"/jobs/{first.json()['job_id']}/result").json()
assert len(bundle["pages"]) == 3 assert len(bundle["pages"]) == 3
assert all(page["status"] == "done" for page in bundle["pages"]) assert all(page["status"] == "done" for page in bundle["pages"])
# IDP_KIE_ENABLED=0: bundle vẫn giữ đủ khung extraction với các trường null.
assert bundle["extraction"] == {"schema": kie.SCHEMA_NAME, "status": "skipped",
def drain(worker, settings): "fields": kie.empty_answer(), "error": None}
"""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): def test_upload_pdf_returns_bundle_without_gpu(tmp_path):
@@ -110,6 +111,7 @@ def test_upload_pdf_returns_bundle_without_gpu(tmp_path):
assert all(0 <= value <= 1000 for value in block["bbox"]) assert all(0 <= value <= 1000 for value in block["bbox"])
assert block["outline_no"] == "0.1" assert block["outline_no"] == "0.1"
assert bundle["outline"][0]["block_ids"][0] == block["block_id"] assert bundle["outline"][0]["block_ids"][0] == block["block_id"]
assert bundle["extraction"]["status"] == "skipped"
# Upload đã dedupe theo sha256 được dọn sau khi finalize. # Upload đã dedupe theo sha256 được dọn sau khi finalize.
assert list(settings.upload_dir.glob("*.pdf")) == [] assert list(settings.upload_dir.glob("*.pdf")) == []
@@ -158,6 +160,7 @@ def test_page_retry_then_partial_failure(tmp_path, monkeypatch):
second = store.claim_page(settings.lease_seconds, settings.ocr_workers) second = store.claim_page(settings.lease_seconds, settings.ocr_workers)
assert second["penalize_repetition"] == 1 assert second["penalize_repetition"] == 1
worker.process_page(second) worker.process_page(second)
worker.extract(store.claim_extract(settings.lease_seconds, settings.ocr_workers))
worker.coordinator_once() worker.coordinator_once()
result = store.get_job(job["id"]) result = store.get_job(job["id"])
assert result["status"] == "partial_failed" assert result["status"] == "partial_failed"
@@ -179,6 +182,168 @@ def test_pdf_text_backend_labels_pages_without_text(tmp_path):
"html": "<p>[no extractable text]</p>"}] "html": "<p>[no extractable text]</p>"}]
KIE_ANSWER = {
"document_type": "QUYẾT ĐỊNH",
"document_number": "123/QĐ-UBND",
"issued_date": "09/09/2026",
"issuing_authority": "ỦY BAN NHÂN DÂN TỈNH BẮC NINH",
"title": "Về việc phê duyệt quy hoạch",
"signer": {"name": "Nguyễn Văn A", "position": "KT. CHỦ TỊCH"},
}
def model_server(kie_content):
"""Server giả đóng vai vLLM: nhận cả prompt DLA lẫn prompt KIE, và nhận callback."""
callbacks, kie_requests = [], []
class Handler(BaseHTTPRequestHandler):
def do_POST(self):
body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
if self.path == "/v1/chat/completions":
content = body["messages"][0]["content"]
assert content[0]["image_url"]["url"].startswith("data:image/png;base64,")
if content[-1]["text"].startswith("Trích xuất thông tin"):
kie_requests.append(body)
answer = {"choices": [{"finish_reason": "stop", "message": {"content": kie_content}}]}
else:
answer = {"choices": [{"finish_reason": "stop", "message": {"content":
'<div data-label="Paragraph" data-bbox="1 1 500 500">Test</div>'}}]}
else:
callbacks.append(body)
answer = {"ok": True}
data = json.dumps(answer).encode()
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
def log_message(self, *_):
pass
return ThreadingHTTPServer(("127.0.0.1", 0), Handler), callbacks, kie_requests
def test_extract_fixed_schema_end_to_end_and_callback(tmp_path):
server, callbacks, kie_requests = model_server("```json\n" + json.dumps(KIE_ANSWER, ensure_ascii=False) + "\n```")
thread = Thread(target=server.serve_forever, daemon=True)
thread.start()
try:
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,
kie_max_tokens=4096)
source = tmp_path / "quyet-dinh.pdf"
make_pdf(source, count=2)
app = create_app(settings)
with TestClient(app) as client:
reply = client.post("/parse", files={"file": ("quyet-dinh.pdf", source.read_bytes(), "application/pdf")},
data={"callback_url": f"http://127.0.0.1:{server.server_port}/callback"})
job_id = reply.json()["job_id"]
assert client.get(f"/jobs/{job_id}/extraction").status_code == 409
drain(Worker(settings), settings)
# Một lượt KIE cho cả tài liệu, gửi kèm ảnh mọi trang.
assert len(kie_requests) == 1
assert len(kie_requests[0]["messages"][0]["content"]) == 3
assert kie_requests[0]["model"] == settings.kie_model
assert kie_requests[0]["max_tokens"] == 4096
extraction = client.get(f"/jobs/{job_id}/extraction").json()
assert extraction["status"] == "done"
assert extraction["schema"] == kie.SCHEMA_NAME
assert extraction["fields"] == KIE_ANSWER
assert client.get(f"/jobs/{job_id}").json()["extract_status"] == "done"
bundle = client.get(f"/jobs/{job_id}/result").json()
assert bundle["extraction"]["fields"] == KIE_ANSWER
assert bundle["extraction"]["status"] == "done"
output = callbacks[0]["conf"]["output"]
assert output["extraction"]["fields"] == KIE_ANSWER
assert len(output["extraction"]["pages"]) == 2
finally:
server.shutdown()
server.server_close()
thread.join()
def test_extract_retries_bad_answer_then_gives_up(tmp_path):
# Model trả JSON nhưng đặt khoá tiếng Việt: coi như hỏng chứ không im lặng trả null.
server, _, kie_requests = model_server('{"loai_van_ban": "QUYẾT ĐỊNH"}')
thread = Thread(target=server.serve_forever, daemon=True)
thread.start()
try:
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,
max_kie_attempts=2)
source = tmp_path / "input.pdf"
make_pdf(source, count=1)
store = Store(settings.db_path)
job, _ = store.create_job(str(uuid4()), str(source), None, None, 100)
worker = Worker(settings, store)
worker.coordinator_once()
worker.process_page(store.claim_page(settings.lease_seconds, settings.ocr_workers))
for _ in range(settings.max_kie_attempts):
with store.tx() as db:
db.execute("UPDATE jobs SET extract_next_at=0 WHERE id=?", (job["id"],))
worker.extract(store.claim_extract(settings.lease_seconds, settings.ocr_workers))
assert len(kie_requests) == settings.max_kie_attempts
worker.coordinator_once()
# Extract hỏng không làm hỏng job: bundle vẫn completed, trường để null kèm lỗi.
result = store.get_job(job["id"])
assert result["status"] == "completed"
bundle = json.loads(result["result_json"])
assert bundle["extraction"]["status"] == "failed"
assert bundle["extraction"]["fields"] == kie.empty_answer()
assert bundle["extraction"]["error"] == "Đáp án không có trường nào của schema"
finally:
server.shutdown()
server.server_close()
thread.join()
def test_kie_prompt_schema_and_answer_shape():
prompt = kie.render_prompt(3)
assert prompt.startswith("Trích xuất thông tin từ ảnh tài liệu (3 trang, ảnh theo thứ tự trang)")
assert '- "signer" (object): Người ký ban hành ở cuối văn bản\n - "name"' in prompt
assert [line for line in prompt.splitlines() if line.startswith('- "')][:5] == [
line for line in kie.render_fields(kie.SCHEMA) if line.startswith('- "')][:5]
assert kie.render_prompt(1).startswith("Trích xuất thông tin từ ảnh tài liệu và")
# Khoá thừa bị bỏ, khoá thiếu thành null, chuỗi rỗng và mảng chuỗi được làm sạch.
answer = kie.normalize_answer({"document_type": ["QUYẾT", "ĐỊNH"], "document_number": " ",
"signer": {"name": "Nguyễn Văn A"}, "ghi_chu": "thừa"})
assert answer == {"document_type": "QUYẾT\nĐỊNH", "document_number": None, "issued_date": None,
"issuing_authority": None, "title": None,
"signer": {"name": "Nguyễn Văn A", "position": None}}
assert list(answer) == [field["key"] for field in kie.SCHEMA]
# Tài liệu dài chỉ gửi các trang đầu và trang cuối (nơi có người ký).
assert kie.select_pages(3, 5) == [1, 2, 3]
assert kie.select_pages(20, 5) == [1, 2, 3, 4, 20]
def test_keeps_empty_visual_blocks_but_rejects_empty_text_blocks():
"""Model trả div rỗng cho con dấu, QR, chữ ký; chỉ block chữ mà rỗng mới là output hỏng."""
def response(content):
return {"choices": [{"finish_reason": "stop", "message": {"content": content}}]}
blocks = validate_response(response(
'<div data-label="Stamp" data-bbox="736 86 909 142"></div>'
'<div data-label="QR Code" data-bbox="814 55 896 112"></div>'
'<div data-label="Paragraph" data-bbox="92 85 795 151"><p>Nội dung</p></div>'))
assert [block["label"] for block in blocks] == ["Stamp", "QR Code", "Paragraph"]
assert [block["html"] for block in blocks[:2]] == ["", ""]
try:
validate_response(response('<div data-label="Paragraph" data-bbox="1 1 500 500"></div>'))
except InvalidOutput as exc:
assert "Paragraph" in str(exc)
else:
raise AssertionError("Block chữ rỗng đáng lẽ phải bị từ chối")
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}}]}
@@ -196,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):
@@ -207,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)))
@@ -223,22 +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
worker = Worker(settings) drain(Worker(settings), settings)
worker.coordinator_once()
page = worker.store.claim_page(settings.lease_seconds, settings.ocr_workers)
worker.process_page(page)
worker.coordinator_once()
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"]
@@ -251,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()