6 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
11 changed files with 459 additions and 116 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

2
.gitignore vendored
View File

@@ -4,8 +4,10 @@ __pycache__/
.pytest_cache/
*.egg-info/
export/
qwen35-4b-model/
idp_parsing_service.egg-info/
build/
chandra-dla-api-v2-20260906-024126.tar
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

@@ -114,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
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:
```bash
@@ -163,20 +126,109 @@ 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`.
## Dựng model
## Triển khai bằng docker compose
`docker-compose.yaml` dựng cả hai model trên **cùng một card** (`GPU_UUID` trong
`.env`): `chandra` (image `IMAGE_TAG`, mặc định `chandra-dla-api:v2-20260906-024126`
đã đóng sẵn weights v2) cổng `PORT` (9222) và `kie` (Qwen3.5-4B, image
`vllm/vllm-openai:v0.23.0`) cổng `KIE_PORT` (9224). Bộ nhớ chia 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. Weights Qwen nằm trong docker volume `qwen35_4b`, nạp một
lần theo lệnh ở đầu file 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
echo GPU_UUID=GPU-xxxx > .env
docker compose up -d
curl http://localhost:9222/v1/models; curl http://localhost:9224/v1/models
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
@@ -205,7 +257,7 @@ curl http://localhost:9222/v1/models; curl http://localhost:9224/v1/models
| `IDP_KIE_MAX_TOKENS` | `2048` | Giới hạn số token đầu ra của mỗi request KIE; độc lập với `--max-model-len` của vLLM |
| `IDP_MAX_KIE_ATTEMPTS` | `3` | Số lần thử bóc trường mỗi tài liệu |
| `IDP_RUN_WORKER` | `0` | `1` chạy worker ngay trong process API |
| `IDP_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_LEASE_SECONDS` | `1800` | Lease task; phải lớn hơn timeout và thời gian chuẩn bị/finalize |
@@ -221,7 +273,7 @@ native RPC, Kerberos và HA nên chọn `IDP_STORAGE=hdfs_cli`, đặt
`IDP_HDFS_NATIVE_URI=hdfs://vptwd` và
`HDFS_PRINCIPAL=searchengine@DATALAKE.DCS.VN`. Gói portable đã kèm Java, Hadoop
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
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.
@@ -229,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:
```bash
./test-hdfs.sh /
./test-hdfs.sh /data/bronze/incoming
docker compose exec worker hdfs dfs -ls /
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

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,32 +1,60 @@
# Hai model của service trên cùng một card GPU:
# chandra (DLA/OCR từng trang) → cổng ${PORT:-9222}, served name "chandra"
# kie (bóc trường, Qwen3.5-4B) → cổng ${KIE_PORT:-9224}, served name "qwen3.5-4b"
# Toàn bộ service trên một host, một card GPU: `cp .env.example .env`, sửa .env, rồi
# docker compose up -d --build
#
# .env cần GPU_UUID (nvidia-smi -L). Mặc định hai model dùng ~80% card (GPU_UTIL 0.55 +
# KIE_GPU_UTIL 0.3); card có tiến trình khác thì hạ tổng xuống dưới phần còn trống.
# kie chỉ khởi động sau khi chandra healthy để hai vLLM không đo bộ nhớ GPU cùng lúc.
# chandra DLA/OCR từng trang, vLLM cổng ${PORT:-9222}, served name "chandra"
# 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
#
# Weights chandra đóng sẵn trong image IMAGE_TAG. Weights Qwen nằm trong volume
# ${KIE_VOLUME:-qwen35_4b}, nạp một lần từ snapshot HF (tar -h để theo symlink):
# docker volume create qwen35_4b
# tar -C <snapshot Qwen/Qwen3.5-4B> -chf - . | docker run --rm -i -v qwen35_4b:/model \
# --entrypoint tar vllm/vllm-openai:v0.23.0 -C /model -xf -
# 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.
x-gpu: &gpu
resources:
reservations:
devices:
- driver: nvidia
device_ids: ["${GPU_DEVICE:-0}"] # như `docker run --gpus device=0`
capabilities: [gpu]
x-vllm-image: &vllm-image ${IMAGE_TAG:-chandra-dla-api:v2-20260906-024126}
x-vllm-env: &vllm-env
HF_HUB_OFFLINE: "1"
TRANSFORMERS_OFFLINE: "1"
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: ${IMAGE_TAG:-chandra-dla-api:v2-20260906-024126}
image: *vllm-image
pull_policy: never
container_name: chandra-ocr
restart: unless-stopped
gpus: &gpu
- driver: cdi
device_ids: ["nvidia.com/gpu=${GPU_UUID:?dat GPU_UUID trong .env}"]
deploy: *gpu
ipc: host
shm_size: "16gb"
ports:
- "${PORT:-9222}:8000"
environment: &env
HF_HUB_OFFLINE: "1"
TRANSFORMERS_OFFLINE: "1"
VLLM_LOGGING_LEVEL: "${VLLM_LOG_LEVEL:-INFO}"
environment: *vllm-env
command:
- --model=/model
- --served-model-name=chandra
@@ -41,28 +69,30 @@ services:
- --seed=42
# 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}
healthcheck: &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
healthcheck: *health
kie:
image: ${KIE_IMAGE:-vllm/vllm-openai:v0.23.0}
# 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
gpus: *gpu
deploy: *gpu
ipc: host
shm_size: "8gb"
ports:
- "${KIE_PORT:-9224}:8000"
environment: *env
environment: *vllm-env
volumes:
- kie_model:/model:ro
- 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
@@ -71,6 +101,7 @@ services:
- --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
@@ -80,7 +111,48 @@ services:
- --mm-processor-kwargs={"min_pixels":65536,"max_pixels":1835008}
healthcheck: *health
volumes:
kie_model:
external: true
name: ${KIE_VOLUME:-qwen35_4b}
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:
test: ["CMD-SHELL", "python -c \"import urllib.request; urllib.request.urlopen('http://127.0.0.1:${IDP_PORT:-8001}/readyz', timeout=3)\""]
interval: 30s
timeout: 5s
retries: 3
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

@@ -4,6 +4,7 @@ import sqlite3
import time
from contextlib import contextmanager
from pathlib import Path
from threading import Lock
from uuid import uuid4
@@ -14,6 +15,9 @@ def retry_delay(attempt: int) -> int:
class Store:
def __init__(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)
self.init()
@@ -81,12 +85,16 @@ class Store:
@contextmanager
def tx(self):
with self._tx_lock:
db = self.connect()
try:
db.execute("BEGIN IMMEDIATE")
yield db
db.execute("COMMIT")
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")
raise
finally:

View File

@@ -46,9 +46,11 @@ def validate_response(response: dict) -> list[dict]:
raise InvalidOutput("Model reached max_tokens", truncated=True)
if finish_reason != "stop" or not isinstance(raw, str):
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)
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:
block["label"] = LABEL_ALIASES.get(block["label"], block["label"])
if block["label"] not in LABELS:

View File

@@ -249,36 +249,42 @@ class Worker:
self.callback(job)
return True
def callback_loop(self):
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():
if not self.callback_once():
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_loop(self):
while not self.stop.is_set():
def page_once(self) -> bool:
page = self.store.claim_page(self.settings.lease_seconds, self.settings.ocr_workers)
if page:
self.process_page(page)
continue
return True
job = self.store.claim_extract(self.settings.lease_seconds, self.settings.ocr_workers)
if job:
self.extract(job)
continue
self.stop.wait(self.settings.poll_seconds)
return True
return False
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)]
threads.extend(threading.Thread(target=self.callback_loop, name=f"callback-{i}", daemon=True)
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:
thread.start()
log.info("Worker started with %s OCR threads and %s callback threads",
self.settings.ocr_workers, self.settings.callback_workers)
try:
while not self.stop.is_set():
if not self.coordinator_once():
self.stop.wait(self.settings.poll_seconds)
self.loop(self.coordinator_once, threads)
finally:
self.stop.set()
for thread in threads:

View File

@@ -372,6 +372,95 @@ def test_rejects_truncated_plain_text_and_invalid_bbox():
pass
else:
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):
@@ -561,4 +650,3 @@ def test_voffice_decryption_rejects_wrong_key(tmp_path):
pass
else:
raise AssertionError("Invalid encrypted document was accepted")