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>
This commit is contained in:
2026-09-23 07:52:41 +00:00
parent 0e15bc89a8
commit de967a64c2
8 changed files with 517 additions and 37 deletions

View File

@@ -16,6 +16,7 @@ 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
@@ -73,7 +74,7 @@ def create_app(settings: Settings | None = None) -> FastAPI:
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",
"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
@@ -168,6 +169,18 @@ def create_app(settings: Settings | None = None) -> FastAPI:
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)

View File

@@ -14,6 +14,12 @@ class Settings:
ocr_url: str = os.getenv("IDP_OCR_URL", "http://localhost:9222/v1/chat/completions")
ocr_model: str = os.getenv("IDP_OCR_MODEL", "chandra")
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"))
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")
ocr_workers: int = int(os.getenv("IDP_OCR_WORKERS", "64"))
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,
next_at REAL NOT NULL DEFAULT 0, lease_until REAL NOT NULL DEFAULT 0,
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_attempts INTEGER 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'")
if "dag_run_id" not in columns:
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
def tx(self):
@@ -164,8 +177,7 @@ class Store:
def claim_page(self, lease_seconds: int, global_limit: int):
now = time.time()
with self.tx() as db:
active = db.execute("SELECT count(*) FROM pages WHERE status='running' AND lease_until>?", (now,)).fetchone()[0]
if active >= global_limit:
if self._gpu_busy(db, now, global_limit):
return None
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<=?)
@@ -180,6 +192,47 @@ class Store:
return self.as_dict(db.execute("SELECT * FROM pages WHERE job_id=? AND page_no=?",
(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):
with self.tx() as db:
return db.execute("""UPDATE pages SET status='done',result_json=?,error=NULL,lease_until=0
@@ -201,7 +254,8 @@ class Store:
now = time.time()
with self.tx() as db:
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')))
OR (j.status='finalizing' AND j.lease_until<=?))
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": 2048,
"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

@@ -17,6 +17,7 @@ from .config import Settings
from .db import Store
from .decrypt import prepare_pdf
from .dla import build_outline
from .kie import SCHEMA_NAME, empty_answer, extract_document
from .ocr import InvalidOutput, infer_page, render_page
from .storage import fetch_pdf
@@ -84,6 +85,22 @@ class Worker:
isinstance(exc, InvalidOutput) and exc.truncated,
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):
job_id = job["id"]
try:
@@ -118,6 +135,12 @@ class Worker:
"source": {"filename": job["filename"] or Path(job["file_path"]).name,
"media_type": "application/pdf",
"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,
}
result_json = json.dumps(bundle, ensure_ascii=False, separators=(",", ":"))
@@ -137,7 +160,7 @@ class Worker:
extraction = None
if canonical is not None:
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):
image, _, _ = render_page(source, page_no)
extraction["pages"].append({
@@ -192,8 +215,12 @@ class Worker:
page = self.store.claim_page(self.settings.lease_seconds, self.settings.ocr_workers)
if page:
self.process_page(page)
else:
self.stop.wait(self.settings.poll_seconds)
continue
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):
threads = [threading.Thread(target=self.page_loop, name=f"ocr-{i}", daemon=True)