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>
317 lines
18 KiB
Python
317 lines
18 KiB
Python
"""SQLite job and page queue. Each claim is an atomic database transaction."""
|
|
import json
|
|
import sqlite3
|
|
import time
|
|
from contextlib import contextmanager
|
|
from pathlib import Path
|
|
from uuid import uuid4
|
|
|
|
|
|
def retry_delay(attempt: int) -> int:
|
|
return min(60, 2 ** min(attempt, 6))
|
|
|
|
|
|
class Store:
|
|
def __init__(self, path: Path):
|
|
self.path = path
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
self.init()
|
|
|
|
def connect(self):
|
|
connection = sqlite3.connect(self.path, timeout=30, isolation_level=None)
|
|
connection.row_factory = sqlite3.Row
|
|
connection.execute("PRAGMA busy_timeout=30000")
|
|
connection.execute("PRAGMA foreign_keys=ON")
|
|
return connection
|
|
|
|
def init(self):
|
|
with self.connect() as db:
|
|
db.execute("PRAGMA journal_mode=WAL")
|
|
db.executescript("""
|
|
CREATE TABLE IF NOT EXISTS jobs (
|
|
id TEXT PRIMARY KEY, request_id TEXT NOT NULL UNIQUE,
|
|
file_path TEXT NOT NULL, callback_url TEXT, batch_id TEXT, dag_run_id TEXT,
|
|
filename TEXT, source_kind TEXT NOT NULL DEFAULT 'path',
|
|
status TEXT NOT NULL, created_at REAL NOT NULL, updated_at REAL NOT NULL,
|
|
total_pages INTEGER NOT NULL DEFAULT 0,
|
|
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,
|
|
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,
|
|
callback_lease_until REAL NOT NULL DEFAULT 0,
|
|
callback_error TEXT
|
|
);
|
|
CREATE TABLE IF NOT EXISTS pages (
|
|
job_id TEXT NOT NULL REFERENCES jobs(id) ON DELETE CASCADE,
|
|
page_no INTEGER NOT NULL, status TEXT NOT NULL,
|
|
attempts INTEGER NOT NULL DEFAULT 0,
|
|
next_at REAL NOT NULL DEFAULT 0, lease_until REAL NOT NULL DEFAULT 0,
|
|
penalize_repetition INTEGER NOT NULL DEFAULT 0,
|
|
error TEXT, result_json TEXT,
|
|
PRIMARY KEY (job_id, page_no)
|
|
);
|
|
CREATE INDEX IF NOT EXISTS jobs_queue_idx ON jobs(status, next_at);
|
|
CREATE INDEX IF NOT EXISTS pages_queue_idx ON pages(status, next_at);
|
|
""")
|
|
columns = {row[1] for row in db.execute("PRAGMA table_info(jobs)")}
|
|
if "result_json" not in columns:
|
|
db.execute("ALTER TABLE jobs ADD COLUMN result_json TEXT")
|
|
if "filename" not in columns:
|
|
db.execute("ALTER TABLE jobs ADD COLUMN filename TEXT")
|
|
if "source_kind" not in columns:
|
|
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):
|
|
db = self.connect()
|
|
try:
|
|
db.execute("BEGIN IMMEDIATE")
|
|
yield db
|
|
db.execute("COMMIT")
|
|
except BaseException:
|
|
db.execute("ROLLBACK")
|
|
raise
|
|
finally:
|
|
db.close()
|
|
|
|
@staticmethod
|
|
def as_dict(row):
|
|
return dict(row) if row else None
|
|
|
|
def create_job(self, request_id: str, file_path: str, callback_url: str | None,
|
|
batch_id: str | None, max_queued: int, filename: str | None = None,
|
|
source_kind: str = "path", dag_run_id: str | None = None):
|
|
now = time.time()
|
|
filename = filename or Path(file_path).name
|
|
with self.tx() as db:
|
|
prior = db.execute("SELECT * FROM jobs WHERE request_id=?", (request_id,)).fetchone()
|
|
if prior:
|
|
if (prior["file_path"], prior["callback_url"], prior["batch_id"],
|
|
prior["filename"], prior["dag_run_id"]) != (file_path, callback_url, batch_id,
|
|
filename, dag_run_id):
|
|
raise ValueError("request_id already exists with different inputs")
|
|
return self.as_dict(prior), False
|
|
queued = db.execute("SELECT count(*) FROM jobs WHERE status IN ('queued','preparing','processing','finalizing')").fetchone()[0]
|
|
if queued >= max_queued:
|
|
raise OverflowError("Job queue is full")
|
|
job_id = "job_" + uuid4().hex
|
|
db.execute("""INSERT INTO jobs(id,request_id,file_path,callback_url,batch_id,dag_run_id,filename,
|
|
source_kind,status,created_at,updated_at)
|
|
VALUES(?,?,?,?,?,?,?,?,'queued',?,?)""",
|
|
(job_id, request_id, file_path, callback_url, batch_id, dag_run_id, filename,
|
|
source_kind, now, now))
|
|
return self.as_dict(db.execute("SELECT * FROM jobs WHERE id=?", (job_id,)).fetchone()), True
|
|
|
|
def get_job(self, job_id: str):
|
|
with self.connect() as db:
|
|
row = db.execute("""SELECT j.*,
|
|
(SELECT count(*) FROM pages p WHERE p.job_id=j.id AND p.status='done') AS completed_pages,
|
|
(SELECT count(*) FROM pages p WHERE p.job_id=j.id AND p.status='failed') AS failed_pages
|
|
FROM jobs j WHERE j.id=?""", (job_id,)).fetchone()
|
|
return self.as_dict(row)
|
|
|
|
def get_pages(self, job_id: str):
|
|
with self.connect() as db:
|
|
rows = db.execute("SELECT page_no,status,attempts,error FROM pages WHERE job_id=? ORDER BY page_no", (job_id,)).fetchall()
|
|
return [self.as_dict(row) for row in rows]
|
|
|
|
def upload_in_use(self, file_path: str, exclude_job_id: str) -> bool:
|
|
"""Một upload được dedupe theo sha256 nên nhiều job có thể trỏ vào cùng file."""
|
|
with self.connect() as db:
|
|
return db.execute("""SELECT count(*) FROM jobs WHERE file_path=? AND id<>?
|
|
AND status IN ('queued','preparing','processing','finalizing')""",
|
|
(file_path, exclude_job_id)).fetchone()[0] > 0
|
|
|
|
def claim_prepare(self, lease_seconds: int):
|
|
now = time.time()
|
|
with self.tx() as db:
|
|
row = db.execute("""SELECT * FROM jobs WHERE
|
|
(status='queued' AND next_at<=?) OR (status='preparing' AND lease_until<=?)
|
|
ORDER BY created_at LIMIT 1""", (now, now)).fetchone()
|
|
if not row:
|
|
return None
|
|
db.execute("""UPDATE jobs SET status='preparing',attempts=attempts+1,
|
|
lease_until=?,updated_at=? WHERE id=?""", (now + lease_seconds, now, row["id"]))
|
|
return self.as_dict(db.execute("SELECT * FROM jobs WHERE id=?", (row["id"],)).fetchone())
|
|
|
|
def prepared(self, job_id: str, attempts: int, page_count: int):
|
|
now = time.time()
|
|
with self.tx() as db:
|
|
row = db.execute("SELECT status,attempts FROM jobs WHERE id=?", (job_id,)).fetchone()
|
|
if not row or row["status"] != "preparing" or row["attempts"] != attempts:
|
|
return False
|
|
db.executemany("INSERT OR IGNORE INTO pages(job_id,page_no,status) VALUES(?,?,'queued')",
|
|
[(job_id, n) for n in range(1, page_count + 1)])
|
|
db.execute("UPDATE jobs SET status='processing',total_pages=?,lease_until=0,error=NULL,updated_at=? WHERE id=?",
|
|
(page_count, now, job_id))
|
|
return True
|
|
|
|
def prepare_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 status=?,error=?,next_at=?,lease_until=0,
|
|
callback_state=CASE WHEN ? AND callback_url IS NOT NULL THEN 'pending' ELSE callback_state END,
|
|
updated_at=? WHERE id=? AND status='preparing' AND attempts=?""",
|
|
("failed" if terminal else "queued", error[:1000], now + retry_delay(attempts),
|
|
int(terminal), now, job_id, attempts))
|
|
|
|
def claim_page(self, lease_seconds: int, global_limit: int):
|
|
now = time.time()
|
|
with self.tx() as db:
|
|
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<=?)
|
|
OR (p.status='running' AND p.lease_until<=?))
|
|
ORDER BY (SELECT count(*) FROM pages active
|
|
WHERE active.job_id=p.job_id AND active.status='running' AND active.lease_until>?),
|
|
p.next_at,j.created_at,p.page_no LIMIT 1""", (now, now, now)).fetchone()
|
|
if not row:
|
|
return None
|
|
db.execute("""UPDATE pages SET status='running',attempts=attempts+1,lease_until=?
|
|
WHERE job_id=? AND page_no=?""", (now + lease_seconds, row["job_id"], row["page_no"]))
|
|
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
|
|
WHERE job_id=? AND page_no=? AND status='running' AND attempts=?""",
|
|
(json.dumps(result, ensure_ascii=False), job_id, page_no, attempts)).rowcount == 1
|
|
|
|
def page_failed(self, job_id: str, page_no: int, attempts: int, error: str,
|
|
truncated: bool, max_attempts: int):
|
|
now = time.time()
|
|
terminal = attempts >= max_attempts
|
|
with self.tx() as db:
|
|
db.execute("""UPDATE pages SET status=?,error=?,next_at=?,lease_until=0,
|
|
penalize_repetition=CASE WHEN ? THEN 1 ELSE penalize_repetition END
|
|
WHERE job_id=? AND page_no=? AND status='running' AND attempts=?""",
|
|
("failed" if terminal else "queued", error[:1000], now + retry_delay(attempts),
|
|
int(truncated), job_id, page_no, attempts))
|
|
|
|
def claim_finalize(self, lease_seconds: int):
|
|
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 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()
|
|
if not row:
|
|
return None
|
|
db.execute("""UPDATE jobs SET status='finalizing',finalize_attempts=finalize_attempts+1,
|
|
lease_until=?,updated_at=? WHERE id=?""", (now + lease_seconds, now, row["id"]))
|
|
return self.as_dict(db.execute("SELECT * FROM jobs WHERE id=?", (row["id"],)).fetchone())
|
|
|
|
def page_results(self, job_id: str):
|
|
with self.connect() as db:
|
|
return [self.as_dict(row) for row in db.execute("""SELECT page_no,status,error,result_json
|
|
FROM pages WHERE job_id=? ORDER BY page_no""", (job_id,))]
|
|
|
|
def finalized(self, job_id: str, attempts: int, result_json: str, has_failures: bool):
|
|
now = time.time()
|
|
with self.tx() as db:
|
|
return db.execute("""UPDATE jobs SET status=?,result_path=NULL,result_json=?,error=NULL,lease_until=0,updated_at=?,
|
|
callback_state=CASE WHEN callback_url IS NOT NULL THEN 'pending' ELSE 'none' END
|
|
WHERE id=? AND status='finalizing' AND finalize_attempts=?""",
|
|
("partial_failed" if has_failures else "completed", result_json, now, job_id, attempts)).rowcount == 1
|
|
|
|
def finalize_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 status=?,error=?,next_at=?,lease_until=0,updated_at=?,
|
|
callback_state=CASE WHEN ? AND callback_url IS NOT NULL THEN 'pending' ELSE callback_state END
|
|
WHERE id=? AND status='finalizing' AND finalize_attempts=?""",
|
|
("failed" if terminal else "processing", error[:1000], now + retry_delay(attempts),
|
|
now, int(terminal), job_id, attempts))
|
|
|
|
def claim_callback(self, lease_seconds: int):
|
|
now = time.time()
|
|
with self.tx() as db:
|
|
row = db.execute("""SELECT * FROM jobs WHERE status IN ('completed','partial_failed','failed')
|
|
AND ((callback_state='pending' AND callback_next_at<=?)
|
|
OR (callback_state='sending' AND callback_lease_until<=?))
|
|
ORDER BY created_at LIMIT 1""", (now, now)).fetchone()
|
|
if not row:
|
|
return None
|
|
db.execute("""UPDATE jobs SET callback_state='sending',callback_attempts=callback_attempts+1,
|
|
callback_lease_until=? WHERE id=?""", (now + lease_seconds, row["id"]))
|
|
return self.as_dict(db.execute("SELECT * FROM jobs WHERE id=?", (row["id"],)).fetchone())
|
|
|
|
def callback_done(self, job_id: str, attempts: int):
|
|
with self.tx() as db:
|
|
db.execute("""UPDATE jobs SET callback_state='delivered',callback_error=NULL,
|
|
callback_lease_until=0 WHERE id=? AND callback_state='sending' AND callback_attempts=?""",
|
|
(job_id, attempts))
|
|
|
|
def callback_failed(self, job_id: str, attempts: int, error: str, max_attempts: int):
|
|
now = time.time()
|
|
with self.tx() as db:
|
|
db.execute("""UPDATE jobs SET callback_state=?,callback_error=?,callback_next_at=?,
|
|
callback_lease_until=0 WHERE id=? AND callback_state='sending' AND callback_attempts=?""",
|
|
("exhausted" if attempts >= max_attempts else "pending", error[:1000],
|
|
now + retry_delay(attempts), job_id, attempts))
|