13 Commits

Author SHA1 Message Date
fcf3188607 Merge pull request 'Fix worker db' (#4) from feat/kie-qwen-page-routing into main
Reviewed-on: thaian02/parsing-service#4
2026-09-29 05:49:27 +00:00
498a22ab61 Fix worker db 2026-09-29 05:39:45 +00:00
d2325f3102 Merge pull request 'feat/kie-qwen-page-routing' (#3) from feat/kie-qwen-page-routing into main
Reviewed-on: thaian02/parsing-service#3
2026-09-29 01:31:14 +00:00
73c51ed1cd SERVICE.md: hướng dẫn chạy compose trên máy không có mạng
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 13:59:26 +00:00
0ac9a5c0fb Triển khai toàn bộ service bằng một docker compose
chandra + kie (vLLM, weights mount từ CHANDRA_MODEL_DIR/KIE_MODEL_DIR) và
api + worker (image build từ Dockerfile, network_mode host, đọc .env) thay cho
hai tmux run-api.sh/run-worker.sh và docker run chandra riêng. Worker mount
native-hdfs của gói portable, đợi hai model healthy mới nhận trang. GPU chọn
bằng GPU_DEVICE (driver nvidia) thay cho CDI GPU_UUID.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 13:40:05 +00:00
3cbba8bd79 Worker không chết vì SQLite locked, trang trắng không bị coi là lỗi
- tx(): chỉ ROLLBACK khi đang có transaction; BEGIN IMMEDIATE hết busy_timeout
  trước đây ném "cannot rollback - no transaction is active" che mất lỗi gốc.
- Luồng OCR/callback/coordinator chạy qua Worker.loop: lỗi được log.exception
  rồi thử lại, không còn giết luồng vĩnh viễn.
- OCR: model trả rỗng (trang trắng) thành trang không có block; output không
  parse được thì kèm 200 ký tự đầu vào thông báo lỗi.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 13:40:05 +00:00
a173348380 Nâng sàn PyMuPDF lên 1.28.2
1.27.x render đen phần lớn trang PDF scan ghép từ dải ảnh Indexed, làm
Chandra trả text lặp và KIE đọc ảnh đen.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-25 04:15:58 +00:00
b6719886f5 docker compose: dựng Chandra v2 và Qwen KIE trên cùng một card
Chandra giữ image v2 và biến PORT/GPU_UTIL cũ; thêm service kie (vLLM
0.23, weights từ volume qwen35_4b, tắt thinking) khởi động sau khi chandra
healthy. Mặc định GPU_UTIL 0.55 + KIE_GPU_UTIL 0.3, đo ~80% card H200.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-25 04:15:58 +00:00
904134a224 KIE: bóc 2 lượt theo trang, mặc định Qwen3.5-4B
- Lượt 1: document_type, document_number, issued_date, issuing_authority,
  title chỉ trên 3 trang đầu.
- Lượt 2: signer chỉ trên trang DLA có Signature/Stamp; ưu tiên trang có
  Stamp trong thân trang (bỏ dấu giáp lai ở dải 10% mép), tối đa
  IDP_KIE_MAX_PAGES trang cuối; không có trang nào thì không gọi model.
- Viết lại description các trường theo yêu cầu nghiệp vụ.
- normalize_answer nhận signer trả về dạng mảng.
- IDP_KIE_URL/IDP_KIE_MODEL mặc định trỏ Qwen3.5-4B cổng 9224, không còn
  dùng chung model OCR (Chandra DLA sinh JSON lan man khi làm KIE).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-25 04:15:58 +00:00
2039ddb487 Merge pull request 'Fix callback worker' (#2) from feat/kie-extraction into main
Reviewed-on: thaian02/parsing-service#2
2026-09-25 02:34:30 +00:00
65c4f44e28 Fix callback worker 2026-09-25 09:30:26 +07:00
bc4d07333e Merge pull request 'feat/kie-extraction' (#1) from feat/kie-extraction into main
Reviewed-on: thaian02/parsing-service#1
2026-09-24 08:17:45 +00:00
79b70bed12 Fix flow 2026-09-24 14:27:43 +07:00
15 changed files with 772 additions and 162 deletions

5
.dockerignore Normal file
View File

@@ -0,0 +1,5 @@
*
!requirements-runtime.txt
!pyproject.toml
!idp_service
idp_service/__pycache__

42
.env.example Normal file
View File

@@ -0,0 +1,42 @@
# docker compose đọc file này (đổi tên thành .env) cho cả biến của compose lẫn env của api/worker.
# --- Model (compose) ---
GPU_DEVICE=0 # index hoặc UUID card, như `docker run --gpus device=0`
KIE_MODEL_DIR=./qwen35-4b-model # mkdir -p qwen35-4b-model; tar -xf qwen35-4b-weights.tar -C qwen35-4b-model
GPU_UTIL=0.55 # chandra; GPU_UTIL + KIE_GPU_UTIL < phần card còn trống
KIE_GPU_UTIL=0.3
MAX_MODEL_LEN=32768 # chandra; cấu hình cũ 98304 cần thêm KV cache GPU
MAX_NUM_SEQS=128
MAX_BATCHED_TOKENS=65536
PORT=9222
KIE_PORT=9224
# IMAGE_TAG=chandra-dla-api:v2-20260906-024126
# APP_IMAGE=idp-parsing-service:0.2.0
# --- HDFS native (worker) ---
HDFS_NATIVE_DIR=/root/idp-portable/native-hdfs # bin/hdfs, conf/krb5.conf, conf/*.keytab
IDP_STORAGE=hdfs_cli
IDP_HDFS_NATIVE_URI=hdfs://vptwd
HDFS_PRINCIPAL=searchengine@DATALAKE.DCS.VN
# --- Service ---
IDP_HOST=0.0.0.0
IDP_PORT=8001
IDP_API_KEY= # bắt buộc đặt khi API mở ra mạng
IDP_CALLBACK_HOSTS=10.1.18.104
NO_PROXY=127.0.0.1,localhost,10.1.18.54,10.1.18.104
IDP_CALLBACK_BASIC_USER=callback_handler
IDP_CALLBACK_BASIC_PASSWORD=change-me
IDP_DATA_DIR=/data/idp-runtime # SQLite + file làm việc; đĩa local, không NFS
IDP_OCR_URL=http://127.0.0.1:9222/v1/chat/completions
IDP_OCR_MODEL=chandra
IDP_KIE_URL=http://127.0.0.1:9224/v1/chat/completions
IDP_KIE_MODEL=qwen3.5-4b
IDP_OCR_WORKERS=64
IDP_OCR_TIMEOUT=180
IDP_LEASE_SECONDS=1800
IDP_VOFFICE_DECRYPT_MODE=auto
IDP_VOFFICE_DES_KEY_HEX=a1e3c21919adeeab

3
.gitignore vendored
View File

@@ -4,7 +4,10 @@ __pycache__/
.pytest_cache/ .pytest_cache/
*.egg-info/ *.egg-info/
export/ export/
qwen35-4b-model/
idp_parsing_service.egg-info/ 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
native-hdfs/

15
Dockerfile Normal file
View File

@@ -0,0 +1,15 @@
FROM python:3.11-slim
# kinit cho client HDFS native (Kerberos) mount từ gói portable vào /opt/native-hdfs.
RUN apt-get update \
&& DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends krb5-user \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /app
COPY requirements-runtime.txt .
RUN pip install --no-cache-dir -r requirements-runtime.txt
COPY pyproject.toml .
COPY idp_service idp_service
RUN pip install --no-cache-dir --no-deps .
ENV PYTHONUNBUFFERED=1

View File

@@ -7,9 +7,9 @@ hoặc nhận qua `callback_url`. Có hai cách nạp đầu vào:
* `POST /parse` — upload thẳng file PDF bằng `multipart/form-data`. * `POST /parse` — upload thẳng file PDF bằng `multipart/form-data`.
* `POST /process` — Airflow ghi file lên HDFS xong rồi gửi đường dẫn (hợp đồng cũ). * `POST /process` — Airflow ghi file lên HDFS xong rồi gửi đường dẫn (hợp đồng cũ).
Worker lấy PDF, chia task theo trang, gọi Chandra, validate, lưu bundle vào job Worker lấy PDF, chia task theo trang, gọi Chandra (DLA), bóc trường bằng
và callback. Nhiều PDF cùng dùng một hàng đợi trang và một giới hạn tổng số Qwen3.5-4B (KIE), validate, lưu bundle vào job và callback. Nhiều PDF cùng dùng
request OCR. một hàng đợi trang và một giới hạn tổng số 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
@@ -19,8 +19,9 @@ cho từng trang để biết trang nào lỗi khi job `partial_failed`, và kh
## Bóc trường (KIE) ## 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** để Sau khi mọi trang OCR xong, worker gọi model KIE (mặc định Qwen3.5-4B, serve riêng
bóc các trường cố định dưới đây, rồi mới finalize: với Chandra) thêm **hai 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 | | Trường | Ý nghĩa |
|---|---| |---|---|
@@ -28,19 +29,33 @@ bóc các trường cố định dưới đây, rồi mới finalize:
| `document_number` | Số, ký hiệu 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` | | `issued_date` | Ngày ban hành, định dạng `dd/mm/yyyy` |
| `issuing_authority` | Cơ quan ban hành | | `issuing_authority` | Cơ quan ban hành |
| `title` | Tên/trích yếu văn bản | | `title` | Tên/tiêu đề văn bản |
| `signer.name` | Họ tên người ký | | `signer.name` | Họ tên người ký |
| `signer.position` | Chức vụ 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 Prompt nằm trong `idp_service/kie.py`, khung 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 `IDP-Training-Pipeline/scripts/data/kie_prompts/extract_vi.txt`; schema cố định,
fine-tune gặp đúng định dạng đã train. Khác ở chỗ schema cố định, không qua lượt 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ì
GLM đề xuất schema. Muốn đổi trường hoặc quy ước của một trường thì sửa `SCHEMA` sửa `SCHEMA` trong file đó; quy ước riêng nằm trong `description` của chính trường:
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ì - `document_type` chỉ lấy tên loại ("THÔNG BÁO LÃI SUẤT CHO VAY" → "THÔNG BÁO"),
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. `title` lấy trích yếu hoặc phần sau tên loại, bỏ dòng "Kính gửi" và ghi chú.
- `issuing_authority` chép đủ các dòng tên cơ quan ở góc trên bên trái, kể cả cơ
quan chủ quản; không lấy quốc hiệu, tiêu ngữ.
- `signer` là người có thẩm quyền ký ban hành, bỏ người lập, người thẩm định, chữ
ký nháy, khối sao y; `position` chép đủ các dòng chức vụ, giữ `KT.`/`TM.`/`TL.`.
- Ngày về `dd/mm/yyyy`, số ký hiệu bỏ nhãn "Số:".
Trang gửi cho mỗi lượt được chọn cứng:
- Lượt 1 (`document_type`, `document_number`, `issued_date`, `issuing_authority`,
`title`): chỉ **3 trang đầu**.
- Lượt 2 (`signer.name`, `signer.position`): chỉ các trang mà DLA trả block
`Signature` hoặc `Stamp`. Chữ ký nháy và dấu giáp lai (đóng ở mép trái/phải) có
thể nằm trên mọi trang, nên nếu có trang mà bbox `Stamp` nằm trong thân trang
(không nằm gọn trong dải 10% mép trái/phải) thì chỉ gửi các trang đó. Giữ tối đa
`IDP_KIE_MAX_PAGES` trang cuối. Không trang nào có chữ ký/con dấu thì không gọi
model, `signer` để null.
Kết quả nằm ở `extraction` trong bundle và ở `GET /jobs/{job_id}/extraction` 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): (có ngay sau bước extract, không phải đợi finalize):
@@ -99,43 +114,6 @@ curl -s http://127.0.0.1:8080/jobs/JOB_ID/result > out.json
`infer.py` là công cụ thử nghiệm độc lập và cần Pillow khi xử lý ảnh. Pillow `infer.py` là công cụ thử nghiệm độc lập và cần Pillow khi xử lý ảnh. Pillow
không nằm trong runtime của service PDF. không nằm trong runtime của service PDF.
### Cài offline trên máy khác
Nếu máy đích không có Internet và cần mang cả Python lẫn virtualenv, dùng gói
`export/idp-portable-linux-x86_64-py311.tar.gz`:
```bash
tar -xzf idp-portable-linux-x86_64-py311.tar.gz
cd idp-portable
cp .env.example .env
# Sửa các hostname, đường dẫn và khóa trong .env
./run-api.sh
# Terminal/process khác:
./run-worker.sh
```
Gói tự chứa CPython 3.11 và toàn bộ runtime, không cần chạy `pip install`.
Hai script tự đọc file `.env` cạnh chúng. Có thể dùng file ở vị trí khác bằng
`IDP_ENV_FILE=/etc/idp/service.env ./run-api.sh`. File dùng cú pháp biến môi
trường của shell; giá trị có khoảng trắng phải đặt trong dấu nháy. Chỉ cấp quyền
đọc file cho tài khoản chạy service vì file chứa API key và khóa giải mã.
Nó chỉ dùng được trên Linux x86_64 có glibc tương thích (PyMuPDF yêu cầu
manylinux 2.28). Có thể chuyển thư mục đã giải nén tới vị trí khác.
Nếu máy đích đã có Python 3.11, bản wheel nhỏ hơn nằm ở
`export/idp-runtime-linux-x86_64-py311.tar.gz`:
Thư mục `export/runtime-wheels` chứa wheel của service và toàn bộ dependency cho
Linux x86_64, CPython 3.11. Chép cả thư mục sang máy đích rồi chạy:
```bash
python3.11 -m pip install --no-index --find-links runtime-wheels \
idp-parsing-service[hdfs]==0.1.0
```
Wheel có native code (`PyMuPDF`, `PyCryptodome`, `pydantic-core`) nên phải tạo
lại bộ export nếu máy đích khác kiến trúc hoặc phiên bản Python.
Gửi job từ đường dẫn HDFS sau khi PDF đã ghi xong: Gửi job từ đường dẫn HDFS sau khi PDF đã ghi xong:
```bash ```bash
@@ -148,6 +126,111 @@ curl http://127.0.0.1:8080/jobs/JOB_ID/pages
Khi đặt `IDP_API_KEY`, mọi endpoint job cần header `X-API-Key`. Khi đặt `IDP_API_KEY`, mọi endpoint job cần header `X-API-Key`.
## Triển khai bằng docker compose
Một file `docker-compose.yaml` dựng đủ 4 container trên **một host, một card GPU**:
| Service | Container | Việc | Cổng |
|---|---|---|---|
| `chandra` | `chandra-ocr` | DLA/OCR từng trang (vLLM, image `IMAGE_TAG`) | `PORT` (9222) |
| `kie` | `qwen-kie` | Bóc trường Qwen3.5-4B (cùng image vLLM với Chandra) | `KIE_PORT` (9224) |
| `api` | `idp-api` | HTTP API (image build từ `Dockerfile`) | `IDP_PORT` (8001) |
| `worker` | `idp-worker` | Hàng đợi trang, KIE, finalize, callback, tải PDF từ HDFS | — |
Image `chandra-dla-api:v2-20260906-024126` đã chứa vLLM 0.23.0 và weight Chandra.
Service `kie` cũng dùng image này, nhưng mount weight Qwen3.5-4B từ host lên `/model`.
Vì `qwen35-4b-weights.tar` đã được tải lên server riêng, thư mục dự án mang đi
không chứa 8.8 GB weight. `deploy-offline.sh` sẽ kiểm tra SHA-256 và giải nén
archive trên server vào `qwen35-4b-model/`. Thư mục dự án có sẵn archive image
API trong `export/` và file `.env`; hai mục này bị Git bỏ qua, vì vậy hãy chuyển
**cả thư mục trên đĩa** (ví dụ bằng `rsync`), không chỉ `git clone`.
Trước khi chạy, kiểm tra `.env`, đặc biệt `KIE_MODEL_DIR=./qwen35-4b-model`, GPU,
API key và `HDFS_NATIVE_DIR`. Gói HDFS native không có trong thư mục dự án: server
phải có thư mục `/root/idp-portable/native-hdfs` (hoặc chỉnh `HDFS_NATIVE_DIR` trong
`.env`) chứa `bin/hdfs`, `conf/krb5.conf` và keytab.
Nếu `chandra-ocr` đang chạy từ compose cũ, dừng stack cũ trước khi khởi động
compose mới để giải phóng tên container và cổng 9222.
Sau khi chuyển thư mục, chạy một lệnh trên server (thay đường dẫn bằng vị trí
archive Qwen đã upload):
```bash
bash deploy-offline.sh /duong/dan/qwen35-4b-weights.tar
```
Script nạp image API từ `export/`, giải nén Qwen nếu cần, rồi chạy Compose với
`--wait` để chỉ báo thành công khi cả bốn container healthy. Mặc định chờ tối đa
30 phút cho hai model tải lên GPU; có thể đổi bằng `DEPLOY_WAIT_SECONDS`. Các lần
sau có thể chạy trực tiếp `docker compose up -d --no-build --pull never --wait`.
Cả bốn service dùng `restart: unless-stopped`: Docker tự khởi động lại container
khi tiến trình chính thoát hoặc daemon khởi động lại. API có healthcheck kiểm tra
HTTP và SQLite; worker kiểm tra SQLite cùng HDFS client/keytab; hai model kiểm tra
`/health`. Healthcheck chuyển trạng thái sang `unhealthy` nhưng Docker Compose
**không tự restart container chỉ vì unhealthy**. Nếu service bị treo mà tiến trình
chưa thoát, cần cảnh báo/giám sát bên ngoài. Worker sẽ thoát nếu một luồng xử lý
chết bất thường để Docker có thể khởi động lại container. Job đang chạy được lưu
trong SQLite và thử lại sau khi lease hết hạn (`IDP_LEASE_SECONDS`, mặc định 1800 giây).
Nếu server có mạng và muốn build lại image API từ source, sau khi Qwen đã giải
nén thì dùng:
```bash
docker compose up -d --build
```
Nếu muốn tự giải nén Qwen trước khi chạy Compose, dùng:
```bash
# Chạy trong thư mục parsing-service; archive có thể nằm ở nơi khác trên server.
echo '65efebd5f15f4db7dac8053bedbb8f38a75d1ac1c11b410db7691d308802bd13 /duong/dan/qwen35-4b-weights.tar' | sha256sum -c -
mkdir -p qwen35-4b-model
tar -xf /duong/dan/qwen35-4b-weights.tar -C qwen35-4b-model
test -f qwen35-4b-model/config.json
test -f qwen35-4b-model/model.safetensors.index.json
```
Sau khi chạy Compose:
```bash
docker compose ps # chandra/kie healthy thì worker mới khởi động
curl -f http://127.0.0.1:9222/health
curl -f http://127.0.0.1:9224/health
```
`.env` vừa cấp biến cho compose vừa là env của `api`/`worker`, nên các biến `IDP_*`
giữ nguyên như khi chạy `run-api.sh`/`run-worker.sh`. Những biến riêng của compose:
- `GPU_DEVICE`: index hoặc UUID card (như `docker run --gpus device=0`). Hai model
chia card bằng `GPU_UTIL` (0.55) và `KIE_GPU_UTIL` (0.3), thực đo ~80% card H200;
`kie` chỉ khởi động sau khi `chandra` healthy để hai vLLM không đo bộ nhớ cùng lúc.
- `KIE_MODEL_DIR`: thư mục weight Qwen trên host, mount chỉ đọc vào `/model` của
container `kie`. Thư mục giải nén từ `qwen35-4b-weights.tar` không chứa symlink
ra ngoài. Chandra dùng weight đã nhúng trong image, không cần mount từ host.
- `HDFS_NATIVE_DIR`: thư mục `native-hdfs` của gói portable (Java, Hadoop client,
`conf/krb5.conf`, keytab), mount chỉ đọc vào worker ở `/opt/native-hdfs`; image
đã có `kinit`. Chỉ cần khi `IDP_STORAGE=hdfs_cli`.
- `IDP_DATA_DIR`: mount cùng đường dẫn vào `api` và `worker` để hai bên dùng chung
SQLite; phải là đĩa local.
`api`/`worker` chạy `network_mode: host` nên gọi model qua `127.0.0.1:9222`/`9224`
và phân giải namenode/KDC theo `/etc/hosts` của host, y như khi chạy bằng script.
Kiểm tra HDFS trong container: `docker compose exec worker hdfs dfs -ls /`.
Máy đích không có Internet: `build` service API cần mạng (base `python:3.11-slim`, apt,
PyPI), nên build ở máy có mạng rồi mang image sang. Máy đích cần hai image:
`idp-parsing-service:0.2.0` (đã đóng trong `export/`) và
`chandra-dla-api:v2-20260906-024126` (đã mang sang trước đó), cộng với thư mục
`qwen35-4b-weights.tar` đã upload riêng trên server.
```bash
# Nếu không dùng deploy-offline.sh, nạp image API từ thư mục dự án:
cd export && sha256sum -c idp-parsing-service-0.2.0.tar.gz.sha256 && cd ..
docker load -i export/idp-parsing-service-0.2.0.tar.gz
docker compose up -d --no-build --pull never
```
## Cấu hình ## Cấu hình
| Biến | Mặc định | Ý nghĩa | | Biến | Mặc định | Ý nghĩa |
@@ -161,17 +244,21 @@ 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_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_URL` | `http://localhost:9224/v1/chat/completions` | API vLLM của model KIE |
| `IDP_KIE_MODEL` | theo `IDP_OCR_MODEL` | Tên model KIE | | `IDP_KIE_MODEL` | `qwen3.5-4b` | Tên model KIE |
| `IDP_KIE_MAX_PAGES` | `5` | Số ảnh tối đa gửi một lượt KIE; quá thì lấy các trang đầu và trang cuối | | `IDP_KIE_MAX_PAGES` | `5` | Số trang có chữ ký/con dấu tối đa gửi lượt bóc người ký; quá thì lấy các trang cuối |
| `IDP_KIE_TIMEOUT` | `300` | Timeout một lượt KIE, giây | | `IDP_KIE_TIMEOUT` | `300` | Timeout một lượt KIE, giây |
| `IDP_KIE_MAX_TOKENS` | `2048` | Giới hạn số token đầu ra của mỗi request KIE; độc lập với `--max-model-len` của vLLM |
| `IDP_MAX_KIE_ATTEMPTS` | `3` | Số lần thử bóc trường mỗi tài liệu | | `IDP_MAX_KIE_ATTEMPTS` | `3` | Số lần thử bóc trường mỗi tài liệu |
| `IDP_RUN_WORKER` | `0` | `1` chạy worker ngay trong process API | | `IDP_RUN_WORKER` | `0` | `1` chạy worker ngay trong process API |
| `IDP_OCR_WORKERS` | `64` | Giới hạn tổng request tới GPU, lưu bằng SQLite | | `IDP_OCR_WORKERS` | `64` | Giới hạn tổng request tới GPU, lưu bằng SQLite. Mỗi luồng giữ khoá ghi SQLite khi nhận việc; log nhiều `database is locked` thì hạ xuống 16–32 |
| `IDP_CALLBACK_WORKERS` | `4` | Số luồng gửi callback độc lập; callback lỗi không giữ luồng chuẩn bị/finalize job |
| `IDP_OCR_TIMEOUT` | `180` | Timeout mỗi request OCR, giây | | `IDP_OCR_TIMEOUT` | `180` | Timeout mỗi request OCR, giây |
| `IDP_LEASE_SECONDS` | `1800` | Lease task; phải lớn hơn timeout và thời gian chuẩn bị/finalize | | `IDP_LEASE_SECONDS` | `1800` | Lease task; phải lớn hơn timeout và thời gian chuẩn bị/finalize |
| `IDP_MAX_PAGE_ATTEMPTS` | `3` | Số lần thử OCR mỗi trang | | `IDP_MAX_PAGE_ATTEMPTS` | `3` | Số lần thử OCR mỗi trang |
@@ -186,7 +273,7 @@ native RPC, Kerberos và HA nên chọn `IDP_STORAGE=hdfs_cli`, đặt
`IDP_HDFS_NATIVE_URI=hdfs://vptwd` và `IDP_HDFS_NATIVE_URI=hdfs://vptwd` và
`HDFS_PRINCIPAL=searchengine@DATALAKE.DCS.VN`. Gói portable đã kèm Java, Hadoop `HDFS_PRINCIPAL=searchengine@DATALAKE.DCS.VN`. Gói portable đã kèm Java, Hadoop
client, `core-site.xml`, `hdfs-site.xml`, `krb5.conf` và keytab; client, `core-site.xml`, `hdfs-site.xml`, `krb5.conf` và keytab;
`run-worker.sh` tự thêm client vào `PATH` và đăng nhập bằng keytab. Giữ quyền container `worker` tự thêm client vào `PATH` và trỏ `KRB5_CONFIG`/`HDFS_KEYTAB` vào đó. Giữ quyền
đọc keytab ở mức `600`. API và worker phải có quyền đọc keytab ở mức `600`. API và worker phải có quyền
truy cập cùng SQLite; chỉ đặt SQLite trên **một host với đĩa bền vững**, không đặt truy cập cùng SQLite; chỉ đặt SQLite trên **một host với đĩa bền vững**, không đặt
trên HDFS/NFS. Nếu cần chạy nhiều host, thay job store bằng PostgreSQL trước. trên HDFS/NFS. Nếu cần chạy nhiều host, thay job store bằng PostgreSQL trước.
@@ -194,8 +281,8 @@ trên HDFS/NFS. Nếu cần chạy nhiều host, thay job store bằng PostgreSQ
Kiểm tra HDFS native ngay trên máy triển khai trước khi chạy worker: Kiểm tra HDFS native ngay trên máy triển khai trước khi chạy worker:
```bash ```bash
./test-hdfs.sh / docker compose exec worker hdfs dfs -ls /
./test-hdfs.sh /data/bronze/incoming docker compose exec worker hdfs dfs -ls /data/bronze/incoming
``` ```
Máy triển khai phải phân giải được hostname trong file cấu hình, kết nối được Máy triển khai phải phân giải được hostname trong file cấu hình, kết nối được
@@ -250,6 +337,12 @@ Callback gửi `{ "dag_run_id": "...", "conf": { "request_id": "...", "job_id":
header `Idempotency-Key: job_id`. Nếu không truyền `dag_run_id`, service dùng header `Idempotency-Key: job_id`. Nếu không truyền `dag_run_id`, service dùng
`job_id` làm giá trị ổn định khi retry. Callback được retry độc lập với OCR, tối đa `job_id` làm giá trị ổn định khi retry. Callback được retry độc lập với OCR, tối đa
`IDP_MAX_CALLBACK_ATTEMPTS` lần; Airflow nên xử lý callback lặp idempotently. `IDP_MAX_CALLBACK_ATTEMPTS` lần; Airflow nên xử lý callback lặp idempotently.
Nếu Airflow trả `409` vì DAG run đã tồn tại, worker gọi GET DAG run đó và chỉ
đánh dấu callback đã giao khi `dag_run_id`, `job_id` và `request_id` đều khớp.
Xung đột với job khác vẫn được ghi là lỗi callback.
Nếu Airflow yêu cầu Basic Auth, đặt cả `IDP_CALLBACK_BASIC_USER` và
`IDP_CALLBACK_BASIC_PASSWORD` trong `.env` của API/worker; worker gửi header
`Authorization: Basic ...` cùng request callback.
Trạng thái `callback_state=exhausted` cho biết cần xử lý thủ công; bundle vẫn Trạng thái `callback_state=exhausted` cho biết cần xử lý thủ công; bundle vẫn
đọc được qua `GET /jobs/{job_id}/result`. đọc được qua `GET /jobs/{job_id}/result`.
@@ -261,11 +354,11 @@ sau. Job chỉ `completed` khi mọi trang hợp lệ. Nếu còn trang lỗi sa
## Giới hạn hiện tại ## Giới hạn hiện tại
HDFS và Chandra chưa chạy ở môi trường này, nên bài test tự động dùng PDF local Bài test tự động dùng PDF local và model giả lập. Bước bóc trường mới được thử
và OCR giả lập; luồng upload được kiểm end to end bằng `IDP_OCR_BACKEND=pdf_text`. tay trên 4 văn bản (quyết định, thông báo, xác nhận, báo cáo 13 trang), chưa có bộ
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; schema 7 trường chưa qua vòng nghiệm thu nên quy ước trong `SCHEMA` còn có thể
đ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 phải chỉnh. Qwen3.5-4B còn đọc sai tên khắc trên dấu tên, và vẫn lấy quốc hiệu làm
ước từng trường trong `SCHEMA` còn có thể phải chỉnh sau khi đối chiếu kết quả. cơ quan ban hành khi văn bản không có tên cơ quan ở góc trên bên trái.
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 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 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ó

51
deploy-offline.sh Executable file
View File

@@ -0,0 +1,51 @@
#!/usr/bin/env bash
# Run all services on a server that already has the Chandra image loaded.
set -euo pipefail
ROOT="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
cd "${ROOT}"
test -f .env || { echo "Missing .env (copy and configure .env.example)" >&2; exit 1; }
MODEL_DIR="${ROOT}/qwen35-4b-model"
ARCHIVE="${1:-${KIE_WEIGHTS_ARCHIVE:-${ROOT}/qwen35-4b-weights.tar}}"
EXPECTED_SHA256="65efebd5f15f4db7dac8053bedbb8f38a75d1ac1c11b410db7691d308802bd13"
if [[ ! -d "${MODEL_DIR}" ]]; then
test -f "${ARCHIVE}" || { echo "Missing Qwen archive: ${ARCHIVE}" >&2; exit 1; }
actual_sha256="$(sha256sum "${ARCHIVE}" | cut -d ' ' -f 1)"
[[ "${actual_sha256}" == "${EXPECTED_SHA256}" ]] || {
echo "Qwen archive checksum mismatch: ${ARCHIVE}" >&2
exit 1
}
staging_dir="$(mktemp -d "${ROOT}/.qwen35-stage.XXXXXX")"
cleanup() { rm -rf -- "${staging_dir}"; }
trap cleanup EXIT
tar -xf "${ARCHIVE}" -C "${staging_dir}"
for required in config.json model.safetensors.index.json \
model.safetensors-00001-of-00002.safetensors \
model.safetensors-00002-of-00002.safetensors; do
test -s "${staging_dir}/${required}" || { echo "Missing Qwen file: ${required}" >&2; exit 1; }
done
mv -- "${staging_dir}" "${MODEL_DIR}"
trap - EXIT
fi
for required in config.json model.safetensors.index.json \
model.safetensors-00001-of-00002.safetensors \
model.safetensors-00002-of-00002.safetensors; do
test -s "${MODEL_DIR}/${required}" || { echo "Missing Qwen file: ${MODEL_DIR}/${required}" >&2; exit 1; }
done
(cd export && sha256sum -c idp-parsing-service-0.2.0.tar.gz.sha256)
docker load -i export/idp-parsing-service-0.2.0.tar.gz
docker compose config --quiet
docker compose config --images | sort -u | while IFS= read -r image; do
docker image inspect "${image}" >/dev/null || { echo "Missing Docker image: ${image}" >&2; exit 1; }
done
if ! docker compose up -d --no-build --pull never --wait \
--wait-timeout "${DEPLOY_WAIT_SECONDS:-1800}"; then
docker compose ps
echo "Deployment did not reach healthy state; inspect docker compose logs" >&2
exit 1
fi
docker compose ps

View File

@@ -1,24 +1,60 @@
services: # Toàn bộ service trên một host, một card GPU: `cp .env.example .env`, sửa .env, rồi
chandra: # docker compose up -d --build
image: ${IMAGE_TAG:-chandra-dla-api:v2-20260906-024126} #
container_name: chandra-ocr # chandra DLA/OCR từng trang, vLLM cổng ${PORT:-9222}, served name "chandra"
restart: unless-stopped # kie bóc trường Qwen3.5-4B, vLLM cổng ${KIE_PORT:-9224}, served name "qwen3.5-4b"
# api HTTP API cổng ${IDP_PORT:-8001}
# worker hàng đợi trang, KIE, finalize, callback; tải PDF từ HDFS
#
# api/worker chạy network_mode host nên .env giữ nguyên như khi chạy run-api.sh/run-worker.sh:
# IDP_OCR_URL=http://127.0.0.1:9222/..., IDP_KIE_URL mặc định http://localhost:9224/...,
# namenode/KDC phân giải theo /etc/hosts của host.
# kie chỉ khởi động sau khi chandra healthy để hai vLLM không đo bộ nhớ GPU cùng lúc;
# worker đợi cả hai model healthy mới nhận trang.
# Chandra đọc weight nhúng sẵn trong image tại /model. Qwen đọc weight đã giải nén
# từ qwen35-4b-weights.tar tại KIE_MODEL_DIR, dùng cùng image làm runtime vLLM.
gpus: x-gpu: &gpu
- driver: cdi resources:
device_ids: ["nvidia.com/gpu=${GPU_UUID:?dat GPU_UUID trong .env}"] reservations:
devices:
- driver: nvidia
device_ids: ["${GPU_DEVICE:-0}"] # như `docker run --gpus device=0`
capabilities: [gpu]
ipc: host x-vllm-image: &vllm-image ${IMAGE_TAG:-chandra-dla-api:v2-20260906-024126}
shm_size: "16gb"
ports: x-vllm-env: &vllm-env
- "${PORT:-9222}:8000"
environment:
HF_HUB_OFFLINE: "1" HF_HUB_OFFLINE: "1"
TRANSFORMERS_OFFLINE: "1" TRANSFORMERS_OFFLINE: "1"
VLLM_LOGGING_LEVEL: "${VLLM_LOG_LEVEL:-INFO}" VLLM_LOGGING_LEVEL: "${VLLM_LOG_LEVEL:-INFO}"
x-health: &health
test: ["CMD-SHELL", "python3 -c \"import urllib.request; urllib.request.urlopen('http://localhost:8000/health')\""]
interval: 30s
timeout: 5s
retries: 20
start_period: 600s
x-app: &app
image: ${APP_IMAGE:-idp-parsing-service:0.2.0}
build: .
restart: unless-stopped
network_mode: host
env_file: .env
services:
chandra:
image: *vllm-image
pull_policy: never
container_name: chandra-ocr
restart: unless-stopped
deploy: *gpu
ipc: host
shm_size: "16gb"
ports:
- "${PORT:-9222}:8000"
environment: *vllm-env
command: command:
- --model=/model - --model=/model
- --served-model-name=chandra - --served-model-name=chandra
@@ -28,15 +64,95 @@ services:
- --max-model-len=${MAX_MODEL_LEN:-32768} - --max-model-len=${MAX_MODEL_LEN:-32768}
- --max-num-seqs=${MAX_NUM_SEQS:-128} - --max-num-seqs=${MAX_NUM_SEQS:-128}
- --max-num-batched-tokens=${MAX_BATCHED_TOKENS:-65536} - --max-num-batched-tokens=${MAX_BATCHED_TOKENS:-65536}
- --gpu-memory-utilization=${GPU_UTIL:-0.28} - --gpu-memory-utilization=${GPU_UTIL:-0.55}
- --enable-prefix-caching - --enable-prefix-caching
- --seed=42 - --seed=42
# PHẢI khớp lúc train (IMAGE_MAX_TOKEN_NUM=1792) — đổi là bbox lệch. # PHẢI khớp lúc train (IMAGE_MAX_TOKEN_NUM=1792) — đổi là bbox lệch.
- --mm-processor-kwargs={"min_pixels":65536,"max_pixels":1835008} - --mm-processor-kwargs={"min_pixels":65536,"max_pixels":1835008}
healthcheck: *health
kie:
# Dùng runtime vLLM đã có trong image Chandra; mount Qwen đè lên /model.
image: *vllm-image
pull_policy: never
container_name: qwen-kie
restart: unless-stopped
depends_on:
chandra:
condition: service_healthy
deploy: *gpu
ipc: host
shm_size: "8gb"
ports:
- "${KIE_PORT:-9224}:8000"
environment: *vllm-env
volumes:
- type: bind
source: ${KIE_MODEL_DIR:?dat KIE_MODEL_DIR trong .env}
target: /model
read_only: true
bind:
create_host_path: false
command:
- --model=/model
- --served-model-name=qwen3.5-4b
- --host=0.0.0.0
- --port=8000
- --dtype=bfloat16
- --max-model-len=32768
- --max-num-seqs=16
- --max-num-batched-tokens=8192
- --gpu-memory-utilization=${KIE_GPU_UTIL:-0.3}
- --enable-prefix-caching
- --seed=42
# Service cần JSON ngay, không cần khối <think>.
- --default-chat-template-kwargs={"enable_thinking":false}
# Mỗi lượt KIE gửi tới 5 trang; giữ ~1.8k token/ảnh như lúc đo kết quả.
- --mm-processor-kwargs={"min_pixels":65536,"max_pixels":1835008}
healthcheck: *health
api:
<<: *app
container_name: idp-api
environment:
IDP_DATA_DIR: ${IDP_DATA_DIR:-/data/idp-runtime}
volumes:
# Cùng đường dẫn trong và ngoài container; SQLite phải nằm trên đĩa local, không NFS.
- ${IDP_DATA_DIR:-/data/idp-runtime}:${IDP_DATA_DIR:-/data/idp-runtime}
command: ["uvicorn", "idp_service.api:app", "--host=${IDP_HOST:-0.0.0.0}", "--port=${IDP_PORT:-8001}"]
healthcheck: healthcheck:
test: ["CMD-SHELL", "python3 -c \"import urllib.request; urllib.request.urlopen('http://localhost:8000/health')\""] test: ["CMD-SHELL", "python -c \"import urllib.request; urllib.request.urlopen('http://127.0.0.1:${IDP_PORT:-8001}/readyz', timeout=3)\""]
interval: 30s interval: 30s
timeout: 5s timeout: 5s
retries: 20 retries: 3
start_period: 600s start_period: 30s
worker:
<<: *app
container_name: idp-worker
depends_on:
chandra:
condition: service_healthy
kie:
condition: service_healthy
environment:
IDP_DATA_DIR: ${IDP_DATA_DIR:-/data/idp-runtime}
# Như run-worker.sh: client HDFS native (Java, Hadoop, conf, keytab) lấy từ gói portable.
PATH: /opt/native-hdfs/bin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
KRB5_CONFIG: /opt/native-hdfs/conf/krb5.conf
HDFS_KEYTAB: /opt/native-hdfs/conf/searchengine.headless.keytab
volumes:
- ${IDP_DATA_DIR:-/data/idp-runtime}:${IDP_DATA_DIR:-/data/idp-runtime}
- type: bind
source: ${HDFS_NATIVE_DIR:?dat HDFS_NATIVE_DIR trong .env}
target: /opt/native-hdfs
read_only: true
bind:
create_host_path: false
command: ["python", "-m", "idp_service.worker"]
healthcheck:
test: ["CMD-SHELL", "python -c \"import os, shutil, sqlite3; from idp_service.config import Settings; s=Settings(); db=sqlite3.connect(str(s.db_path), timeout=3); db.execute('SELECT 1'); db.close(); assert s.storage != 'hdfs_cli' or (shutil.which('hdfs') and os.access(os.environ.get('HDFS_KEYTAB', ''), os.R_OK))\""]
interval: 30s
timeout: 5s
retries: 3
start_period: 30s

View File

@@ -11,17 +11,21 @@ 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_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_url: str = os.getenv("IDP_KIE_URL", "http://localhost:9224/v1/chat/completions")
kie_model: str = os.getenv("IDP_KIE_MODEL") or os.getenv("IDP_OCR_MODEL", "chandra") kie_model: str = os.getenv("IDP_KIE_MODEL", "qwen3.5-4b")
kie_max_pages: int = int(os.getenv("IDP_KIE_MAX_PAGES", "5")) kie_max_pages: int = int(os.getenv("IDP_KIE_MAX_PAGES", "5"))
kie_timeout: int = int(os.getenv("IDP_KIE_TIMEOUT", "300")) kie_timeout: int = int(os.getenv("IDP_KIE_TIMEOUT", "300"))
kie_max_tokens: int = int(os.getenv("IDP_KIE_MAX_TOKENS", "2048"))
max_kie_attempts: int = int(os.getenv("IDP_MAX_KIE_ATTEMPTS", "3")) max_kie_attempts: int = int(os.getenv("IDP_MAX_KIE_ATTEMPTS", "3"))
run_worker: bool = os.getenv("IDP_RUN_WORKER", "0").lower() in ("1", "true", "yes") run_worker: bool = os.getenv("IDP_RUN_WORKER", "0").lower() in ("1", "true", "yes")
ocr_workers: int = int(os.getenv("IDP_OCR_WORKERS", "64")) ocr_workers: int = int(os.getenv("IDP_OCR_WORKERS", "64"))
callback_workers: int = int(os.getenv("IDP_CALLBACK_WORKERS", "4"))
max_queued_jobs: int = int(os.getenv("IDP_MAX_QUEUED_JOBS", "1000")) max_queued_jobs: int = int(os.getenv("IDP_MAX_QUEUED_JOBS", "1000"))
max_pdf_bytes: int = int(os.getenv("IDP_MAX_PDF_BYTES", str(1024**3))) max_pdf_bytes: int = int(os.getenv("IDP_MAX_PDF_BYTES", str(1024**3)))
max_pages: int = int(os.getenv("IDP_MAX_PAGES", "5000")) max_pages: int = int(os.getenv("IDP_MAX_PAGES", "5000"))

View File

@@ -4,6 +4,7 @@ import sqlite3
import time import time
from contextlib import contextmanager from contextlib import contextmanager
from pathlib import Path from pathlib import Path
from threading import Lock
from uuid import uuid4 from uuid import uuid4
@@ -14,6 +15,9 @@ def retry_delay(attempt: int) -> int:
class Store: class Store:
def __init__(self, path: Path): def __init__(self, path: Path):
self.path = path self.path = path
# Worker threads share this Store. Serialize their write transactions so
# idle queue polling does not make dozens of SQLite writers contend.
self._tx_lock = Lock()
path.parent.mkdir(parents=True, exist_ok=True) path.parent.mkdir(parents=True, exist_ok=True)
self.init() self.init()
@@ -81,12 +85,16 @@ class Store:
@contextmanager @contextmanager
def tx(self): def tx(self):
with self._tx_lock:
db = self.connect() db = self.connect()
try: try:
db.execute("BEGIN IMMEDIATE") db.execute("BEGIN IMMEDIATE")
yield db yield db
db.execute("COMMIT") db.execute("COMMIT")
except BaseException: except BaseException:
# BEGIN IMMEDIATE hết busy_timeout thì chưa có transaction: ROLLBACK lúc đó
# sẽ ném "no transaction is active" và che mất lỗi "database is locked" gốc.
if db.in_transaction:
db.execute("ROLLBACK") db.execute("ROLLBACK")
raise raise
finally: finally:

View File

@@ -1,9 +1,12 @@
"""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. """Bóc 7 trường cơ bản của văn bản hành chính bằng hai lượt model trên ảnh trang.
Prompt giữ nguyên từng byte theo template lượt 2 của IDP-Training-Pipeline Lượt 1 hỏi tên loại, số ký hiệu, ngày, cơ quan, trích yếu trên 3 trang đầu. Lượt 2
hỏi người ký trên các trang mà DLA thấy chữ ký/con dấu (xem `signer_pages`).
Khung 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/ (`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. prompt_kie_extract_vi.txt`); schema tại đây cố định, không qua lượt GLM đề xuất
Khác ở chỗ schema tại đây cố định, không qua lượt GLM đề xuất schema. schema. Quy ước riêng từng trường nằm trong `description`.
Schema chỉ dùng hai kiểu của template: string và object. Thêm list/table/boolean 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. thì phải mở rộng `render_fields` và `normalize_answer` theo template gốc.
@@ -22,26 +25,46 @@ SCHEMA_NAME = "basic-document-v1"
SCHEMA = [ SCHEMA = [
{"key": "document_type", {"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"}, "description": "Tên loại văn bản in hoa ở giữa trang, ví dụ QUYẾT ĐỊNH, THÔNG BÁO, TỜ TRÌNH, BÁO CÁO; "
"chỉ lấy tên loại, bỏ phần nội dung đi sau cùng dòng (\"THÔNG BÁO LÃI SUẤT CHO VAY\" "
"thì lấy \"THÔNG BÁO\"); công văn không in tên loại thì ghi \"CÔNG VĂN\""},
{"key": "document_number", {"key": "document_number",
"description": 'Số, ký hiệu văn bản, ví dụ "123/QĐ-UBND"; bỏ nhãn "Số:" đứng trước'}, "description": 'Số, ký hiệu của chính văn bản, ở góc trên bên trái dưới tên cơ quan, ví dụ "123/QĐ-UBND"; '
'bỏ nhãn "Số:"; không lấy số văn bản được viện dẫn trong nội dung, mã khách hàng, mã hồ sơ'},
{"key": "issued_date", {"key": "issued_date",
"description": "Ngày ban hành văn bản. Định dạng dd/mm/yyyy"}, "description": 'Ngày ban hành ở dòng địa danh, ngày tháng góc trên bên phải, ví dụ "Hà Nội, ngày 03 tháng 3 '
'năm 2025"; không lấy ngày trong phần nội dung. Định dạng dd/mm/yyyy'},
{"key": "issuing_authority", {"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; " "description": "Tên cơ quan, tổ chức ban hành ở góc trên bên trái, phía trên số ký hiệu; chép đủ các dòng "
"bỏ tên cơ quan chủ quản cấp trên nếu có dòng riêng"}, "tên cơ quan ở góc đó, kể cả cơ quan chủ quản, nối bằng dấu cách. Không lấy quốc hiệu CỘNG HÒA "
"XÃ HỘI CHỦ NGHĨA VIỆT NAM, tiêu ngữ hay chức danh, tên cơ quan trong phần nội dung; góc trên "
"bên trái không có tên cơ quan thì để null"},
{"key": "title", {"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; " "description": 'Tên, tiêu đề văn bản: trích yếu nằm ngay dưới tên loại văn bản, thường bắt đầu bằng "Về" '
"chép đúng như trên văn bản, giữ nguyên tiền tố V/v nếu có"}, 'hoặc "V/v", giữ nguyên tiền tố; tên loại và nội dung chung một dòng thì lấy phần sau tên loại '
'("THÔNG BÁO LÃI SUẤT CHO VAY" thì lấy "LÃI SUẤT CHO VAY"). Không lấy dòng "Kính gửi", căn '
'cứ, dòng ghi chú trong ngoặc đơn hay mã số. Chép đúng như trên văn bản'},
{"key": "signer", "type": "object", {"key": "signer", "type": "object",
"description": "Người ký ban hành ở cuối văn bản", "description": "Người có thẩm quyền ký ban hành văn bản, thường ở khối ký cuối cùng và có dấu cơ quan đóng "
"trùm lên chữ ký. Nhiều khối ký thì chỉ lấy người này; bỏ qua người lập, người làm đơn, người "
"thẩm định, chữ ký nháy và khối sao y bản chính",
"fields": [ "fields": [
{"key": "name", "description": "Họ tên người ký; bỏ học hàm, học vị"}, {"key": "name",
"description": 'Họ tên người ký, ghi dưới chữ ký hoặc sau "Đã ký:"; bỏ học hàm, học vị'},
{"key": "position", {"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'}, "description": 'Chức vụ người ký ghi phía trên chữ ký hoặc cạnh tên, ví dụ "GIÁM ĐỐC", '
'"KT. CHỦ TỊCH PHÓ CHỦ TỊCH"; chép đủ các dòng chức vụ nối bằng dấu cách, giữ tiền tố '
'KT., TM., TL., Q.; chép đúng như trên văn bản'},
]}, ]},
] ]
# Lượt 1 hỏi trường đầu văn bản trên 3 trang đầu, lượt 2 hỏi người ký trên trang có chữ ký/con dấu.
HEADER_FIELDS = [item for item in SCHEMA if item["key"] != "signer"]
SIGNER_FIELDS = [item for item in SCHEMA if item["key"] == "signer"]
HEADER_PAGES = 3
SIGN_LABELS = {"Signature", "Stamp"}
STAMP_MARGIN = 100 # dải mép trái/phải (thang bbox 0–1000) nơi đóng dấu giáp lai
# Giống extract_vi.txt của IDP-Training-Pipeline. # 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. 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.
@@ -73,9 +96,9 @@ def render_fields(fields: list[dict], depth: int = 0) -> list[str]:
return lines return lines
def render_prompt(page_count: int) -> str: def render_prompt(page_count: int, fields: list[dict] = SCHEMA) -> str:
pages = PAGE_HINT.format(count=page_count) if page_count > 1 else "" 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))) return PROMPT_TEMPLATE.replace("{pages}", pages).replace("{fields}", "\n".join(render_fields(fields)))
def empty_answer(fields: list[dict] = SCHEMA) -> dict: def empty_answer(fields: list[dict] = SCHEMA) -> dict:
@@ -105,6 +128,9 @@ def normalize_answer(payload: dict, fields: list[dict] = SCHEMA) -> dict:
for item in fields: for item in fields:
value = payload.get(item["key"]) if isinstance(payload, dict) else None value = payload.get(item["key"]) if isinstance(payload, dict) else None
if item.get("fields"): if item.get("fields"):
if isinstance(value, list):
# Model đôi khi bọc object trong mảng (trang có cả khối sao y); lấy người đầu tiên.
value = next((v for v in value if isinstance(v, dict)), {})
answer[item["key"]] = normalize_answer(value if isinstance(value, dict) else {}, item["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): elif isinstance(value, list) and all(isinstance(v, str) for v in value):
answer[item["key"]] = "\n".join(value).strip() or None answer[item["key"]] = "\n".join(value).strip() or None
@@ -121,26 +147,38 @@ def has_any_key(payload: dict, fields: list[dict] = SCHEMA) -> bool:
return any(item["key"] in payload for item in fields) return any(item["key"] in payload for item in fields)
def select_pages(page_count: int, max_pages: int) -> list[int]: def header_pages(page_count: 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ý).""" """Tên loại, số ký hiệu, ngày, cơ quan, trích yếu chỉ bóc trong 3 trang đầu."""
if page_count <= max_pages: return list(range(1, min(page_count, HEADER_PAGES) + 1))
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: def signer_pages(page_blocks: dict[int, list[dict]], max_pages: int) -> list[int]:
page_numbers = select_pages(page_count, settings.kie_max_pages) """Người ký chỉ bóc trên trang DLA thấy chữ ký hoặc con dấu.
prompt = render_prompt(len(page_numbers))
Chữ ký nháy và dấu giáp lai (đóng ở mép trái/phải) có thể nằm trên mọi trang,
nên ưu tiên trang có con dấu nằm trong thân trang, nơi người có thẩm quyền ký
ban hành; không có thì lấy mọi trang có chữ ký/con dấu. Giữ tối đa `max_pages`
trang cuối.
"""
pages = sorted(page_blocks.items())
sealed = [no for no, blocks in pages if any(
block["label"] == "Stamp" and block["bbox"][0] < 1000 - STAMP_MARGIN and block["bbox"][2] > STAMP_MARGIN
for block in blocks)]
signed = [no for no, blocks in pages if any(block["label"] in SIGN_LABELS for block in blocks)]
return (sealed or signed)[-max_pages:]
def ask_model(settings: Settings, pdf_path: Path, page_numbers: list[int], fields: list[dict]) -> dict:
content = [] content = []
for page_no in page_numbers: for page_no in page_numbers:
image, _, _ = render_page(pdf_path, page_no) image, _, _ = render_page(pdf_path, page_no)
content.append({"type": "image_url", "image_url": { content.append({"type": "image_url", "image_url": {
"url": "data:image/png;base64," + base64.b64encode(image).decode("ascii")}}) "url": "data:image/png;base64," + base64.b64encode(image).decode("ascii")}})
content.append({"type": "text", "text": prompt}) content.append({"type": "text", "text": render_prompt(len(page_numbers), fields)})
payload = { payload = {
"model": settings.kie_model, "model": settings.kie_model,
"messages": [{"role": "user", "content": content}], "messages": [{"role": "user", "content": content}],
"max_tokens": 2048, "max_tokens": settings.kie_max_tokens,
"temperature": 0.0, "temperature": 0.0,
"top_p": 0.1, "top_p": 0.1,
} }
@@ -158,6 +196,19 @@ def extract_document(settings: Settings, pdf_path: Path, page_count: int) -> dic
if not isinstance(text, str) or not text.strip(): if not isinstance(text, str) or not text.strip():
raise InvalidOutput(f"Empty KIE answer (finish_reason={finish_reason})") raise InvalidOutput(f"Empty KIE answer (finish_reason={finish_reason})")
answer = parse_model_json(text) answer = parse_model_json(text)
if not has_any_key(answer): if not has_any_key(answer, fields):
raise InvalidOutput("Đáp án không có trường nào của schema") raise InvalidOutput("Đáp án không có trường nào của schema")
return normalize_answer(answer) return normalize_answer(answer, fields)
def extract_document(settings: Settings, pdf_path: Path, page_count: int,
page_blocks: dict[int, list[dict]]) -> dict:
"""Hai lượt model: trường đầu văn bản trên 3 trang đầu, người ký trên trang có chữ ký/con dấu.
`page_blocks` là block DLA của các trang OCR thành công. Không trang nào có
chữ ký/con dấu thì không hỏi model, signer để null.
"""
answer = ask_model(settings, pdf_path, header_pages(page_count), HEADER_FIELDS)
pages = signer_pages(page_blocks, settings.kie_max_pages)
answer.update(ask_model(settings, pdf_path, pages, SIGNER_FIELDS) if pages else empty_answer(SIGNER_FIELDS))
return answer

View File

@@ -46,9 +46,11 @@ def validate_response(response: dict) -> list[dict]:
raise InvalidOutput("Model reached max_tokens", truncated=True) raise InvalidOutput("Model reached max_tokens", truncated=True)
if finish_reason != "stop" or not isinstance(raw, str): if finish_reason != "stop" or not isinstance(raw, str):
raise InvalidOutput(f"Unexpected finish_reason: {finish_reason}") raise InvalidOutput(f"Unexpected finish_reason: {finish_reason}")
if not raw.strip():
return [] # Trang trắng: model dừng ngay, không có gì để bóc.
blocks = parse_blocks(raw) blocks = parse_blocks(raw)
if not blocks: if not blocks:
raise InvalidOutput("No HTML layout blocks returned") raise InvalidOutput(f"No HTML layout blocks returned: {raw[:200]!r}")
for block in blocks: for block in blocks:
block["label"] = LABEL_ALIASES.get(block["label"], block["label"]) block["label"] = LABEL_ALIASES.get(block["label"], block["label"])
if block["label"] not in LABELS: if block["label"] not in LABELS:

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
@@ -33,8 +35,12 @@ class Worker:
settings.work_dir.mkdir(parents=True, exist_ok=True) settings.work_dir.mkdir(parents=True, exist_ok=True)
if settings.ocr_workers < 1 or settings.lease_seconds <= settings.ocr_timeout: if settings.ocr_workers < 1 or settings.lease_seconds <= settings.ocr_timeout:
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.callback_workers < 1:
raise ValueError("IDP_CALLBACK_WORKERS must be positive")
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")
@@ -86,7 +92,7 @@ class Worker:
self.settings.max_page_attempts) self.settings.max_page_attempts)
def extract(self, job: dict): 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.""" """Bóc các trường cố định cho cả tài liệu, chạy sau khi mọi trang đã OCR xong để dùng block DLA."""
job_id, attempts = job["id"], job["extract_attempts"] job_id, attempts = job["id"], job["extract_attempts"]
if not self.settings.kie_enabled or self.settings.ocr_backend == "pdf_text": if not self.settings.kie_enabled or self.settings.ocr_backend == "pdf_text":
self.store.extract_done(job_id, attempts, None, status="skipped") self.store.extract_done(job_id, attempts, None, status="skipped")
@@ -94,7 +100,10 @@ class Worker:
try: try:
if attempts > self.settings.max_kie_attempts: if attempts > self.settings.max_kie_attempts:
raise ValueError("Extract lease expired too many times") raise ValueError("Extract lease expired too many times")
answer = extract_document(self.settings, self.job_dir(job_id) / "source.pdf", job["total_pages"]) page_blocks = {r["page_no"]: json.loads(r["result_json"])["blocks"]
for r in self.store.page_results(job_id) if r["status"] == "done"}
answer = extract_document(self.settings, self.job_dir(job_id) / "source.pdf",
job["total_pages"], page_blocks)
self.store.extract_done(job_id, attempts, json.dumps(answer, ensure_ascii=False)) self.store.extract_done(job_id, attempts, json.dumps(answer, ensure_ascii=False))
log.info("Extracted fields for %s", job_id) log.info("Extracted fields for %s", job_id)
except Exception as exc: except Exception as exc:
@@ -179,12 +188,20 @@ class Worker:
}, },
}, },
} }
headers = {"Content-Type": "application/json", "Idempotency-Key": job["id"]}
if self.settings.callback_basic_user:
credentials = f"{self.settings.callback_basic_user}:{self.settings.callback_basic_password}"
headers["Authorization"] = "Basic " + base64.b64encode(credentials.encode("utf-8")).decode("ascii")
request = Request(job["callback_url"], data=json.dumps(payload).encode("utf-8"), request = Request(job["callback_url"], data=json.dumps(payload).encode("utf-8"),
headers={"Content-Type": "application/json", headers=headers, method="POST")
"Idempotency-Key": job["id"]}, method="POST") try:
with urlopen(request, timeout=10) as response: with urlopen(request, timeout=10) as response:
if not 200 <= response.status < 300: if not 200 <= response.status < 300:
raise RuntimeError(f"Callback HTTP {response.status}") raise RuntimeError(f"Callback HTTP {response.status}")
except HTTPError as exc:
if exc.code != 409 or not self.airflow_run_matches(job["callback_url"], payload, headers):
raise
log.info("Airflow DAG run already exists for %s; callback confirmed", job["id"])
self.store.callback_done(job["id"], job["callback_attempts"]) self.store.callback_done(job["id"], job["callback_attempts"])
shutil.rmtree(self.job_dir(job["id"]), ignore_errors=True) shutil.rmtree(self.job_dir(job["id"]), ignore_errors=True)
except Exception as exc: except Exception as exc:
@@ -194,6 +211,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)
@@ -204,34 +240,51 @@ class Worker:
if job: if job:
self.finalize(job) self.finalize(job)
did_work = True did_work = True
job = self.store.claim_callback(self.settings.lease_seconds)
if job:
self.callback(job)
did_work = True
return did_work return did_work
def page_loop(self): def callback_once(self) -> bool:
job = self.store.claim_callback(self.settings.lease_seconds)
if not job:
return False
self.callback(job)
return True
def loop(self, step, monitor_threads=()):
"""Lỗi tạm thời (SQLite locked, HDFS chập chờn) chỉ log rồi thử lại, không được giết luồng."""
while not self.stop.is_set(): while not self.stop.is_set():
dead = [thread.name for thread in monitor_threads if not thread.is_alive()]
if dead:
raise RuntimeError(f"Worker threads stopped unexpectedly: {', '.join(dead)}")
try:
if step():
continue
except Exception:
log.exception("Worker step %s failed", step.__name__)
self.stop.wait(self.settings.poll_seconds)
def page_once(self) -> bool:
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)
continue return True
job = self.store.claim_extract(self.settings.lease_seconds, self.settings.ocr_workers) job = self.store.claim_extract(self.settings.lease_seconds, self.settings.ocr_workers)
if job: if job:
self.extract(job) self.extract(job)
continue return True
self.stop.wait(self.settings.poll_seconds) return False
def run(self): def run(self):
threads = [threading.Thread(target=self.page_loop, name=f"ocr-{i}", daemon=True) threads = [threading.Thread(target=self.loop, args=(self.page_once,), name=f"ocr-{i}", daemon=True)
for i in range(self.settings.ocr_workers)] for i in range(self.settings.ocr_workers)]
threads.extend(threading.Thread(target=self.loop, args=(self.callback_once,),
name=f"callback-{i}", daemon=True)
for i in range(self.settings.callback_workers))
for thread in threads: for thread in threads:
thread.start() thread.start()
log.info("Worker started with %s OCR threads", len(threads)) log.info("Worker started with %s OCR threads and %s callback threads",
self.settings.ocr_workers, self.settings.callback_workers)
try: try:
while not self.stop.is_set(): self.loop(self.coordinator_once, threads)
if not self.coordinator_once():
self.stop.wait(self.settings.poll_seconds)
finally: finally:
self.stop.set() self.stop.set()
for thread in threads: for thread in threads:

View File

@@ -6,7 +6,7 @@ dependencies = [
"fastapi>=0.115,<1", "fastapi>=0.115,<1",
"uvicorn>=0.30,<1", "uvicorn>=0.30,<1",
"python-multipart>=0.0.9,<1", "python-multipart>=0.0.9,<1",
"pymupdf>=1.24,<2", "pymupdf>=1.28.2,<2",
"pycryptodome>=3.20,<4", "pycryptodome>=3.20,<4",
] ]

View File

@@ -3,7 +3,7 @@ import json
from dataclasses import replace from dataclasses import replace
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path from pathlib import Path
from threading import Thread from threading import Event, Thread
from uuid import uuid4 from uuid import uuid4
import pymupdf import pymupdf
@@ -46,6 +46,7 @@ def drain(worker, settings):
if job: if job:
worker.extract(job) worker.extract(job)
assert worker.coordinator_once() assert worker.coordinator_once()
worker.callback_once()
def test_api_idempotency_and_end_to_end(tmp_path, monkeypatch): def test_api_idempotency_and_end_to_end(tmp_path, monkeypatch):
@@ -207,7 +208,8 @@ def model_server(kie_content):
answer = {"choices": [{"finish_reason": "stop", "message": {"content": kie_content}}]} answer = {"choices": [{"finish_reason": "stop", "message": {"content": kie_content}}]}
else: else:
answer = {"choices": [{"finish_reason": "stop", "message": {"content": answer = {"choices": [{"finish_reason": "stop", "message": {"content":
'<div data-label="Paragraph" data-bbox="1 1 500 500">Test</div>'}}]} '<div data-label="Paragraph" data-bbox="1 1 500 500">Test</div>'
'<div data-label="Signature" data-bbox="600 800 900 900"></div>'}}]}
else: else:
callbacks.append(body) callbacks.append(body)
answer = {"ok": True} answer = {"ok": True}
@@ -230,7 +232,8 @@ def test_extract_fixed_schema_end_to_end_and_callback(tmp_path):
thread.start() thread.start()
try: try:
url = f"http://127.0.0.1:{server.server_port}/v1/chat/completions" url = f"http://127.0.0.1:{server.server_port}/v1/chat/completions"
settings = replace(settings_for(tmp_path), ocr_url=url, kie_enabled=True, kie_url=url) settings = replace(settings_for(tmp_path), ocr_url=url, kie_enabled=True, kie_url=url,
kie_max_tokens=4096)
source = tmp_path / "quyet-dinh.pdf" source = tmp_path / "quyet-dinh.pdf"
make_pdf(source, count=2) make_pdf(source, count=2)
app = create_app(settings) app = create_app(settings)
@@ -242,10 +245,13 @@ def test_extract_fixed_schema_end_to_end_and_callback(tmp_path):
drain(Worker(settings), settings) drain(Worker(settings), settings)
# Một lượt KIE cho cả tài liệu, gửi kèm ảnh mọi trang. # Lượt 1 hỏi trường đầu văn bản trên 3 trang đầu, lượt 2 hỏi người ký trên trang có chữ ký.
assert len(kie_requests) == 1 assert len(kie_requests) == 2
assert len(kie_requests[0]["messages"][0]["content"]) == 3 header, signer = (request["messages"][0]["content"] for request in kie_requests)
assert len(header) == 3 and '"document_type"' in header[-1]["text"] and '"signer"' not in header[-1]["text"]
assert len(signer) == 3 and '"signer"' in signer[-1]["text"] and '"title"' not in signer[-1]["text"]
assert kie_requests[0]["model"] == settings.kie_model assert kie_requests[0]["model"] == settings.kie_model
assert kie_requests[0]["max_tokens"] == 4096
extraction = client.get(f"/jobs/{job_id}/extraction").json() extraction = client.get(f"/jobs/{job_id}/extraction").json()
assert extraction["status"] == "done" assert extraction["status"] == "done"
@@ -304,7 +310,7 @@ def test_extract_retries_bad_answer_then_gives_up(tmp_path):
def test_kie_prompt_schema_and_answer_shape(): def test_kie_prompt_schema_and_answer_shape():
prompt = kie.render_prompt(3) 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 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 '- "signer" (object): Người có thẩm quyền ký' in prompt and '\n - "name"' in prompt
assert [line for line in prompt.splitlines() if line.startswith('- "')][:5] == [ assert [line for line in prompt.splitlines() if line.startswith('- "')][:5] == [
line for line in kie.render_fields(kie.SCHEMA) 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à") assert kie.render_prompt(1).startswith("Trích xuất thông tin từ ảnh tài liệu và")
@@ -316,10 +322,21 @@ def test_kie_prompt_schema_and_answer_shape():
"issuing_authority": None, "title": None, "issuing_authority": None, "title": None,
"signer": {"name": "Nguyễn Văn A", "position": None}} "signer": {"name": "Nguyễn Văn A", "position": None}}
assert list(answer) == [field["key"] for field in kie.SCHEMA] assert list(answer) == [field["key"] for field in kie.SCHEMA]
assert kie.normalize_answer({"signer": [{"name": "Lương Cường", "position": "CHỦ TỊCH"}, {"name": "B"}]},
kie.SIGNER_FIELDS) == {"signer": {"name": "Lương Cường", "position": "CHỦ TỊCH"}}
# Tài liệu dài chỉ gửi các trang đầu và trang cuối (nơi có người ký). # Trường đầu văn bản lấy 3 trang đầu; người ký lấy trang DLA có chữ ký/con dấu, tối đa N trang cuối.
assert kie.select_pages(3, 5) == [1, 2, 3] assert kie.header_pages(1) == [1]
assert kie.select_pages(20, 5) == [1, 2, 3, 4, 20] assert kie.header_pages(10) == [1, 2, 3]
text = [{"label": "Paragraph", "bbox": [0, 0, 1000, 500]}]
edge_stamp = [{"label": "Stamp", "bbox": [950, 100, 1000, 200]}]
initials = [{"label": "Signature", "bbox": [400, 850, 600, 930]}]
seal = [{"label": "Stamp", "bbox": [480, 400, 650, 530]}]
assert kie.signer_pages({1: text, 2: text}, 5) == []
assert kie.signer_pages({1: edge_stamp, 2: text, 3: initials}, 5) == [1, 3]
assert kie.signer_pages({no: edge_stamp for no in range(1, 11)}, 3) == [8, 9, 10]
# Có dấu trong thân trang thì chỉ lấy trang đó, bỏ trang chữ ký nháy và dấu giáp lai.
assert kie.signer_pages({1: initials + edge_stamp, 2: initials, 3: seal}, 5) == [3]
def test_keeps_empty_visual_blocks_but_rejects_empty_text_blocks(): def test_keeps_empty_visual_blocks_but_rejects_empty_text_blocks():
@@ -355,10 +372,100 @@ def test_rejects_truncated_plain_text_and_invalid_bbox():
pass pass
else: else:
raise AssertionError("Invalid output was accepted") raise AssertionError("Invalid output was accepted")
assert validate_response(response(" \n")) == [] # trang trắng
def test_locked_database_surfaces_and_does_not_kill_worker_thread(tmp_path, monkeypatch):
import sqlite3
settings = replace(settings_for(tmp_path), ocr_workers=1)
store = Store(settings.db_path)
blocker = store.connect()
blocker.execute("BEGIN IMMEDIATE")
monkeypatch.setattr(store, "connect", lambda: sqlite3.connect(settings.db_path, timeout=0.05,
isolation_level=None))
try:
with store.tx():
pass
except sqlite3.OperationalError as exc:
assert "locked" in str(exc)
else:
raise AssertionError("Lock đáng lẽ phải làm BEGIN IMMEDIATE lỗi")
worker = Worker(settings, store)
calls = []
def step():
calls.append(1)
if len(calls) == 3:
worker.stop.set()
return store.claim_page(settings.lease_seconds, settings.ocr_workers)
worker.loop(step) # lỗi "database is locked" hai lần vẫn chạy tiếp tới lần thứ ba
assert len(calls) == 3
blocker.execute("ROLLBACK")
def test_worker_store_serializes_write_transactions(tmp_path, monkeypatch):
import sqlite3
store = Store(settings_for(tmp_path).db_path)
monkeypatch.setattr(store, "connect", lambda: sqlite3.connect(store.path, timeout=0.05,
isolation_level=None))
first_entered = Event()
release_first = Event()
second_started = Event()
second_done = Event()
errors = []
def first_writer():
try:
with store.tx():
first_entered.set()
release_first.wait(2)
except Exception as exc:
errors.append(exc)
def second_writer():
second_started.set()
try:
store.claim_page(1800, 2)
except Exception as exc:
errors.append(exc)
finally:
second_done.set()
first = Thread(target=first_writer)
second = Thread(target=second_writer)
first.start()
try:
assert first_entered.wait(2)
second.start()
assert second_started.wait(2)
assert not second_done.wait(0.1)
finally:
release_first.set()
first.join(2)
if second.ident is not None:
second.join(2)
assert second_done.is_set()
assert not errors
def test_worker_main_loop_exits_when_processing_thread_stops(tmp_path):
worker = Worker(settings_for(tmp_path))
dead_thread = Thread(name="dead-ocr")
try:
worker.loop(lambda: False, [dead_thread])
except RuntimeError as exc:
assert "dead-ocr" in str(exc)
else:
raise AssertionError("Worker must exit so Docker can restart it")
def test_real_http_ocr_and_callback(tmp_path): def test_real_http_ocr_and_callback(tmp_path):
callbacks = [] callbacks = []
auth_headers = []
class Handler(BaseHTTPRequestHandler): class Handler(BaseHTTPRequestHandler):
def do_POST(self): def do_POST(self):
@@ -370,8 +477,20 @@ def test_real_http_ocr_and_callback(tmp_path):
'<div data-label="Paragraph" data-bbox="1 1 500 500">Test</div>'}}]} '<div data-label="Paragraph" data-bbox="1 1 500 500">Test</div>'}}]}
else: else:
callbacks.append(body) callbacks.append(body)
answer = {"ok": True} auth_headers.append(self.headers.get("Authorization"))
answer = {"detail": "DAG Run already exists"}
data = json.dumps(answer).encode() data = json.dumps(answer).encode()
self.send_response(200 if self.path == "/v1/chat/completions" else 409)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
def do_GET(self):
assert self.path == "/api/v1/dags/test/dagRuns/callback_test_001"
assert self.headers.get("Authorization") == auth_headers[0]
data = json.dumps({"dag_run_id": callbacks[0]["dag_run_id"],
"conf": callbacks[0]["conf"]}).encode()
self.send_response(200) self.send_response(200)
self.send_header("Content-Type", "application/json") self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(data))) self.send_header("Content-Length", str(len(data)))
@@ -386,18 +505,21 @@ def test_real_http_ocr_and_callback(tmp_path):
thread.start() thread.start()
try: try:
settings = replace(settings_for(tmp_path), settings = replace(settings_for(tmp_path),
ocr_url=f"http://127.0.0.1:{server.server_port}/v1/chat/completions") ocr_url=f"http://127.0.0.1:{server.server_port}/v1/chat/completions",
callback_basic_user="callback_handler",
callback_basic_password="callback_handler")
source = tmp_path / "input.pdf" source = tmp_path / "input.pdf"
make_pdf(source, count=1) make_pdf(source, count=1)
app = create_app(settings) app = create_app(settings)
with TestClient(app) as client: with TestClient(app) as client:
reply = client.post("/process", json={"request_id": str(uuid4()), "file_path": str(source), reply = client.post("/process", json={"request_id": str(uuid4()), "file_path": str(source),
"dag_run_id": "callback_test_001", "dag_run_id": "callback_test_001",
"callback_url": f"http://127.0.0.1:{server.server_port}/callback"}) "callback_url": f"http://127.0.0.1:{server.server_port}/api/v1/dags/test/dagRuns"})
assert reply.status_code == 202 assert reply.status_code == 202
drain(Worker(settings), settings) drain(Worker(settings), settings)
assert client.get(f"/jobs/{reply.json()['job_id']}").json()["callback_state"] == "delivered" assert client.get(f"/jobs/{reply.json()['job_id']}").json()["callback_state"] == "delivered"
assert callbacks[0]["dag_run_id"] == "callback_test_001" assert callbacks[0]["dag_run_id"] == "callback_test_001"
assert auth_headers == ["Basic " + base64.b64encode(b"callback_handler:callback_handler").decode("ascii")]
assert set(callbacks[0]) == {"dag_run_id", "conf"} assert set(callbacks[0]) == {"dag_run_id", "conf"}
conf = callbacks[0]["conf"] conf = callbacks[0]["conf"]
assert conf["request_id"] == reply.json()["request_id"] assert conf["request_id"] == reply.json()["request_id"]
@@ -410,6 +532,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()
@@ -432,6 +564,41 @@ def test_global_gpu_limit_and_fairness_across_files(tmp_path):
assert store.claim_page(settings.lease_seconds, global_limit=2) is None assert store.claim_page(settings.lease_seconds, global_limit=2) is None
def test_slow_callback_does_not_block_next_job_or_callback(tmp_path, monkeypatch):
settings = replace(settings_for(tmp_path), callback_workers=2)
store = Store(settings.db_path)
source = tmp_path / "input.pdf"
make_pdf(source, count=1)
bad, _ = store.create_job(str(uuid4()), str(source), "http://bad-callback", None, 100)
good, _ = store.create_job(str(uuid4()), str(source), "http://good-callback", None, 100)
later, _ = store.create_job(str(uuid4()), str(source), None, None, 100)
with store.tx() as db:
db.execute("UPDATE jobs SET status='completed', callback_state='pending' WHERE id IN (?, ?)",
(bad["id"], good["id"]))
worker = Worker(settings, store)
started, release = Event(), Event()
def fake_callback(job):
if job["id"] == bad["id"]:
started.set()
assert release.wait(5)
store.callback_done(job["id"], job["callback_attempts"])
monkeypatch.setattr(worker, "callback", fake_callback)
thread = Thread(target=worker.callback_once)
thread.start()
try:
assert started.wait(5)
assert worker.coordinator_once()
assert store.get_job(later["id"])["status"] == "processing"
assert worker.callback_once()
assert store.get_job(good["id"])["callback_state"] == "delivered"
finally:
release.set()
thread.join(timeout=5)
assert not thread.is_alive()
def test_webhdfs_adapter_streams(tmp_path, monkeypatch): def test_webhdfs_adapter_streams(tmp_path, monkeypatch):
class FakeClient: class FakeClient:
def __init__(self): def __init__(self):

2
uv.lock generated
View File

@@ -313,7 +313,7 @@ requires-dist = [
{ name = "hdfs", marker = "extra == 'hdfs'", specifier = ">=2.7,<3" }, { name = "hdfs", marker = "extra == 'hdfs'", specifier = ">=2.7,<3" },
{ name = "httpx", marker = "extra == 'test'", specifier = ">=0.27,<1" }, { name = "httpx", marker = "extra == 'test'", specifier = ">=0.27,<1" },
{ name = "pycryptodome", specifier = ">=3.20,<4" }, { name = "pycryptodome", specifier = ">=3.20,<4" },
{ name = "pymupdf", specifier = ">=1.24,<2" }, { name = "pymupdf", specifier = ">=1.28.2,<2" },
{ name = "pytest", marker = "extra == 'test'", specifier = ">=8,<10" }, { name = "pytest", marker = "extra == 'test'", specifier = ">=8,<10" },
{ name = "python-multipart", specifier = ">=0.0.9,<1" }, { name = "python-multipart", specifier = ">=0.0.9,<1" },
{ name = "uvicorn", specifier = ">=0.30,<1" }, { name = "uvicorn", specifier = ">=0.30,<1" },