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

@@ -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()