Spaces:
Paused
Paused
hoang.nguyen6 commited on
Commit ·
f66643d
unverified ·
0
Parent(s):
deploy
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .env.example +19 -0
- .github/workflows/ci.yml +45 -0
- .gitignore +54 -0
- .ruffignore +12 -0
- Dockerfile +121 -0
- LICENSE +661 -0
- README.md +406 -0
- app.json +5 -0
- app.py +34 -0
- benchmark/__init__.py +0 -0
- benchmark/parser/.gitignore +8 -0
- benchmark/parser/README.md +175 -0
- benchmark/parser/evaluation/aggregate_reports.py +122 -0
- benchmark/parser/evaluation/compare_matchers.py +154 -0
- benchmark/parser/evaluation/download_dataset.py +86 -0
- benchmark/parser/evaluation/eval_formula.py +244 -0
- benchmark/parser/evaluation/eval_formula_cdm.py +233 -0
- benchmark/parser/evaluation/eval_layout.py +639 -0
- benchmark/parser/evaluation/eval_table.py +248 -0
- benchmark/parser/evaluation/requirements-eval.txt +22 -0
- benchmark/parser/run_parser/build_pdfs.py +147 -0
- benchmark/parser/run_parser/run_parser.py +214 -0
- benchmark/translation/.gitignore +4 -0
- benchmark/translation/README.md +102 -0
- benchmark/translation/__init__.py +6 -0
- benchmark/translation/aggregate.py +132 -0
- benchmark/translation/instrument.py +113 -0
- benchmark/translation/requirements.txt +12 -0
- benchmark/translation/run_all.sh +150 -0
- benchmark/translation/run_translate.py +318 -0
- benchmark/translation/score_comet.py +163 -0
- benchmark/translation/wmt24pp_adapter.py +200 -0
- docker-compose.yml +49 -0
- docs/ADVANCED.md +357 -0
- docs/APIS.md +95 -0
- docs/CODE_OF_CONDUCT.md +128 -0
- docs/README_GUI.md +40 -0
- docs/README_ja-JP.md +389 -0
- docs/README_ko-KR.md +382 -0
- docs/README_zh-CN.md +312 -0
- docs/README_zh-TW.md +366 -0
- pdf2zh/__init__.py +15 -0
- pdf2zh/backend.py +98 -0
- pdf2zh/cache.py +142 -0
- pdf2zh/config.py +242 -0
- pdf2zh/converter.py +533 -0
- pdf2zh/doclayout.py +174 -0
- pdf2zh/e2e.py +258 -0
- pdf2zh/gui.py +892 -0
- pdf2zh/high_level.py +449 -0
.env.example
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Thiết bị chạy model: "cuda", "cpu", hoặc "auto" (auto -> cuda nếu có GPU)
|
| 2 |
+
DEVICE=auto
|
| 3 |
+
|
| 4 |
+
# Batch size cho A100 80GB / 142GB RAM — tận dụng VRAM cho Phase 1 (đỉnh ~45-55GB,
|
| 5 |
+
# vẫn còn headroom an toàn trong 80GB).
|
| 6 |
+
# - OCR (recognition) nặng nhất: 512 ~ 13GB VRAM.
|
| 7 |
+
# - layout/detection 64: gấp đôi mặc định, tăng throughput Phase 1 nhờ thừa VRAM.
|
| 8 |
+
# - page 32 + table 512: 142GB RAM & 80GB VRAM dư sức.
|
| 9 |
+
# GPU nhỏ hơn (T4/16GB): để trống tất cả (None) để Surya tự chọn batch nhỏ, tránh OOM.
|
| 10 |
+
PAGE_BATCH_SIZE=32
|
| 11 |
+
LAYOUT_BATCH_SIZE=64
|
| 12 |
+
DETECTION_BATCH_SIZE=64
|
| 13 |
+
OCR_BATCH_SIZE=512
|
| 14 |
+
TABLE_BATCH_SIZE=512
|
| 15 |
+
|
| 16 |
+
# Cấu hình cho OCR (Lưu ý: text threshold > blank threshold) — ảnh hưởng độ chính xác,
|
| 17 |
+
# không liên quan VRAM.
|
| 18 |
+
DETECTOR_BLANK_THRESHOLD=0.5
|
| 19 |
+
DETECTOR_TEXT_THRESHOLD=0.6
|
.github/workflows/ci.yml
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: CI
|
| 2 |
+
|
| 3 |
+
on:
|
| 4 |
+
pull_request:
|
| 5 |
+
push:
|
| 6 |
+
branches: [main, develop, feature/*]
|
| 7 |
+
|
| 8 |
+
jobs:
|
| 9 |
+
lint-and-test:
|
| 10 |
+
runs-on: ubuntu-latest
|
| 11 |
+
|
| 12 |
+
steps:
|
| 13 |
+
- name: Checkout code
|
| 14 |
+
uses: actions/checkout@v4
|
| 15 |
+
|
| 16 |
+
- name: Setup Python 3.12
|
| 17 |
+
uses: actions/setup-python@v5
|
| 18 |
+
with:
|
| 19 |
+
python-version: "3.12"
|
| 20 |
+
|
| 21 |
+
- name: Cache pip dependencies
|
| 22 |
+
uses: actions/cache@v4
|
| 23 |
+
with:
|
| 24 |
+
path: ~/.cache/pip
|
| 25 |
+
key: ${{ runner.os }}-pip-${{ hashFiles('**/pyproject.toml') }}
|
| 26 |
+
restore-keys: |
|
| 27 |
+
${{ runner.os }}-pip-
|
| 28 |
+
|
| 29 |
+
- name: Install dependencies
|
| 30 |
+
run: |
|
| 31 |
+
python -m pip install --upgrade pip
|
| 32 |
+
pip install -e ".[dev]"
|
| 33 |
+
|
| 34 |
+
# 🔍 Lint with Ruff
|
| 35 |
+
- name: Lint with Ruff
|
| 36 |
+
run: ruff check pdf2zh test
|
| 37 |
+
|
| 38 |
+
# 🎨 Format check with Black
|
| 39 |
+
- name: Check formatting with Black
|
| 40 |
+
run: black --check pdf2zh test
|
| 41 |
+
|
| 42 |
+
# 🧪 Run tests
|
| 43 |
+
- name: Run pytest
|
| 44 |
+
run: pytest test/ -v
|
| 45 |
+
|
.gitignore
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# macOS
|
| 2 |
+
.DS_Store
|
| 3 |
+
.AppleDouble
|
| 4 |
+
.LSOverride
|
| 5 |
+
|
| 6 |
+
# Python
|
| 7 |
+
__pycache__/
|
| 8 |
+
*.py[cod]
|
| 9 |
+
*.pyo
|
| 10 |
+
*.pyd
|
| 11 |
+
.Python
|
| 12 |
+
*.egg
|
| 13 |
+
*.egg-info/
|
| 14 |
+
dist/
|
| 15 |
+
build/
|
| 16 |
+
.eggs/
|
| 17 |
+
*.whl
|
| 18 |
+
|
| 19 |
+
# Virtual environments
|
| 20 |
+
.venv/
|
| 21 |
+
venv/
|
| 22 |
+
env/
|
| 23 |
+
ENV/
|
| 24 |
+
|
| 25 |
+
# IDE
|
| 26 |
+
.vscode/
|
| 27 |
+
.idea/
|
| 28 |
+
*.swp
|
| 29 |
+
*.swo
|
| 30 |
+
|
| 31 |
+
# Jupyter
|
| 32 |
+
.ipynb_checkpoints/
|
| 33 |
+
|
| 34 |
+
# Logs & temp
|
| 35 |
+
*.log
|
| 36 |
+
*.tmp
|
| 37 |
+
./claude CLAUDE.md
|
| 38 |
+
.claude/
|
| 39 |
+
CLAUDE.md
|
| 40 |
+
claude
|
| 41 |
+
.DS_Store
|
| 42 |
+
|
| 43 |
+
# File
|
| 44 |
+
output.json
|
| 45 |
+
math.json
|
| 46 |
+
*.pdf
|
| 47 |
+
SURYAOCR_README.md
|
| 48 |
+
test.py
|
| 49 |
+
|
| 50 |
+
# Bỏ qua tất cả mọi thứ bên trong thư mục model_path
|
| 51 |
+
pdf2zh/scanned/model_path/*
|
| 52 |
+
test_local/
|
| 53 |
+
|
| 54 |
+
.env
|
.ruffignore
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Ignore generated files and directories
|
| 2 |
+
__pycache__/
|
| 3 |
+
*.egg-info/
|
| 4 |
+
.git/
|
| 5 |
+
.venv/
|
| 6 |
+
venv/
|
| 7 |
+
env/
|
| 8 |
+
dist/
|
| 9 |
+
build/
|
| 10 |
+
.pytest_cache/
|
| 11 |
+
.mypy_cache/
|
| 12 |
+
.ruff_cache/
|
Dockerfile
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# syntax=docker/dockerfile:1
|
| 2 |
+
# E2E PDF translator (OCR -> Translate -> Render) for a GPU Hugging Face Space.
|
| 3 |
+
# Base: CUDA 13 runtime + Ubuntu 22.04 (Python 3.10) — the config that builds cleanly.
|
| 4 |
+
# Only surya-ocr/paddleocr are pinned (in requirements.txt); torch/paddle/numpy stay
|
| 5 |
+
# unpinned so pip resolves a mutually compatible CUDA stack. T4 = Turing sm_75 (OK on CUDA 13).
|
| 6 |
+
# NOTE: if this tag 404s at build, pick an existing one from
|
| 7 |
+
# https://hub.docker.com/r/nvidia/cuda/tags (e.g. 13.0.1-cudnn-runtime-ubuntu22.04).
|
| 8 |
+
FROM nvidia/cuda:13.0.0-cudnn-runtime-ubuntu22.04
|
| 9 |
+
|
| 10 |
+
ENV DEBIAN_FRONTEND=noninteractive \
|
| 11 |
+
PYTHONUNBUFFERED=1 \
|
| 12 |
+
PIP_NO_CACHE_DIR=1 \
|
| 13 |
+
TORCH_DEVICE=cuda \
|
| 14 |
+
TYPST_BIN=typst \
|
| 15 |
+
PDF2ZH_FONT_DIR=/app/fonts \
|
| 16 |
+
HF_HOME=/app/.cache/huggingface \
|
| 17 |
+
TRANSFORMERS_CACHE=/app/.cache/huggingface \
|
| 18 |
+
TYPST_PACKAGE_CACHE_PATH=/app/.cache/typst \
|
| 19 |
+
MODEL_CACHE_DIR=/app/.cache/datalab/models \
|
| 20 |
+
PADDLE_PDX_CACHE_HOME=/app/.cache/paddlex
|
| 21 |
+
|
| 22 |
+
WORKDIR /app
|
| 23 |
+
EXPOSE 7860
|
| 24 |
+
|
| 25 |
+
# ── System deps ───────────────────────────────────────────────────────────────
|
| 26 |
+
# - python 3.10 + pip (Ubuntu 22.04 default)
|
| 27 |
+
# - OpenCV / PyMuPDF runtime libs (libgl1, libglib2.0-0, ...)
|
| 28 |
+
# - fonts: Noto Sans/Serif + Noto CJK (covers Vietnamese + CJK), fontconfig
|
| 29 |
+
# - wget/xz to fetch the typst binary
|
| 30 |
+
RUN apt-get update && apt-get install --no-install-recommends -y \
|
| 31 |
+
python3 python3-pip python3-dev \
|
| 32 |
+
libgl1 libglib2.0-0 libxext6 libsm6 libxrender1 \
|
| 33 |
+
fontconfig fonts-noto-core fonts-noto-cjk \
|
| 34 |
+
wget xz-utils ca-certificates && \
|
| 35 |
+
rm -rf /var/lib/apt/lists/*
|
| 36 |
+
|
| 37 |
+
# ── Typst binary ────────────────────────────────────────────────────────────────
|
| 38 |
+
ARG TYPST_VERSION=v0.14.2
|
| 39 |
+
RUN wget -qO /tmp/typst.tar.xz \
|
| 40 |
+
"https://github.com/typst/typst/releases/download/${TYPST_VERSION}/typst-x86_64-unknown-linux-musl.tar.xz" && \
|
| 41 |
+
tar -xJf /tmp/typst.tar.xz -C /tmp && \
|
| 42 |
+
install -m 0755 /tmp/typst-x86_64-unknown-linux-musl/typst /usr/local/bin/typst && \
|
| 43 |
+
rm -rf /tmp/typst* && typst --version
|
| 44 |
+
|
| 45 |
+
# ── Extra fonts (Be Vietnam Pro — open-source Google Font) ───────────────────────
|
| 46 |
+
RUN mkdir -p /app/fonts && \
|
| 47 |
+
for w in Regular Bold Italic; do \
|
| 48 |
+
wget -qO "/app/fonts/BeVietnamPro-${w}.ttf" \
|
| 49 |
+
"https://github.com/google/fonts/raw/main/ofl/bevietnampro/BeVietnamPro-${w}.ttf" || true; \
|
| 50 |
+
done && \
|
| 51 |
+
# also surface the system Noto fonts to the typst --font-path dir
|
| 52 |
+
cp -n /usr/share/fonts/truetype/noto/*.ttf /app/fonts/ 2>/dev/null || true && \
|
| 53 |
+
cp -n /usr/share/fonts/opentype/noto/*.otf /app/fonts/ 2>/dev/null || true && \
|
| 54 |
+
fc-cache -f
|
| 55 |
+
|
| 56 |
+
# ── Python deps ──────────────────────────────────────────────────────────────────
|
| 57 |
+
COPY requirements.txt .
|
| 58 |
+
RUN python3 -m pip install --upgrade pip && \
|
| 59 |
+
python3 -m pip install -r requirements.txt
|
| 60 |
+
|
| 61 |
+
# ── App code ─────────────────────────────────────────────────────────────────────
|
| 62 |
+
# Running from /app puts the pdf2zh package on sys.path, so no editable install is
|
| 63 |
+
# needed (and it avoids pulling pyproject's heavier optional deps like babeldoc).
|
| 64 |
+
COPY . .
|
| 65 |
+
|
| 66 |
+
# ── Seed .env from the tracked template ────────────────────────────────────────
|
| 67 |
+
# .env is gitignored (absent from the image) but Settings reads env_file=".env".
|
| 68 |
+
# Copy it here as root: the Space runs the container as a non-root user that cannot
|
| 69 |
+
# write to /app at runtime, so seeding only in the entrypoint fails with EACCES.
|
| 70 |
+
RUN cp -n .env.example .env 2>/dev/null || true
|
| 71 |
+
|
| 72 |
+
# ── Pre-cache typst packages (cmarker + mitex) so runtime needs no network ─────────
|
| 73 |
+
RUN mkdir -p /app/.cache/typst && \
|
| 74 |
+
printf '#import "@preview/cmarker:0.1.8"\n#import "@preview/mitex:0.2.6": *\n#cmarker.render("ok")\n' \
|
| 75 |
+
> /tmp/warm.typ && \
|
| 76 |
+
typst compile /tmp/warm.typ /tmp/warm.pdf || echo "typst package pre-cache skipped"
|
| 77 |
+
|
| 78 |
+
# OCR models (~3-5GB) are NOT baked in — they download on the first request:
|
| 79 |
+
# - Surya (layout/detection/recognition) -> Datalab's servers, cached in MODEL_CACHE_DIR
|
| 80 |
+
# - Paddle table-cell model -> PaddleX model server, cached in PADDLE_PDX_CACHE_HOME
|
| 81 |
+
# Make caches writable in case the Space runs the container as a non-root user.
|
| 82 |
+
RUN mkdir -p /app/.cache/datalab/models /app/.cache/paddlex /app/.cache/huggingface \
|
| 83 |
+
/app/.cache/typst && chmod -R 777 /app/.cache
|
| 84 |
+
|
| 85 |
+
# Force UTF-8 so the app can write Vietnamese text / .typ files on a minimal locale
|
| 86 |
+
# (placed after pip so the heavy install layer stays cached). Avoids
|
| 87 |
+
# UnicodeEncodeError: 'ascii' codec can't encode ... at render time.
|
| 88 |
+
ENV PYTHONUTF8=1 \
|
| 89 |
+
LANG=C.UTF-8 \
|
| 90 |
+
LC_ALL=C.UTF-8
|
| 91 |
+
|
| 92 |
+
# Entrypoint: prefer HF Persistent Storage (/data) for the model caches so they
|
| 93 |
+
# survive sleep/restart and download only once. Falls back to /app/.cache (ephemeral)
|
| 94 |
+
# when persistent storage is not enabled.
|
| 95 |
+
RUN cat > /usr/local/bin/entrypoint.sh <<'EOF'
|
| 96 |
+
#!/usr/bin/env bash
|
| 97 |
+
set -e
|
| 98 |
+
if mkdir -p /data 2>/dev/null && [ -w /data ]; then
|
| 99 |
+
CACHE_ROOT=/data
|
| 100 |
+
else
|
| 101 |
+
CACHE_ROOT=/app/.cache
|
| 102 |
+
fi
|
| 103 |
+
export MODEL_CACHE_DIR="$CACHE_ROOT/datalab/models"
|
| 104 |
+
export PADDLE_PDX_CACHE_HOME="$CACHE_ROOT/paddlex"
|
| 105 |
+
export HF_HOME="$CACHE_ROOT/huggingface"
|
| 106 |
+
export TRANSFORMERS_CACHE="$CACHE_ROOT/huggingface"
|
| 107 |
+
mkdir -p "$MODEL_CACHE_DIR" "$PADDLE_PDX_CACHE_HOME" "$HF_HOME"
|
| 108 |
+
echo "[entrypoint] model cache root = $CACHE_ROOT"
|
| 109 |
+
# Fallback seed for writable-/app environments (local runs). On the Space /app is
|
| 110 |
+
# read-only at runtime, so .env is already baked at build time; keep this non-fatal
|
| 111 |
+
# (|| true) so a failed copy never aborts the entrypoint under `set -e`.
|
| 112 |
+
if [ ! -f /app/.env ] && [ -f /app/.env.example ]; then
|
| 113 |
+
cp /app/.env.example /app/.env 2>/dev/null \
|
| 114 |
+
&& echo "[entrypoint] seeded /app/.env from .env.example" \
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
GNU AFFERO GENERAL PUBLIC LICENSE
|
| 2 |
+
Version 3, 19 November 2007
|
| 3 |
+
|
| 4 |
+
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
| 5 |
+
Everyone is permitted to copy and distribute verbatim copies
|
| 6 |
+
of this license document, but changing it is not allowed.
|
| 7 |
+
|
| 8 |
+
Preamble
|
| 9 |
+
|
| 10 |
+
The GNU Affero General Public License is a free, copyleft license for
|
| 11 |
+
software and other kinds of works, specifically designed to ensure
|
| 12 |
+
cooperation with the community in the case of network server software.
|
| 13 |
+
|
| 14 |
+
The licenses for most software and other practical works are designed
|
| 15 |
+
to take away your freedom to share and change the works. By contrast,
|
| 16 |
+
our General Public Licenses are intended to guarantee your freedom to
|
| 17 |
+
share and change all versions of a program--to make sure it remains free
|
| 18 |
+
software for all its users.
|
| 19 |
+
|
| 20 |
+
When we speak of free software, we are referring to freedom, not
|
| 21 |
+
price. Our General Public Licenses are designed to make sure that you
|
| 22 |
+
have the freedom to distribute copies of free software (and charge for
|
| 23 |
+
them if you wish), that you receive source code or can get it if you
|
| 24 |
+
want it, that you can change the software or use pieces of it in new
|
| 25 |
+
free programs, and that you know you can do these things.
|
| 26 |
+
|
| 27 |
+
Developers that use our General Public Licenses protect your rights
|
| 28 |
+
with two steps: (1) assert copyright on the software, and (2) offer
|
| 29 |
+
you this License which gives you legal permission to copy, distribute
|
| 30 |
+
and/or modify the software.
|
| 31 |
+
|
| 32 |
+
A secondary benefit of defending all users' freedom is that
|
| 33 |
+
improvements made in alternate versions of the program, if they
|
| 34 |
+
receive widespread use, become available for other developers to
|
| 35 |
+
incorporate. Many developers of free software are heartened and
|
| 36 |
+
encouraged by the resulting cooperation. However, in the case of
|
| 37 |
+
software used on network servers, this result may fail to come about.
|
| 38 |
+
The GNU General Public License permits making a modified version and
|
| 39 |
+
letting the public access it on a server without ever releasing its
|
| 40 |
+
source code to the public.
|
| 41 |
+
|
| 42 |
+
The GNU Affero General Public License is designed specifically to
|
| 43 |
+
ensure that, in such cases, the modified source code becomes available
|
| 44 |
+
to the community. It requires the operator of a network server to
|
| 45 |
+
provide the source code of the modified version running there to the
|
| 46 |
+
users of that server. Therefore, public use of a modified version, on
|
| 47 |
+
a publicly accessible server, gives the public access to the source
|
| 48 |
+
code of the modified version.
|
| 49 |
+
|
| 50 |
+
An older license, called the Affero General Public License and
|
| 51 |
+
published by Affero, was designed to accomplish similar goals. This is
|
| 52 |
+
a different license, not a version of the Affero GPL, but Affero has
|
| 53 |
+
released a new version of the Affero GPL which permits relicensing under
|
| 54 |
+
this license.
|
| 55 |
+
|
| 56 |
+
The precise terms and conditions for copying, distribution and
|
| 57 |
+
modification follow.
|
| 58 |
+
|
| 59 |
+
TERMS AND CONDITIONS
|
| 60 |
+
|
| 61 |
+
0. Definitions.
|
| 62 |
+
|
| 63 |
+
"This License" refers to version 3 of the GNU Affero General Public License.
|
| 64 |
+
|
| 65 |
+
"Copyright" also means copyright-like laws that apply to other kinds of
|
| 66 |
+
works, such as semiconductor masks.
|
| 67 |
+
|
| 68 |
+
"The Program" refers to any copyrightable work licensed under this
|
| 69 |
+
License. Each licensee is addressed as "you". "Licensees" and
|
| 70 |
+
"recipients" may be individuals or organizations.
|
| 71 |
+
|
| 72 |
+
To "modify" a work means to copy from or adapt all or part of the work
|
| 73 |
+
in a fashion requiring copyright permission, other than the making of an
|
| 74 |
+
exact copy. The resulting work is called a "modified version" of the
|
| 75 |
+
earlier work or a work "based on" the earlier work.
|
| 76 |
+
|
| 77 |
+
A "covered work" means either the unmodified Program or a work based
|
| 78 |
+
on the Program.
|
| 79 |
+
|
| 80 |
+
To "propagate" a work means to do anything with it that, without
|
| 81 |
+
permission, would make you directly or secondarily liable for
|
| 82 |
+
infringement under applicable copyright law, except executing it on a
|
| 83 |
+
computer or modifying a private copy. Propagation includes copying,
|
| 84 |
+
distribution (with or without modification), making available to the
|
| 85 |
+
public, and in some countries other activities as well.
|
| 86 |
+
|
| 87 |
+
To "convey" a work means any kind of propagation that enables other
|
| 88 |
+
parties to make or receive copies. Mere interaction with a user through
|
| 89 |
+
a computer network, with no transfer of a copy, is not conveying.
|
| 90 |
+
|
| 91 |
+
An interactive user interface displays "Appropriate Legal Notices"
|
| 92 |
+
to the extent that it includes a convenient and prominently visible
|
| 93 |
+
feature that (1) displays an appropriate copyright notice, and (2)
|
| 94 |
+
tells the user that there is no warranty for the work (except to the
|
| 95 |
+
extent that warranties are provided), that licensees may convey the
|
| 96 |
+
work under this License, and how to view a copy of this License. If
|
| 97 |
+
the interface presents a list of user commands or options, such as a
|
| 98 |
+
menu, a prominent item in the list meets this criterion.
|
| 99 |
+
|
| 100 |
+
1. Source Code.
|
| 101 |
+
|
| 102 |
+
The "source code" for a work means the preferred form of the work
|
| 103 |
+
for making modifications to it. "Object code" means any non-source
|
| 104 |
+
form of a work.
|
| 105 |
+
|
| 106 |
+
A "Standard Interface" means an interface that either is an official
|
| 107 |
+
standard defined by a recognized standards body, or, in the case of
|
| 108 |
+
interfaces specified for a particular programming language, one that
|
| 109 |
+
is widely used among developers working in that language.
|
| 110 |
+
|
| 111 |
+
The "System Libraries" of an executable work include anything, other
|
| 112 |
+
than the work as a whole, that (a) is included in the normal form of
|
| 113 |
+
packaging a Major Component, but which is not part of that Major
|
| 114 |
+
Component, and (b) serves only to enable use of the work with that
|
| 115 |
+
Major Component, or to implement a Standard Interface for which an
|
| 116 |
+
implementation is available to the public in source code form. A
|
| 117 |
+
"Major Component", in this context, means a major essential component
|
| 118 |
+
(kernel, window system, and so on) of the specific operating system
|
| 119 |
+
(if any) on which the executable work runs, or a compiler used to
|
| 120 |
+
produce the work, or an object code interpreter used to run it.
|
| 121 |
+
|
| 122 |
+
The "Corresponding Source" for a work in object code form means all
|
| 123 |
+
the source code needed to generate, install, and (for an executable
|
| 124 |
+
work) run the object code and to modify the work, including scripts to
|
| 125 |
+
control those activities. However, it does not include the work's
|
| 126 |
+
System Libraries, or general-purpose tools or generally available free
|
| 127 |
+
programs which are used unmodified in performing those activities but
|
| 128 |
+
which are not part of the work. For example, Corresponding Source
|
| 129 |
+
includes interface definition files associated with source files for
|
| 130 |
+
the work, and the source code for shared libraries and dynamically
|
| 131 |
+
linked subprograms that the work is specifically designed to require,
|
| 132 |
+
such as by intimate data communication or control flow between those
|
| 133 |
+
subprograms and other parts of the work.
|
| 134 |
+
|
| 135 |
+
The Corresponding Source need not include anything that users
|
| 136 |
+
can regenerate automatically from other parts of the Corresponding
|
| 137 |
+
Source.
|
| 138 |
+
|
| 139 |
+
The Corresponding Source for a work in source code form is that
|
| 140 |
+
same work.
|
| 141 |
+
|
| 142 |
+
2. Basic Permissions.
|
| 143 |
+
|
| 144 |
+
All rights granted under this License are granted for the term of
|
| 145 |
+
copyright on the Program, and are irrevocable provided the stated
|
| 146 |
+
conditions are met. This License explicitly affirms your unlimited
|
| 147 |
+
permission to run the unmodified Program. The output from running a
|
| 148 |
+
covered work is covered by this License only if the output, given its
|
| 149 |
+
content, constitutes a covered work. This License acknowledges your
|
| 150 |
+
rights of fair use or other equivalent, as provided by copyright law.
|
| 151 |
+
|
| 152 |
+
You may make, run and propagate covered works that you do not
|
| 153 |
+
convey, without conditions so long as your license otherwise remains
|
| 154 |
+
in force. You may convey covered works to others for the sole purpose
|
| 155 |
+
of having them make modifications exclusively for you, or provide you
|
| 156 |
+
with facilities for running those works, provided that you comply with
|
| 157 |
+
the terms of this License in conveying all material for which you do
|
| 158 |
+
not control copyright. Those thus making or running the covered works
|
| 159 |
+
for you must do so exclusively on your behalf, under your direction
|
| 160 |
+
and control, on terms that prohibit them from making any copies of
|
| 161 |
+
your copyrighted material outside their relationship with you.
|
| 162 |
+
|
| 163 |
+
Conveying under any other circumstances is permitted solely under
|
| 164 |
+
the conditions stated below. Sublicensing is not allowed; section 10
|
| 165 |
+
makes it unnecessary.
|
| 166 |
+
|
| 167 |
+
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
| 168 |
+
|
| 169 |
+
No covered work shall be deemed part of an effective technological
|
| 170 |
+
measure under any applicable law fulfilling obligations under article
|
| 171 |
+
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
| 172 |
+
similar laws prohibiting or restricting circumvention of such
|
| 173 |
+
measures.
|
| 174 |
+
|
| 175 |
+
When you convey a covered work, you waive any legal power to forbid
|
| 176 |
+
circumvention of technological measures to the extent such circumvention
|
| 177 |
+
is effected by exercising rights under this License with respect to
|
| 178 |
+
the covered work, and you disclaim any intention to limit operation or
|
| 179 |
+
modification of the work as a means of enforcing, against the work's
|
| 180 |
+
users, your or third parties' legal rights to forbid circumvention of
|
| 181 |
+
technological measures.
|
| 182 |
+
|
| 183 |
+
4. Conveying Verbatim Copies.
|
| 184 |
+
|
| 185 |
+
You may convey verbatim copies of the Program's source code as you
|
| 186 |
+
receive it, in any medium, provided that you conspicuously and
|
| 187 |
+
appropriately publish on each copy an appropriate copyright notice;
|
| 188 |
+
keep intact all notices stating that this License and any
|
| 189 |
+
non-permissive terms added in accord with section 7 apply to the code;
|
| 190 |
+
keep intact all notices of the absence of any warranty; and give all
|
| 191 |
+
recipients a copy of this License along with the Program.
|
| 192 |
+
|
| 193 |
+
You may charge any price or no price for each copy that you convey,
|
| 194 |
+
and you may offer support or warranty protection for a fee.
|
| 195 |
+
|
| 196 |
+
5. Conveying Modified Source Versions.
|
| 197 |
+
|
| 198 |
+
You may convey a work based on the Program, or the modifications to
|
| 199 |
+
produce it from the Program, in the form of source code under the
|
| 200 |
+
terms of section 4, provided that you also meet all of these conditions:
|
| 201 |
+
|
| 202 |
+
a) The work must carry prominent notices stating that you modified
|
| 203 |
+
it, and giving a relevant date.
|
| 204 |
+
|
| 205 |
+
b) The work must carry prominent notices stating that it is
|
| 206 |
+
released under this License and any conditions added under section
|
| 207 |
+
7. This requirement modifies the requirement in section 4 to
|
| 208 |
+
"keep intact all notices".
|
| 209 |
+
|
| 210 |
+
c) You must license the entire work, as a whole, under this
|
| 211 |
+
License to anyone who comes into possession of a copy. This
|
| 212 |
+
License will therefore apply, along with any applicable section 7
|
| 213 |
+
additional terms, to the whole of the work, and all its parts,
|
| 214 |
+
regardless of how they are packaged. This License gives no
|
| 215 |
+
permission to license the work in any other way, but it does not
|
| 216 |
+
invalidate such permission if you have separately received it.
|
| 217 |
+
|
| 218 |
+
d) If the work has interactive user interfaces, each must display
|
| 219 |
+
Appropriate Legal Notices; however, if the Program has interactive
|
| 220 |
+
interfaces that do not display Appropriate Legal Notices, your
|
| 221 |
+
work need not make them do so.
|
| 222 |
+
|
| 223 |
+
A compilation of a covered work with other separate and independent
|
| 224 |
+
works, which are not by their nature extensions of the covered work,
|
| 225 |
+
and which are not combined with it such as to form a larger program,
|
| 226 |
+
in or on a volume of a storage or distribution medium, is called an
|
| 227 |
+
"aggregate" if the compilation and its resulting copyright are not
|
| 228 |
+
used to limit the access or legal rights of the compilation's users
|
| 229 |
+
beyond what the individual works permit. Inclusion of a covered work
|
| 230 |
+
in an aggregate does not cause this License to apply to the other
|
| 231 |
+
parts of the aggregate.
|
| 232 |
+
|
| 233 |
+
6. Conveying Non-Source Forms.
|
| 234 |
+
|
| 235 |
+
You may convey a covered work in object code form under the terms
|
| 236 |
+
of sections 4 and 5, provided that you also convey the
|
| 237 |
+
machine-readable Corresponding Source under the terms of this License,
|
| 238 |
+
in one of these ways:
|
| 239 |
+
|
| 240 |
+
a) Convey the object code in, or embodied in, a physical product
|
| 241 |
+
(including a physical distribution medium), accompanied by the
|
| 242 |
+
Corresponding Source fixed on a durable physical medium
|
| 243 |
+
customarily used for software interchange.
|
| 244 |
+
|
| 245 |
+
b) Convey the object code in, or embodied in, a physical product
|
| 246 |
+
(including a physical distribution medium), accompanied by a
|
| 247 |
+
written offer, valid for at least three years and valid for as
|
| 248 |
+
long as you offer spare parts or customer support for that product
|
| 249 |
+
model, to give anyone who possesses the object code either (1) a
|
| 250 |
+
copy of the Corresponding Source for all the software in the
|
| 251 |
+
product that is covered by this License, on a durable physical
|
| 252 |
+
medium customarily used for software interchange, for a price no
|
| 253 |
+
more than your reasonable cost of physically performing this
|
| 254 |
+
conveying of source, or (2) access to copy the
|
| 255 |
+
Corresponding Source from a network server at no charge.
|
| 256 |
+
|
| 257 |
+
c) Convey individual copies of the object code with a copy of the
|
| 258 |
+
written offer to provide the Corresponding Source. This
|
| 259 |
+
alternative is allowed only occasionally and noncommercially, and
|
| 260 |
+
only if you received the object code with such an offer, in accord
|
| 261 |
+
with subsection 6b.
|
| 262 |
+
|
| 263 |
+
d) Convey the object code by offering access from a designated
|
| 264 |
+
place (gratis or for a charge), and offer equivalent access to the
|
| 265 |
+
Corresponding Source in the same way through the same place at no
|
| 266 |
+
further charge. You need not require recipients to copy the
|
| 267 |
+
Corresponding Source along with the object code. If the place to
|
| 268 |
+
copy the object code is a network server, the Corresponding Source
|
| 269 |
+
may be on a different server (operated by you or a third party)
|
| 270 |
+
that supports equivalent copying facilities, provided you maintain
|
| 271 |
+
clear directions next to the object code saying where to find the
|
| 272 |
+
Corresponding Source. Regardless of what server hosts the
|
| 273 |
+
Corresponding Source, you remain obligated to ensure that it is
|
| 274 |
+
available for as long as needed to satisfy these requirements.
|
| 275 |
+
|
| 276 |
+
e) Convey the object code using peer-to-peer transmission, provided
|
| 277 |
+
you inform other peers where the object code and Corresponding
|
| 278 |
+
Source of the work are being offered to the general public at no
|
| 279 |
+
charge under subsection 6d.
|
| 280 |
+
|
| 281 |
+
A separable portion of the object code, whose source code is excluded
|
| 282 |
+
from the Corresponding Source as a System Library, need not be
|
| 283 |
+
included in conveying the object code work.
|
| 284 |
+
|
| 285 |
+
A "User Product" is either (1) a "consumer product", which means any
|
| 286 |
+
tangible personal property which is normally used for personal, family,
|
| 287 |
+
or household purposes, or (2) anything designed or sold for incorporation
|
| 288 |
+
into a dwelling. In determining whether a product is a consumer product,
|
| 289 |
+
doubtful cases shall be resolved in favor of coverage. For a particular
|
| 290 |
+
product received by a particular user, "normally used" refers to a
|
| 291 |
+
typical or common use of that class of product, regardless of the status
|
| 292 |
+
of the particular user or of the way in which the particular user
|
| 293 |
+
actually uses, or expects or is expected to use, the product. A product
|
| 294 |
+
is a consumer product regardless of whether the product has substantial
|
| 295 |
+
commercial, industrial or non-consumer uses, unless such uses represent
|
| 296 |
+
the only significant mode of use of the product.
|
| 297 |
+
|
| 298 |
+
"Installation Information" for a User Product means any methods,
|
| 299 |
+
procedures, authorization keys, or other information required to install
|
| 300 |
+
and execute modified versions of a covered work in that User Product from
|
| 301 |
+
a modified version of its Corresponding Source. The information must
|
| 302 |
+
suffice to ensure that the continued functioning of the modified object
|
| 303 |
+
code is in no case prevented or interfered with solely because
|
| 304 |
+
modification has been made.
|
| 305 |
+
|
| 306 |
+
If you convey an object code work under this section in, or with, or
|
| 307 |
+
specifically for use in, a User Product, and the conveying occurs as
|
| 308 |
+
part of a transaction in which the right of possession and use of the
|
| 309 |
+
User Product is transferred to the recipient in perpetuity or for a
|
| 310 |
+
fixed term (regardless of how the transaction is characterized), the
|
| 311 |
+
Corresponding Source conveyed under this section must be accompanied
|
| 312 |
+
by the Installation Information. But this requirement does not apply
|
| 313 |
+
if neither you nor any third party retains the ability to install
|
| 314 |
+
modified object code on the User Product (for example, the work has
|
| 315 |
+
been installed in ROM).
|
| 316 |
+
|
| 317 |
+
The requirement to provide Installation Information does not include a
|
| 318 |
+
requirement to continue to provide support service, warranty, or updates
|
| 319 |
+
for a work that has been modified or installed by the recipient, or for
|
| 320 |
+
the User Product in which it has been modified or installed. Access to a
|
| 321 |
+
network may be denied when the modification itself materially and
|
| 322 |
+
adversely affects the operation of the network or violates the rules and
|
| 323 |
+
protocols for communication across the network.
|
| 324 |
+
|
| 325 |
+
Corresponding Source conveyed, and Installation Information provided,
|
| 326 |
+
in accord with this section must be in a format that is publicly
|
| 327 |
+
documented (and with an implementation available to the public in
|
| 328 |
+
source code form), and must require no special password or key for
|
| 329 |
+
unpacking, reading or copying.
|
| 330 |
+
|
| 331 |
+
7. Additional Terms.
|
| 332 |
+
|
| 333 |
+
"Additional permissions" are terms that supplement the terms of this
|
| 334 |
+
License by making exceptions from one or more of its conditions.
|
| 335 |
+
Additional permissions that are applicable to the entire Program shall
|
| 336 |
+
be treated as though they were included in this License, to the extent
|
| 337 |
+
that they are valid under applicable law. If additional permissions
|
| 338 |
+
apply only to part of the Program, that part may be used separately
|
| 339 |
+
under those permissions, but the entire Program remains governed by
|
| 340 |
+
this License without regard to the additional permissions.
|
| 341 |
+
|
| 342 |
+
When you convey a copy of a covered work, you may at your option
|
| 343 |
+
remove any additional permissions from that copy, or from any part of
|
| 344 |
+
it. (Additional permissions may be written to require their own
|
| 345 |
+
removal in certain cases when you modify the work.) You may place
|
| 346 |
+
additional permissions on material, added by you to a covered work,
|
| 347 |
+
for which you have or can give appropriate copyright permission.
|
| 348 |
+
|
| 349 |
+
Notwithstanding any other provision of this License, for material you
|
| 350 |
+
add to a covered work, you may (if authorized by the copyright holders of
|
| 351 |
+
that material) supplement the terms of this License with terms:
|
| 352 |
+
|
| 353 |
+
a) Disclaiming warranty or limiting liability differently from the
|
| 354 |
+
terms of sections 15 and 16 of this License; or
|
| 355 |
+
|
| 356 |
+
b) Requiring preservation of specified reasonable legal notices or
|
| 357 |
+
author attributions in that material or in the Appropriate Legal
|
| 358 |
+
Notices displayed by works containing it; or
|
| 359 |
+
|
| 360 |
+
c) Prohibiting misrepresentation of the origin of that material, or
|
| 361 |
+
requiring that modified versions of such material be marked in
|
| 362 |
+
reasonable ways as different from the original version; or
|
| 363 |
+
|
| 364 |
+
d) Limiting the use for publicity purposes of names of licensors or
|
| 365 |
+
authors of the material; or
|
| 366 |
+
|
| 367 |
+
e) Declining to grant rights under trademark law for use of some
|
| 368 |
+
trade names, trademarks, or service marks; or
|
| 369 |
+
|
| 370 |
+
f) Requiring indemnification of licensors and authors of that
|
| 371 |
+
material by anyone who conveys the material (or modified versions of
|
| 372 |
+
it) with contractual assumptions of liability to the recipient, for
|
| 373 |
+
any liability that these contractual assumptions directly impose on
|
| 374 |
+
those licensors and authors.
|
| 375 |
+
|
| 376 |
+
All other non-permissive additional terms are considered "further
|
| 377 |
+
restrictions" within the meaning of section 10. If the Program as you
|
| 378 |
+
received it, or any part of it, contains a notice stating that it is
|
| 379 |
+
governed by this License along with a term that is a further
|
| 380 |
+
restriction, you may remove that term. If a license document contains
|
| 381 |
+
a further restriction but permits relicensing or conveying under this
|
| 382 |
+
License, you may add to a covered work material governed by the terms
|
| 383 |
+
of that license document, provided that the further restriction does
|
| 384 |
+
not survive such relicensing or conveying.
|
| 385 |
+
|
| 386 |
+
If you add terms to a covered work in accord with this section, you
|
| 387 |
+
must place, in the relevant source files, a statement of the
|
| 388 |
+
additional terms that apply to those files, or a notice indicating
|
| 389 |
+
where to find the applicable terms.
|
| 390 |
+
|
| 391 |
+
Additional terms, permissive or non-permissive, may be stated in the
|
| 392 |
+
form of a separately written license, or stated as exceptions;
|
| 393 |
+
the above requirements apply either way.
|
| 394 |
+
|
| 395 |
+
8. Termination.
|
| 396 |
+
|
| 397 |
+
You may not propagate or modify a covered work except as expressly
|
| 398 |
+
provided under this License. Any attempt otherwise to propagate or
|
| 399 |
+
modify it is void, and will automatically terminate your rights under
|
| 400 |
+
this License (including any patent licenses granted under the third
|
| 401 |
+
paragraph of section 11).
|
| 402 |
+
|
| 403 |
+
However, if you cease all violation of this License, then your
|
| 404 |
+
license from a particular copyright holder is reinstated (a)
|
| 405 |
+
provisionally, unless and until the copyright holder explicitly and
|
| 406 |
+
finally terminates your license, and (b) permanently, if the copyright
|
| 407 |
+
holder fails to notify you of the violation by some reasonable means
|
| 408 |
+
prior to 60 days after the cessation.
|
| 409 |
+
|
| 410 |
+
Moreover, your license from a particular copyright holder is
|
| 411 |
+
reinstated permanently if the copyright holder notifies you of the
|
| 412 |
+
violation by some reasonable means, this is the first time you have
|
| 413 |
+
received notice of violation of this License (for any work) from that
|
| 414 |
+
copyright holder, and you cure the violation prior to 30 days after
|
| 415 |
+
your receipt of the notice.
|
| 416 |
+
|
| 417 |
+
Termination of your rights under this section does not terminate the
|
| 418 |
+
licenses of parties who have received copies or rights from you under
|
| 419 |
+
this License. If your rights have been terminated and not permanently
|
| 420 |
+
reinstated, you do not qualify to receive new licenses for the same
|
| 421 |
+
material under section 10.
|
| 422 |
+
|
| 423 |
+
9. Acceptance Not Required for Having Copies.
|
| 424 |
+
|
| 425 |
+
You are not required to accept this License in order to receive or
|
| 426 |
+
run a copy of the Program. Ancillary propagation of a covered work
|
| 427 |
+
occurring solely as a consequence of using peer-to-peer transmission
|
| 428 |
+
to receive a copy likewise does not require acceptance. However,
|
| 429 |
+
nothing other than this License grants you permission to propagate or
|
| 430 |
+
modify any covered work. These actions infringe copyright if you do
|
| 431 |
+
not accept this License. Therefore, by modifying or propagating a
|
| 432 |
+
covered work, you indicate your acceptance of this License to do so.
|
| 433 |
+
|
| 434 |
+
10. Automatic Licensing of Downstream Recipients.
|
| 435 |
+
|
| 436 |
+
Each time you convey a covered work, the recipient automatically
|
| 437 |
+
receives a license from the original licensors, to run, modify and
|
| 438 |
+
propagate that work, subject to this License. You are not responsible
|
| 439 |
+
for enforcing compliance by third parties with this License.
|
| 440 |
+
|
| 441 |
+
An "entity transaction" is a transaction transferring control of an
|
| 442 |
+
organization, or substantially all assets of one, or subdividing an
|
| 443 |
+
organization, or merging organizations. If propagation of a covered
|
| 444 |
+
work results from an entity transaction, each party to that
|
| 445 |
+
transaction who receives a copy of the work also receives whatever
|
| 446 |
+
licenses to the work the party's predecessor in interest had or could
|
| 447 |
+
give under the previous paragraph, plus a right to possession of the
|
| 448 |
+
Corresponding Source of the work from the predecessor in interest, if
|
| 449 |
+
the predecessor has it or can get it with reasonable efforts.
|
| 450 |
+
|
| 451 |
+
You may not impose any further restrictions on the exercise of the
|
| 452 |
+
rights granted or affirmed under this License. For example, you may
|
| 453 |
+
not impose a license fee, royalty, or other charge for exercise of
|
| 454 |
+
rights granted under this License, and you may not initiate litigation
|
| 455 |
+
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
| 456 |
+
any patent claim is infringed by making, using, selling, offering for
|
| 457 |
+
sale, or importing the Program or any portion of it.
|
| 458 |
+
|
| 459 |
+
11. Patents.
|
| 460 |
+
|
| 461 |
+
A "contributor" is a copyright holder who authorizes use under this
|
| 462 |
+
License of the Program or a work on which the Program is based. The
|
| 463 |
+
work thus licensed is called the contributor's "contributor version".
|
| 464 |
+
|
| 465 |
+
A contributor's "essential patent claims" are all patent claims
|
| 466 |
+
owned or controlled by the contributor, whether already acquired or
|
| 467 |
+
hereafter acquired, that would be infringed by some manner, permitted
|
| 468 |
+
by this License, of making, using, or selling its contributor version,
|
| 469 |
+
but do not include claims that would be infringed only as a
|
| 470 |
+
consequence of further modification of the contributor version. For
|
| 471 |
+
purposes of this definition, "control" includes the right to grant
|
| 472 |
+
patent sublicenses in a manner consistent with the requirements of
|
| 473 |
+
this License.
|
| 474 |
+
|
| 475 |
+
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
| 476 |
+
patent license under the contributor's essential patent claims, to
|
| 477 |
+
make, use, sell, offer for sale, import and otherwise run, modify and
|
| 478 |
+
propagate the contents of its contributor version.
|
| 479 |
+
|
| 480 |
+
In the following three paragraphs, a "patent license" is any express
|
| 481 |
+
agreement or commitment, however denominated, not to enforce a patent
|
| 482 |
+
(such as an express permission to practice a patent or covenant not to
|
| 483 |
+
sue for patent infringement). To "grant" such a patent license to a
|
| 484 |
+
party means to make such an agreement or commitment not to enforce a
|
| 485 |
+
patent against the party.
|
| 486 |
+
|
| 487 |
+
If you convey a covered work, knowingly relying on a patent license,
|
| 488 |
+
and the Corresponding Source of the work is not available for anyone
|
| 489 |
+
to copy, free of charge and under the terms of this License, through a
|
| 490 |
+
publicly available network server or other readily accessible means,
|
| 491 |
+
then you must either (1) cause the Corresponding Source to be so
|
| 492 |
+
available, or (2) arrange to deprive yourself of the benefit of the
|
| 493 |
+
patent license for this particular work, or (3) arrange, in a manner
|
| 494 |
+
consistent with the requirements of this License, to extend the patent
|
| 495 |
+
license to downstream recipients. "Knowingly relying" means you have
|
| 496 |
+
actual knowledge that, but for the patent license, your conveying the
|
| 497 |
+
covered work in a country, or your recipient's use of the covered work
|
| 498 |
+
in a country, would infringe one or more identifiable patents in that
|
| 499 |
+
country that you have reason to believe are valid.
|
| 500 |
+
|
| 501 |
+
If, pursuant to or in connection with a single transaction or
|
| 502 |
+
arrangement, you convey, or propagate by procuring conveyance of, a
|
| 503 |
+
covered work, and grant a patent license to some of the parties
|
| 504 |
+
receiving the covered work authorizing them to use, propagate, modify
|
| 505 |
+
or convey a specific copy of the covered work, then the patent license
|
| 506 |
+
you grant is automatically extended to all recipients of the covered
|
| 507 |
+
work and works based on it.
|
| 508 |
+
|
| 509 |
+
A patent license is "discriminatory" if it does not include within
|
| 510 |
+
the scope of its coverage, prohibits the exercise of, or is
|
| 511 |
+
conditioned on the non-exercise of one or more of the rights that are
|
| 512 |
+
specifically granted under this License. You may not convey a covered
|
| 513 |
+
work if you are a party to an arrangement with a third party that is
|
| 514 |
+
in the business of distributing software, under which you make payment
|
| 515 |
+
to the third party based on the extent of your activity of conveying
|
| 516 |
+
the work, and under which the third party grants, to any of the
|
| 517 |
+
parties who would receive the covered work from you, a discriminatory
|
| 518 |
+
patent license (a) in connection with copies of the covered work
|
| 519 |
+
conveyed by you (or copies made from those copies), or (b) primarily
|
| 520 |
+
for and in connection with specific products or compilations that
|
| 521 |
+
contain the covered work, unless you entered into that arrangement,
|
| 522 |
+
or that patent license was granted, prior to 28 March 2007.
|
| 523 |
+
|
| 524 |
+
Nothing in this License shall be construed as excluding or limiting
|
| 525 |
+
any implied license or other defenses to infringement that may
|
| 526 |
+
otherwise be available to you under applicable patent law.
|
| 527 |
+
|
| 528 |
+
12. No Surrender of Others' Freedom.
|
| 529 |
+
|
| 530 |
+
If conditions are imposed on you (whether by court order, agreement or
|
| 531 |
+
otherwise) that contradict the conditions of this License, they do not
|
| 532 |
+
excuse you from the conditions of this License. If you cannot convey a
|
| 533 |
+
covered work so as to satisfy simultaneously your obligations under this
|
| 534 |
+
License and any other pertinent obligations, then as a consequence you may
|
| 535 |
+
not convey it at all. For example, if you agree to terms that obligate you
|
| 536 |
+
to collect a royalty for further conveying from those to whom you convey
|
| 537 |
+
the Program, the only way you could satisfy both those terms and this
|
| 538 |
+
License would be to refrain entirely from conveying the Program.
|
| 539 |
+
|
| 540 |
+
13. Remote Network Interaction; Use with the GNU General Public License.
|
| 541 |
+
|
| 542 |
+
Notwithstanding any other provision of this License, if you modify the
|
| 543 |
+
Program, your modified version must prominently offer all users
|
| 544 |
+
interacting with it remotely through a computer network (if your version
|
| 545 |
+
supports such interaction) an opportunity to receive the Corresponding
|
| 546 |
+
Source of your version by providing access to the Corresponding Source
|
| 547 |
+
from a network server at no charge, through some standard or customary
|
| 548 |
+
means of facilitating copying of software. This Corresponding Source
|
| 549 |
+
shall include the Corresponding Source for any work covered by version 3
|
| 550 |
+
of the GNU General Public License that is incorporated pursuant to the
|
| 551 |
+
following paragraph.
|
| 552 |
+
|
| 553 |
+
Notwithstanding any other provision of this License, you have
|
| 554 |
+
permission to link or combine any covered work with a work licensed
|
| 555 |
+
under version 3 of the GNU General Public License into a single
|
| 556 |
+
combined work, and to convey the resulting work. The terms of this
|
| 557 |
+
License will continue to apply to the part which is the covered work,
|
| 558 |
+
but the work with which it is combined will remain governed by version
|
| 559 |
+
3 of the GNU General Public License.
|
| 560 |
+
|
| 561 |
+
14. Revised Versions of this License.
|
| 562 |
+
|
| 563 |
+
The Free Software Foundation may publish revised and/or new versions of
|
| 564 |
+
the GNU Affero General Public License from time to time. Such new versions
|
| 565 |
+
will be similar in spirit to the present version, but may differ in detail to
|
| 566 |
+
address new problems or concerns.
|
| 567 |
+
|
| 568 |
+
Each version is given a distinguishing version number. If the
|
| 569 |
+
Program specifies that a certain numbered version of the GNU Affero General
|
| 570 |
+
Public License "or any later version" applies to it, you have the
|
| 571 |
+
option of following the terms and conditions either of that numbered
|
| 572 |
+
version or of any later version published by the Free Software
|
| 573 |
+
Foundation. If the Program does not specify a version number of the
|
| 574 |
+
GNU Affero General Public License, you may choose any version ever published
|
| 575 |
+
by the Free Software Foundation.
|
| 576 |
+
|
| 577 |
+
If the Program specifies that a proxy can decide which future
|
| 578 |
+
versions of the GNU Affero General Public License can be used, that proxy's
|
| 579 |
+
public statement of acceptance of a version permanently authorizes you
|
| 580 |
+
to choose that version for the Program.
|
| 581 |
+
|
| 582 |
+
Later license versions may give you additional or different
|
| 583 |
+
permissions. However, no additional obligations are imposed on any
|
| 584 |
+
author or copyright holder as a result of your choosing to follow a
|
| 585 |
+
later version.
|
| 586 |
+
|
| 587 |
+
15. Disclaimer of Warranty.
|
| 588 |
+
|
| 589 |
+
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
| 590 |
+
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
| 591 |
+
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
| 592 |
+
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
| 593 |
+
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
| 594 |
+
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
| 595 |
+
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
| 596 |
+
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
| 597 |
+
|
| 598 |
+
16. Limitation of Liability.
|
| 599 |
+
|
| 600 |
+
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
| 601 |
+
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
| 602 |
+
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
| 603 |
+
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
| 604 |
+
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
| 605 |
+
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
| 606 |
+
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
| 607 |
+
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
| 608 |
+
SUCH DAMAGES.
|
| 609 |
+
|
| 610 |
+
17. Interpretation of Sections 15 and 16.
|
| 611 |
+
|
| 612 |
+
If the disclaimer of warranty and limitation of liability provided
|
| 613 |
+
above cannot be given local legal effect according to their terms,
|
| 614 |
+
reviewing courts shall apply local law that most closely approximates
|
| 615 |
+
an absolute waiver of all civil liability in connection with the
|
| 616 |
+
Program, unless a warranty or assumption of liability accompanies a
|
| 617 |
+
copy of the Program in return for a fee.
|
| 618 |
+
|
| 619 |
+
END OF TERMS AND CONDITIONS
|
| 620 |
+
|
| 621 |
+
How to Apply These Terms to Your New Programs
|
| 622 |
+
|
| 623 |
+
If you develop a new program, and you want it to be of the greatest
|
| 624 |
+
possible use to the public, the best way to achieve this is to make it
|
| 625 |
+
free software which everyone can redistribute and change under these terms.
|
| 626 |
+
|
| 627 |
+
To do so, attach the following notices to the program. It is safest
|
| 628 |
+
to attach them to the start of each source file to most effectively
|
| 629 |
+
state the exclusion of warranty; and each file should have at least
|
| 630 |
+
the "copyright" line and a pointer to where the full notice is found.
|
| 631 |
+
|
| 632 |
+
<one line to give the program's name and a brief idea of what it does.>
|
| 633 |
+
Copyright (C) <year> <name of author>
|
| 634 |
+
|
| 635 |
+
This program is free software: you can redistribute it and/or modify
|
| 636 |
+
it under the terms of the GNU Affero General Public License as published
|
| 637 |
+
by the Free Software Foundation, either version 3 of the License, or
|
| 638 |
+
(at your option) any later version.
|
| 639 |
+
|
| 640 |
+
This program is distributed in the hope that it will be useful,
|
| 641 |
+
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
| 642 |
+
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
| 643 |
+
GNU Affero General Public License for more details.
|
| 644 |
+
|
| 645 |
+
You should have received a copy of the GNU Affero General Public License
|
| 646 |
+
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
| 647 |
+
|
| 648 |
+
Also add information on how to contact you by electronic and paper mail.
|
| 649 |
+
|
| 650 |
+
If your software can interact with users remotely through a computer
|
| 651 |
+
network, you should also make sure that it provides a way for users to
|
| 652 |
+
get its source. For example, if your program is a web application, its
|
| 653 |
+
interface could display a "Source" link that leads users to an archive
|
| 654 |
+
of the code. There are many ways you could offer source, and different
|
| 655 |
+
solutions will be better for different programs; see section 13 for the
|
| 656 |
+
specific requirements.
|
| 657 |
+
|
| 658 |
+
You should also get your employer (if you work as a programmer) or school,
|
| 659 |
+
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
| 660 |
+
For more information on this, and how to apply and follow the GNU AGPL, see
|
| 661 |
+
<https://www.gnu.org/licenses/>.
|
README.md
ADDED
|
@@ -0,0 +1,406 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: PDF Translator
|
| 3 |
+
emoji: 📄
|
| 4 |
+
colorFrom: indigo
|
| 5 |
+
colorTo: blue
|
| 6 |
+
sdk: docker
|
| 7 |
+
app_port: 7860
|
| 8 |
+
pinned: false
|
| 9 |
+
---
|
| 10 |
+
|
| 11 |
+
# PDF Translator — End-to-End (OCR → Translate → Render)
|
| 12 |
+
|
| 13 |
+
A single Gradio app that runs a full document-translation pipeline and rebuilds a
|
| 14 |
+
**layout-faithful PDF** in the target language. It chains three phases into one
|
| 15 |
+
end-to-end flow:
|
| 16 |
+
|
| 17 |
+
| Phase | Package | What it does |
|
| 18 |
+
|-------|---------|--------------|
|
| 19 |
+
| **1 · Parse / OCR** | [`pdf2zh/parser`](pdf2zh/parser) | Layout detection + OCR (Surya) and table cells (PaddleOCR) → a structured `ParsedDocument` (JSON). |
|
| 20 |
+
| **2 · Translate** | [`pdf2zh/translation`](pdf2zh/translation) | Async, chunked LLM translation with glossary, math-fix, TOC-fix and vision passes. |
|
| 21 |
+
| **3 · Render** | [`pdf2zh/render`](pdf2zh/render) | Rebuilds the PDF with **Typst**, overlaying translated text on the original layout. |
|
| 22 |
+
|
| 23 |
+
- **Entry point:** [`app.py`](app.py) → warms up models, then launches the Gradio UI ([`pdf2zh/webapp/ui.py`](pdf2zh/webapp/ui.py)).
|
| 24 |
+
- **Orchestration:** [`pdf2zh/e2e.py`](pdf2zh/e2e.py) — `run_pipeline()` chains Phase 1 → 2 → 3.
|
| 25 |
+
|
| 26 |
+
---
|
| 27 |
+
|
| 28 |
+
## Table of contents
|
| 29 |
+
|
| 30 |
+
1. [How it works](#how-it-works)
|
| 31 |
+
2. [Prerequisites (exact versions)](#prerequisites-exact-versions)
|
| 32 |
+
3. [Quick start — Docker (recommended, closest to production)](#quick-start--docker-recommended-closest-to-production)
|
| 33 |
+
4. [Run locally without Docker (personal GPU / laptop)](#run-locally-without-docker-personal-gpu--laptop)
|
| 34 |
+
5. [Configuration reference (`.env`)](#configuration-reference-env)
|
| 35 |
+
6. [Model downloads & caching](#model-downloads--caching)
|
| 36 |
+
7. [Using the web app](#using-the-web-app)
|
| 37 |
+
8. [Command-line & programmatic use](#command-line--programmatic-use)
|
| 38 |
+
9. [Testing](#testing)
|
| 39 |
+
10. [Deploy to a Hugging Face Space](#deploy-to-a-hugging-face-space)
|
| 40 |
+
11. [Troubleshooting](#troubleshooting)
|
| 41 |
+
12. [Customizing](#customizing)
|
| 42 |
+
13. [Known limitations](#known-limitations)
|
| 43 |
+
14. [License](#license)
|
| 44 |
+
|
| 45 |
+
---
|
| 46 |
+
|
| 47 |
+
## How it works
|
| 48 |
+
|
| 49 |
+
```
|
| 50 |
+
app.py (Gradio UI, warmup() on boot, demo.queue serializes requests)
|
| 51 |
+
│
|
| 52 |
+
▼
|
| 53 |
+
pdf2zh/e2e.py :: run_pipeline(pdf_path, src_lang, tgt_lang, provider,
|
| 54 |
+
api_key, model, pages, font, work_dir, progress)
|
| 55 |
+
├─ Phase 1 get_parser().parse_pdf(...) # StageAParser — models loaded ONCE (singleton)
|
| 56 |
+
│ └─ writes work_dir/phase1_parsed.json
|
| 57 |
+
├─ Phase 2 translate_document(parsed_dict, TranslatorConfig)
|
| 58 |
+
│ └─ writes work_dir/phase2_translated.json
|
| 59 |
+
└─ Phase 3 render_document(pdf_path, translated_dict, out.pdf, RenderConfig)
|
| 60 |
+
└─ shells out to the `typst` binary → translated_<hash>.pdf
|
| 61 |
+
```
|
| 62 |
+
|
| 63 |
+
- **Model singleton** — `StageAParser` loads ~3–5 GB of OCR weights exactly once
|
| 64 |
+
(`warmup()` at startup), not per request. See [`pdf2zh/e2e.py`](pdf2zh/e2e.py).
|
| 65 |
+
- **Providers** — OpenRouter, Gemini, OpenAI, DeepSeek, MiniMax, Anthropic, LiteLLM.
|
| 66 |
+
The user supplies their **own API key** in the UI; nothing is stored server-side.
|
| 67 |
+
- **Fonts** — the chosen font heads a multilingual fallback chain
|
| 68 |
+
(Noto Sans / Noto Serif / Noto CJK / Be Vietnam Pro) so missing glyphs degrade
|
| 69 |
+
gracefully. The default Helvetica lacks Vietnamese glyphs and is always overridden.
|
| 70 |
+
|
| 71 |
+
---
|
| 72 |
+
|
| 73 |
+
## Prerequisites (exact versions)
|
| 74 |
+
|
| 75 |
+
Reproducing this project reliably means matching the following stack. Deviating
|
| 76 |
+
(especially on the OCR/GPU pins) is the most common cause of a broken build.
|
| 77 |
+
|
| 78 |
+
| Component | Version / constraint | Notes |
|
| 79 |
+
|-----------|----------------------|-------|
|
| 80 |
+
| **Python** | `>=3.10, <3.13` | 3.10 / 3.11 / 3.12 only. Set in [`pyproject.toml`](pyproject.toml). |
|
| 81 |
+
| **Typst** | `v0.14.2` binary on `PATH` | Phase 3 shells out to it. Later 0.x may work but is untested. |
|
| 82 |
+
| **CUDA (GPU path)** | **13.x** runtime + driver | Docker base = `nvidia/cuda:13.0.0-cudnn-runtime-ubuntu22.04`. |
|
| 83 |
+
| **surya-ocr** | `==0.17.1` (pinned) | 0.18+ dropped the `settings.*_BATCH_SIZE` API used by `hardware.py`. |
|
| 84 |
+
| **transformers** | `==4.56.1` (pinned) | Matches surya-ocr 0.17.1. |
|
| 85 |
+
| **paddleocr** | `==3.6.0` (pinned) | Table-cell recognition. |
|
| 86 |
+
| **paddlepaddle-gpu** | `==3.3.1` (cu130) | Installed from the `cu130` extra index (see `requirements.txt`). |
|
| 87 |
+
| **torch / torchvision / numpy** | unpinned | Left to pip so it resolves a CUDA stack compatible with paddle. |
|
| 88 |
+
| **Fonts** | Noto Sans, Noto Serif, Noto CJK, Be Vietnam Pro | Must be visible to Typst (bundled in the Docker image). |
|
| 89 |
+
|
| 90 |
+
> **GPU is strongly recommended.** Phase 1 (Surya + PaddleOCR + Torch) is slow on CPU.
|
| 91 |
+
> A single 16 GB T4 works for small page ranges; an A100 (80 GB) handles the full
|
| 92 |
+
> batch-size settings in `.env.example`. On Apple Silicon the parser auto-selects
|
| 93 |
+
> the `mps` device with reduced batch sizes.
|
| 94 |
+
|
| 95 |
+
---
|
| 96 |
+
|
| 97 |
+
## Quick start — Docker (recommended, closest to production)
|
| 98 |
+
|
| 99 |
+
Docker is the only path that pins **every** system dependency (CUDA, Typst, fonts,
|
| 100 |
+
locale). Use it for the most reproducible result.
|
| 101 |
+
|
| 102 |
+
```bash
|
| 103 |
+
# 1. Clone
|
| 104 |
+
git clone https://github.com/HoanggNguyen/PDFTranslator.git
|
| 105 |
+
cd PDFTranslator
|
| 106 |
+
|
| 107 |
+
# 2. Seed the environment file (the container also does this, but do it locally too)
|
| 108 |
+
cp .env.example .env
|
| 109 |
+
|
| 110 |
+
# 3. Build the image (installs CUDA deps, Typst v0.14.2, fonts, Python deps)
|
| 111 |
+
docker build -t pdf2zh .
|
| 112 |
+
|
| 113 |
+
# 4a. Run WITH a GPU (requires the NVIDIA Container Toolkit on the host)
|
| 114 |
+
docker run --gpus all -p 7860:7860 pdf2zh
|
| 115 |
+
|
| 116 |
+
# 4b. Run WITHOUT a GPU (CPU only — much slower, fine for testing wiring)
|
| 117 |
+
docker run -p 7860:7860 -e DEVICE=cpu pdf2zh
|
| 118 |
+
|
| 119 |
+
# 5. Open the app
|
| 120 |
+
# http://localhost:7860
|
| 121 |
+
```
|
| 122 |
+
|
| 123 |
+
**Persisting model weights across restarts** (avoid re-downloading ~3–5 GB):
|
| 124 |
+
|
| 125 |
+
```bash
|
| 126 |
+
docker run --gpus all -p 7860:7860 \
|
| 127 |
+
-v "$PWD/.model-cache:/data" \
|
| 128 |
+
pdf2zh
|
| 129 |
+
```
|
| 130 |
+
|
| 131 |
+
The container entrypoint prefers `/data` for all model caches when it is writable
|
| 132 |
+
(see the `entrypoint.sh` block in the [`Dockerfile`](Dockerfile)); mounting a host
|
| 133 |
+
volume there makes the weights survive container restarts.
|
| 134 |
+
|
| 135 |
+
> **NVIDIA Container Toolkit** is required for `--gpus all`. Install it on the host
|
| 136 |
+
> first: <https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/latest/install-guide.html>.
|
| 137 |
+
> Verify with `docker run --rm --gpus all nvidia/cuda:13.0.0-base-ubuntu22.04 nvidia-smi`.
|
| 138 |
+
|
| 139 |
+
---
|
| 140 |
+
|
| 141 |
+
## Run locally without Docker (personal GPU / laptop)
|
| 142 |
+
|
| 143 |
+
Use this when you want to develop against the code directly. You are responsible
|
| 144 |
+
for three system dependencies that Docker would otherwise provide: **Python 3.10–3.12**,
|
| 145 |
+
the **Typst binary**, and **fonts**.
|
| 146 |
+
|
| 147 |
+
### 1. Clone and create an isolated environment
|
| 148 |
+
|
| 149 |
+
```bash
|
| 150 |
+
git clone https://github.com/HoanggNguyen/PDFTranslator.git
|
| 151 |
+
cd PDFTranslator
|
| 152 |
+
|
| 153 |
+
python3.12 -m venv .venv # any 3.10–3.12 interpreter
|
| 154 |
+
source .venv/bin/activate # Windows: .venv\Scripts\activate
|
| 155 |
+
python -m pip install --upgrade pip
|
| 156 |
+
```
|
| 157 |
+
|
| 158 |
+
### 2. Install the Typst binary (v0.14.2)
|
| 159 |
+
|
| 160 |
+
Phase 3 calls the `typst` executable. It must be on `PATH` (or point `TYPST_BIN`
|
| 161 |
+
at it).
|
| 162 |
+
|
| 163 |
+
```bash
|
| 164 |
+
# macOS (Homebrew)
|
| 165 |
+
brew install typst # then verify the version is 0.14.x
|
| 166 |
+
typst --version
|
| 167 |
+
|
| 168 |
+
# Linux (x86_64) — pinned release, matches the Docker image
|
| 169 |
+
wget -qO /tmp/typst.tar.xz \
|
| 170 |
+
"https://github.com/typst/typst/releases/download/v0.14.2/typst-x86_64-unknown-linux-musl.tar.xz"
|
| 171 |
+
tar -xJf /tmp/typst.tar.xz -C /tmp
|
| 172 |
+
sudo install -m 0755 /tmp/typst-x86_64-unknown-linux-musl/typst /usr/local/bin/typst
|
| 173 |
+
typst --version
|
| 174 |
+
|
| 175 |
+
# Any platform (Cargo)
|
| 176 |
+
cargo install typst-cli --locked
|
| 177 |
+
```
|
| 178 |
+
|
| 179 |
+
### 3. Install fonts (Vietnamese + CJK coverage)
|
| 180 |
+
|
| 181 |
+
Typst renders with whatever fonts it can find. Install Noto (covers Vietnamese and
|
| 182 |
+
CJK) and optionally Be Vietnam Pro, then confirm Typst sees them:
|
| 183 |
+
|
| 184 |
+
- **Linux:** `sudo apt-get install -y fonts-noto-core fonts-noto-cjk && fc-cache -f`
|
| 185 |
+
- **macOS:** install the Noto families (e.g. via Homebrew casks or Google Fonts).
|
| 186 |
+
- Alternatively, drop `.ttf/.otf` files into a directory and set `PDF2ZH_FONT_DIR`
|
| 187 |
+
to it; the app passes that directory to Typst's `--font-path`.
|
| 188 |
+
|
| 189 |
+
```bash
|
| 190 |
+
typst fonts | grep -i noto # should list Noto families
|
| 191 |
+
```
|
| 192 |
+
|
| 193 |
+
### 4. Install Python dependencies
|
| 194 |
+
|
| 195 |
+
```bash
|
| 196 |
+
# GPU stack (Linux + CUDA 13) — installs paddlepaddle-gpu (cu130) via the extra index
|
| 197 |
+
pip install -r requirements.txt
|
| 198 |
+
|
| 199 |
+
# CPU / macOS: requirements.txt targets a CUDA GPU. On a machine without a
|
| 200 |
+
# CUDA GPU, edit requirements.txt to drop the `paddlepaddle-gpu` line and the
|
| 201 |
+
# cu130 --extra-index-url, and install the CPU wheel instead:
|
| 202 |
+
# pip install paddlepaddle==3.3.1
|
| 203 |
+
# then: pip install -r requirements.txt
|
| 204 |
+
```
|
| 205 |
+
|
| 206 |
+
### 5. Configure and run
|
| 207 |
+
|
| 208 |
+
```bash
|
| 209 |
+
cp .env.example .env # then edit as needed (see Configuration reference)
|
| 210 |
+
python app.py # warms up models, serves http://localhost:7860
|
| 211 |
+
```
|
| 212 |
+
|
| 213 |
+
The first launch downloads the OCR weights (~3–5 GB) — see the next section.
|
| 214 |
+
|
| 215 |
+
---
|
| 216 |
+
|
| 217 |
+
## Configuration reference (`.env`)
|
| 218 |
+
|
| 219 |
+
`.env` is **gitignored**; [`.env.example`](.env.example) is the tracked template —
|
| 220 |
+
always `cp .env.example .env` after cloning. Values are read by
|
| 221 |
+
[`pdf2zh/config.py`](pdf2zh/config.py) (`Settings`, via `pydantic-settings`) and
|
| 222 |
+
consumed by the Phase-1 parser.
|
| 223 |
+
|
| 224 |
+
| Variable | Default | Meaning |
|
| 225 |
+
|----------|---------|---------|
|
| 226 |
+
| `DEVICE` | `auto` | `cuda`, `mps`, `cpu`, or `auto` (→ CUDA if a GPU is present, else MPS, else CPU). |
|
| 227 |
+
| `PAGE_BATCH_SIZE` | *(unset)* | Pages processed per batch. Leave unset on small GPUs. |
|
| 228 |
+
| `LAYOUT_BATCH_SIZE` | *(unset)* | Surya layout batch. |
|
| 229 |
+
| `DETECTION_BATCH_SIZE` | *(unset)* | Surya text-detection batch. |
|
| 230 |
+
| `OCR_BATCH_SIZE` | *(unset)* | Surya recognition batch (heaviest on VRAM). |
|
| 231 |
+
| `TABLE_BATCH_SIZE` | *(unset)* | Paddle table-cell batch. |
|
| 232 |
+
| `DETECTOR_BLANK_THRESHOLD` | `0.5` | OCR accuracy tuning (not VRAM related). |
|
| 233 |
+
| `DETECTOR_TEXT_THRESHOLD` | `0.6` | Must be **>** the blank threshold. |
|
| 234 |
+
|
| 235 |
+
**Batch-size guidance** (from `.env.example`):
|
| 236 |
+
- **Large GPU (A100 80 GB):** the values in `.env.example` (OCR 512, layout/detection 64,
|
| 237 |
+
page 32, table 512) peak around 45–55 GB VRAM.
|
| 238 |
+
- **Small GPU (T4 16 GB):** leave every batch size **unset (empty)** so Surya picks
|
| 239 |
+
safe defaults and avoids OOM.
|
| 240 |
+
- Unset values fall back to per-device defaults in
|
| 241 |
+
[`pdf2zh/parser/utils/hardware.py`](pdf2zh/parser/utils/hardware.py).
|
| 242 |
+
|
| 243 |
+
### Provider / API keys
|
| 244 |
+
|
| 245 |
+
You do **not** put translation API keys in `.env` for normal use — they are entered
|
| 246 |
+
in the web UI per request and never stored. For **headless/CLI** runs you may set the
|
| 247 |
+
provider's env var instead of passing `--api-key`:
|
| 248 |
+
|
| 249 |
+
| Provider (UI label) | Key (config) | Env var | Default model |
|
| 250 |
+
|---------------------|--------------|---------|---------------|
|
| 251 |
+
| OpenRouter | `openrouter` | `OPENROUTER_API_KEY` | `google/gemini-3.1-flash-lite` |
|
| 252 |
+
| Gemini | `gemini` | `GEMINI_API_KEY` | `gemini-2.5-flash-lite` |
|
| 253 |
+
| OpenAI | `openai` | `OPENAI_API_KEY` | `gpt-4o-mini` |
|
| 254 |
+
| DeepSeek | `deepseek` | `DEEPSEEK_API_KEY` | `deepseek-chat` |
|
| 255 |
+
| MiniMax | `minimax` | `MINIMAX_API_KEY` | `MiniMax-Text-01` |
|
| 256 |
+
| Anthropic | `anthropic` | `ANTHROPIC_API_KEY` | `claude-haiku-4-5` |
|
| 257 |
+
| LiteLLM | `litellm` | `LITELLM_API_KEY` (+ `LITELLM_BASE_URL`) | proxy-routed |
|
| 258 |
+
|
| 259 |
+
Defined in [`pdf2zh/translation/config.py`](pdf2zh/translation/config.py) (`PROVIDERS`).
|
| 260 |
+
|
| 261 |
+
---
|
| 262 |
+
|
| 263 |
+
## Model downloads & caching
|
| 264 |
+
|
| 265 |
+
The OCR weights are **not** bundled — they download on the **first request** and are
|
| 266 |
+
then cached. Point these env vars at a persistent, writable directory to download
|
| 267 |
+
them only once:
|
| 268 |
+
|
| 269 |
+
| Env var | What it caches |
|
| 270 |
+
|---------|----------------|
|
| 271 |
+
| `MODEL_CACHE_DIR` | Surya layout / detection / recognition models (Datalab). |
|
| 272 |
+
| `PADDLE_PDX_CACHE_HOME` | Paddle table-cell model (PaddleX). |
|
| 273 |
+
| `HF_HOME` / `TRANSFORMERS_CACHE` | Hugging Face / transformers assets. |
|
| 274 |
+
|
| 275 |
+
In Docker these default to `/app/.cache/*` and, when Hugging Face Persistent Storage
|
| 276 |
+
(or a mounted `-v host:/data`) is available, to `/data/*` (handled by the entrypoint).
|
| 277 |
+
Locally they default to the standard per-tool locations unless you export them, e.g.:
|
| 278 |
+
|
| 279 |
+
```bash
|
| 280 |
+
export MODEL_CACHE_DIR="$HOME/.cache/pdf2zh/datalab"
|
| 281 |
+
export PADDLE_PDX_CACHE_HOME="$HOME/.cache/pdf2zh/paddlex"
|
| 282 |
+
export HF_HOME="$HOME/.cache/pdf2zh/huggingface"
|
| 283 |
+
```
|
| 284 |
+
|
| 285 |
+
> First run also warms the Typst package cache (`cmarker`, `mitex`). In Docker this
|
| 286 |
+
> is pre-baked; locally Typst fetches them once from `@preview` (needs network on
|
| 287 |
+
> first render).
|
| 288 |
+
|
| 289 |
+
---
|
| 290 |
+
|
| 291 |
+
## Using the web app
|
| 292 |
+
|
| 293 |
+
1. Upload a PDF in the main panel.
|
| 294 |
+
2. In the sidebar pick a **Provider**, paste your **API key** (optionally click
|
| 295 |
+
*Load models* to fetch the model list, or type a model name).
|
| 296 |
+
3. Choose **source / target language**, **output font**, and **page range**
|
| 297 |
+
(All / First page / First 5 / First N — capped at 50 pages per request to guard
|
| 298 |
+
against OOM).
|
| 299 |
+
4. Click **Translate**. A modal streams per-phase progress.
|
| 300 |
+
5. Preview and download the translated PDF.
|
| 301 |
+
|
| 302 |
+
---
|
| 303 |
+
|
| 304 |
+
## Command-line & programmatic use
|
| 305 |
+
|
| 306 |
+
Useful for automation, batch jobs, and debugging a single phase in isolation.
|
| 307 |
+
|
| 308 |
+
### End-to-end (all three phases)
|
| 309 |
+
|
| 310 |
+
```python
|
| 311 |
+
from pdf2zh.e2e import run_pipeline
|
| 312 |
+
|
| 313 |
+
out = run_pipeline(
|
| 314 |
+
pdf_path="test/file/translate.cli.plain.text.pdf",
|
| 315 |
+
src_lang="English", tgt_lang="Vietnamese",
|
| 316 |
+
provider="openrouter", api_key="<YOUR_KEY>",
|
| 317 |
+
model=None, # None → provider default
|
| 318 |
+
pages=[0], # 0-based list, or None for all pages
|
| 319 |
+
font="Noto Sans",
|
| 320 |
+
work_dir="/tmp/e2e_test", # phase1/phase2 JSON + final PDF land here
|
| 321 |
+
progress=lambda f, m: print(f"{f:.0%} {m}"),
|
| 322 |
+
)
|
| 323 |
+
print("OUTPUT:", out)
|
| 324 |
+
```
|
| 325 |
+
|
| 326 |
+
### Phase 2 only — translate an existing parsed JSON
|
| 327 |
+
|
| 328 |
+
```bash
|
| 329 |
+
python test/verify_translate.py \
|
| 330 |
+
--input test_local/output_math.json \
|
| 331 |
+
--provider openrouter --api-key "$OPENROUTER_API_KEY" \
|
| 332 |
+
--src English --tgt Vietnamese
|
| 333 |
+
```
|
| 334 |
+
|
| 335 |
+
(The underlying CLI is [`pdf2zh/translation/cli.py`](pdf2zh/translation/cli.py):
|
| 336 |
+
`--provider`, `--model`, `--api-key`, `--concurrent`, `--chunk-bytes`,
|
| 337 |
+
`--no-glossary`, `--no-math-fix`, `--no-toc-fix`, …)
|
| 338 |
+
|
| 339 |
+
### Phase 3 only — render translated JSON back onto the original PDF
|
| 340 |
+
|
| 341 |
+
```bash
|
| 342 |
+
python -m pdf2zh.render \
|
| 343 |
+
--pdf <source.pdf> \
|
| 344 |
+
--parsed test_local/output_math.translated.json \
|
| 345 |
+
--output /tmp/render_test.pdf \
|
| 346 |
+
--font-family "Noto Sans" \
|
| 347 |
+
--typst-bin typst
|
| 348 |
+
```
|
| 349 |
+
|
| 350 |
+
See [`pdf2zh/render/cli.py`](pdf2zh/render/cli.py) for all flags
|
| 351 |
+
(`--pages`, `--min-font`, `--no-redact`, `--keep-typst-source`, `--aggressive-compress`, …).
|
| 352 |
+
|
| 353 |
+
---
|
| 354 |
+
|
| 355 |
+
## Testing
|
| 356 |
+
|
| 357 |
+
```bash
|
| 358 |
+
# 0. Cheap import check (does NOT load models)
|
| 359 |
+
python -c "import pdf2zh.e2e; print('e2e import OK')"
|
| 360 |
+
|
| 361 |
+
# 1. Unit / integration tests (do not require a GPU or API key for most cases)
|
| 362 |
+
pytest -q
|
| 363 |
+
|
| 364 |
+
# 2. Phase-2 smoke (needs an API key)
|
| 365 |
+
python test/verify_translate.py --input test_local/output_math.json \
|
| 366 |
+
--provider openrouter --api-key "$OPENROUTER_API_KEY" --src English --tgt Vietnamese
|
| 367 |
+
|
| 368 |
+
# 3. Phase-3 render feasibility / smoke
|
| 369 |
+
python test/verify_render.py --input <source.pdf> \
|
| 370 |
+
--parsed test_local/output_math.translated.json --output /tmp/render_test.pdf
|
| 371 |
+
```
|
| 372 |
+
|
| 373 |
+
Tips: the first run downloads the OCR models (~3–5 GB); use a **single page** while
|
| 374 |
+
iterating to keep API cost and latency low.
|
| 375 |
+
|
| 376 |
+
---
|
| 377 |
+
|
| 378 |
+
## Customizing
|
| 379 |
+
|
| 380 |
+
- **Add a font** — drop a `.ttf/.otf` into the font directory (`PDF2ZH_FONT_DIR`,
|
| 381 |
+
`/app/fonts` in Docker; see [`Dockerfile`](Dockerfile)) and add its family name to
|
| 382 |
+
`BUNDLED_FONTS` in [`pdf2zh/e2e.py`](pdf2zh/e2e.py).
|
| 383 |
+
- **Add a provider** — add an entry to `PROVIDERS` in
|
| 384 |
+
[`pdf2zh/translation/config.py`](pdf2zh/translation/config.py) and to `PROVIDER_KEY`
|
| 385 |
+
in [`pdf2zh/webapp/config.py`](pdf2zh/webapp/config.py).
|
| 386 |
+
- **Change page limit / default language / default font** — edit the constants in
|
| 387 |
+
[`pdf2zh/webapp/config.py`](pdf2zh/webapp/config.py) (`MAX_CUSTOM_PAGES`,
|
| 388 |
+
`PAGE_PRESETS`) and [`pdf2zh/e2e.py`](pdf2zh/e2e.py) (`SUPPORTED_LANGUAGES`,
|
| 389 |
+
`DEFAULT_FONT`).
|
| 390 |
+
- **Tune OCR batch sizes / device** — edit `.env` (see Configuration reference).
|
| 391 |
+
|
| 392 |
+
---
|
| 393 |
+
|
| 394 |
+
## Known limitations
|
| 395 |
+
|
| 396 |
+
- Equation elements without `equation_words` are rendered as-is (not translated).
|
| 397 |
+
- A single T4 (16 GB) can OOM on large PDFs; the UI caps custom page counts at 50 and
|
| 398 |
+
serializes requests via `demo.queue()`. Reduce the page range if needed.
|
| 399 |
+
- Phase 3 depends on the external `typst` binary; a version mismatch can change layout.
|
| 400 |
+
|
| 401 |
+
---
|
| 402 |
+
|
| 403 |
+
## License
|
| 404 |
+
|
| 405 |
+
This project builds on [PDFMathTranslate](https://github.com/Byaidu/PDFMathTranslate)
|
| 406 |
+
(AGPL-3.0). See [`LICENSE`](LICENSE).
|
app.json
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"name": "PDFMathTranslate",
|
| 3 |
+
"description": "PDF scientific paper translation and bilingual comparison.",
|
| 4 |
+
"repository": "https://github.com/Byaidu/PDFMathTranslate"
|
| 5 |
+
}
|
app.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Gradio app entry point: end-to-end PDF translation (OCR -> Translate -> Render).
|
| 2 |
+
|
| 3 |
+
Single entry point for the Hugging Face Space (Docker SDK). UI, styling, and the
|
| 4 |
+
pipeline runner live in ``pdf2zh.webapp``; this module only warms up the heavy
|
| 5 |
+
models and launches the server.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import logging
|
| 11 |
+
import tempfile
|
| 12 |
+
|
| 13 |
+
from pdf2zh.e2e import warmup
|
| 14 |
+
from pdf2zh.webapp.ui import build_ui
|
| 15 |
+
|
| 16 |
+
logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
|
| 17 |
+
logger = logging.getLogger(__name__)
|
| 18 |
+
|
| 19 |
+
# Load the heavy Phase-1 models at boot so the first request isn't penalized.
|
| 20 |
+
try:
|
| 21 |
+
warmup()
|
| 22 |
+
except Exception as exc: # noqa: BLE001 — log but still start the UI
|
| 23 |
+
logger.warning("warmup failed (models will load on first request): %s", exc)
|
| 24 |
+
|
| 25 |
+
demo = build_ui()
|
| 26 |
+
|
| 27 |
+
if __name__ == "__main__":
|
| 28 |
+
# The rendered PDF lives under the system temp dir (see runner.py); allow
|
| 29 |
+
# Gradio to serve it so the preview/download components can load it.
|
| 30 |
+
demo.queue(max_size=8).launch(
|
| 31 |
+
server_name="0.0.0.0",
|
| 32 |
+
server_port=7860,
|
| 33 |
+
allowed_paths=[tempfile.gettempdir()],
|
| 34 |
+
)
|
benchmark/__init__.py
ADDED
|
File without changes
|
benchmark/parser/.gitignore
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
data/
|
| 2 |
+
parser_results/
|
| 3 |
+
eval_results/
|
| 4 |
+
|
| 5 |
+
myenv/
|
| 6 |
+
.venv/
|
| 7 |
+
__pycache__/
|
| 8 |
+
cdm_work/
|
benchmark/parser/README.md
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Benchmark — Đánh giá phân tích bố cục (parser vs OmniDocBench)
|
| 2 |
+
|
| 3 |
+
Đo độ chính xác của `StageAParser` (giai đoạn phân tích cấu trúc của PDFTranslator) bằng cách đối chiếu trực tiếp với ground truth của **OmniDocBench**. Quy trình gồm **hai giai đoạn**:
|
| 4 |
+
|
| 5 |
+
1. **Sinh prediction** — chạy parser trên toàn bộ trang OmniDocBench → cần **GPU** (nên dùng Google Colab A100).
|
| 6 |
+
2. **Chấm điểm (eval)** — tính các độ đo (định vị, phân loại, OCR, thứ tự đọc, công thức, bảng) → chỉ cần **CPU**, chạy local. Riêng chỉ số **CDM** cho công thức cần thêm TeX Live + ImageMagick.
|
| 7 |
+
|
| 8 |
+
---
|
| 9 |
+
|
| 10 |
+
## Cấu trúc thư mục
|
| 11 |
+
|
| 12 |
+
```
|
| 13 |
+
benchmark/parser/
|
| 14 |
+
├── run_parser/ # build_pdfs.py, run_parser.py (sinh prediction — cần GPU)
|
| 15 |
+
├── evaluation/ # eval_layout / eval_formula / eval_table / eval_formula_cdm
|
| 16 |
+
│ # aggregate_reports.py, compare_matchers.py, download_dataset.py
|
| 17 |
+
│ # requirements-eval.txt
|
| 18 |
+
├── data/ # OmniDocBench.json + images/ + pdfs/ (tải/tạo ở bước 1)
|
| 19 |
+
├── parser_results/ # batch_*.json (ParsedDocument) + mapping.json (đầu ra parser)
|
| 20 |
+
└── eval_results/ # *.json report + eval_summary_*.csv (đầu ra eval)
|
| 21 |
+
```
|
| 22 |
+
|
| 23 |
+
---
|
| 24 |
+
|
| 25 |
+
## 0. Chuẩn bị
|
| 26 |
+
|
| 27 |
+
```bash
|
| 28 |
+
git clone https://github.com/HoanggNguyen/PDFTranslator.git
|
| 29 |
+
cd PDFTranslator
|
| 30 |
+
# repo OmniDocBench chỉ cần cho CDM (đánh giá công thức):
|
| 31 |
+
git clone https://github.com/opendatalab/OmniDocBench.git
|
| 32 |
+
cd benchmark/parser
|
| 33 |
+
```
|
| 34 |
+
|
| 35 |
+
---
|
| 36 |
+
|
| 37 |
+
## 1. Sinh prediction bằng parser (GPU)
|
| 38 |
+
|
| 39 |
+
Giai đoạn này cần GPU lớn. Nếu GPU laptop không đủ thì dùng **GoogleColab**.
|
| 40 |
+
|
| 41 |
+
### 1a. Kiểm tra GPU và tạo môi trường ảo
|
| 42 |
+
|
| 43 |
+
```bash
|
| 44 |
+
nvidia-smi
|
| 45 |
+
```
|
| 46 |
+
|
| 47 |
+
Trên Colab, tạo môi trường ảo riêng để **tránh xung đột** với các gói cài sẵn:
|
| 48 |
+
|
| 49 |
+
```bash
|
| 50 |
+
pip install virtualenv
|
| 51 |
+
virtualenv myenv
|
| 52 |
+
./myenv/bin/pip install -r ../../requirements.txt
|
| 53 |
+
```
|
| 54 |
+
|
| 55 |
+
(Nếu chạy local có GPU đủ: dùng venv của repo và `pip install -r ../../requirements.txt`.)
|
| 56 |
+
|
| 57 |
+
### 1b. Tải dữ liệu → gộp PDF → chạy parser
|
| 58 |
+
|
| 59 |
+
```bash
|
| 60 |
+
# (1) tải ảnh + OmniDocBench.json về data/
|
| 61 |
+
./myenv/bin/python evaluation/download_dataset.py --out data
|
| 62 |
+
|
| 63 |
+
# (2) gộp ảnh thành PDF 32 trang/PDF (tạo kèm data/pdfs/mapping.json)
|
| 64 |
+
./myenv/bin/python run_parser/build_pdfs.py \
|
| 65 |
+
--images data/images --out data/pdfs --per-pdf 32
|
| 66 |
+
|
| 67 |
+
# (3) chạy parser -> parser_results/batch_*.json + báo cáo thời gian
|
| 68 |
+
./myenv/bin/python run_parser/run_parser.py \
|
| 69 |
+
--pdfs data/pdfs \
|
| 70 |
+
--out parser_results \
|
| 71 |
+
--timing eval_results/parser_timing.json \
|
| 72 |
+
--device cuda
|
| 73 |
+
```
|
| 74 |
+
|
| 75 |
+
Tuỳ chọn hữu ích của `run_parser.py`:
|
| 76 |
+
|
| 77 |
+
- Batch size (điều chỉnh theo VRAM): `--layout-batch-size`, `--detection-batch-size`, `--ocr-batch-size`, `--table-batch-size`, `--page-batch-size` (mặc định hợp cho A100).
|
| 78 |
+
- Ngưỡng detector: `--blank-threshold`, `--text-threshold`.
|
| 79 |
+
- `--limit N`: chỉ chạy N PDF đầu (test nhanh); `--overwrite`: chạy lại PDF đã có JSON.
|
| 80 |
+
|
| 81 |
+
> `build_pdfs.py` ghi `mapping.json` cạnh các PDF (`data/pdfs/mapping.json`). Để các
|
| 82 |
+
> lệnh eval ở Giai đoạn 2 chạy nguyên trạng, sau khi chạy parser hãy copy nó vào
|
| 83 |
+
> `parser_results/`: `cp data/pdfs/mapping.json parser_results/`.
|
| 84 |
+
|
| 85 |
+
- Tải `parser_results/` từ Colab về máy để chấm điểm ở Giai đoạn 2.
|
| 86 |
+
|
| 87 |
+
---
|
| 88 |
+
|
| 89 |
+
## 2. Chấm điểm (eval — CPU, chạy local)
|
| 90 |
+
|
| 91 |
+
### 2a. Môi trường eval
|
| 92 |
+
|
| 93 |
+
```bash
|
| 94 |
+
python3 -m venv .venv
|
| 95 |
+
.venv/bin/pip install -r evaluation/requirements-eval.txt
|
| 96 |
+
|
| 97 |
+
sudo apt install -y texlive-latex-base texlive-latex-extra \
|
| 98 |
+
texlive-fonts-recommended imagemagick
|
| 99 |
+
```
|
| 100 |
+
|
| 101 |
+
Đặt cho gọn: `PY=.venv/bin/python`.
|
| 102 |
+
|
| 103 |
+
### 2b. Localization + Classification + OCR + Reading order
|
| 104 |
+
|
| 105 |
+
```bash
|
| 106 |
+
# fine (bung merge_list — khuyến nghị)
|
| 107 |
+
$PY evaluation/eval_layout.py \
|
| 108 |
+
--gt data/OmniDocBench.json --pred parser_results \
|
| 109 |
+
--mapping parser_results/mapping.json \
|
| 110 |
+
--gt-granularity fine --out eval_results/eval_report_fine.json
|
| 111 |
+
|
| 112 |
+
# merged (box top-level như OmniDocBench)
|
| 113 |
+
$PY evaluation/eval_layout.py \
|
| 114 |
+
--gt data/OmniDocBench.json --pred parser_results \
|
| 115 |
+
--mapping parser_results/mapping.json \
|
| 116 |
+
--gt-granularity merged --out eval_results/eval_report_merged.json
|
| 117 |
+
|
| 118 |
+
# fine + mask-math (thay công thức inline bằng token -> CER/WER text thuần)
|
| 119 |
+
$PY evaluation/eval_layout.py \
|
| 120 |
+
--gt data/OmniDocBench.json --pred parser_results \
|
| 121 |
+
--mapping parser_results/mapping.json \
|
| 122 |
+
--gt-granularity fine --mask-math \
|
| 123 |
+
--out eval_results/eval_report_fine_maskmath.json
|
| 124 |
+
```
|
| 125 |
+
|
| 126 |
+
### 2c. Công thức (edit distance) + Bảng (nội dung)
|
| 127 |
+
|
| 128 |
+
```bash
|
| 129 |
+
$PY evaluation/eval_formula.py \
|
| 130 |
+
--gt data/OmniDocBench.json --pred parser_results \
|
| 131 |
+
--mapping parser_results/mapping.json \
|
| 132 |
+
--out eval_results/eval_report_formula.json
|
| 133 |
+
|
| 134 |
+
$PY evaluation/eval_table.py \
|
| 135 |
+
--gt data/OmniDocBench.json --pred parser_results \
|
| 136 |
+
--mapping parser_results/mapping.json \
|
| 137 |
+
--out eval_results/eval_report_table.json
|
| 138 |
+
```
|
| 139 |
+
|
| 140 |
+
### 2d. Công thức CDM (chuẩn vàng — cần TeX Live + ImageMagick + pylatexenc)
|
| 141 |
+
|
| 142 |
+
```bash
|
| 143 |
+
$PY evaluation/eval_formula_cdm.py \
|
| 144 |
+
--gt data/OmniDocBench.json --pred parser_results \
|
| 145 |
+
--mapping parser_results/mapping.json \
|
| 146 |
+
--omnidocbench ../../OmniDocBench \
|
| 147 |
+
--out eval_results/eval_report_formula_cdm.json
|
| 148 |
+
# thêm --limit 200 để test nhanh
|
| 149 |
+
```
|
| 150 |
+
|
| 151 |
+
### 2e. Gom kết quả thành CSV
|
| 152 |
+
|
| 153 |
+
```bash
|
| 154 |
+
$PY evaluation/aggregate_reports.py \
|
| 155 |
+
--layout fine=eval_results/eval_report_fine.json \
|
| 156 |
+
--layout merged=eval_results/eval_report_merged.json \
|
| 157 |
+
--layout fine_maskmath=eval_results/eval_report_fine_maskmath.json \
|
| 158 |
+
--formula eval_results/eval_report_formula.json \
|
| 159 |
+
--report table=eval_results/eval_report_table.json \
|
| 160 |
+
--out eval_results/eval_summary
|
| 161 |
+
```
|
| 162 |
+
|
| 163 |
+
### 2f. (tuỳ chọn) So sánh 3 cách matching localization
|
| 164 |
+
|
| 165 |
+
```bash
|
| 166 |
+
$PY evaluation/compare_matchers.py --iou 0.5 --granularity fine
|
| 167 |
+
```
|
| 168 |
+
|
| 169 |
+
---
|
| 170 |
+
|
| 171 |
+
## Ghi chú
|
| 172 |
+
|
| 173 |
+
- GT↔pred nối theo **tên ảnh** (`image_path`) qua `mapping.json` — khớp 1:1.
|
| 174 |
+
- Eval chạy **CPU** (trừ CDM cần TeX Live). Chỉ Giai đoạn 1 (parser) mới cần GPU.
|
| 175 |
+
- Các script trong `evaluation/` import lẫn nhau theo thư mục cạnh bên; hãy gọi bằng `python evaluation/<script>.py` (đừng đổi tên/di chuyển lẻ từng file).
|
benchmark/parser/evaluation/aggregate_reports.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Gom các report JSON (layout/OCR + formula) thành CSV để phân tích / vẽ biểu đồ.
|
| 2 |
+
|
| 3 |
+
Đọc report của eval_layout.py và eval_formula.py, làm phẳng mọi metric theo từng
|
| 4 |
+
lát cắt (slice) và xuất:
|
| 5 |
+
* <out>_long.csv : (report, slice, metric, value) -- tiện nhóm/vẽ.
|
| 6 |
+
* <out>_wide.csv : mỗi hàng = 1 slice, mỗi cột = "<report>.<metric>".
|
| 7 |
+
|
| 8 |
+
Ví dụ
|
| 9 |
+
-----
|
| 10 |
+
# chạy từ benchmark/parser/
|
| 11 |
+
python evaluation/aggregate_reports.py \
|
| 12 |
+
--layout fine=eval_results/eval_report_fine.json \
|
| 13 |
+
--layout merged=eval_results/eval_report_merged.json \
|
| 14 |
+
--formula eval_results/eval_report_formula.json \
|
| 15 |
+
--report table=eval_results/eval_report_table.json \
|
| 16 |
+
--out eval_results/eval_summary
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
from __future__ import annotations
|
| 20 |
+
|
| 21 |
+
import argparse
|
| 22 |
+
import json
|
| 23 |
+
from pathlib import Path
|
| 24 |
+
|
| 25 |
+
import pandas as pd
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def flatten(d: dict, prefix: str = "") -> dict:
|
| 29 |
+
"""Làm phẳng dict lồng nhau -> {'a.b.c': value} (bỏ qua list)."""
|
| 30 |
+
out = {}
|
| 31 |
+
for k, v in d.items():
|
| 32 |
+
key = f"{prefix}{k}"
|
| 33 |
+
if isinstance(v, dict):
|
| 34 |
+
out.update(flatten(v, key + "."))
|
| 35 |
+
elif isinstance(v, list):
|
| 36 |
+
continue
|
| 37 |
+
else:
|
| 38 |
+
out[key] = v
|
| 39 |
+
return out
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def rows_from_report(name: str, path: Path):
|
| 43 |
+
rep = json.load(open(path, encoding="utf-8"))
|
| 44 |
+
rows = []
|
| 45 |
+
for slice_key, metrics in rep["slices"].items():
|
| 46 |
+
flat = flatten(metrics)
|
| 47 |
+
for metric, value in flat.items():
|
| 48 |
+
rows.append({"report": name, "slice": slice_key,
|
| 49 |
+
"metric": metric, "value": value})
|
| 50 |
+
return rows
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def parse_kv(s: str, default_name: str) -> tuple[str, Path]:
|
| 54 |
+
if "=" in s:
|
| 55 |
+
name, path = s.split("=", 1)
|
| 56 |
+
return name, Path(path)
|
| 57 |
+
return default_name, Path(s)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def parse_args():
|
| 61 |
+
ap = argparse.ArgumentParser(description=__doc__,
|
| 62 |
+
formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 63 |
+
ap.add_argument("--layout", action="append", default=[],
|
| 64 |
+
help="report layout, dạng name=path (lặp nhiều lần). "
|
| 65 |
+
"VD: fine=../../eval_report_fine.json")
|
| 66 |
+
ap.add_argument("--formula", action="append", default=[],
|
| 67 |
+
help="report formula, dạng [name=]path (lặp nhiều lần).")
|
| 68 |
+
ap.add_argument("--report", action="append", default=[],
|
| 69 |
+
help="report BẤT KỲ (table/cdm/…), dạng name=path (lặp nhiều lần).")
|
| 70 |
+
ap.add_argument("--out", type=Path, required=True,
|
| 71 |
+
help="Tiền tố file ra: <out>_long.csv và <out>_wide.csv")
|
| 72 |
+
return ap.parse_args()
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def main() -> int:
|
| 76 |
+
args = parse_args()
|
| 77 |
+
rows = []
|
| 78 |
+
for spec in args.layout:
|
| 79 |
+
name, path = parse_kv(spec, "layout")
|
| 80 |
+
rows += rows_from_report(f"layout_{name}", path)
|
| 81 |
+
for spec in args.formula:
|
| 82 |
+
name, path = parse_kv(spec, "formula")
|
| 83 |
+
rows += rows_from_report(name if "=" in spec else "formula", path)
|
| 84 |
+
for spec in args.report:
|
| 85 |
+
name, path = parse_kv(spec, "report")
|
| 86 |
+
rows += rows_from_report(name, path)
|
| 87 |
+
|
| 88 |
+
if not rows:
|
| 89 |
+
print("Không có report nào. Truyền --layout/--formula.")
|
| 90 |
+
return 1
|
| 91 |
+
|
| 92 |
+
df = pd.DataFrame(rows)
|
| 93 |
+
long_path = args.out.with_name(args.out.name + "_long.csv")
|
| 94 |
+
df.to_csv(long_path, index=False)
|
| 95 |
+
|
| 96 |
+
# wide: slice x (report.metric)
|
| 97 |
+
df["col"] = df["report"] + "." + df["metric"]
|
| 98 |
+
wide = df.pivot_table(index="slice", columns="col", values="value", aggfunc="first")
|
| 99 |
+
# đưa 'all' lên đầu
|
| 100 |
+
order = ["all"] + sorted(s for s in wide.index if s != "all")
|
| 101 |
+
wide = wide.reindex([s for s in order if s in wide.index])
|
| 102 |
+
wide_path = args.out.with_name(args.out.name + "_wide.csv")
|
| 103 |
+
wide.to_csv(wide_path)
|
| 104 |
+
|
| 105 |
+
print(f"[aggregate] {len(rows)} dòng metric, {df['slice'].nunique()} slice, "
|
| 106 |
+
f"{df['report'].nunique()} report")
|
| 107 |
+
print(f" long -> {long_path}")
|
| 108 |
+
print(f" wide -> {wide_path}")
|
| 109 |
+
|
| 110 |
+
# in nhanh vài cột chính cho 'all'
|
| 111 |
+
key_cols = [c for c in wide.columns if any(
|
| 112 |
+
k in c for k in ("f1@0.5", "CER", "WER", "reading_order.edit_distance_mean",
|
| 113 |
+
"coverage", "edit_matched_micro"))]
|
| 114 |
+
if "all" in wide.index and key_cols:
|
| 115 |
+
print("\n[all] các cột chính:")
|
| 116 |
+
for c in sorted(key_cols):
|
| 117 |
+
print(f" {c:45s} {wide.loc['all', c]}")
|
| 118 |
+
return 0
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
if __name__ == "__main__":
|
| 122 |
+
raise SystemExit(main())
|
benchmark/parser/evaluation/compare_matchers.py
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""So sánh 3 cách MATCHING cho localization (class-agnostic) trên cùng dữ liệu:
|
| 2 |
+
|
| 3 |
+
(0) HIỆN TẠI — containment + union, hai chiều tách rời (recall-side / precision-side).
|
| 4 |
+
(A) COCO 1-1 — ghép 1-1 tham lam theo IoU giảm dần, mỗi GT/pred dùng 1 lần (chuẩn
|
| 5 |
+
detection; không có confidence nên sort theo IoU).
|
| 6 |
+
(B) COMPONENT — đồ thị chồng lấn (cạnh khi IoU>=.5 hoặc containment>=.5 hai chiều) →
|
| 7 |
+
thành phần liên thông; cụm "khớp" nếu IoU(union_GT, union_pred)>=t →
|
| 8 |
+
mọi GT/pred trong cụm tính TP (một phép ghép nhất quán, xử lý N-M).
|
| 9 |
+
|
| 10 |
+
Báo P/R/F1@IoU cho tổng thể + vài lát cắt. Chỉ để đối chiếu, KHÔNG thay eval_layout.
|
| 11 |
+
|
| 12 |
+
.venv/bin/python compare_matchers.py [--iou 0.5] [--granularity fine]
|
| 13 |
+
"""
|
| 14 |
+
from __future__ import annotations
|
| 15 |
+
import argparse, json
|
| 16 |
+
from collections import defaultdict
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
import sys
|
| 19 |
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
| 20 |
+
import eval_layout as E
|
| 21 |
+
|
| 22 |
+
# benchmark/parser/ — chứa data/ (GT) và parser_results/ (batch_*.json + mapping.json)
|
| 23 |
+
BASE = Path(__file__).resolve().parents[1]
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
# ---- (A) COCO 1-1 greedy ----
|
| 27 |
+
def coco_tp(gts, preds, t):
|
| 28 |
+
pairs = []
|
| 29 |
+
for i, g in enumerate(gts):
|
| 30 |
+
for j, p in enumerate(preds):
|
| 31 |
+
v = E.iou(g["box"], p["box"])
|
| 32 |
+
if v >= t:
|
| 33 |
+
pairs.append((v, i, j))
|
| 34 |
+
pairs.sort(reverse=True)
|
| 35 |
+
ug, up, tp = set(), set(), 0
|
| 36 |
+
for v, i, j in pairs:
|
| 37 |
+
if i in ug or j in up:
|
| 38 |
+
continue
|
| 39 |
+
ug.add(i); up.add(j); tp += 1
|
| 40 |
+
return tp, tp # tp_gt == tp_pred (ghép 1-1)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
# ---- (B) connected components ----
|
| 44 |
+
def comp_tp(gts, preds, t):
|
| 45 |
+
parent = {}
|
| 46 |
+
def find(x):
|
| 47 |
+
parent.setdefault(x, x)
|
| 48 |
+
root = x
|
| 49 |
+
while parent[root] != root:
|
| 50 |
+
root = parent[root]
|
| 51 |
+
while parent[x] != root:
|
| 52 |
+
parent[x], x = root, parent[x]
|
| 53 |
+
return root
|
| 54 |
+
def union(a, b):
|
| 55 |
+
ra, rb = find(a), find(b)
|
| 56 |
+
if ra != rb:
|
| 57 |
+
parent[ra] = rb
|
| 58 |
+
for i in range(len(gts)):
|
| 59 |
+
find(("g", i))
|
| 60 |
+
for j in range(len(preds)):
|
| 61 |
+
find(("p", j))
|
| 62 |
+
for i, g in enumerate(gts):
|
| 63 |
+
for j, p in enumerate(preds):
|
| 64 |
+
gb, pb = g["box"], p["box"]
|
| 65 |
+
if (E.iou(gb, pb) >= 0.5 or E.contain_ratio(gb, pb) >= 0.5
|
| 66 |
+
or E.contain_ratio(pb, gb) >= 0.5):
|
| 67 |
+
union(("g", i), ("p", j))
|
| 68 |
+
comps = defaultdict(lambda: {"g": [], "p": []})
|
| 69 |
+
for i, g in enumerate(gts):
|
| 70 |
+
comps[find(("g", i))]["g"].append(g["box"])
|
| 71 |
+
for j, p in enumerate(preds):
|
| 72 |
+
comps[find(("p", j))]["p"].append(p["box"])
|
| 73 |
+
tp_g = tp_p = 0
|
| 74 |
+
for c in comps.values():
|
| 75 |
+
if not c["g"] or not c["p"]:
|
| 76 |
+
continue
|
| 77 |
+
if E.iou(E.union_box(c["g"]), E.union_box(c["p"])) >= t:
|
| 78 |
+
tp_g += len(c["g"]); tp_p += len(c["p"])
|
| 79 |
+
return tp_g, tp_p
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
# ---- (0) current two-sided ----
|
| 83 |
+
def cur_tp(gts, preds, t):
|
| 84 |
+
rec = E.match_side(gts, preds, 0.5)
|
| 85 |
+
prc = E.match_side(preds, gts, 0.5)
|
| 86 |
+
tp_g = sum(1 for r in rec if r["union_iou"] >= t)
|
| 87 |
+
tp_p = sum(1 for r in prc if r["union_iou"] >= t)
|
| 88 |
+
return tp_g, tp_p
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def prf(tp_g, tp_p, n_gt, n_pred):
|
| 92 |
+
r = tp_g / n_gt if n_gt else 0.0
|
| 93 |
+
p = tp_p / n_pred if n_pred else 0.0
|
| 94 |
+
f = 2 * p * r / (p + r) if (p + r) else 0.0
|
| 95 |
+
return p, r, f
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def main():
|
| 99 |
+
ap = argparse.ArgumentParser()
|
| 100 |
+
ap.add_argument("--iou", type=float, default=0.5)
|
| 101 |
+
ap.add_argument("--granularity", default="fine")
|
| 102 |
+
ap.add_argument("--gt", type=Path, default=BASE / "data" / "OmniDocBench.json")
|
| 103 |
+
ap.add_argument("--mapping", type=Path,
|
| 104 |
+
default=BASE / "parser_results" / "mapping.json")
|
| 105 |
+
ap.add_argument("--pred", type=Path, default=BASE / "parser_results",
|
| 106 |
+
help="Thư mục chứa batch_*.json của parser.")
|
| 107 |
+
args = ap.parse_args()
|
| 108 |
+
t = args.iou
|
| 109 |
+
|
| 110 |
+
gt = E.load_gt(args.gt, args.granularity)
|
| 111 |
+
mp = json.load(open(args.mapping))
|
| 112 |
+
idx = E.build_pred_index(args.pred, mp)
|
| 113 |
+
|
| 114 |
+
METHODS = {"current": cur_tp, "coco_1to1": coco_tp, "component": comp_tp}
|
| 115 |
+
# acc[slice][method] = [tp_g, tp_p, n_gt, n_pred]
|
| 116 |
+
acc = defaultdict(lambda: {m: [0, 0, 0, 0] for m in METHODS})
|
| 117 |
+
|
| 118 |
+
for name, pp in idx.items():
|
| 119 |
+
g = gt.get(name)
|
| 120 |
+
if g is None:
|
| 121 |
+
continue
|
| 122 |
+
gts = E.prep_gt(g, True)
|
| 123 |
+
preds = E.prep_pred(pp)
|
| 124 |
+
keys = ["all"]
|
| 125 |
+
lang = g["attr"].get("language"); lay = g["attr"].get("layout")
|
| 126 |
+
if lang: keys.append(f"language={lang}")
|
| 127 |
+
if lay: keys.append(f"layout={lay}")
|
| 128 |
+
per = {}
|
| 129 |
+
for m, fn in METHODS.items():
|
| 130 |
+
per[m] = fn(gts, preds, t)
|
| 131 |
+
for k in keys:
|
| 132 |
+
for m in METHODS:
|
| 133 |
+
a = acc[k][m]
|
| 134 |
+
a[0] += per[m][0]; a[1] += per[m][1]
|
| 135 |
+
a[2] += len(gts); a[3] += len(preds)
|
| 136 |
+
|
| 137 |
+
def show(k):
|
| 138 |
+
print(f"\n### {k}")
|
| 139 |
+
print(f" {'method':10s} P@{t} R@{t} F1@{t}")
|
| 140 |
+
for m in METHODS:
|
| 141 |
+
tp_g, tp_p, n_gt, n_pred = acc[k][m]
|
| 142 |
+
p, r, f = prf(tp_g, tp_p, n_gt, n_pred)
|
| 143 |
+
print(f" {m:10s} {p:.3f} {r:.3f} {f:.3f}")
|
| 144 |
+
|
| 145 |
+
print(f"So sánh matching @IoU={t}, granularity={args.granularity}, pred={args.pred}")
|
| 146 |
+
show("all")
|
| 147 |
+
for k in ["layout=single_column", "layout=double_column", "layout=three_column",
|
| 148 |
+
"language=english", "language=simplified_chinese"]:
|
| 149 |
+
if k in acc:
|
| 150 |
+
show(k)
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
if __name__ == "__main__":
|
| 154 |
+
main()
|
benchmark/parser/evaluation/download_dataset.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Download the OmniDocBench dataset (page images + GT annotations) from HuggingFace.
|
| 2 |
+
|
| 3 |
+
The dataset repo ``opendatalab/OmniDocBench`` is public, so no token is needed.
|
| 4 |
+
It contains:
|
| 5 |
+
- ``images/`` — all benchmark page images (one image per page)
|
| 6 |
+
- ``OmniDocBench.json`` — ground-truth annotations (used later for metrics)
|
| 7 |
+
|
| 8 |
+
We fetch only those two (skipping the README figures at the repo root).
|
| 9 |
+
``snapshot_download`` is resumable: re-running continues an interrupted download.
|
| 10 |
+
|
| 11 |
+
Run this on the LOGIN NODE (it has internet; compute nodes may not) and point
|
| 12 |
+
``--out`` at /media/lhbac32 so the data is staged on shared storage.
|
| 13 |
+
|
| 14 |
+
Example
|
| 15 |
+
-------
|
| 16 |
+
# chạy từ benchmark/parser/ — tải ảnh + OmniDocBench.json về data/
|
| 17 |
+
python evaluation/download_dataset.py --out data
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
from __future__ import annotations
|
| 21 |
+
|
| 22 |
+
import argparse
|
| 23 |
+
import sys
|
| 24 |
+
from pathlib import Path
|
| 25 |
+
|
| 26 |
+
REPO_ID = "opendatalab/OmniDocBench"
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def parse_args() -> argparse.Namespace:
|
| 30 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 31 |
+
parser.add_argument(
|
| 32 |
+
"--out", required=True, type=Path,
|
| 33 |
+
help="Destination folder, e.g. /media/lhbac32/OmniDocBench",
|
| 34 |
+
)
|
| 35 |
+
parser.add_argument(
|
| 36 |
+
"--images-only", action="store_true",
|
| 37 |
+
help="Download only images/ (skip OmniDocBench.json).",
|
| 38 |
+
)
|
| 39 |
+
return parser.parse_args()
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def main() -> int:
|
| 43 |
+
args = parse_args()
|
| 44 |
+
|
| 45 |
+
try:
|
| 46 |
+
from huggingface_hub import snapshot_download
|
| 47 |
+
except ImportError:
|
| 48 |
+
print(
|
| 49 |
+
"huggingface_hub is not installed. Install it first:\n"
|
| 50 |
+
" pip install --user huggingface_hub\n"
|
| 51 |
+
"or, with the alternative CLI:\n"
|
| 52 |
+
f" hf download {REPO_ID} --repo-type dataset "
|
| 53 |
+
f"--local-dir {args.out} --include 'images/**' 'OmniDocBench.json'",
|
| 54 |
+
file=sys.stderr,
|
| 55 |
+
)
|
| 56 |
+
return 1
|
| 57 |
+
|
| 58 |
+
allow_patterns = ["images/**"]
|
| 59 |
+
if not args.images_only:
|
| 60 |
+
allow_patterns.append("OmniDocBench.json")
|
| 61 |
+
|
| 62 |
+
args.out.mkdir(parents=True, exist_ok=True)
|
| 63 |
+
print(f"[download] repo={REPO_ID} -> {args.out}", flush=True)
|
| 64 |
+
print(f"[download] patterns={allow_patterns}", flush=True)
|
| 65 |
+
|
| 66 |
+
snapshot_download(
|
| 67 |
+
repo_id=REPO_ID,
|
| 68 |
+
repo_type="dataset",
|
| 69 |
+
local_dir=str(args.out),
|
| 70 |
+
allow_patterns=allow_patterns,
|
| 71 |
+
resume_download=True,
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
images_dir = args.out / "images"
|
| 75 |
+
gt_json = args.out / "OmniDocBench.json"
|
| 76 |
+
num_images = sum(1 for _ in images_dir.glob("*")) if images_dir.is_dir() else 0
|
| 77 |
+
|
| 78 |
+
print("\n[download] done.", flush=True)
|
| 79 |
+
print(f" images dir : {images_dir} ({num_images} files)", flush=True)
|
| 80 |
+
if gt_json.exists():
|
| 81 |
+
print(f" GT json : {gt_json}", flush=True)
|
| 82 |
+
return 0
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
if __name__ == "__main__":
|
| 86 |
+
raise SystemExit(main())
|
benchmark/parser/evaluation/eval_formula.py
ADDED
|
@@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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Đánh giá nhận dạng CÔNG THỨC (isolated formula) parser-vs-GT trên OmniDocBench.
|
| 2 |
+
|
| 3 |
+
Vấn đề "không đồng nhất": GT lưu LaTeX bọc ``$$...$$``; parser xuất
|
| 4 |
+
``<math display="block"> ...thân LaTeX... </math>``. Thân hai bên đều là LaTeX
|
| 5 |
+
nên chỉ cần BÓC LỚP BỌC rồi so:
|
| 6 |
+
* GT : bỏ ``$$ $ \\[ \\] \\( \\)`` ngoài cùng, gom khoảng trắng/newline.
|
| 7 |
+
* pred: bỏ thẻ ``<math ...>`` / ``</math>`` (và delimiter nếu có), gom trắng.
|
| 8 |
+
|
| 9 |
+
Matching theo CONTAINMENT + UNION (giống eval_layout): với mỗi công thức GT, gom
|
| 10 |
+
mọi Equation của parser nằm gọn trong nó rồi NỐI lại theo thứ tự đọc — chịu được
|
| 11 |
+
trường hợp parser over-split 1 công thức thành nhiều mảnh.
|
| 12 |
+
|
| 13 |
+
Metric = Normalized Edit Distance (Levenshtein/max(len), đúng công thức
|
| 14 |
+
OmniDocBench). Báo:
|
| 15 |
+
* edit_all : tính trên MỌI công thức GT (GT không match -> pred rỗng -> phạt
|
| 16 |
+
hết) => phản ánh cả nhận dạng LẪN sót detect.
|
| 17 |
+
* edit_matched : chỉ trên công thức GT có ít nhất 1 Equation phủ => chất lượng
|
| 18 |
+
nhận dạng thuần, tách khỏi lỗi detect.
|
| 19 |
+
* coverage : tỉ lệ công thức GT được phủ (recall detect).
|
| 20 |
+
* pred_unmatched: số Equation của parser không rơi vào công thức GT nào (FP).
|
| 21 |
+
Chia theo language / layout / subset / data_source (chú ý subset=equation_hard).
|
| 22 |
+
|
| 23 |
+
LƯU Ý: đây là edit distance trên LaTeX -> nhạy với khác ký hiệu
|
| 24 |
+
(``\\left[`` vs ``\\left\\lbrack``, ``dx`` vs ``\\partial x``). Chuẩn vàng là
|
| 25 |
+
**CDM** (render ra ảnh rồi so) nhưng cần môi trường KaTeX/texlive riêng — để dành.
|
| 26 |
+
|
| 27 |
+
Ví dụ
|
| 28 |
+
-----
|
| 29 |
+
# chạy từ benchmark/parser/
|
| 30 |
+
python evaluation/eval_formula.py \
|
| 31 |
+
--gt data/OmniDocBench.json --pred parser_results \
|
| 32 |
+
--mapping parser_results/mapping.json --out eval_results/eval_report_formula.json
|
| 33 |
+
"""
|
| 34 |
+
|
| 35 |
+
from __future__ import annotations
|
| 36 |
+
|
| 37 |
+
import argparse
|
| 38 |
+
import json
|
| 39 |
+
import re
|
| 40 |
+
from collections import defaultdict
|
| 41 |
+
import sys
|
| 42 |
+
from pathlib import Path
|
| 43 |
+
|
| 44 |
+
sys.path.insert(0, str(Path(__file__).resolve().parent)) # import module cạnh bên
|
| 45 |
+
import eval_layout as E # tái dùng geometry, _dist, load_gt, build_pred_index
|
| 46 |
+
|
| 47 |
+
SLICE_KEYS = ("language", "layout", "subset", "data_source")
|
| 48 |
+
_MATH_TAG = re.compile(r"</?math[^>]*>", re.IGNORECASE)
|
| 49 |
+
_WS = re.compile(r"\s+")
|
| 50 |
+
_DELIMS = (("$$", "$$"), ("\\[", "\\]"), ("\\(", "\\)"), ("$", "$"))
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def norm_formula(s: str) -> str:
|
| 54 |
+
"""Bóc lớp bọc (math tag + delimiter) + thẻ định dạng -> LaTeX trần.
|
| 55 |
+
|
| 56 |
+
Quan trọng: parser hay nhét thẻ định dạng (``<b>49</b>`` = số bài tập, ``<sub>``,
|
| 57 |
+
``<sup>``…) vào Equation. Nếu không bóc, thẻ lọt vào LaTeX -> CDM render ra ký
|
| 58 |
+
hiệu rác -> điểm ≈ 0 oan. Bóc thẻ (giữ nội dung) + unescape như norm_ocr.
|
| 59 |
+
"""
|
| 60 |
+
s = E._html.unescape(s or "")
|
| 61 |
+
s = _MATH_TAG.sub(" ", s).strip()
|
| 62 |
+
s = E._FMT_TAGS.sub("", s) # <b><i><u><sub><sup>... (giữ nội dung)
|
| 63 |
+
changed = True
|
| 64 |
+
while changed: # bóc nhiều lớp delimiter lồng nhau nếu có
|
| 65 |
+
changed = False
|
| 66 |
+
for a, b in _DELIMS:
|
| 67 |
+
if len(s) >= len(a) + len(b) and s.startswith(a) and s.endswith(b):
|
| 68 |
+
s = s[len(a):len(s) - len(b)].strip()
|
| 69 |
+
changed = True
|
| 70 |
+
return _WS.sub(" ", s).strip()
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def gt_equations(page: dict, drop_ignore: bool) -> list[dict]:
|
| 74 |
+
out = []
|
| 75 |
+
for d in page["dets"]:
|
| 76 |
+
if d.get("category_type") != "equation_isolated":
|
| 77 |
+
continue
|
| 78 |
+
if drop_ignore and d.get("ignore"):
|
| 79 |
+
continue
|
| 80 |
+
out.append({
|
| 81 |
+
"box": E.norm_box(E.poly_to_xyxy(d["poly"]), page["w"], page["h"]),
|
| 82 |
+
"latex": norm_formula(d.get("latex") or d.get("text") or ""),
|
| 83 |
+
})
|
| 84 |
+
return out
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def pred_equations(page: dict) -> list[dict]:
|
| 88 |
+
W, H = page.get("page_width"), page.get("page_height")
|
| 89 |
+
out = []
|
| 90 |
+
for e in page["elements"]:
|
| 91 |
+
if e.get("label") != "Equation":
|
| 92 |
+
continue
|
| 93 |
+
out.append({
|
| 94 |
+
"box": E.norm_box(e["bbox_pdf"], W, H),
|
| 95 |
+
"text": e.get("source_text") or "",
|
| 96 |
+
})
|
| 97 |
+
return out
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
class Acc:
|
| 101 |
+
def __init__(self):
|
| 102 |
+
self.n_gt = self.n_matched = 0
|
| 103 |
+
self.n_pred = self.n_pred_unmatched = 0
|
| 104 |
+
self.num_all = self.den_all = 0.0
|
| 105 |
+
self.num_m = self.den_m = 0.0
|
| 106 |
+
self.ratio_all = [] # per-formula normalized edit dist (over all GT)
|
| 107 |
+
|
| 108 |
+
def summary(self):
|
| 109 |
+
return {
|
| 110 |
+
"gt_formulas": self.n_gt,
|
| 111 |
+
"coverage": round(self.n_matched / self.n_gt, 4) if self.n_gt else None,
|
| 112 |
+
"pred_formulas": self.n_pred,
|
| 113 |
+
"pred_unmatched": self.n_pred_unmatched,
|
| 114 |
+
"edit_all_micro": round(self.num_all / self.den_all, 4) if self.den_all else None,
|
| 115 |
+
"edit_all_sample": round(sum(self.ratio_all) / len(self.ratio_all), 4) if self.ratio_all else None,
|
| 116 |
+
"edit_matched_micro": round(self.num_m / self.den_m, 4) if self.den_m else None,
|
| 117 |
+
"score_matched": round(1 - self.num_m / self.den_m, 4) if self.den_m else None,
|
| 118 |
+
}
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def score_page(gts, preds, member_thr):
|
| 122 |
+
used = [False] * len(preds)
|
| 123 |
+
ps = {"n_gt": len(gts), "n_matched": 0, "n_pred": len(preds),
|
| 124 |
+
"pairs": []} # (dist, maxlen, matched_bool)
|
| 125 |
+
for g in gts:
|
| 126 |
+
members, idxs = [], []
|
| 127 |
+
for i, p in enumerate(preds):
|
| 128 |
+
if E.contain_ratio(p["box"], g["box"]) >= member_thr:
|
| 129 |
+
members.append(p)
|
| 130 |
+
idxs.append(i)
|
| 131 |
+
gt_norm = g["latex"]
|
| 132 |
+
if members:
|
| 133 |
+
for i in idxs:
|
| 134 |
+
used[i] = True
|
| 135 |
+
members.sort(key=lambda m: (round(m["box"][1], 3), m["box"][0]))
|
| 136 |
+
pred_norm = norm_formula(" ".join(m["text"] for m in members))
|
| 137 |
+
ps["n_matched"] += 1
|
| 138 |
+
matched = True
|
| 139 |
+
else:
|
| 140 |
+
pred_norm = ""
|
| 141 |
+
matched = False
|
| 142 |
+
if gt_norm or pred_norm:
|
| 143 |
+
# Bỏ HẲN whitespace khi so edit distance: GT chèn dấu cách quanh mọi token
|
| 144 |
+
# (`\mathbb { R }`) còn parser xuất gọn (`\mathbb{R}`) — khác biệt spacing
|
| 145 |
+
# vô nghĩa về ngữ nghĩa/hiển thị. Chỉ bỏ ở ĐÂY (bước đo); norm_formula giữ
|
| 146 |
+
# nguyên spacing để CDM render an toàn (không nối `\in A` -> `\inA`).
|
| 147 |
+
pe, ge = _WS.sub("", pred_norm), _WS.sub("", gt_norm)
|
| 148 |
+
d = E._dist(pe, ge)
|
| 149 |
+
ps["pairs"].append((d, max(len(pe), len(ge)), matched))
|
| 150 |
+
ps["n_pred_unmatched"] = sum(1 for u in used if not u)
|
| 151 |
+
return ps
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def evaluate(gt_pages, pred_index, member_thr, drop_ignore):
|
| 155 |
+
slices = defaultdict(Acc)
|
| 156 |
+
for img_name, pred_page in pred_index.items():
|
| 157 |
+
gt_page = gt_pages.get(img_name)
|
| 158 |
+
if gt_page is None:
|
| 159 |
+
continue
|
| 160 |
+
gts = gt_equations(gt_page, drop_ignore)
|
| 161 |
+
preds = pred_equations(pred_page)
|
| 162 |
+
if not gts and not preds:
|
| 163 |
+
continue
|
| 164 |
+
ps = score_page(gts, preds, member_thr)
|
| 165 |
+
|
| 166 |
+
keys = ["all"]
|
| 167 |
+
for k in SLICE_KEYS:
|
| 168 |
+
v = gt_page["attr"].get(k)
|
| 169 |
+
if isinstance(v, list):
|
| 170 |
+
keys += [f"{k}={x}" for x in v]
|
| 171 |
+
elif v is not None:
|
| 172 |
+
keys.append(f"{k}={v}")
|
| 173 |
+
|
| 174 |
+
for key in keys:
|
| 175 |
+
a = slices[key]
|
| 176 |
+
a.n_gt += ps["n_gt"]
|
| 177 |
+
a.n_matched += ps["n_matched"]
|
| 178 |
+
a.n_pred += ps["n_pred"]
|
| 179 |
+
a.n_pred_unmatched += ps["n_pred_unmatched"]
|
| 180 |
+
for d, mlen, matched in ps["pairs"]:
|
| 181 |
+
a.num_all += d
|
| 182 |
+
a.den_all += mlen
|
| 183 |
+
a.ratio_all.append(d / mlen if mlen else 0.0)
|
| 184 |
+
if matched:
|
| 185 |
+
a.num_m += d
|
| 186 |
+
a.den_m += mlen
|
| 187 |
+
return slices
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def parse_args():
|
| 191 |
+
ap = argparse.ArgumentParser(description=__doc__,
|
| 192 |
+
formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 193 |
+
ap.add_argument("--gt", type=Path, required=True)
|
| 194 |
+
ap.add_argument("--pred", type=Path, required=True)
|
| 195 |
+
ap.add_argument("--mapping", type=Path, required=True)
|
| 196 |
+
ap.add_argument("--out", type=Path, default=None)
|
| 197 |
+
ap.add_argument("--member-thr", type=float, default=0.5)
|
| 198 |
+
ap.add_argument("--keep-ignore", action="store_true")
|
| 199 |
+
ap.add_argument("--min-slice", type=int, default=20,
|
| 200 |
+
help="Chỉ in lát cắt có >= N công thức GT.")
|
| 201 |
+
return ap.parse_args()
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def main() -> int:
|
| 205 |
+
args = parse_args()
|
| 206 |
+
gt_pages = E.load_gt(args.gt, "merged")
|
| 207 |
+
mapping = json.load(open(args.mapping, encoding="utf-8"))
|
| 208 |
+
pred_index = E.build_pred_index(args.pred, mapping)
|
| 209 |
+
print(f"[formula] GT trang={len(gt_pages)} pred trang={len(pred_index)} "
|
| 210 |
+
f"member_thr={args.member_thr}")
|
| 211 |
+
|
| 212 |
+
slices = evaluate(gt_pages, pred_index, args.member_thr, not args.keep_ignore)
|
| 213 |
+
report = {
|
| 214 |
+
"config": {"member_thr": args.member_thr, "drop_ignore": not args.keep_ignore},
|
| 215 |
+
"slices": {k: a.summary() for k, a in slices.items()},
|
| 216 |
+
}
|
| 217 |
+
if args.out:
|
| 218 |
+
args.out.write_text(json.dumps(report, indent=2, ensure_ascii=False), encoding="utf-8")
|
| 219 |
+
|
| 220 |
+
a = slices["all"].summary()
|
| 221 |
+
print("\n===== FORMULA (all) =====")
|
| 222 |
+
print(f" GT công thức = {a['gt_formulas']} coverage(recall detect) = {a['coverage']}")
|
| 223 |
+
print(f" pred Equation = {a['pred_formulas']} không khớp GT nào = {a['pred_unmatched']}")
|
| 224 |
+
print(f" edit_all micro = {a['edit_all_micro']} sample = {a['edit_all_sample']} (gồm cả sót detect)")
|
| 225 |
+
print(f" edit_matched micro = {a['edit_matched_micro']} -> score = {a['score_matched']} (nhận dạng thuần)")
|
| 226 |
+
|
| 227 |
+
print("\n===== THEO LÁT CẮT (coverage / edit_matched / edit_all) =====")
|
| 228 |
+
for key in sorted(slices):
|
| 229 |
+
if key == "all":
|
| 230 |
+
continue
|
| 231 |
+
s = slices[key].summary()
|
| 232 |
+
if s["gt_formulas"] < args.min_slice:
|
| 233 |
+
continue
|
| 234 |
+
print(f" {key:28s} cov={str(s['coverage']):>6} "
|
| 235 |
+
f"editM={str(s['edit_matched_micro']):>6} "
|
| 236 |
+
f"editAll={str(s['edit_all_micro']):>6} (gt={s['gt_formulas']})")
|
| 237 |
+
|
| 238 |
+
if args.out:
|
| 239 |
+
print(f"\n[formula] report -> {args.out}")
|
| 240 |
+
return 0
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
if __name__ == "__main__":
|
| 244 |
+
raise SystemExit(main())
|
benchmark/parser/evaluation/eval_formula_cdm.py
ADDED
|
@@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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Đánh giá công thức bằng CDM (Character Detection Matching) — chuẩn vàng.
|
| 2 |
+
|
| 3 |
+
CDM render LaTeX (GT và pred) ra ảnh rồi khớp từng ký hiệu -> precision/recall/F1,
|
| 4 |
+
KHÔNG bị nhiễu bởi khác ký hiệu như edit distance (``\\left[`` vs ``\\left\\lbrack``…).
|
| 5 |
+
|
| 6 |
+
Script này TÁI DÙNG lớp ``CDM`` trong OmniDocBench/src/metrics/cdm và bộ ghép cặp
|
| 7 |
+
công thức của ``eval_formula.py`` (match Equation ↔ equation_isolated theo bbox).
|
| 8 |
+
Chỉ chạy trên các công thức GT ĐÃ được parser phủ (matched); công thức sót detect
|
| 9 |
+
đã phản ánh ở ``coverage`` của eval_formula.
|
| 10 |
+
|
| 11 |
+
YÊU CẦU HỆ THỐNG (CDM render bằng LaTeX + ImageMagick):
|
| 12 |
+
* pdflatex, kpsewhich (texlive) -> apt install texlive-latex-extra texlive-latex-base
|
| 13 |
+
* magick / convert (ImageMagick) -> apt install imagemagick
|
| 14 |
+
* python: numpy, Pillow (đã thêm vào requirements-eval.txt)
|
| 15 |
+
Nếu thiếu, script báo rõ và thoát (không chạy dở).
|
| 16 |
+
|
| 17 |
+
Ví dụ (chạy nơi có texlive + imagemagick, vd Colab/Docker)
|
| 18 |
+
-----
|
| 19 |
+
# chạy từ benchmark/parser/ (cần texlive + imagemagick + pylatexenc)
|
| 20 |
+
python evaluation/eval_formula_cdm.py \
|
| 21 |
+
--gt data/OmniDocBench.json --pred parser_results \
|
| 22 |
+
--mapping parser_results/mapping.json --omnidocbench ../../OmniDocBench \
|
| 23 |
+
--out eval_results/eval_report_formula_cdm.json --limit 200
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
from __future__ import annotations
|
| 27 |
+
|
| 28 |
+
import argparse
|
| 29 |
+
import json
|
| 30 |
+
import os
|
| 31 |
+
import shutil
|
| 32 |
+
import sys
|
| 33 |
+
import tempfile
|
| 34 |
+
from collections import defaultdict
|
| 35 |
+
from pathlib import Path
|
| 36 |
+
|
| 37 |
+
sys.path.insert(0, str(Path(__file__).resolve().parent)) # import module cạnh bên
|
| 38 |
+
import eval_layout as E
|
| 39 |
+
import eval_formula as F
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def ensure_magick() -> None:
|
| 43 |
+
"""CDM gọi hardcode lệnh ``magick`` (ImageMagick 7). Trên ImageMagick 6 chỉ có
|
| 44 |
+
``convert`` -> tạo shim ``magick`` trỏ về ``convert`` và nhét vào PATH.
|
| 45 |
+
(build_tex_env của CDM copy os.environ nên shim này được thấy.)"""
|
| 46 |
+
if shutil.which("magick"):
|
| 47 |
+
return
|
| 48 |
+
convert = shutil.which("convert")
|
| 49 |
+
if not convert:
|
| 50 |
+
return
|
| 51 |
+
shim_dir = Path(tempfile.gettempdir()) / "cdm_magick_shim"
|
| 52 |
+
shim_dir.mkdir(exist_ok=True)
|
| 53 |
+
shim = shim_dir / "magick"
|
| 54 |
+
shim.write_text(f'#!/bin/sh\nexec "{convert}" "$@"\n')
|
| 55 |
+
shim.chmod(0o755)
|
| 56 |
+
os.environ["PATH"] = str(shim_dir) + os.pathsep + os.environ.get("PATH", "")
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def check_system_deps() -> list[str]:
|
| 60 |
+
missing = []
|
| 61 |
+
if not (shutil.which("pdflatex") and shutil.which("kpsewhich")):
|
| 62 |
+
missing.append("pdflatex/kpsewhich (texlive)")
|
| 63 |
+
if not (shutil.which("magick") or shutil.which("convert")):
|
| 64 |
+
missing.append("magick/convert (ImageMagick)")
|
| 65 |
+
for mod in ("numpy", "PIL", "scipy"):
|
| 66 |
+
try:
|
| 67 |
+
__import__(mod)
|
| 68 |
+
except Exception:
|
| 69 |
+
missing.append(f"python:{mod}")
|
| 70 |
+
return missing
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def resolve_omnidocbench(arg: Path | None) -> Path:
|
| 74 |
+
if arg is not None:
|
| 75 |
+
if (arg / "src" / "metrics" / "cdm").is_dir():
|
| 76 |
+
return arg.resolve()
|
| 77 |
+
raise FileNotFoundError(f"Không thấy src/metrics/cdm dưới {arg}")
|
| 78 |
+
for cand in (Path(__file__).resolve().parents[3] / "OmniDocBench",
|
| 79 |
+
Path("../../../OmniDocBench"), Path("OmniDocBench")):
|
| 80 |
+
if (cand / "src" / "metrics" / "cdm").is_dir():
|
| 81 |
+
return cand.resolve()
|
| 82 |
+
raise FileNotFoundError("Không định vị được OmniDocBench (truyền --omnidocbench).")
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def collect_pairs(gt_pages, pred_index, member_thr):
|
| 86 |
+
"""Trả list (img_id, gt_latex, pred_latex, slice_keys) cho công thức đã match."""
|
| 87 |
+
pairs = []
|
| 88 |
+
for img_name, pred_page in pred_index.items():
|
| 89 |
+
gt_page = gt_pages.get(img_name)
|
| 90 |
+
if gt_page is None:
|
| 91 |
+
continue
|
| 92 |
+
gts = F.gt_equations(gt_page, drop_ignore=True)
|
| 93 |
+
preds = F.pred_equations(pred_page)
|
| 94 |
+
keys = ["all"]
|
| 95 |
+
for k in F.SLICE_KEYS:
|
| 96 |
+
v = gt_page["attr"].get(k)
|
| 97 |
+
if isinstance(v, list):
|
| 98 |
+
keys += [f"{k}={x}" for x in v]
|
| 99 |
+
elif v is not None:
|
| 100 |
+
keys.append(f"{k}={v}")
|
| 101 |
+
for gi, g in enumerate(gts):
|
| 102 |
+
members = [p for p in preds if E.contain_ratio(p["box"], g["box"]) >= member_thr]
|
| 103 |
+
if not members:
|
| 104 |
+
continue
|
| 105 |
+
members.sort(key=lambda m: (round(m["box"][1], 3), m["box"][0]))
|
| 106 |
+
pred_latex = F.norm_formula(" ".join(m["text"] for m in members))
|
| 107 |
+
if g["latex"] or pred_latex:
|
| 108 |
+
pairs.append((f"{img_name}#{gi}", g["latex"], pred_latex, keys))
|
| 109 |
+
return pairs
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def _micro_f1(tp, gt_tok, pred_tok):
|
| 113 |
+
r = tp / gt_tok if gt_tok else None
|
| 114 |
+
p = tp / pred_tok if pred_tok else None
|
| 115 |
+
f = (2 * p * r / (p + r)) if (p and r and (p + r)) else None
|
| 116 |
+
return p, r, f
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
class Acc:
|
| 120 |
+
def __init__(self):
|
| 121 |
+
self.tp = self.gt_tok = self.pred_tok = 0
|
| 122 |
+
self.n_pred_zero = self.n_gt_zero = 0
|
| 123 |
+
self.f1_list = []
|
| 124 |
+
|
| 125 |
+
def add(self, m):
|
| 126 |
+
self.tp += m.get("tp", 0)
|
| 127 |
+
self.gt_tok += m.get("gt_tokens", 0)
|
| 128 |
+
self.pred_tok += m.get("pred_tokens", 0)
|
| 129 |
+
self.n_pred_zero += (m.get("pred_tokens", 0) == 0)
|
| 130 |
+
self.n_gt_zero += (m.get("gt_tokens", 0) == 0)
|
| 131 |
+
self.f1_list.append(m.get("F1_score", 0.0))
|
| 132 |
+
|
| 133 |
+
def summary(self):
|
| 134 |
+
n = len(self.f1_list)
|
| 135 |
+
p, r, f = _micro_f1(self.tp, self.gt_tok, self.pred_tok)
|
| 136 |
+
rd = lambda x: round(x, 4) if x is not None else None
|
| 137 |
+
return {
|
| 138 |
+
"n": n,
|
| 139 |
+
"CDM_recall_micro": rd(r), "CDM_precision_micro": rd(p),
|
| 140 |
+
"CDM_F1_micro": rd(f),
|
| 141 |
+
"CDM_F1_mean": rd(sum(self.f1_list) / n) if n else None,
|
| 142 |
+
"pred_render_fail_rate": rd(self.n_pred_zero / n) if n else None,
|
| 143 |
+
"gt_render_fail_rate": rd(self.n_gt_zero / n) if n else None,
|
| 144 |
+
}
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def parse_args():
|
| 148 |
+
ap = argparse.ArgumentParser(description=__doc__,
|
| 149 |
+
formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 150 |
+
ap.add_argument("--gt", type=Path, required=True)
|
| 151 |
+
ap.add_argument("--pred", type=Path, required=True)
|
| 152 |
+
ap.add_argument("--mapping", type=Path, required=True)
|
| 153 |
+
ap.add_argument("--omnidocbench", type=Path, default=None,
|
| 154 |
+
help="Đường dẫn repo OmniDocBench (để import CDM).")
|
| 155 |
+
ap.add_argument("--out", type=Path, default=None)
|
| 156 |
+
ap.add_argument("--member-thr", type=float, default=0.5)
|
| 157 |
+
ap.add_argument("--limit", type=int, default=None, help="Chỉ chấm N cặp đầu (test).")
|
| 158 |
+
ap.add_argument("--result-dir", type=Path, default=Path("./cdm_work"),
|
| 159 |
+
help="Thư mục tạm CDM render (mặc định ./cdm_work).")
|
| 160 |
+
return ap.parse_args()
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def main() -> int:
|
| 164 |
+
args = parse_args()
|
| 165 |
+
|
| 166 |
+
ensure_magick()
|
| 167 |
+
missing = check_system_deps()
|
| 168 |
+
if missing:
|
| 169 |
+
print("[cdm] THIẾU dependency, không chạy được CDM:", flush=True)
|
| 170 |
+
for m in missing:
|
| 171 |
+
print(f" - {m}", flush=True)
|
| 172 |
+
print("\nCài (Ubuntu/Colab):\n"
|
| 173 |
+
" apt-get install -y texlive-latex-base texlive-latex-extra "
|
| 174 |
+
"texlive-fonts-recommended imagemagick\n"
|
| 175 |
+
" .venv/bin/pip install numpy Pillow", flush=True)
|
| 176 |
+
return 2
|
| 177 |
+
|
| 178 |
+
odb = resolve_omnidocbench(args.omnidocbench)
|
| 179 |
+
# Import THẲNG gói cdm (thêm src/metrics vào path) để né src/__init__.py
|
| 180 |
+
# vốn kéo theo cli/yaml/evaluate... rất nặng.
|
| 181 |
+
sys.path.insert(0, str(odb / "src" / "metrics"))
|
| 182 |
+
from cdm.cdm import cdm_metrics # noqa: E402
|
| 183 |
+
|
| 184 |
+
gt_pages = E.load_gt(args.gt, "merged")
|
| 185 |
+
mapping = json.load(open(args.mapping, encoding="utf-8"))
|
| 186 |
+
pred_index = E.build_pred_index(args.pred, mapping)
|
| 187 |
+
pairs = collect_pairs(gt_pages, pred_index, args.member_thr)
|
| 188 |
+
if args.limit:
|
| 189 |
+
pairs = pairs[: args.limit]
|
| 190 |
+
print(f"[cdm] {len(pairs)} cặp công thức đã match sẽ chấm bằng CDM "
|
| 191 |
+
f"(render LaTeX -> có thể chậm)...", flush=True)
|
| 192 |
+
|
| 193 |
+
args.result_dir.mkdir(parents=True, exist_ok=True)
|
| 194 |
+
slices = defaultdict(Acc)
|
| 195 |
+
for i, (img_id, gt_latex, pred_latex, keys) in enumerate(pairs, 1):
|
| 196 |
+
try:
|
| 197 |
+
m = cdm_metrics(gt_latex, pred_latex, save_vis=False,
|
| 198 |
+
tmp_dir=str(args.result_dir))
|
| 199 |
+
except Exception as exc:
|
| 200 |
+
print(f" [{i}] lỗi CDM {img_id}: {exc!r}", flush=True)
|
| 201 |
+
continue
|
| 202 |
+
for key in keys:
|
| 203 |
+
slices[key].add(m)
|
| 204 |
+
if i % 50 == 0:
|
| 205 |
+
print(f" ...{i}/{len(pairs)}", flush=True)
|
| 206 |
+
|
| 207 |
+
report = {"config": {"member_thr": args.member_thr, "n_pairs": len(pairs)},
|
| 208 |
+
"slices": {k: a.summary() for k, a in slices.items()}}
|
| 209 |
+
if args.out:
|
| 210 |
+
args.out.write_text(json.dumps(report, indent=2, ensure_ascii=False), encoding="utf-8")
|
| 211 |
+
|
| 212 |
+
a = slices["all"].summary()
|
| 213 |
+
print("\n===== FORMULA CDM (all, trên công thức đã match) =====")
|
| 214 |
+
print(f" n = {a['n']} render_fail = {a['pred_render_fail_rate']}")
|
| 215 |
+
print(f" CDM F1 micro = {a['CDM_F1_micro']} (P={a['CDM_precision_micro']}, "
|
| 216 |
+
f"R={a['CDM_recall_micro']}) mean={a['CDM_F1_mean']}")
|
| 217 |
+
|
| 218 |
+
print("\n===== THEO LÁT CẮT (CDM F1) =====")
|
| 219 |
+
for key in sorted(slices):
|
| 220 |
+
if key == "all":
|
| 221 |
+
continue
|
| 222 |
+
s = slices[key].summary()
|
| 223 |
+
if (s["n"] or 0) < 20:
|
| 224 |
+
continue
|
| 225 |
+
print(f" {key:28s} F1={str(s['CDM_F1_micro']):>7} "
|
| 226 |
+
f"render_fail={str(s['pred_render_fail_rate']):>7} (n={s['n']})")
|
| 227 |
+
if args.out:
|
| 228 |
+
print(f"\n[cdm] report -> {args.out}")
|
| 229 |
+
return 0
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
if __name__ == "__main__":
|
| 233 |
+
raise SystemExit(main())
|
benchmark/parser/evaluation/eval_layout.py
ADDED
|
@@ -0,0 +1,639 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Đánh giá output của StageAParser với ground-truth OmniDocBench (parser-vs-GT).
|
| 2 |
+
|
| 3 |
+
Thiết kế để chịu được lệch granularity (many-to-one / one-to-many) sinh ra khi
|
| 4 |
+
parser gộp nhiều thứ rời rạc vào một bbox rồi split (is_sparse_text_block), hoặc
|
| 5 |
+
ngược lại parser gộp nhiều box GT vào một:
|
| 6 |
+
|
| 7 |
+
* Matching theo CONTAINMENT + UNION, không phải IoU 1-1:
|
| 8 |
+
- recall (neo theo GT) : gom mọi pred nằm gọn (>= member_thr) trong 1 GT,
|
| 9 |
+
union lại rồi so IoU với GT. -> gộp nhiều GT vào
|
| 10 |
+
1 pred sẽ bị phạt recall (đúng: parser thiếu tách).
|
| 11 |
+
- precision (neo theo pred): đối xứng, gom mọi GT nằm gọn trong 1 pred.
|
| 12 |
+
-> over-split sẽ bị phạt precision (đúng).
|
| 13 |
+
* Tách LOCALIZATION (class-agnostic) và CLASSIFICATION (label-agreement) để mẹo
|
| 14 |
+
"label con = label mẹ" không bị phạt kép.
|
| 15 |
+
* Chuẩn hoá bbox về [0,1] theo kích thước từng trang -> khỏi lệch DPI.
|
| 16 |
+
* Chọn granularity GT: 'merged' (dùng box top-level như OmniDocBench) hoặc
|
| 17 |
+
'fine' (bung merge_list ra sub-box; hợp với output đã split).
|
| 18 |
+
* Báo cáo tổng + theo lát cắt: language / layout / subset / data_source.
|
| 19 |
+
* OCR edit distance (chuẩn hoá) trên các nhóm văn bản; reading-order edit dist.
|
| 20 |
+
|
| 21 |
+
Để so BEFORE vs AFTER split: chạy 2 lần trên 2 thư mục parser_results khác nhau
|
| 22 |
+
(một bản dump trước split, một bản sau split) rồi đối chiếu report.
|
| 23 |
+
|
| 24 |
+
Ví dụ
|
| 25 |
+
-----
|
| 26 |
+
# chạy từ benchmark/parser/
|
| 27 |
+
python evaluation/eval_layout.py \
|
| 28 |
+
--gt data/OmniDocBench.json \
|
| 29 |
+
--pred parser_results \
|
| 30 |
+
--mapping parser_results/mapping.json \
|
| 31 |
+
--gt-granularity fine \
|
| 32 |
+
--out eval_results/eval_report_fine.json
|
| 33 |
+
"""
|
| 34 |
+
|
| 35 |
+
from __future__ import annotations
|
| 36 |
+
|
| 37 |
+
import argparse
|
| 38 |
+
import glob
|
| 39 |
+
import json
|
| 40 |
+
from collections import Counter, defaultdict
|
| 41 |
+
from pathlib import Path
|
| 42 |
+
|
| 43 |
+
# --------------------------------------------------------------------------- #
|
| 44 |
+
# Ánh xạ nhãn về NHÓM THÔ (ổn định hơn map chi tiết 28<->14). #
|
| 45 |
+
# Sửa trực tiếp ở đây nếu bạn muốn gộp/tách nhóm khác đi. #
|
| 46 |
+
# --------------------------------------------------------------------------- #
|
| 47 |
+
GT_GROUP = {
|
| 48 |
+
"text_block": "text", "reference": "text", "list_group": "text",
|
| 49 |
+
"code_txt": "code", "equation_explanation": "text",
|
| 50 |
+
"title": "section",
|
| 51 |
+
"equation_isolated": "formula", "equation_semantic": "formula",
|
| 52 |
+
"table": "table",
|
| 53 |
+
"figure": "figure",
|
| 54 |
+
"figure_caption": "caption", "table_caption": "caption",
|
| 55 |
+
"equation_caption": "caption", "code_txt_caption": "caption",
|
| 56 |
+
"header": "header_footer", "footer": "header_footer", "page_number": "header_footer",
|
| 57 |
+
"figure_footnote": "text", "table_footnote": "text", "page_footnote": "footnote",
|
| 58 |
+
"abandon": "abandon",
|
| 59 |
+
# *_mask, unknown_mask, ... -> "other" (mặc định)
|
| 60 |
+
}
|
| 61 |
+
PRED_GROUP = {
|
| 62 |
+
"Text": "text", "ListItem": "text", "TableOfContents": "text", "Code": "code",
|
| 63 |
+
"SectionHeader": "section",
|
| 64 |
+
"Equation": "formula",
|
| 65 |
+
"Table": "table",
|
| 66 |
+
"Figure": "figure", "Picture": "figure",
|
| 67 |
+
"Caption": "caption",
|
| 68 |
+
"PageHeader": "header_footer", "PageFooter": "header_footer",
|
| 69 |
+
"Footnote": "footnote",
|
| 70 |
+
"Form": "text",
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
# Nhóm không đưa vào matching (không phải mục tiêu detect / không có đối ứng).
|
| 74 |
+
EXCLUDE_GROUPS = {"abandon", "other"}
|
| 75 |
+
# Nhóm tính OCR edit distance (văn bản thuần; formula/table so nội dung riêng).
|
| 76 |
+
OCR_GROUPS = {"text", "section", "caption", "footnote"}
|
| 77 |
+
# Các chiều lát cắt lấy từ page_attribute.
|
| 78 |
+
SLICE_KEYS = ("language", "layout", "subset", "data_source")
|
| 79 |
+
IOU_THRESHOLDS = [round(0.5 + 0.05 * i, 2) for i in range(10)] # .50 .. .95
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
# --------------------------------------------------------------------------- #
|
| 83 |
+
# Hình học #
|
| 84 |
+
# --------------------------------------------------------------------------- #
|
| 85 |
+
def poly_to_xyxy(poly: list[float]) -> list[float]:
|
| 86 |
+
xs, ys = poly[0::2], poly[1::2]
|
| 87 |
+
return [min(xs), min(ys), max(xs), max(ys)]
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def norm_box(b: list[float], w: float, h: float) -> list[float]:
|
| 91 |
+
if not w or not h:
|
| 92 |
+
return [0.0, 0.0, 0.0, 0.0]
|
| 93 |
+
return [b[0] / w, b[1] / h, b[2] / w, b[3] / h]
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def area(b: list[float]) -> float:
|
| 97 |
+
return max(0.0, b[2] - b[0]) * max(0.0, b[3] - b[1])
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def inter_area(a: list[float], b: list[float]) -> float:
|
| 101 |
+
x0, y0 = max(a[0], b[0]), max(a[1], b[1])
|
| 102 |
+
x1, y1 = min(a[2], b[2]), min(a[3], b[3])
|
| 103 |
+
return max(0.0, x1 - x0) * max(0.0, y1 - y0)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def iou(a: list[float], b: list[float]) -> float:
|
| 107 |
+
inter = inter_area(a, b)
|
| 108 |
+
union = area(a) + area(b) - inter
|
| 109 |
+
return inter / union if union > 0 else 0.0
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def contain_ratio(inner: list[float], outer: list[float]) -> float:
|
| 113 |
+
"""Tỉ lệ diện tích của `inner` nằm trong `outer` (0..1)."""
|
| 114 |
+
a = area(inner)
|
| 115 |
+
return inter_area(inner, outer) / a if a > 0 else 0.0
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def union_box(boxes: list[list[float]]) -> list[float]:
|
| 119 |
+
return [min(b[0] for b in boxes), min(b[1] for b in boxes),
|
| 120 |
+
max(b[2] for b in boxes), max(b[3] for b in boxes)]
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
# --------------------------------------------------------------------------- #
|
| 124 |
+
# Edit distance. Ưu tiên python-Levenshtein (C). Không có thì dùng Myers #
|
| 125 |
+
# bit-parallel thuần Python (exact, ~300x nhanh hơn DP trên chuỗi dài). #
|
| 126 |
+
# --------------------------------------------------------------------------- #
|
| 127 |
+
def _myers(a, b) -> int:
|
| 128 |
+
"""Levenshtein (Hyyrö/Myers bit-parallel). Dùng được cho str và list."""
|
| 129 |
+
if len(a) == 0 or len(b) == 0:
|
| 130 |
+
return max(len(a), len(b))
|
| 131 |
+
if len(a) > len(b):
|
| 132 |
+
a, b = b, a
|
| 133 |
+
m = len(a)
|
| 134 |
+
mask = (1 << m) - 1
|
| 135 |
+
Peq = {}
|
| 136 |
+
for i, c in enumerate(a):
|
| 137 |
+
Peq[c] = Peq.get(c, 0) | (1 << i)
|
| 138 |
+
Pv, Mv, score, last = mask, 0, m, 1 << (m - 1)
|
| 139 |
+
for c in b:
|
| 140 |
+
Eq = Peq.get(c, 0)
|
| 141 |
+
Xv = Eq | Mv
|
| 142 |
+
Xh = (((Eq & Pv) + Pv) ^ Pv) | Eq
|
| 143 |
+
Ph = (Mv | ~(Xh | Pv)) & mask
|
| 144 |
+
Mh = (Pv & Xh) & mask
|
| 145 |
+
if Ph & last:
|
| 146 |
+
score += 1
|
| 147 |
+
elif Mh & last:
|
| 148 |
+
score -= 1
|
| 149 |
+
Ph = ((Ph << 1) | 1) & mask
|
| 150 |
+
Mh = (Mh << 1) & mask
|
| 151 |
+
Pv = (Mh | ~(Xv | Ph)) & mask
|
| 152 |
+
Mv = (Ph & Xv) & mask
|
| 153 |
+
return score
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
try:
|
| 157 |
+
import Levenshtein as _Lev
|
| 158 |
+
|
| 159 |
+
def _dist(a, b) -> int:
|
| 160 |
+
if isinstance(a, str) and isinstance(b, str):
|
| 161 |
+
return _Lev.distance(a, b)
|
| 162 |
+
return _myers(a, b)
|
| 163 |
+
except Exception: # pragma: no cover
|
| 164 |
+
def _dist(a, b) -> int:
|
| 165 |
+
return _myers(a, b)
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def norm_edit(a, b) -> float:
|
| 169 |
+
"""Normalized edit distance = dist / max(len). 0 = giống hệt."""
|
| 170 |
+
m = max(len(a), len(b))
|
| 171 |
+
return _dist(a, b) / m if m else 0.0
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
import html as _html
|
| 175 |
+
import re as _re
|
| 176 |
+
|
| 177 |
+
_MATH_BLOCK = _re.compile(r"<math\b[^>]*>(.*?)</math>", _re.IGNORECASE | _re.DOTALL)
|
| 178 |
+
_INLINE_DOLLAR = _re.compile(r"\$\$?(.+?)\$\$?", _re.DOTALL) # $...$ hoặc $$...$$
|
| 179 |
+
_FMT_TAGS = _re.compile(
|
| 180 |
+
r"</?(?:b|i|u|s|em|strong|del|mark|sub|sup|small|big|tt|code|span|font|br|p|h[1-6])\b[^>]*>",
|
| 181 |
+
_re.IGNORECASE)
|
| 182 |
+
_ANY_TAG = _re.compile(r"</?[a-zA-Z][^>]*>")
|
| 183 |
+
_WS = _re.compile(r"\s+")
|
| 184 |
+
_PLACEHOLDER = "░" # token thay cho công thức khi --mask-math
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def norm_ocr(s: str, mask_math: bool = False) -> str:
|
| 188 |
+
"""Chuẩn hoá text cho đo OCR, tránh phạt oan do thẻ HTML / lớp bọc công thức.
|
| 189 |
+
|
| 190 |
+
- Hợp nhất inline math: pred ``<math>BODY</math>`` và GT ``$BODY$`` -> BODY
|
| 191 |
+
(hoặc placeholder nếu mask_math) để hai bên so được.
|
| 192 |
+
- Bóc các thẻ định dạng (<b>,<i>,<sub>,<sup>,...) giữ lại nội dung bên trong.
|
| 193 |
+
- Unescape HTML entity, gom khoảng trắng.
|
| 194 |
+
"""
|
| 195 |
+
s = _html.unescape(s or "")
|
| 196 |
+
if mask_math:
|
| 197 |
+
s = _MATH_BLOCK.sub(f" {_PLACEHOLDER} ", s)
|
| 198 |
+
s = _INLINE_DOLLAR.sub(f" {_PLACEHOLDER} ", s)
|
| 199 |
+
else:
|
| 200 |
+
s = _MATH_BLOCK.sub(lambda m: " " + m.group(1).strip() + " ", s)
|
| 201 |
+
s = _INLINE_DOLLAR.sub(lambda m: " " + m.group(1).strip() + " ", s)
|
| 202 |
+
s = _FMT_TAGS.sub("", s)
|
| 203 |
+
s = _ANY_TAG.sub("", s)
|
| 204 |
+
return _WS.sub(" ", s).strip()
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
def norm_text(s: str) -> str: # giữ tương thích (chỉ gom trắng)
|
| 208 |
+
return " ".join((s or "").split())
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
# --------------------------------------------------------------------------- #
|
| 212 |
+
# Nạp dữ liệu #
|
| 213 |
+
# --------------------------------------------------------------------------- #
|
| 214 |
+
def load_gt(path: Path, granularity: str) -> dict:
|
| 215 |
+
data = json.load(open(path, encoding="utf-8"))
|
| 216 |
+
pages = {}
|
| 217 |
+
for p in data:
|
| 218 |
+
info = p["page_info"]
|
| 219 |
+
dets = []
|
| 220 |
+
for d in p["layout_dets"]:
|
| 221 |
+
if granularity == "fine" and d.get("merge_list"):
|
| 222 |
+
dets.extend(d["merge_list"])
|
| 223 |
+
else:
|
| 224 |
+
dets.append(d)
|
| 225 |
+
pages[info["image_path"]] = {
|
| 226 |
+
"w": info["width"], "h": info["height"],
|
| 227 |
+
"attr": info.get("page_attribute", {}), "dets": dets,
|
| 228 |
+
}
|
| 229 |
+
return pages
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
def prep_gt(page: dict, drop_ignore: bool) -> list[dict]:
|
| 233 |
+
out = []
|
| 234 |
+
for d in page["dets"]:
|
| 235 |
+
if drop_ignore and d.get("ignore"):
|
| 236 |
+
continue
|
| 237 |
+
grp = GT_GROUP.get(d.get("category_type"), "other")
|
| 238 |
+
if grp in EXCLUDE_GROUPS:
|
| 239 |
+
continue
|
| 240 |
+
txt = d.get("text") or d.get("latex") or d.get("html") or ""
|
| 241 |
+
out.append({
|
| 242 |
+
"box": norm_box(poly_to_xyxy(d["poly"]), page["w"], page["h"]),
|
| 243 |
+
"group": grp, "cat": d.get("category_type"),
|
| 244 |
+
"text": txt, "order": d.get("order"),
|
| 245 |
+
})
|
| 246 |
+
return out
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
def prep_pred(page: dict) -> list[dict]:
|
| 250 |
+
out = []
|
| 251 |
+
W, H = page.get("page_width"), page.get("page_height")
|
| 252 |
+
for i, e in enumerate(page["elements"]):
|
| 253 |
+
grp = PRED_GROUP.get(e.get("label"), "other")
|
| 254 |
+
if grp in EXCLUDE_GROUPS:
|
| 255 |
+
continue
|
| 256 |
+
out.append({
|
| 257 |
+
"box": norm_box(e["bbox_pdf"], W, H),
|
| 258 |
+
"group": grp, "label": e.get("label"),
|
| 259 |
+
"text": e.get("source_text") or "",
|
| 260 |
+
"order": i, # thứ tự parser xuất (đã là reading order)
|
| 261 |
+
})
|
| 262 |
+
return out
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
# --------------------------------------------------------------------------- #
|
| 266 |
+
# Matching containment + union (bất đối xứng theo thiết kế) #
|
| 267 |
+
# --------------------------------------------------------------------------- #
|
| 268 |
+
def match_side(anchors: list[dict], others: list[dict], member_thr: float):
|
| 269 |
+
"""Với mỗi anchor, gom `others` nằm gọn trong nó (>= member_thr), union lại.
|
| 270 |
+
|
| 271 |
+
Trả list record: {anchor, members, union_iou, group_ok}.
|
| 272 |
+
"""
|
| 273 |
+
records = []
|
| 274 |
+
for a in anchors:
|
| 275 |
+
members = [o for o in others if contain_ratio(o["box"], a["box"]) >= member_thr]
|
| 276 |
+
if members:
|
| 277 |
+
u = union_box([m["box"] for m in members])
|
| 278 |
+
u_iou = iou(u, a["box"])
|
| 279 |
+
grp_counts = Counter(m["group"] for m in members)
|
| 280 |
+
group_ok = grp_counts.most_common(1)[0][0] == a["group"]
|
| 281 |
+
else:
|
| 282 |
+
u_iou, group_ok = 0.0, False
|
| 283 |
+
records.append({"anchor": a, "members": members,
|
| 284 |
+
"union_iou": u_iou, "group_ok": group_ok})
|
| 285 |
+
return records
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
def read_order_seq(matched_pairs: list[tuple]) -> float:
|
| 289 |
+
"""Normalized edit distance giữa thứ tự đọc GT và thứ tự GỐC parser xuất.
|
| 290 |
+
|
| 291 |
+
matched_pairs: list of (gt, pred_union_box, pred_order) với gt['order'] hợp lệ.
|
| 292 |
+
pred_order = chỉ số element nhỏ nhất của các pred thành viên = vị trí parser đặt
|
| 293 |
+
vùng này trong luồng đọc (parser vốn xuất theo reading order, xử lý đa cột đúng —
|
| 294 |
+
KHÔNG suy lại từ (y, x) vì sort (y,x) đọc ngang qua cột sẽ sai ở layout đa cột).
|
| 295 |
+
"""
|
| 296 |
+
pairs = [(g, ub, po) for g, ub, po in matched_pairs if g.get("order") is not None]
|
| 297 |
+
if len(pairs) < 2:
|
| 298 |
+
return None
|
| 299 |
+
ids = list(range(len(pairs)))
|
| 300 |
+
gt_seq = [i for i, _ in sorted(zip(ids, pairs), key=lambda t: t[1][0]["order"])]
|
| 301 |
+
pred_seq = [i for i, _ in sorted(zip(ids, pairs), key=lambda t: t[1][2])]
|
| 302 |
+
return norm_edit(gt_seq, pred_seq)
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
# --------------------------------------------------------------------------- #
|
| 306 |
+
# Localization matchers (tính TP theo từng ngưỡng IoU). #
|
| 307 |
+
# - COCO 1-1 : ghép tham lam theo IoU giảm dần, mỗi GT/pred dùng 1 lần #
|
| 308 |
+
# (chuẩn detection; không có confidence nên xếp theo IoU). #
|
| 309 |
+
# - COMPONENT : đồ thị chồng lấn -> thành phần liên thông; cụm 'khớp' nếu #
|
| 310 |
+
# IoU(union_GT, union_pred) >= t -> mọi GT/pred trong cụm là TP #
|
| 311 |
+
# (một phép ghép nhất quán, xử lý N-M). #
|
| 312 |
+
# Trả dict {t: (tp_gt, tp_pred)} cho từng ngưỡng. #
|
| 313 |
+
# --------------------------------------------------------------------------- #
|
| 314 |
+
def coco_tp_by_threshold(gts, preds, thresholds):
|
| 315 |
+
pairs = []
|
| 316 |
+
for i, g in enumerate(gts):
|
| 317 |
+
for j, p in enumerate(preds):
|
| 318 |
+
v = iou(g["box"], p["box"])
|
| 319 |
+
if v > 0:
|
| 320 |
+
pairs.append((v, i, j))
|
| 321 |
+
pairs.sort(reverse=True)
|
| 322 |
+
out = {}
|
| 323 |
+
for t in thresholds:
|
| 324 |
+
ug, up, tp = set(), set(), 0
|
| 325 |
+
for v, i, j in pairs:
|
| 326 |
+
if v < t:
|
| 327 |
+
break # pairs xếp giảm dần
|
| 328 |
+
if i in ug or j in up:
|
| 329 |
+
continue
|
| 330 |
+
ug.add(i); up.add(j); tp += 1
|
| 331 |
+
out[t] = (tp, tp) # ghép 1-1: tp_gt == tp_pred
|
| 332 |
+
return out
|
| 333 |
+
|
| 334 |
+
|
| 335 |
+
def component_tp_by_threshold(gts, preds, thresholds):
|
| 336 |
+
parent = {}
|
| 337 |
+
def find(x):
|
| 338 |
+
parent.setdefault(x, x)
|
| 339 |
+
root = x
|
| 340 |
+
while parent[root] != root:
|
| 341 |
+
root = parent[root]
|
| 342 |
+
while parent[x] != root:
|
| 343 |
+
parent[x], x = root, parent[x]
|
| 344 |
+
return root
|
| 345 |
+
def union(a, b):
|
| 346 |
+
ra, rb = find(a), find(b)
|
| 347 |
+
if ra != rb:
|
| 348 |
+
parent[ra] = rb
|
| 349 |
+
for i in range(len(gts)):
|
| 350 |
+
find(("g", i))
|
| 351 |
+
for j in range(len(preds)):
|
| 352 |
+
find(("p", j))
|
| 353 |
+
for i, g in enumerate(gts):
|
| 354 |
+
for j, p in enumerate(preds):
|
| 355 |
+
gb, pb = g["box"], p["box"]
|
| 356 |
+
if (iou(gb, pb) >= 0.5 or contain_ratio(gb, pb) >= 0.5
|
| 357 |
+
or contain_ratio(pb, gb) >= 0.5):
|
| 358 |
+
union(("g", i), ("p", j))
|
| 359 |
+
comps = defaultdict(lambda: {"g": [], "p": []})
|
| 360 |
+
for i, g in enumerate(gts):
|
| 361 |
+
comps[find(("g", i))]["g"].append(g["box"])
|
| 362 |
+
for j, p in enumerate(preds):
|
| 363 |
+
comps[find(("p", j))]["p"].append(p["box"])
|
| 364 |
+
comp_list = []
|
| 365 |
+
for c in comps.values():
|
| 366 |
+
if c["g"] and c["p"]:
|
| 367 |
+
uiou = iou(union_box(c["g"]), union_box(c["p"]))
|
| 368 |
+
comp_list.append((uiou, len(c["g"]), len(c["p"])))
|
| 369 |
+
out = {}
|
| 370 |
+
for t in thresholds:
|
| 371 |
+
tg = sum(ng for uiou, ng, _ in comp_list if uiou >= t)
|
| 372 |
+
tp = sum(npd for uiou, _, npd in comp_list if uiou >= t)
|
| 373 |
+
out[t] = (tg, tp)
|
| 374 |
+
return out
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
MATCHERS = ("coco", "component")
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
# --------------------------------------------------------------------------- #
|
| 381 |
+
# Tổng hợp #
|
| 382 |
+
# --------------------------------------------------------------------------- #
|
| 383 |
+
class Acc:
|
| 384 |
+
"""Bộ đếm tích luỹ cho 1 lát cắt."""
|
| 385 |
+
def __init__(self):
|
| 386 |
+
self.gt_total = 0
|
| 387 |
+
self.pred_total = 0
|
| 388 |
+
# loc[matcher][t] = [tp_gt, tp_pred] cho từng matcher (coco / component)
|
| 389 |
+
self.loc = {m: {t: [0, 0] for t in IOU_THRESHOLDS} for m in MATCHERS}
|
| 390 |
+
self.cls_matched = 0 # cặp recall khớp @0.5
|
| 391 |
+
self.cls_correct = 0 # trong đó đúng nhóm
|
| 392 |
+
self.edit_num = 0.0 # normalized-by-max (kiểu OmniDocBench Edit_dist)
|
| 393 |
+
self.edit_den = 0.0
|
| 394 |
+
self.cer_num = 0.0 # CER: char edits / độ dài GT
|
| 395 |
+
self.cer_den = 0.0
|
| 396 |
+
self.wer_num = 0.0 # WER: word edits / số từ GT
|
| 397 |
+
self.wer_den = 0.0
|
| 398 |
+
self.ocr_pairs = 0
|
| 399 |
+
self.ro_scores = []
|
| 400 |
+
|
| 401 |
+
def add(self, ps: dict):
|
| 402 |
+
"""Cộng dồn contribution của 1 trang (đã tính sẵn một lần)."""
|
| 403 |
+
self.gt_total += ps["gt_total"]
|
| 404 |
+
self.pred_total += ps["pred_total"]
|
| 405 |
+
for m in MATCHERS:
|
| 406 |
+
for t in IOU_THRESHOLDS:
|
| 407 |
+
self.loc[m][t][0] += ps["loc"][m][t][0]
|
| 408 |
+
self.loc[m][t][1] += ps["loc"][m][t][1]
|
| 409 |
+
self.cls_matched += ps["cls_matched"]
|
| 410 |
+
self.cls_correct += ps["cls_correct"]
|
| 411 |
+
self.edit_num += ps["edit_num"]
|
| 412 |
+
self.edit_den += ps["edit_den"]
|
| 413 |
+
self.cer_num += ps["cer_num"]
|
| 414 |
+
self.cer_den += ps["cer_den"]
|
| 415 |
+
self.wer_num += ps["wer_num"]
|
| 416 |
+
self.wer_den += ps["wer_den"]
|
| 417 |
+
self.ocr_pairs += ps["ocr_pairs"]
|
| 418 |
+
if ps["ro"] is not None:
|
| 419 |
+
self.ro_scores.append(ps["ro"])
|
| 420 |
+
|
| 421 |
+
def prf(self, m, t):
|
| 422 |
+
tg, tp = self.loc[m][t]
|
| 423 |
+
r = tg / self.gt_total if self.gt_total else 0.0
|
| 424 |
+
p = tp / self.pred_total if self.pred_total else 0.0
|
| 425 |
+
f = 2 * p * r / (p + r) if (p + r) else 0.0
|
| 426 |
+
return p, r, f
|
| 427 |
+
|
| 428 |
+
def _loc_block(self, m):
|
| 429 |
+
p50, r50, f50 = self.prf(m, 0.5)
|
| 430 |
+
p75, r75, f75 = self.prf(m, 0.75)
|
| 431 |
+
mf = sum(self.prf(m, t)[2] for t in IOU_THRESHOLDS) / len(IOU_THRESHOLDS)
|
| 432 |
+
return {
|
| 433 |
+
"precision@0.5": round(p50, 4), "recall@0.5": round(r50, 4),
|
| 434 |
+
"f1@0.5": round(f50, 4), "f1@0.75": round(f75, 4),
|
| 435 |
+
"mF1@[.5:.95]": round(mf, 4),
|
| 436 |
+
}
|
| 437 |
+
|
| 438 |
+
def summary(self):
|
| 439 |
+
return {
|
| 440 |
+
"gt_boxes": self.gt_total, "pred_boxes": self.pred_total,
|
| 441 |
+
# localization báo cả 2 matcher: coco (chuẩn, nghiêm) + component (độ phủ)
|
| 442 |
+
"localization": {m: self._loc_block(m) for m in MATCHERS},
|
| 443 |
+
"classification": {
|
| 444 |
+
"label_accuracy_on_matched@0.5":
|
| 445 |
+
round(self.cls_correct / self.cls_matched, 4) if self.cls_matched else None,
|
| 446 |
+
"matched_pairs": self.cls_matched,
|
| 447 |
+
},
|
| 448 |
+
"ocr": {
|
| 449 |
+
"edit_distance_micro":
|
| 450 |
+
round(self.edit_num / self.edit_den, 4) if self.edit_den else None,
|
| 451 |
+
"CER":
|
| 452 |
+
round(self.cer_num / self.cer_den, 4) if self.cer_den else None,
|
| 453 |
+
"WER":
|
| 454 |
+
round(self.wer_num / self.wer_den, 4) if self.wer_den else None,
|
| 455 |
+
"text_pairs": self.ocr_pairs,
|
| 456 |
+
},
|
| 457 |
+
"reading_order": {
|
| 458 |
+
"edit_distance_mean":
|
| 459 |
+
round(sum(self.ro_scores) / len(self.ro_scores), 4) if self.ro_scores else None,
|
| 460 |
+
"pages": len(self.ro_scores),
|
| 461 |
+
},
|
| 462 |
+
}
|
| 463 |
+
|
| 464 |
+
|
| 465 |
+
def score_page(gts, preds, member_thr, mask_math=False) -> dict:
|
| 466 |
+
"""Tính TẤT CẢ contribution của 1 trang MỘT LẦN (edit distance không lặp lại)."""
|
| 467 |
+
# rec (union-gather phía GT) chỉ dùng cho classification / OCR / reading-order.
|
| 468 |
+
rec = match_side(gts, preds, member_thr)
|
| 469 |
+
|
| 470 |
+
ps = {
|
| 471 |
+
"gt_total": len(gts), "pred_total": len(preds),
|
| 472 |
+
# Localization: tính TP theo 2 matcher độc lập (KHÔNG dùng cho OCR/cls/RO).
|
| 473 |
+
"loc": {
|
| 474 |
+
"coco": coco_tp_by_threshold(gts, preds, IOU_THRESHOLDS),
|
| 475 |
+
"component": component_tp_by_threshold(gts, preds, IOU_THRESHOLDS),
|
| 476 |
+
},
|
| 477 |
+
"cls_matched": 0, "cls_correct": 0,
|
| 478 |
+
"edit_num": 0.0, "edit_den": 0.0,
|
| 479 |
+
"cer_num": 0.0, "cer_den": 0.0, "wer_num": 0.0, "wer_den": 0.0,
|
| 480 |
+
"ocr_pairs": 0, "ro": None,
|
| 481 |
+
}
|
| 482 |
+
|
| 483 |
+
matched_pairs = []
|
| 484 |
+
for r in rec:
|
| 485 |
+
if r["union_iou"] < 0.5 or not r["members"]:
|
| 486 |
+
continue
|
| 487 |
+
ps["cls_matched"] += 1
|
| 488 |
+
if r["group_ok"]:
|
| 489 |
+
ps["cls_correct"] += 1
|
| 490 |
+
g = r["anchor"]
|
| 491 |
+
matched_pairs.append((g, union_box([m["box"] for m in r["members"]]),
|
| 492 |
+
min(m["order"] for m in r["members"])))
|
| 493 |
+
if g["group"] in OCR_GROUPS and g["text"]:
|
| 494 |
+
members = sorted(r["members"], key=lambda m: (round(m["box"][1], 3), m["box"][0]))
|
| 495 |
+
pred_text = norm_ocr(" ".join(m["text"] for m in members), mask_math)
|
| 496 |
+
gt_text = norm_ocr(g["text"], mask_math)
|
| 497 |
+
if pred_text or gt_text:
|
| 498 |
+
ps["edit_num"] += _dist(pred_text, gt_text)
|
| 499 |
+
ps["edit_den"] += max(len(pred_text), len(gt_text))
|
| 500 |
+
ps["ocr_pairs"] += 1
|
| 501 |
+
if gt_text: # CER chuẩn hoá theo GT (reference)
|
| 502 |
+
ps["cer_num"] += _dist(pred_text, gt_text)
|
| 503 |
+
ps["cer_den"] += len(gt_text)
|
| 504 |
+
# WER chỉ có nghĩa với ngôn ngữ tách từ bằng dấu cách.
|
| 505 |
+
# CJK (không dấu cách) -> dùng CER, bỏ khỏi WER để tránh nhiễu.
|
| 506 |
+
if " " in gt_text:
|
| 507 |
+
gw, pw = gt_text.split(), pred_text.split()
|
| 508 |
+
ps["wer_num"] += _dist(pw, gw)
|
| 509 |
+
ps["wer_den"] += len(gw)
|
| 510 |
+
|
| 511 |
+
ps["ro"] = read_order_seq(matched_pairs)
|
| 512 |
+
return ps
|
| 513 |
+
|
| 514 |
+
|
| 515 |
+
def evaluate(gt_pages, pred_index, member_thr, drop_ignore, mask_math=False):
|
| 516 |
+
slices = defaultdict(Acc) # key -> Acc ; key "all" luôn có
|
| 517 |
+
|
| 518 |
+
for img_name, pred_page in pred_index.items():
|
| 519 |
+
gt_page = gt_pages.get(img_name)
|
| 520 |
+
if gt_page is None:
|
| 521 |
+
continue
|
| 522 |
+
gts = prep_gt(gt_page, drop_ignore)
|
| 523 |
+
preds = prep_pred(pred_page)
|
| 524 |
+
ps = score_page(gts, preds, member_thr, mask_math) # <-- tính 1 lần
|
| 525 |
+
|
| 526 |
+
keys = ["all"]
|
| 527 |
+
for k in SLICE_KEYS:
|
| 528 |
+
v = gt_page["attr"].get(k)
|
| 529 |
+
if isinstance(v, list):
|
| 530 |
+
keys += [f"{k}={x}" for x in v]
|
| 531 |
+
elif v is not None:
|
| 532 |
+
keys.append(f"{k}={v}")
|
| 533 |
+
|
| 534 |
+
for key in keys: # <-- chỉ cộng số học
|
| 535 |
+
slices[key].add(ps)
|
| 536 |
+
|
| 537 |
+
return slices
|
| 538 |
+
|
| 539 |
+
|
| 540 |
+
# --------------------------------------------------------------------------- #
|
| 541 |
+
def build_pred_index(pred_dir: Path, mapping: dict) -> dict:
|
| 542 |
+
"""image_name -> pred page dict, dựa trên mapping (page_index k -> images[k])."""
|
| 543 |
+
by_stem = {Path(e["pdf"]).stem: e["images"] for e in mapping["pdfs"]}
|
| 544 |
+
index = {}
|
| 545 |
+
missing = 0
|
| 546 |
+
for f in sorted(glob.glob(str(pred_dir / "*.json"))):
|
| 547 |
+
stem = Path(f).stem
|
| 548 |
+
images = by_stem.get(stem)
|
| 549 |
+
if images is None:
|
| 550 |
+
continue
|
| 551 |
+
doc = json.load(open(f, encoding="utf-8"))
|
| 552 |
+
for page in doc["pages"]:
|
| 553 |
+
k = page.get("page_index")
|
| 554 |
+
if k is None or k >= len(images):
|
| 555 |
+
missing += 1
|
| 556 |
+
continue
|
| 557 |
+
index[images[k]] = page
|
| 558 |
+
if missing:
|
| 559 |
+
print(f"[warn] {missing} trang pred không map được về ảnh.")
|
| 560 |
+
return index
|
| 561 |
+
|
| 562 |
+
|
| 563 |
+
def parse_args():
|
| 564 |
+
ap = argparse.ArgumentParser(description=__doc__,
|
| 565 |
+
formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 566 |
+
ap.add_argument("--gt", type=Path, required=True, help="OmniDocBench.json")
|
| 567 |
+
ap.add_argument("--pred", type=Path, required=True, help="Thư mục parser_results/")
|
| 568 |
+
ap.add_argument("--mapping", type=Path, required=True, help="mapping.json")
|
| 569 |
+
ap.add_argument("--out", type=Path, default=None, help="File report JSON.")
|
| 570 |
+
ap.add_argument("--gt-granularity", choices=["merged", "fine"], default="fine",
|
| 571 |
+
help="merged=box top-level (như OmniDocBench); fine=bung merge_list.")
|
| 572 |
+
ap.add_argument("--member-thr", type=float, default=0.5,
|
| 573 |
+
help="Ngưỡng containment để coi 1 box là thành viên (0..1).")
|
| 574 |
+
ap.add_argument("--keep-ignore", action="store_true",
|
| 575 |
+
help="Giữ cả box GT ignore=true (mặc định bỏ).")
|
| 576 |
+
ap.add_argument("--mask-math", action="store_true",
|
| 577 |
+
help="Thay công thức inline bằng 1 token khi đo OCR (đo text thuần).")
|
| 578 |
+
ap.add_argument("--min-slice", type=int, default=30,
|
| 579 |
+
help="Chỉ in lát cắt có >= N trang-box (đỡ nhiễu).")
|
| 580 |
+
return ap.parse_args()
|
| 581 |
+
|
| 582 |
+
|
| 583 |
+
def main() -> int:
|
| 584 |
+
args = parse_args()
|
| 585 |
+
gt_pages = load_gt(args.gt, args.gt_granularity)
|
| 586 |
+
mapping = json.load(open(args.mapping, encoding="utf-8"))
|
| 587 |
+
pred_index = build_pred_index(args.pred, mapping)
|
| 588 |
+
print(f"[eval] GT trang={len(gt_pages)} pred trang map được={len(pred_index)} "
|
| 589 |
+
f"granularity={args.gt_granularity} member_thr={args.member_thr}")
|
| 590 |
+
|
| 591 |
+
slices = evaluate(gt_pages, pred_index, args.member_thr,
|
| 592 |
+
not args.keep_ignore, args.mask_math)
|
| 593 |
+
|
| 594 |
+
report = {
|
| 595 |
+
"config": {
|
| 596 |
+
"gt_granularity": args.gt_granularity, "member_thr": args.member_thr,
|
| 597 |
+
"drop_ignore": not args.keep_ignore, "mask_math": args.mask_math,
|
| 598 |
+
"iou_thresholds": IOU_THRESHOLDS,
|
| 599 |
+
"excluded_groups": sorted(EXCLUDE_GROUPS), "ocr_groups": sorted(OCR_GROUPS),
|
| 600 |
+
},
|
| 601 |
+
"slices": {k: acc.summary() for k, acc in slices.items()},
|
| 602 |
+
}
|
| 603 |
+
if args.out:
|
| 604 |
+
args.out.write_text(json.dumps(report, indent=2, ensure_ascii=False), encoding="utf-8")
|
| 605 |
+
|
| 606 |
+
a = slices["all"].summary()
|
| 607 |
+
print("\n===== TỔNG (all) =====")
|
| 608 |
+
print(f" GT boxes={a['gt_boxes']} pred boxes={a['pred_boxes']}")
|
| 609 |
+
for m in MATCHERS:
|
| 610 |
+
loc = a["localization"][m]
|
| 611 |
+
print(f" LOCALIZATION[{m:9s}] P@.5={loc['precision@0.5']} R@.5={loc['recall@0.5']} "
|
| 612 |
+
f"F1@.5={loc['f1@0.5']} F1@.75={loc['f1@0.75']} mF1={loc['mF1@[.5:.95]']}")
|
| 613 |
+
print(f" CLASSIFY label_acc@.5={a['classification']['label_accuracy_on_matched@0.5']} "
|
| 614 |
+
f"(trên {a['classification']['matched_pairs']} cặp)")
|
| 615 |
+
print(f" OCR edit_dist={a['ocr']['edit_distance_micro']} "
|
| 616 |
+
f"CER={a['ocr']['CER']} WER={a['ocr']['WER']} "
|
| 617 |
+
f"(trên {a['ocr']['text_pairs']} vùng)")
|
| 618 |
+
print(f" READING ORDER edit_dist={a['reading_order']['edit_distance_mean']} "
|
| 619 |
+
f"({a['reading_order']['pages']} trang)")
|
| 620 |
+
|
| 621 |
+
print("\n===== THEO LÁT CẮT (F1@.5 / labelAcc / OCRedit) =====")
|
| 622 |
+
for key in sorted(slices):
|
| 623 |
+
if key == "all":
|
| 624 |
+
continue
|
| 625 |
+
s = slices[key].summary()
|
| 626 |
+
if s["gt_boxes"] < args.min_slice:
|
| 627 |
+
continue
|
| 628 |
+
print(f" {key:28s} F1@.5 coco={s['localization']['coco']['f1@0.5']:.3f} "
|
| 629 |
+
f"comp={s['localization']['component']['f1@0.5']:.3f} "
|
| 630 |
+
f"labelAcc={str(s['classification']['label_accuracy_on_matched@0.5']):>6} "
|
| 631 |
+
f"CER={str(s['ocr']['CER']):>6} (gt={s['gt_boxes']})")
|
| 632 |
+
|
| 633 |
+
if args.out:
|
| 634 |
+
print(f"\n[eval] report -> {args.out}")
|
| 635 |
+
return 0
|
| 636 |
+
|
| 637 |
+
|
| 638 |
+
if __name__ == "__main__":
|
| 639 |
+
raise SystemExit(main())
|
benchmark/parser/evaluation/eval_table.py
ADDED
|
@@ -0,0 +1,248 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Đánh giá BẢNG theo hướng "coi cả bảng là một vùng OCR" (không đo cấu trúc HTML).
|
| 2 |
+
|
| 3 |
+
Lý do: GT OmniDocBench chỉ có ``html`` (không có bbox từng cell) và parser xuất
|
| 4 |
+
``cells`` phẳng (bbox + text, không có hàng/cột). Nên KHÔNG dựng HTML/TEDS; thay
|
| 5 |
+
vào đó nối text các cell theo thứ tự đọc (row-major) rồi so với text bóc từ GT html.
|
| 6 |
+
|
| 7 |
+
* GT text : nối ``text_content`` của từng ``<td>/<th>`` (thứ tự tài liệu = row-major).
|
| 8 |
+
Nếu bảng có nhiều bản html hợp lệ (html/html_2/html_3) -> lấy bản cho
|
| 9 |
+
edit distance THẤP nhất (giống OmniDocBench chấp nhận đa đáp án).
|
| 10 |
+
* pred text: gom cell của các Table phủ bởi GT, cụm thành hàng theo y, sort x,
|
| 11 |
+
nối row-major.
|
| 12 |
+
* Chuẩn hoá bằng norm_ocr (bóc thẻ, hợp nhất inline math ``$..$``/``<math>``).
|
| 13 |
+
|
| 14 |
+
Metric: Edit distance (/max, kiểu OmniDocBench) + CER, coverage, edit_matched /
|
| 15 |
+
edit_all. ĐO NỘI DUNG, KHÔNG đo cấu trúc hàng/cột (hạn chế đã biết).
|
| 16 |
+
|
| 17 |
+
Ví dụ
|
| 18 |
+
-----
|
| 19 |
+
# chạy từ benchmark/parser/
|
| 20 |
+
python evaluation/eval_table.py --gt data/OmniDocBench.json --pred parser_results \
|
| 21 |
+
--mapping parser_results/mapping.json --out eval_results/eval_report_table.json
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
from __future__ import annotations
|
| 25 |
+
|
| 26 |
+
import argparse
|
| 27 |
+
import json
|
| 28 |
+
from collections import defaultdict
|
| 29 |
+
import sys
|
| 30 |
+
from pathlib import Path
|
| 31 |
+
|
| 32 |
+
from lxml import html as LH
|
| 33 |
+
|
| 34 |
+
sys.path.insert(0, str(Path(__file__).resolve().parent)) # import module cạnh bên
|
| 35 |
+
import eval_layout as E
|
| 36 |
+
|
| 37 |
+
SLICE_KEYS = ("language", "layout", "subset", "data_source")
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def html_to_text(html_str: str) -> str:
|
| 41 |
+
"""Nối text từng cell <td>/<th> theo thứ tự tài liệu (row-major)."""
|
| 42 |
+
try:
|
| 43 |
+
tree = LH.fromstring(html_str)
|
| 44 |
+
except Exception:
|
| 45 |
+
return ""
|
| 46 |
+
cells = tree.xpath("//td | //th")
|
| 47 |
+
if cells:
|
| 48 |
+
return " ".join(c.text_content() for c in cells)
|
| 49 |
+
return tree.text_content()
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def cluster_rows(cells: list[dict]) -> list[dict]:
|
| 53 |
+
"""Sắp cell theo thứ tự đọc row-major (cụm hàng theo y, rồi sort x)."""
|
| 54 |
+
if not cells:
|
| 55 |
+
return []
|
| 56 |
+
boxes = [(c, c["bbox_pdf"]) for c in cells]
|
| 57 |
+
boxes.sort(key=lambda cb: (cb[1][1] + cb[1][3]) / 2.0) # theo y-center
|
| 58 |
+
heights = sorted((b[3] - b[1]) for _, b in boxes)
|
| 59 |
+
med_h = heights[len(heights) // 2] or 1.0
|
| 60 |
+
rows, cur, cur_y = [], [], None
|
| 61 |
+
for c, b in boxes:
|
| 62 |
+
yc = (b[1] + b[3]) / 2.0
|
| 63 |
+
if cur_y is None or abs(yc - cur_y) <= med_h * 0.6:
|
| 64 |
+
cur.append((c, b))
|
| 65 |
+
cur_y = yc if cur_y is None else (cur_y + yc) / 2.0
|
| 66 |
+
else:
|
| 67 |
+
rows.append(cur)
|
| 68 |
+
cur, cur_y = [(c, b)], yc
|
| 69 |
+
if cur:
|
| 70 |
+
rows.append(cur)
|
| 71 |
+
ordered = []
|
| 72 |
+
for row in rows:
|
| 73 |
+
row.sort(key=lambda cb: cb[1][0]) # trong hàng: theo x
|
| 74 |
+
ordered.extend(c for c, _ in row)
|
| 75 |
+
return ordered
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def gt_tables(page: dict, drop_ignore: bool) -> list[dict]:
|
| 79 |
+
out = []
|
| 80 |
+
for d in page["dets"]:
|
| 81 |
+
if d.get("category_type") != "table":
|
| 82 |
+
continue
|
| 83 |
+
if drop_ignore and d.get("ignore"):
|
| 84 |
+
continue
|
| 85 |
+
variants = [d[k] for k in ("html", "html_2", "html_3") if d.get(k)]
|
| 86 |
+
out.append({
|
| 87 |
+
"box": E.norm_box(E.poly_to_xyxy(d["poly"]), page["w"], page["h"]),
|
| 88 |
+
"texts": [E.norm_ocr(html_to_text(h)) for h in variants] or [""],
|
| 89 |
+
})
|
| 90 |
+
return out
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def pred_tables(page: dict) -> list[dict]:
|
| 94 |
+
W, H = page.get("page_width"), page.get("page_height")
|
| 95 |
+
out = []
|
| 96 |
+
for e in page["elements"]:
|
| 97 |
+
if e.get("label") != "Table":
|
| 98 |
+
continue
|
| 99 |
+
out.append({
|
| 100 |
+
"box": E.norm_box(e["bbox_pdf"], W, H),
|
| 101 |
+
"cells": [c for c in e.get("cells", []) if c.get("bbox_pdf")],
|
| 102 |
+
})
|
| 103 |
+
return out
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
class Acc:
|
| 107 |
+
def __init__(self):
|
| 108 |
+
self.n_gt = self.n_matched = self.n_pred = self.n_pred_unmatched = 0
|
| 109 |
+
self.num_all = self.den_all = 0.0
|
| 110 |
+
self.num_m = self.den_m = 0.0
|
| 111 |
+
self.cer_num = self.cer_den = 0.0
|
| 112 |
+
|
| 113 |
+
def summary(self):
|
| 114 |
+
return {
|
| 115 |
+
"gt_tables": self.n_gt,
|
| 116 |
+
"coverage": round(self.n_matched / self.n_gt, 4) if self.n_gt else None,
|
| 117 |
+
"pred_tables": self.n_pred, "pred_unmatched": self.n_pred_unmatched,
|
| 118 |
+
"edit_all_micro": round(self.num_all / self.den_all, 4) if self.den_all else None,
|
| 119 |
+
"edit_matched_micro": round(self.num_m / self.den_m, 4) if self.den_m else None,
|
| 120 |
+
"score_matched": round(1 - self.num_m / self.den_m, 4) if self.den_m else None,
|
| 121 |
+
"CER_matched": round(self.cer_num / self.cer_den, 4) if self.cer_den else None,
|
| 122 |
+
}
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def best_pair(pred_text: str, gt_texts: list[str]):
|
| 126 |
+
"""Lấy (dist, maxlen, gtlen) theo bản GT html cho edit distance nhỏ nhất."""
|
| 127 |
+
best = None
|
| 128 |
+
for gt in gt_texts:
|
| 129 |
+
d = E._dist(pred_text, gt)
|
| 130 |
+
if best is None or d < best[0]:
|
| 131 |
+
best = (d, max(len(pred_text), len(gt)), len(gt))
|
| 132 |
+
return best
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def score_page(gts, preds, member_thr):
|
| 136 |
+
used = [False] * len(preds)
|
| 137 |
+
ps = {"n_gt": len(gts), "n_matched": 0, "n_pred": len(preds), "pairs": []}
|
| 138 |
+
for g in gts:
|
| 139 |
+
members, idxs = [], []
|
| 140 |
+
for i, p in enumerate(preds):
|
| 141 |
+
if E.contain_ratio(p["box"], g["box"]) >= member_thr:
|
| 142 |
+
members.append(p)
|
| 143 |
+
idxs.append(i)
|
| 144 |
+
if members:
|
| 145 |
+
for i in idxs:
|
| 146 |
+
used[i] = True
|
| 147 |
+
cells = [c for m in members for c in m["cells"]]
|
| 148 |
+
pred_text = E.norm_ocr(" ".join(
|
| 149 |
+
c.get("source_text", "") for c in cluster_rows(cells)))
|
| 150 |
+
ps["n_matched"] += 1
|
| 151 |
+
matched = True
|
| 152 |
+
else:
|
| 153 |
+
pred_text = ""
|
| 154 |
+
matched = False
|
| 155 |
+
d, mlen, gtlen = best_pair(pred_text, g["texts"])
|
| 156 |
+
if mlen:
|
| 157 |
+
ps["pairs"].append((d, mlen, gtlen, matched))
|
| 158 |
+
ps["n_pred_unmatched"] = sum(1 for u in used if not u)
|
| 159 |
+
return ps
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def evaluate(gt_pages, pred_index, member_thr, drop_ignore):
|
| 163 |
+
slices = defaultdict(Acc)
|
| 164 |
+
for img_name, pred_page in pred_index.items():
|
| 165 |
+
gt_page = gt_pages.get(img_name)
|
| 166 |
+
if gt_page is None:
|
| 167 |
+
continue
|
| 168 |
+
gts = gt_tables(gt_page, drop_ignore)
|
| 169 |
+
preds = pred_tables(pred_page)
|
| 170 |
+
if not gts and not preds:
|
| 171 |
+
continue
|
| 172 |
+
ps = score_page(gts, preds, member_thr)
|
| 173 |
+
keys = ["all"]
|
| 174 |
+
for k in SLICE_KEYS:
|
| 175 |
+
v = gt_page["attr"].get(k)
|
| 176 |
+
if isinstance(v, list):
|
| 177 |
+
keys += [f"{k}={x}" for x in v]
|
| 178 |
+
elif v is not None:
|
| 179 |
+
keys.append(f"{k}={v}")
|
| 180 |
+
for key in keys:
|
| 181 |
+
a = slices[key]
|
| 182 |
+
a.n_gt += ps["n_gt"]
|
| 183 |
+
a.n_matched += ps["n_matched"]
|
| 184 |
+
a.n_pred += ps["n_pred"]
|
| 185 |
+
a.n_pred_unmatched += ps["n_pred_unmatched"]
|
| 186 |
+
for d, mlen, gtlen, matched in ps["pairs"]:
|
| 187 |
+
a.num_all += d
|
| 188 |
+
a.den_all += mlen
|
| 189 |
+
if matched:
|
| 190 |
+
a.num_m += d
|
| 191 |
+
a.den_m += mlen
|
| 192 |
+
a.cer_num += d
|
| 193 |
+
a.cer_den += gtlen
|
| 194 |
+
return slices
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
def parse_args():
|
| 198 |
+
ap = argparse.ArgumentParser(description=__doc__,
|
| 199 |
+
formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 200 |
+
ap.add_argument("--gt", type=Path, required=True)
|
| 201 |
+
ap.add_argument("--pred", type=Path, required=True)
|
| 202 |
+
ap.add_argument("--mapping", type=Path, required=True)
|
| 203 |
+
ap.add_argument("--out", type=Path, default=None)
|
| 204 |
+
ap.add_argument("--member-thr", type=float, default=0.5)
|
| 205 |
+
ap.add_argument("--keep-ignore", action="store_true")
|
| 206 |
+
ap.add_argument("--min-slice", type=int, default=10)
|
| 207 |
+
return ap.parse_args()
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def main() -> int:
|
| 211 |
+
args = parse_args()
|
| 212 |
+
gt_pages = E.load_gt(args.gt, "merged")
|
| 213 |
+
mapping = json.load(open(args.mapping, encoding="utf-8"))
|
| 214 |
+
pred_index = E.build_pred_index(args.pred, mapping)
|
| 215 |
+
print(f"[table] GT trang={len(gt_pages)} pred trang={len(pred_index)} "
|
| 216 |
+
f"member_thr={args.member_thr}")
|
| 217 |
+
|
| 218 |
+
slices = evaluate(gt_pages, pred_index, args.member_thr, not args.keep_ignore)
|
| 219 |
+
report = {"config": {"member_thr": args.member_thr, "note": "OCR-only, no structure"},
|
| 220 |
+
"slices": {k: a.summary() for k, a in slices.items()}}
|
| 221 |
+
if args.out:
|
| 222 |
+
args.out.write_text(json.dumps(report, indent=2, ensure_ascii=False), encoding="utf-8")
|
| 223 |
+
|
| 224 |
+
a = slices["all"].summary()
|
| 225 |
+
print("\n===== TABLE (all) — đo NỘI DUNG, không đo cấu trúc =====")
|
| 226 |
+
print(f" GT bảng = {a['gt_tables']} coverage = {a['coverage']}")
|
| 227 |
+
print(f" pred Table = {a['pred_tables']} không khớp = {a['pred_unmatched']}")
|
| 228 |
+
print(f" edit_matched micro = {a['edit_matched_micro']} -> score = {a['score_matched']}")
|
| 229 |
+
print(f" CER_matched = {a['CER_matched']}")
|
| 230 |
+
print(f" edit_all micro = {a['edit_all_micro']} (gồm cả sót detect)")
|
| 231 |
+
|
| 232 |
+
print("\n===== THEO LÁT CẮT (coverage / edit_matched / CER) =====")
|
| 233 |
+
for key in sorted(slices):
|
| 234 |
+
if key == "all":
|
| 235 |
+
continue
|
| 236 |
+
s = slices[key].summary()
|
| 237 |
+
if s["gt_tables"] < args.min_slice:
|
| 238 |
+
continue
|
| 239 |
+
print(f" {key:28s} cov={str(s['coverage']):>6} "
|
| 240 |
+
f"editM={str(s['edit_matched_micro']):>6} "
|
| 241 |
+
f"CER={str(s['CER_matched']):>6} (gt={s['gt_tables']})")
|
| 242 |
+
if args.out:
|
| 243 |
+
print(f"\n[table] report -> {args.out}")
|
| 244 |
+
return 0
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
if __name__ == "__main__":
|
| 248 |
+
raise SystemExit(main())
|
benchmark/parser/evaluation/requirements-eval.txt
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Thư viện cho các script đánh giá parser-vs-GT (eval_layout.py + formula/table).
|
| 2 |
+
# Chỉ dùng để CHẤM ĐIỂM, tách khỏi requirements.txt chạy parser.
|
| 3 |
+
|
| 4 |
+
# Edit distance nhanh (khớp đúng metric OmniDocBench: Levenshtein.distance).
|
| 5 |
+
python-Levenshtein>=0.21
|
| 6 |
+
|
| 7 |
+
# TEDS cho bảng — tái dùng OmniDocBench/src/metrics/table_metric.py:
|
| 8 |
+
apted>=1.0.3 # tree edit distance
|
| 9 |
+
lxml>=4.9 # parse HTML bảng
|
| 10 |
+
tqdm>=4.66 # progress bar (table_metric import)
|
| 11 |
+
|
| 12 |
+
# Tiện phân tích / xuất bảng số (tùy chọn, để gom kết quả ra CSV).
|
| 13 |
+
pandas>=2.0
|
| 14 |
+
|
| 15 |
+
# CDM cho công thức (eval_formula_cdm.py). NGOÀI RA cần dependency HỆ THỐNG:
|
| 16 |
+
# apt install texlive-latex-base texlive-latex-extra texlive-fonts-recommended imagemagick
|
| 17 |
+
numpy>=1.24
|
| 18 |
+
Pillow>=10.0
|
| 19 |
+
scipy>=1.10
|
| 20 |
+
# BẮT BUỘC cho CDM: thiếu pylatexenc thì tokenizer LaTeX trả rỗng -> CDM fallback
|
| 21 |
+
# cắt theo dấu cách -> điểm sai bét (F1 giả ~0). Có nó thì CDM bất biến với spacing.
|
| 22 |
+
pylatexenc>=2.10
|
benchmark/parser/run_parser/build_pdfs.py
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Group OmniDocBench page images into multi-page PDFs (default 32 images/PDF).
|
| 2 |
+
|
| 3 |
+
Why: we want to benchmark the *real* ``StageAParser.parse_pdf`` path. parse_pdf
|
| 4 |
+
takes a PDF, so we pack the individual page images into PDFs — each image
|
| 5 |
+
becomes one page, at native resolution (PyMuPDF embeds it, no re-encode).
|
| 6 |
+
|
| 7 |
+
A ``mapping.json`` records exactly which image landed on which page of which
|
| 8 |
+
PDF, so the per-PDF parser output can be split back to per-image results after
|
| 9 |
+
the run.
|
| 10 |
+
|
| 11 |
+
Output layout::
|
| 12 |
+
|
| 13 |
+
<out>/
|
| 14 |
+
batch_00000.pdf # 32 pages = 32 images
|
| 15 |
+
batch_00001.pdf
|
| 16 |
+
...
|
| 17 |
+
mapping.json
|
| 18 |
+
|
| 19 |
+
``mapping.json``::
|
| 20 |
+
|
| 21 |
+
{
|
| 22 |
+
"per_pdf": 32,
|
| 23 |
+
"num_images": 1651,
|
| 24 |
+
"num_pdfs": 52,
|
| 25 |
+
"pdfs": [
|
| 26 |
+
{"pdf": "batch_00000.pdf", "images": ["imgA.jpg", "imgB.jpg", ...]},
|
| 27 |
+
...
|
| 28 |
+
]
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
Page index (0-based) of an image == its position in that PDF's ``images`` list.
|
| 32 |
+
|
| 33 |
+
Example
|
| 34 |
+
-------
|
| 35 |
+
# chạy từ benchmark/parser/
|
| 36 |
+
python run_parser/build_pdfs.py \
|
| 37 |
+
--images data/images \
|
| 38 |
+
--out data/pdfs \
|
| 39 |
+
--per-pdf 32
|
| 40 |
+
"""
|
| 41 |
+
|
| 42 |
+
from __future__ import annotations
|
| 43 |
+
|
| 44 |
+
import argparse
|
| 45 |
+
import json
|
| 46 |
+
from pathlib import Path
|
| 47 |
+
|
| 48 |
+
IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".bmp", ".tif", ".tiff", ".webp"}
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def parse_args() -> argparse.Namespace:
|
| 52 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 53 |
+
parser.add_argument("--images", required=True, type=Path,
|
| 54 |
+
help="Folder of page images (one image per page).")
|
| 55 |
+
parser.add_argument("--out", required=True, type=Path,
|
| 56 |
+
help="Output folder for the batched PDFs + mapping.json.")
|
| 57 |
+
parser.add_argument("--per-pdf", type=int, default=32,
|
| 58 |
+
help="Number of images packed into each PDF (default 32).")
|
| 59 |
+
parser.add_argument("--limit", type=int, default=None,
|
| 60 |
+
help="Only use the first N images (quick test).")
|
| 61 |
+
return parser.parse_args()
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def find_images(images_dir: Path) -> list[Path]:
|
| 65 |
+
if not images_dir.is_dir():
|
| 66 |
+
raise NotADirectoryError(f"--images is not a folder: {images_dir}")
|
| 67 |
+
files = [p for p in sorted(images_dir.iterdir())
|
| 68 |
+
if p.is_file() and p.suffix.lower() in IMAGE_EXTENSIONS]
|
| 69 |
+
if not files:
|
| 70 |
+
raise FileNotFoundError(f"No image files found in {images_dir}")
|
| 71 |
+
return files
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def image_to_pdf_pages(doc, image_path: Path) -> bool:
|
| 75 |
+
"""Append the image as one page to ``doc``. Returns True on success."""
|
| 76 |
+
import fitz # PyMuPDF
|
| 77 |
+
|
| 78 |
+
try:
|
| 79 |
+
with fitz.open(image_path) as img_doc:
|
| 80 |
+
pdf_bytes = img_doc.convert_to_pdf()
|
| 81 |
+
with fitz.open("pdf", pdf_bytes) as img_pdf:
|
| 82 |
+
doc.insert_pdf(img_pdf)
|
| 83 |
+
return True
|
| 84 |
+
except Exception as exc:
|
| 85 |
+
print(f" [skip] {image_path.name}: {exc!r}", flush=True)
|
| 86 |
+
return False
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def main() -> int:
|
| 90 |
+
args = parse_args()
|
| 91 |
+
|
| 92 |
+
import fitz # PyMuPDF
|
| 93 |
+
|
| 94 |
+
images = find_images(args.images)
|
| 95 |
+
if args.limit is not None:
|
| 96 |
+
images = images[: args.limit]
|
| 97 |
+
|
| 98 |
+
args.out.mkdir(parents=True, exist_ok=True)
|
| 99 |
+
|
| 100 |
+
per_pdf = max(1, args.per_pdf)
|
| 101 |
+
num_pdfs = (len(images) + per_pdf - 1) // per_pdf
|
| 102 |
+
width = max(5, len(str(num_pdfs - 1)))
|
| 103 |
+
|
| 104 |
+
print(f"[build_pdfs] {len(images)} images -> {num_pdfs} PDFs "
|
| 105 |
+
f"({per_pdf} images/PDF) in {args.out}", flush=True)
|
| 106 |
+
|
| 107 |
+
pdf_entries: list[dict] = []
|
| 108 |
+
for pdf_idx in range(num_pdfs):
|
| 109 |
+
chunk = images[pdf_idx * per_pdf: (pdf_idx + 1) * per_pdf]
|
| 110 |
+
pdf_name = f"batch_{pdf_idx:0{width}d}.pdf"
|
| 111 |
+
out_pdf = args.out / pdf_name
|
| 112 |
+
|
| 113 |
+
doc = fitz.open()
|
| 114 |
+
used_images: list[str] = []
|
| 115 |
+
try:
|
| 116 |
+
for image_path in chunk:
|
| 117 |
+
if image_to_pdf_pages(doc, image_path):
|
| 118 |
+
used_images.append(image_path.name)
|
| 119 |
+
if len(doc) == 0:
|
| 120 |
+
print(f" [warn] {pdf_name}: no valid pages, skipped", flush=True)
|
| 121 |
+
continue
|
| 122 |
+
doc.save(out_pdf)
|
| 123 |
+
finally:
|
| 124 |
+
doc.close()
|
| 125 |
+
|
| 126 |
+
pdf_entries.append({"pdf": pdf_name, "images": used_images})
|
| 127 |
+
print(f" [{pdf_idx + 1}/{num_pdfs}] {pdf_name} {len(used_images)} pages",
|
| 128 |
+
flush=True)
|
| 129 |
+
|
| 130 |
+
mapping = {
|
| 131 |
+
"per_pdf": per_pdf,
|
| 132 |
+
"num_images": sum(len(e["images"]) for e in pdf_entries),
|
| 133 |
+
"num_pdfs": len(pdf_entries),
|
| 134 |
+
"pdfs": pdf_entries,
|
| 135 |
+
}
|
| 136 |
+
mapping_path = args.out / "mapping.json"
|
| 137 |
+
mapping_path.write_text(json.dumps(mapping, indent=2, ensure_ascii=False),
|
| 138 |
+
encoding="utf-8")
|
| 139 |
+
|
| 140 |
+
print(f"\n[build_pdfs] done. {mapping['num_pdfs']} PDFs, "
|
| 141 |
+
f"{mapping['num_images']} pages total.", flush=True)
|
| 142 |
+
print(f" mapping: {mapping_path}", flush=True)
|
| 143 |
+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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Benchmark ``StageAParser.parse_pdf`` over the batched OmniDocBench PDFs.
|
| 2 |
+
|
| 3 |
+
Workflow (see build_pdfs.py first):
|
| 4 |
+
images -> batched PDFs (32 pages each) -> THIS script -> per-PDF JSON + timing.
|
| 5 |
+
|
| 6 |
+
To measure parse time accurately, all three models (layout / OCR / table) are
|
| 7 |
+
loaded into VRAM *before* the timed loop, and an optional warmup parse is run
|
| 8 |
+
on the first PDF (discarded) so CUDA kernel autotuning does not pollute the
|
| 9 |
+
first real measurement.
|
| 10 |
+
|
| 11 |
+
For each PDF we call ``parse_pdf`` and save the ``ParsedDocument`` as
|
| 12 |
+
``<pdf_stem>.json``; split back to per-image results later using the
|
| 13 |
+
``mapping.json`` produced by build_pdfs.py.
|
| 14 |
+
|
| 15 |
+
Example
|
| 16 |
+
-------
|
| 17 |
+
# chạy từ benchmark/parser/ (cần GPU)
|
| 18 |
+
python run_parser/run_parser.py \
|
| 19 |
+
--pdfs data/pdfs \
|
| 20 |
+
--out parser_results \
|
| 21 |
+
--timing eval_results/parser_timing.json \
|
| 22 |
+
--device cuda
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
from __future__ import annotations
|
| 26 |
+
|
| 27 |
+
import argparse
|
| 28 |
+
import json
|
| 29 |
+
import sys
|
| 30 |
+
import time
|
| 31 |
+
from pathlib import Path
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def parse_args() -> argparse.Namespace:
|
| 35 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 36 |
+
parser.add_argument("--pdfs", required=True, type=Path,
|
| 37 |
+
help="Folder of batched PDFs (from build_pdfs.py).")
|
| 38 |
+
parser.add_argument("--out", required=True, type=Path,
|
| 39 |
+
help="Output folder for per-PDF ParsedDocument JSON.")
|
| 40 |
+
parser.add_argument("--timing", type=Path, default=None,
|
| 41 |
+
help="JSON timing report path (default: <out>/_timing.json).")
|
| 42 |
+
parser.add_argument("--pdftranslator", type=Path, default=None,
|
| 43 |
+
help="PDFTranslator repo root (default: sibling ../PDFTranslator).")
|
| 44 |
+
parser.add_argument("--device", default="auto",
|
| 45 |
+
help="Torch device for StageAParser (auto|cuda|cpu).")
|
| 46 |
+
# Batch size + ngưỡng detector (điều chỉnh theo VRAM; mặc định hợp cho A100).
|
| 47 |
+
parser.add_argument("--page-batch-size", type=int, default=32)
|
| 48 |
+
parser.add_argument("--layout-batch-size", type=int, default=32)
|
| 49 |
+
parser.add_argument("--detection-batch-size", type=int, default=32)
|
| 50 |
+
parser.add_argument("--ocr-batch-size", type=int, default=512)
|
| 51 |
+
parser.add_argument("--table-batch-size", type=int, default=512)
|
| 52 |
+
parser.add_argument("--blank-threshold", type=float, default=0.5,
|
| 53 |
+
help="detector_blank_threshold cho Surya OCR.")
|
| 54 |
+
parser.add_argument("--text-threshold", type=float, default=0.6,
|
| 55 |
+
help="detector_text_threshold cho Surya OCR.")
|
| 56 |
+
parser.add_argument("--limit", type=int, default=None,
|
| 57 |
+
help="Only process the first N PDFs (quick test).")
|
| 58 |
+
parser.add_argument("--overwrite", action="store_true",
|
| 59 |
+
help="Re-run PDFs whose JSON already exists (default: skip/resume).")
|
| 60 |
+
parser.add_argument("--no-warmup", dest="warmup", action="store_false",
|
| 61 |
+
help="Skip the warmup parse of the first PDF.")
|
| 62 |
+
return parser.parse_args()
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def resolve_pdftranslator(arg: Path | None) -> Path:
|
| 66 |
+
if arg is not None:
|
| 67 |
+
if (arg / "pdf2zh").is_dir():
|
| 68 |
+
return arg.resolve()
|
| 69 |
+
raise FileNotFoundError(f"pdf2zh not found under --pdftranslator {arg}")
|
| 70 |
+
# Walk up from this file until we find the PDFTranslator repo root (has pdf2zh).
|
| 71 |
+
for parent in Path(__file__).resolve().parents:
|
| 72 |
+
if (parent / "pdf2zh").is_dir():
|
| 73 |
+
return parent
|
| 74 |
+
raise FileNotFoundError(
|
| 75 |
+
"Cannot locate the PDFTranslator repo root (no pdf2zh/ found above "
|
| 76 |
+
f"{__file__}). Pass --pdftranslator explicitly."
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def preload_models(parser) -> float:
|
| 81 |
+
"""Load all model weights into VRAM. Returns seconds spent."""
|
| 82 |
+
start = time.perf_counter()
|
| 83 |
+
for name in ("layout_model", "ocr_model", "table_model"):
|
| 84 |
+
model = getattr(parser, name, None)
|
| 85 |
+
if model is not None and getattr(model, "model", None) is None:
|
| 86 |
+
print(f"[run_parser] loading {name} ...", flush=True)
|
| 87 |
+
model.load_model()
|
| 88 |
+
return time.perf_counter() - start
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def main() -> int:
|
| 92 |
+
args = parse_args()
|
| 93 |
+
|
| 94 |
+
pdftranslator = resolve_pdftranslator(args.pdftranslator)
|
| 95 |
+
sys.path.insert(0, str(pdftranslator))
|
| 96 |
+
|
| 97 |
+
from pdf2zh.parser.main import StageAParser
|
| 98 |
+
|
| 99 |
+
pdfs = sorted(p for p in args.pdfs.glob("*.pdf"))
|
| 100 |
+
if not pdfs:
|
| 101 |
+
raise FileNotFoundError(f"No .pdf files found in {args.pdfs}")
|
| 102 |
+
if args.limit is not None:
|
| 103 |
+
pdfs = pdfs[: args.limit]
|
| 104 |
+
|
| 105 |
+
args.out.mkdir(parents=True, exist_ok=True)
|
| 106 |
+
timing_path = args.timing or (args.out / "_timing.json")
|
| 107 |
+
|
| 108 |
+
print(f"[run_parser] {len(pdfs)} PDFs from {args.pdfs}", flush=True)
|
| 109 |
+
print(f"[run_parser] device={args.device} out={args.out}", flush=True)
|
| 110 |
+
|
| 111 |
+
# 1) Construct parser (declares models, no weights yet — lazy loading).
|
| 112 |
+
init_start = time.perf_counter()
|
| 113 |
+
parser = StageAParser(
|
| 114 |
+
device=args.device,
|
| 115 |
+
page_batch_size=args.page_batch_size,
|
| 116 |
+
layout_batch_size=args.layout_batch_size,
|
| 117 |
+
detection_batch_size=args.detection_batch_size,
|
| 118 |
+
ocr_batch_size=args.ocr_batch_size,
|
| 119 |
+
table_batch_size=args.table_batch_size,
|
| 120 |
+
detector_blank_threshold=args.blank_threshold,
|
| 121 |
+
detector_text_threshold=args.text_threshold,
|
| 122 |
+
)
|
| 123 |
+
init_seconds = time.perf_counter() - init_start
|
| 124 |
+
|
| 125 |
+
# 2) Preload ALL model weights before timing anything.
|
| 126 |
+
model_load_seconds = preload_models(parser)
|
| 127 |
+
print(f"[run_parser] parser init: {init_seconds:.1f}s "
|
| 128 |
+
f"model load: {model_load_seconds:.1f}s", flush=True)
|
| 129 |
+
|
| 130 |
+
# 3) Warmup parse (discarded) so CUDA autotune doesn't skew the first PDF.
|
| 131 |
+
warmup_seconds = None
|
| 132 |
+
if args.warmup and pdfs:
|
| 133 |
+
w_start = time.perf_counter()
|
| 134 |
+
try:
|
| 135 |
+
parser.parse_pdf(str(pdfs[0]))
|
| 136 |
+
warmup_seconds = time.perf_counter() - w_start
|
| 137 |
+
print(f"[run_parser] warmup parse: {warmup_seconds:.2f}s (discarded)",
|
| 138 |
+
flush=True)
|
| 139 |
+
except Exception as exc:
|
| 140 |
+
print(f"[run_parser] warmup failed (ignored): {exc!r}", flush=True)
|
| 141 |
+
|
| 142 |
+
# 4) Timed loop over all PDFs.
|
| 143 |
+
per_pdf: list[dict] = []
|
| 144 |
+
processed = skipped = failed = 0
|
| 145 |
+
total_parse_seconds = 0.0
|
| 146 |
+
total_pages = 0
|
| 147 |
+
|
| 148 |
+
for idx, pdf_path in enumerate(pdfs, start=1):
|
| 149 |
+
out_path = args.out / f"{pdf_path.stem}.json"
|
| 150 |
+
if out_path.exists() and not args.overwrite:
|
| 151 |
+
skipped += 1
|
| 152 |
+
continue
|
| 153 |
+
|
| 154 |
+
record: dict = {"pdf": pdf_path.name, "index": idx}
|
| 155 |
+
start = time.perf_counter()
|
| 156 |
+
try:
|
| 157 |
+
doc = parser.parse_pdf(str(pdf_path))
|
| 158 |
+
elapsed = time.perf_counter() - start
|
| 159 |
+
doc.save(out_path)
|
| 160 |
+
|
| 161 |
+
num_pages = len(doc.pages)
|
| 162 |
+
num_elements = sum(len(p.elements) for p in doc.pages)
|
| 163 |
+
record.update(
|
| 164 |
+
seconds=round(elapsed, 4),
|
| 165 |
+
num_pages=num_pages,
|
| 166 |
+
num_elements=num_elements,
|
| 167 |
+
seconds_per_page=round(elapsed / num_pages, 4) if num_pages else None,
|
| 168 |
+
ok=True,
|
| 169 |
+
)
|
| 170 |
+
total_parse_seconds += elapsed
|
| 171 |
+
total_pages += num_pages
|
| 172 |
+
processed += 1
|
| 173 |
+
print(f"[{idx}/{len(pdfs)}] {pdf_path.name} {elapsed:.2f}s "
|
| 174 |
+
f"pages={num_pages} elements={num_elements}", flush=True)
|
| 175 |
+
except Exception as exc:
|
| 176 |
+
elapsed = time.perf_counter() - start
|
| 177 |
+
record.update(seconds=round(elapsed, 4), ok=False, error=repr(exc))
|
| 178 |
+
failed += 1
|
| 179 |
+
print(f"[{idx}/{len(pdfs)}] {pdf_path.name} FAILED: {exc!r}", flush=True)
|
| 180 |
+
|
| 181 |
+
per_pdf.append(record)
|
| 182 |
+
|
| 183 |
+
report = {
|
| 184 |
+
"device": args.device,
|
| 185 |
+
"pdfs_dir": str(args.pdfs),
|
| 186 |
+
"out_dir": str(args.out),
|
| 187 |
+
"num_pdfs_total": len(pdfs),
|
| 188 |
+
"num_processed": processed,
|
| 189 |
+
"num_skipped_existing": skipped,
|
| 190 |
+
"num_failed": failed,
|
| 191 |
+
"parser_init_seconds": round(init_seconds, 4),
|
| 192 |
+
"model_load_seconds": round(model_load_seconds, 4),
|
| 193 |
+
"warmup_seconds": round(warmup_seconds, 4) if warmup_seconds is not None else None,
|
| 194 |
+
"total_parse_seconds": round(total_parse_seconds, 4),
|
| 195 |
+
"total_pages": total_pages,
|
| 196 |
+
"avg_seconds_per_pdf": round(total_parse_seconds / processed, 4) if processed else None,
|
| 197 |
+
"avg_seconds_per_page": round(total_parse_seconds / total_pages, 4) if total_pages else None,
|
| 198 |
+
"per_pdf": per_pdf,
|
| 199 |
+
}
|
| 200 |
+
timing_path.write_text(json.dumps(report, indent=2, ensure_ascii=False), encoding="utf-8")
|
| 201 |
+
|
| 202 |
+
print("\n[run_parser] done.", flush=True)
|
| 203 |
+
print(f" processed={processed} skipped={skipped} failed={failed}", flush=True)
|
| 204 |
+
print(f" model load : {model_load_seconds:.1f}s", flush=True)
|
| 205 |
+
print(f" total parse: {total_parse_seconds:.1f}s over {total_pages} pages", flush=True)
|
| 206 |
+
if report["avg_seconds_per_page"] is not None:
|
| 207 |
+
print(f" avg/page : {report['avg_seconds_per_page']:.3f}s", flush=True)
|
| 208 |
+
print(f" timing : {timing_path}", flush=True)
|
| 209 |
+
|
| 210 |
+
return 1 if (processed == 0 and skipped == 0) else 0
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
if __name__ == "__main__":
|
| 214 |
+
raise SystemExit(main())
|
benchmark/translation/.gitignore
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.cache_wmt24pp/
|
| 2 |
+
out/
|
| 3 |
+
*.jsonl
|
| 4 |
+
!.gitkeep
|
benchmark/translation/README.md
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Harness đánh giá Phase-2 (dịch) — hướng dẫn chạy
|
| 2 |
+
|
| 3 |
+
Đánh giá **đúng core dịch** (`translate_document`) trên WMT24++ mà **không sửa** một dòng nào
|
| 4 |
+
trong `pdf2zh/translation/`. Thiết kế đầy đủ: [../../docs/EVALUATION_PLAN.md](../../docs/EVALUATION_PLAN.md).
|
| 5 |
+
|
| 6 |
+
```
|
| 7 |
+
wmt24pp_adapter.py WMT24++ jsonl -> doc dict + alignment (55 cặp)
|
| 8 |
+
instrument.py httpx hook read-only: latency + token/request
|
| 9 |
+
run_translate.py Bước A: dịch + đo latency -> hypotheses.jsonl, latency.jsonl
|
| 10 |
+
score_comet.py Bước B: COMET-DA + chrF++ (local CPU/MPS) -> comet_scores.json
|
| 11 |
+
aggregate.py gộp -> report.md (bảng §10)
|
| 12 |
+
```
|
| 13 |
+
|
| 14 |
+
## 0. Chuẩn bị
|
| 15 |
+
|
| 16 |
+
Đặt key/base_url vào file **`.env` ở gốc repo** (harness tự `load_dotenv()`, khỏi cần `export`):
|
| 17 |
+
|
| 18 |
+
```dotenv
|
| 19 |
+
# .env (gốc repo)
|
| 20 |
+
GEMINI_API_KEY=...
|
| 21 |
+
ANTHROPIC_API_KEY=...
|
| 22 |
+
# provider litellm:
|
| 23 |
+
LITELLM_API_KEY=sk-local
|
| 24 |
+
LITELLM_BASE_URL=http://localhost:4000/v1
|
| 25 |
+
```
|
| 26 |
+
(Bước dịch chỉ cần httpx — đã có sẵn trong pdf2zh; `datasets` là tùy chọn.)
|
| 27 |
+
|
| 28 |
+
# Bước chấm COMET cần torch + unbabel-comet (ƯA Python 3.10–3.12).
|
| 29 |
+
# Nếu env chính là 3.13 → tạo venv riêng CHỈ cho chấm điểm:
|
| 30 |
+
python3.11 -m venv .venv-score && source .venv-score/bin/activate
|
| 31 |
+
pip install -r benchmark/translation/requirements.txt
|
| 32 |
+
deactivate
|
| 33 |
+
```
|
| 34 |
+
|
| 35 |
+
> Chạy mọi lệnh từ **thư mục gốc repo**. COMET-DA tải model công khai (~2.3GB) lần đầu.
|
| 36 |
+
|
| 37 |
+
---
|
| 38 |
+
|
| 39 |
+
## TEST TRƯỚC (1 doc) — làm đủ 2 bước này trước khi chạy full
|
| 40 |
+
|
| 41 |
+
### T1. Dịch thử 1 document (kiểm tra key + luồng + alignment)
|
| 42 |
+
```bash
|
| 43 |
+
python -m benchmark.translation.run_translate --pair vi_VN --provider gemini --limit-docs 1 --repeats 1
|
| 44 |
+
```
|
| 45 |
+
Xem `benchmark/translation/out/hypotheses.jsonl` (source/hypothesis/reference thẳng hàng,
|
| 46 |
+
`is_fallback`) và `benchmark/translation/out/latency.jsonl` (wall_s, n_req, n_retry, tok_out).
|
| 47 |
+
Nếu `is_fallback` nhiều → key/model lỗi hoặc rate-limit.
|
| 48 |
+
|
| 49 |
+
### T2. Chấm thử COMET trên đúng 1 doc đó
|
| 50 |
+
```bash
|
| 51 |
+
# trong .venv-score nếu tách env:
|
| 52 |
+
python -m benchmark.translation.score_comet \
|
| 53 |
+
--hyp benchmark/translation/out/hypotheses.jsonl --out benchmark/translation/out/comet_test.json
|
| 54 |
+
```
|
| 55 |
+
Ra điểm COMET-DA + chrF++. Nếu chạy được → sẵn sàng full.
|
| 56 |
+
|
| 57 |
+
> Reset trước khi chạy full: `rm -f benchmark/translation/out/*.jsonl` (run_translate **append**).
|
| 58 |
+
|
| 59 |
+
---
|
| 60 |
+
|
| 61 |
+
## CHẠY FULL
|
| 62 |
+
|
| 63 |
+
### Tier A — quét đa ngôn ngữ (55 cặp, 1–2 hệ) — dữ liệu chính RQ1
|
| 64 |
+
Chỉ cần **hypotheses** → chạy **quality-gen** (song song cho nhanh; latency KHÔNG faithful):
|
| 65 |
+
```bash
|
| 66 |
+
for L in vi_VN de_DE zh_CN ja_JP ru_RU es_MX fr_FR hi_IN ar_SA ...; do # đủ 55 locale
|
| 67 |
+
python -m benchmark.translation.run_translate --pair $L --provider gemini \
|
| 68 |
+
--repeats 1 --doc-workers 6
|
| 69 |
+
done
|
| 70 |
+
```
|
| 71 |
+
|
| 72 |
+
### Tier B — so sánh hệ (3–5 provider × ~9 cặp đại diện, có vi_VN)
|
| 73 |
+
Cần **latency trung thực** → chạy **latency-measure** (tuần tự, concurrency=8, N≥5):
|
| 74 |
+
```bash
|
| 75 |
+
for P in "gemini:" "openai:" "deepseek:" "anthropic:claude-haiku-4-5"; do
|
| 76 |
+
prov=${P%%:*}; model=${P#*:}
|
| 77 |
+
for L in vi_VN de_DE zh_CN ja_JP hi_IN ru_RU fr_FR ar_SA th_TH; do
|
| 78 |
+
python -m benchmark.translation.run_translate --pair $L --provider $prov \
|
| 79 |
+
${model:+--model $model} --repeats 5 # doc-workers=1 mặc định
|
| 80 |
+
done
|
| 81 |
+
done
|
| 82 |
+
```
|
| 83 |
+
|
| 84 |
+
### Chấm điểm + gộp báo cáo
|
| 85 |
+
```bash
|
| 86 |
+
python -m benchmark.translation.score_comet --hyp benchmark/translation/out/hypotheses.jsonl \
|
| 87 |
+
--out benchmark/translation/out/comet_scores.json
|
| 88 |
+
python -m benchmark.translation.aggregate --out-dir benchmark/translation/out # -> report.md
|
| 89 |
+
```
|
| 90 |
+
|
| 91 |
+
---
|
| 92 |
+
|
| 93 |
+
## Lưu ý quan trọng
|
| 94 |
+
|
| 95 |
+
- **quality-gen (`--doc-workers>1`) vs latency-measure (mặc định):** số `s/doc` chỉ trung thực ở
|
| 96 |
+
latency-measure. `aggregate.py` chỉ lấy bản ghi `mode="latency-measure"` cho bảng latency.
|
| 97 |
+
- **Nút thắt = rate-limit provider**, không phải Mac. Free tier → nhiều 429 (`n_retry` cao) →
|
| 98 |
+
chậm. Dùng key trả phí cho lượt 55 cặp. Ước lượng thời gian: [§6.2 của plan](../../docs/EVALUATION_PLAN.md).
|
| 99 |
+
- **RAM 16GB:** dùng `wmt22-comet-da` (mặc định), **không** XCOMET. `--gpus 0` (CPU) an toàn;
|
| 100 |
+
thử MPS thủ công nếu muốn nhanh hơn.
|
| 101 |
+
- **Bất biến:** sau cùng `git diff pdf2zh/translation/` phải **rỗng** — harness chỉ đọc & gọi.
|
| 102 |
+
- `run_translate.py` **append** vào jsonl → xóa `benchmark/translation/out/*.jsonl` khi muốn chạy lại từ đầu.
|
benchmark/translation/__init__.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Evaluation harness for the Phase-2 translation core.
|
| 2 |
+
|
| 3 |
+
Everything here lives OUTSIDE pdf2zh/translation and only *calls into* the public
|
| 4 |
+
entrypoint (translate_document) + observes it (timers, read-only httpx hooks). See
|
| 5 |
+
docs/EVALUATION_PLAN.md. The translation core is never modified.
|
| 6 |
+
"""
|
benchmark/translation/aggregate.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Gộp latency + COMET -> bảng markdown cho báo cáo (§10).
|
| 2 |
+
|
| 3 |
+
python -m benchmark.translation.aggregate --out-dir benchmark/translation/out
|
| 4 |
+
Đọc: latency.jsonl, comet_scores.json
|
| 5 |
+
Ghi: benchmark/translation/out/report.md
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import argparse
|
| 11 |
+
import json
|
| 12 |
+
import statistics as stats
|
| 13 |
+
from collections import defaultdict
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def _pct(xs, p):
|
| 18 |
+
if not xs:
|
| 19 |
+
return 0.0
|
| 20 |
+
s = sorted(xs)
|
| 21 |
+
k = (len(s) - 1) * p / 100
|
| 22 |
+
lo, hi = int(k), min(int(k) + 1, len(s) - 1)
|
| 23 |
+
return s[lo] + (s[hi] - s[lo]) * (k - lo)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def load_latency(path: Path):
|
| 27 |
+
"""Return per-system aggregate over latency-measure records."""
|
| 28 |
+
recs = defaultdict(list)
|
| 29 |
+
if not path.exists():
|
| 30 |
+
return {}
|
| 31 |
+
for line in open(path, encoding="utf-8"):
|
| 32 |
+
if not line.strip():
|
| 33 |
+
continue
|
| 34 |
+
r = json.loads(line)
|
| 35 |
+
if r.get("mode") == "latency-measure":
|
| 36 |
+
recs[r["system"]].append(r)
|
| 37 |
+
agg = {}
|
| 38 |
+
for sys_, rs in recs.items():
|
| 39 |
+
walls = [r["wall_s"] for r in rs]
|
| 40 |
+
total_w = sum(walls)
|
| 41 |
+
tok_out = sum(r.get("tok_out", 0) or 0 for r in rs)
|
| 42 |
+
src_words = sum(r.get("src_words", 0) or 0 for r in rs)
|
| 43 |
+
# s / 1000 source words — chuẩn hoá latency theo độ dài, so được doc dài/ngắn.
|
| 44 |
+
s_per_kword = [1000 * r["wall_s"] / r["src_words"]
|
| 45 |
+
for r in rs if r.get("src_words")]
|
| 46 |
+
# Tỉ lệ giãn ký tự dst/src (ràng buộc ±15% là theo ký tự) — theo từng doc.
|
| 47 |
+
char_ratio = [r["dst_chars"] / r["src_chars"]
|
| 48 |
+
for r in rs if r.get("src_chars") and r.get("dst_chars")]
|
| 49 |
+
agg[sys_] = {
|
| 50 |
+
"s_per_doc_median": round(stats.median(walls), 2),
|
| 51 |
+
"s_per_doc_p25": round(_pct(walls, 25), 2),
|
| 52 |
+
"s_per_doc_p95": round(_pct(walls, 95), 2),
|
| 53 |
+
"src_words_per_s": round(src_words / total_w, 2) if total_w else 0,
|
| 54 |
+
"s_per_kword_median": round(stats.median(s_per_kword), 2) if s_per_kword else 0,
|
| 55 |
+
"char_ratio_median": round(stats.median(char_ratio), 3) if char_ratio else 0,
|
| 56 |
+
"out_tok_per_s": round(tok_out / total_w, 1) if total_w else 0,
|
| 57 |
+
"retries": sum(r.get("n_retry", 0) or 0 for r in rs),
|
| 58 |
+
"n": len(rs),
|
| 59 |
+
}
|
| 60 |
+
return agg
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def md_table(headers, rows) -> str:
|
| 64 |
+
out = ["| " + " | ".join(headers) + " |",
|
| 65 |
+
"|" + "|".join("---" for _ in headers) + "|"]
|
| 66 |
+
for row in rows:
|
| 67 |
+
out.append("| " + " | ".join(str(c) for c in row) + " |")
|
| 68 |
+
return "\n".join(out)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def main() -> None:
|
| 72 |
+
ap = argparse.ArgumentParser()
|
| 73 |
+
ap.add_argument("--out-dir", default="benchmark/translation/out")
|
| 74 |
+
args = ap.parse_args()
|
| 75 |
+
d = Path(args.out_dir)
|
| 76 |
+
|
| 77 |
+
comet = json.loads((d / "comet_scores.json").read_text()) if (d / "comet_scores.json").exists() else {}
|
| 78 |
+
lat = load_latency(d / "latency.jsonl")
|
| 79 |
+
|
| 80 |
+
md = ["# Kết quả đánh giá — bảng tổng hợp\n"]
|
| 81 |
+
|
| 82 |
+
# (A) per-language COMET × system
|
| 83 |
+
langs = sorted({lang for rel in comet.values() for lang in rel.get("by_language", {})})
|
| 84 |
+
if langs:
|
| 85 |
+
systems = list(comet)
|
| 86 |
+
md.append("## (A) COMET-DA theo ngôn ngữ × hệ\n")
|
| 87 |
+
headers = ["Target"] + systems
|
| 88 |
+
rows = []
|
| 89 |
+
for lang in langs:
|
| 90 |
+
row = [lang]
|
| 91 |
+
for s in systems:
|
| 92 |
+
m = comet[s]["by_language"].get(lang, {}).get("comet", {})
|
| 93 |
+
row.append(m.get("mean", "—"))
|
| 94 |
+
rows.append(row)
|
| 95 |
+
md.append(md_table(headers, rows) + "\n")
|
| 96 |
+
|
| 97 |
+
# (B) system × quality × latency × cost
|
| 98 |
+
md.append("## (B) So sánh hệ — quality × latency\n")
|
| 99 |
+
headers = ["System", "COMET-DA", "chrF++", "s/doc (median)", "p25–p95",
|
| 100 |
+
"s/1k-words", "words/s", "len ratio (dst/src)", "len-viol%",
|
| 101 |
+
"out tok/s", "429 retries", "fallback%"]
|
| 102 |
+
rows = []
|
| 103 |
+
for s, rel in comet.items():
|
| 104 |
+
o = rel["overall"]
|
| 105 |
+
L = lat.get(s, {})
|
| 106 |
+
rows.append([
|
| 107 |
+
s, o["comet"]["mean"], o["chrf"]["mean"],
|
| 108 |
+
L.get("s_per_doc_median", "—"),
|
| 109 |
+
f'{L.get("s_per_doc_p25","—")}–{L.get("s_per_doc_p95","—")}',
|
| 110 |
+
L.get("s_per_kword_median", "—"),
|
| 111 |
+
L.get("src_words_per_s", "—"),
|
| 112 |
+
L.get("char_ratio_median", "—"),
|
| 113 |
+
o.get("len_viol_pct", "—"),
|
| 114 |
+
L.get("out_tok_per_s", "—"), L.get("retries", "—"), o["fallback_pct"],
|
| 115 |
+
])
|
| 116 |
+
md.append(md_table(headers, rows) + "\n")
|
| 117 |
+
|
| 118 |
+
# per-domain
|
| 119 |
+
for s, rel in comet.items():
|
| 120 |
+
md.append(f"### per-domain — {s}\n")
|
| 121 |
+
rows = [[dom, m["comet"]["mean"], m["comet"]["n"]] for dom, m in rel["by_domain"].items()]
|
| 122 |
+
md.append(md_table(["domain", "COMET-DA", "n"], rows) + "\n")
|
| 123 |
+
|
| 124 |
+
report = "\n".join(md)
|
| 125 |
+
d.mkdir(parents=True, exist_ok=True)
|
| 126 |
+
(d / "report.md").write_text(report, encoding="utf-8")
|
| 127 |
+
print(report)
|
| 128 |
+
print(f"\nSaved -> {d/'report.md'}")
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
if __name__ == "__main__":
|
| 132 |
+
main()
|
benchmark/translation/instrument.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Read-only latency/token instrumentation for the translation core.
|
| 2 |
+
|
| 3 |
+
Monkeypatches ``httpx.AsyncClient.send`` to time every request and read the API
|
| 4 |
+
``usage`` block. It only *observes* — control flow, headers, and bodies are untouched,
|
| 5 |
+
so the measured system behaves exactly as in production. Thread-safe (the harness may
|
| 6 |
+
run several documents concurrently in quality-gen mode).
|
| 7 |
+
|
| 8 |
+
Usage:
|
| 9 |
+
with Instrument() as inst:
|
| 10 |
+
start = inst.mark()
|
| 11 |
+
translate_document(doc, cfg)
|
| 12 |
+
stats = inst.since(start) # RequestStats for just this document
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
from __future__ import annotations
|
| 16 |
+
|
| 17 |
+
import time
|
| 18 |
+
from dataclasses import dataclass
|
| 19 |
+
from threading import Lock
|
| 20 |
+
|
| 21 |
+
import httpx
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
@dataclass
|
| 25 |
+
class ReqRecord:
|
| 26 |
+
url: str
|
| 27 |
+
status: int
|
| 28 |
+
elapsed_s: float
|
| 29 |
+
tok_in: int | None
|
| 30 |
+
tok_out: int | None
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
@dataclass
|
| 34 |
+
class RequestStats:
|
| 35 |
+
n_req: int
|
| 36 |
+
n_retry: int # 429 or 5xx responses (each triggers a retry in the gateway)
|
| 37 |
+
tok_in: int
|
| 38 |
+
tok_out: int
|
| 39 |
+
req_latencies: list[float]
|
| 40 |
+
|
| 41 |
+
@property
|
| 42 |
+
def p50(self) -> float:
|
| 43 |
+
return _pct(self.req_latencies, 50)
|
| 44 |
+
|
| 45 |
+
@property
|
| 46 |
+
def p95(self) -> float:
|
| 47 |
+
return _pct(self.req_latencies, 95)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def _pct(xs: list[float], p: float) -> float:
|
| 51 |
+
if not xs:
|
| 52 |
+
return 0.0
|
| 53 |
+
s = sorted(xs)
|
| 54 |
+
k = (len(s) - 1) * p / 100.0
|
| 55 |
+
lo, hi = int(k), min(int(k) + 1, len(s) - 1)
|
| 56 |
+
return s[lo] + (s[hi] - s[lo]) * (k - lo)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
class Instrument:
|
| 60 |
+
def __init__(self) -> None:
|
| 61 |
+
self._records: list[ReqRecord] = []
|
| 62 |
+
self._lock = Lock()
|
| 63 |
+
self._orig = None
|
| 64 |
+
|
| 65 |
+
def __enter__(self) -> "Instrument":
|
| 66 |
+
self._orig = httpx.AsyncClient.send
|
| 67 |
+
orig = self._orig
|
| 68 |
+
records, lock = self._records, self._lock
|
| 69 |
+
|
| 70 |
+
async def patched(client_self, request, **kwargs):
|
| 71 |
+
t0 = time.perf_counter()
|
| 72 |
+
resp = await orig(client_self, request, **kwargs)
|
| 73 |
+
elapsed = time.perf_counter() - t0
|
| 74 |
+
tok_in = tok_out = None
|
| 75 |
+
try:
|
| 76 |
+
# For non-streaming requests (the gateway never streams) the body is
|
| 77 |
+
# already read+cached by the time send() returns, so .json() is safe
|
| 78 |
+
# and does not consume anything the gateway needs later.
|
| 79 |
+
if not kwargs.get("stream", False):
|
| 80 |
+
usage = resp.json().get("usage") or {}
|
| 81 |
+
tok_in = usage.get("prompt_tokens")
|
| 82 |
+
tok_out = usage.get("completion_tokens")
|
| 83 |
+
except Exception: # noqa: BLE001 — instrumentation must never break a run
|
| 84 |
+
pass
|
| 85 |
+
with lock:
|
| 86 |
+
records.append(ReqRecord(
|
| 87 |
+
url=str(request.url), status=resp.status_code,
|
| 88 |
+
elapsed_s=elapsed, tok_in=tok_in, tok_out=tok_out,
|
| 89 |
+
))
|
| 90 |
+
return resp
|
| 91 |
+
|
| 92 |
+
httpx.AsyncClient.send = patched
|
| 93 |
+
return self
|
| 94 |
+
|
| 95 |
+
def __exit__(self, *_) -> None:
|
| 96 |
+
if self._orig is not None:
|
| 97 |
+
httpx.AsyncClient.send = self._orig
|
| 98 |
+
|
| 99 |
+
def mark(self) -> int:
|
| 100 |
+
"""Index snapshot; pass to since() to get stats for work done after it."""
|
| 101 |
+
with self._lock:
|
| 102 |
+
return len(self._records)
|
| 103 |
+
|
| 104 |
+
def since(self, mark: int) -> RequestStats:
|
| 105 |
+
with self._lock:
|
| 106 |
+
recs = self._records[mark:]
|
| 107 |
+
return RequestStats(
|
| 108 |
+
n_req=len(recs),
|
| 109 |
+
n_retry=sum(1 for r in recs if r.status == 429 or r.status >= 500),
|
| 110 |
+
tok_in=sum(r.tok_in or 0 for r in recs),
|
| 111 |
+
tok_out=sum(r.tok_out or 0 for r in recs),
|
| 112 |
+
req_latencies=[r.elapsed_s for r in recs],
|
| 113 |
+
)
|
benchmark/translation/requirements.txt
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Bước A (dịch) — chỉ cần httpx (đã có trong pdf2zh) + tùy chọn datasets để liệt kê 55 cặp.
|
| 2 |
+
# jsonl được tải trực tiếp bằng httpx nên KHÔNG bắt buộc `datasets`.
|
| 3 |
+
datasets # optional: chỉ cho list_all_pairs()
|
| 4 |
+
google-auth # optional: chỉ khi dùng --provider vertex (ADC project/region)
|
| 5 |
+
|
| 6 |
+
# Bước B (chấm COMET) — chạy local CPU/MPS. LƯU Ý: unbabel-comet + torch thường ưa
|
| 7 |
+
# Python 3.10–3.12. Nếu env chính là 3.13, tạo venv riêng cho bước chấm:
|
| 8 |
+
# python3.11 -m venv .venv-score && source .venv-score/bin/activate
|
| 9 |
+
# pip install -r benchmark/translation/requirements.txt
|
| 10 |
+
unbabel-comet>=2.2.0
|
| 11 |
+
sacrebleu>=2.4.0
|
| 12 |
+
# torch được unbabel-comet kéo theo; trên Mac Apple Silicon: pip install torch (wheel arm64).
|
benchmark/translation/run_all.sh
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# =============================================================================
|
| 3 |
+
# Chạy pipeline eval qua nhiều system (mặc định provider = litellm):
|
| 4 |
+
# mặc định: qwen3.6-35b-a3b, gemini-3.1-flash-lite (đổi qua biến MODELS)
|
| 5 |
+
#
|
| 6 |
+
# Mỗi system: dịch WMT24++ -> đo latency -> chấm COMET-DA + chrF++ + các metric.
|
| 7 |
+
# Output:
|
| 8 |
+
# benchmark/translation/out/<provider-model>/ hypotheses.jsonl, latency.jsonl, comet_scores.json, report.md
|
| 9 |
+
# benchmark/translation/out/_all/ gộp tất cả -> comet_scores.json + report.md (bảng SO SÁNH)
|
| 10 |
+
#
|
| 11 |
+
# YÊU CẦU: chạy trong env có pdf2zh + unbabel-comet + sacrebleu (vd conda `thesis`),
|
| 12 |
+
# và .env (gốc repo) có LITELLM_BASE_URL + LITELLM_API_KEY (harness tự load).
|
| 13 |
+
#
|
| 14 |
+
# Override qua biến môi trường, ví dụ:
|
| 15 |
+
# PAIRS="vi_VN de_DE" LIMIT_DOCS=30 REPEATS=1 bash benchmark/translation/run_all.sh
|
| 16 |
+
# LIMIT_DOCS="" REPEATS=5 bash benchmark/translation/run_all.sh # full pair, đo latency N=5
|
| 17 |
+
# PAIRS=ALL LIMIT_DOCS="" bash benchmark/translation/run_all.sh # 55 cặp, tất cả docs
|
| 18 |
+
# # đổi provider/model để reuse (mỗi entry là "model" hoặc "provider:model"):
|
| 19 |
+
# MODELS="openai:gpt-4o-mini anthropic:claude-haiku-4-5 gemini:gemini-2.5-flash" bash benchmark/translation/run_all.sh
|
| 20 |
+
# # tắt thinking cho model reasoning qua OpenRouter (Qwen, DeepSeek R1, ...):
|
| 21 |
+
# NO_REASONING=1 MODELS="openrouter:qwen/qwen3.5-flash-02-23" bash benchmark/translation/run_all.sh
|
| 22 |
+
# =============================================================================
|
| 23 |
+
set -u
|
| 24 |
+
cd "$(dirname "$0")/../.." # repo root
|
| 25 |
+
|
| 26 |
+
PY=${PYTHON:-python}
|
| 27 |
+
# Provider MẶC ĐỊNH cho entry không ghi tiền tố "provider:". Đổi cả loạt: PROVIDER=openai ...
|
| 28 |
+
PROVIDER=${PROVIDER:-litellm}
|
| 29 |
+
# MODELS: mỗi entry là "model" (dùng PROVIDER) HOẶC "provider:model" (tự chỉ định).
|
| 30 |
+
# litellm: MODELS="qwen3.6-35b-a3b gemini-3.1-flash-lite"
|
| 31 |
+
# trực tiếp: MODELS="openai:gpt-4o-mini anthropic:claude-haiku-4-5"
|
| 32 |
+
read -ra ENTRIES <<< "${MODELS:-gemini-3.1-flash-lite}"
|
| 33 |
+
# Resolve mỗi entry -> "provider|model"
|
| 34 |
+
RESOLVED=()
|
| 35 |
+
for e in "${ENTRIES[@]}"; do
|
| 36 |
+
if [[ "$e" == *:* ]]; then RESOLVED+=("${e%%:*}|${e#*:}"); else RESOLVED+=("$PROVIDER|$e"); fi
|
| 37 |
+
done
|
| 38 |
+
PROVS=$(printf '%s\n' "${RESOLVED[@]}" | cut -d'|' -f1 | sort -u | tr '\n' ' ')
|
| 39 |
+
PAIRS=${PAIRS:-"vi_VN"} # danh sách locale, cách nhau bởi khoảng trắng
|
| 40 |
+
LIMIT_DOCS=${LIMIT_DOCS-20} # số doc/pair; LIMIT_DOCS="" -> FULL (~170 doc); unset -> 20
|
| 41 |
+
REPEATS=${REPEATS:-1} # >1 = latency-measure ổn định (tuần tự, chậm)
|
| 42 |
+
DOC_WORKERS=${DOC_WORKERS:-1} # >1 = quality-gen: dịch nhiều doc song song (nhanh; latency KHÔNG faithful)
|
| 43 |
+
SCORE=${SCORE:-1} # 0 = CHỈ DỊCH (bỏ hết COMET) -> chấm sau trên GPU box
|
| 44 |
+
SCORE_PER_MODEL=${SCORE_PER_MODEL:-1} # 0 = bỏ chấm COMET per-model, chỉ chấm _all (nhanh hơn nhiều khi nhiều model)
|
| 45 |
+
RUN_AGGREGATE=${RUN_AGGREGATE:-1} # 0 = bỏ bước report.md (chỉ ra comet_scores.json + latency.jsonl)
|
| 46 |
+
RESUME=${RESUME:-0} # 1 = KHÔNG xóa dữ liệu cũ; bỏ qua cặp đã xong (chạy tiếp sau khi stuck)
|
| 47 |
+
NO_REASONING=${NO_REASONING:-0} # 1 = tắt thinking (OpenRouter: reasoning={enabled:false}; no-op provider khác)
|
| 48 |
+
OUT_ROOT=${OUT_ROOT:-benchmark/translation/out}
|
| 49 |
+
COMET_MODEL=${COMET_MODEL:-Unbabel/wmt22-comet-da}
|
| 50 |
+
|
| 51 |
+
limit_flag=""; [ -n "$LIMIT_DOCS" ] && limit_flag="--limit-docs $LIMIT_DOCS"
|
| 52 |
+
|
| 53 |
+
# --- Preflight: kiểm tra deps + key trước khi tốn thời gian ------------------
|
| 54 |
+
echo ">>> Preflight..."
|
| 55 |
+
$PY -c "import httpx, json_repair, dotenv, comet, sacrebleu" 2>/dev/null \
|
| 56 |
+
|| { echo "!! Thiếu deps. Chạy trong env có pdf2zh + unbabel-comet + sacrebleu."; exit 1; }
|
| 57 |
+
# Kiểm key cho ĐÚNG các provider được dùng (litellm/openai/anthropic/gemini...).
|
| 58 |
+
$PY -c "
|
| 59 |
+
from dotenv import load_dotenv; load_dotenv()
|
| 60 |
+
import os, sys
|
| 61 |
+
from pdf2zh.translation.config import PROVIDERS
|
| 62 |
+
provs = '$PROVS'.split()
|
| 63 |
+
miss = [p for p in provs if p in PROVIDERS and not os.environ.get(PROVIDERS[p]['env_var'])]
|
| 64 |
+
if miss:
|
| 65 |
+
print('!! Thiếu key trong .env: ' + ', '.join(f\"{p} -> {PROVIDERS[p]['env_var']}\" for p in miss))
|
| 66 |
+
sys.exit(1)
|
| 67 |
+
" || exit 1
|
| 68 |
+
# PAIRS=ALL -> bung ra toàn bộ 55 locale (ưu tiên list từ HF, fallback LOCALE_NAME).
|
| 69 |
+
if [ "$PAIRS" = "ALL" ] || [ "$PAIRS" = "all" ]; then
|
| 70 |
+
PAIRS=$($PY -c "
|
| 71 |
+
try:
|
| 72 |
+
from benchmark.translation.wmt24pp_adapter import list_all_pairs
|
| 73 |
+
print(' '.join(sorted(list_all_pairs())))
|
| 74 |
+
except Exception:
|
| 75 |
+
from benchmark.translation.wmt24pp_adapter import LOCALE_NAME
|
| 76 |
+
print(' '.join(sorted(LOCALE_NAME)))
|
| 77 |
+
") || { echo '!! Không lấy được danh sách ngôn ngữ.'; exit 1; }
|
| 78 |
+
echo " PAIRS=ALL -> $(echo $PAIRS | wc -w | tr -d ' ') ngôn ngữ"
|
| 79 |
+
fi
|
| 80 |
+
echo " OK — systems: $(printf '%s ' "${RESOLVED[@]}" | tr '|' '/')| pairs: $(echo $PAIRS | wc -w | tr -d ' ') | limit_docs: ${LIMIT_DOCS:-ALL} | repeats: $REPEATS"
|
| 81 |
+
|
| 82 |
+
ALL_DIR="$OUT_ROOT/_all"
|
| 83 |
+
mkdir -p "$ALL_DIR"
|
| 84 |
+
: > "$ALL_DIR/hypotheses.jsonl"; : > "$ALL_DIR/latency.jsonl" # reset combined
|
| 85 |
+
|
| 86 |
+
# --- Vòng lặp system (provider|model) ---------------------------------------
|
| 87 |
+
for RES in "${RESOLVED[@]}"; do
|
| 88 |
+
PROV="${RES%%|*}"; MODEL="${RES#*|}"
|
| 89 |
+
SLUG=$(echo "${PROV}-${MODEL}" | sed 's/[^a-zA-Z0-9]/-/g') # gồm provider -> không đụng nhau
|
| 90 |
+
DIR="$OUT_ROOT/$SLUG"
|
| 91 |
+
mkdir -p "$DIR"
|
| 92 |
+
if [ "$RESUME" != "1" ]; then
|
| 93 |
+
: > "$DIR/hypotheses.jsonl"; : > "$DIR/latency.jsonl" # reset (run_translate append)
|
| 94 |
+
fi
|
| 95 |
+
echo ""
|
| 96 |
+
echo "=================================================================="
|
| 97 |
+
echo ">>> SYSTEM: $PROV / $MODEL -> $DIR ${RESUME:+(RESUME=$RESUME)}"
|
| 98 |
+
echo "=================================================================="
|
| 99 |
+
|
| 100 |
+
resume_flag=""; [ "$RESUME" = "1" ] && resume_flag="--resume"
|
| 101 |
+
no_reasoning_flag=""; [ "$NO_REASONING" = "1" ] && no_reasoning_flag="--no-reasoning"
|
| 102 |
+
for PAIR in $PAIRS; do
|
| 103 |
+
# RESUME: run_translate tự lọc theo TỪNG DOC (bỏ doc đã OK, dịch lại doc
|
| 104 |
+
# lỗi/thiếu) dựa vào latency.jsonl hiện có — không bỏ qua cả cặp một cách thô.
|
| 105 |
+
echo "--- [dịch] en-$PAIR ${resume_flag:+(resume)} ${no_reasoning_flag:+(no-reasoning)} ---"
|
| 106 |
+
$PY -m benchmark.translation.run_translate --provider "$PROV" --model "$MODEL" \
|
| 107 |
+
--pair "$PAIR" $limit_flag --repeats "$REPEATS" --doc-workers "$DOC_WORKERS" \
|
| 108 |
+
--out "$DIR" $resume_flag $no_reasoning_flag \
|
| 109 |
+
|| echo "!! translate FAILED: $PROV/$MODEL / en-$PAIR — bỏ qua cặp này"
|
| 110 |
+
done
|
| 111 |
+
|
| 112 |
+
if [ -s "$DIR/hypotheses.jsonl" ]; then
|
| 113 |
+
if [ "$SCORE" != "0" ] && [ "$SCORE_PER_MODEL" != "0" ]; then
|
| 114 |
+
echo "--- [chấm] COMET-DA + chrF++ cho $PROV/$MODEL ---"
|
| 115 |
+
if $PY -m benchmark.translation.score_comet --hyp "$DIR/hypotheses.jsonl" \
|
| 116 |
+
--out "$DIR/comet_scores.json" --model "$COMET_MODEL"; then
|
| 117 |
+
[ "$RUN_AGGREGATE" != "0" ] && $PY -m benchmark.translation.aggregate --out-dir "$DIR"
|
| 118 |
+
else
|
| 119 |
+
echo "!! scoring FAILED: $PROV/$MODEL"
|
| 120 |
+
fi
|
| 121 |
+
fi
|
| 122 |
+
# gộp vào combined để so sánh các system
|
| 123 |
+
cat "$DIR/hypotheses.jsonl" >> "$ALL_DIR/hypotheses.jsonl"
|
| 124 |
+
cat "$DIR/latency.jsonl" >> "$ALL_DIR/latency.jsonl"
|
| 125 |
+
else
|
| 126 |
+
echo "!! $PROV/$MODEL không có hypothesis nào — bỏ qua chấm điểm."
|
| 127 |
+
fi
|
| 128 |
+
done
|
| 129 |
+
|
| 130 |
+
# --- Tổng hợp so sánh 4 model -----------------------------------------------
|
| 131 |
+
echo ""
|
| 132 |
+
echo "=================================================================="
|
| 133 |
+
echo ">>> TỔNG HỢP SO SÁNH (benchmark/translation/out/_all)"
|
| 134 |
+
echo "=================================================================="
|
| 135 |
+
if [ "$SCORE" != "0" ] && [ -s "$ALL_DIR/hypotheses.jsonl" ]; then
|
| 136 |
+
$PY -m benchmark.translation.score_comet --hyp "$ALL_DIR/hypotheses.jsonl" \
|
| 137 |
+
--out "$ALL_DIR/comet_scores.json" --model "$COMET_MODEL"
|
| 138 |
+
[ "$RUN_AGGREGATE" != "0" ] && $PY -m benchmark.translation.aggregate --out-dir "$ALL_DIR"
|
| 139 |
+
elif [ "$SCORE" = "0" ]; then
|
| 140 |
+
echo ">>> SCORE=0: bỏ COMET. Chấm sau: python -m benchmark.translation.score_comet --hyp $ALL_DIR/hypotheses.jsonl --out $ALL_DIR/comet_scores.json [--gpus 1]"
|
| 141 |
+
fi
|
| 142 |
+
|
| 143 |
+
echo ""
|
| 144 |
+
echo "XONG. Output:"
|
| 145 |
+
for RES in "${RESOLVED[@]}"; do
|
| 146 |
+
PROV="${RES%%|*}"; MODEL="${RES#*|}"
|
| 147 |
+
SLUG=$(echo "${PROV}-${MODEL}" | sed 's/[^a-zA-Z0-9]/-/g')
|
| 148 |
+
echo " - $PROV/$MODEL : $OUT_ROOT/$SLUG/{hypotheses,latency}.jsonl · comet_scores.json · report.md"
|
| 149 |
+
done
|
| 150 |
+
echo " - SO SÁNH các system : $ALL_DIR/report.md (+ comet_scores.json keyed theo system)"
|
benchmark/translation/run_translate.py
ADDED
|
@@ -0,0 +1,318 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Bước A — dịch WMT24++ qua ĐÚNG core (translate_document) + đo latency.
|
| 2 |
+
|
| 3 |
+
Chạy 1 doc để test, hoặc full pair/sweep. Ghi:
|
| 4 |
+
<out>/hypotheses.jsonl — 1 dòng/segment (từ repeat 0), để chấm COMET/judge
|
| 5 |
+
<out>/latency.jsonl — 1 dòng/doc/repeat, để thống kê latency
|
| 6 |
+
|
| 7 |
+
Hai chế độ:
|
| 8 |
+
* latency-measure (mặc định, --doc-workers 1): tuần tự, concurrency=8 chuẩn
|
| 9 |
+
production, N repeats → số s/doc trung thực.
|
| 10 |
+
* quality-gen (--doc-workers N>1): chạy nhiều doc song song để lấy hypotheses
|
| 11 |
+
nhanh; latency KHÔNG còn production-faithful (đánh dấu mode="quality-gen").
|
| 12 |
+
|
| 13 |
+
Ví dụ:
|
| 14 |
+
# test 1 doc:
|
| 15 |
+
python -m benchmark.translation.run_translate --pair vi_VN --provider gemini --limit-docs 1 --repeats 1
|
| 16 |
+
# full pair, đo latency:
|
| 17 |
+
python -m benchmark.translation.run_translate --pair vi_VN --provider gemini --repeats 5
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
from __future__ import annotations
|
| 21 |
+
|
| 22 |
+
import argparse
|
| 23 |
+
import copy
|
| 24 |
+
import json
|
| 25 |
+
import logging
|
| 26 |
+
import os
|
| 27 |
+
import time
|
| 28 |
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 29 |
+
from pathlib import Path
|
| 30 |
+
|
| 31 |
+
# Allow `python benchmark/translation/run_translate.py` as well as `-m`.
|
| 32 |
+
import sys
|
| 33 |
+
sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent))
|
| 34 |
+
|
| 35 |
+
from dotenv import load_dotenv # noqa: E402
|
| 36 |
+
|
| 37 |
+
from pdf2zh.translation.config import PROVIDERS, TranslatorConfig, resolve_provider # noqa: E402
|
| 38 |
+
from pdf2zh.translation.pipeline import translate_document # noqa: E402
|
| 39 |
+
|
| 40 |
+
from benchmark.translation.instrument import Instrument # noqa: E402
|
| 41 |
+
from benchmark.translation.wmt24pp_adapter import ( # noqa: E402
|
| 42 |
+
DocBundle,
|
| 43 |
+
extract_hypotheses,
|
| 44 |
+
load_pair,
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
logger = logging.getLogger("benchmark.translation.run_translate")
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def build_config(args, api_key: str) -> TranslatorConfig:
|
| 51 |
+
cfg = TranslatorConfig(
|
| 52 |
+
source_language="English",
|
| 53 |
+
provider=args.provider,
|
| 54 |
+
model=args.model,
|
| 55 |
+
api_key=api_key,
|
| 56 |
+
)
|
| 57 |
+
if args.no_post_fix:
|
| 58 |
+
cfg.toc_fix_enabled = False
|
| 59 |
+
cfg.math_fix_enabled = False
|
| 60 |
+
if args.no_reasoning:
|
| 61 |
+
cfg.disable_reasoning = True
|
| 62 |
+
return cfg
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def vertex_auth(cfg: TranslatorConfig, model: str | None):
|
| 66 |
+
"""Cấu hình cfg gọi thẳng Vertex AI (OpenAI-compat) bằng ADC + project/region.
|
| 67 |
+
|
| 68 |
+
Trả về hàm refresh() lấy access-token mới (token GCP hết hạn ~1h; harness gọi
|
| 69 |
+
refresh trước mỗi doc để token luôn tươi cho run dài). KHÔNG đụng core: chỉ set
|
| 70 |
+
base_url/api_key/model trên cfg và đặt provider='litellm' (một key hợp lệ trong
|
| 71 |
+
PROVIDERS) để resolve_provider(cfg) không raise khi base_url/model/key đã có.
|
| 72 |
+
|
| 73 |
+
.env cần: VERTEX_PROJECT (và tùy chọn VERTEX_LOCATION, mặc định us-central1).
|
| 74 |
+
Xác thực: `gcloud auth application-default login` (ADC) hoặc
|
| 75 |
+
GOOGLE_APPLICATION_CREDENTIALS trỏ tới service-account JSON.
|
| 76 |
+
"""
|
| 77 |
+
try:
|
| 78 |
+
import google.auth
|
| 79 |
+
import google.auth.transport.requests as gart
|
| 80 |
+
except ImportError:
|
| 81 |
+
raise SystemExit("Cần google-auth: pip install google-auth")
|
| 82 |
+
project = os.environ.get("VERTEX_PROJECT") or os.environ.get("GOOGLE_CLOUD_PROJECT")
|
| 83 |
+
region = os.environ.get("VERTEX_LOCATION", "us-central1")
|
| 84 |
+
if not project:
|
| 85 |
+
raise SystemExit("Đặt VERTEX_PROJECT (và tùy chọn VERTEX_LOCATION) trong .env")
|
| 86 |
+
if not model:
|
| 87 |
+
raise SystemExit("Vertex cần --model, ví dụ: google/gemini-2.5-flash")
|
| 88 |
+
creds, _ = google.auth.default(
|
| 89 |
+
scopes=["https://www.googleapis.com/auth/cloud-platform"]
|
| 90 |
+
)
|
| 91 |
+
req = gart.Request()
|
| 92 |
+
|
| 93 |
+
def refresh() -> str:
|
| 94 |
+
creds.refresh(req) # chỉ gọi mạng khi token gần hết hạn (google-auth tự cache)
|
| 95 |
+
return creds.token
|
| 96 |
+
|
| 97 |
+
# location 'global' dùng host không có tiền tố region.
|
| 98 |
+
host = "aiplatform.googleapis.com" if region == "global" else f"{region}-aiplatform.googleapis.com"
|
| 99 |
+
cfg.base_url = (
|
| 100 |
+
f"https://{host}/v1beta1/"
|
| 101 |
+
f"projects/{project}/locations/{region}/endpoints/openapi"
|
| 102 |
+
)
|
| 103 |
+
cfg.provider = "litellm" # để resolve_provider(cfg) chấp nhận (đã set base_url/model/key)
|
| 104 |
+
cfg.model = model
|
| 105 |
+
cfg.api_key = refresh()
|
| 106 |
+
return refresh
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def _fresh(bundle: DocBundle) -> DocBundle:
|
| 110 |
+
"""Copy so a repeat translates a clean, untranslated doc."""
|
| 111 |
+
return DocBundle(
|
| 112 |
+
pair=bundle.pair, document_id=bundle.document_id,
|
| 113 |
+
segs=bundle.segs, doc=copy.deepcopy(bundle.doc),
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def translate_one(bundle: DocBundle, cfg: TranslatorConfig,
|
| 118 |
+
inst: Instrument | None) -> tuple[DocBundle, dict]:
|
| 119 |
+
"""Translate one document; return the (mutated) bundle + a latency record.
|
| 120 |
+
|
| 121 |
+
Never raises: a translate_document failure (network glitch, malformed
|
| 122 |
+
provider response, ...) must not lose the OTHER documents in the same
|
| 123 |
+
batch. Failures are recorded (rec["error"]) and yield an empty translation
|
| 124 |
+
for that doc so hypotheses/latency for the rest of the pair are preserved.
|
| 125 |
+
"""
|
| 126 |
+
b = _fresh(bundle)
|
| 127 |
+
src_chars = sum(len(s.source) for s in b.segs)
|
| 128 |
+
src_words = sum(len(s.source.split()) for s in b.segs)
|
| 129 |
+
mark = inst.mark() if inst else 0
|
| 130 |
+
t0 = time.perf_counter()
|
| 131 |
+
try:
|
| 132 |
+
translate_document(b.doc, cfg)
|
| 133 |
+
error = None
|
| 134 |
+
except Exception as exc: # noqa: BLE001 — isolate one bad doc from the rest
|
| 135 |
+
logger.warning("doc %s failed: %s: %s", b.document_id, type(exc).__name__, exc)
|
| 136 |
+
error = f"{type(exc).__name__}: {exc}"
|
| 137 |
+
wall = time.perf_counter() - t0
|
| 138 |
+
# Độ dài BẢN DỊCH (destination) — để đo tỉ lệ giãn & ràng buộc ±15% theo từng LLM.
|
| 139 |
+
dst_texts = [e.get("translated_text", "") for e in b.doc["pages"][0]["elements"]]
|
| 140 |
+
dst_chars = sum(len(t) for t in dst_texts)
|
| 141 |
+
dst_words = sum(len(t.split()) for t in dst_texts)
|
| 142 |
+
rec = {
|
| 143 |
+
"document_id": b.document_id,
|
| 144 |
+
"n_segments": len(b.segs),
|
| 145 |
+
"src_words": src_words, # để chuẩn hoá latency theo độ dài (từ-nguồn/s)
|
| 146 |
+
"src_chars": src_chars,
|
| 147 |
+
"dst_words": dst_words,
|
| 148 |
+
"dst_chars": dst_chars,
|
| 149 |
+
"wall_s": round(wall, 4),
|
| 150 |
+
"error": error,
|
| 151 |
+
}
|
| 152 |
+
if inst:
|
| 153 |
+
st = inst.since(mark)
|
| 154 |
+
rec.update({
|
| 155 |
+
"n_req": st.n_req, "n_retry": st.n_retry,
|
| 156 |
+
"tok_in": st.tok_in, "tok_out": st.tok_out,
|
| 157 |
+
"req_p50": round(st.p50, 4), "req_p95": round(st.p95, 4),
|
| 158 |
+
})
|
| 159 |
+
return b, rec
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def main() -> None:
|
| 163 |
+
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 164 |
+
ap.add_argument("--pair", required=True, help="Target locale, e.g. vi_VN, de_DE, zh_CN")
|
| 165 |
+
ap.add_argument("--provider", default="gemini", choices=list(PROVIDERS) + ["vertex"])
|
| 166 |
+
ap.add_argument("--model", default=None, help="Override model id (else provider default)")
|
| 167 |
+
ap.add_argument("--api-key", default=None, help="Else read provider env var")
|
| 168 |
+
ap.add_argument("--limit-docs", type=int, default=None, help="First N documents only (test)")
|
| 169 |
+
ap.add_argument("--repeats", type=int, default=5, help="Latency repeats per doc")
|
| 170 |
+
ap.add_argument("--doc-workers", type=int, default=1, help=">1 = quality-gen (latency not faithful)")
|
| 171 |
+
ap.add_argument("--no-post-fix", action="store_true", help="Disable toc_fix/math_fix (for the no-op check)")
|
| 172 |
+
ap.add_argument("--no-reasoning", action="store_true",
|
| 173 |
+
help="OpenRouter only: send reasoning={enabled: false} to skip the "
|
| 174 |
+
"model's thinking pass (faster/cheaper on reasoning models it proxies, "
|
| 175 |
+
"e.g. Qwen, DeepSeek R1). No-op for other providers.")
|
| 176 |
+
ap.add_argument("--out", default="benchmark/translation/out", help="Output dir")
|
| 177 |
+
ap.add_argument("--resume", action="store_true",
|
| 178 |
+
help="Skip docs already succeeded (found in existing latency.jsonl "
|
| 179 |
+
"for this system+pair, error=null) — retries only missing/failed docs")
|
| 180 |
+
ap.add_argument("--system-label", default=None,
|
| 181 |
+
help="Ghi đè nhãn 'system' dùng để log VÀ để so khớp --resume — dùng khi "
|
| 182 |
+
"gọi qua route khác (vd vertex) để BÙ dữ liệu cho cùng một model đã "
|
| 183 |
+
"chạy qua route cũ (vd litellm), coi là cùng một nguồn kết quả. "
|
| 184 |
+
"VD: --provider vertex --model google/gemini-3.1-flash-lite "
|
| 185 |
+
"--system-label litellm/gemini-3.1-flash-lite")
|
| 186 |
+
ap.add_argument("--verbose", action="store_true")
|
| 187 |
+
args = ap.parse_args()
|
| 188 |
+
|
| 189 |
+
logging.basicConfig(
|
| 190 |
+
level=logging.DEBUG if args.verbose else logging.INFO,
|
| 191 |
+
format="%(asctime)s %(levelname)s %(name)s %(message)s",
|
| 192 |
+
)
|
| 193 |
+
if args.verbose:
|
| 194 |
+
# --verbose chỉ để xem log CỦA HARNESS (benchmark.translation.*, json_translator,
|
| 195 |
+
# pdf2zh.*) ở mức
|
| 196 |
+
# DEBUG — httpx/httpcore/google-auth/urllib3 quá ồn (log từng gói TCP/TLS) nên
|
| 197 |
+
# giữ ở INFO, đủ để vẫn thấy "HTTP Request: POST ... 200/400/429" của mỗi call.
|
| 198 |
+
for noisy in ("httpcore", "httpx", "urllib3", "google", "google.auth"):
|
| 199 |
+
logging.getLogger(noisy).setLevel(logging.INFO)
|
| 200 |
+
|
| 201 |
+
load_dotenv() # nạp .env (repo root) trước khi đọc key/base_url
|
| 202 |
+
refresh = None # token-refresh callback (chỉ dùng cho vertex)
|
| 203 |
+
if args.provider == "vertex":
|
| 204 |
+
cfg = build_config(args, api_key="") # api_key sẽ do vertex_auth cấp
|
| 205 |
+
refresh = vertex_auth(cfg, args.model)
|
| 206 |
+
else:
|
| 207 |
+
api_key = args.api_key or os.environ.get(PROVIDERS[args.provider]["env_var"], "")
|
| 208 |
+
if not api_key:
|
| 209 |
+
raise SystemExit(f"No API key: pass --api-key or set {PROVIDERS[args.provider]['env_var']}")
|
| 210 |
+
cfg = build_config(args, api_key)
|
| 211 |
+
resolve_provider(cfg) # fill model/base_url now so the system label is accurate
|
| 212 |
+
system = args.system_label or f"{args.provider}/{cfg.model}"
|
| 213 |
+
if args.system_label:
|
| 214 |
+
logger.warning("system-label override: gọi %s/%s nhưng ghi log là %r",
|
| 215 |
+
args.provider, cfg.model, system)
|
| 216 |
+
mode = "quality-gen" if args.doc_workers > 1 else "latency-measure"
|
| 217 |
+
logger.info("System=%s pair=en-%s mode=%s", system, args.pair, mode)
|
| 218 |
+
|
| 219 |
+
bundles = load_pair(args.pair)
|
| 220 |
+
if args.limit_docs:
|
| 221 |
+
bundles = bundles[: args.limit_docs]
|
| 222 |
+
logger.info("Documents: %d", len(bundles))
|
| 223 |
+
|
| 224 |
+
if args.resume:
|
| 225 |
+
lat_path = Path(args.out) / "latency.jsonl"
|
| 226 |
+
done_ids: set[str] = set()
|
| 227 |
+
if lat_path.exists():
|
| 228 |
+
with open(lat_path, encoding="utf-8") as f:
|
| 229 |
+
for line in f:
|
| 230 |
+
line = line.strip()
|
| 231 |
+
if not line:
|
| 232 |
+
continue
|
| 233 |
+
r = json.loads(line)
|
| 234 |
+
if (r.get("system") == system and r.get("pair") == f"en-{args.pair}"
|
| 235 |
+
and not r.get("error")):
|
| 236 |
+
done_ids.add(r["document_id"])
|
| 237 |
+
before = len(bundles)
|
| 238 |
+
skipped_in_scope = sum(1 for b in bundles if b.document_id in done_ids)
|
| 239 |
+
bundles = [b for b in bundles if b.document_id not in done_ids]
|
| 240 |
+
logger.info(
|
| 241 |
+
"Resume: %d known-OK trong cả cặp en-%s | phạm vi hiện tại %d doc "
|
| 242 |
+
"-> %d đã OK (skip), %d còn lại (missing/failed) sẽ dịch",
|
| 243 |
+
len(done_ids), args.pair, before, skipped_in_scope, len(bundles),
|
| 244 |
+
)
|
| 245 |
+
if not bundles:
|
| 246 |
+
logger.info("Không còn doc nào cần dịch cho en-%s — bỏ qua.", args.pair)
|
| 247 |
+
return
|
| 248 |
+
|
| 249 |
+
out = Path(args.out)
|
| 250 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 251 |
+
hyp_f = open(out / "hypotheses.jsonl", "a", encoding="utf-8")
|
| 252 |
+
lat_f = open(out / "latency.jsonl", "a", encoding="utf-8")
|
| 253 |
+
|
| 254 |
+
n_hyp = n_err = 0
|
| 255 |
+
|
| 256 |
+
def _write(b: DocBundle, rec: dict, rep: int, is_canonical: bool) -> None:
|
| 257 |
+
"""Ghi + flush NGAY cho một doc — không đợi cả lô 170 doc xong. Một doc
|
| 258 |
+
lỗi (rec['error'] set) không mất dữ liệu của các doc khác đã hoàn tất."""
|
| 259 |
+
nonlocal n_hyp, n_err
|
| 260 |
+
rec.update({"system": system, "pair": f"en-{args.pair}",
|
| 261 |
+
"repeat": rep, "mode": mode})
|
| 262 |
+
if rec.get("error"):
|
| 263 |
+
n_err += 1
|
| 264 |
+
lat_f.write(json.dumps(rec, ensure_ascii=False) + "\n")
|
| 265 |
+
lat_f.flush()
|
| 266 |
+
if is_canonical and not rec.get("error"):
|
| 267 |
+
for h in extract_hypotheses(b):
|
| 268 |
+
h["system"] = system
|
| 269 |
+
hyp_f.write(json.dumps(h, ensure_ascii=False) + "\n")
|
| 270 |
+
n_hyp += 1
|
| 271 |
+
hyp_f.flush()
|
| 272 |
+
|
| 273 |
+
with Instrument() as inst:
|
| 274 |
+
for rep in range(args.repeats):
|
| 275 |
+
is_canonical = rep == 0 # write hypotheses only from the first pass
|
| 276 |
+
if args.doc_workers > 1:
|
| 277 |
+
if refresh:
|
| 278 |
+
cfg.api_key = refresh() # 1 lần/batch (token đủ dùng ~1h)
|
| 279 |
+
with ThreadPoolExecutor(max_workers=args.doc_workers) as ex:
|
| 280 |
+
futures = [ex.submit(translate_one, b, cfg, None) for b in bundles]
|
| 281 |
+
for fut in as_completed(futures):
|
| 282 |
+
b, rec = fut.result() # translate_one never raises (see docstring)
|
| 283 |
+
_write(b, rec, rep, is_canonical)
|
| 284 |
+
else:
|
| 285 |
+
for b in bundles:
|
| 286 |
+
if refresh:
|
| 287 |
+
cfg.api_key = refresh() # trước mỗi doc -> token luôn tươi cho run dài
|
| 288 |
+
bb, rec = translate_one(b, cfg, inst)
|
| 289 |
+
_write(bb, rec, rep, is_canonical)
|
| 290 |
+
|
| 291 |
+
logger.info("repeat %d/%d done (%d errors)", rep + 1, args.repeats, n_err)
|
| 292 |
+
|
| 293 |
+
hyp_f.close(); lat_f.close()
|
| 294 |
+
if n_err:
|
| 295 |
+
logger.warning("%d/%d documents failed this run (see 'error' field in latency.jsonl)",
|
| 296 |
+
n_err, len(bundles) * args.repeats)
|
| 297 |
+
|
| 298 |
+
# Quick console summary.
|
| 299 |
+
walls, words = [], 0.0
|
| 300 |
+
with open(out / "latency.jsonl", encoding="utf-8") as f:
|
| 301 |
+
for line in f:
|
| 302 |
+
r = json.loads(line)
|
| 303 |
+
if r["system"] == system and r["pair"] == f"en-{args.pair}":
|
| 304 |
+
walls.append(r["wall_s"])
|
| 305 |
+
words += r.get("src_words", 0)
|
| 306 |
+
walls.sort()
|
| 307 |
+
med = walls[len(walls) // 2] if walls else 0.0
|
| 308 |
+
wps = words / sum(walls) if walls else 0.0
|
| 309 |
+
print(f"\n=== {system} | en-{args.pair} ===")
|
| 310 |
+
print(f" docs×repeats measured : {len(walls)}")
|
| 311 |
+
print(f" s/doc median : {med:.2f}s (min {min(walls, default=0):.2f} / max {max(walls, default=0):.2f})")
|
| 312 |
+
print(f" throughput : {wps:.2f} source-words/s")
|
| 313 |
+
print(f" hypotheses written : {n_h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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Bước B — chấm quality (local, CPU/MPS, 0 token API).
|
| 2 |
+
|
| 3 |
+
Đọc hypotheses.jsonl, tính:
|
| 4 |
+
* COMET-DA (Unbabel/wmt22-comet-da, ref-based) — metric CHÍNH
|
| 5 |
+
* chrF++ (sacrebleu) — lexical baseline
|
| 6 |
+
* fallback% / empty% / length-violation% — chỉ số độ tin cậy hệ thống
|
| 7 |
+
|
| 8 |
+
Aggregate theo system × (language, domain). WMT24++ là segment-level (~32 từ) nên
|
| 9 |
+
KHÔNG cần chunk — feed thẳng, giới hạn 512-token không cắn (xem §4).
|
| 10 |
+
|
| 11 |
+
CHẠY ĐỘC LẬP: file này KHÔNG phụ thuộc pdf2zh — chỉ cần comet + sacrebleu + torch.
|
| 12 |
+
Có thể copy riêng file này + hypotheses.jsonl lên GPU box (A100...) để chấm nhanh:
|
| 13 |
+
|
| 14 |
+
# CPU (Mac):
|
| 15 |
+
python -m benchmark.translation.score_comet --hyp benchmark/translation/out/_all/hypotheses.jsonl --out comet_scores.json
|
| 16 |
+
# GPU (A100, nhanh gấp bội — 110k segment ~vài phút):
|
| 17 |
+
pip install unbabel-comet sacrebleu
|
| 18 |
+
python score_comet.py --hyp hypotheses.jsonl --out comet_scores.json --gpus 1 --batch-size 64
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
from __future__ import annotations
|
| 22 |
+
|
| 23 |
+
import argparse
|
| 24 |
+
import json
|
| 25 |
+
import statistics as stats
|
| 26 |
+
from collections import defaultdict
|
| 27 |
+
from pathlib import Path
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def _length_violation(translation: str, source: str, tol: float) -> bool:
|
| 31 |
+
"""Cùng logic với pdf2zh.translation.pipeline._length_violation (inline để
|
| 32 |
+
score_comet CHẠY ĐỘC LẬP trên GPU box — chỉ cần comet + sacrebleu + torch,
|
| 33 |
+
không cần cài cả pdf2zh)."""
|
| 34 |
+
if len(source) < 20:
|
| 35 |
+
return False
|
| 36 |
+
return abs(len(translation) - len(source)) / max(len(source), 1) > tol
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def load_hyp(path: Path) -> list[dict]:
|
| 40 |
+
rows = []
|
| 41 |
+
with open(path, encoding="utf-8") as f:
|
| 42 |
+
for line in f:
|
| 43 |
+
line = line.strip()
|
| 44 |
+
if line:
|
| 45 |
+
rows.append(json.loads(line))
|
| 46 |
+
return rows
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def comet_scores(rows: list[dict], model_name: str, batch_size: int, gpus: int,
|
| 50 |
+
num_workers: int = 2) -> list[float]:
|
| 51 |
+
from comet import download_model, load_from_checkpoint
|
| 52 |
+
ckpt = download_model(model_name)
|
| 53 |
+
model = load_from_checkpoint(ckpt)
|
| 54 |
+
data = [{"src": r["source"], "mt": r["hypothesis"], "ref": r["reference"]} for r in rows]
|
| 55 |
+
# num_workers > 0 explicitly: on CPU (gpus=0) COMET derives num_workers=2*gpus=0 but
|
| 56 |
+
# still passes multiprocessing_context, which newer torch rejects.
|
| 57 |
+
try:
|
| 58 |
+
out = model.predict(data, batch_size=batch_size, gpus=gpus, num_workers=num_workers)
|
| 59 |
+
except TypeError: # older comet without the num_workers kwarg
|
| 60 |
+
out = model.predict(data, batch_size=batch_size, gpus=gpus)
|
| 61 |
+
return list(out["scores"] if isinstance(out, dict) else out.scores)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def chrf_scores(rows: list[dict]) -> list[float]:
|
| 65 |
+
from sacrebleu.metrics import CHRF
|
| 66 |
+
chrf = CHRF(word_order=2) # chrF++
|
| 67 |
+
return [chrf.sentence_score(r["hypothesis"], [r["reference"]]).score for r in rows]
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def _agg(vals: list[float]) -> dict:
|
| 71 |
+
if not vals:
|
| 72 |
+
return {"n": 0, "mean": None, "median": None}
|
| 73 |
+
return {"n": len(vals), "mean": round(stats.mean(vals), 4),
|
| 74 |
+
"median": round(stats.median(vals), 4)}
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def summarize(rows: list[dict]) -> dict:
|
| 78 |
+
"""Group by system, then language(pair) and domain."""
|
| 79 |
+
by_sys: dict[str, list[dict]] = defaultdict(list)
|
| 80 |
+
for r in rows:
|
| 81 |
+
by_sys[r["system"]].append(r)
|
| 82 |
+
|
| 83 |
+
report: dict = {}
|
| 84 |
+
for system, rs in by_sys.items():
|
| 85 |
+
comet = [r["_comet"] for r in rs]
|
| 86 |
+
chrf = [r["_chrf"] for r in rs]
|
| 87 |
+
n = len(rs)
|
| 88 |
+
rel = {
|
| 89 |
+
"overall": {"comet": _agg(comet), "chrf": _agg(chrf),
|
| 90 |
+
"fallback_pct": round(100 * sum(r["is_fallback"] for r in rs) / n, 2),
|
| 91 |
+
"empty_pct": round(100 * sum(r["is_empty"] for r in rs) / n, 2),
|
| 92 |
+
"len_viol_pct": round(100 * sum(
|
| 93 |
+
_length_violation(r["hypothesis"], r["source"], 0.15) for r in rs) / n, 2)},
|
| 94 |
+
"by_language": {},
|
| 95 |
+
"by_domain": {},
|
| 96 |
+
}
|
| 97 |
+
for key, field in (("by_language", "pair"), ("by_domain", "domain")):
|
| 98 |
+
groups: dict[str, list[dict]] = defaultdict(list)
|
| 99 |
+
for r in rs:
|
| 100 |
+
groups[r[field]].append(r)
|
| 101 |
+
for g, gr in sorted(groups.items()):
|
| 102 |
+
rel[key][g] = {
|
| 103 |
+
"comet": _agg([x["_comet"] for x in gr]),
|
| 104 |
+
"chrf": _agg([x["_chrf"] for x in gr]),
|
| 105 |
+
"fallback_pct": round(100 * sum(x["is_fallback"] for x in gr) / len(gr), 2),
|
| 106 |
+
}
|
| 107 |
+
report[system] = rel
|
| 108 |
+
return report
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def print_tables(report: dict) -> None:
|
| 112 |
+
for system, rel in report.items():
|
| 113 |
+
o = rel["overall"]
|
| 114 |
+
print(f"\n=== {system} ===")
|
| 115 |
+
print(f" COMET-DA mean {o['comet']['mean']} | chrF++ mean {o['chrf']['mean']} "
|
| 116 |
+
f"| fallback {o['fallback_pct']}% empty {o['empty_pct']}% len-viol {o['len_viol_pct']}% "
|
| 117 |
+
f"(n={o['comet']['n']})")
|
| 118 |
+
if len(rel["by_language"]) > 1:
|
| 119 |
+
print(" per-language (COMET-DA mean):")
|
| 120 |
+
for lang, m in rel["by_language"].items():
|
| 121 |
+
print(f" {lang:<12} {m['comet']['mean']} (chrF {m['chrf']['mean']}, "
|
| 122 |
+
f"fallback {m['fallback_pct']}%, n={m['comet']['n']})")
|
| 123 |
+
print(" per-domain (COMET-DA mean):")
|
| 124 |
+
for dom, m in rel["by_domain"].items():
|
| 125 |
+
print(f" {dom:<10} {m['comet']['mean']} (n={m['comet']['n']})")
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def main() -> None:
|
| 129 |
+
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 130 |
+
ap.add_argument("--hyp", default="benchmark/translation/out/hypotheses.jsonl")
|
| 131 |
+
ap.add_argument("--out", default="benchmark/translation/out/comet_scores.json")
|
| 132 |
+
ap.add_argument("--model", default="Unbabel/wmt22-comet-da")
|
| 133 |
+
ap.add_argument("--batch-size", type=int, default=16)
|
| 134 |
+
ap.add_argument("--gpus", type=int, default=0, help="0 = CPU (an toàn trên Mac); >0 nếu có CUDA")
|
| 135 |
+
ap.add_argument("--num-workers", type=int, default=2, help="DataLoader workers (>0 để né bug torch mới)")
|
| 136 |
+
ap.add_argument("--no-comet", action="store_true", help="Chỉ chrF (bỏ qua tải model COMET)")
|
| 137 |
+
args = ap.parse_args()
|
| 138 |
+
|
| 139 |
+
rows = load_hyp(Path(args.hyp))
|
| 140 |
+
print(f"Loaded {len(rows)} segments from {args.hyp}")
|
| 141 |
+
|
| 142 |
+
chrf = chrf_scores(rows)
|
| 143 |
+
for r, c in zip(rows, chrf):
|
| 144 |
+
r["_chrf"] = c
|
| 145 |
+
if args.no_comet:
|
| 146 |
+
for r in rows:
|
| 147 |
+
r["_comet"] = float("nan")
|
| 148 |
+
else:
|
| 149 |
+
print(f"Scoring COMET ({args.model}, gpus={args.gpus}) — có thể mất vài phút...")
|
| 150 |
+
cs = comet_scores(rows, args.model, args.batch_size, args.gpus, args.num_workers)
|
| 151 |
+
for r, c in zip(rows, cs):
|
| 152 |
+
r["_comet"] = c
|
| 153 |
+
|
| 154 |
+
report = summarize(rows)
|
| 155 |
+
Path(args.out).parent.mkdir(parents=True, exist_ok=True)
|
| 156 |
+
with open(args.out, "w", encoding="utf-8") as f:
|
| 157 |
+
json.dump(report, f, ensure_ascii=False, indent=2)
|
| 158 |
+
print_tables(report)
|
| 159 |
+
print(f"\nSaved -> {args.out}")
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
if __name__ == "__main__":
|
| 163 |
+
main()
|
benchmark/translation/wmt24pp_adapter.py
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""WMT24++ → `doc` adapter (the crux: reuse the translation core unchanged).
|
| 2 |
+
|
| 3 |
+
Loads a WMT24++ language-pair file (`en-<xx>.jsonl`), filters bad sources, groups
|
| 4 |
+
segments by `document_id`, and wraps each document into the exact `doc` dict that
|
| 5 |
+
`translate_document` consumes. After translation, extracts the hypothesis per segment
|
| 6 |
+
aligned 1:1 with the reference.
|
| 7 |
+
|
| 8 |
+
No dependency on `datasets` for loading: the jsonl is fetched directly with httpx
|
| 9 |
+
(already a project dep) and cached locally. `datasets` is only needed if you want to
|
| 10 |
+
enumerate all configs via `list_all_pairs()`.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
from __future__ import annotations
|
| 14 |
+
|
| 15 |
+
import json
|
| 16 |
+
import logging
|
| 17 |
+
from dataclasses import dataclass, field
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
|
| 20 |
+
import httpx
|
| 21 |
+
|
| 22 |
+
logger = logging.getLogger("benchmark.translation.adapter")
|
| 23 |
+
|
| 24 |
+
HF_BASE = "https://huggingface.co/datasets/google/wmt24pp/resolve/main"
|
| 25 |
+
CACHE_DIR = Path(__file__).parent / ".cache_wmt24pp"
|
| 26 |
+
|
| 27 |
+
# Target-locale -> full English language name (interpolated into the prompt).
|
| 28 |
+
# Best-effort cover of the WMT24++ 55 locales; validate against
|
| 29 |
+
# `datasets.get_dataset_config_names("google/wmt24pp")` before a full sweep.
|
| 30 |
+
LOCALE_NAME: dict[str, str] = {
|
| 31 |
+
"ar_EG": "Egyptian Arabic", "ar_SA": "Arabic", "bg_BG": "Bulgarian",
|
| 32 |
+
"bn_IN": "Bengali", "ca_ES": "Catalan", "cs_CZ": "Czech", "da_DK": "Danish",
|
| 33 |
+
"de_DE": "German", "el_GR": "Greek", "es_MX": "Mexican Spanish",
|
| 34 |
+
"et_EE": "Estonian", "fa_IR": "Persian", "fi_FI": "Finnish",
|
| 35 |
+
"fil_PH": "Filipino", "fr_CA": "Canadian French", "fr_FR": "French",
|
| 36 |
+
"gu_IN": "Gujarati", "he_IL": "Hebrew", "hi_IN": "Hindi", "hr_HR": "Croatian",
|
| 37 |
+
"hu_HU": "Hungarian", "id_ID": "Indonesian", "is_IS": "Icelandic",
|
| 38 |
+
"it_IT": "Italian", "ja_JP": "Japanese", "kn_IN": "Kannada", "ko_KR": "Korean",
|
| 39 |
+
"lt_LT": "Lithuanian", "lv_LV": "Latvian", "ml_IN": "Malayalam",
|
| 40 |
+
"mr_IN": "Marathi", "nl_NL": "Dutch", "no_NO": "Norwegian", "pa_IN": "Punjabi",
|
| 41 |
+
"pl_PL": "Polish", "pt_BR": "Brazilian Portuguese", "pt_PT": "Portuguese",
|
| 42 |
+
"ro_RO": "Romanian", "ru_RU": "Russian", "sk_SK": "Slovak", "sl_SI": "Slovenian",
|
| 43 |
+
"sr_RS": "Serbian", "sv_SE": "Swedish", "sw_KE": "Swahili", "sw_TZ": "Swahili",
|
| 44 |
+
"ta_IN": "Tamil",
|
| 45 |
+
"te_IN": "Telugu", "th_TH": "Thai", "tr_TR": "Turkish", "uk_UA": "Ukrainian",
|
| 46 |
+
"ur_PK": "Urdu", "vi_VN": "Vietnamese", "zh_CN": "Simplified Chinese",
|
| 47 |
+
"zh_TW": "Traditional Chinese", "zu_ZA": "Zulu",
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
# Minimal fallback for an unmapped locale's base subtag.
|
| 51 |
+
_BASE_NAME = {
|
| 52 |
+
"ar": "Arabic", "zh": "Chinese", "pt": "Portuguese", "fr": "French",
|
| 53 |
+
"es": "Spanish", "en": "English",
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def language_name(locale: str) -> str:
|
| 58 |
+
"""Full language name for a target locale like 'vi_VN'. Falls back to the base
|
| 59 |
+
subtag name, else the locale string itself (with a warning)."""
|
| 60 |
+
if locale in LOCALE_NAME:
|
| 61 |
+
return LOCALE_NAME[locale]
|
| 62 |
+
base = locale.split("_")[0]
|
| 63 |
+
if base in _BASE_NAME:
|
| 64 |
+
return _BASE_NAME[base]
|
| 65 |
+
logger.warning("No language name for locale %r; using it verbatim in the prompt.", locale)
|
| 66 |
+
return locale
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
@dataclass
|
| 70 |
+
class SegRecord:
|
| 71 |
+
"""One aligned segment: source, reference, and where it came from."""
|
| 72 |
+
|
| 73 |
+
pair: str # e.g. "en-vi_VN"
|
| 74 |
+
document_id: str
|
| 75 |
+
seg_index: int # order within the document (== internal task id)
|
| 76 |
+
source: str
|
| 77 |
+
reference: str # WMT24++ post-edit `target`
|
| 78 |
+
domain: str
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
@dataclass
|
| 82 |
+
class DocBundle:
|
| 83 |
+
"""All segments of one WMT24++ document + the built `doc` dict."""
|
| 84 |
+
|
| 85 |
+
pair: str
|
| 86 |
+
document_id: str
|
| 87 |
+
segs: list[SegRecord]
|
| 88 |
+
doc: dict = field(default_factory=dict)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def pair_config(target_locale: str) -> str:
|
| 92 |
+
"""WMT24++ config/file stem for an English->target pair."""
|
| 93 |
+
return f"en-{target_locale}"
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def _download_jsonl(pair: str) -> Path:
|
| 97 |
+
CACHE_DIR.mkdir(parents=True, exist_ok=True)
|
| 98 |
+
dest = CACHE_DIR / f"{pair}.jsonl"
|
| 99 |
+
if dest.exists() and dest.stat().st_size > 0:
|
| 100 |
+
return dest
|
| 101 |
+
url = f"{HF_BASE}/{pair}.jsonl"
|
| 102 |
+
logger.info("Downloading %s", url)
|
| 103 |
+
with httpx.stream("GET", url, timeout=120, follow_redirects=True) as r:
|
| 104 |
+
r.raise_for_status()
|
| 105 |
+
with open(dest, "wb") as f:
|
| 106 |
+
for chunk in r.iter_bytes():
|
| 107 |
+
f.write(chunk)
|
| 108 |
+
return dest
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def load_pair(
|
| 112 |
+
target_locale: str,
|
| 113 |
+
*,
|
| 114 |
+
drop_bad_source: bool = True,
|
| 115 |
+
) -> list[DocBundle]:
|
| 116 |
+
"""Load one pair, filter bad sources, group into documents (order preserved).
|
| 117 |
+
|
| 118 |
+
Returns a list of DocBundle, each with its `doc` dict ready for translate_document.
|
| 119 |
+
"""
|
| 120 |
+
pair = pair_config(target_locale)
|
| 121 |
+
path = _download_jsonl(pair)
|
| 122 |
+
tgt_name = language_name(target_locale)
|
| 123 |
+
|
| 124 |
+
rows: list[dict] = []
|
| 125 |
+
with open(path, encoding="utf-8") as f:
|
| 126 |
+
for line in f:
|
| 127 |
+
line = line.strip()
|
| 128 |
+
if line:
|
| 129 |
+
rows.append(json.loads(line))
|
| 130 |
+
|
| 131 |
+
n_total = len(rows)
|
| 132 |
+
if drop_bad_source:
|
| 133 |
+
rows = [r for r in rows if not r.get("is_bad_source", False)]
|
| 134 |
+
logger.info("%s: %d rows (%d after is_bad_source filter)", pair, n_total, len(rows))
|
| 135 |
+
|
| 136 |
+
# Group by document_id, preserving first-seen order and within-doc order.
|
| 137 |
+
docs: dict[str, list[dict]] = {}
|
| 138 |
+
for r in rows:
|
| 139 |
+
docs.setdefault(str(r.get("document_id", "0")), []).append(r)
|
| 140 |
+
|
| 141 |
+
bundles: list[DocBundle] = []
|
| 142 |
+
for doc_id, seg_rows in docs.items():
|
| 143 |
+
segs = [
|
| 144 |
+
SegRecord(
|
| 145 |
+
pair=pair,
|
| 146 |
+
document_id=doc_id,
|
| 147 |
+
seg_index=i,
|
| 148 |
+
source=sr["source"],
|
| 149 |
+
reference=sr.get("target", sr.get("original_target", "")),
|
| 150 |
+
domain=sr.get("domain", "unknown"),
|
| 151 |
+
)
|
| 152 |
+
for i, sr in enumerate(seg_rows)
|
| 153 |
+
]
|
| 154 |
+
doc = {
|
| 155 |
+
"source_language": "English",
|
| 156 |
+
"target_language": tgt_name,
|
| 157 |
+
"pages": [{"elements": [
|
| 158 |
+
{"category": "TEXT", "source_text": s.source} for s in segs
|
| 159 |
+
]}],
|
| 160 |
+
}
|
| 161 |
+
bundles.append(DocBundle(pair=pair, document_id=doc_id, segs=segs, doc=doc))
|
| 162 |
+
return bundles
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def extract_hypotheses(bundle: DocBundle) -> list[dict]:
|
| 166 |
+
"""After translate_document mutated bundle.doc in place, read back the hypothesis
|
| 167 |
+
per element (aligned 1:1 with segments) and pair it with the reference.
|
| 168 |
+
|
| 169 |
+
`collect_translatables` walks pages->elements in order and writes into
|
| 170 |
+
element['translated_text'], so element[i] corresponds to segs[i].
|
| 171 |
+
"""
|
| 172 |
+
elements = bundle.doc["pages"][0]["elements"]
|
| 173 |
+
out: list[dict] = []
|
| 174 |
+
for seg, elem in zip(bundle.segs, elements):
|
| 175 |
+
hyp = elem.get("translated_text", "")
|
| 176 |
+
out.append({
|
| 177 |
+
"pair": seg.pair,
|
| 178 |
+
"document_id": seg.document_id,
|
| 179 |
+
"seg_index": seg.seg_index,
|
| 180 |
+
"domain": seg.domain,
|
| 181 |
+
"source": seg.source,
|
| 182 |
+
"reference": seg.reference,
|
| 183 |
+
"hypothesis": hyp,
|
| 184 |
+
# pipeline falls back to source when it can't translate an id.
|
| 185 |
+
"is_fallback": bool(hyp) and hyp == seg.source,
|
| 186 |
+
"is_empty": not hyp,
|
| 187 |
+
})
|
| 188 |
+
return out
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def list_all_pairs() -> list[str]:
|
| 192 |
+
"""All target locales available in google/wmt24pp (needs `datasets`)."""
|
| 193 |
+
try:
|
| 194 |
+
from datasets import get_dataset_config_names
|
| 195 |
+
except ImportError as exc: # pragma: no cover
|
| 196 |
+
raise RuntimeError(
|
| 197 |
+
"list_all_pairs() needs `datasets`; or pass locales explicitly from LOCALE_NAME."
|
| 198 |
+
) from exc
|
| 199 |
+
configs = get_dataset_config_names("google/wmt24pp")
|
| 200 |
+
return [c.split("en-", 1)[1] for c in configs if c.startswith("en-")]
|
docker-compose.yml
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This is the final, recommended configuration.
|
| 2 |
+
# It builds a single, self-contained image with all dependencies.
|
| 3 |
+
|
| 4 |
+
services:
|
| 5 |
+
pdf2zh:
|
| 6 |
+
build:
|
| 7 |
+
context: .
|
| 8 |
+
# All the setup steps are now part of a one-time build process.
|
| 9 |
+
dockerfile_inline: |
|
| 10 |
+
FROM ghcr.io/astral-sh/uv:python3.12-bookworm-slim
|
| 11 |
+
|
| 12 |
+
WORKDIR /app
|
| 13 |
+
|
| 14 |
+
# 1. Install system-level dependencies FIRST.
|
| 15 |
+
# This is what solves the "libGL.so.1 not found" error.
|
| 16 |
+
RUN apt-get update && \
|
| 17 |
+
apt-get install --no-install-recommends -y libgl1 libglib2.0-0 libxext6 libsm6 libxrender1 && \
|
| 18 |
+
rm -rf /var/lib/apt/lists/*
|
| 19 |
+
|
| 20 |
+
# 2. Copy only the dependency file and install Python packages.
|
| 21 |
+
# This layer is cached and only re-runs if pyproject.toml changes.
|
| 22 |
+
COPY pyproject.toml .
|
| 23 |
+
RUN uv pip install --system --no-cache -r pyproject.toml
|
| 24 |
+
|
| 25 |
+
# 3. Copy the rest of your application code.
|
| 26 |
+
COPY . .
|
| 27 |
+
|
| 28 |
+
# 4. Install the local package and perform final updates/warmups.
|
| 29 |
+
RUN uv pip install --system --no-cache . && \
|
| 30 |
+
uv pip install --system --no-cache -U "babeldoc<0.3.0" "pymupdf<1.25.3" "pdfminer-six==20250416" && \
|
| 31 |
+
babeldoc --warmup
|
| 32 |
+
|
| 33 |
+
# The rest of the configuration is for RUNNING the built image.
|
| 34 |
+
ports:
|
| 35 |
+
- "7860:7860"
|
| 36 |
+
|
| 37 |
+
environment:
|
| 38 |
+
- PYTHONUNBUFFERED=1
|
| 39 |
+
# The UV_LINK_MODE warning happens during build, so we can set it there if needed,
|
| 40 |
+
# but it's generally harmless.
|
| 41 |
+
|
| 42 |
+
command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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[**Documentation**](https://github.com/Byaidu/PDFMathTranslate) > **Advanced Usage** _(current)_
|
| 2 |
+
|
| 3 |
+
---
|
| 4 |
+
|
| 5 |
+
<h3 id="toc">Table of Contents</h3>
|
| 6 |
+
|
| 7 |
+
- [Full / partial translation](#partial)
|
| 8 |
+
- [Specify source and target languages](#language)
|
| 9 |
+
- [Translate with different services](#services)
|
| 10 |
+
- [Translate wih exceptions](#exceptions)
|
| 11 |
+
- [Multi-threads](#threads)
|
| 12 |
+
- [Custom prompt](#prompt)
|
| 13 |
+
- [Authorization](#auth)
|
| 14 |
+
- [Custom configuration file](#cofig)
|
| 15 |
+
- [Fonts Subseting](#fonts-subset)
|
| 16 |
+
- [Translation cache](#cache)
|
| 17 |
+
|
| 18 |
+
---
|
| 19 |
+
|
| 20 |
+
<h3 id="partial">Full / partial translation</h3>
|
| 21 |
+
|
| 22 |
+
- Entire document
|
| 23 |
+
|
| 24 |
+
```bash
|
| 25 |
+
pdf2zh example.pdf
|
| 26 |
+
```
|
| 27 |
+
|
| 28 |
+
- Part of the document
|
| 29 |
+
|
| 30 |
+
```bash
|
| 31 |
+
pdf2zh example.pdf -p 1-3,5
|
| 32 |
+
```
|
| 33 |
+
|
| 34 |
+
[⬆️ Back to top](#toc)
|
| 35 |
+
|
| 36 |
+
---
|
| 37 |
+
|
| 38 |
+
<h3 id="language">Specify source and target languages</h3>
|
| 39 |
+
|
| 40 |
+
See [Google Languages Codes](https://developers.google.com/admin-sdk/directory/v1/languages), [DeepL Languages Codes](https://developers.deepl.com/docs/resources/supported-languages)
|
| 41 |
+
|
| 42 |
+
```bash
|
| 43 |
+
pdf2zh example.pdf -li en -lo ja
|
| 44 |
+
```
|
| 45 |
+
|
| 46 |
+
[⬆️ Back to top](#toc)
|
| 47 |
+
|
| 48 |
+
---
|
| 49 |
+
|
| 50 |
+
<h3 id="services">Translate with different services</h3>
|
| 51 |
+
|
| 52 |
+
We've provided a detailed table on the required [environment variables](https://chatgpt.com/share/6734a83d-9d48-800e-8a46-f57ca6e8bcb4) for each translation service. Make sure to set them before using the respective service.
|
| 53 |
+
|
| 54 |
+
| **Translator** | **Service** | **Environment Variables** | **Default Values** | **Notes** |
|
| 55 |
+
|----------------------|----------------|-----------------------------------------------------------------------|----------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
| 56 |
+
| **Google (Default)** | `google` | None | N/A | None |
|
| 57 |
+
| **Bing** | `bing` | None | N/A | None |
|
| 58 |
+
| **302.AI** | `302ai` | `X302AI_API_KEY`, `X302AI_MODEL` | `[Your Key]`, `Gemma-7B` | See [302.AI](https://share.302.ai/tqTWfD) |
|
| 59 |
+
| **OpenAI** | `openai` | `OPENAI_BASE_URL`, `OPENAI_API_KEY`, `OPENAI_MODEL` | `https://api.openai.com/v1`, `[Your Key]`, `gpt-4o-mini` | See [OpenAI](https://platform.openai.com/docs/overview) |
|
| 60 |
+
| **DeepL** | `deepl` | `DEEPL_AUTH_KEY` | `[Your Key]` | See [DeepL](https://support.deepl.com/hc/en-us/articles/360020695820-API-Key-for-DeepL-s-API) |
|
| 61 |
+
| **DeepLX** | `deeplx` | `DEEPLX_ENDPOINT` | `https://api.deepl.com/translate` | See [DeepLX](https://github.com/OwO-Network/DeepLX) |
|
| 62 |
+
| **Ollama** | `ollama` | `OLLAMA_HOST`, `OLLAMA_MODEL` | `http://127.0.0.1:11434`, `gemma2` | See [Ollama](https://github.com/ollama/ollama) |
|
| 63 |
+
| **Xinference** | `xinference` | `XINFERENCE_HOST`, `XINFERENCE_MODEL` | `http://127.0.0.1:9997`, `gemma-2-it` | See [Xinference](https://github.com/xorbitsai/inference) |
|
| 64 |
+
| **AzureOpenAI** | `azure-openai` | `AZURE_OPENAI_BASE_URL`, `AZURE_OPENAI_API_KEY`, `AZURE_OPENAI_MODEL` | `[Your Endpoint]`, `[Your Key]`, `gpt-4o-mini` | See [Azure OpenAI](https://learn.microsoft.com/zh-cn/azure/ai-services/openai/chatgpt-quickstart?tabs=command-line%2Cjavascript-keyless%2Ctypescript-keyless%2Cpython&pivots=programming-language-python) |
|
| 65 |
+
| **Zhipu** | `zhipu` | `ZHIPU_API_KEY`, `ZHIPU_MODEL` | `[Your Key]`, `glm-4-flash` | See [Zhipu](https://open.bigmodel.cn/dev/api/thirdparty-frame/openai-sdk) |
|
| 66 |
+
| **ModelScope** | `modelscope` | `MODELSCOPE_API_KEY`, `MODELSCOPE_MODEL` | `[Your Key]`, `Qwen/Qwen2.5-Coder-32B-Instruct` | See [ModelScope](https://www.modelscope.cn/docs/model-service/API-Inference/intro) |
|
| 67 |
+
| **Silicon** | `silicon` | `SILICON_API_KEY`, `SILICON_MODEL` | `[Your Key]`, `Qwen/Qwen2.5-7B-Instruct` | See [SiliconCloud](https://docs.siliconflow.cn/quickstart) |
|
| 68 |
+
| **Gemini** | `gemini` | `GEMINI_API_KEY`, `GEMINI_MODEL` | `[Your Key]`, `gemini-1.5-flash` | See [Gemini](https://ai.google.dev/gemini-api/docs/openai) |
|
| 69 |
+
| **Azure** | `azure` | `AZURE_ENDPOINT`, `AZURE_API_KEY` | `https://api.translator.azure.cn`, `[Your Key]` | See [Azure](https://docs.azure.cn/en-us/ai-services/translator/text-translation-overview) |
|
| 70 |
+
| **Tencent** | `tencent` | `TENCENTCLOUD_SECRET_ID`, `TENCENTCLOUD_SECRET_KEY` | `[Your ID]`, `[Your Key]` | See [Tencent](https://www.tencentcloud.com/products/tmt?from_qcintl=122110104) |
|
| 71 |
+
| **Dify** | `dify` | `DIFY_API_URL`, `DIFY_API_KEY` | `[Your DIFY URL]`, `[Your Key]` | See [Dify](https://github.com/langgenius/dify),Three variables, lang_out, lang_in, and text, need to be defined in Dify's workflow input. |
|
| 72 |
+
| **AnythingLLM** | `anythingllm` | `AnythingLLM_URL`, `AnythingLLM_APIKEY` | `[Your AnythingLLM URL]`, `[Your Key]` | See [anything-llm](https://github.com/Mintplex-Labs/anything-llm) |
|
| 73 |
+
|**Argos Translate**|`argos`| | |See [argos-translate](https://github.com/argosopentech/argos-translate)|
|
| 74 |
+
|**Grok**|`grok`| `GORK_API_KEY`, `GORK_MODEL` | `[Your GORK_API_KEY]`, `grok-2-1212` |See [Grok](https://docs.x.ai/docs/overview)|
|
| 75 |
+
|**Groq**|`groq`| `GROQ_API_KEY`, `GROQ_MODEL` | `[Your GROQ_API_KEY]`, `llama-3-3-70b-versatile` |See [Groq](https://console.groq.com/docs/models)|
|
| 76 |
+
|**DeepSeek**|`deepseek`| `DEEPSEEK_API_KEY`, `DEEPSEEK_MODEL` | `[Your DEEPSEEK_API_KEY]`, `deepseek-chat` |See [DeepSeek](https://www.deepseek.com/)|
|
| 77 |
+
|**OpenAI-Liked**|`openailiked`| `OPENAILIKED_BASE_URL`, `OPENAILIKED_API_KEY`, `OPENAILIKED_MODEL` | `url`, `[Your Key]`, `model name` | None |
|
| 78 |
+
|**Ali Qwen Translation**|`qwen-mt`| `ALI_MODEL`, `ALI_API_KEY`, `ALI_DOMAINS` | `qwen-mt-turbo`, `[Your Key]`, `scientific paper` | Tranditional Chinese are not yet supported, it will be translated into Simplified Chinese. More see [Qwen MT](https://bailian.console.aliyun.com/?spm=5176.28197581.0.0.72e329a4HRxe99#/model-market/detail/qwen-mt-turbo) |
|
| 79 |
+
|
| 80 |
+
For large language models that are compatible with the OpenAI API but not listed in the table above, you can set environment variables using the same method outlined for OpenAI in the table.
|
| 81 |
+
|
| 82 |
+
Use `-s service` or `-s service:model` to specify service:
|
| 83 |
+
|
| 84 |
+
```bash
|
| 85 |
+
pdf2zh example.pdf -s openai:gpt-4o-mini
|
| 86 |
+
```
|
| 87 |
+
|
| 88 |
+
Or specify model with environment variables:
|
| 89 |
+
|
| 90 |
+
```bash
|
| 91 |
+
set OPENAI_MODEL=gpt-4o-mini
|
| 92 |
+
pdf2zh example.pdf -s openai
|
| 93 |
+
```
|
| 94 |
+
|
| 95 |
+
For PowerShell user:
|
| 96 |
+
|
| 97 |
+
```shell
|
| 98 |
+
$env:OPENAI_MODEL = gpt-4o-mini
|
| 99 |
+
pdf2zh example.pdf -s openai
|
| 100 |
+
```
|
| 101 |
+
|
| 102 |
+
[⬆️ Back to top](#toc)
|
| 103 |
+
|
| 104 |
+
---
|
| 105 |
+
|
| 106 |
+
<h3 id="exceptions">Translate wih exceptions</h3>
|
| 107 |
+
|
| 108 |
+
Use regex to specify formula fonts and characters that need to be preserved:
|
| 109 |
+
|
| 110 |
+
```bash
|
| 111 |
+
pdf2zh example.pdf -f "(CM[^RT].*|MS.*|.*Ital)" -c "(\(|\||\)|\+|=|\d|[\u0080-\ufaff])"
|
| 112 |
+
```
|
| 113 |
+
|
| 114 |
+
Preserve `Latex`, `Mono`, `Code`, `Italic`, `Symbol` and `Math` fonts by default:
|
| 115 |
+
|
| 116 |
+
```bash
|
| 117 |
+
pdf2zh example.pdf -f "(CM[^R]|MS.M|XY|MT|BL|RM|EU|LA|RS|LINE|LCIRCLE|TeX-|rsfs|txsy|wasy|stmary|.*Mono|.*Code|.*Ital|.*Sym|.*Math)"
|
| 118 |
+
```
|
| 119 |
+
|
| 120 |
+
[⬆️ Back to top](#toc)
|
| 121 |
+
|
| 122 |
+
---
|
| 123 |
+
|
| 124 |
+
<h3 id="threads">Multi-threads</h3>
|
| 125 |
+
|
| 126 |
+
Use `-t` to specify how many threads to use in translation:
|
| 127 |
+
|
| 128 |
+
```bash
|
| 129 |
+
pdf2zh example.pdf -t 1
|
| 130 |
+
```
|
| 131 |
+
|
| 132 |
+
[⬆️ Back to top](#toc)
|
| 133 |
+
|
| 134 |
+
---
|
| 135 |
+
|
| 136 |
+
<h3 id="prompt">Custom prompt</h3>
|
| 137 |
+
|
| 138 |
+
Note: System prompt is currently not supported. See [this change](https://github.com/Byaidu/PDFMathTranslate/pull/637).
|
| 139 |
+
|
| 140 |
+
Use `--prompt` to specify which prompt to use in llm:
|
| 141 |
+
|
| 142 |
+
```bash
|
| 143 |
+
pdf2zh example.pdf --prompt prompt.txt
|
| 144 |
+
```
|
| 145 |
+
|
| 146 |
+
For example:
|
| 147 |
+
|
| 148 |
+
```txt
|
| 149 |
+
You are a professional, authentic machine translation engine. Only Output the translated text, do not include any other text.
|
| 150 |
+
|
| 151 |
+
Translate the following markdown source text to ${lang_out}. Keep the formula notation {v*} unchanged. Output translation directly without any additional text.
|
| 152 |
+
|
| 153 |
+
Source Text: ${text}
|
| 154 |
+
|
| 155 |
+
Translated Text:
|
| 156 |
+
```
|
| 157 |
+
|
| 158 |
+
In custom prompt file, there are three variables can be used.
|
| 159 |
+
|
| 160 |
+
|**variables**|**comment**|
|
| 161 |
+
|-|-|
|
| 162 |
+
|`lang_in`|input language|
|
| 163 |
+
|`lang_out`|output language|
|
| 164 |
+
|`text`|text need to be translated|
|
| 165 |
+
|
| 166 |
+
[⬆️ Back to top](#toc)
|
| 167 |
+
|
| 168 |
+
---
|
| 169 |
+
|
| 170 |
+
<h3 id="auth">Authorization</h3>
|
| 171 |
+
|
| 172 |
+
Use `--authorized` to specify which user to use Web UI and custom the login page:
|
| 173 |
+
|
| 174 |
+
```bash
|
| 175 |
+
pdf2zh example.pdf --authorized users.txt auth.html
|
| 176 |
+
```
|
| 177 |
+
|
| 178 |
+
example users.txt
|
| 179 |
+
Each line contains two elements, username, and password, separated by a comma.
|
| 180 |
+
|
| 181 |
+
```
|
| 182 |
+
admin,123456
|
| 183 |
+
user1,password1
|
| 184 |
+
user2,abc123
|
| 185 |
+
guest,guest123
|
| 186 |
+
test,test123
|
| 187 |
+
```
|
| 188 |
+
|
| 189 |
+
example auth.html
|
| 190 |
+
|
| 191 |
+
```html
|
| 192 |
+
<!DOCTYPE html>
|
| 193 |
+
<html>
|
| 194 |
+
<head>
|
| 195 |
+
<title>Simple HTML</title>
|
| 196 |
+
</head>
|
| 197 |
+
<body>
|
| 198 |
+
<h1>Hello, World!</h1>
|
| 199 |
+
<p>Welcome to my simple HTML page.</p>
|
| 200 |
+
</body>
|
| 201 |
+
</html>
|
| 202 |
+
```
|
| 203 |
+
|
| 204 |
+
[⬆️ Back to top](#toc)
|
| 205 |
+
|
| 206 |
+
---
|
| 207 |
+
|
| 208 |
+
<h3 id="cofig">Custom configuration file</h3>
|
| 209 |
+
|
| 210 |
+
Use `--config` to specify which file to configure the PDFMathTranslate:
|
| 211 |
+
|
| 212 |
+
```bash
|
| 213 |
+
pdf2zh example.pdf --config config.json
|
| 214 |
+
```
|
| 215 |
+
|
| 216 |
+
```bash
|
| 217 |
+
pdf2zh -i --config config.json
|
| 218 |
+
```
|
| 219 |
+
|
| 220 |
+
example config.json
|
| 221 |
+
|
| 222 |
+
```json
|
| 223 |
+
{
|
| 224 |
+
"USE_MODELSCOPE": "0",
|
| 225 |
+
"PDF2ZH_LANG_FROM": "English",
|
| 226 |
+
"PDF2ZH_LANG_TO": "Simplified Chinese",
|
| 227 |
+
"NOTO_FONT_PATH": "/app/SourceHanSerifCN-Regular.ttf",
|
| 228 |
+
"translators": [
|
| 229 |
+
{
|
| 230 |
+
"name": "deeplx",
|
| 231 |
+
"envs": {
|
| 232 |
+
"DEEPLX_ENDPOINT": "http://localhost:1188/translate/",
|
| 233 |
+
"DEEPLX_ACCESS_TOKEN": null
|
| 234 |
+
}
|
| 235 |
+
},
|
| 236 |
+
{
|
| 237 |
+
"name": "ollama",
|
| 238 |
+
"envs": {
|
| 239 |
+
"OLLAMA_HOST": "http://127.0.0.1:11434",
|
| 240 |
+
"OLLAMA_MODEL": "gemma2"
|
| 241 |
+
}
|
| 242 |
+
}
|
| 243 |
+
]
|
| 244 |
+
}
|
| 245 |
+
```
|
| 246 |
+
|
| 247 |
+
By default, the config file is saved in the `~/.config/PDFMathTranslate/config.json`. The program will start by reading the contents of config.json, and after that it will read the contents of the environment variables. When an environment variable is available, the contents of the environment variable are used first and the file is updated.
|
| 248 |
+
|
| 249 |
+
[⬆️ Back to top](#toc)
|
| 250 |
+
|
| 251 |
+
---
|
| 252 |
+
|
| 253 |
+
<h3 id="font-subset">Fonts subsetting</h3>
|
| 254 |
+
|
| 255 |
+
By default, PDFMathTranslate uses fonts subsetting to decrease sizes of output files. You can use `--skip-subset-fonts` option to disable fonts subsetting when encoutering compatibility issues.
|
| 256 |
+
|
| 257 |
+
```bash
|
| 258 |
+
pdf2zh example.pdf --skip-subset-fonts
|
| 259 |
+
```
|
| 260 |
+
|
| 261 |
+
[⬆️ Back to top](#toc)
|
| 262 |
+
|
| 263 |
+
---
|
| 264 |
+
|
| 265 |
+
<h3 id="cache">Translation cache</h3>
|
| 266 |
+
|
| 267 |
+
PDFMathTranslate caches translated texts to increase speed and avoid unnecessary API calls for same contents. You can use `--ignore-cache` option to ignore translation cache and force retranslation.
|
| 268 |
+
|
| 269 |
+
```bash
|
| 270 |
+
pdf2zh example.pdf --ignore-cache
|
| 271 |
+
```
|
| 272 |
+
|
| 273 |
+
[⬆️ Back to top](#toc)
|
| 274 |
+
|
| 275 |
+
---
|
| 276 |
+
|
| 277 |
+
<h3 id="public-services">Deployment as a public services</h3>
|
| 278 |
+
|
| 279 |
+
PDFMathTranslate has added the features of **enabling partial services** and **hiding Backend information** in
|
| 280 |
+
the configuration file. You can enable these by setting `ENABLED_SERVICES` and `HIDDEN_GRADIO_DETAILS` in the
|
| 281 |
+
configuration file. Among them:
|
| 282 |
+
|
| 283 |
+
- `ENABLED_SERVICES` allows you to choose to enable only certain options, limiting the number of available services.
|
| 284 |
+
- `HIDDEN_GRADIO_DETAILS` will hide the real API_KEY on the web, preventing users from obtaining server-side keys.
|
| 285 |
+
|
| 286 |
+
A usable configuration is as follows:
|
| 287 |
+
|
| 288 |
+
```json
|
| 289 |
+
{
|
| 290 |
+
"USE_MODELSCOPE": "0",
|
| 291 |
+
"translators": [
|
| 292 |
+
{
|
| 293 |
+
"name": "grok",
|
| 294 |
+
"envs": {
|
| 295 |
+
"GORK_API_KEY": null,
|
| 296 |
+
"GORK_MODEL": "grok-2-1212"
|
| 297 |
+
}
|
| 298 |
+
},
|
| 299 |
+
{
|
| 300 |
+
"name": "openai",
|
| 301 |
+
"envs": {
|
| 302 |
+
"OPENAI_BASE_URL": "https://api.openai.com/v1",
|
| 303 |
+
"OPENAI_API_KEY": "sk-xxxx",
|
| 304 |
+
"OPENAI_MODEL": "gpt-4o-mini"
|
| 305 |
+
}
|
| 306 |
+
}
|
| 307 |
+
],
|
| 308 |
+
"ENABLED_SERVICES": [
|
| 309 |
+
"OpenAI",
|
| 310 |
+
"Grok"
|
| 311 |
+
],
|
| 312 |
+
"HIDDEN_GRADIO_DETAILS": true,
|
| 313 |
+
"PDF2ZH_LANG_FROM": "English",
|
| 314 |
+
"PDF2ZH_LANG_TO": "Simplified Chinese",
|
| 315 |
+
"NOTO_FONT_PATH": "/app/SourceHanSerifCN-Regular.ttf"
|
| 316 |
+
}
|
| 317 |
+
```
|
| 318 |
+
|
| 319 |
+
[⬆️ Back to top](#toc)
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
---
|
| 323 |
+
|
| 324 |
+
<h3 id="mcp">MCP</h3>
|
| 325 |
+
|
| 326 |
+
PDFMathTranslate can run as MCP server. To use this, you need to run `uv pip install pdf2zh`, and config `claude_desktop_config.json`, an example config is as follows:
|
| 327 |
+
|
| 328 |
+
``` json
|
| 329 |
+
{
|
| 330 |
+
"mcpServers": {
|
| 331 |
+
"filesystem": {
|
| 332 |
+
"command": "npx",
|
| 333 |
+
"args": [
|
| 334 |
+
"-y",
|
| 335 |
+
"@modelcontextprotocol/server-filesystem",
|
| 336 |
+
"/path/to/Document"
|
| 337 |
+
]
|
| 338 |
+
},
|
| 339 |
+
"translate_pdf": {
|
| 340 |
+
"command": "uv",
|
| 341 |
+
"args": [
|
| 342 |
+
"run",
|
| 343 |
+
"pdf2zh",
|
| 344 |
+
"--mcp"
|
| 345 |
+
]
|
| 346 |
+
}
|
| 347 |
+
}
|
| 348 |
+
}
|
| 349 |
+
```
|
| 350 |
+
|
| 351 |
+
[filesystem](https://github.com/modelcontextprotocol/servers/tree/main/src/filesystem) is a reuqired mcp server to find pdf file, and `translate_pdf` is our mcp server.
|
| 352 |
+
|
| 353 |
+
To test if the mcp server works, you can open claude desktop and tell
|
| 354 |
+
|
| 355 |
+
```
|
| 356 |
+
find the `test.pdf` in my Document folder and translate it to Chinese
|
| 357 |
+
```
|
docs/APIS.md
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[**Documentation**](https://github.com/Byaidu/PDFMathTranslate) > **API Details** _(current)_
|
| 2 |
+
|
| 3 |
+
<h2 id="toc">Table of Content</h2>
|
| 4 |
+
The present project supports two types of APIs, All methods need the Redis;
|
| 5 |
+
|
| 6 |
+
- [Functional calls in Python](#api-python)
|
| 7 |
+
- [HTTP protocols](#api-http)
|
| 8 |
+
|
| 9 |
+
---
|
| 10 |
+
|
| 11 |
+
<h2 id="api-python">Python</h2>
|
| 12 |
+
|
| 13 |
+
As `pdf2zh` is an installed module in Python, we expose two methods for other programs to call in any Python scripts.
|
| 14 |
+
|
| 15 |
+
For example, if you want translate a document from English to Chinese using Google Translate, you may use the following code:
|
| 16 |
+
|
| 17 |
+
```python
|
| 18 |
+
from pdf2zh import translate, translate_stream
|
| 19 |
+
|
| 20 |
+
params = {
|
| 21 |
+
'lang_in': 'en',
|
| 22 |
+
'lang_out': 'zh',
|
| 23 |
+
'service': 'google',
|
| 24 |
+
'thread': 4,
|
| 25 |
+
}
|
| 26 |
+
```
|
| 27 |
+
Translate with files:
|
| 28 |
+
```python
|
| 29 |
+
(file_mono, file_dual) = translate(files=['example.pdf'], **params)[0]
|
| 30 |
+
```
|
| 31 |
+
Translate with stream:
|
| 32 |
+
```python
|
| 33 |
+
with open('example.pdf', 'rb') as f:
|
| 34 |
+
(stream_mono, stream_dual) = translate_stream(stream=f.read(), **params)
|
| 35 |
+
```
|
| 36 |
+
|
| 37 |
+
[⬆️ Back to top](#toc)
|
| 38 |
+
|
| 39 |
+
---
|
| 40 |
+
|
| 41 |
+
<h2 id="api-http">HTTP</h2>
|
| 42 |
+
|
| 43 |
+
In a more flexible way, you can communicate with the program using HTTP protocols, if:
|
| 44 |
+
|
| 45 |
+
1. Install and run backend
|
| 46 |
+
|
| 47 |
+
```bash
|
| 48 |
+
pip install pdf2zh[backend]
|
| 49 |
+
pdf2zh --flask
|
| 50 |
+
pdf2zh --celery worker
|
| 51 |
+
```
|
| 52 |
+
|
| 53 |
+
2. Using HTTP protocols as follows:
|
| 54 |
+
|
| 55 |
+
- Submit translate task
|
| 56 |
+
|
| 57 |
+
```bash
|
| 58 |
+
curl http://localhost:11008/v1/translate -F "file=@example.pdf" -F "data={\"lang_in\":\"en\",\"lang_out\":\"zh\",\"service\":\"google\",\"thread\":4}"
|
| 59 |
+
{"id":"d9894125-2f4e-45ea-9d93-1a9068d2045a"}
|
| 60 |
+
```
|
| 61 |
+
|
| 62 |
+
- Check Progress
|
| 63 |
+
|
| 64 |
+
```bash
|
| 65 |
+
curl http://localhost:11008/v1/translate/d9894125-2f4e-45ea-9d93-1a9068d2045a
|
| 66 |
+
{"info":{"n":13,"total":506},"state":"PROGRESS"}
|
| 67 |
+
```
|
| 68 |
+
|
| 69 |
+
- Check Progress _(if finished)_
|
| 70 |
+
|
| 71 |
+
```bash
|
| 72 |
+
curl http://localhost:11008/v1/translate/d9894125-2f4e-45ea-9d93-1a9068d2045a
|
| 73 |
+
{"state":"SUCCESS"}
|
| 74 |
+
```
|
| 75 |
+
|
| 76 |
+
- Save monolingual file
|
| 77 |
+
|
| 78 |
+
```bash
|
| 79 |
+
curl http://localhost:11008/v1/translate/d9894125-2f4e-45ea-9d93-1a9068d2045a/mono --output example-mono.pdf
|
| 80 |
+
```
|
| 81 |
+
|
| 82 |
+
- Save bilingual file
|
| 83 |
+
|
| 84 |
+
```bash
|
| 85 |
+
curl http://localhost:11008/v1/translate/d9894125-2f4e-45ea-9d93-1a9068d2045a/dual --output example-dual.pdf
|
| 86 |
+
```
|
| 87 |
+
|
| 88 |
+
- Interrupt if running and delete the task
|
| 89 |
+
```bash
|
| 90 |
+
curl http://localhost:11008/v1/translate/d9894125-2f4e-45ea-9d93-1a9068d2045a -X DELETE
|
| 91 |
+
```
|
| 92 |
+
|
| 93 |
+
[⬆️ Back to top](#toc)
|
| 94 |
+
|
| 95 |
+
---
|
docs/CODE_OF_CONDUCT.md
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Contributor Covenant Code of Conduct
|
| 2 |
+
|
| 3 |
+
## Our Pledge
|
| 4 |
+
|
| 5 |
+
We as members, contributors, and leaders pledge to make participation in our
|
| 6 |
+
community a harassment-free experience for everyone, regardless of age, body
|
| 7 |
+
size, visible or invisible disability, ethnicity, sex characteristics, gender
|
| 8 |
+
identity and expression, level of experience, education, socio-economic status,
|
| 9 |
+
nationality, personal appearance, race, religion, or sexual identity
|
| 10 |
+
and orientation.
|
| 11 |
+
|
| 12 |
+
We pledge to act and interact in ways that contribute to an open, welcoming,
|
| 13 |
+
diverse, inclusive, and healthy community.
|
| 14 |
+
|
| 15 |
+
## Our Standards
|
| 16 |
+
|
| 17 |
+
Examples of behavior that contributes to a positive environment for our
|
| 18 |
+
community include:
|
| 19 |
+
|
| 20 |
+
* Demonstrating empathy and kindness toward other people
|
| 21 |
+
* Being respectful of differing opinions, viewpoints, and experiences
|
| 22 |
+
* Giving and gracefully accepting constructive feedback
|
| 23 |
+
* Accepting responsibility and apologizing to those affected by our mistakes,
|
| 24 |
+
and learning from the experience
|
| 25 |
+
* Focusing on what is best not just for us as individuals, but for the
|
| 26 |
+
overall community
|
| 27 |
+
|
| 28 |
+
Examples of unacceptable behavior include:
|
| 29 |
+
|
| 30 |
+
* The use of sexualized language or imagery, and sexual attention or
|
| 31 |
+
advances of any kind
|
| 32 |
+
* Trolling, insulting or derogatory comments, and personal or political attacks
|
| 33 |
+
* Public or private harassment
|
| 34 |
+
* Publishing others' private information, such as a physical or email
|
| 35 |
+
address, without their explicit permission
|
| 36 |
+
* Other conduct which could reasonably be considered inappropriate in a
|
| 37 |
+
professional setting
|
| 38 |
+
|
| 39 |
+
## Enforcement Responsibilities
|
| 40 |
+
|
| 41 |
+
Community leaders are responsible for clarifying and enforcing our standards of
|
| 42 |
+
acceptable behavior and will take appropriate and fair corrective action in
|
| 43 |
+
response to any behavior that they deem inappropriate, threatening, offensive,
|
| 44 |
+
or harmful.
|
| 45 |
+
|
| 46 |
+
Community leaders have the right and responsibility to remove, edit, or reject
|
| 47 |
+
comments, commits, code, wiki edits, issues, and other contributions that are
|
| 48 |
+
not aligned to this Code of Conduct, and will communicate reasons for moderation
|
| 49 |
+
decisions when appropriate.
|
| 50 |
+
|
| 51 |
+
## Scope
|
| 52 |
+
|
| 53 |
+
This Code of Conduct applies within all community spaces, and also applies when
|
| 54 |
+
an individual is officially representing the community in public spaces.
|
| 55 |
+
Examples of representing our community include using an official e-mail address,
|
| 56 |
+
posting via an official social media account, or acting as an appointed
|
| 57 |
+
representative at an online or offline event.
|
| 58 |
+
|
| 59 |
+
## Enforcement
|
| 60 |
+
|
| 61 |
+
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
| 62 |
+
reported to the community leaders responsible for enforcement at
|
| 63 |
+
.
|
| 64 |
+
All complaints will be reviewed and investigated promptly and fairly.
|
| 65 |
+
|
| 66 |
+
All community leaders are obligated to respect the privacy and security of the
|
| 67 |
+
reporter of any incident.
|
| 68 |
+
|
| 69 |
+
## Enforcement Guidelines
|
| 70 |
+
|
| 71 |
+
Community leaders will follow these Community Impact Guidelines in determining
|
| 72 |
+
the consequences for any action they deem in violation of this Code of Conduct:
|
| 73 |
+
|
| 74 |
+
### 1. Correction
|
| 75 |
+
|
| 76 |
+
**Community Impact**: Use of inappropriate language or other behavior deemed
|
| 77 |
+
unprofessional or unwelcome in the community.
|
| 78 |
+
|
| 79 |
+
**Consequence**: A private, written warning from community leaders, providing
|
| 80 |
+
clarity around the nature of the violation and an explanation of why the
|
| 81 |
+
behavior was inappropriate. A public apology may be requested.
|
| 82 |
+
|
| 83 |
+
### 2. Warning
|
| 84 |
+
|
| 85 |
+
**Community Impact**: A violation through a single incident or series
|
| 86 |
+
of actions.
|
| 87 |
+
|
| 88 |
+
**Consequence**: A warning with consequences for continued behavior. No
|
| 89 |
+
interaction with the people involved, including unsolicited interaction with
|
| 90 |
+
those enforcing the Code of Conduct, for a specified period of time. This
|
| 91 |
+
includes avoiding interactions in community spaces as well as external channels
|
| 92 |
+
like social media. Violating these terms may lead to a temporary or
|
| 93 |
+
permanent ban.
|
| 94 |
+
|
| 95 |
+
### 3. Temporary Ban
|
| 96 |
+
|
| 97 |
+
**Community Impact**: A serious violation of community standards, including
|
| 98 |
+
sustained inappropriate behavior.
|
| 99 |
+
|
| 100 |
+
**Consequence**: A temporary ban from any sort of interaction or public
|
| 101 |
+
communication with the community for a specified period of time. No public or
|
| 102 |
+
private interaction with the people involved, including unsolicited interaction
|
| 103 |
+
with those enforcing the Code of Conduct, is allowed during this period.
|
| 104 |
+
Violating these terms may lead to a permanent ban.
|
| 105 |
+
|
| 106 |
+
### 4. Permanent Ban
|
| 107 |
+
|
| 108 |
+
**Community Impact**: Demonstrating a pattern of violation of community
|
| 109 |
+
standards, including sustained inappropriate behavior, harassment of an
|
| 110 |
+
individual, or aggression toward or disparagement of classes of individuals.
|
| 111 |
+
|
| 112 |
+
**Consequence**: A permanent ban from any sort of public interaction within
|
| 113 |
+
the community.
|
| 114 |
+
|
| 115 |
+
## Attribution
|
| 116 |
+
|
| 117 |
+
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
|
| 118 |
+
version 2.0, available at
|
| 119 |
+
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
|
| 120 |
+
|
| 121 |
+
Community Impact Guidelines were inspired by [Mozilla's code of conduct
|
| 122 |
+
enforcement ladder](https://github.com/mozilla/diversity).
|
| 123 |
+
|
| 124 |
+
[homepage]: https://www.contributor-covenant.org
|
| 125 |
+
|
| 126 |
+
For answers to common questions about this code of conduct, see the FAQ at
|
| 127 |
+
https://www.contributor-covenant.org/faq. Translations are available at
|
| 128 |
+
https://www.contributor-covenant.org/translations.
|
docs/README_GUI.md
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Interact with GUI
|
| 2 |
+
|
| 3 |
+
This subfolder provides the GUI mode of `pdf2zh`.
|
| 4 |
+
|
| 5 |
+
## Usage
|
| 6 |
+
|
| 7 |
+
1. Run `pdf2zh -i`
|
| 8 |
+
|
| 9 |
+
2. Drop the PDF file into the window and click `Translate`.
|
| 10 |
+
|
| 11 |
+
### Environment Variables
|
| 12 |
+
|
| 13 |
+
You can set the source and target languages using environment variables:
|
| 14 |
+
|
| 15 |
+
- `PDF2ZH_LANG_FROM`: Sets the source language. Defaults to "English".
|
| 16 |
+
- `PDF2ZH_LANG_TO`: Sets the target language. Defaults to "Simplified Chinese".
|
| 17 |
+
|
| 18 |
+
### Supported Languages
|
| 19 |
+
|
| 20 |
+
The following languages are supported:
|
| 21 |
+
|
| 22 |
+
- English
|
| 23 |
+
- Simplified Chinese
|
| 24 |
+
- Traditional Chinese
|
| 25 |
+
- French
|
| 26 |
+
- German
|
| 27 |
+
- Japanese
|
| 28 |
+
- Korean
|
| 29 |
+
- Russian
|
| 30 |
+
- Spanish
|
| 31 |
+
- Italian
|
| 32 |
+
|
| 33 |
+
## Preview
|
| 34 |
+
|
| 35 |
+
<img src="./images/before.png" width="500"/>
|
| 36 |
+
<img src="./images/after.png" width="500"/>
|
| 37 |
+
|
| 38 |
+
## Maintainance
|
| 39 |
+
|
| 40 |
+
GUI maintained by [Rongxin](https://github.com/reycn)
|
docs/README_ja-JP.md
ADDED
|
@@ -0,0 +1,389 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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|
+
|
| 7 |
+
<h2 id="title">PDFMathTranslate</h2>
|
| 8 |
+
|
| 9 |
+
<p>
|
| 10 |
+
<!-- PyPI -->
|
| 11 |
+
<a href="https://pypi.org/project/pdf2zh/">
|
| 12 |
+
<img src="https://img.shields.io/pypi/v/pdf2zh"/></a>
|
| 13 |
+
<a href="https://pepy.tech/projects/pdf2zh">
|
| 14 |
+
<img src="https://static.pepy.tech/badge/pdf2zh"></a>
|
| 15 |
+
<a href="https://hub.docker.com/repository/docker/byaidu/pdf2zh">
|
| 16 |
+
<img src="https://img.shields.io/docker/pulls/byaidu/pdf2zh"></a>
|
| 17 |
+
<!-- License -->
|
| 18 |
+
<a href="./LICENSE">
|
| 19 |
+
<img src="https://img.shields.io/github/license/Byaidu/PDFMathTranslate"/></a>
|
| 20 |
+
<a href="https://huggingface.co/spaces/reycn/PDFMathTranslate-Docker">
|
| 21 |
+
<img src="https://img.shields.io/badge/%F0%9F%A4%97-Online%20Demo-FF9E0D"/></a>
|
| 22 |
+
<a href="https://www.modelscope.cn/studios/AI-ModelScope/PDFMathTranslate">
|
| 23 |
+
<img src="https://img.shields.io/badge/ModelScope-Demo-blue"></a>
|
| 24 |
+
<a href="https://github.com/Byaidu/PDFMathTranslate/pulls">
|
| 25 |
+
<img src="https://img.shields.io/badge/contributions-welcome-green"/></a>
|
| 26 |
+
<a href="https://gitcode.com/Byaidu/PDFMathTranslate/overview">
|
| 27 |
+
<img src="https://gitcode.com/Byaidu/PDFMathTranslate/star/badge.svg"></a>
|
| 28 |
+
<a href="https://t.me/+Z9_SgnxmsmA5NzBl">
|
| 29 |
+
<img src="https://img.shields.io/badge/Telegram-2CA5E0?style=flat-squeare&logo=telegram&logoColor=white"/></a>
|
| 30 |
+
</p>
|
| 31 |
+
|
| 32 |
+
<a href="https://trendshift.io/repositories/12424" target="_blank"><img src="https://trendshift.io/api/badge/repositories/12424" alt="Byaidu%2FPDFMathTranslate | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
|
| 33 |
+
|
| 34 |
+
</div>
|
| 35 |
+
|
| 36 |
+
科学 PDF 文書の翻訳およびバイリンガル比較ツール
|
| 37 |
+
|
| 38 |
+
- 📊 数式、チャート、目次、注釈を保持 *([プレビュー](#preview))*
|
| 39 |
+
- 🌐 [複数の言語](#language) と [多様な翻訳サービス](#services) をサポート
|
| 40 |
+
- 🤖 [コマンドラインツール](#usage)、[インタラクティブユーザーインターフェース](#gui)、および [Docker](#docker) を提供
|
| 41 |
+
|
| 42 |
+
フィードバックは [GitHub Issues](https://github.com/Byaidu/PDFMathTranslate/issues)、[Telegram グループ](https://t.me/+Z9_SgnxmsmA5NzBl)
|
| 43 |
+
|
| 44 |
+
<h2 id="updates">最近の更新</h2>
|
| 45 |
+
|
| 46 |
+
- [2024年11月26日] CLIがオンラインファイルをサポートするようになりました *(by [@reycn](https://github.com/reycn))*
|
| 47 |
+
- [2024年11月24日] 依存関係のサイズを削減するために [ONNX](https://github.com/onnx/onnx) サポートを追加しました *(by [@Wybxc](https://github.com/Wybxc))*
|
| 48 |
+
- [2024年11月23日] 🌟 [公共サービス](#demo) がオンラインになりました! *(by [@Byaidu](https://github.com/Byaidu))*
|
| 49 |
+
- [2024年11月23日] ウェブボットを防ぐためのファイアウォールを追加しました *(by [@Byaidu](https://github.com/Byaidu))*
|
| 50 |
+
- [2024年11月22日] GUIがイタリア語をサポートし、改善されました *(by [@Byaidu](https://github.com/Byaidu), [@reycn](https://github.com/reycn))*
|
| 51 |
+
- [2024年11月22日] デプロイされたサービスを他の人と共有できるようになりました *(by [@Zxis233](https://github.com/Zxis233))*
|
| 52 |
+
- [2024年11月22日] Tencent翻訳をサポートしました *(by [@hellofinch](https://github.com/hellofinch))*
|
| 53 |
+
- [2024年11月21日] GUIがバイリンガルドキュメントのダウンロードをサポートするようになりました *(by [@reycn](https://github.com/reycn))*
|
| 54 |
+
- [2024年11月20日] 🌟 [デモ](#demo) がオンラインになりました! *(by [@reycn](https://github.com/reycn))*
|
| 55 |
+
|
| 56 |
+
<h2 id="preview">プレビュー</h2>
|
| 57 |
+
|
| 58 |
+
<div align="center">
|
| 59 |
+
<img src="./images/preview.gif" width="80%"/>
|
| 60 |
+
</div>
|
| 61 |
+
|
| 62 |
+
<h2 id="demo">公共サービス 🌟</h2>
|
| 63 |
+
|
| 64 |
+
### 無料サービス (<https://pdf2zh.com/>)
|
| 65 |
+
|
| 66 |
+
インストールなしで [公共サービス](https://pdf2zh.com/) をオンラインで試すことができます。
|
| 67 |
+
|
| 68 |
+
### デモ
|
| 69 |
+
|
| 70 |
+
インストールなしで [HuggingFace上のデモ](https://huggingface.co/spaces/reycn/PDFMathTranslate-Docker), [ModelScope上のデモ](https://www.modelscope.cn/studios/AI-ModelScope/PDFMathTranslate) を試すことができます。
|
| 71 |
+
デモの計算リソースは限られているため、乱用しないようにしてください。
|
| 72 |
+
|
| 73 |
+
<h2 id="install">インストールと使用方法</h2>
|
| 74 |
+
|
| 75 |
+
このプロジェクトを使用するための4つの方法を提供しています:[コマンドライン](#cmd)、[ポータブル](#portable)、[GUI](#gui)、および [Docker](#docker)。
|
| 76 |
+
|
| 77 |
+
pdf2zhの実行には追加モデル(`wybxc/DocLayout-YOLO-DocStructBench-onnx`)が必要です。このモデルはModelScopeでも見つけることができます。起動時にこのモデルのダウンロードに問題がある場合は、以下の環境変数を使用してください:
|
| 78 |
+
|
| 79 |
+
```shell
|
| 80 |
+
set HF_ENDPOINT=https://hf-mirror.com
|
| 81 |
+
```
|
| 82 |
+
|
| 83 |
+
For PowerShell user:
|
| 84 |
+
```shell
|
| 85 |
+
$env:HF_ENDPOINT = https://hf-mirror.com
|
| 86 |
+
```
|
| 87 |
+
|
| 88 |
+
<h3 id="cmd">方法1. コマンドライン</h3>
|
| 89 |
+
|
| 90 |
+
1. Pythonがインストールされていること (バージョン3.10 <= バージョン <= 3.12)
|
| 91 |
+
2. パッケージをインストールします:
|
| 92 |
+
|
| 93 |
+
```bash
|
| 94 |
+
pip install pdf2zh
|
| 95 |
+
```
|
| 96 |
+
|
| 97 |
+
3. 翻訳を実行し、[現在の作業ディレクトリ](https://chatgpt.com/share/6745ed36-9acc-800e-8a90-59204bd13444) にファイルを生成します:
|
| 98 |
+
|
| 99 |
+
```bash
|
| 100 |
+
pdf2zh document.pdf
|
| 101 |
+
```
|
| 102 |
+
|
| 103 |
+
<h3 id="portable">方法2. ポータブル</h3>
|
| 104 |
+
|
| 105 |
+
Python環境を事前にインストールする必要はありません
|
| 106 |
+
|
| 107 |
+
[setup.bat](https://raw.githubusercontent.com/Byaidu/PDFMathTranslate/refs/heads/main/script/setup.bat) をダウンロードしてダブルクリックして実行します
|
| 108 |
+
|
| 109 |
+
<h3 id="gui">方法3. GUI</h3>
|
| 110 |
+
|
| 111 |
+
1. Pythonがインストールされていること (バージョン3.10 <= バージョン <= 3.12)
|
| 112 |
+
2. パッケージをインストールします:
|
| 113 |
+
|
| 114 |
+
```bash
|
| 115 |
+
pip install pdf2zh
|
| 116 |
+
```
|
| 117 |
+
|
| 118 |
+
3. ブラウザで使用を開始します:
|
| 119 |
+
|
| 120 |
+
```bash
|
| 121 |
+
pdf2zh -i
|
| 122 |
+
```
|
| 123 |
+
|
| 124 |
+
4. ブラウザが自動的に起動しない場合は、次のURLを開きます:
|
| 125 |
+
|
| 126 |
+
```bash
|
| 127 |
+
http://localhost:7860/
|
| 128 |
+
```
|
| 129 |
+
|
| 130 |
+
<img src="./images/gui.gif" width="500"/>
|
| 131 |
+
|
| 132 |
+
詳細については、[GUIのドキュメント](./README_GUI.md) を参照してください。
|
| 133 |
+
|
| 134 |
+
<h3 id="docker">方法4. Docker</h3>
|
| 135 |
+
|
| 136 |
+
1. プルして実行します:
|
| 137 |
+
|
| 138 |
+
```bash
|
| 139 |
+
docker pull byaidu/pdf2zh
|
| 140 |
+
docker run -d -p 7860:7860 byaidu/pdf2zh
|
| 141 |
+
```
|
| 142 |
+
|
| 143 |
+
2. ブラウザで開きます:
|
| 144 |
+
|
| 145 |
+
```
|
| 146 |
+
http://localhost:7860/
|
| 147 |
+
```
|
| 148 |
+
|
| 149 |
+
クラウドサービスでのDockerデプロイメント用:
|
| 150 |
+
|
| 151 |
+
<div>
|
| 152 |
+
<a href="https://www.heroku.com/deploy?template=https://github.com/Byaidu/PDFMathTranslate">
|
| 153 |
+
<img src="https://www.herokucdn.com/deploy/button.svg" alt="Deploy" height="26"></a>
|
| 154 |
+
<a href="https://render.com/deploy">
|
| 155 |
+
<img src="https://render.com/images/deploy-to-render-button.svg" alt="Deploy to Koyeb" height="26"></a>
|
| 156 |
+
<a href="https://zeabur.com/templates/5FQIGX?referralCode=reycn">
|
| 157 |
+
<img src="https://zeabur.com/button.svg" alt="Deploy on Zeabur" height="26"></a>
|
| 158 |
+
<a href="https://app.koyeb.com/deploy?type=git&builder=buildpack&repository=github.com/Byaidu/PDFMathTranslate&branch=main&name=pdf-math-translate">
|
| 159 |
+
<img src="https://www.koyeb.com/static/images/deploy/button.svg" alt="Deploy to Koyeb" height="26"></a>
|
| 160 |
+
</div>
|
| 161 |
+
|
| 162 |
+
<h2 id="usage">高度なオプション</h2>
|
| 163 |
+
|
| 164 |
+
コマンドラインで翻訳コマンドを実行し、現在の作業ディレクトリに翻訳されたドキュメント `example-mono.pdf` とバイリンガルドキュメント `example-dual.pdf` を生成します。デフォルトではGoogle翻訳サービスを使用します。More support translation services can find [HERE](https://github.com/Byaidu/PDFMathTranslate/blob/main/docs/ADVANCED.md#services).
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
<img src="./images/cmd.explained.png" width="580px" alt="cmd"/>
|
| 168 |
+
|
| 169 |
+
以下の表に、参考のためにすべての高度なオプションをリストしました:
|
| 170 |
+
|
| 171 |
+
| オプション | 機能 | 例 |
|
| 172 |
+
| -------- | ------- |------- |
|
| 173 |
+
| files | ローカルファイル | `pdf2zh ~/local.pdf` |
|
| 174 |
+
| links | オンラインファイル | `pdf2zh http://arxiv.org/paper.pdf` |
|
| 175 |
+
| `-i` | [GUIに入る](#gui) | `pdf2zh -i` |
|
| 176 |
+
| `-p` | [部分的なドキュメント翻訳](#partial) | `pdf2zh example.pdf -p 1` |
|
| 177 |
+
| `-li` | [ソース言語](#languages) | `pdf2zh example.pdf -li en` |
|
| 178 |
+
| `-lo` | [ターゲット言語](#languages) | `pdf2zh example.pdf -lo zh` |
|
| 179 |
+
| `-s` | [翻訳サービス](#services) | `pdf2zh example.pdf -s deepl` |
|
| 180 |
+
| `-t` | [マルチスレッド](#threads) | `pdf2zh example.pdf -t 1` |
|
| 181 |
+
| `-o` | 出力ディレクトリ | `pdf2zh example.pdf -o output` |
|
| 182 |
+
| `-f`, `-c` | [例外](#exceptions) | `pdf2zh example.pdf -f "(MS.*)"` |
|
| 183 |
+
| `--share` | [gradio公開リンクを取得] | `pdf2zh -i --share` |
|
| 184 |
+
| `--authorized` | [[ウェブ認証とカスタム認証ページの追加](https://github.com/Byaidu/PDFMathTranslate/blob/main/docs/ADVANCED.)] | `pdf2zh -i --authorized users.txt [auth.html]` |
|
| 185 |
+
| `--prompt` | [カスタムビッグモデルのプロンプトを使用する] | `pdf2zh --prompt [prompt.txt]` |
|
| 186 |
+
| `--onnx` | [カスタムDocLayout-YOLO ONNXモデルの使用] | `pdf2zh --onnx [onnx/model/path]` |
|
| 187 |
+
| `--serverport` | [カスタムWebUIポートを使用する] | `pdf2zh --serverport 7860` |
|
| 188 |
+
| `--dir` | [batch translate] | `pdf2zh --dir /path/to/translate/` |
|
| 189 |
+
| `--config` | [configuration file](https://github.com/Byaidu/PDFMathTranslate/blob/main/docs/ADVANCED.md#cofig) | `pdf2zh --config /path/to/config/config.json` |
|
| 190 |
+
| `--serverport` | [custom gradio server port] | `pdf2zh --serverport 7860` |
|
| 191 |
+
|
| 192 |
+
<h3 id="partial">全文または部分的なドキュメント翻訳</h3>
|
| 193 |
+
|
| 194 |
+
- **全文翻訳**
|
| 195 |
+
|
| 196 |
+
```bash
|
| 197 |
+
pdf2zh example.pdf
|
| 198 |
+
```
|
| 199 |
+
|
| 200 |
+
- **部分翻訳**
|
| 201 |
+
|
| 202 |
+
```bash
|
| 203 |
+
pdf2zh example.pdf -p 1-3,5
|
| 204 |
+
```
|
| 205 |
+
|
| 206 |
+
<h3 id="language">ソース言語とターゲット言語を指定</h3>
|
| 207 |
+
|
| 208 |
+
[Google Languages Codes](https://developers.google.com/admin-sdk/directory/v1/languages)、[DeepL Languages Codes](https://developers.deepl.com/docs/resources/supported-languages) を参照してください
|
| 209 |
+
|
| 210 |
+
```bash
|
| 211 |
+
pdf2zh example.pdf -li en -lo ja
|
| 212 |
+
```
|
| 213 |
+
|
| 214 |
+
<h3 id="services">異なるサービスで翻訳</h3>
|
| 215 |
+
|
| 216 |
+
以下の表は、各翻訳サービスに必要な [環境変数](https://chatgpt.com/share/6734a83d-9d48-800e-8a46-f57ca6e8bcb4) を示しています。各サービスを使用する前に、これらの変数を設定してください。
|
| 217 |
+
|
| 218 |
+
|**Translator**|**Service**|**Environment Variables**|**Default Values**|**Notes**|
|
| 219 |
+
|-|-|-|-|-|
|
| 220 |
+
|**Google (Default)**|`google`|None|N/A|None|
|
| 221 |
+
|**Bing**|`bing`|None|N/A|None|
|
| 222 |
+
|**DeepL**|`deepl`|`DEEPL_AUTH_KEY`|`[Your Key]`|See [DeepL](https://support.deepl.com/hc/en-us/articles/360020695820-API-Key-for-DeepL-s-API)|
|
| 223 |
+
|**DeepLX**|`deeplx`|`DEEPLX_ENDPOINT`|`https://api.deepl.com/translate`|See [DeepLX](https://github.com/OwO-Network/DeepLX)|
|
| 224 |
+
|**Ollama**|`ollama`|`OLLAMA_HOST`, `OLLAMA_MODEL`|`http://127.0.0.1:11434`, `gemma2`|See [Ollama](https://github.com/ollama/ollama)|
|
| 225 |
+
|**OpenAI**|`openai`|`OPENAI_BASE_URL`, `OPENAI_API_KEY`, `OPENAI_MODEL`|`https://api.openai.com/v1`, `[Your Key]`, `gpt-4o-mini`|See [OpenAI](https://platform.openai.com/docs/overview)|
|
| 226 |
+
|**AzureOpenAI**|`azure-openai`|`AZURE_OPENAI_BASE_URL`, `AZURE_OPENAI_API_KEY`, `AZURE_OPENAI_MODEL`|`[Your Endpoint]`, `[Your Key]`, `gpt-4o-mini`|See [Azure OpenAI](https://learn.microsoft.com/zh-cn/azure/ai-services/openai/chatgpt-quickstart?tabs=command-line%2Cjavascript-keyless%2Ctypescript-keyless%2Cpython&pivots=programming-language-python)|
|
| 227 |
+
|**Zhipu**|`zhipu`|`ZHIPU_API_KEY`, `ZHIPU_MODEL`|`[Your Key]`, `glm-4-flash`|See [Zhipu](https://open.bigmodel.cn/dev/api/thirdparty-frame/openai-sdk)|
|
| 228 |
+
| **ModelScope** | `modelscope` |`MODELSCOPE_API_KEY`, `MODELSCOPE_MODEL`|`[Your Key]`, `Qwen/Qwen2.5-Coder-32B-Instruct`| See [ModelScope](https://www.modelscope.cn/docs/model-service/API-Inference/intro)|
|
| 229 |
+
|**Silicon**|`silicon`|`SILICON_API_KEY`, `SILICON_MODEL`|`[Your Key]`, `Qwen/Qwen2.5-7B-Instruct`|See [SiliconCloud](https://docs.siliconflow.cn/quickstart)|
|
| 230 |
+
|**Gemini**|`gemini`|`GEMINI_API_KEY`, `GEMINI_MODEL`|`[Your Key]`, `gemini-1.5-flash`|See [Gemini](https://ai.google.dev/gemini-api/docs/openai)|
|
| 231 |
+
|**Azure**|`azure`|`AZURE_ENDPOINT`, `AZURE_API_KEY`|`https://api.translator.azure.cn`, `[Your Key]`|See [Azure](https://docs.azure.cn/en-us/ai-services/translator/text-translation-overview)|
|
| 232 |
+
|**Tencent**|`tencent`|`TENCENTCLOUD_SECRET_ID`, `TENCENTCLOUD_SECRET_KEY`|`[Your ID]`, `[Your Key]`|See [Tencent](https://www.tencentcloud.com/products/tmt?from_qcintl=122110104)|
|
| 233 |
+
|**Dify**|`dify`|`DIFY_API_URL`, `DIFY_API_KEY`|`[Your DIFY URL]`, `[Your Key]`|See [Dify](https://github.com/langgenius/dify),Three variables, lang_out, lang_in, and text, need to be defined in Dify's workflow input.|
|
| 234 |
+
|**AnythingLLM**|`anythingllm`|`AnythingLLM_URL`, `AnythingLLM_APIKEY`|`[Your AnythingLLM URL]`, `[Your Key]`|See [anything-llm](https://github.com/Mintplex-Labs/anything-llm)|
|
| 235 |
+
|**Argos Translate**|`argos`| | |See [argos-translate](https://github.com/argosopentech/argos-translate)|
|
| 236 |
+
|**Grok**|`grok`| `GORK_API_KEY`, `GORK_MODEL` | `[Your GORK_API_KEY]`, `grok-2-1212` |See [Grok](https://docs.x.ai/docs/overview)|
|
| 237 |
+
|**DeepSeek**|`deepseek`| `DEEPSEEK_API_KEY`, `DEEPSEEK_MODEL` | `[Your DEEPSEEK_API_KEY]`, `deepseek-chat` |See [DeepSeek](https://www.deepseek.com/)|
|
| 238 |
+
|**OpenAI-Liked**|`openailiked`| `OPENAILIKED_BASE_URL`, `OPENAILIKED_API_KEY`, `OPENAILIKED_MODEL` | `url`, `[Your Key]`, `model name` | None |
|
| 239 |
+
|
| 240 |
+
(need Japenese translation)
|
| 241 |
+
For large language models that are compatible with the OpenAI API but not listed in the table above, you can set environment variables using the same method outlined for OpenAI in the table.
|
| 242 |
+
|
| 243 |
+
`-s service` または `-s service:model` を使用してサービスを指定します:
|
| 244 |
+
|
| 245 |
+
```bash
|
| 246 |
+
pdf2zh example.pdf -s openai:gpt-4o-mini
|
| 247 |
+
```
|
| 248 |
+
|
| 249 |
+
または環境変数でモデルを指定します:
|
| 250 |
+
|
| 251 |
+
```bash
|
| 252 |
+
set OPENAI_MODEL=gpt-4o-mini
|
| 253 |
+
pdf2zh example.pdf -s openai
|
| 254 |
+
```
|
| 255 |
+
|
| 256 |
+
For PowerShell user:
|
| 257 |
+
```shell
|
| 258 |
+
$env:OPENAI_MODEL = gpt-4o-mini
|
| 259 |
+
pdf2zh example.pdf -s openai
|
| 260 |
+
```
|
| 261 |
+
|
| 262 |
+
<h3 id="exceptions">例外を指定して翻訳</h3>
|
| 263 |
+
|
| 264 |
+
正規表現を使用して保持する必要がある数式フォントと文字を指定します:
|
| 265 |
+
|
| 266 |
+
```bash
|
| 267 |
+
pdf2zh example.pdf -f "(CM[^RT].*|MS.*|.*Ital)" -c "(\(|\||\)|\+|=|\d|[\u0080-\ufaff])"
|
| 268 |
+
```
|
| 269 |
+
|
| 270 |
+
デフォルトで `Latex`、`Mono`、`Code`、`Italic`、`Symbol` および `Math` フォントを保持します:
|
| 271 |
+
|
| 272 |
+
```bash
|
| 273 |
+
pdf2zh example.pdf -f "(CM[^R]|MS.M|XY|MT|BL|RM|EU|LA|RS|LINE|LCIRCLE|TeX-|rsfs|txsy|wasy|stmary|.*Mono|.*Code|.*Ital|.*Sym|.*Math)"
|
| 274 |
+
```
|
| 275 |
+
|
| 276 |
+
<h3 id="threads">スレッド数を指定</h3>
|
| 277 |
+
|
| 278 |
+
`-t` を使用して翻訳に使用するスレッド数を指定します:
|
| 279 |
+
|
| 280 |
+
```bash
|
| 281 |
+
pdf2zh example.pdf -t 1
|
| 282 |
+
```
|
| 283 |
+
|
| 284 |
+
<h3 id="prompt">カスタム プロンプト</h3>
|
| 285 |
+
|
| 286 |
+
`--prompt`を使用して、LLMで使用するプロンプトを指定します:
|
| 287 |
+
|
| 288 |
+
```bash
|
| 289 |
+
pdf2zh example.pdf -pr prompt.txt
|
| 290 |
+
```
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
`prompt.txt`の例:
|
| 294 |
+
|
| 295 |
+
```txt
|
| 296 |
+
[
|
| 297 |
+
{
|
| 298 |
+
"role": "system",
|
| 299 |
+
"content": "You are a professional,authentic machine translation engine.",
|
| 300 |
+
},
|
| 301 |
+
{
|
| 302 |
+
"role": "user",
|
| 303 |
+
"content": "Translate the following markdown source text to ${lang_out}. Keep the formula notation {{v*}} unchanged. Output translation directly without any additional text.\nSource Text: ${text}\nTranslated Text:",
|
| 304 |
+
},
|
| 305 |
+
]
|
| 306 |
+
```
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
カスタムプロンプトファイルでは、以下の3つの変数が使用できます。
|
| 310 |
+
|
| 311 |
+
|**変数**|**内容**|
|
| 312 |
+
|-|-|
|
| 313 |
+
|`lang_in`|ソース言語|
|
| 314 |
+
|`lang_out`|ターゲット言語|
|
| 315 |
+
|`text`|翻訳するテキスト|
|
| 316 |
+
|
| 317 |
+
<h2 id="todo">API</h2>
|
| 318 |
+
|
| 319 |
+
### Python
|
| 320 |
+
|
| 321 |
+
```python
|
| 322 |
+
from pdf2zh import translate, translate_stream
|
| 323 |
+
|
| 324 |
+
params = {"lang_in": "en", "lang_out": "zh", "service": "google", "thread": 4}
|
| 325 |
+
file_mono, file_dual = translate(files=["example.pdf"], **params)[0]
|
| 326 |
+
with open("example.pdf", "rb") as f:
|
| 327 |
+
stream_mono, stream_dual = translate_stream(stream=f.read(), **params)
|
| 328 |
+
```
|
| 329 |
+
|
| 330 |
+
### HTTP
|
| 331 |
+
|
| 332 |
+
```bash
|
| 333 |
+
pip install pdf2zh[backend]
|
| 334 |
+
pdf2zh --flask
|
| 335 |
+
pdf2zh --celery worker
|
| 336 |
+
```
|
| 337 |
+
|
| 338 |
+
```bash
|
| 339 |
+
curl http://localhost:11008/v1/translate -F "file=@example.pdf" -F "data={\"lang_in\":\"en\",\"lang_out\":\"zh\",\"service\":\"google\",\"thread\":4}"
|
| 340 |
+
{"id":"d9894125-2f4e-45ea-9d93-1a9068d2045a"}
|
| 341 |
+
|
| 342 |
+
curl http://localhost:11008/v1/translate/d9894125-2f4e-45ea-9d93-1a9068d2045a
|
| 343 |
+
{"info":{"n":13,"total":506},"state":"PROGRESS"}
|
| 344 |
+
|
| 345 |
+
curl http://localhost:11008/v1/translate/d9894125-2f4e-45ea-9d93-1a9068d2045a
|
| 346 |
+
{"state":"SUCCESS"}
|
| 347 |
+
|
| 348 |
+
curl http://localhost:11008/v1/translate/d9894125-2f4e-45ea-9d93-1a9068d2045a/mono --output example-mono.pdf
|
| 349 |
+
|
| 350 |
+
curl http://localhost:11008/v1/translate/d9894125-2f4e-45ea-9d93-1a9068d2045a/dual --output example-dual.pdf
|
| 351 |
+
|
| 352 |
+
curl http://localhost:11008/v1/translate/d9894125-2f4e-45ea-9d93-1a9068d2045a -X DELETE
|
| 353 |
+
```
|
| 354 |
+
|
| 355 |
+
<h2 id="acknowledgement">謝辞</h2>
|
| 356 |
+
|
| 357 |
+
- ドキュメントのマージ:[PyMuPDF](https://github.com/pymupdf/PyMuPDF)
|
| 358 |
+
|
| 359 |
+
- ドキュメントの解析:[Pdfminer.six](https://github.com/pdfminer/pdfminer.six)
|
| 360 |
+
|
| 361 |
+
- ドキュメントの抽出:[MinerU](https://github.com/opendatalab/MinerU)
|
| 362 |
+
|
| 363 |
+
- ドキュメントプレビュー:[Gradio PDF](https://github.com/freddyaboulton/gradio-pdf)
|
| 364 |
+
|
| 365 |
+
- マルチスレッド翻訳:[MathTranslate](https://github.com/SUSYUSTC/MathTranslate)
|
| 366 |
+
|
| 367 |
+
- レイアウト解析:[DocLayout-YOLO](https://github.com/opendatalab/DocLayout-YOLO)
|
| 368 |
+
|
| 369 |
+
- ドキュメント標準:[PDF Explained](https://zxyle.github.io/PDF-Explained/)、[PDF Cheat Sheets](https://pdfa.org/resource/pdf-cheat-sheets/)
|
| 370 |
+
|
| 371 |
+
- 多言語フォント:[Go Noto Universal](https://github.com/satbyy/go-noto-universal)
|
| 372 |
+
|
| 373 |
+
<h2 id="contrib">貢献者</h2>
|
| 374 |
+
|
| 375 |
+
<a href="https://github.com/Byaidu/PDFMathTranslate/graphs/contributors">
|
| 376 |
+
<img src="https://opencollective.com/PDFMathTranslate/contributors.svg?width=890&button=false" />
|
| 377 |
+
</a>
|
| 378 |
+
|
| 379 |
+

|
| 380 |
+
|
| 381 |
+
<h2 id="star_hist">スター履歴</h2>
|
| 382 |
+
|
| 383 |
+
<a href="https://star-history.com/#Byaidu/PDFMathTranslate&Date">
|
| 384 |
+
<picture>
|
| 385 |
+
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=Byaidu/PDFMathTranslate&type=Date&theme=dark" />
|
| 386 |
+
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=Byaidu/PDFMathTranslate&type=Date" />
|
| 387 |
+
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=Byaidu/PDFMathTranslate&type=Date"/>
|
| 388 |
+
</picture>
|
| 389 |
+
</a>
|
docs/README_ko-KR.md
ADDED
|
@@ -0,0 +1,382 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Create new file
|
| 2 |
+
|
| 3 |
+
<div align="center">
|
| 4 |
+
|
| 5 |
+
[English](../README.md) | [简体中文](README_zh-CN.md) | [繁體中文](README_zh-TW.md) | [日本語](README_ja-JP.md) | 한국어
|
| 6 |
+
|
| 7 |
+
<img src="./images/banner.png" width="320px" alt="PDF2ZH"/>
|
| 8 |
+
|
| 9 |
+
<h2 id="title">PDFMathTranslate</h2>
|
| 10 |
+
|
| 11 |
+
<p>
|
| 12 |
+
<!-- PyPI -->
|
| 13 |
+
<a href="https://pypi.org/project/pdf2zh/">
|
| 14 |
+
<img src="https://img.shields.io/pypi/v/pdf2zh"/></a>
|
| 15 |
+
<a href="https://pepy.tech/projects/pdf2zh">
|
| 16 |
+
<img src="https://static.pepy.tech/badge/pdf2zh"></a>
|
| 17 |
+
<a href="https://hub.docker.com/repository/docker/byaidu/pdf2zh">
|
| 18 |
+
<img src="https://img.shields.io/docker/pulls/byaidu/pdf2zh"></a>
|
| 19 |
+
<!-- License -->
|
| 20 |
+
<a href="./LICENSE">
|
| 21 |
+
<img src="https://img.shields.io/github/license/Byaidu/PDFMathTranslate"/></a>
|
| 22 |
+
<a href="https://huggingface.co/spaces/reycn/PDFMathTranslate-Docker">
|
| 23 |
+
<img src="https://img.shields.io/badge/%F0%9F%A4%97-Online%20Demo-FF9E0D"/></a>
|
| 24 |
+
<a href="https://www.modelscope.cn/studios/AI-ModelScope/PDFMathTranslate">
|
| 25 |
+
<img src="https://img.shields.io/badge/ModelScope-Demo-blue"></a>
|
| 26 |
+
<a href="https://github.com/Byaidu/PDFMathTranslate/pulls">
|
| 27 |
+
<img src="https://img.shields.io/badge/contributions-welcome-green"/></a>
|
| 28 |
+
<a href="https://gitcode.com/Byaidu/PDFMathTranslate/overview">
|
| 29 |
+
<img src="https://gitcode.com/Byaidu/PDFMathTranslate/star/badge.svg"></a>
|
| 30 |
+
<a href="https://t.me/+Z9_SgnxmsmA5NzBl">
|
| 31 |
+
<img src="https://img.shields.io/badge/Telegram-2CA5E0?style=flat-squeare&logo=telegram&logoColor=white"/></a>
|
| 32 |
+
</p>
|
| 33 |
+
|
| 34 |
+
<a href="https://trendshift.io/repositories/12424" target="_blank"><img src="https://trendshift.io/api/badge/repositories/12424" alt="Byaidu%2FPDFMathTranslate | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
|
| 35 |
+
|
| 36 |
+
</div>
|
| 37 |
+
|
| 38 |
+
과학 PDF 문서 번역 및 이중 언어 비교 도구
|
| 39 |
+
|
| 40 |
+
- 📊 수식, 차트, 목차, 주석 유지 _([미리보기](#preview))_
|
| 41 |
+
- 🌐 [다양한 언어](#language)와 [다양한 번역 서비스](#services) 지원
|
| 42 |
+
- 🤖 [커맨드라인 도구](#usage), [대화형 사용자 인터페이스](#gui), 및 [Docker](#docker) 제공
|
| 43 |
+
|
| 44 |
+
피드백은 [GitHub Issues](https://github.com/Byaidu/PDFMathTranslate/issues) 또는 [Telegram 그룹](https://t.me/+Z9_SgnxmsmA5NzBl)에서 해주세요.
|
| 45 |
+
|
| 46 |
+
<h2 id="updates">최근 업데이트</h2>
|
| 47 |
+
|
| 48 |
+
- [2024년 12월 24일] [Xinference](https://github.com/xorbitsai/inference) 실행 로컬 LLM 지원 추가 _(by [@imClumsyPanda](https://github.com/imClumsyPanda))_
|
| 49 |
+
- [2024년 11월 26일] CLI가 온라인 파일을 지원하게 되었습니다 _(by [@reycn](https://github.com/reycn))_
|
| 50 |
+
- [2024년 11월 24일] 의존성 크기를 줄이기 위해 [ONNX](https://github.com/onnx/onnx) 지원 추가 _(by [@Wybxc](https://github.com/Wybxc))_
|
| 51 |
+
- [2024년 11월 23일] 🌟 [무료 공공 서비스](#demo) 온라인! _(by [@Byaidu](https://github.com/Byaidu))_
|
| 52 |
+
- [2024년 11월 23일] 웹 봇을 방지하기 위한 방화벽 추가 _(by [@Byaidu](https://github.com/Byaidu))_
|
| 53 |
+
- [2024년 11월 22일] GUI가 이탈리아어를 지원하고 개선되었습니다 _(by [@Byaidu](https://github.com/Byaidu), [@reycn](https://github.com/reycn))_
|
| 54 |
+
- [2024년 11월 22일] 배포된 서비스를 다른 사람과 공유할 수 있게 되었습니다 _(by [@Zxis233](https://github.com/Zxis233))_
|
| 55 |
+
- [2024년 11월 22일] Tencent 번역 지원 _(by [@hellofinch](https://github.com/hellofinch))_
|
| 56 |
+
- [2024년 11월 21일] GUI가 이중 언어 문서 다운로드를 지원하게 되었습니다 _(by [@reycn](https://github.com/reycn))_
|
| 57 |
+
- [2024년 11월 20일] 🌟 [데모](#demo)가 온라인이 되었습니다! _(by [@reycn](https://github.com/reycn))_
|
| 58 |
+
|
| 59 |
+
<h2 id="preview">미리보기</h2>
|
| 60 |
+
|
| 61 |
+
<div align="center">
|
| 62 |
+
<img src="./images/preview.gif" width="80%"/>
|
| 63 |
+
</div>
|
| 64 |
+
|
| 65 |
+
<h2 id="demo">공공 서비스 🌟</h2>
|
| 66 |
+
|
| 67 |
+
### 무료 서비스 (<https://pdf2zh.com/>)
|
| 68 |
+
|
| 69 |
+
설치 없이 [무료 공공 서비스](https://pdf2zh.com/)를 온라인으로 사용해 볼 수 있습니다.
|
| 70 |
+
|
| 71 |
+
### 데모
|
| 72 |
+
|
| 73 |
+
설치 없이 [HuggingFace의 데모](https://huggingface.co/spaces/reycn/PDFMathTranslate-Docker)와 [ModelScope의 데모](https://www.modelscope.cn/studios/AI-ModelScope/PDFMathTranslate)를 사용해 볼 수 있습니다.
|
| 74 |
+
데모의 컴퓨팅 리소스가 제한되어 있으므로 남용하지 말아주세요.
|
| 75 |
+
|
| 76 |
+
<h2 id="install">설치 및 사용법</h2>
|
| 77 |
+
|
| 78 |
+
이 프로젝트를 사용하는 4가지 방법을 제공합니다: [커맨드라인 도구](#cmd), [포터블](#portable), [GUI](#gui), 및 [Docker](#docker).
|
| 79 |
+
|
| 80 |
+
pdf2zh 실행에는 추가 모델(`wybxc/DocLayout-YOLO-DocStructBench-onnx`)이 필요합니다. 이 모델은 ModelScope에서도 찾을 수 있습니다. 시작할 때 이 모델 다운로드에 문제가 있다면 다음 환경 변수를 사용하세요:
|
| 81 |
+
|
| 82 |
+
```shell
|
| 83 |
+
set HF_ENDPOINT=https://hf-mirror.com
|
| 84 |
+
```
|
| 85 |
+
|
| 86 |
+
PowerShell 사용자의 경우:
|
| 87 |
+
|
| 88 |
+
```shell
|
| 89 |
+
$env:HF_ENDPOINT = https://hf-mirror.com
|
| 90 |
+
```
|
| 91 |
+
|
| 92 |
+
<h3 id="cmd">방법 1. 커맨드라인 도구</h3>
|
| 93 |
+
|
| 94 |
+
1. Python이 설치되어 있어야 합니다 (버전 3.10 <= 버전 <= 3.12)
|
| 95 |
+
2. 패키지를 설치합니다:
|
| 96 |
+
|
| 97 |
+
```bash
|
| 98 |
+
pip install pdf2zh
|
| 99 |
+
```
|
| 100 |
+
|
| 101 |
+
3. 번역을 실행하고 [현재 작업 디렉토리](https://chatgpt.com/share/6745ed36-9acc-800e-8a90-59204bd13444)에 파일을 생성합니다:
|
| 102 |
+
|
| 103 |
+
```bash
|
| 104 |
+
pdf2zh document.pdf
|
| 105 |
+
```
|
| 106 |
+
|
| 107 |
+
<h3 id="portable">방법 2. 포터블</h3>
|
| 108 |
+
|
| 109 |
+
Python 환경을 미리 설치할 필요가 없습니다.
|
| 110 |
+
|
| 111 |
+
[setup.bat](https://raw.githubusercontent.com/Byaidu/PDFMathTranslate/refs/heads/main/script/setup.bat)을 다운로드하고 더블클릭하여 실행합니다.
|
| 112 |
+
|
| 113 |
+
<h3 id="gui">방법 3. GUI</h3>
|
| 114 |
+
|
| 115 |
+
1. Python이 설치되어 있어야 합니다 (버전 3.10 <= 버전 <= 3.12)
|
| 116 |
+
2. 패키지를 설치합니다:
|
| 117 |
+
|
| 118 |
+
```bash
|
| 119 |
+
pip install pdf2zh
|
| 120 |
+
```
|
| 121 |
+
|
| 122 |
+
3. 브라우저에서 사용을 시작합니다:
|
| 123 |
+
|
| 124 |
+
```bash
|
| 125 |
+
pdf2zh -i
|
| 126 |
+
```
|
| 127 |
+
|
| 128 |
+
4. 브라우저가 자동으로 시작되지 않으면 다음 URL을 엽니다:
|
| 129 |
+
|
| 130 |
+
```bash
|
| 131 |
+
http://localhost:7860/
|
| 132 |
+
```
|
| 133 |
+
|
| 134 |
+
<img src="./images/gui.gif" width="500"/>
|
| 135 |
+
|
| 136 |
+
자세한 내용은 [GUI 문서](./README_GUI.md)를 참조하세요.
|
| 137 |
+
|
| 138 |
+
<h3 id="docker">방법 4. Docker</h3>
|
| 139 |
+
|
| 140 |
+
1. 풀하고 실행합니다:
|
| 141 |
+
|
| 142 |
+
```bash
|
| 143 |
+
docker pull byaidu/pdf2zh
|
| 144 |
+
docker run -d -p 7860:7860 byaidu/pdf2zh
|
| 145 |
+
```
|
| 146 |
+
|
| 147 |
+
2. 브라우저에서 엽니다:
|
| 148 |
+
|
| 149 |
+
```
|
| 150 |
+
http://localhost:7860/
|
| 151 |
+
```
|
| 152 |
+
|
| 153 |
+
클라우드 서비스에서 Docker 배포용:
|
| 154 |
+
|
| 155 |
+
<div>
|
| 156 |
+
<a href="https://www.heroku.com/deploy?template=https://github.com/Byaidu/PDFMathTranslate">
|
| 157 |
+
<img src="https://www.herokucdn.com/deploy/button.svg" alt="Deploy" height="26"></a>
|
| 158 |
+
<a href="https://render.com/deploy">
|
| 159 |
+
<img src="https://render.com/images/deploy-to-render-button.svg" alt="Deploy to Koyeb" height="26"></a>
|
| 160 |
+
<a href="https://zeabur.com/templates/5FQIGX?referralCode=reycn">
|
| 161 |
+
<img src="https://zeabur.com/button.svg" alt="Deploy on Zeabur" height="26"></a>
|
| 162 |
+
<a href="https://app.koyeb.com/deploy?type=git&builder=buildpack&repository=github.com/Byaidu/PDFMathTranslate&branch=main&name=pdf-math-translate">
|
| 163 |
+
<img src="https://www.koyeb.com/static/images/deploy/button.svg" alt="Deploy to Koyeb" height="26"></a>
|
| 164 |
+
</div>
|
| 165 |
+
|
| 166 |
+
<h2 id="usage">고급 옵션</h2>
|
| 167 |
+
|
| 168 |
+
커맨드라인에서 번역 명령을 실행하여 현재 작업 디렉토리에 번역된 문서 `example-mono.pdf`와 이중 언어 문서 `example-dual.pdf`를 생성합니다. 기본적으로 Google 번역 서비스를 사용합니다. 더 많은 지원 번역 서비스는 [여기](https://github.com/Byaidu/PDFMathTranslate/blob/main/docs/ADVANCED.md#services)에서 찾을 수 있습니다.
|
| 169 |
+
|
| 170 |
+
<img src="./images/cmd.explained.png" width="580px" alt="cmd"/>
|
| 171 |
+
|
| 172 |
+
다음 표에 참고용으로 모든 고급 옵션을 나열했습니다:
|
| 173 |
+
|
| 174 |
+
| 옵션 | 기능 | 예시 |
|
| 175 |
+
| -------------- | ---------------------------------------------------------------------------------------------------------------- | ---------------------------------------------- |
|
| 176 |
+
| files | 로컬 파일 | `pdf2zh ~/local.pdf` |
|
| 177 |
+
| links | 온라인 파일 | `pdf2zh http://arxiv.org/paper.pdf` |
|
| 178 |
+
| `-i` | [GUI 진입](#gui) | `pdf2zh -i` |
|
| 179 |
+
| `-p` | [부분 문서 번역](#partial) | `pdf2zh example.pdf -p 1` |
|
| 180 |
+
| `-li` | [소스 언어](#languages) | `pdf2zh example.pdf -li en` |
|
| 181 |
+
| `-lo` | [대상 언어](#languages) | `pdf2zh example.pdf -lo zh` |
|
| 182 |
+
| `-s` | [번역 서비스](#services) | `pdf2zh example.pdf -s deepl` |
|
| 183 |
+
| `-t` | [멀티스레드](#threads) | `pdf2zh example.pdf -t 1` |
|
| 184 |
+
| `-o` | 출력 디렉토리 | `pdf2zh example.pdf -o output` |
|
| 185 |
+
| `-f`, `-c` | [예외](#exceptions) | `pdf2zh example.pdf -f "(MS.*)"` |
|
| 186 |
+
| `--share` | [gradio 공개 링크 얻기] | `pdf2zh -i --share` |
|
| 187 |
+
| `--authorized` | [[웹 인증 및 사용자 정의 인증 페이지 추가](https://github.com/Byaidu/PDFMathTranslate/blob/main/docs/ADVANCED.)] | `pdf2zh -i --authorized users.txt [auth.html]` |
|
| 188 |
+
| `--prompt` | [사용자 정의 대형 모델 프롬프트 사용] | `pdf2zh --prompt [prompt.txt]` |
|
| 189 |
+
| `--onnx` | [사용자 정의 DocLayout-YOLO ONNX 모델 사용] | `pdf2zh --onnx [onnx/model/path]` |
|
| 190 |
+
| `--serverport` | [사용자 정의 WebUI 포트 사용] | `pdf2zh --serverport 7860` |
|
| 191 |
+
| `--dir` | [배치 번역] | `pdf2zh --dir /path/to/translate/` |
|
| 192 |
+
| `--config` | [구성 파일](https://github.com/Byaidu/PDFMathTranslate/blob/main/docs/ADVANCED.md#cofig) | `pdf2zh --config /path/to/config/config.json` |
|
| 193 |
+
|
| 194 |
+
<h3 id="partial">전체 또는 부분 문서 번역</h3>
|
| 195 |
+
|
| 196 |
+
- **전체 번역**
|
| 197 |
+
|
| 198 |
+
```bash
|
| 199 |
+
pdf2zh example.pdf
|
| 200 |
+
```
|
| 201 |
+
|
| 202 |
+
- **부분 번역**
|
| 203 |
+
|
| 204 |
+
```bash
|
| 205 |
+
pdf2zh example.pdf -p 1-3,5
|
| 206 |
+
```
|
| 207 |
+
|
| 208 |
+
<h3 id="language">소스 언어와 대상 언어 지정</h3>
|
| 209 |
+
|
| 210 |
+
[Google Languages Codes](https://developers.google.com/admin-sdk/directory/v1/languages), [DeepL Languages Codes](https://developers.deepl.com/docs/resources/supported-languages) 참조
|
| 211 |
+
|
| 212 |
+
```bash
|
| 213 |
+
pdf2zh example.pdf -li en -lo ko
|
| 214 |
+
```
|
| 215 |
+
|
| 216 |
+
<h3 id="services">다른 서비스로 번역</h3>
|
| 217 |
+
|
| 218 |
+
다음 표는 각 번역 서비스에 필요한 [환경 변수](https://chatgpt.com/share/6734a83d-9d48-800e-8a46-f57ca6e8bcb4)를 보여줍니다. 각 서비스를 사용하기 전에 이러한 변수를 설정하세요.
|
| 219 |
+
|
| 220 |
+
| **번역기** | **서비스** | **환경 변수** | **기본값** | **참고** |
|
| 221 |
+
| ------------------- | -------------- | --------------------------------------------------------------------- | -------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
| 222 |
+
| **Google (기본)** | `google` | 없음 | N/A | 없음 |
|
| 223 |
+
| **Bing** | `bing` | 없음 | N/A | 없음 |
|
| 224 |
+
| **DeepL** | `deepl` | `DEEPL_AUTH_KEY` | `[Your Key]` | [DeepL](https://support.deepl.com/hc/en-us/articles/360020695820-API-Key-for-DeepL-s-API) 참조 |
|
| 225 |
+
| **DeepLX** | `deeplx` | `DEEPLX_ENDPOINT` | `https://api.deepl.com/translate` | [DeepLX](https://github.com/OwO-Network/DeepLX) 참조 |
|
| 226 |
+
| **Ollama** | `ollama` | `OLLAMA_HOST`, `OLLAMA_MODEL` | `http://127.0.0.1:11434`, `gemma2` | [Ollama](https://github.com/ollama/ollama) 참조 |
|
| 227 |
+
| **OpenAI** | `openai` | `OPENAI_BASE_URL`, `OPENAI_API_KEY`, `OPENAI_MODEL` | `https://api.openai.com/v1`, `[Your Key]`, `gpt-4o-mini` | [OpenAI](https://platform.openai.com/docs/overview) 참조 |
|
| 228 |
+
| **AzureOpenAI** | `azure-openai` | `AZURE_OPENAI_BASE_URL`, `AZURE_OPENAI_API_KEY`, `AZURE_OPENAI_MODEL` | `[Your Endpoint]`, `[Your Key]`, `gpt-4o-mini` | [Azure OpenAI](https://learn.microsoft.com/zh-cn/azure/ai-services/openai/chatgpt-quickstart?tabs=command-line%2Cjavascript-keyless%2Ctypescript-keyless%2Cpython&pivots=programming-language-python) 참조 |
|
| 229 |
+
| **Zhipu** | `zhipu` | `ZHIPU_API_KEY`, `ZHIPU_MODEL` | `[Your Key]`, `glm-4-flash` | [Zhipu](https://open.bigmodel.cn/dev/api/thirdparty-frame/openai-sdk) 참조 |
|
| 230 |
+
| **ModelScope** | `modelscope` | `MODELSCOPE_API_KEY`, `MODELSCOPE_MODEL` | `[Your Key]`, `Qwen/Qwen2.5-Coder-32B-Instruct` | [ModelScope](https://www.modelscope.cn/docs/model-service/API-Inference/intro) 참조 |
|
| 231 |
+
| **Silicon** | `silicon` | `SILICON_API_KEY`, `SILICON_MODEL` | `[Your Key]`, `Qwen/Qwen2.5-7B-Instruct` | [SiliconCloud](https://docs.siliconflow.cn/quickstart) 참조 |
|
| 232 |
+
| **Gemini** | `gemini` | `GEMINI_API_KEY`, `GEMINI_MODEL` | `[Your Key]`, `gemini-1.5-flash` | [Gemini](https://ai.google.dev/gemini-api/docs/openai) 참조 |
|
| 233 |
+
| **Azure** | `azure` | `AZURE_ENDPOINT`, `AZURE_API_KEY` | `https://api.translator.azure.cn`, `[Your Key]` | [Azure](https://docs.azure.cn/en-us/ai-services/translator/text-translation-overview) 참조 |
|
| 234 |
+
| **Tencent** | `tencent` | `TENCENTCLOUD_SECRET_ID`, `TENCENTCLOUD_SECRET_KEY` | `[Your ID]`, `[Your Key]` | [Tencent](https://www.tencentcloud.com/products/tmt?from_qcintl=122110104) 참조 |
|
| 235 |
+
| **Dify** | `dify` | `DIFY_API_URL`, `DIFY_API_KEY` | `[Your DIFY URL]`, `[Your Key]` | [Dify](https://github.com/langgenius/dify) 참조, Dify의 워크플로우 입력에서 lang_out, lang_in, text 세 변수를 정의해야 합니다. |
|
| 236 |
+
| **AnythingLLM** | `anythingllm` | `AnythingLLM_URL`, `AnythingLLM_APIKEY` | `[Your AnythingLLM URL]`, `[Your Key]` | [anything-llm](https://github.com/Mintplex-Labs/anything-llm) 참조 |
|
| 237 |
+
| **Argos Translate** | `argos` | | | [argos-translate](https://github.com/argosopentech/argos-translate) 참조 |
|
| 238 |
+
| **Grok** | `grok` | `GORK_API_KEY`, `GORK_MODEL` | `[Your GORK_API_KEY]`, `grok-2-1212` | [Grok](https://docs.x.ai/docs/overview) 참조 |
|
| 239 |
+
| **DeepSeek** | `deepseek` | `DEEPSEEK_API_KEY`, `DEEPSEEK_MODEL` | `[Your DEEPSEEK_API_KEY]`, `deepseek-chat` | [DeepSeek](https://www.deepseek.com/) 참조 |
|
| 240 |
+
| **OpenAI-Liked** | `openailiked` | `OPENAILIKED_BASE_URL`, `OPENAILIKED_API_KEY`, `OPENAILIKED_MODEL` | `url`, `[Your Key]`, `model name` | 없음 |
|
| 241 |
+
|
| 242 |
+
위 표에 없는 OpenAI API와 호환되는 대형 언어 모델의 경우, 표의 OpenAI와 동일한 방식으로 환경 변수를 설정할 수 있습니다.
|
| 243 |
+
|
| 244 |
+
`-s service` 또는 `-s service:model`을 사��하여 번역 서비스를 지정합니다:
|
| 245 |
+
|
| 246 |
+
```bash
|
| 247 |
+
pdf2zh example.pdf -s openai:gpt-4o-mini
|
| 248 |
+
```
|
| 249 |
+
|
| 250 |
+
또는 환경 변수로 모델을 지정합니다:
|
| 251 |
+
|
| 252 |
+
```bash
|
| 253 |
+
set OPENAI_MODEL=gpt-4o-mini
|
| 254 |
+
pdf2zh example.pdf -s openai
|
| 255 |
+
```
|
| 256 |
+
|
| 257 |
+
PowerShell 사용자의 경우:
|
| 258 |
+
|
| 259 |
+
```shell
|
| 260 |
+
$env:OPENAI_MODEL = gpt-4o-mini
|
| 261 |
+
pdf2zh example.pdf -s openai
|
| 262 |
+
```
|
| 263 |
+
|
| 264 |
+
<h3 id="exceptions">예외 지정</h3>
|
| 265 |
+
|
| 266 |
+
정규식을 사용하여 보존해야 할 수식 폰트와 문자를 지정합니다:
|
| 267 |
+
|
| 268 |
+
```bash
|
| 269 |
+
pdf2zh example.pdf -f "(CM[^RT].*|MS.*|.*Ital)" -c "(\(|\||\)|\+|=|\d|[\u0080-\ufaff])"
|
| 270 |
+
```
|
| 271 |
+
|
| 272 |
+
기본적으로 `Latex`, `Mono`, `Code`, `Italic`, `Symbol` 및 `Math` 폰트를 보존합니다:
|
| 273 |
+
|
| 274 |
+
```bash
|
| 275 |
+
pdf2zh example.pdf -f "(CM[^R]|MS.M|XY|MT|BL|RM|EU|LA|RS|LINE|LCIRCLE|TeX-|rsfs|txsy|wasy|stmary|.*Mono|.*Code|.*Ital|.*Sym|.*Math)"
|
| 276 |
+
```
|
| 277 |
+
|
| 278 |
+
<h3 id="threads">스레드 수 지정</h3>
|
| 279 |
+
|
| 280 |
+
`-t`를 사용하여 번역에 사용할 스레드 수를 지정합니다:
|
| 281 |
+
|
| 282 |
+
```bash
|
| 283 |
+
pdf2zh example.pdf -t 1
|
| 284 |
+
```
|
| 285 |
+
|
| 286 |
+
<h3 id="prompt">사용자 정의 프롬프트</h3>
|
| 287 |
+
|
| 288 |
+
`--prompt`를 사용하여 LLM에서 사용할 프롬프트를 지정합니다:
|
| 289 |
+
|
| 290 |
+
```bash
|
| 291 |
+
pdf2zh example.pdf -pr prompt.txt
|
| 292 |
+
```
|
| 293 |
+
|
| 294 |
+
`prompt.txt` 예시:
|
| 295 |
+
|
| 296 |
+
```txt
|
| 297 |
+
[
|
| 298 |
+
{
|
| 299 |
+
"role": "system",
|
| 300 |
+
"content": "You are a professional,authentic machine translation engine.",
|
| 301 |
+
},
|
| 302 |
+
{
|
| 303 |
+
"role": "user",
|
| 304 |
+
"content": "Translate the following markdown source text to ${lang_out}. Keep the formula notation {{v*}} unchanged. Output translation directly without any additional text.\nSource Text: ${text}\nTranslated Text:",
|
| 305 |
+
},
|
| 306 |
+
]
|
| 307 |
+
```
|
| 308 |
+
|
| 309 |
+
사용자 정의 프롬프트 파일에서는 다음 세 가지 변수를 사용할 수 있습니다:
|
| 310 |
+
|
| 311 |
+
| **변수** | **내용** |
|
| 312 |
+
| ---------- | ------------- |
|
| 313 |
+
| `lang_in` | 소스 언어 |
|
| 314 |
+
| `lang_out` | 대상 언어 |
|
| 315 |
+
| `text` | 번역할 텍스트 |
|
| 316 |
+
|
| 317 |
+
<h2 id="todo">API</h2>
|
| 318 |
+
|
| 319 |
+
### Python
|
| 320 |
+
|
| 321 |
+
```python
|
| 322 |
+
from pdf2zh import translate, translate_stream
|
| 323 |
+
|
| 324 |
+
params = {"lang_in": "en", "lang_out": "ko", "service": "google", "thread": 4}
|
| 325 |
+
file_mono, file_dual = translate(files=["example.pdf"], **params)[0]
|
| 326 |
+
with open("example.pdf", "rb") as f:
|
| 327 |
+
stream_mono, stream_dual = translate_stream(stream=f.read(), **params)
|
| 328 |
+
```
|
| 329 |
+
|
| 330 |
+
### HTTP
|
| 331 |
+
|
| 332 |
+
```bash
|
| 333 |
+
pip install pdf2zh[backend]
|
| 334 |
+
pdf2zh --flask
|
| 335 |
+
pdf2zh --celery worker
|
| 336 |
+
```
|
| 337 |
+
|
| 338 |
+
```bash
|
| 339 |
+
curl http://localhost:11008/v1/translate -F "file=@example.pdf" -F "data={\"lang_in\":\"en\",\"lang_out\":\"ko\",\"service\":\"google\",\"thread\":4}"
|
| 340 |
+
{"id":"d9894125-2f4e-45ea-9d93-1a9068d2045a"}
|
| 341 |
+
|
| 342 |
+
curl http://localhost:11008/v1/translate/d9894125-2f4e-45ea-9d93-1a9068d2045a
|
| 343 |
+
{"info":{"n":13,"total":506},"state":"PROGRESS"}
|
| 344 |
+
|
| 345 |
+
curl http://localhost:11008/v1/translate/d9894125-2f4e-45ea-9d93-1a9068d2045a
|
| 346 |
+
{"state":"SUCCESS"}
|
| 347 |
+
|
| 348 |
+
curl http://localhost:11008/v1/translate/d9894125-2f4e-45ea-9d93-1a9068d2045a/mono --output example-mono.pdf
|
| 349 |
+
|
| 350 |
+
curl http://localhost:11008/v1/translate/d9894125-2f4e-45ea-9d93-1a9068d2045a/dual --output example-dual.pdf
|
| 351 |
+
|
| 352 |
+
curl http://localhost:11008/v1/translate/d9894125-2f4e-45ea-9d93-1a9068d2045a -X DELETE
|
| 353 |
+
```
|
| 354 |
+
|
| 355 |
+
<h2 id="acknowledgement">감사의 말</h2>
|
| 356 |
+
|
| 357 |
+
- 문서 병합: [PyMuPDF](https://github.com/pymupdf/PyMuPDF)
|
| 358 |
+
- 문서 파싱: [Pdfminer.six](https://github.com/pdfminer/pdfminer.six)
|
| 359 |
+
- 문서 추출: [MinerU](https://github.com/opendatalab/MinerU)
|
| 360 |
+
- 문서 미리보기: [Gradio PDF](https://github.com/freddyaboulton/gradio-pdf)
|
| 361 |
+
- 멀티스레드 번역: [MathTranslate](https://github.com/SUSYUSTC/MathTranslate)
|
| 362 |
+
- 레이아웃 파싱: [DocLayout-YOLO](https://github.com/opendatalab/DocLayout-YOLO)
|
| 363 |
+
- 문서 표준: [PDF Explained](https://zxyle.github.io/PDF-Explained/), [PDF Cheat Sheets](https://pdfa.org/resource/pdf-cheat-sheets/)
|
| 364 |
+
- 다국어 폰트: [Go Noto Universal](https://github.com/satbyy/go-noto-universal)
|
| 365 |
+
|
| 366 |
+
<h2 id="contrib">기여자</h2>
|
| 367 |
+
|
| 368 |
+
<a href="https://github.com/Byaidu/PDFMathTranslate/graphs/contributors">
|
| 369 |
+
<img src="https://opencollective.com/PDFMathTranslate/contributors.svg?width=890&button=false" />
|
| 370 |
+
</a>
|
| 371 |
+
|
| 372 |
+

|
| 373 |
+
|
| 374 |
+
<h2 id="star_hist">스타 히스토리</h2>
|
| 375 |
+
|
| 376 |
+
<a href="https://star-history.com/#Byaidu/PDFMathTranslate&Date">
|
| 377 |
+
<picture>
|
| 378 |
+
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=Byaidu/PDFMathTranslate&type=Date&theme=dark" />
|
| 379 |
+
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=Byaidu/PDFMathTranslate&type=Date" />
|
| 380 |
+
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=Byaidu/PDFMathTranslate&type=Date"/>
|
| 381 |
+
</picture>
|
| 382 |
+
</a>
|
docs/README_zh-CN.md
ADDED
|
@@ -0,0 +1,312 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<div align="center">
|
| 2 |
+
|
| 3 |
+
[English](../README.md) | 简体中文 | [繁體中文](README_zh-TW.md) | [日本語](README_ja-JP.md)
|
| 4 |
+
|
| 5 |
+
<img src="./images/banner.png" width="320px" alt="PDF2ZH"/>
|
| 6 |
+
|
| 7 |
+
<h2 id="title">PDFMathTranslate</h2>
|
| 8 |
+
|
| 9 |
+
<p>
|
| 10 |
+
<!-- PyPI -->
|
| 11 |
+
<a href="https://pypi.org/project/pdf2zh/">
|
| 12 |
+
<img src="https://img.shields.io/pypi/v/pdf2zh"/></a>
|
| 13 |
+
<a href="https://pepy.tech/projects/pdf2zh">
|
| 14 |
+
<img src="https://static.pepy.tech/badge/pdf2zh"></a>
|
| 15 |
+
<a href="https://hub.docker.com/repository/docker/byaidu/pdf2zh">
|
| 16 |
+
<img src="https://img.shields.io/docker/pulls/byaidu/pdf2zh"></a>
|
| 17 |
+
<!-- License -->
|
| 18 |
+
<a href="./LICENSE">
|
| 19 |
+
<img src="https://img.shields.io/github/license/Byaidu/PDFMathTranslate"/></a>
|
| 20 |
+
<a href="https://huggingface.co/spaces/reycn/PDFMathTranslate-Docker">
|
| 21 |
+
<img src="https://img.shields.io/badge/%F0%9F%A4%97-Online%20Demo-FF9E0D"/></a>
|
| 22 |
+
<a href="https://www.modelscope.cn/studios/AI-ModelScope/PDFMathTranslate">
|
| 23 |
+
<img src="https://img.shields.io/badge/ModelScope-Demo-blue"></a>
|
| 24 |
+
<a href="https://github.com/Byaidu/PDFMathTranslate/pulls">
|
| 25 |
+
<img src="https://img.shields.io/badge/contributions-welcome-green"/></a>
|
| 26 |
+
<a href="https://gitcode.com/Byaidu/PDFMathTranslate/overview">
|
| 27 |
+
<img src="https://gitcode.com/Byaidu/PDFMathTranslate/star/badge.svg"></a>
|
| 28 |
+
<a href="https://t.me/+Z9_SgnxmsmA5NzBl">
|
| 29 |
+
<img src="https://img.shields.io/badge/Telegram-2CA5E0?style=flat-squeare&logo=telegram&logoColor=white"/></a>
|
| 30 |
+
</p>
|
| 31 |
+
|
| 32 |
+
<a href="https://trendshift.io/repositories/12424" target="_blank"><img src="https://trendshift.io/api/badge/repositories/12424" alt="Byaidu%2FPDFMathTranslate | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
|
| 33 |
+
|
| 34 |
+
</div>
|
| 35 |
+
|
| 36 |
+
科学 PDF 文档翻译及双语对照工具
|
| 37 |
+
|
| 38 |
+
- 📊 保留公式、图表、目录和注释 *([预览效果](#preview))*
|
| 39 |
+
- 🌐 支持 [多种语言](./ADVANCED.md#language) 和 [诸多翻译服务](./ADVANCED.md#services)
|
| 40 |
+
- 🤖 提供 [命令行工具](#usage),[图形交互界面](#gui),以及 [容器化部署](#docker)
|
| 41 |
+
|
| 42 |
+
欢迎在 [GitHub Issues](https://github.com/Byaidu/PDFMathTranslate/issues) 或 [Telegram 用户群](https://t.me/+Z9_SgnxmsmA5NzBl)
|
| 43 |
+
|
| 44 |
+
有关如何贡献的详细信息,请查阅 [贡献指南](https://github.com/Byaidu/PDFMathTranslate/wiki/Contribution-Guide---%E8%B4%A1%E7%8C%AE%E6%8C%87%E5%8D%97)
|
| 45 |
+
|
| 46 |
+
<h2 id="updates">更新</h2>
|
| 47 |
+
|
| 48 |
+
- [2025 年 2 月 22 日] 更好的发布 CI 和精心打包的 windows-amd64 exe (由 [@awwaawwa](https://github.com/awwaawwa) 提供)
|
| 49 |
+
- [2024 年 12 月 24 日] 翻译器现在支持在 [Xinference](https://github.com/xorbitsai/inference) 上使用本地模型 _(由 [@imClumsyPanda](https://github.com/imClumsyPanda) 提供)_
|
| 50 |
+
- [2024 年 12 月 19 日] 现在支持非 PDF/A 文档,使用 `-cp` _(由 [@reycn](https://github.com/reycn) 提供)_
|
| 51 |
+
- [2024 年 12 月 13 日] 额外支持后端 _(由 [@YadominJinta](https://github.com/YadominJinta) 提供)_
|
| 52 |
+
- [2024 年 12 月 10 日] 翻译器现在支持 Azure 上的 OpenAI 模型 _(由 [@yidasanqian](https://github.com/yidasanqian) 提供)_
|
| 53 |
+
|
| 54 |
+
<h2 id="preview">预览</h2>
|
| 55 |
+
<div align="center">
|
| 56 |
+
<img src="./images/preview.gif" width="80%"/>
|
| 57 |
+
</div>
|
| 58 |
+
|
| 59 |
+
<h2 id="demo">在线演示 🌟</h2>
|
| 60 |
+
|
| 61 |
+
<h2 id="demo">在线服务 🌟</h2>
|
| 62 |
+
|
| 63 |
+
您可以通过以下演示尝试我们的应用程序:
|
| 64 |
+
|
| 65 |
+
- [公共免费服务](https://pdf2zh.com/) 在线使用,无需安装 _(推荐)_。
|
| 66 |
+
- [沉浸式翻译 - BabelDOC](https://app.immersivetranslate.com/babel-doc/) 每月免费 1000 页 _(推荐)_
|
| 67 |
+
- [在 HuggingFace 上托管的演示](https://huggingface.co/spaces/reycn/PDFMathTranslate-Docker)
|
| 68 |
+
- [在 ModelScope 上托管的演示](https://www.modelscope.cn/studios/AI-ModelScope/PDFMathTranslate) 无需安装。
|
| 69 |
+
|
| 70 |
+
请注意演示的计算资源有限,请避免滥用它们。
|
| 71 |
+
<h2 id="install">安装和使用</h2>
|
| 72 |
+
|
| 73 |
+
### 方法
|
| 74 |
+
|
| 75 |
+
针对不同的使用案例,我们提供不同的方法来使用我们的程序:
|
| 76 |
+
|
| 77 |
+
<details open>
|
| 78 |
+
<summary>1. UV 安装</summary>
|
| 79 |
+
|
| 80 |
+
1. 安装 Python (3.10 <= 版本 <= 3.12)
|
| 81 |
+
2. 安装我们的包:
|
| 82 |
+
|
| 83 |
+
```bash
|
| 84 |
+
pip install uv
|
| 85 |
+
uv tool install --python 3.12 pdf2zh
|
| 86 |
+
```
|
| 87 |
+
|
| 88 |
+
3. 执行翻译,文件生成在 [当前工作目录](https://chatgpt.com/share/6745ed36-9acc-800e-8a90-59204bd13444):
|
| 89 |
+
|
| 90 |
+
```bash
|
| 91 |
+
pdf2zh document.pdf
|
| 92 |
+
```
|
| 93 |
+
|
| 94 |
+
</details>
|
| 95 |
+
|
| 96 |
+
<details>
|
| 97 |
+
<summary>2. Windows exe</summary>
|
| 98 |
+
|
| 99 |
+
1. 从 [发布页面](https://github.com/Byaidu/PDFMathTranslate/releases) 下载 pdf2zh-version-win64.zip
|
| 100 |
+
|
| 101 |
+
2. 解压缩并双击 `pdf2zh.exe` 运行。
|
| 102 |
+
|
| 103 |
+
</details>
|
| 104 |
+
|
| 105 |
+
<details>
|
| 106 |
+
<summary id="gui">3. 图形用户界面</summary>
|
| 107 |
+
1. 安装 Python (3.10 <= 版本 <= 3.12)
|
| 108 |
+
2. 安装我们的包:
|
| 109 |
+
|
| 110 |
+
```bash
|
| 111 |
+
pip install pdf2zh
|
| 112 |
+
```
|
| 113 |
+
|
| 114 |
+
3. 在浏览器中开始使用:
|
| 115 |
+
|
| 116 |
+
```bash
|
| 117 |
+
pdf2zh -i
|
| 118 |
+
```
|
| 119 |
+
|
| 120 |
+
4. 如果您的浏览器没有自动启动,请访问
|
| 121 |
+
|
| 122 |
+
```bash
|
| 123 |
+
http://localhost:7860/
|
| 124 |
+
```
|
| 125 |
+
|
| 126 |
+
<img src="./images/gui.gif" width="500"/>
|
| 127 |
+
|
| 128 |
+
有关更多详细信息,请参阅 [GUI 文档](./README_GUI.md)���
|
| 129 |
+
|
| 130 |
+
</details>
|
| 131 |
+
|
| 132 |
+
<details>
|
| 133 |
+
<summary id="docker">4. Docker</summary>
|
| 134 |
+
|
| 135 |
+
1. 拉取并运行:
|
| 136 |
+
|
| 137 |
+
```bash
|
| 138 |
+
docker pull byaidu/pdf2zh
|
| 139 |
+
docker run -d -p 7860:7860 byaidu/pdf2zh
|
| 140 |
+
```
|
| 141 |
+
|
| 142 |
+
2. 在浏览器中打开:
|
| 143 |
+
|
| 144 |
+
```
|
| 145 |
+
http://localhost:7860/
|
| 146 |
+
```
|
| 147 |
+
|
| 148 |
+
对于云服务上的 docker 部署:
|
| 149 |
+
|
| 150 |
+
<div>
|
| 151 |
+
<a href="https://www.heroku.com/deploy?template=https://github.com/Byaidu/PDFMathTranslate">
|
| 152 |
+
<img src="https://www.herokucdn.com/deploy/button.svg" alt="部署" height="26"></a>
|
| 153 |
+
<a href="https://render.com/deploy">
|
| 154 |
+
<img src="https://render.com/images/deploy-to-render-button.svg" alt="部署到 Koyeb" height="26"></a>
|
| 155 |
+
<a href="https://zeabur.com/templates/5FQIGX?referralCode=reycn">
|
| 156 |
+
<img src="https://zeabur.com/button.svg" alt="在 Zeabur 上部署" height="26"></a>
|
| 157 |
+
<a href="https://template.sealos.io/deploy?templateName=pdf2zh">
|
| 158 |
+
<img src="https://sealos.io/Deploy-on-Sealos.svg" alt="在 Sealos 上部署" height="26"></a>
|
| 159 |
+
<a href="https://app.koyeb.com/deploy?type=git&builder=buildpack&repository=github.com/Byaidu/PDFMathTranslate&branch=main&name=pdf-math-translate">
|
| 160 |
+
<img src="https://www.koyeb.com/static/images/deploy/button.svg" alt="部署到 Koyeb" height="26"></a>
|
| 161 |
+
</div>
|
| 162 |
+
|
| 163 |
+
</details>
|
| 164 |
+
|
| 165 |
+
<details>
|
| 166 |
+
<summary>5. Zotero 插件</summary>
|
| 167 |
+
|
| 168 |
+
有关更多细节,请参见 [Zotero PDF2zh](https://github.com/guaguastandup/zotero-pdf2zh)。
|
| 169 |
+
|
| 170 |
+
</details>
|
| 171 |
+
|
| 172 |
+
<details>
|
| 173 |
+
<summary>6. 命令行</summary>
|
| 174 |
+
|
| 175 |
+
1. 已安装 Python(3.10 <= 版本 <= 3.12)
|
| 176 |
+
2. 安装我们的包:
|
| 177 |
+
|
| 178 |
+
```bash
|
| 179 |
+
pip install pdf2zh
|
| 180 |
+
```
|
| 181 |
+
|
| 182 |
+
3. 执行翻译,文件生成在 [当前工作目录](https://chatgpt.com/share/6745ed36-9acc-800e-8a90-59204bd13444):
|
| 183 |
+
|
| 184 |
+
```bash
|
| 185 |
+
pdf2zh document.pdf
|
| 186 |
+
```
|
| 187 |
+
|
| 188 |
+
</details>
|
| 189 |
+
|
| 190 |
+
> [!TIP]
|
| 191 |
+
>
|
| 192 |
+
> - 如果你使用 Windows 并在下载后无法打开文件,请安装 [vc_redist.x64.exe](https://aka.ms/vs/17/release/vc_redist.x64.exe) 并重试。
|
| 193 |
+
>
|
| 194 |
+
> - 如果你无法访问 Docker Hub,请尝试在 [GitHub 容器注册中心](https://github.com/Byaidu/PDFMathTranslate/pkgs/container/pdfmathtranslate) 上使用该镜像。
|
| 195 |
+
> ```bash
|
| 196 |
+
> docker pull ghcr.io/byaidu/pdfmathtranslate
|
| 197 |
+
> docker run -d -p 7860:7860 ghcr.io/byaidu/pdfmathtranslate
|
| 198 |
+
> ```
|
| 199 |
+
|
| 200 |
+
### 无法安装?
|
| 201 |
+
|
| 202 |
+
当前程序在工作前需要一个 AI 模型 (`wybxc/DocLayout-YOLO-DocStructBench-onnx`),一些用户由于网络问题无法下载。如果你在下载此模型时遇到问题,我们提供以下环境变量的解决方法:
|
| 203 |
+
|
| 204 |
+
```shell
|
| 205 |
+
set HF_ENDPOINT=https://hf-mirror.com
|
| 206 |
+
```
|
| 207 |
+
|
| 208 |
+
对于 PowerShell 用户:
|
| 209 |
+
|
| 210 |
+
```shell
|
| 211 |
+
$env:HF_ENDPOINT = https://hf-mirror.com
|
| 212 |
+
```
|
| 213 |
+
|
| 214 |
+
如果此解决方案对您无效或您遇到其他问题,请参阅 [常见问题解答](https://github.com/Byaidu/PDFMathTranslate/wiki#-faq--%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98)。
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
<h2 id="usage">高级选项</h2>
|
| 218 |
+
|
| 219 |
+
在命令行中执行翻译命令,在当前工作目录下生成译文文档 `example-mono.pdf` 和双语对照文档 `example-dual.pdf`,默认使用 Google 翻译服务,更多支持的服务在[这里](https://github.com/Byaidu/PDFMathTranslate/blob/main/docs/ADVANCED.md#services))。
|
| 220 |
+
|
| 221 |
+
<img src="./images/cmd.explained.png" width="580px" alt="cmd"/>
|
| 222 |
+
|
| 223 |
+
在下表中,我们列出了所有高级选项供参考:
|
| 224 |
+
|
| 225 |
+
| 选项 | 功能 | 示例 |
|
| 226 |
+
| ------------ | ------------------------------------------------------------------------------------------------------------- | ---------------------------------------------- |
|
| 227 |
+
| files | 本地文件 | `pdf2zh ~/local.pdf` |
|
| 228 |
+
| links | 在线文件 | `pdf2zh http://arxiv.org/paper.pdf` |
|
| 229 |
+
| `-i` | [进入 GUI](#gui) | `pdf2zh -i` |
|
| 230 |
+
| `-p` | [部分文档翻译](https://github.com/Byaidu/PDFMathTranslate/blob/main/docs/ADVANCED.md#partial) | `pdf2zh example.pdf -p 1` |
|
| 231 |
+
| `-li` | [源语言](https://github.com/Byaidu/PDFMathTranslate/blob/main/docs/ADVANCED.md#languages) | `pdf2zh example.pdf -li en` |
|
| 232 |
+
| `-lo` | [目标语言](https://github.com/Byaidu/PDFMathTranslate/blob/main/docs/ADVANCED.md#languages) | `pdf2zh example.pdf -lo zh` |
|
| 233 |
+
| `-s` | [翻译服务](https://github.com/Byaidu/PDFMathTranslate/blob/main/docs/ADVANCED.md#services) | `pdf2zh example.pdf -s deepl` |
|
| 234 |
+
| `-t` | [多线程](https://github.com/Byaidu/PDFMathTranslate/blob/main/docs/ADVANCED.md#threads) | `pdf2zh example.pdf -t 1` |
|
| 235 |
+
| `-o` | 输出目录 | `pdf2zh example.pdf -o output` |
|
| 236 |
+
| `-f`, `-c` | [异常](https://github.com/Byaidu/PDFMathTranslate/blob/main/docs/ADVANCED.md#exceptions) | `pdf2zh example.pdf -f "(MS.*)"` |
|
| 237 |
+
| `-cp` | 兼容模式 | `pdf2zh example.pdf --compatible` |
|
| 238 |
+
| `--share` | 公开链接 | `pdf2zh -i --share` |
|
| 239 |
+
| `--authorized` | [授权](https://github.com/Byaidu/PDFMathTranslate/blob/main/docs/ADVANCED.md#auth) | `pdf2zh -i --authorized users.txt [auth.html]` |
|
| 240 |
+
| `--prompt` | [自定义提示](https://github.com/Byaidu/PDFMathTranslate/blob/main/docs/ADVANCED.md#prompt) | `pdf2zh --prompt [prompt.txt]` |
|
| 241 |
+
| `--onnx` | [使用自定义 DocLayout-YOLO ONNX 模型] | `pdf2zh --onnx [onnx/model/path]` |
|
| 242 |
+
| `--serverport` | [使用自定义 WebUI 端口] | `pdf2zh --serverport 7860` |
|
| 243 |
+
| `--dir` | [批量翻译] | `pdf2zh --dir /path/to/translate/` |
|
| 244 |
+
| `--config` | [配置文件](https://github.com/Byaidu/PDFMathTranslate/blob/main/docs/ADVANCED.md#cofig) | `pdf2zh --config /path/to/config/config.json` |
|
| 245 |
+
| `--serverport` | [自定义 gradio 服务器端口] | `pdf2zh --serverport 7860` |
|
| 246 |
+
| `--babeldoc`| 使用实验性后端 [BabelDOC](https://funstory-ai.github.io/BabelDOC/) 翻译 |`pdf2zh --babeldoc` -s openai example.pdf|
|
| 247 |
+
|
| 248 |
+
有关详细说明,请参阅我们的文档 [高级用法](./ADVANCED.md),以获取每个选项的完整列表。
|
| 249 |
+
|
| 250 |
+
<h2 id="downstream">二次开发 (API)</h2>
|
| 251 |
+
|
| 252 |
+
当前的 pdf2zh API 暂时已弃用。API 将在 [pdf2zh 2.0](https://github.com/Byaidu/PDFMathTranslate/issues/586)发布后重新提供。对于需要程序化访问的用户,请使用[BabelDOC](https://github.com/funstory-ai/BabelDOC)的 `babeldoc.high_level.async_translate` 函数。
|
| 253 |
+
|
| 254 |
+
API 暂时弃用意味着:相关代码暂时不会被移除,但不会提供技术支持,也不会修复 bug。
|
| 255 |
+
|
| 256 |
+
<!-- 对于下游应用程序,请参阅我们的文档 [API 详细信息](./APIS.md),以获取更多信息:
|
| 257 |
+
- [Python API](./APIS.md#api-python),如何在其他 Python 程序中使用该程序
|
| 258 |
+
- [HTTP API](./APIS.md#api-http),如何与已安装该程序的服务器进行通信 -->
|
| 259 |
+
|
| 260 |
+
<h2 id="todo">待办事项</h2>
|
| 261 |
+
|
| 262 |
+
- [ ] 使用基于 DocLayNet 的模型解析布局,[PaddleX](https://github.com/PaddlePaddle/PaddleX/blob/17cc27ac3842e7880ca4aad92358d3ef8555429a/paddlex/repo_apis/PaddleDetection_api/object_det/official_categories.py#L81),[PaperMage](https://github.com/allenai/papermage/blob/9cd4bb48cbedab45d0f7a455711438f1632abebe/README.md?plain=1#L102),[SAM2](https://github.com/facebookresearch/sam2)
|
| 263 |
+
|
| 264 |
+
- [ ] 修复页面旋转、目录、列表格式
|
| 265 |
+
|
| 266 |
+
- [ ] 修复旧论文中的像素公式
|
| 267 |
+
|
| 268 |
+
- [ ] 异步重试,除了 KeyboardInterrupt
|
| 269 |
+
|
| 270 |
+
- [ ] 针对西方语言的 Knuth–Plass 算法
|
| 271 |
+
|
| 272 |
+
- [ ] 支持非 PDF/A 文件
|
| 273 |
+
|
| 274 |
+
- [ ] [Zotero](https://github.com/zotero/zotero) 和 [Obsidian](https://github.com/obsidianmd/obsidian-releases) 的插件
|
| 275 |
+
|
| 276 |
+
<h2 id="acknowledgement">致谢</h2>
|
| 277 |
+
|
| 278 |
+
- [Immersive Translation](https://immersivetranslate.com) 为此项目的活跃贡献者提供每月的专业会员兑换码,详细信息请查看:[CONTRIBUTOR_REWARD.md](https://github.com/funstory-ai/BabelDOC/blob/main/docs/CONTRIBUTOR_REWARD.md)
|
| 279 |
+
|
| 280 |
+
- 文档合并:[PyMuPDF](https://github.com/pymupdf/PyMuPDF)
|
| 281 |
+
|
| 282 |
+
- 文档解析:[Pdfminer.six](https://github.com/pdfminer/pdfminer.six)
|
| 283 |
+
|
| 284 |
+
- 文档提取:[MinerU](https://github.com/opendatalab/MinerU)
|
| 285 |
+
|
| 286 |
+
- 文档预览:[Gradio PDF](https://github.com/freddyaboulton/gradio-pdf)
|
| 287 |
+
|
| 288 |
+
- 多线程翻译:[MathTranslate](https://github.com/SUSYUSTC/MathTranslate)
|
| 289 |
+
|
| 290 |
+
- 布局解析:[DocLayout-YOLO](https://github.com/opendatalab/DocLayout-YOLO)
|
| 291 |
+
|
| 292 |
+
- 文档标准:[PDF Explained](https://zxyle.github.io/PDF-Explained/),[PDF Cheat Sheets](https://pdfa.org/resource/pdf-cheat-sheets/)
|
| 293 |
+
|
| 294 |
+
- 多语言字体:[Go Noto Universal](https://github.com/satbyy/go-noto-universal)
|
| 295 |
+
|
| 296 |
+
<h2 id="contrib">贡献者</h2>
|
| 297 |
+
|
| 298 |
+
<a href="https://github.com/Byaidu/PDFMathTranslate/graphs/contributors">
|
| 299 |
+
<img src="https://opencollective.com/PDFMathTranslate/contributors.svg?width=890&button=false" />
|
| 300 |
+
</a>
|
| 301 |
+
|
| 302 |
+

|
| 303 |
+
|
| 304 |
+
<h2 id="star_hist">星标历史</h2>
|
| 305 |
+
|
| 306 |
+
<a href="https://star-history.com/#Byaidu/PDFMathTranslate&Date">
|
| 307 |
+
<picture>
|
| 308 |
+
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=Byaidu/PDFMathTranslate&type=Date&theme=dark" />
|
| 309 |
+
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=Byaidu/PDFMathTranslate&type=Date" />
|
| 310 |
+
<img alt="星标历史图表" src="https://api.star-history.com/svg?repos=Byaidu/PDFMathTranslate&type=Date"/>
|
| 311 |
+
</picture>
|
| 312 |
+
</a>
|
docs/README_zh-TW.md
ADDED
|
@@ -0,0 +1,366 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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ner.png" width="320px" alt="PDF2ZH"/>
|
| 6 |
+
|
| 7 |
+
<h2 id="title">PDFMathTranslate</h2>
|
| 8 |
+
|
| 9 |
+
<p>
|
| 10 |
+
<!-- PyPI -->
|
| 11 |
+
<a href="https://pypi.org/project/pdf2zh/">
|
| 12 |
+
<img src="https://img.shields.io/pypi/v/pdf2zh"/></a>
|
| 13 |
+
<a href="https://pepy.tech/projects/pdf2zh">
|
| 14 |
+
<img src="https://static.pepy.tech/badge/pdf2zh"></a>
|
| 15 |
+
<a href="https://hub.docker.com/repository/docker/byaidu/pdf2zh">
|
| 16 |
+
<img src="https://img.shields.io/docker/pulls/byaidu/pdf2zh"></a>
|
| 17 |
+
<!-- License -->
|
| 18 |
+
<a href="./LICENSE">
|
| 19 |
+
<img src="https://img.shields.io/github/license/Byaidu/PDFMathTranslate"/></a>
|
| 20 |
+
<a href="https://huggingface.co/spaces/reycn/PDFMathTranslate-Docker">
|
| 21 |
+
<img src="https://img.shields.io/badge/%F0%9F%A4%97-Online%20Demo-FF9E0D"/></a>
|
| 22 |
+
<a href="https://www.modelscope.cn/studios/AI-ModelScope/PDFMathTranslate">
|
| 23 |
+
<img src="https://img.shields.io/badge/ModelScope-Demo-blue"></a>
|
| 24 |
+
<a href="https://github.com/Byaidu/PDFMathTranslate/pulls">
|
| 25 |
+
<img src="https://img.shields.io/badge/contributions-welcome-green"/></a>
|
| 26 |
+
<a href="https://gitcode.com/Byaidu/PDFMathTranslate/overview">
|
| 27 |
+
<img src="https://gitcode.com/Byaidu/PDFMathTranslate/star/badge.svg"></a>
|
| 28 |
+
<a href="https://t.me/+Z9_SgnxmsmA5NzBl">
|
| 29 |
+
<img src="https://img.shields.io/badge/Telegram-2CA5E0?style=flat-squeare&logo=telegram&logoColor=white"/></a>
|
| 30 |
+
</p>
|
| 31 |
+
|
| 32 |
+
<a href="https://trendshift.io/repositories/12424" target="_blank"><img src="https://trendshift.io/api/badge/repositories/12424" alt="Byaidu%2FPDFMathTranslate | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
|
| 33 |
+
|
| 34 |
+
</div>
|
| 35 |
+
|
| 36 |
+
科學 PDF 文件翻譯及雙語對照工具
|
| 37 |
+
|
| 38 |
+
- 📊 保留公式、圖表、目錄和註釋 *([預覽效果](#preview))*
|
| 39 |
+
- 🌐 支援 [多種語言](#language) 和 [諸多翻譯服務](#services)
|
| 40 |
+
- 🤖 提供 [命令列工具](#usage)、[圖形使用者介面](#gui),以及 [容器化部署](#docker)
|
| 41 |
+
|
| 42 |
+
歡迎在 [GitHub Issues](https://github.com/Byaidu/PDFMathTranslate/issues) 或 [Telegram 使用者群](https://t.me/+Z9_SgnxmsmA5NzBl)(https://qm.qq.com/q/DixZCxQej0) 中提出回饋
|
| 43 |
+
|
| 44 |
+
如需瞭解如何貢獻的詳細資訊,請查閱 [貢獻指南](https://github.com/Byaidu/PDFMathTranslate/wiki/Contribution-Guide---%E8%B4%A1%E7%8C%AE%E6%8C%87%E5%8D%97)
|
| 45 |
+
|
| 46 |
+
<h2 id="updates">近期更新</h2>
|
| 47 |
+
|
| 48 |
+
- [Dec. 24 2024] 翻譯功能支援接入由 [Xinference](https://github.com/xorbitsai/inference) 執行的本機 LLM _(by [@imClumsyPanda](https://github.com/imClumsyPanda))_
|
| 49 |
+
- [Nov. 26 2024] CLI 現在已支援(多個)線上 PDF 檔 *(by [@reycn](https://github.com/reycn))*
|
| 50 |
+
- [Nov. 24 2024] 為了降低依賴大小,提供 [ONNX](https://github.com/onnx/onnx) 支援 *(by [@Wybxc](https://github.com/Wybxc))*
|
| 51 |
+
- [Nov. 23 2024] 🌟 [免費公共服務](#demo) 上線! *(by [@Byaidu](https://github.com/Byaidu))*
|
| 52 |
+
- [Nov. 23 2024] 新增防止網頁爬蟲的防火牆 *(by [@Byaidu](https://github.com/Byaidu))*
|
| 53 |
+
- [Nov. 22 2024] 圖形使用者介面現已支援義大利語並進行了一些更新 *(by [@Byaidu](https://github.com/Byaidu), [@reycn](https://github.com/reycn))*
|
| 54 |
+
- [Nov. 22 2024] 現在你可以將自己部署的服務分享給朋友 *(by [@Zxis233](https://github.com/Zxis233))*
|
| 55 |
+
- [Nov. 22 2024] 支援騰訊翻譯 *(by [@hellofinch](https://github.com/hellofinch))*
|
| 56 |
+
- [Nov. 21 2024] 圖形使用者介面現在支援下載雙語文件 *(by [@reycn](https://github.com/reycn))*
|
| 57 |
+
- [Nov. 20 2024] 🌟 提供了 [線上示範](#demo)! *(by [@reycn](https://github.com/reycn))*
|
| 58 |
+
|
| 59 |
+
<h2 id="preview">效果預覽</h2>
|
| 60 |
+
|
| 61 |
+
<div align="center">
|
| 62 |
+
<img src="./images/preview.gif" width="80%"/>
|
| 63 |
+
</div>
|
| 64 |
+
|
| 65 |
+
<h2 id="demo">線上示範 🌟</h2>
|
| 66 |
+
|
| 67 |
+
### 免費服務 (<https://pdf2zh.com/>)
|
| 68 |
+
|
| 69 |
+
你可以立即嘗試 [免費公共服務](https://pdf2zh.com/) 而無需安裝
|
| 70 |
+
|
| 71 |
+
### 線上示範
|
| 72 |
+
|
| 73 |
+
你可以直接在 [HuggingFace 上的線上示範](https://huggingface.co/spaces/reycn/PDFMathTranslate-Docker)和[魔搭的線上示範](https://www.modelscope.cn/studios/AI-ModelScope/PDFMathTranslate)進行嘗試,無需安裝。
|
| 74 |
+
請注意,示範使用的運算資源有限,請勿濫用。
|
| 75 |
+
|
| 76 |
+
<h2 id="install">安裝與使用</h2>
|
| 77 |
+
|
| 78 |
+
我們提供了四種使用此專案的方法:[命令列工具](#cmd)、[便攜式安裝](#portable)、[圖形使用者介面](#gui) 與 [容器化部署](#docker)。
|
| 79 |
+
|
| 80 |
+
pdf2zh 在執行時需要額外下載模型(`wybxc/DocLayout-YOLO-DocStructBench-onnx`),該模型也可在魔搭(ModelScope)上取得。如果在啟動時下載該模型時遇到問題,請使用如下環境變數:
|
| 81 |
+
```shell
|
| 82 |
+
set HF_ENDPOINT=https://hf-mirror.com
|
| 83 |
+
```
|
| 84 |
+
|
| 85 |
+
<h3 id="cmd">方法一、命令列工具</h3>
|
| 86 |
+
|
| 87 |
+
1. 確保已安裝 Python 版本大於 3.10 且小於 3.12
|
| 88 |
+
2. 安裝此程式:
|
| 89 |
+
|
| 90 |
+
```bash
|
| 91 |
+
pip install pdf2zh
|
| 92 |
+
```
|
| 93 |
+
|
| 94 |
+
3. 執行翻譯,生成檔案位於 [目前工作目錄](https://chatgpt.com/share/6745ed36-9acc-800e-8a90-59204bd13444):
|
| 95 |
+
|
| 96 |
+
```bash
|
| 97 |
+
pdf2zh document.pdf
|
| 98 |
+
```
|
| 99 |
+
|
| 100 |
+
<h3 id="portable">方法二、便攜式安裝</h3>
|
| 101 |
+
|
| 102 |
+
無需預先安裝 Python 環境
|
| 103 |
+
|
| 104 |
+
下載 [setup.bat](https://raw.githubusercontent.com/Byaidu/PDFMathTranslate/refs/heads/main/script/setup.bat) 並直接雙擊執行
|
| 105 |
+
|
| 106 |
+
<h3 id="gui">方法三、圖形使用者介面</h3>
|
| 107 |
+
|
| 108 |
+
1. 確保已安裝 Python 版本大於 3.10 且小於 3.12
|
| 109 |
+
2. 安裝此程式:
|
| 110 |
+
|
| 111 |
+
```bash
|
| 112 |
+
pip install pdf2zh
|
| 113 |
+
```
|
| 114 |
+
|
| 115 |
+
3. 在瀏覽器中啟動使用:
|
| 116 |
+
|
| 117 |
+
```bash
|
| 118 |
+
pdf2zh -i
|
| 119 |
+
```
|
| 120 |
+
|
| 121 |
+
4. 如果您的瀏覽器沒有自動開啟並跳轉,請手動在瀏覽器開啟:
|
| 122 |
+
|
| 123 |
+
```bash
|
| 124 |
+
http://localhost:7860/
|
| 125 |
+
```
|
| 126 |
+
|
| 127 |
+
<img src="./images/gui.gif" width="500"/>
|
| 128 |
+
|
| 129 |
+
查看 [documentation for GUI](/README_GUI.md) 以獲取詳細說明
|
| 130 |
+
|
| 131 |
+
<h3 id="docker">方法四、容器化部署</h3>
|
| 132 |
+
|
| 133 |
+
1. 拉取 Docker 映像檔並執行:
|
| 134 |
+
|
| 135 |
+
```bash
|
| 136 |
+
docker pull byaidu/pdf2zh
|
| 137 |
+
docker run -d -p 7860:7860 byaidu/pdf2zh
|
| 138 |
+
```
|
| 139 |
+
|
| 140 |
+
2. 透過瀏覽器開啟:
|
| 141 |
+
|
| 142 |
+
```
|
| 143 |
+
http://localhost:7860/
|
| 144 |
+
```
|
| 145 |
+
|
| 146 |
+
用於在雲服務上部署容器映像檔:
|
| 147 |
+
|
| 148 |
+
<div>
|
| 149 |
+
<a href="https://www.heroku.com/deploy?template=https://github.com/Byaidu/PDFMathTranslate">
|
| 150 |
+
<img src="https://www.herokucdn.com/deploy/button.svg" alt="Deploy" height="26"></a>
|
| 151 |
+
<a href="https://render.com/deploy">
|
| 152 |
+
<img src="https://render.com/images/deploy-to-render-button.svg" alt="Deploy to Koyeb" height="26"></a>
|
| 153 |
+
<a href="https://zeabur.com/templates/5FQIGX?referralCode=reycn">
|
| 154 |
+
<img src="https://zeabur.com/button.svg" alt="Deploy on Zeabur" height="26"></a>
|
| 155 |
+
<a href="https://app.koyeb.com/deploy?type=git&builder=buildpack&repository=github.com/Byaidu/PDFMathTranslate&branch=main&name=pdf-math-translate">
|
| 156 |
+
<img src="https://www.koyeb.com/static/images/deploy/button.svg" alt="Deploy to Koyeb" height="26"></a>
|
| 157 |
+
</div>
|
| 158 |
+
|
| 159 |
+
<h2 id="usage">高級選項</h2>
|
| 160 |
+
|
| 161 |
+
在命令列中執行翻譯指令,並在目前工作目錄下生成譯文檔案 `example-mono.pdf` 和雙語對照檔案 `example-dual.pdf`。預設使用 Google 翻譯服務。
|
| 162 |
+
|
| 163 |
+
<img src="./images/cmd.explained.png" width="580px" alt="cmd"/>
|
| 164 |
+
|
| 165 |
+
以下表格列出了所有高級選項,供參考:
|
| 166 |
+
|
| 167 |
+
| Option | 功能 | 範例 |
|
| 168 |
+
| -------- | ------- |------- |
|
| 169 |
+
| files | 本機檔案 | `pdf2zh ~/local.pdf` |
|
| 170 |
+
| links | 線上檔案 | `pdf2zh http://arxiv.org/paper.pdf` |
|
| 171 |
+
| `-i` | [進入圖形介面](#gui) | `pdf2zh -i` |
|
| 172 |
+
| `-p` | [僅翻譯部分文件](#partial) | `pdf2zh example.pdf -p 1` |
|
| 173 |
+
| `-li` | [原文語言](#language) | `pdf2zh example.pdf -li en` |
|
| 174 |
+
| `-lo` | [目標語言](#language) | `pdf2zh example.pdf -lo zh` |
|
| 175 |
+
| `-s` | [指定翻譯服務](#services) | `pdf2zh example.pdf -s deepl` |
|
| 176 |
+
| `-t` | [多執行緒](#threads) | `pdf2zh example.pdf -t 1` |
|
| 177 |
+
| `-o` | 輸出目錄 | `pdf2zh example.pdf -o output` |
|
| 178 |
+
| `-f`, `-c` | [例外規則](#exceptions) | `pdf2zh example.pdf -f "(MS.*)"` |
|
| 179 |
+
| `--share` | [獲取 gradio 公開連結] | `pdf2zh -i --share` |
|
| 180 |
+
| `--authorized` | [[添加網頁認證及自訂認證頁面](https://github.com/Byaidu/PDFMathTranslate/blob/main/docs/ADVANCED.)] | `pdf2zh -i --authorized users.txt [auth.html]` |
|
| 181 |
+
| `--prompt` | [使用自訂的大模型 Prompt] | `pdf2zh --prompt [prompt.txt]` |
|
| 182 |
+
| `--onnx` | [使用自訂的 DocLayout-YOLO ONNX 模型] | `pdf2zh --onnx [onnx/model/path]` |
|
| 183 |
+
| `--serverport` | [自訂 WebUI 埠號] | `pdf2zh --serverport 7860` |
|
| 184 |
+
| `--dir` | [資料夾翻譯] | `pdf2zh --dir /path/to/translate/` |
|
| 185 |
+
|
| 186 |
+
<h3 id="partial">全文或部分文件翻譯</h3>
|
| 187 |
+
|
| 188 |
+
- **全文翻譯**
|
| 189 |
+
|
| 190 |
+
```bash
|
| 191 |
+
pdf2zh example.pdf
|
| 192 |
+
```
|
| 193 |
+
|
| 194 |
+
- **部分翻譯**
|
| 195 |
+
|
| 196 |
+
```bash
|
| 197 |
+
pdf2zh example.pdf -p 1-3,5
|
| 198 |
+
```
|
| 199 |
+
|
| 200 |
+
<h3 id="language">指定原文語言與目標語言</h3>
|
| 201 |
+
|
| 202 |
+
可參考 [Google 語言代碼](https://developers.google.com/admin-sdk/directory/v1/languages)、[DeepL 語言代碼](https://developers.deepl.com/docs/resources/supported-languages)
|
| 203 |
+
|
| 204 |
+
```bash
|
| 205 |
+
pdf2zh example.pdf -li en -lo ja
|
| 206 |
+
```
|
| 207 |
+
|
| 208 |
+
<h3 id="services">使用不同的翻譯服務</h3>
|
| 209 |
+
|
| 210 |
+
下表列出了每個翻譯服務所需的 [環境變數](https://chatgpt.com/share/6734a83d-9d48-800e-8a46-f57ca6e8bcb4)。在使用前,請先確保已設定好對應的變數。
|
| 211 |
+
|
| 212 |
+
|**Translator**|**Service**|**Environment Variables**|**Default Values**|**Notes**|
|
| 213 |
+
|-|-|-|-|-|
|
| 214 |
+
|**Google (Default)**|`google`|無|N/A|無|
|
| 215 |
+
|**Bing**|`bing`|無|N/A|無|
|
| 216 |
+
|**DeepL**|`deepl`|`DEEPL_AUTH_KEY`|`[Your Key]`|參閱 [DeepL](https://support.deepl.com/hc/en-us/articles/360020695820-API-Key-for-DeepL-s-API)|
|
| 217 |
+
|**DeepLX**|`deeplx`|`DEEPLX_ENDPOINT`|`https://api.deepl.com/translate`|參閱 [DeepLX](https://github.com/OwO-Network/DeepLX)|
|
| 218 |
+
|**Ollama**|`ollama`|`OLLAMA_HOST`, `OLLAMA_MODEL`|`http://127.0.0.1:11434`, `gemma2`|參閱 [Ollama](https://github.com/ollama/ollama)|
|
| 219 |
+
|**OpenAI**|`openai`|`OPENAI_BASE_URL`, `OPENAI_API_KEY`, `OPENAI_MODEL`|`https://api.openai.com/v1`, `[Your Key]`, `gpt-4o-mini`|參閱 [OpenAI](https://platform.openai.com/docs/overview)|
|
| 220 |
+
|**AzureOpenAI**|`azure-openai`|`AZURE_OPENAI_BASE_URL`, `AZURE_OPENAI_API_KEY`, `AZURE_OPENAI_MODEL`|`[Your Endpoint]`, `[Your Key]`, `gpt-4o-mini`|參閱 [Azure OpenAI](https://learn.microsoft.com/zh-cn/azure/ai-services/openai/chatgpt-quickstart?tabs=command-line%2Cjavascript-keyless%2Ctypescript-keyless%2Cpython&pivots=programming-language-python)|
|
| 221 |
+
|**Zhipu**|`zhipu`|`ZHIPU_API_KEY`, `ZHIPU_MODEL`|`[Your Key]`, `glm-4-flash`|參閱 [Zhipu](https://open.bigmodel.cn/dev/api/thirdparty-frame/openai-sdk)|
|
| 222 |
+
| **ModelScope** | `modelscope` |`MODELSCOPE_API_KEY`, `MODELSCOPE_MODEL`|`[Your Key]`, `Qwen/Qwen2.5-Coder-32B-Instruct`| 參閱 [ModelScope](https://www.modelscope.cn/docs/model-service/API-Inference/intro)|
|
| 223 |
+
|**Silicon**|`silicon`|`SILICON_API_KEY`, `SILICON_MODEL`|`[Your Key]`, `Qwen/Qwen2.5-7B-Instruct`|參閱 [SiliconCloud](https://docs.siliconflow.cn/quickstart)|
|
| 224 |
+
|**Gemini**|`gemini`|`GEMINI_API_KEY`, `GEMINI_MODEL`|`[Your Key]`, `gemini-1.5-flash`|參閱 [Gemini](https://ai.google.dev/gemini-api/docs/openai)|
|
| 225 |
+
|**Azure**|`azure`|`AZURE_ENDPOINT`, `AZURE_API_KEY`|`https://api.translator.azure.cn`, `[Your Key]`|參閱 [Azure](https://docs.azure.cn/en-us/ai-services/translator/text-translation-overview)|
|
| 226 |
+
|**Tencent**|`tencent`|`TENCENTCLOUD_SECRET_ID`, `TENCENTCLOUD_SECRET_KEY`|`[Your ID]`, `[Your Key]`|參閱 [Tencent](https://www.tencentcloud.com/products/tmt?from_qcintl=122110104)|
|
| 227 |
+
|**Dify**|`dify`|`DIFY_API_URL`, `DIFY_API_KEY`|`[Your DIFY URL]`, `[Your Key]`|參閱 [Dify](https://github.com/langgenius/dify),需要在 Dify 的工作流程輸入中定義三個變數:lang_out、lang_in、text。|
|
| 228 |
+
|**AnythingLLM**|`anythingllm`|`AnythingLLM_URL`, `AnythingLLM_APIKEY`|`[Your AnythingLLM URL]`, `[Your Key]`|參閱 [anything-llm](https://github.com/Mintplex-Labs/anything-llm)|
|
| 229 |
+
|**Argos Translate**|`argos`| | |參閱 [argos-translate](https://github.com/argosopentech/argos-translate)|
|
| 230 |
+
|**Grok**|`grok`| `GORK_API_KEY`, `GORK_MODEL` | `[Your GORK_API_KEY]`, `grok-2-1212` |參閱 [Grok](https://docs.x.ai/docs/overview)|
|
| 231 |
+
|**DeepSeek**|`deepseek`| `DEEPSEEK_API_KEY`, `DEEPSEEK_MODEL` | `[Your DEEPSEEK_API_KEY]`, `deepseek-chat` |參閱 [DeepSeek](https://www.deepseek.com/)|
|
| 232 |
+
|**OpenAI-Liked**|`openailiked`| `OPENAILIKED_BASE_URL`, `OPENAILIKED_API_KEY`, `OPENAILIKED_MODEL` | `url`, `[Your Key]`, `model name` | 無 |
|
| 233 |
+
|
| 234 |
+
對於不在上述表格中,但兼容 OpenAI API 的大語言模型,可以使用與 OpenAI 相同的方式設定環境變數。
|
| 235 |
+
|
| 236 |
+
使用 `-s service` 或 `-s service:model` 指定翻譯服務:
|
| 237 |
+
|
| 238 |
+
```bash
|
| 239 |
+
pdf2zh example.pdf -s openai:gpt-4o-mini
|
| 240 |
+
```
|
| 241 |
+
|
| 242 |
+
或使用環境變數指定模型:
|
| 243 |
+
|
| 244 |
+
```bash
|
| 245 |
+
set OPENAI_MODEL=gpt-4o-mini
|
| 246 |
+
pdf2zh example.pdf -s openai
|
| 247 |
+
```
|
| 248 |
+
|
| 249 |
+
<h3 id="exceptions">指定例外規則</h3>
|
| 250 |
+
|
| 251 |
+
使用正則表達式指定需要保留的公式字體與字元:
|
| 252 |
+
|
| 253 |
+
```bash
|
| 254 |
+
pdf2zh example.pdf -f "(CM[^RT].*|MS.*|.*Ital)" -c "(\(|\||\)|\+|=|\d|[\u0080-\ufaff])"
|
| 255 |
+
```
|
| 256 |
+
|
| 257 |
+
預設保留 `Latex`, `Mono`, `Code`, `Italic`, `Symbol` 以及 `Math` 字體:
|
| 258 |
+
|
| 259 |
+
```bash
|
| 260 |
+
pdf2zh example.pdf -f "(CM[^R]|MS.M|XY|MT|BL|RM|EU|LA|RS|LINE|LCIRCLE|TeX-|rsfs|txsy|wasy|stmary|.*Mono|.*Code|.*Ital|.*Sym|.*Math)"
|
| 261 |
+
```
|
| 262 |
+
|
| 263 |
+
<h3 id="threads">指定執行緒數量</h3>
|
| 264 |
+
|
| 265 |
+
使用 `-t` 參數指定翻譯使用的執行緒數量:
|
| 266 |
+
|
| 267 |
+
```bash
|
| 268 |
+
pdf2zh example.pdf -t 1
|
| 269 |
+
```
|
| 270 |
+
|
| 271 |
+
<h3 id="prompt">自訂大模型 Prompt</h3>
|
| 272 |
+
|
| 273 |
+
使用 `--prompt` 指定在使用大模型翻譯時所採用的 Prompt 檔案。
|
| 274 |
+
|
| 275 |
+
```bash
|
| 276 |
+
pdf2zh example.pdf -pr prompt.txt
|
| 277 |
+
```
|
| 278 |
+
|
| 279 |
+
範例 `prompt.txt` 檔案內容:
|
| 280 |
+
|
| 281 |
+
```
|
| 282 |
+
[
|
| 283 |
+
{
|
| 284 |
+
"role": "system",
|
| 285 |
+
"content": "You are a professional,authentic machine translation engine.",
|
| 286 |
+
},
|
| 287 |
+
{
|
| 288 |
+
"role": "user",
|
| 289 |
+
"content": "Translate the following markdown source text to ${lang_out}. Keep the formula notation {{v*}} unchanged. Output translation directly without any additional text.\nSource Text: ${text}\nTranslated Text:",
|
| 290 |
+
},
|
| 291 |
+
]
|
| 292 |
+
```
|
| 293 |
+
|
| 294 |
+
在自訂 Prompt 檔案中,可以使用以下三個內建變數來傳遞參數:
|
| 295 |
+
|**變數名稱**|**說明**|
|
| 296 |
+
|-|-|
|
| 297 |
+
|`lang_in`|輸入語言|
|
| 298 |
+
|`lang_out`|輸出語言|
|
| 299 |
+
|`text`|需要翻譯的文本|
|
| 300 |
+
|
| 301 |
+
<h2 id="todo">API</h2>
|
| 302 |
+
|
| 303 |
+
### Python
|
| 304 |
+
|
| 305 |
+
```python
|
| 306 |
+
from pdf2zh import translate, translate_stream
|
| 307 |
+
|
| 308 |
+
params = {"lang_in": "en", "lang_out": "zh", "service": "google", "thread": 4}
|
| 309 |
+
file_mono, file_dual = translate(files=["example.pdf"], **params)[0]
|
| 310 |
+
with open("example.pdf", "rb") as f:
|
| 311 |
+
stream_mono, stream_dual = translate_stream(stream=f.read(), **params)
|
| 312 |
+
```
|
| 313 |
+
|
| 314 |
+
### HTTP
|
| 315 |
+
|
| 316 |
+
```bash
|
| 317 |
+
pip install pdf2zh[backend]
|
| 318 |
+
pdf2zh --flask
|
| 319 |
+
pdf2zh --celery worker
|
| 320 |
+
```
|
| 321 |
+
|
| 322 |
+
```bash
|
| 323 |
+
curl http://localhost:11008/v1/translate -F "file=@example.pdf" -F "data={\"lang_in\":\"en\",\"lang_out\":\"zh\",\"service\":\"google\",\"thread\":4}"
|
| 324 |
+
{"id":"d9894125-2f4e-45ea-9d93-1a9068d2045a"}
|
| 325 |
+
|
| 326 |
+
curl http://localhost:11008/v1/translate/d9894125-2f4e-45ea-9d93-1a9068d2045a
|
| 327 |
+
{"info":{"n":13,"total":506},"state":"PROGRESS"}
|
| 328 |
+
|
| 329 |
+
curl http://localhost:11008/v1/translate/d9894125-2f4e-45ea-9d93-1a9068d2045a
|
| 330 |
+
{"state":"SUCCESS"}
|
| 331 |
+
|
| 332 |
+
curl http://localhost:11008/v1/translate/d9894125-2f4e-45ea-9d93-1a9068d2045a/mono --output example-mono.pdf
|
| 333 |
+
|
| 334 |
+
curl http://localhost:11008/v1/translate/d9894125-2f4e-45ea-9d93-1a9068d2045a/dual --output example-dual.pdf
|
| 335 |
+
|
| 336 |
+
curl http://localhost:11008/v1/translate/d9894125-2f4e-45ea-9d93-1a9068d2045a -X DELETE
|
| 337 |
+
```
|
| 338 |
+
|
| 339 |
+
<h2 id="acknowledgement">致謝</h2>
|
| 340 |
+
|
| 341 |
+
- 文件合併:[PyMuPDF](https://github.com/pymupdf/PyMuPDF)
|
| 342 |
+
- 文件解析:[Pdfminer.six](https://github.com/pdfminer/pdfminer.six)
|
| 343 |
+
- 文件提取:[MinerU](https://github.com/opendatalab/MinerU)
|
| 344 |
+
- 文件預覽:[Gradio PDF](https://github.com/freddyaboulton/gradio-pdf)
|
| 345 |
+
- 多執行緒翻譯:[MathTranslate](https://github.com/SUSYUSTC/MathTranslate)
|
| 346 |
+
- 版面解析:[DocLayout-YOLO](https://github.com/opendatalab/DocLayout-YOLO)
|
| 347 |
+
- PDF 標準:[PDF Explained](https://zxyle.github.io/PDF-Explained/)、[PDF Cheat Sheets](https://pdfa.org/resource/pdf-cheat-sheets/)
|
| 348 |
+
- 多語言字型:[Go Noto Universal](https://github.com/satbyy/go-noto-universal)
|
| 349 |
+
|
| 350 |
+
<h2 id="contrib">貢獻者</h2>
|
| 351 |
+
|
| 352 |
+
<a href="https://github.com/Byaidu/PDFMathTranslate/graphs/contributors">
|
| 353 |
+
<img src="https://opencollective.com/PDFMathTranslate/contributors.svg?width=890&button=false" />
|
| 354 |
+
</a>
|
| 355 |
+
|
| 356 |
+

|
| 357 |
+
|
| 358 |
+
<h2 id="star_hist">星標歷史</h2>
|
| 359 |
+
|
| 360 |
+
<a href="https://star-history.com/#Byaidu/PDFMathTranslate&Date">
|
| 361 |
+
<picture>
|
| 362 |
+
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=Byaidu/PDFMathTranslate&type=Date&theme=dark" />
|
| 363 |
+
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=Byaidu/PDFMathTranslate&type=Date" />
|
| 364 |
+
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=Byaidu/PDFMathTranslate&type=Date"/>
|
| 365 |
+
</picture>
|
| 366 |
+
</a>
|
pdf2zh/__init__.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
|
| 3 |
+
log = logging.getLogger(__name__)
|
| 4 |
+
|
| 5 |
+
__version__ = "1.9.11"
|
| 6 |
+
__author__ = "Byaidu"
|
| 7 |
+
__all__ = ["translate", "translate_stream"]
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def __getattr__(name):
|
| 11 |
+
if name in {"translate", "translate_stream"}:
|
| 12 |
+
from pdf2zh.high_level import translate, translate_stream
|
| 13 |
+
|
| 14 |
+
return {"translate": translate, "translate_stream": translate_stream}[name]
|
| 15 |
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
pdf2zh/backend.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import io
|
| 2 |
+
import json
|
| 3 |
+
|
| 4 |
+
import tqdm
|
| 5 |
+
from celery import Celery, Task
|
| 6 |
+
from celery.result import AsyncResult
|
| 7 |
+
from flask import Flask, request, send_file
|
| 8 |
+
|
| 9 |
+
from pdf2zh import translate_stream
|
| 10 |
+
from pdf2zh.config import ConfigManager
|
| 11 |
+
from pdf2zh.doclayout import ModelInstance
|
| 12 |
+
|
| 13 |
+
flask_app = Flask("pdf2zh")
|
| 14 |
+
flask_app.config.from_mapping(
|
| 15 |
+
CELERY=dict(
|
| 16 |
+
broker_url=ConfigManager.get("CELERY_BROKER", "redis://127.0.0.1:6379/0"),
|
| 17 |
+
result_backend=ConfigManager.get("CELERY_RESULT", "redis://127.0.0.1:6379/0"),
|
| 18 |
+
)
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def celery_init_app(app: Flask) -> Celery:
|
| 23 |
+
class FlaskTask(Task):
|
| 24 |
+
def __call__(self, *args, **kwargs):
|
| 25 |
+
with app.app_context():
|
| 26 |
+
return self.run(*args, **kwargs)
|
| 27 |
+
|
| 28 |
+
celery_app = Celery(app.name)
|
| 29 |
+
celery_app.config_from_object(app.config["CELERY"])
|
| 30 |
+
celery_app.Task = FlaskTask
|
| 31 |
+
celery_app.set_default()
|
| 32 |
+
celery_app.autodiscover_tasks()
|
| 33 |
+
app.extensions["celery"] = celery_app
|
| 34 |
+
return celery_app
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
celery_app = celery_init_app(flask_app)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
@celery_app.task(bind=True)
|
| 41 |
+
def translate_task(
|
| 42 |
+
self: Task,
|
| 43 |
+
stream: bytes,
|
| 44 |
+
args: dict,
|
| 45 |
+
):
|
| 46 |
+
def progress_bar(t: tqdm.tqdm):
|
| 47 |
+
self.update_state(state="PROGRESS", meta={"n": t.n, "total": t.total}) # noqa
|
| 48 |
+
print(f"Translating {t.n} / {t.total} pages")
|
| 49 |
+
|
| 50 |
+
doc_mono, doc_dual = translate_stream(
|
| 51 |
+
stream,
|
| 52 |
+
callback=progress_bar,
|
| 53 |
+
model=ModelInstance.value,
|
| 54 |
+
**args,
|
| 55 |
+
)
|
| 56 |
+
return doc_mono, doc_dual
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
@flask_app.route("/v1/translate", methods=["POST"])
|
| 60 |
+
def create_translate_tasks():
|
| 61 |
+
file = request.files["file"]
|
| 62 |
+
stream = file.stream.read()
|
| 63 |
+
print(request.form.get("data"))
|
| 64 |
+
args = json.loads(request.form.get("data"))
|
| 65 |
+
task = translate_task.delay(stream, args)
|
| 66 |
+
return {"id": task.id}
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
@flask_app.route("/v1/translate/<id>", methods=["GET"])
|
| 70 |
+
def get_translate_task(id: str):
|
| 71 |
+
result: AsyncResult = celery_app.AsyncResult(id)
|
| 72 |
+
if str(result.state) == "PROGRESS":
|
| 73 |
+
return {"state": str(result.state), "info": result.info}
|
| 74 |
+
else:
|
| 75 |
+
return {"state": str(result.state)}
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
@flask_app.route("/v1/translate/<id>", methods=["DELETE"])
|
| 79 |
+
def delete_translate_task(id: str):
|
| 80 |
+
result: AsyncResult = celery_app.AsyncResult(id)
|
| 81 |
+
result.revoke(terminate=True)
|
| 82 |
+
return {"state": str(result.state)}
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
@flask_app.route("/v1/translate/<id>/<format>")
|
| 86 |
+
def get_translate_result(id: str, format: str):
|
| 87 |
+
result = celery_app.AsyncResult(id)
|
| 88 |
+
if not result.ready():
|
| 89 |
+
return {"error": "task not finished"}, 400
|
| 90 |
+
if not result.successful():
|
| 91 |
+
return {"error": "task failed"}, 400
|
| 92 |
+
doc_mono, doc_dual = result.get()
|
| 93 |
+
to_send = doc_mono if format == "mono" else doc_dual
|
| 94 |
+
return send_file(io.BytesIO(to_send), "application/pdf")
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
if __name__ == "__main__":
|
| 98 |
+
flask_app.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8 |
+
# we don't init the database here
|
| 9 |
+
db = SqliteDatabase(None)
|
| 10 |
+
logger = logging.getLogger(__name__)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class _TranslationCache(Model):
|
| 14 |
+
id = AutoField()
|
| 15 |
+
translate_engine = CharField(max_length=20)
|
| 16 |
+
translate_engine_params = TextField()
|
| 17 |
+
original_text = TextField()
|
| 18 |
+
translation = TextField()
|
| 19 |
+
|
| 20 |
+
class Meta:
|
| 21 |
+
database = db
|
| 22 |
+
constraints = [SQL("""
|
| 23 |
+
UNIQUE (
|
| 24 |
+
translate_engine,
|
| 25 |
+
translate_engine_params,
|
| 26 |
+
original_text
|
| 27 |
+
)
|
| 28 |
+
ON CONFLICT REPLACE
|
| 29 |
+
""")]
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class TranslationCache:
|
| 33 |
+
@staticmethod
|
| 34 |
+
def _sort_dict_recursively(obj):
|
| 35 |
+
if isinstance(obj, dict):
|
| 36 |
+
return {
|
| 37 |
+
k: TranslationCache._sort_dict_recursively(v)
|
| 38 |
+
for k in sorted(obj.keys())
|
| 39 |
+
for v in [obj[k]]
|
| 40 |
+
}
|
| 41 |
+
elif isinstance(obj, list):
|
| 42 |
+
return [TranslationCache._sort_dict_recursively(item) for item in obj]
|
| 43 |
+
return obj
|
| 44 |
+
|
| 45 |
+
def __init__(self, translate_engine: str, translate_engine_params: dict = None):
|
| 46 |
+
assert (
|
| 47 |
+
len(translate_engine) < 20
|
| 48 |
+
), "current cache require translate engine name less than 20 characters"
|
| 49 |
+
self.translate_engine = translate_engine
|
| 50 |
+
self.replace_params(translate_engine_params)
|
| 51 |
+
|
| 52 |
+
# The program typically starts multi-threaded translation
|
| 53 |
+
# only after cache parameters are fully configured,
|
| 54 |
+
# so thread safety doesn't need to be considered here.
|
| 55 |
+
def replace_params(self, params: dict = None):
|
| 56 |
+
if params is None:
|
| 57 |
+
params = {}
|
| 58 |
+
self.params = params
|
| 59 |
+
params = self._sort_dict_recursively(params)
|
| 60 |
+
self.translate_engine_params = json.dumps(params)
|
| 61 |
+
|
| 62 |
+
def update_params(self, params: dict = None):
|
| 63 |
+
if params is None:
|
| 64 |
+
params = {}
|
| 65 |
+
self.params.update(params)
|
| 66 |
+
self.replace_params(self.params)
|
| 67 |
+
|
| 68 |
+
def add_params(self, k: str, v):
|
| 69 |
+
self.params[k] = v
|
| 70 |
+
self.replace_params(self.params)
|
| 71 |
+
|
| 72 |
+
# Since peewee and the underlying sqlite are thread-safe,
|
| 73 |
+
# get and set operations don't need locks.
|
| 74 |
+
def get(self, original_text: str) -> Optional[str]:
|
| 75 |
+
result = _TranslationCache.get_or_none(
|
| 76 |
+
translate_engine=self.translate_engine,
|
| 77 |
+
translate_engine_params=self.translate_engine_params,
|
| 78 |
+
original_text=original_text,
|
| 79 |
+
)
|
| 80 |
+
return result.translation if result else None
|
| 81 |
+
|
| 82 |
+
def set(self, original_text: str, translation: str):
|
| 83 |
+
try:
|
| 84 |
+
_TranslationCache.create(
|
| 85 |
+
translate_engine=self.translate_engine,
|
| 86 |
+
translate_engine_params=self.translate_engine_params,
|
| 87 |
+
original_text=original_text,
|
| 88 |
+
translation=translation,
|
| 89 |
+
)
|
| 90 |
+
except Exception as e:
|
| 91 |
+
logger.debug(f"Error setting cache: {e}")
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def init_db(remove_exists=False):
|
| 95 |
+
cache_folder = os.path.join(os.path.expanduser("~"), ".cache", "pdf2zh")
|
| 96 |
+
os.makedirs(cache_folder, exist_ok=True)
|
| 97 |
+
# The current version does not support database migration, so add the version number to the file name.
|
| 98 |
+
cache_db_path = os.path.join(cache_folder, "cache.v1.db")
|
| 99 |
+
if remove_exists and os.path.exists(cache_db_path):
|
| 100 |
+
os.remove(cache_db_path)
|
| 101 |
+
db.init(
|
| 102 |
+
cache_db_path,
|
| 103 |
+
pragmas={
|
| 104 |
+
"journal_mode": "wal",
|
| 105 |
+
"busy_timeout": 1000,
|
| 106 |
+
},
|
| 107 |
+
)
|
| 108 |
+
db.create_tables([_TranslationCache], safe=True)
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def init_test_db():
|
| 112 |
+
import tempfile
|
| 113 |
+
|
| 114 |
+
cache_db_path = tempfile.mktemp(suffix=".db")
|
| 115 |
+
test_db = SqliteDatabase(
|
| 116 |
+
cache_db_path,
|
| 117 |
+
pragmas={
|
| 118 |
+
"journal_mode": "wal",
|
| 119 |
+
"busy_timeout": 1000,
|
| 120 |
+
},
|
| 121 |
+
)
|
| 122 |
+
test_db.bind([_TranslationCache], bind_refs=False, bind_backrefs=False)
|
| 123 |
+
test_db.connect()
|
| 124 |
+
test_db.create_tables([_TranslationCache], safe=True)
|
| 125 |
+
return test_db
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def clean_test_db(test_db):
|
| 129 |
+
test_db.drop_tables([_TranslationCache])
|
| 130 |
+
test_db.close()
|
| 131 |
+
db_path = test_db.database
|
| 132 |
+
if os.path.exists(db_path):
|
| 133 |
+
os.remove(test_db.database)
|
| 134 |
+
wal_path = db_path + "-wal"
|
| 135 |
+
if os.path.exists(wal_path):
|
| 136 |
+
os.remove(wal_path)
|
| 137 |
+
shm_path = db_path + "-shm"
|
| 138 |
+
if os.path.exists(shm_path):
|
| 139 |
+
os.remove(shm_path)
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
init_db()
|
pdf2zh/config.py
ADDED
|
@@ -0,0 +1,242 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import copy
|
| 2 |
+
import json
|
| 3 |
+
import os
|
| 4 |
+
from functools import lru_cache
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from threading import RLock # 改成 RLock
|
| 7 |
+
from typing import Optional
|
| 8 |
+
|
| 9 |
+
from pydantic_settings import BaseSettings, SettingsConfigDict
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class Settings(BaseSettings):
|
| 13 |
+
# Khai báo các biến tương ứng trong .env (tự động convert kiểu dữ liệu)
|
| 14 |
+
device: str = "auto"
|
| 15 |
+
page_batch_size: Optional[int] = None
|
| 16 |
+
layout_batch_size: Optional[int] = None
|
| 17 |
+
detection_batch_size: Optional[int] = None
|
| 18 |
+
ocr_batch_size: Optional[int] = None
|
| 19 |
+
table_batch_size: Optional[int] = None
|
| 20 |
+
detector_blank_threshold: Optional[float] = None
|
| 21 |
+
detector_text_threshold: Optional[float] = None
|
| 22 |
+
|
| 23 |
+
model_config = SettingsConfigDict(
|
| 24 |
+
env_file=".env",
|
| 25 |
+
env_file_encoding="utf-8",
|
| 26 |
+
extra="ignore", # Bỏ qua các biến khác trong file .env nếu có
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
@lru_cache
|
| 31 |
+
def get_settings() -> Settings:
|
| 32 |
+
"""Get cached settings instance."""
|
| 33 |
+
return Settings()
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class ConfigManager:
|
| 37 |
+
_instance = None
|
| 38 |
+
_lock = RLock() # 用 RLock 替换 Lock,允许在同一个线程中重复获取锁
|
| 39 |
+
|
| 40 |
+
@classmethod
|
| 41 |
+
def get_instance(cls):
|
| 42 |
+
"""获取单例实例"""
|
| 43 |
+
# 先判断是否存在实例,如果不存在再加锁进行初始化
|
| 44 |
+
if cls._instance is None:
|
| 45 |
+
with cls._lock:
|
| 46 |
+
if cls._instance is None:
|
| 47 |
+
cls._instance = cls()
|
| 48 |
+
return cls._instance
|
| 49 |
+
|
| 50 |
+
def __init__(self):
|
| 51 |
+
# 防止重复初始化
|
| 52 |
+
if hasattr(self, "_initialized") and self._initialized:
|
| 53 |
+
return
|
| 54 |
+
self._initialized = True
|
| 55 |
+
|
| 56 |
+
self._config_path = Path.home() / ".config" / "PDFMathTranslate" / "config.json"
|
| 57 |
+
self._config_data = {}
|
| 58 |
+
|
| 59 |
+
# 这里不要再加锁,因为外层可能已经加了锁 (get_instance), RLock也无妨
|
| 60 |
+
self._ensure_config_exists()
|
| 61 |
+
|
| 62 |
+
def _ensure_config_exists(self, isInit=True):
|
| 63 |
+
"""确保配置文件存在,如果不存在则创建默认配置"""
|
| 64 |
+
# 这里也不需要显式再次加锁,原因同上,方法体中再调用 _load_config(),
|
| 65 |
+
# 而 _load_config() 内部会加锁。因为 RLock 是可重入的,不会阻塞。
|
| 66 |
+
if not self._config_path.exists():
|
| 67 |
+
if isInit:
|
| 68 |
+
self._config_path.parent.mkdir(parents=True, exist_ok=True)
|
| 69 |
+
self._config_data = {} # 默认配置内容
|
| 70 |
+
self._save_config()
|
| 71 |
+
else:
|
| 72 |
+
raise ValueError(f"config file {self._config_path} not found!")
|
| 73 |
+
else:
|
| 74 |
+
self._load_config()
|
| 75 |
+
|
| 76 |
+
def _load_config(self):
|
| 77 |
+
"""从 config.json 中加载配置"""
|
| 78 |
+
with self._lock: # 加锁确保线程安全
|
| 79 |
+
with self._config_path.open("r", encoding="utf-8") as f:
|
| 80 |
+
self._config_data = json.load(f)
|
| 81 |
+
|
| 82 |
+
def _save_config(self):
|
| 83 |
+
"""保存配置到 config.json"""
|
| 84 |
+
with self._lock: # 加锁确保线程安全
|
| 85 |
+
# 移除循环引用并写入
|
| 86 |
+
cleaned_data = self._remove_circular_references(self._config_data)
|
| 87 |
+
with self._config_path.open("w", encoding="utf-8") as f:
|
| 88 |
+
json.dump(cleaned_data, f, indent=4, ensure_ascii=False)
|
| 89 |
+
|
| 90 |
+
def _remove_circular_references(self, obj, seen=None):
|
| 91 |
+
"""递归移除循环引用"""
|
| 92 |
+
if seen is None:
|
| 93 |
+
seen = set()
|
| 94 |
+
obj_id = id(obj)
|
| 95 |
+
if obj_id in seen:
|
| 96 |
+
return None # 遇到已处理过的对象,视为循环引用
|
| 97 |
+
seen.add(obj_id)
|
| 98 |
+
|
| 99 |
+
if isinstance(obj, dict):
|
| 100 |
+
return {
|
| 101 |
+
k: self._remove_circular_references(v, seen) for k, v in obj.items()
|
| 102 |
+
}
|
| 103 |
+
elif isinstance(obj, list):
|
| 104 |
+
return [self._remove_circular_references(i, seen) for i in obj]
|
| 105 |
+
return obj
|
| 106 |
+
|
| 107 |
+
@classmethod
|
| 108 |
+
def custome_config(cls, file_path):
|
| 109 |
+
"""使用自定义路径加载配置文件"""
|
| 110 |
+
custom_path = Path(file_path)
|
| 111 |
+
if not custom_path.exists():
|
| 112 |
+
raise ValueError(f"Config file {custom_path} not found!")
|
| 113 |
+
# 加锁
|
| 114 |
+
with cls._lock:
|
| 115 |
+
instance = cls()
|
| 116 |
+
instance._config_path = custom_path
|
| 117 |
+
# 此处传 isInit=False,若不存在则报错;若存在则正常 _load_config()
|
| 118 |
+
instance._ensure_config_exists(isInit=False)
|
| 119 |
+
cls._instance = instance
|
| 120 |
+
|
| 121 |
+
@classmethod
|
| 122 |
+
def get(cls, key, default=None):
|
| 123 |
+
"""获取配置值"""
|
| 124 |
+
instance = cls.get_instance()
|
| 125 |
+
# 读取时,加锁或不加锁都行。但为了统一,我们在修改配置前后都要加锁。
|
| 126 |
+
# get 只要最终需要保存,则会加锁 -> _save_config()
|
| 127 |
+
if key in instance._config_data:
|
| 128 |
+
return instance._config_data[key]
|
| 129 |
+
|
| 130 |
+
# 若环境变量中存在该 key,则使用环境变量并写回 config
|
| 131 |
+
if key in os.environ:
|
| 132 |
+
value = os.environ[key]
|
| 133 |
+
instance._config_data[key] = value
|
| 134 |
+
instance._save_config()
|
| 135 |
+
return value
|
| 136 |
+
|
| 137 |
+
# 若 default 不为 None,则设置并保存
|
| 138 |
+
if default is not None:
|
| 139 |
+
instance._config_data[key] = default
|
| 140 |
+
instance._save_config()
|
| 141 |
+
return default
|
| 142 |
+
|
| 143 |
+
# 找不到则抛出异常
|
| 144 |
+
# raise KeyError(f"{key} is not found in config file or environment variables.")
|
| 145 |
+
return default
|
| 146 |
+
|
| 147 |
+
@classmethod
|
| 148 |
+
def set(cls, key, value):
|
| 149 |
+
"""设置配置值并保存"""
|
| 150 |
+
instance = cls.get_instance()
|
| 151 |
+
with instance._lock:
|
| 152 |
+
instance._config_data[key] = value
|
| 153 |
+
instance._save_config()
|
| 154 |
+
|
| 155 |
+
@classmethod
|
| 156 |
+
def get_translator_by_name(cls, name):
|
| 157 |
+
"""根据 name 获取对应的 translator 配置"""
|
| 158 |
+
instance = cls.get_instance()
|
| 159 |
+
translators = instance._config_data.get("translators", [])
|
| 160 |
+
for translator in translators:
|
| 161 |
+
if translator.get("name") == name:
|
| 162 |
+
return translator["envs"]
|
| 163 |
+
return None
|
| 164 |
+
|
| 165 |
+
@classmethod
|
| 166 |
+
def set_translator_by_name(cls, name, new_translator_envs):
|
| 167 |
+
"""根据 name 设置或更新 translator 配置"""
|
| 168 |
+
instance = cls.get_instance()
|
| 169 |
+
with instance._lock:
|
| 170 |
+
translators = instance._config_data.get("translators", [])
|
| 171 |
+
for translator in translators:
|
| 172 |
+
if translator.get("name") == name:
|
| 173 |
+
translator["envs"] = copy.deepcopy(new_translator_envs)
|
| 174 |
+
instance._save_config()
|
| 175 |
+
return
|
| 176 |
+
translators.append(
|
| 177 |
+
{"name": name, "envs": copy.deepcopy(new_translator_envs)}
|
| 178 |
+
)
|
| 179 |
+
instance._config_data["translators"] = translators
|
| 180 |
+
instance._save_config()
|
| 181 |
+
|
| 182 |
+
@classmethod
|
| 183 |
+
def get_env_by_translatername(cls, translater_name, name, default=None):
|
| 184 |
+
"""根据 name 获取对应的 translator 配置"""
|
| 185 |
+
instance = cls.get_instance()
|
| 186 |
+
translators = instance._config_data.get("translators", [])
|
| 187 |
+
for translator in translators:
|
| 188 |
+
if translator.get("name") == translater_name.name:
|
| 189 |
+
if translator["envs"][name]:
|
| 190 |
+
return translator["envs"][name]
|
| 191 |
+
else:
|
| 192 |
+
with instance._lock:
|
| 193 |
+
translator["envs"][name] = default
|
| 194 |
+
instance._save_config()
|
| 195 |
+
return default
|
| 196 |
+
|
| 197 |
+
with instance._lock:
|
| 198 |
+
translators = instance._config_data.get("translators", [])
|
| 199 |
+
for translator in translators:
|
| 200 |
+
if translator.get("name") == translater_name.name:
|
| 201 |
+
translator["envs"][name] = default
|
| 202 |
+
instance._save_config()
|
| 203 |
+
return default
|
| 204 |
+
translators.append(
|
| 205 |
+
{
|
| 206 |
+
"name": translater_name.name,
|
| 207 |
+
"envs": copy.deepcopy(translater_name.envs),
|
| 208 |
+
}
|
| 209 |
+
)
|
| 210 |
+
instance._config_data["translators"] = translators
|
| 211 |
+
instance._save_config()
|
| 212 |
+
return default
|
| 213 |
+
|
| 214 |
+
@classmethod
|
| 215 |
+
def delete(cls, key):
|
| 216 |
+
"""删除配置值并保存"""
|
| 217 |
+
instance = cls.get_instance()
|
| 218 |
+
with instance._lock:
|
| 219 |
+
if key in instance._config_data:
|
| 220 |
+
del instance._config_data[key]
|
| 221 |
+
instance._save_config()
|
| 222 |
+
|
| 223 |
+
@classmethod
|
| 224 |
+
def clear(cls):
|
| 225 |
+
"""删除配置值并保存"""
|
| 226 |
+
instance = cls.get_instance()
|
| 227 |
+
with instance._lock:
|
| 228 |
+
instance._config_data = {}
|
| 229 |
+
instance._save_config()
|
| 230 |
+
|
| 231 |
+
@classmethod
|
| 232 |
+
def all(cls):
|
| 233 |
+
"""返回所有配置项"""
|
| 234 |
+
instance = cls.get_instance()
|
| 235 |
+
# 这里只做读取操作,一般可不加锁。不过为了保险也可以加锁。
|
| 236 |
+
return instance._config_data
|
| 237 |
+
|
| 238 |
+
@classmethod
|
| 239 |
+
def remove(cls):
|
| 240 |
+
instance = cls.get_instance()
|
| 241 |
+
with instance._lock:
|
| 242 |
+
os.remove(instance._config_path)
|
pdf2zh/converter.py
ADDED
|
@@ -0,0 +1,533 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import concurrent.futures
|
| 2 |
+
import logging
|
| 3 |
+
import re
|
| 4 |
+
import unicodedata
|
| 5 |
+
from enum import Enum
|
| 6 |
+
from string import Template
|
| 7 |
+
from typing import Dict
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
from pdfminer.converter import PDFConverter
|
| 11 |
+
from pdfminer.layout import LTChar, LTFigure, LTLine, LTPage
|
| 12 |
+
from pdfminer.pdffont import PDFCIDFont, PDFUnicodeNotDefined
|
| 13 |
+
from pdfminer.pdfinterp import PDFGraphicState, PDFResourceManager
|
| 14 |
+
from pdfminer.utils import apply_matrix_pt, mult_matrix
|
| 15 |
+
from pymupdf import Font
|
| 16 |
+
from tenacity import retry, wait_fixed
|
| 17 |
+
|
| 18 |
+
from pdf2zh.translator import (
|
| 19 |
+
AnythingLLMTranslator,
|
| 20 |
+
ArgosTranslator,
|
| 21 |
+
AzureOpenAITranslator,
|
| 22 |
+
AzureTranslator,
|
| 23 |
+
BaseTranslator,
|
| 24 |
+
BingTranslator,
|
| 25 |
+
DeepLTranslator,
|
| 26 |
+
DeepLXTranslator,
|
| 27 |
+
DeepseekTranslator,
|
| 28 |
+
DifyTranslator,
|
| 29 |
+
GeminiTranslator,
|
| 30 |
+
GoogleTranslator,
|
| 31 |
+
GrokTranslator,
|
| 32 |
+
GroqTranslator,
|
| 33 |
+
ModelScopeTranslator,
|
| 34 |
+
OllamaTranslator,
|
| 35 |
+
OpenAIlikedTranslator,
|
| 36 |
+
OpenAITranslator,
|
| 37 |
+
QwenMtTranslator,
|
| 38 |
+
SiliconTranslator,
|
| 39 |
+
TencentTranslator,
|
| 40 |
+
X302AITranslator,
|
| 41 |
+
XinferenceTranslator,
|
| 42 |
+
ZhipuTranslator,
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
log = logging.getLogger(__name__)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class PDFConverterEx(PDFConverter):
|
| 49 |
+
def __init__(
|
| 50 |
+
self,
|
| 51 |
+
rsrcmgr: PDFResourceManager,
|
| 52 |
+
) -> None:
|
| 53 |
+
PDFConverter.__init__(self, rsrcmgr, None, "utf-8", 1, None)
|
| 54 |
+
|
| 55 |
+
def begin_page(self, page, ctm) -> None:
|
| 56 |
+
# 重载替换 cropbox
|
| 57 |
+
x0, y0, x1, y1 = page.cropbox
|
| 58 |
+
x0, y0 = apply_matrix_pt(ctm, (x0, y0))
|
| 59 |
+
x1, y1 = apply_matrix_pt(ctm, (x1, y1))
|
| 60 |
+
mediabox = (0, 0, abs(x0 - x1), abs(y0 - y1))
|
| 61 |
+
self.cur_item = LTPage(page.pageno, mediabox)
|
| 62 |
+
|
| 63 |
+
def end_page(self, page):
|
| 64 |
+
# 重载返回指令流
|
| 65 |
+
return self.receive_layout(self.cur_item)
|
| 66 |
+
|
| 67 |
+
def begin_figure(self, name, bbox, matrix) -> None:
|
| 68 |
+
# 重载设置 pageid
|
| 69 |
+
self._stack.append(self.cur_item)
|
| 70 |
+
self.cur_item = LTFigure(name, bbox, mult_matrix(matrix, self.ctm))
|
| 71 |
+
self.cur_item.pageid = self._stack[-1].pageid
|
| 72 |
+
|
| 73 |
+
def end_figure(self, _: str) -> None:
|
| 74 |
+
# 重载返回指令流
|
| 75 |
+
fig = self.cur_item
|
| 76 |
+
assert isinstance(self.cur_item, LTFigure), str(type(self.cur_item))
|
| 77 |
+
self.cur_item = self._stack.pop()
|
| 78 |
+
self.cur_item.add(fig)
|
| 79 |
+
return self.receive_layout(fig)
|
| 80 |
+
|
| 81 |
+
def render_char(
|
| 82 |
+
self,
|
| 83 |
+
matrix,
|
| 84 |
+
font,
|
| 85 |
+
fontsize: float,
|
| 86 |
+
scaling: float,
|
| 87 |
+
rise: float,
|
| 88 |
+
cid: int,
|
| 89 |
+
ncs,
|
| 90 |
+
graphicstate: PDFGraphicState,
|
| 91 |
+
) -> float:
|
| 92 |
+
# 重载设置 cid 和 font
|
| 93 |
+
try:
|
| 94 |
+
text = font.to_unichr(cid)
|
| 95 |
+
assert isinstance(text, str), str(type(text))
|
| 96 |
+
except PDFUnicodeNotDefined:
|
| 97 |
+
text = self.handle_undefined_char(font, cid)
|
| 98 |
+
textwidth = font.char_width(cid)
|
| 99 |
+
textdisp = font.char_disp(cid)
|
| 100 |
+
item = LTChar(
|
| 101 |
+
matrix,
|
| 102 |
+
font,
|
| 103 |
+
fontsize,
|
| 104 |
+
scaling,
|
| 105 |
+
rise,
|
| 106 |
+
text,
|
| 107 |
+
textwidth,
|
| 108 |
+
textdisp,
|
| 109 |
+
ncs,
|
| 110 |
+
graphicstate,
|
| 111 |
+
)
|
| 112 |
+
self.cur_item.add(item)
|
| 113 |
+
item.cid = cid # hack 插入原字符编码
|
| 114 |
+
item.font = font # hack 插入原字符字体
|
| 115 |
+
return item.adv
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
class Paragraph:
|
| 119 |
+
def __init__(self, y, x, x0, x1, y0, y1, size, brk):
|
| 120 |
+
self.y: float = y # 初始纵坐标
|
| 121 |
+
self.x: float = x # 初始横坐标
|
| 122 |
+
self.x0: float = x0 # 左边界
|
| 123 |
+
self.x1: float = x1 # 右边界
|
| 124 |
+
self.y0: float = y0 # 上边界
|
| 125 |
+
self.y1: float = y1 # 下边界
|
| 126 |
+
self.size: float = size # 字体大小
|
| 127 |
+
self.brk: bool = brk # 换行标记
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
# fmt: off
|
| 131 |
+
class TranslateConverter(PDFConverterEx):
|
| 132 |
+
def __init__(
|
| 133 |
+
self,
|
| 134 |
+
rsrcmgr,
|
| 135 |
+
vfont: str = None,
|
| 136 |
+
vchar: str = None,
|
| 137 |
+
thread: int = 0,
|
| 138 |
+
layout={},
|
| 139 |
+
lang_in: str = "",
|
| 140 |
+
lang_out: str = "",
|
| 141 |
+
service: str = "",
|
| 142 |
+
noto_name: str = "",
|
| 143 |
+
noto: Font = None,
|
| 144 |
+
envs: Dict = None,
|
| 145 |
+
prompt: Template = None,
|
| 146 |
+
ignore_cache: bool = False,
|
| 147 |
+
) -> None:
|
| 148 |
+
super().__init__(rsrcmgr)
|
| 149 |
+
self.vfont = vfont
|
| 150 |
+
self.vchar = vchar
|
| 151 |
+
self.thread = thread
|
| 152 |
+
self.layout = layout
|
| 153 |
+
self.noto_name = noto_name
|
| 154 |
+
self.noto = noto
|
| 155 |
+
self.translator: BaseTranslator = None
|
| 156 |
+
# e.g. "ollama:gemma2:9b" -> ["ollama", "gemma2:9b"]
|
| 157 |
+
param = service.split(":", 1)
|
| 158 |
+
service_name = param[0]
|
| 159 |
+
service_model = param[1] if len(param) > 1 else None
|
| 160 |
+
if not envs:
|
| 161 |
+
envs = {}
|
| 162 |
+
for translator in [GoogleTranslator, BingTranslator, DeepLTranslator, DeepLXTranslator, OllamaTranslator, XinferenceTranslator, AzureOpenAITranslator,
|
| 163 |
+
OpenAITranslator, ZhipuTranslator, ModelScopeTranslator, SiliconTranslator, GeminiTranslator, AzureTranslator, TencentTranslator, DifyTranslator, AnythingLLMTranslator, ArgosTranslator, GrokTranslator, GroqTranslator, DeepseekTranslator, OpenAIlikedTranslator, QwenMtTranslator, X302AITranslator]:
|
| 164 |
+
if service_name == translator.name:
|
| 165 |
+
self.translator = translator(lang_in, lang_out, service_model, envs=envs, prompt=prompt, ignore_cache=ignore_cache)
|
| 166 |
+
if not self.translator:
|
| 167 |
+
raise ValueError("Unsupported translation service")
|
| 168 |
+
|
| 169 |
+
def receive_layout(self, ltpage: LTPage):
|
| 170 |
+
# 段落
|
| 171 |
+
sstk: list[str] = [] # 段落文字栈
|
| 172 |
+
pstk: list[Paragraph] = [] # 段落属性栈
|
| 173 |
+
vbkt: int = 0 # 段落公式括号计数
|
| 174 |
+
# 公式组
|
| 175 |
+
vstk: list[LTChar] = [] # 公式符号组
|
| 176 |
+
vlstk: list[LTLine] = [] # 公式线条组
|
| 177 |
+
vfix: float = 0 # 公式纵向偏移
|
| 178 |
+
# 公式组栈
|
| 179 |
+
var: list[list[LTChar]] = [] # 公式符号组栈
|
| 180 |
+
varl: list[list[LTLine]] = [] # 公式线条组栈
|
| 181 |
+
varf: list[float] = [] # 公式纵向偏移栈
|
| 182 |
+
vlen: list[float] = [] # 公式宽度栈
|
| 183 |
+
# 全局
|
| 184 |
+
lstk: list[LTLine] = [] # 全局线条栈
|
| 185 |
+
xt: LTChar = None # 上一个字符
|
| 186 |
+
xt_cls: int = -1 # 上一个字符所属段落,保证无论第一个字符属于哪个类别都可以触发新段落
|
| 187 |
+
vmax: float = ltpage.width / 4 # 行内公式最大宽度
|
| 188 |
+
ops: str = "" # 渲染结果
|
| 189 |
+
|
| 190 |
+
def vflag(font: str, char: str): # 匹配公式(和角标)字体
|
| 191 |
+
if isinstance(font, bytes): # 不一定能 decode,直接转 str
|
| 192 |
+
try:
|
| 193 |
+
font = font.decode('utf-8') # 尝试使用 UTF-8 解码
|
| 194 |
+
except UnicodeDecodeError:
|
| 195 |
+
font = ""
|
| 196 |
+
font = font.split("+")[-1] # 字体名截断
|
| 197 |
+
if re.match(r"\(cid:", char):
|
| 198 |
+
return True
|
| 199 |
+
# 基于字体名规则的判定
|
| 200 |
+
if self.vfont:
|
| 201 |
+
if re.match(self.vfont, font):
|
| 202 |
+
return True
|
| 203 |
+
else:
|
| 204 |
+
if re.match( # latex 字体
|
| 205 |
+
r"(CM[^R]|MS.M|XY|MT|BL|RM|EU|LA|RS|LINE|LCIRCLE|TeX-|rsfs|txsy|wasy|stmary|.*Mono|.*Code|.*Ital|.*Sym|.*Math)",
|
| 206 |
+
font,
|
| 207 |
+
):
|
| 208 |
+
return True
|
| 209 |
+
# 基于字符集规则的判定
|
| 210 |
+
if self.vchar:
|
| 211 |
+
if re.match(self.vchar, char):
|
| 212 |
+
return True
|
| 213 |
+
else:
|
| 214 |
+
if (
|
| 215 |
+
char
|
| 216 |
+
and char != " " # 非空格
|
| 217 |
+
and (
|
| 218 |
+
unicodedata.category(char[0])
|
| 219 |
+
in ["Lm", "Mn", "Sk", "Sm", "Zl", "Zp", "Zs"] # 文字修饰符、数学符号、分隔符号
|
| 220 |
+
or ord(char[0]) in range(0x370, 0x400) # 希腊字母
|
| 221 |
+
)
|
| 222 |
+
):
|
| 223 |
+
return True
|
| 224 |
+
return False
|
| 225 |
+
|
| 226 |
+
############################################################
|
| 227 |
+
# A. 原文档解析
|
| 228 |
+
for child in ltpage:
|
| 229 |
+
if isinstance(child, LTChar):
|
| 230 |
+
cur_v = False
|
| 231 |
+
layout = self.layout[ltpage.pageid]
|
| 232 |
+
# ltpage.height 可能是 fig 里面的高度,这里统一用 layout.shape
|
| 233 |
+
h, w = layout.shape
|
| 234 |
+
# 读取当前字符在 layout 中的类别
|
| 235 |
+
cx, cy = np.clip(int(child.x0), 0, w - 1), np.clip(int(child.y0), 0, h - 1)
|
| 236 |
+
cls = layout[cy, cx]
|
| 237 |
+
# 锚定文档中 bullet 的位置
|
| 238 |
+
if child.get_text() == "•":
|
| 239 |
+
cls = 0
|
| 240 |
+
# 判定当前字符是否属于公式
|
| 241 |
+
if ( # 判定当前字符是否属于公式
|
| 242 |
+
cls == 0 # 1. 类别为保留区域
|
| 243 |
+
or (cls == xt_cls and len(sstk[-1].strip()) > 1 and child.size < pstk[-1].size * 0.79) # 2. 角标字体,有 0.76 的角标和 0.799 的大写,这里用 0.79 取中,同时考虑首字母放大的情况
|
| 244 |
+
or vflag(child.fontname, child.get_text()) # 3. 公式字体
|
| 245 |
+
or (child.matrix[0] == 0 and child.matrix[3] == 0) # 4. 垂直字体
|
| 246 |
+
):
|
| 247 |
+
cur_v = True
|
| 248 |
+
# 判定括号组是否属于公式
|
| 249 |
+
if not cur_v:
|
| 250 |
+
if vstk and child.get_text() == "(":
|
| 251 |
+
cur_v = True
|
| 252 |
+
vbkt += 1
|
| 253 |
+
if vbkt and child.get_text() == ")":
|
| 254 |
+
cur_v = True
|
| 255 |
+
vbkt -= 1
|
| 256 |
+
if ( # 判定当前公式是否结束
|
| 257 |
+
not cur_v # 1. 当前字符不属于公式
|
| 258 |
+
or cls != xt_cls # 2. 当前字符与前一个字符不属于同一段落
|
| 259 |
+
# or (abs(child.x0 - xt.x0) > vmax and cls != 0) # 3. 段落内换行,可能是一长串斜体的段落,也可能是段内分式换行,这里设个阈值进行区分
|
| 260 |
+
# 禁止纯公式(代码)段落换行,直到文字开始再重开文字段落,保证只存在两种情况
|
| 261 |
+
# A. 纯公式(代码)段落(锚定绝对位置)sstk[-1]=="" -> sstk[-1]=="{v*}"
|
| 262 |
+
# B. 文字开头段落(排版相对位置)sstk[-1]!=""
|
| 263 |
+
or (sstk[-1] != "" and abs(child.x0 - xt.x0) > vmax) # 因为 cls==xt_cls==0 一定有 sstk[-1]=="",所以这里不需要再判定 cls!=0
|
| 264 |
+
):
|
| 265 |
+
if vstk:
|
| 266 |
+
if ( # 根据公式右侧的文字修正公式的纵向偏移
|
| 267 |
+
not cur_v # 1. 当前字符不属于公式
|
| 268 |
+
and cls == xt_cls # 2. 当前字符与前一个字符属于同一段落
|
| 269 |
+
and child.x0 > max([vch.x0 for vch in vstk]) # 3. 当前字符在公式右侧
|
| 270 |
+
):
|
| 271 |
+
vfix = vstk[0].y0 - child.y0
|
| 272 |
+
if sstk[-1] == "":
|
| 273 |
+
xt_cls = -1 # 禁止纯公式段落(sstk[-1]=="{v*}")的后续连接,但是要考虑新字符和后续字符的连接,所以这里修改的是上个字符的类别
|
| 274 |
+
sstk[-1] += f"{{v{len(var)}}}"
|
| 275 |
+
var.append(vstk)
|
| 276 |
+
varl.append(vlstk)
|
| 277 |
+
varf.append(vfix)
|
| 278 |
+
vstk = []
|
| 279 |
+
vlstk = []
|
| 280 |
+
vfix = 0
|
| 281 |
+
# 当前字符不属于公式或当前字符是公式的第一个字符
|
| 282 |
+
if not vstk:
|
| 283 |
+
if cls == xt_cls: # 当前字符与前一个字符属于同一段落
|
| 284 |
+
if child.x0 > xt.x1 + 1: # 添加行内空格
|
| 285 |
+
sstk[-1] += " "
|
| 286 |
+
elif child.x1 < xt.x0: # 添加换行空格并标记原文段落存在换行
|
| 287 |
+
sstk[-1] += " "
|
| 288 |
+
pstk[-1].brk = True
|
| 289 |
+
else: # 根据当前字符构建一个新的段落
|
| 290 |
+
sstk.append("")
|
| 291 |
+
pstk.append(Paragraph(child.y0, child.x0, child.x0, child.x0, child.y0, child.y1, child.size, False))
|
| 292 |
+
if not cur_v: # 文字入栈
|
| 293 |
+
if ( # 根据当前字符修正段落属性
|
| 294 |
+
child.size > pstk[-1].size # 1. 当前字符比段落字体大
|
| 295 |
+
or len(sstk[-1].strip()) == 1 # 2. 当前字符为段落第二个文字(考虑首字母放大的情况)
|
| 296 |
+
) and child.get_text() != " ": # 3. 当前字符不是空格
|
| 297 |
+
pstk[-1].y -= child.size - pstk[-1].size # 修正段落初始纵坐标,假设两个不同大小字符的上边界对齐
|
| 298 |
+
pstk[-1].size = child.size
|
| 299 |
+
sstk[-1] += child.get_text()
|
| 300 |
+
else: # 公式入栈
|
| 301 |
+
if ( # 根据公式左侧的文字修正公式的纵向偏移
|
| 302 |
+
not vstk # 1. 当前字符是公式的第一个字符
|
| 303 |
+
and cls == xt_cls # 2. 当前字符与前一个字符属于同一段落
|
| 304 |
+
and child.x0 > xt.x0 # 3. 前一个字符在公式左侧
|
| 305 |
+
):
|
| 306 |
+
vfix = child.y0 - xt.y0
|
| 307 |
+
vstk.append(child)
|
| 308 |
+
# 更新段落边界,因为段落内换行之后可能是公式开头,所以要在外边处理
|
| 309 |
+
pstk[-1].x0 = min(pstk[-1].x0, child.x0)
|
| 310 |
+
pstk[-1].x1 = max(pstk[-1].x1, child.x1)
|
| 311 |
+
pstk[-1].y0 = min(pstk[-1].y0, child.y0)
|
| 312 |
+
pstk[-1].y1 = max(pstk[-1].y1, child.y1)
|
| 313 |
+
# 更新上一个字符
|
| 314 |
+
xt = child
|
| 315 |
+
xt_cls = cls
|
| 316 |
+
elif isinstance(child, LTFigure): # 图表
|
| 317 |
+
pass
|
| 318 |
+
elif isinstance(child, LTLine): # 线条
|
| 319 |
+
layout = self.layout[ltpage.pageid]
|
| 320 |
+
# ltpage.height 可能是 fig 里面的高度,这里统一用 layout.shape
|
| 321 |
+
h, w = layout.shape
|
| 322 |
+
# 读取当前线条在 layout 中的类别
|
| 323 |
+
cx, cy = np.clip(int(child.x0), 0, w - 1), np.clip(int(child.y0), 0, h - 1)
|
| 324 |
+
cls = layout[cy, cx]
|
| 325 |
+
if vstk and cls == xt_cls: # 公式线条
|
| 326 |
+
vlstk.append(child)
|
| 327 |
+
else: # 全局线条
|
| 328 |
+
lstk.append(child)
|
| 329 |
+
else:
|
| 330 |
+
pass
|
| 331 |
+
# 处理结尾
|
| 332 |
+
if vstk: # 公式出栈
|
| 333 |
+
sstk[-1] += f"{{v{len(var)}}}"
|
| 334 |
+
var.append(vstk)
|
| 335 |
+
varl.append(vlstk)
|
| 336 |
+
varf.append(vfix)
|
| 337 |
+
log.debug("\n==========[VSTACK]==========\n")
|
| 338 |
+
for id, v in enumerate(var): # 计算公式宽度
|
| 339 |
+
line_width = max([vch.x1 for vch in v]) - v[0].x0
|
| 340 |
+
log.debug(f'< {line_width:.1f} {v[0].x0:.1f} {v[0].y0:.1f} {v[0].cid} {v[0].fontname} {len(varl[id])} > v{id} = {"".join([ch.get_text() for ch in v])}')
|
| 341 |
+
vlen.append(line_width)
|
| 342 |
+
|
| 343 |
+
############################################################
|
| 344 |
+
# B. 段落翻译
|
| 345 |
+
log.debug("\n==========[SSTACK]==========\n")
|
| 346 |
+
|
| 347 |
+
@retry(wait=wait_fixed(1))
|
| 348 |
+
def worker(s: str): # 多线程翻译
|
| 349 |
+
if not s.strip() or re.match(r"^\{v\d+\}$", s): # 空白和公式不翻译
|
| 350 |
+
return s
|
| 351 |
+
try:
|
| 352 |
+
new = self.translator.translate(s)
|
| 353 |
+
return new
|
| 354 |
+
except BaseException as e:
|
| 355 |
+
if log.isEnabledFor(logging.DEBUG):
|
| 356 |
+
log.exception(e)
|
| 357 |
+
else:
|
| 358 |
+
log.exception(e, exc_info=False)
|
| 359 |
+
raise e
|
| 360 |
+
with concurrent.futures.ThreadPoolExecutor(
|
| 361 |
+
max_workers=self.thread
|
| 362 |
+
) as executor:
|
| 363 |
+
news = list(executor.map(worker, sstk))
|
| 364 |
+
|
| 365 |
+
############################################################
|
| 366 |
+
# C. 新文档排版
|
| 367 |
+
def raw_string(fcur: str, cstk: str): # 编码字符串
|
| 368 |
+
if fcur == self.noto_name:
|
| 369 |
+
return "".join(["%04x" % self.noto.has_glyph(ord(c)) for c in cstk])
|
| 370 |
+
elif isinstance(self.fontmap[fcur], PDFCIDFont): # 判断编码长度
|
| 371 |
+
return "".join(["%04x" % ord(c) for c in cstk])
|
| 372 |
+
else:
|
| 373 |
+
return "".join(["%02x" % ord(c) for c in cstk])
|
| 374 |
+
|
| 375 |
+
# 根据目标语言获取默认行距
|
| 376 |
+
LANG_LINEHEIGHT_MAP = {
|
| 377 |
+
"zh-cn": 1.4, "zh-tw": 1.4, "zh-hans": 1.4, "zh-hant": 1.4, "zh": 1.4,
|
| 378 |
+
"ja": 1.1, "ko": 1.2, "en": 1.2, "ar": 1.0, "ru": 0.8, "uk": 0.8, "ta": 0.8
|
| 379 |
+
}
|
| 380 |
+
default_line_height = LANG_LINEHEIGHT_MAP.get(self.translator.lang_out.lower(), 1.1) # 小语种默认1.1
|
| 381 |
+
_x, _y = 0, 0
|
| 382 |
+
ops_list = []
|
| 383 |
+
|
| 384 |
+
def gen_op_txt(font, size, x, y, rtxt):
|
| 385 |
+
return f"/{font} {size:f} Tf 1 0 0 1 {x:f} {y:f} Tm [<{rtxt}>] TJ "
|
| 386 |
+
|
| 387 |
+
def gen_op_line(x, y, xlen, ylen, linewidth):
|
| 388 |
+
return f"ET q 1 0 0 1 {x:f} {y:f} cm [] 0 d 0 J {linewidth:f} w 0 0 m {xlen:f} {ylen:f} l S Q BT "
|
| 389 |
+
|
| 390 |
+
for id, new in enumerate(news):
|
| 391 |
+
x: float = pstk[id].x # 段落初始横坐标
|
| 392 |
+
y: float = pstk[id].y # 段落初始纵坐标
|
| 393 |
+
x0: float = pstk[id].x0 # 段落左边界
|
| 394 |
+
x1: float = pstk[id].x1 # 段落右边界
|
| 395 |
+
height: float = pstk[id].y1 - pstk[id].y0 # 段落高度
|
| 396 |
+
size: float = pstk[id].size # 段落字体大小
|
| 397 |
+
brk: bool = pstk[id].brk # 段落换行标记
|
| 398 |
+
cstk: str = "" # 当前文字栈
|
| 399 |
+
fcur: str = None # 当前字体 ID
|
| 400 |
+
lidx = 0 # 记录换行次数
|
| 401 |
+
tx = x
|
| 402 |
+
fcur_ = fcur
|
| 403 |
+
ptr = 0
|
| 404 |
+
log.debug(f"< {y} {x} {x0} {x1} {size} {brk} > {sstk[id]} | {new}")
|
| 405 |
+
|
| 406 |
+
ops_vals: list[dict] = []
|
| 407 |
+
|
| 408 |
+
while ptr < len(new):
|
| 409 |
+
vy_regex = re.match(
|
| 410 |
+
r"\{\s*v([\d\s]+)\}", new[ptr:], re.IGNORECASE
|
| 411 |
+
) # 匹配 {vn} 公式标记
|
| 412 |
+
mod = 0 # 文字修饰符
|
| 413 |
+
if vy_regex: # 加载公式
|
| 414 |
+
ptr += len(vy_regex.group(0))
|
| 415 |
+
try:
|
| 416 |
+
vid = int(vy_regex.group(1).replace(" ", ""))
|
| 417 |
+
adv = vlen[vid]
|
| 418 |
+
except Exception:
|
| 419 |
+
continue # 翻译器可能会自动补个越界的公式标记
|
| 420 |
+
if var[vid][-1].get_text() and unicodedata.category(var[vid][-1].get_text()[0]) in ["Lm", "Mn", "Sk"]: # 文字修饰符
|
| 421 |
+
mod = var[vid][-1].width
|
| 422 |
+
else: # 加载文字
|
| 423 |
+
ch = new[ptr]
|
| 424 |
+
fcur_ = None
|
| 425 |
+
try:
|
| 426 |
+
if fcur_ is None and self.fontmap["tiro"].to_unichr(ord(ch)) == ch:
|
| 427 |
+
fcur_ = "tiro" # 默认拉丁字体
|
| 428 |
+
except Exception:
|
| 429 |
+
pass
|
| 430 |
+
if fcur_ is None:
|
| 431 |
+
fcur_ = self.noto_name # 默认非拉丁字体
|
| 432 |
+
if fcur_ == self.noto_name: # FIXME: change to CONST
|
| 433 |
+
adv = self.noto.char_lengths(ch, size)[0]
|
| 434 |
+
else:
|
| 435 |
+
adv = self.fontmap[fcur_].char_width(ord(ch)) * size
|
| 436 |
+
ptr += 1
|
| 437 |
+
if ( # 输出文字缓冲区
|
| 438 |
+
fcur_ != fcur # 1. 字体更新
|
| 439 |
+
or vy_regex # 2. 插入公式
|
| 440 |
+
or x + adv > x1 + 0.1 * size # 3. 到达右边界(可能一整行都被符号化,这里需要考虑浮点误差)
|
| 441 |
+
):
|
| 442 |
+
if cstk:
|
| 443 |
+
ops_vals.append({
|
| 444 |
+
"type": OpType.TEXT,
|
| 445 |
+
"font": fcur,
|
| 446 |
+
"size": size,
|
| 447 |
+
"x": tx,
|
| 448 |
+
"dy": 0,
|
| 449 |
+
"rtxt": raw_string(fcur, cstk),
|
| 450 |
+
"lidx": lidx
|
| 451 |
+
})
|
| 452 |
+
cstk = ""
|
| 453 |
+
if brk and x + adv > x1 + 0.1 * size: # 到达右边界且原文段落存在换行
|
| 454 |
+
x = x0
|
| 455 |
+
lidx += 1
|
| 456 |
+
if vy_regex: # 插入公式
|
| 457 |
+
fix = 0
|
| 458 |
+
if fcur is not None: # 段落内公式修正纵向偏移
|
| 459 |
+
fix = varf[vid]
|
| 460 |
+
for vch in var[vid]: # 排版公式字符
|
| 461 |
+
vc = chr(vch.cid)
|
| 462 |
+
ops_vals.append({
|
| 463 |
+
"type": OpType.TEXT,
|
| 464 |
+
"font": self.fontid[vch.font],
|
| 465 |
+
"size": vch.size,
|
| 466 |
+
"x": x + vch.x0 - var[vid][0].x0,
|
| 467 |
+
"dy": fix + vch.y0 - var[vid][0].y0,
|
| 468 |
+
"rtxt": raw_string(self.fontid[vch.font], vc),
|
| 469 |
+
"lidx": lidx
|
| 470 |
+
})
|
| 471 |
+
if log.isEnabledFor(logging.DEBUG):
|
| 472 |
+
lstk.append(LTLine(0.1, (_x, _y), (x + vch.x0 - var[vid][0].x0, fix + y + vch.y0 - var[vid][0].y0)))
|
| 473 |
+
_x, _y = x + vch.x0 - var[vid][0].x0, fix + y + vch.y0 - var[vid][0].y0
|
| 474 |
+
for line_item in varl[vid]: # 排版公式线条
|
| 475 |
+
if line_item.linewidth < 5: # hack 有的文档会用粗线条当图片背景
|
| 476 |
+
ops_vals.append({
|
| 477 |
+
"type": OpType.LINE,
|
| 478 |
+
"x": line_item.pts[0][0] + x - var[vid][0].x0,
|
| 479 |
+
"dy": line_item.pts[0][1] + fix - var[vid][0].y0,
|
| 480 |
+
"linewidth": line_item.linewidth,
|
| 481 |
+
"xlen": line_item.pts[1][0] - line_item.pts[0][0],
|
| 482 |
+
"ylen": line_item.pts[1][1] - line_item.pts[0][1],
|
| 483 |
+
"lidx": lidx
|
| 484 |
+
})
|
| 485 |
+
else: # 插入文字缓冲区
|
| 486 |
+
if not cstk: # 单行开头
|
| 487 |
+
tx = x
|
| 488 |
+
if x == x0 and ch == " ": # 消除段落换行空格
|
| 489 |
+
adv = 0
|
| 490 |
+
else:
|
| 491 |
+
cstk += ch
|
| 492 |
+
else:
|
| 493 |
+
cstk += ch
|
| 494 |
+
adv -= mod # 文字修饰符
|
| 495 |
+
fcur = fcur_
|
| 496 |
+
x += adv
|
| 497 |
+
if log.isEnabledFor(logging.DEBUG):
|
| 498 |
+
lstk.append(LTLine(0.1, (_x, _y), (x, y)))
|
| 499 |
+
_x, _y = x, y
|
| 500 |
+
# 处理结尾
|
| 501 |
+
if cstk:
|
| 502 |
+
ops_vals.append({
|
| 503 |
+
"type": OpType.TEXT,
|
| 504 |
+
"font": fcur,
|
| 505 |
+
"size": size,
|
| 506 |
+
"x": tx,
|
| 507 |
+
"dy": 0,
|
| 508 |
+
"rtxt": raw_string(fcur, cstk),
|
| 509 |
+
"lidx": lidx
|
| 510 |
+
})
|
| 511 |
+
|
| 512 |
+
line_height = default_line_height
|
| 513 |
+
|
| 514 |
+
while (lidx + 1) * size * line_height > height and line_height >= 1:
|
| 515 |
+
line_height -= 0.05
|
| 516 |
+
|
| 517 |
+
for vals in ops_vals:
|
| 518 |
+
if vals["type"] == OpType.TEXT:
|
| 519 |
+
ops_list.append(gen_op_txt(vals["font"], vals["size"], vals["x"], vals["dy"] + y - vals["lidx"] * size * line_height, vals["rtxt"]))
|
| 520 |
+
elif vals["type"] == OpType.LINE:
|
| 521 |
+
ops_list.append(gen_op_line(vals["x"], vals["dy"] + y - vals["lidx"] * size * line_height, vals["xlen"], vals["ylen"], vals["linewidth"]))
|
| 522 |
+
|
| 523 |
+
for line_item in lstk: # 排版全局线条
|
| 524 |
+
if line_item.linewidth < 5: # hack 有的文档会用粗线条当图片背景
|
| 525 |
+
ops_list.append(gen_op_line(line_item.pts[0][0], line_item.pts[0][1], line_item.pts[1][0] - line_item.pts[0][0], line_item.pts[1][1] - line_item.pts[0][1], line_item.linewidth))
|
| 526 |
+
|
| 527 |
+
ops = f"BT {''.join(ops_list)}ET "
|
| 528 |
+
return ops
|
| 529 |
+
|
| 530 |
+
|
| 531 |
+
class OpType(Enum):
|
| 532 |
+
TEXT = "text"
|
| 533 |
+
LINE = "line"
|
pdf2zh/doclayout.py
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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ast
|
| 3 |
+
|
| 4 |
+
import cv2
|
| 5 |
+
import numpy as np
|
| 6 |
+
from babeldoc.assets.assets import get_doclayout_onnx_model_path
|
| 7 |
+
|
| 8 |
+
try:
|
| 9 |
+
import onnx
|
| 10 |
+
import onnxruntime
|
| 11 |
+
except ImportError as e:
|
| 12 |
+
if "DLL load failed" in str(e):
|
| 13 |
+
raise OSError(
|
| 14 |
+
"Microsoft Visual C++ Redistributable is not installed. "
|
| 15 |
+
"Download it at https://aka.ms/vs/17/release/vc_redist.x64.exe"
|
| 16 |
+
) from e
|
| 17 |
+
raise
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class DocLayoutModel(abc.ABC):
|
| 21 |
+
@staticmethod
|
| 22 |
+
def load_onnx():
|
| 23 |
+
model = OnnxModel.from_pretrained()
|
| 24 |
+
return model
|
| 25 |
+
|
| 26 |
+
@staticmethod
|
| 27 |
+
def load_available():
|
| 28 |
+
return DocLayoutModel.load_onnx()
|
| 29 |
+
|
| 30 |
+
@property
|
| 31 |
+
@abc.abstractmethod
|
| 32 |
+
def stride(self) -> int:
|
| 33 |
+
"""Stride of the model input."""
|
| 34 |
+
pass
|
| 35 |
+
|
| 36 |
+
@abc.abstractmethod
|
| 37 |
+
def predict(self, image, imgsz=1024, **kwargs) -> list:
|
| 38 |
+
"""
|
| 39 |
+
Predict the layout of a document page.
|
| 40 |
+
|
| 41 |
+
Args:
|
| 42 |
+
image: The image of the document page.
|
| 43 |
+
imgsz: Resize the image to this size. Must be a multiple of the stride.
|
| 44 |
+
**kwargs: Additional arguments.
|
| 45 |
+
"""
|
| 46 |
+
pass
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class YoloResult:
|
| 50 |
+
"""Helper class to store detection results from ONNX model."""
|
| 51 |
+
|
| 52 |
+
def __init__(self, boxes, names):
|
| 53 |
+
self.boxes = [YoloBox(data=d) for d in boxes]
|
| 54 |
+
self.boxes.sort(key=lambda x: x.conf, reverse=True)
|
| 55 |
+
self.names = names
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class YoloBox:
|
| 59 |
+
"""Helper class to store detection results from ONNX model."""
|
| 60 |
+
|
| 61 |
+
def __init__(self, data):
|
| 62 |
+
self.xyxy = data[:4]
|
| 63 |
+
self.conf = data[-2]
|
| 64 |
+
self.cls = data[-1]
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
class OnnxModel(DocLayoutModel):
|
| 68 |
+
def __init__(self, model_path: str):
|
| 69 |
+
self.model_path = model_path
|
| 70 |
+
|
| 71 |
+
model = onnx.load(model_path)
|
| 72 |
+
metadata = {d.key: d.value for d in model.metadata_props}
|
| 73 |
+
self._stride = ast.literal_eval(metadata["stride"])
|
| 74 |
+
self._names = ast.literal_eval(metadata["names"])
|
| 75 |
+
|
| 76 |
+
self.model = onnxruntime.InferenceSession(model.SerializeToString())
|
| 77 |
+
|
| 78 |
+
@staticmethod
|
| 79 |
+
def from_pretrained():
|
| 80 |
+
pth = get_doclayout_onnx_model_path()
|
| 81 |
+
return OnnxModel(pth)
|
| 82 |
+
|
| 83 |
+
@property
|
| 84 |
+
def stride(self):
|
| 85 |
+
return self._stride
|
| 86 |
+
|
| 87 |
+
def resize_and_pad_image(self, image, new_shape):
|
| 88 |
+
"""
|
| 89 |
+
Resize and pad the image to the specified size, ensuring dimensions are multiples of stride.
|
| 90 |
+
|
| 91 |
+
Parameters:
|
| 92 |
+
- image: Input image
|
| 93 |
+
- new_shape: Target size (integer or (height, width) tuple)
|
| 94 |
+
- stride: Padding alignment stride, default 32
|
| 95 |
+
|
| 96 |
+
Returns:
|
| 97 |
+
- Processed image
|
| 98 |
+
"""
|
| 99 |
+
if isinstance(new_shape, int):
|
| 100 |
+
new_shape = (new_shape, new_shape)
|
| 101 |
+
|
| 102 |
+
h, w = image.shape[:2]
|
| 103 |
+
new_h, new_w = new_shape
|
| 104 |
+
|
| 105 |
+
# Calculate scaling ratio
|
| 106 |
+
r = min(new_h / h, new_w / w)
|
| 107 |
+
resized_h, resized_w = int(round(h * r)), int(round(w * r))
|
| 108 |
+
|
| 109 |
+
# Resize image
|
| 110 |
+
image = cv2.resize(
|
| 111 |
+
image, (resized_w, resized_h), interpolation=cv2.INTER_LINEAR
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
# Calculate padding size and align to stride multiple
|
| 115 |
+
pad_w = (new_w - resized_w) % self.stride
|
| 116 |
+
pad_h = (new_h - resized_h) % self.stride
|
| 117 |
+
top, bottom = pad_h // 2, pad_h - pad_h // 2
|
| 118 |
+
left, right = pad_w // 2, pad_w - pad_w // 2
|
| 119 |
+
|
| 120 |
+
# Add padding
|
| 121 |
+
image = cv2.copyMakeBorder(
|
| 122 |
+
image, top, bottom, left, right, cv2.BORDER_CONSTANT, value=(114, 114, 114)
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
return image
|
| 126 |
+
|
| 127 |
+
def scale_boxes(self, img1_shape, boxes, img0_shape):
|
| 128 |
+
"""
|
| 129 |
+
Rescales bounding boxes (in the format of xyxy by default) from the shape of the image they were originally
|
| 130 |
+
specified in (img1_shape) to the shape of a different image (img0_shape).
|
| 131 |
+
|
| 132 |
+
Args:
|
| 133 |
+
img1_shape (tuple): The shape of the image that the bounding boxes are for,
|
| 134 |
+
in the format of (height, width).
|
| 135 |
+
boxes (torch.Tensor): the bounding boxes of the objects in the image, in the format of (x1, y1, x2, y2)
|
| 136 |
+
img0_shape (tuple): the shape of the target image, in the format of (height, width).
|
| 137 |
+
|
| 138 |
+
Returns:
|
| 139 |
+
boxes (torch.Tensor): The scaled bounding boxes, in the format of (x1, y1, x2, y2)
|
| 140 |
+
"""
|
| 141 |
+
|
| 142 |
+
# Calculate scaling ratio
|
| 143 |
+
gain = min(img1_shape[0] / img0_shape[0], img1_shape[1] / img0_shape[1])
|
| 144 |
+
|
| 145 |
+
# Calculate padding size
|
| 146 |
+
pad_x = round((img1_shape[1] - img0_shape[1] * gain) / 2 - 0.1)
|
| 147 |
+
pad_y = round((img1_shape[0] - img0_shape[0] * gain) / 2 - 0.1)
|
| 148 |
+
|
| 149 |
+
# Remove padding and scale boxes
|
| 150 |
+
boxes[..., :4] = (boxes[..., :4] - [pad_x, pad_y, pad_x, pad_y]) / gain
|
| 151 |
+
return boxes
|
| 152 |
+
|
| 153 |
+
def predict(self, image, imgsz=1024, **kwargs):
|
| 154 |
+
# Preprocess input image
|
| 155 |
+
orig_h, orig_w = image.shape[:2]
|
| 156 |
+
pix = self.resize_and_pad_image(image, new_shape=imgsz)
|
| 157 |
+
pix = np.transpose(pix, (2, 0, 1)) # CHW
|
| 158 |
+
pix = np.expand_dims(pix, axis=0) # BCHW
|
| 159 |
+
pix = pix.astype(np.float32) / 255.0 # Normalize to [0, 1]
|
| 160 |
+
new_h, new_w = pix.shape[2:]
|
| 161 |
+
|
| 162 |
+
# Run inference
|
| 163 |
+
preds = self.model.run(None, {"images": pix})[0]
|
| 164 |
+
|
| 165 |
+
# Postprocess predictions
|
| 166 |
+
preds = preds[preds[..., 4] > 0.25]
|
| 167 |
+
preds[..., :4] = self.scale_boxes(
|
| 168 |
+
(new_h, new_w), preds[..., :4], (orig_h, orig_w)
|
| 169 |
+
)
|
| 170 |
+
return [YoloResult(boxes=preds, names=self._names)]
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
class ModelInstance:
|
| 174 |
+
value: OnnxModel = None
|
pdf2zh/e2e.py
ADDED
|
@@ -0,0 +1,258 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""End-to-end orchestration: OCR (Phase 1) -> Translate (Phase 2) -> Render (Phase 3).
|
| 2 |
+
|
| 3 |
+
This module wires the three existing phases into a single callable used by the
|
| 4 |
+
Gradio app (``app.py``). It reuses the public APIs of each phase and adds:
|
| 5 |
+
- a process-wide lazy singleton for ``StageAParser`` (its 3-5GB models load once),
|
| 6 |
+
- language-name + font handling shared across the run,
|
| 7 |
+
- intermediate JSON artifacts written to a per-request work dir.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
import json
|
| 13 |
+
import logging
|
| 14 |
+
import os
|
| 15 |
+
import time
|
| 16 |
+
import uuid
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
from typing import Callable, Optional
|
| 19 |
+
|
| 20 |
+
from pdf2zh.config import get_settings
|
| 21 |
+
from pdf2zh.parser import PDFTypeDetector, StageAParser
|
| 22 |
+
from pdf2zh.render import RenderConfig, render_document
|
| 23 |
+
from pdf2zh.translation import TranslatorConfig, translate_document
|
| 24 |
+
|
| 25 |
+
logger = logging.getLogger(__name__)
|
| 26 |
+
|
| 27 |
+
# Full language names — Phase 2 prompts interpolate these directly (prompts.py).
|
| 28 |
+
SUPPORTED_LANGUAGES = [
|
| 29 |
+
"English",
|
| 30 |
+
"Vietnamese",
|
| 31 |
+
"Simplified Chinese",
|
| 32 |
+
"Japanese",
|
| 33 |
+
"Korean",
|
| 34 |
+
"French",
|
| 35 |
+
"German",
|
| 36 |
+
"Spanish",
|
| 37 |
+
]
|
| 38 |
+
|
| 39 |
+
# Directories searched by Typst for fonts (populated in the Docker image).
|
| 40 |
+
FONT_DIRS = [os.environ.get("PDF2ZH_FONT_DIR", "/app/fonts")]
|
| 41 |
+
|
| 42 |
+
# Fonts pre-installed in the image (see Dockerfile). The UI exposes these.
|
| 43 |
+
# Family names must match what Typst sees (apt fonts-noto-* + bundled Be Vietnam Pro).
|
| 44 |
+
BUNDLED_FONTS = ["Noto Sans", "Noto Serif", "Be Vietnam Pro", "Noto Sans CJK SC"]
|
| 45 |
+
DEFAULT_FONT = "Noto Sans" # neutral, full Vietnamese coverage
|
| 46 |
+
# Appended after the user's choice so missing glyphs fall back gracefully.
|
| 47 |
+
FALLBACK_TAIL = ["Noto Sans", "Noto Serif", "Noto Sans CJK SC"]
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def font_chain(selected: str) -> list[str]:
|
| 51 |
+
"""User-selected font first, then multilingual fallbacks (deduped, ordered)."""
|
| 52 |
+
chain = [selected, *FALLBACK_TAIL]
|
| 53 |
+
return list(dict.fromkeys(c for c in chain if c))
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
# --------------------------------------------------------------------------- #
|
| 57 |
+
# Phase-1 model singleton
|
| 58 |
+
# --------------------------------------------------------------------------- #
|
| 59 |
+
_parser: Optional[StageAParser] = None
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def get_parser() -> StageAParser:
|
| 63 |
+
"""Process-wide lazy singleton. The Surya/Paddle models load exactly once."""
|
| 64 |
+
global _parser
|
| 65 |
+
settings = get_settings()
|
| 66 |
+
if _parser is None:
|
| 67 |
+
logger.info("Loading StageAParser models (one-time)...")
|
| 68 |
+
_parser = StageAParser(**settings.model_dump())
|
| 69 |
+
logger.info("StageAParser ready.")
|
| 70 |
+
return _parser
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def warmup() -> None:
|
| 74 |
+
"""Load models at app startup so the first request isn't penalized."""
|
| 75 |
+
get_parser()
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
# --------------------------------------------------------------------------- #
|
| 79 |
+
# Config builders
|
| 80 |
+
# --------------------------------------------------------------------------- #
|
| 81 |
+
def build_translator_config(
|
| 82 |
+
src_lang: str,
|
| 83 |
+
tgt_lang: str,
|
| 84 |
+
provider: str,
|
| 85 |
+
api_key: str,
|
| 86 |
+
model: str | None,
|
| 87 |
+
) -> TranslatorConfig:
|
| 88 |
+
"""Build Phase-2 config. Languages are set on the config directly (the
|
| 89 |
+
pipeline reads ``cfg.source_language`` before the doc dict), and the API key
|
| 90 |
+
is passed through so ``resolve_provider`` never needs an env var."""
|
| 91 |
+
return TranslatorConfig(
|
| 92 |
+
source_language=src_lang,
|
| 93 |
+
target_language=tgt_lang,
|
| 94 |
+
provider=provider,
|
| 95 |
+
model=(model.strip() or None) if model else None,
|
| 96 |
+
api_key=api_key.strip(),
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def build_render_config(font: str, pages: list[int] | None) -> RenderConfig:
|
| 101 |
+
"""Build Phase-3 config. The chosen font heads a fallback chain; the default
|
| 102 |
+
Helvetica lacks Vietnamese glyphs so we always override it."""
|
| 103 |
+
cfg = RenderConfig()
|
| 104 |
+
cfg.font_family = font_chain(font)
|
| 105 |
+
cfg.typst_font_paths = FONT_DIRS
|
| 106 |
+
cfg.typst_binary = os.environ.get("TYPST_BIN", "typst")
|
| 107 |
+
cfg.pages = pages
|
| 108 |
+
cfg.redact_native_text = True
|
| 109 |
+
cfg.min_font_size_pt = 7.0
|
| 110 |
+
return cfg
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
# --------------------------------------------------------------------------- #
|
| 114 |
+
# Orchestration — split into per-phase steps so the stepped UI can checkpoint
|
| 115 |
+
# (review/edit) between phases and re-run only what changed.
|
| 116 |
+
# --------------------------------------------------------------------------- #
|
| 117 |
+
def _progress_fn(
|
| 118 |
+
progress: Callable[[float, str], None] | None,
|
| 119 |
+
) -> Callable[[float, str], None]:
|
| 120 |
+
def _p(frac: float, msg: str) -> None:
|
| 121 |
+
logger.info(msg)
|
| 122 |
+
if progress is not None:
|
| 123 |
+
progress(frac, msg)
|
| 124 |
+
|
| 125 |
+
return _p
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def run_parse(
|
| 129 |
+
pdf_path: str,
|
| 130 |
+
pages: list[int] | None,
|
| 131 |
+
work_dir: str | Path,
|
| 132 |
+
progress: Callable[[float, str], None] | None = None,
|
| 133 |
+
) -> dict:
|
| 134 |
+
"""Phase 1 — OCR / layout parse (slowest step, loads heavy models).
|
| 135 |
+
|
| 136 |
+
Returns the parsed doc as a dict and writes ``phase1_parsed.json``.
|
| 137 |
+
"""
|
| 138 |
+
work = Path(work_dir)
|
| 139 |
+
work.mkdir(parents=True, exist_ok=True)
|
| 140 |
+
if not pdf_path:
|
| 141 |
+
raise ValueError("Vui lòng tải lên một file PDF.")
|
| 142 |
+
_p = _progress_fn(progress)
|
| 143 |
+
|
| 144 |
+
# Detect type (informational only — the Surya path handles all types).
|
| 145 |
+
_p(0.05, "Đang nhận diện loại PDF...")
|
| 146 |
+
try:
|
| 147 |
+
pdf_type = PDFTypeDetector().detect(pdf_path)
|
| 148 |
+
logger.info("PDF type: %s", pdf_type)
|
| 149 |
+
except Exception as exc: # detection is best-effort, never fatal
|
| 150 |
+
logger.warning("PDF type detection failed: %s", exc)
|
| 151 |
+
|
| 152 |
+
_p(0.1, "Phase 1/3 — OCR & phân tích bố cục (bước chậm nhất)...")
|
| 153 |
+
parser = get_parser()
|
| 154 |
+
parsed_doc = parser.parse_pdf(pdf_path, cache_path=None, pages=pages)
|
| 155 |
+
(work / "phase1_parsed.json").write_text(parsed_doc.to_json(), encoding="utf-8")
|
| 156 |
+
return parsed_doc.to_dict()
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def run_translate(
|
| 160 |
+
parsed_dict: dict,
|
| 161 |
+
src_lang: str,
|
| 162 |
+
tgt_lang: str,
|
| 163 |
+
provider: str,
|
| 164 |
+
api_key: str,
|
| 165 |
+
model: str | None,
|
| 166 |
+
work_dir: str | Path,
|
| 167 |
+
progress: Callable[[float, str], None] | None = None,
|
| 168 |
+
) -> dict:
|
| 169 |
+
"""Phase 2 — translate the (possibly edited) parsed doc.
|
| 170 |
+
|
| 171 |
+
Returns the translated dict and writes ``phase2_translated.json``.
|
| 172 |
+
"""
|
| 173 |
+
work = Path(work_dir)
|
| 174 |
+
work.mkdir(parents=True, exist_ok=True)
|
| 175 |
+
if not api_key or not api_key.strip():
|
| 176 |
+
raise ValueError("Thiếu API key — nhập API key của provider ở thanh bên.")
|
| 177 |
+
if not src_lang or not tgt_lang:
|
| 178 |
+
raise ValueError("Chọn ngôn ngữ nguồn và ngôn ngữ đích.")
|
| 179 |
+
_p = _progress_fn(progress)
|
| 180 |
+
|
| 181 |
+
_p(0.55, f"Phase 2/3 — Đang dịch {src_lang} → {tgt_lang}...")
|
| 182 |
+
tcfg = build_translator_config(src_lang, tgt_lang, provider, api_key, model)
|
| 183 |
+
translated_dict = translate_document(parsed_dict, tcfg)
|
| 184 |
+
(work / "phase2_translated.json").write_text(
|
| 185 |
+
json.dumps(translated_dict, ensure_ascii=False, indent=2), encoding="utf-8"
|
| 186 |
+
)
|
| 187 |
+
return translated_dict
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def run_render(
|
| 191 |
+
pdf_path: str,
|
| 192 |
+
translated_dict: dict,
|
| 193 |
+
pages: list[int] | None,
|
| 194 |
+
font: str,
|
| 195 |
+
work_dir: str | Path,
|
| 196 |
+
progress: Callable[[float, str], None] | None = None,
|
| 197 |
+
) -> str:
|
| 198 |
+
"""Phase 3 — render the (possibly edited) translated doc to a PDF.
|
| 199 |
+
|
| 200 |
+
The output contains only the translated pages. Returns the output path.
|
| 201 |
+
"""
|
| 202 |
+
work = Path(work_dir)
|
| 203 |
+
work.mkdir(parents=True, exist_ok=True)
|
| 204 |
+
_p = _progress_fn(progress)
|
| 205 |
+
|
| 206 |
+
_p(0.85, "Phase 3/3 — Đang dựng PDF bản dịch (typst)...")
|
| 207 |
+
out_path = str(work / f"translated_{uuid.uuid4().hex[:8]}.pdf")
|
| 208 |
+
rcfg = build_render_config(font, pages)
|
| 209 |
+
render_document(pdf_path, translated_dict, out_path, rcfg)
|
| 210 |
+
_p(1.0, "Hoàn tất.")
|
| 211 |
+
return out_path
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
def run_pipeline(
|
| 215 |
+
pdf_path: str,
|
| 216 |
+
src_lang: str,
|
| 217 |
+
tgt_lang: str,
|
| 218 |
+
provider: str,
|
| 219 |
+
api_key: str,
|
| 220 |
+
model: str | None,
|
| 221 |
+
pages: list[int] | None,
|
| 222 |
+
font: str,
|
| 223 |
+
work_dir: str | Path,
|
| 224 |
+
progress: Callable[[float, str], None] | None = None,
|
| 225 |
+
) -> str:
|
| 226 |
+
"""Run Phase 1 -> 2 -> 3 end-to-end and return the translated PDF path.
|
| 227 |
+
|
| 228 |
+
``pages`` is a 0-based index list (or None for all) shared by Phase 1 and 3.
|
| 229 |
+
Thin wrapper over run_parse/run_translate/run_render; the stepped UI calls
|
| 230 |
+
those directly so it can checkpoint between phases.
|
| 231 |
+
"""
|
| 232 |
+
# Fail fast on user-input errors before any GPU work.
|
| 233 |
+
if not pdf_path:
|
| 234 |
+
raise ValueError("Vui lòng tải lên một file PDF.")
|
| 235 |
+
if not api_key or not api_key.strip():
|
| 236 |
+
raise ValueError("Thiếu API key — nhập API key của provider ở thanh bên.")
|
| 237 |
+
if not src_lang or not tgt_lang:
|
| 238 |
+
raise ValueError("Chọn ngôn ngữ nguồn và ngôn ngữ đích.")
|
| 239 |
+
|
| 240 |
+
t0 = time.perf_counter()
|
| 241 |
+
parsed = run_parse(pdf_path, pages, work_dir, progress)
|
| 242 |
+
t1 = time.perf_counter()
|
| 243 |
+
translated = run_translate(
|
| 244 |
+
parsed, src_lang, tgt_lang, provider, api_key, model, work_dir, progress
|
| 245 |
+
)
|
| 246 |
+
t2 = time.perf_counter()
|
| 247 |
+
out_path = run_render(pdf_path, translated, pages, font, work_dir, progress)
|
| 248 |
+
t3 = time.perf_counter()
|
| 249 |
+
# End-to-end runs only (the stepped UI calls run_parse/translate/render
|
| 250 |
+
# directly). Logged last so the breakdown is easy to trace after a run.
|
| 251 |
+
logger.info(
|
| 252 |
+
"[latency] parse=%.2fs translate=%.2fs render=%.2fs total=%.2fs",
|
| 253 |
+
t1 - t0,
|
| 254 |
+
t2 - t1,
|
| 255 |
+
t3 - t2,
|
| 256 |
+
t3 - t0,
|
| 257 |
+
)
|
| 258 |
+
return out_path
|
pdf2zh/gui.py
ADDED
|
@@ -0,0 +1,892 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
import cgi
|
| 3 |
+
import logging
|
| 4 |
+
import os
|
| 5 |
+
import shutil
|
| 6 |
+
import typing as T
|
| 7 |
+
import uuid
|
| 8 |
+
from asyncio import CancelledError
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
from string import Template
|
| 11 |
+
|
| 12 |
+
import gradio as gr
|
| 13 |
+
import requests
|
| 14 |
+
import tqdm
|
| 15 |
+
from babeldoc import __version__ as babeldoc_version
|
| 16 |
+
from babeldoc.docvision.doclayout import OnnxModel
|
| 17 |
+
from gradio_pdf import PDF
|
| 18 |
+
|
| 19 |
+
from pdf2zh import __version__
|
| 20 |
+
from pdf2zh.config import ConfigManager
|
| 21 |
+
from pdf2zh.doclayout import ModelInstance
|
| 22 |
+
from pdf2zh.high_level import translate
|
| 23 |
+
from pdf2zh.translator import (
|
| 24 |
+
AnythingLLMTranslator,
|
| 25 |
+
ArgosTranslator,
|
| 26 |
+
AzureOpenAITranslator,
|
| 27 |
+
AzureTranslator,
|
| 28 |
+
BaseTranslator,
|
| 29 |
+
BingTranslator,
|
| 30 |
+
DeepLTranslator,
|
| 31 |
+
DeepLXTranslator,
|
| 32 |
+
DeepseekTranslator,
|
| 33 |
+
DifyTranslator,
|
| 34 |
+
GeminiTranslator,
|
| 35 |
+
GoogleTranslator,
|
| 36 |
+
GrokTranslator,
|
| 37 |
+
GroqTranslator,
|
| 38 |
+
ModelScopeTranslator,
|
| 39 |
+
OllamaTranslator,
|
| 40 |
+
OpenAIlikedTranslator,
|
| 41 |
+
OpenAITranslator,
|
| 42 |
+
QwenMtTranslator,
|
| 43 |
+
SiliconTranslator,
|
| 44 |
+
TencentTranslator,
|
| 45 |
+
X302AITranslator,
|
| 46 |
+
XinferenceTranslator,
|
| 47 |
+
ZhipuTranslator,
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
logger = logging.getLogger(__name__)
|
| 51 |
+
|
| 52 |
+
BABELDOC_MODEL = OnnxModel.load_available()
|
| 53 |
+
# The following variables associate strings with translators
|
| 54 |
+
service_map: dict[str, BaseTranslator] = {
|
| 55 |
+
"Google": GoogleTranslator,
|
| 56 |
+
"Bing": BingTranslator,
|
| 57 |
+
"DeepL": DeepLTranslator,
|
| 58 |
+
"DeepLX": DeepLXTranslator,
|
| 59 |
+
"Ollama": OllamaTranslator,
|
| 60 |
+
"Xinference": XinferenceTranslator,
|
| 61 |
+
"AzureOpenAI": AzureOpenAITranslator,
|
| 62 |
+
"OpenAI": OpenAITranslator,
|
| 63 |
+
"Zhipu": ZhipuTranslator,
|
| 64 |
+
"ModelScope": ModelScopeTranslator,
|
| 65 |
+
"Silicon": SiliconTranslator,
|
| 66 |
+
"Gemini": GeminiTranslator,
|
| 67 |
+
"Azure": AzureTranslator,
|
| 68 |
+
"Tencent": TencentTranslator,
|
| 69 |
+
"Dify": DifyTranslator,
|
| 70 |
+
"AnythingLLM": AnythingLLMTranslator,
|
| 71 |
+
"Argos Translate": ArgosTranslator,
|
| 72 |
+
"Grok": GrokTranslator,
|
| 73 |
+
"Groq": GroqTranslator,
|
| 74 |
+
"DeepSeek": DeepseekTranslator,
|
| 75 |
+
"OpenAI-liked": OpenAIlikedTranslator,
|
| 76 |
+
"Ali Qwen-Translation": QwenMtTranslator,
|
| 77 |
+
"302.AI": X302AITranslator,
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
# The following variables associate strings with specific languages
|
| 81 |
+
lang_map = {
|
| 82 |
+
"Simplified Chinese": "zh",
|
| 83 |
+
"Traditional Chinese": "zh-TW",
|
| 84 |
+
"English": "en",
|
| 85 |
+
"French": "fr",
|
| 86 |
+
"German": "de",
|
| 87 |
+
"Japanese": "ja",
|
| 88 |
+
"Korean": "ko",
|
| 89 |
+
"Russian": "ru",
|
| 90 |
+
"Spanish": "es",
|
| 91 |
+
"Italian": "it",
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
# The following variable associate strings with page ranges
|
| 95 |
+
page_map = {
|
| 96 |
+
"All": None,
|
| 97 |
+
"First": [0],
|
| 98 |
+
"First 5 pages": list(range(0, 5)),
|
| 99 |
+
"Others": None,
|
| 100 |
+
}
|
| 101 |
+
|
| 102 |
+
# Check if this is a public demo, which has resource limits
|
| 103 |
+
flag_demo = False
|
| 104 |
+
|
| 105 |
+
# Limit resources
|
| 106 |
+
if ConfigManager.get("PDF2ZH_DEMO"):
|
| 107 |
+
flag_demo = True
|
| 108 |
+
service_map = {
|
| 109 |
+
"Google": GoogleTranslator,
|
| 110 |
+
}
|
| 111 |
+
page_map = {
|
| 112 |
+
"First": [0],
|
| 113 |
+
"First 20 pages": list(range(0, 20)),
|
| 114 |
+
}
|
| 115 |
+
client_key = ConfigManager.get("PDF2ZH_CLIENT_KEY")
|
| 116 |
+
server_key = ConfigManager.get("PDF2ZH_SERVER_KEY")
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
# Limit Enabled Services
|
| 120 |
+
enabled_services: T.Optional[T.List[str]] = ConfigManager.get("ENABLED_SERVICES")
|
| 121 |
+
if isinstance(enabled_services, list):
|
| 122 |
+
default_services = ["Google", "Bing"]
|
| 123 |
+
enabled_services_names = [str(_).lower().strip() for _ in enabled_services]
|
| 124 |
+
enabled_services = [
|
| 125 |
+
k
|
| 126 |
+
for k in service_map.keys()
|
| 127 |
+
if str(k).lower().strip() in enabled_services_names
|
| 128 |
+
]
|
| 129 |
+
if len(enabled_services) == 0:
|
| 130 |
+
raise RuntimeError("No services available.")
|
| 131 |
+
enabled_services = default_services + enabled_services
|
| 132 |
+
else:
|
| 133 |
+
enabled_services = list(service_map.keys())
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
# Configure about Gradio show keys
|
| 137 |
+
hidden_gradio_details: bool = bool(ConfigManager.get("HIDDEN_GRADIO_DETAILS"))
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
# Public demo control
|
| 141 |
+
def verify_recaptcha(response):
|
| 142 |
+
"""
|
| 143 |
+
This function verifies the reCAPTCHA response.
|
| 144 |
+
"""
|
| 145 |
+
recaptcha_url = "https://www.google.com/recaptcha/api/siteverify"
|
| 146 |
+
data = {"secret": server_key, "response": response}
|
| 147 |
+
result = requests.post(recaptcha_url, data=data).json()
|
| 148 |
+
return result.get("success")
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def download_with_limit(url: str, save_path: str, size_limit: int) -> str:
|
| 152 |
+
"""
|
| 153 |
+
This function downloads a file from a URL and saves it to a specified path.
|
| 154 |
+
|
| 155 |
+
Inputs:
|
| 156 |
+
- url: The URL to download the file from
|
| 157 |
+
- save_path: The path to save the file to
|
| 158 |
+
- size_limit: The maximum size of the file to download
|
| 159 |
+
|
| 160 |
+
Returns:
|
| 161 |
+
- The path of the downloaded file
|
| 162 |
+
"""
|
| 163 |
+
chunk_size = 1024
|
| 164 |
+
total_size = 0
|
| 165 |
+
with requests.get(url, stream=True, timeout=10) as response:
|
| 166 |
+
response.raise_for_status()
|
| 167 |
+
content = response.headers.get("Content-Disposition")
|
| 168 |
+
try: # filename from header
|
| 169 |
+
_, params = cgi.parse_header(content)
|
| 170 |
+
filename = params["filename"]
|
| 171 |
+
except Exception: # filename from url
|
| 172 |
+
filename = os.path.basename(url)
|
| 173 |
+
filename = os.path.splitext(os.path.basename(filename))[0] + ".pdf"
|
| 174 |
+
with open(save_path / filename, "wb") as file:
|
| 175 |
+
for chunk in response.iter_content(chunk_size=chunk_size):
|
| 176 |
+
total_size += len(chunk)
|
| 177 |
+
if size_limit and total_size > size_limit:
|
| 178 |
+
raise gr.Error("Exceeds file size limit")
|
| 179 |
+
file.write(chunk)
|
| 180 |
+
return save_path / filename
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def stop_translate_file(state: dict) -> None:
|
| 184 |
+
"""
|
| 185 |
+
This function stops the translation process.
|
| 186 |
+
|
| 187 |
+
Inputs:
|
| 188 |
+
- state: The state of the translation process
|
| 189 |
+
|
| 190 |
+
Returns:- None
|
| 191 |
+
"""
|
| 192 |
+
session_id = state["session_id"]
|
| 193 |
+
if session_id is None:
|
| 194 |
+
return
|
| 195 |
+
if session_id in cancellation_event_map:
|
| 196 |
+
logger.info(f"Stopping translation for session {session_id}")
|
| 197 |
+
cancellation_event_map[session_id].set()
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def translate_file(
|
| 201 |
+
file_type,
|
| 202 |
+
file_input,
|
| 203 |
+
link_input,
|
| 204 |
+
service,
|
| 205 |
+
lang_from,
|
| 206 |
+
lang_to,
|
| 207 |
+
page_range,
|
| 208 |
+
page_input,
|
| 209 |
+
prompt,
|
| 210 |
+
threads,
|
| 211 |
+
skip_subset_fonts,
|
| 212 |
+
ignore_cache,
|
| 213 |
+
vfont,
|
| 214 |
+
use_babeldoc,
|
| 215 |
+
recaptcha_response,
|
| 216 |
+
state,
|
| 217 |
+
progress=gr.Progress(),
|
| 218 |
+
*envs,
|
| 219 |
+
):
|
| 220 |
+
"""
|
| 221 |
+
This function translates a PDF file from one language to another.
|
| 222 |
+
|
| 223 |
+
Inputs:
|
| 224 |
+
- file_type: The type of file to translate
|
| 225 |
+
- file_input: The file to translate
|
| 226 |
+
- link_input: The link to the file to translate
|
| 227 |
+
- service: The translation service to use
|
| 228 |
+
- lang_from: The language to translate from
|
| 229 |
+
- lang_to: The language to translate to
|
| 230 |
+
- page_range: The range of pages to translate
|
| 231 |
+
- page_input: The input for the page range
|
| 232 |
+
- prompt: The custom prompt for the llm
|
| 233 |
+
- threads: The number of threads to use
|
| 234 |
+
- recaptcha_response: The reCAPTCHA response
|
| 235 |
+
- state: The state of the translation process
|
| 236 |
+
- progress: The progress bar
|
| 237 |
+
- envs: The environment variables
|
| 238 |
+
|
| 239 |
+
Returns:
|
| 240 |
+
- The translated file
|
| 241 |
+
- The translated file
|
| 242 |
+
- The translated file
|
| 243 |
+
- The progress bar
|
| 244 |
+
- The progress bar
|
| 245 |
+
- The progress bar
|
| 246 |
+
"""
|
| 247 |
+
session_id = uuid.uuid4()
|
| 248 |
+
state["session_id"] = session_id
|
| 249 |
+
cancellation_event_map[session_id] = asyncio.Event()
|
| 250 |
+
# Translate PDF content using selected service.
|
| 251 |
+
if flag_demo and not verify_recaptcha(recaptcha_response):
|
| 252 |
+
raise gr.Error("reCAPTCHA fail")
|
| 253 |
+
|
| 254 |
+
progress(0, desc="Starting translation...")
|
| 255 |
+
|
| 256 |
+
output = Path("pdf2zh_files")
|
| 257 |
+
output.mkdir(parents=True, exist_ok=True)
|
| 258 |
+
|
| 259 |
+
if file_type == "File":
|
| 260 |
+
if not file_input:
|
| 261 |
+
raise gr.Error("No input")
|
| 262 |
+
file_path = shutil.copy(file_input, output)
|
| 263 |
+
else:
|
| 264 |
+
if not link_input:
|
| 265 |
+
raise gr.Error("No input")
|
| 266 |
+
file_path = download_with_limit(
|
| 267 |
+
link_input,
|
| 268 |
+
output,
|
| 269 |
+
5 * 1024 * 1024 if flag_demo else None,
|
| 270 |
+
)
|
| 271 |
+
|
| 272 |
+
filename = os.path.splitext(os.path.basename(file_path))[0]
|
| 273 |
+
file_raw = output / f"{filename}.pdf"
|
| 274 |
+
file_mono = output / f"{filename}-mono.pdf"
|
| 275 |
+
file_dual = output / f"{filename}-dual.pdf"
|
| 276 |
+
|
| 277 |
+
translator = service_map[service]
|
| 278 |
+
if page_range != "Others":
|
| 279 |
+
selected_page = page_map[page_range]
|
| 280 |
+
else:
|
| 281 |
+
selected_page = []
|
| 282 |
+
for p in page_input.split(","):
|
| 283 |
+
if "-" in p:
|
| 284 |
+
start, end = p.split("-")
|
| 285 |
+
selected_page.extend(range(int(start) - 1, int(end)))
|
| 286 |
+
else:
|
| 287 |
+
selected_page.append(int(p) - 1)
|
| 288 |
+
lang_from = lang_map[lang_from]
|
| 289 |
+
lang_to = lang_map[lang_to]
|
| 290 |
+
|
| 291 |
+
_envs = {}
|
| 292 |
+
for i, env in enumerate(translator.envs.items()):
|
| 293 |
+
_envs[env[0]] = envs[i]
|
| 294 |
+
for k, v in _envs.items():
|
| 295 |
+
if str(k).upper().endswith("API_KEY") and str(v) == "***":
|
| 296 |
+
# Load Real API_KEYs from local configure file
|
| 297 |
+
real_keys: str = ConfigManager.get_env_by_translatername(
|
| 298 |
+
translator, k, None
|
| 299 |
+
)
|
| 300 |
+
_envs[k] = real_keys
|
| 301 |
+
|
| 302 |
+
print(f"Files before translation: {os.listdir(output)}")
|
| 303 |
+
|
| 304 |
+
def progress_bar(t: tqdm.tqdm):
|
| 305 |
+
desc = getattr(t, "desc", "Translating...")
|
| 306 |
+
if desc == "":
|
| 307 |
+
desc = "Translating..."
|
| 308 |
+
progress(t.n / t.total, desc=desc)
|
| 309 |
+
|
| 310 |
+
try:
|
| 311 |
+
threads = int(threads)
|
| 312 |
+
except ValueError:
|
| 313 |
+
threads = 1
|
| 314 |
+
|
| 315 |
+
param = {
|
| 316 |
+
"files": [str(file_raw)],
|
| 317 |
+
"pages": selected_page,
|
| 318 |
+
"lang_in": lang_from,
|
| 319 |
+
"lang_out": lang_to,
|
| 320 |
+
"service": f"{translator.name}",
|
| 321 |
+
"output": output,
|
| 322 |
+
"thread": int(threads),
|
| 323 |
+
"callback": progress_bar,
|
| 324 |
+
"cancellation_event": cancellation_event_map[session_id],
|
| 325 |
+
"envs": _envs,
|
| 326 |
+
"prompt": Template(prompt) if prompt else None,
|
| 327 |
+
"skip_subset_fonts": skip_subset_fonts,
|
| 328 |
+
"ignore_cache": ignore_cache,
|
| 329 |
+
"vfont": vfont, # 添加自定义公式字体正则表达式
|
| 330 |
+
"model": ModelInstance.value,
|
| 331 |
+
}
|
| 332 |
+
|
| 333 |
+
try:
|
| 334 |
+
if use_babeldoc:
|
| 335 |
+
return babeldoc_translate_file(**param)
|
| 336 |
+
translate(**param)
|
| 337 |
+
except CancelledError:
|
| 338 |
+
del cancellation_event_map[session_id]
|
| 339 |
+
raise gr.Error("Translation cancelled")
|
| 340 |
+
print(f"Files after translation: {os.listdir(output)}")
|
| 341 |
+
|
| 342 |
+
if not file_mono.exists() or not file_dual.exists():
|
| 343 |
+
raise gr.Error("No output")
|
| 344 |
+
|
| 345 |
+
progress(1.0, desc="Translation complete!")
|
| 346 |
+
|
| 347 |
+
return (
|
| 348 |
+
str(file_mono),
|
| 349 |
+
str(file_mono),
|
| 350 |
+
str(file_dual),
|
| 351 |
+
gr.update(visible=True),
|
| 352 |
+
gr.update(visible=True),
|
| 353 |
+
gr.update(visible=True),
|
| 354 |
+
)
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
def babeldoc_translate_file(**kwargs):
|
| 358 |
+
from babeldoc.high_level import init as babeldoc_init
|
| 359 |
+
|
| 360 |
+
babeldoc_init()
|
| 361 |
+
from babeldoc.high_level import async_translate as babeldoc_translate
|
| 362 |
+
from babeldoc.translation_config import TranslationConfig as YadtConfig
|
| 363 |
+
|
| 364 |
+
for translator in [
|
| 365 |
+
GoogleTranslator,
|
| 366 |
+
BingTranslator,
|
| 367 |
+
DeepLTranslator,
|
| 368 |
+
DeepLXTranslator,
|
| 369 |
+
OllamaTranslator,
|
| 370 |
+
XinferenceTranslator,
|
| 371 |
+
AzureOpenAITranslator,
|
| 372 |
+
OpenAITranslator,
|
| 373 |
+
ZhipuTranslator,
|
| 374 |
+
ModelScopeTranslator,
|
| 375 |
+
SiliconTranslator,
|
| 376 |
+
GeminiTranslator,
|
| 377 |
+
AzureTranslator,
|
| 378 |
+
TencentTranslator,
|
| 379 |
+
DifyTranslator,
|
| 380 |
+
AnythingLLMTranslator,
|
| 381 |
+
ArgosTranslator,
|
| 382 |
+
GrokTranslator,
|
| 383 |
+
GroqTranslator,
|
| 384 |
+
DeepseekTranslator,
|
| 385 |
+
OpenAIlikedTranslator,
|
| 386 |
+
QwenMtTranslator,
|
| 387 |
+
X302AITranslator,
|
| 388 |
+
]:
|
| 389 |
+
if kwargs["service"] == translator.name:
|
| 390 |
+
translator = translator(
|
| 391 |
+
kwargs["lang_in"],
|
| 392 |
+
kwargs["lang_out"],
|
| 393 |
+
"",
|
| 394 |
+
envs=kwargs["envs"],
|
| 395 |
+
prompt=kwargs["prompt"],
|
| 396 |
+
ignore_cache=kwargs["ignore_cache"],
|
| 397 |
+
)
|
| 398 |
+
break
|
| 399 |
+
else:
|
| 400 |
+
raise ValueError("Unsupported translation service")
|
| 401 |
+
import asyncio
|
| 402 |
+
|
| 403 |
+
from babeldoc.main import create_progress_handler
|
| 404 |
+
|
| 405 |
+
for file in kwargs["files"]:
|
| 406 |
+
file = file.strip("\"'")
|
| 407 |
+
yadt_config = YadtConfig(
|
| 408 |
+
input_file=file,
|
| 409 |
+
font=None,
|
| 410 |
+
pages=",".join((str(x) for x in getattr(kwargs, "raw_pages", []))),
|
| 411 |
+
output_dir=kwargs["output"],
|
| 412 |
+
doc_layout_model=BABELDOC_MODEL,
|
| 413 |
+
translator=translator,
|
| 414 |
+
debug=False,
|
| 415 |
+
lang_in=kwargs["lang_in"],
|
| 416 |
+
lang_out=kwargs["lang_out"],
|
| 417 |
+
no_dual=False,
|
| 418 |
+
no_mono=False,
|
| 419 |
+
qps=kwargs["thread"],
|
| 420 |
+
use_rich_pbar=False,
|
| 421 |
+
disable_rich_text_translate=not isinstance(translator, OpenAITranslator),
|
| 422 |
+
skip_clean=kwargs["skip_subset_fonts"],
|
| 423 |
+
report_interval=0.5,
|
| 424 |
+
)
|
| 425 |
+
|
| 426 |
+
async def yadt_translate_coro(yadt_config):
|
| 427 |
+
progress_context, progress_handler = create_progress_handler(yadt_config)
|
| 428 |
+
|
| 429 |
+
# 开始翻译
|
| 430 |
+
with progress_context:
|
| 431 |
+
async for event in babeldoc_translate(yadt_config):
|
| 432 |
+
progress_handler(event)
|
| 433 |
+
if yadt_config.debug:
|
| 434 |
+
logger.debug(event)
|
| 435 |
+
kwargs["callback"](progress_context)
|
| 436 |
+
if kwargs["cancellation_event"].is_set():
|
| 437 |
+
yadt_config.cancel_translation()
|
| 438 |
+
raise CancelledError
|
| 439 |
+
if event["type"] == "finish":
|
| 440 |
+
result = event["translate_result"]
|
| 441 |
+
logger.info("Translation Result:")
|
| 442 |
+
logger.info(f" Original PDF: {result.original_pdf_path}")
|
| 443 |
+
logger.info(f" Time Cost: {result.total_seconds:.2f}s")
|
| 444 |
+
logger.info(f" Mono PDF: {result.mono_pdf_path or 'None'}")
|
| 445 |
+
logger.info(f" Dual PDF: {result.dual_pdf_path or 'None'}")
|
| 446 |
+
file_mono = result.mono_pdf_path
|
| 447 |
+
file_dual = result.dual_pdf_path
|
| 448 |
+
break
|
| 449 |
+
import gc
|
| 450 |
+
|
| 451 |
+
gc.collect()
|
| 452 |
+
return (
|
| 453 |
+
str(file_mono),
|
| 454 |
+
str(file_mono),
|
| 455 |
+
str(file_dual),
|
| 456 |
+
gr.update(visible=True),
|
| 457 |
+
gr.update(visible=True),
|
| 458 |
+
gr.update(visible=True),
|
| 459 |
+
)
|
| 460 |
+
|
| 461 |
+
return asyncio.run(yadt_translate_coro(yadt_config))
|
| 462 |
+
|
| 463 |
+
|
| 464 |
+
# Global setup
|
| 465 |
+
custom_blue = gr.themes.Color(
|
| 466 |
+
c50="#E8F3FF",
|
| 467 |
+
c100="#BEDAFF",
|
| 468 |
+
c200="#94BFFF",
|
| 469 |
+
c300="#6AA1FF",
|
| 470 |
+
c400="#4080FF",
|
| 471 |
+
c500="#165DFF", # Primary color
|
| 472 |
+
c600="#0E42D2",
|
| 473 |
+
c700="#0A2BA6",
|
| 474 |
+
c800="#061D79",
|
| 475 |
+
c900="#03114D",
|
| 476 |
+
c950="#020B33",
|
| 477 |
+
)
|
| 478 |
+
|
| 479 |
+
custom_css = """
|
| 480 |
+
.secondary-text {color: #999 !important;}
|
| 481 |
+
footer {visibility: hidden}
|
| 482 |
+
.env-warning {color: #dd5500 !important;}
|
| 483 |
+
.env-success {color: #559900 !important;}
|
| 484 |
+
|
| 485 |
+
/* Add dashed border to input-file class */
|
| 486 |
+
.input-file {
|
| 487 |
+
border: 1.2px dashed #165DFF !important;
|
| 488 |
+
border-radius: 6px !important;
|
| 489 |
+
}
|
| 490 |
+
|
| 491 |
+
.progress-bar-wrap {
|
| 492 |
+
border-radius: 8px !important;
|
| 493 |
+
}
|
| 494 |
+
|
| 495 |
+
.progress-bar {
|
| 496 |
+
border-radius: 8px !important;
|
| 497 |
+
}
|
| 498 |
+
|
| 499 |
+
.pdf-canvas canvas {
|
| 500 |
+
width: 100%;
|
| 501 |
+
}
|
| 502 |
+
"""
|
| 503 |
+
|
| 504 |
+
demo_recaptcha = """
|
| 505 |
+
<script src="https://www.google.com/recaptcha/api.js?render=explicit" async defer></script>
|
| 506 |
+
<script type="text/javascript">
|
| 507 |
+
var onVerify = function(token) {
|
| 508 |
+
el=document.getElementById('verify').getElementsByTagName('textarea')[0];
|
| 509 |
+
el.value=token;
|
| 510 |
+
el.dispatchEvent(new Event('input'));
|
| 511 |
+
};
|
| 512 |
+
</script>
|
| 513 |
+
"""
|
| 514 |
+
|
| 515 |
+
tech_details_string = f"""
|
| 516 |
+
<summary>Technical details</summary>
|
| 517 |
+
- GitHub: <a href="https://github.com/Byaidu/PDFMathTranslate">Byaidu/PDFMathTranslate</a><br>
|
| 518 |
+
- BabelDOC: <a href="https://github.com/funstory-ai/BabelDOC">funstory-ai/BabelDOC</a><br>
|
| 519 |
+
- GUI by: <a href="https://github.com/reycn">Rongxin</a><br>
|
| 520 |
+
- pdf2zh Version: {__version__} <br>
|
| 521 |
+
- BabelDOC Version: {babeldoc_version}
|
| 522 |
+
"""
|
| 523 |
+
cancellation_event_map = {}
|
| 524 |
+
|
| 525 |
+
|
| 526 |
+
# The following code creates the GUI
|
| 527 |
+
with gr.Blocks(
|
| 528 |
+
title="PDFMathTranslate - PDF Translation with preserved formats",
|
| 529 |
+
theme=gr.themes.Default(
|
| 530 |
+
primary_hue=custom_blue, spacing_size="md", radius_size="lg"
|
| 531 |
+
),
|
| 532 |
+
css=custom_css,
|
| 533 |
+
head=demo_recaptcha if flag_demo else "",
|
| 534 |
+
) as demo:
|
| 535 |
+
gr.Markdown(
|
| 536 |
+
"# [PDFMathTranslate @ GitHub](https://github.com/Byaidu/PDFMathTranslate)"
|
| 537 |
+
)
|
| 538 |
+
|
| 539 |
+
with gr.Row():
|
| 540 |
+
with gr.Column(scale=1):
|
| 541 |
+
gr.Markdown("## File | < 5 MB" if flag_demo else "## File")
|
| 542 |
+
file_type = gr.Radio(
|
| 543 |
+
choices=["File", "Link"],
|
| 544 |
+
label="Type",
|
| 545 |
+
value="File",
|
| 546 |
+
)
|
| 547 |
+
file_input = gr.File(
|
| 548 |
+
label="File",
|
| 549 |
+
file_count="single",
|
| 550 |
+
file_types=[".pdf"],
|
| 551 |
+
type="filepath",
|
| 552 |
+
elem_classes=["input-file"],
|
| 553 |
+
)
|
| 554 |
+
link_input = gr.Textbox(
|
| 555 |
+
label="Link",
|
| 556 |
+
visible=False,
|
| 557 |
+
interactive=True,
|
| 558 |
+
)
|
| 559 |
+
gr.Markdown("## Option")
|
| 560 |
+
service = gr.Dropdown(
|
| 561 |
+
label="Service",
|
| 562 |
+
choices=enabled_services,
|
| 563 |
+
value=enabled_services[0],
|
| 564 |
+
)
|
| 565 |
+
envs = []
|
| 566 |
+
for i in range(3):
|
| 567 |
+
envs.append(
|
| 568 |
+
gr.Textbox(
|
| 569 |
+
visible=False,
|
| 570 |
+
interactive=True,
|
| 571 |
+
)
|
| 572 |
+
)
|
| 573 |
+
with gr.Row():
|
| 574 |
+
lang_from = gr.Dropdown(
|
| 575 |
+
label="Translate from",
|
| 576 |
+
choices=lang_map.keys(),
|
| 577 |
+
value=ConfigManager.get("PDF2ZH_LANG_FROM", "English"),
|
| 578 |
+
)
|
| 579 |
+
lang_to = gr.Dropdown(
|
| 580 |
+
label="Translate to",
|
| 581 |
+
choices=lang_map.keys(),
|
| 582 |
+
value=ConfigManager.get("PDF2ZH_LANG_TO", "Simplified Chinese"),
|
| 583 |
+
)
|
| 584 |
+
page_range = gr.Radio(
|
| 585 |
+
choices=page_map.keys(),
|
| 586 |
+
label="Pages",
|
| 587 |
+
value=list(page_map.keys())[0],
|
| 588 |
+
)
|
| 589 |
+
|
| 590 |
+
page_input = gr.Textbox(
|
| 591 |
+
label="Page range",
|
| 592 |
+
visible=False,
|
| 593 |
+
interactive=True,
|
| 594 |
+
)
|
| 595 |
+
|
| 596 |
+
with gr.Accordion("Open for More Experimental Options!", open=False):
|
| 597 |
+
gr.Markdown("#### Experimental")
|
| 598 |
+
threads = gr.Textbox(
|
| 599 |
+
label="number of threads", interactive=True, value="4"
|
| 600 |
+
)
|
| 601 |
+
skip_subset_fonts = gr.Checkbox(
|
| 602 |
+
label="Skip font subsetting", interactive=True, value=False
|
| 603 |
+
)
|
| 604 |
+
ignore_cache = gr.Checkbox(
|
| 605 |
+
label="Ignore cache", interactive=True, value=False
|
| 606 |
+
)
|
| 607 |
+
vfont = gr.Textbox(
|
| 608 |
+
label="Custom formula font regex (vfont)",
|
| 609 |
+
interactive=True,
|
| 610 |
+
value=ConfigManager.get("PDF2ZH_VFONT", ""),
|
| 611 |
+
)
|
| 612 |
+
prompt = gr.Textbox(
|
| 613 |
+
label="Custom Prompt for llm", interactive=True, visible=False
|
| 614 |
+
)
|
| 615 |
+
use_babeldoc = gr.Checkbox(
|
| 616 |
+
label="Use BabelDOC", interactive=True, value=False
|
| 617 |
+
)
|
| 618 |
+
envs.append(prompt)
|
| 619 |
+
|
| 620 |
+
def on_select_service(service, evt: gr.EventData):
|
| 621 |
+
translator = service_map[service]
|
| 622 |
+
_envs = []
|
| 623 |
+
for i in range(4):
|
| 624 |
+
_envs.append(gr.update(visible=False, value=""))
|
| 625 |
+
for i, env in enumerate(translator.envs.items()):
|
| 626 |
+
label = env[0]
|
| 627 |
+
value = ConfigManager.get_env_by_translatername(
|
| 628 |
+
translator, env[0], env[1]
|
| 629 |
+
)
|
| 630 |
+
visible = True
|
| 631 |
+
if hidden_gradio_details:
|
| 632 |
+
if (
|
| 633 |
+
"MODEL" not in str(label).upper()
|
| 634 |
+
and value
|
| 635 |
+
and hidden_gradio_details
|
| 636 |
+
):
|
| 637 |
+
visible = False
|
| 638 |
+
# Hidden Keys From Gradio
|
| 639 |
+
if "API_KEY" in label.upper():
|
| 640 |
+
value = "***" # We use "***" Present Real API_KEY
|
| 641 |
+
_envs[i] = gr.update(
|
| 642 |
+
visible=visible,
|
| 643 |
+
label=label,
|
| 644 |
+
value=value,
|
| 645 |
+
)
|
| 646 |
+
_envs[-1] = gr.update(visible=translator.CustomPrompt)
|
| 647 |
+
return _envs
|
| 648 |
+
|
| 649 |
+
def on_select_filetype(file_type):
|
| 650 |
+
return (
|
| 651 |
+
gr.update(visible=file_type == "File"),
|
| 652 |
+
gr.update(visible=file_type == "Link"),
|
| 653 |
+
)
|
| 654 |
+
|
| 655 |
+
def on_select_page(choice):
|
| 656 |
+
if choice == "Others":
|
| 657 |
+
return gr.update(visible=True)
|
| 658 |
+
else:
|
| 659 |
+
return gr.update(visible=False)
|
| 660 |
+
|
| 661 |
+
def on_vfont_change(value):
|
| 662 |
+
ConfigManager.set("PDF2ZH_VFONT", value)
|
| 663 |
+
return value
|
| 664 |
+
|
| 665 |
+
output_title = gr.Markdown("## Translated", visible=False)
|
| 666 |
+
output_file_mono = gr.File(
|
| 667 |
+
label="Download Translation (Mono)", visible=False
|
| 668 |
+
)
|
| 669 |
+
output_file_dual = gr.File(
|
| 670 |
+
label="Download Translation (Dual)", visible=False
|
| 671 |
+
)
|
| 672 |
+
recaptcha_response = gr.Textbox(
|
| 673 |
+
label="reCAPTCHA Response", elem_id="verify", visible=False
|
| 674 |
+
)
|
| 675 |
+
recaptcha_box = gr.HTML('<div id="recaptcha-box"></div>')
|
| 676 |
+
translate_btn = gr.Button("Translate", variant="primary")
|
| 677 |
+
cancellation_btn = gr.Button("Cancel", variant="secondary")
|
| 678 |
+
tech_details_tog = gr.Markdown(
|
| 679 |
+
tech_details_string,
|
| 680 |
+
elem_classes=["secondary-text"],
|
| 681 |
+
)
|
| 682 |
+
page_range.select(on_select_page, page_range, page_input)
|
| 683 |
+
service.select(
|
| 684 |
+
on_select_service,
|
| 685 |
+
service,
|
| 686 |
+
envs,
|
| 687 |
+
)
|
| 688 |
+
vfont.change(on_vfont_change, inputs=vfont, outputs=None)
|
| 689 |
+
file_type.select(
|
| 690 |
+
on_select_filetype,
|
| 691 |
+
file_type,
|
| 692 |
+
[file_input, link_input],
|
| 693 |
+
js=(
|
| 694 |
+
f"""
|
| 695 |
+
(a,b)=>{{
|
| 696 |
+
try{{
|
| 697 |
+
grecaptcha.render('recaptcha-box',{{
|
| 698 |
+
'sitekey':'{client_key}',
|
| 699 |
+
'callback':'onVerify'
|
| 700 |
+
}});
|
| 701 |
+
}}catch(error){{}}
|
| 702 |
+
return [a];
|
| 703 |
+
}}
|
| 704 |
+
"""
|
| 705 |
+
if flag_demo
|
| 706 |
+
else ""
|
| 707 |
+
),
|
| 708 |
+
)
|
| 709 |
+
|
| 710 |
+
with gr.Column(scale=2):
|
| 711 |
+
gr.Markdown("## Preview")
|
| 712 |
+
preview = PDF(label="Document Preview", visible=True, height=2000)
|
| 713 |
+
|
| 714 |
+
# Event handlers
|
| 715 |
+
file_input.upload(
|
| 716 |
+
lambda x: x,
|
| 717 |
+
inputs=file_input,
|
| 718 |
+
outputs=preview,
|
| 719 |
+
js=(
|
| 720 |
+
f"""
|
| 721 |
+
(a,b)=>{{
|
| 722 |
+
try{{
|
| 723 |
+
grecaptcha.render('recaptcha-box',{{
|
| 724 |
+
'sitekey':'{client_key}',
|
| 725 |
+
'callback':'onVerify'
|
| 726 |
+
}});
|
| 727 |
+
}}catch(error){{}}
|
| 728 |
+
return [a];
|
| 729 |
+
}}
|
| 730 |
+
"""
|
| 731 |
+
if flag_demo
|
| 732 |
+
else ""
|
| 733 |
+
),
|
| 734 |
+
)
|
| 735 |
+
|
| 736 |
+
state = gr.State({"session_id": None})
|
| 737 |
+
|
| 738 |
+
translate_btn.click(
|
| 739 |
+
translate_file,
|
| 740 |
+
inputs=[
|
| 741 |
+
file_type,
|
| 742 |
+
file_input,
|
| 743 |
+
link_input,
|
| 744 |
+
service,
|
| 745 |
+
lang_from,
|
| 746 |
+
lang_to,
|
| 747 |
+
page_range,
|
| 748 |
+
page_input,
|
| 749 |
+
prompt,
|
| 750 |
+
threads,
|
| 751 |
+
skip_subset_fonts,
|
| 752 |
+
ignore_cache,
|
| 753 |
+
vfont,
|
| 754 |
+
use_babeldoc,
|
| 755 |
+
recaptcha_response,
|
| 756 |
+
state,
|
| 757 |
+
*envs,
|
| 758 |
+
],
|
| 759 |
+
outputs=[
|
| 760 |
+
output_file_mono,
|
| 761 |
+
preview,
|
| 762 |
+
output_file_dual,
|
| 763 |
+
output_file_mono,
|
| 764 |
+
output_file_dual,
|
| 765 |
+
output_title,
|
| 766 |
+
],
|
| 767 |
+
).then(lambda: None, js="()=>{grecaptcha.reset()}" if flag_demo else "")
|
| 768 |
+
|
| 769 |
+
cancellation_btn.click(
|
| 770 |
+
stop_translate_file,
|
| 771 |
+
inputs=[state],
|
| 772 |
+
)
|
| 773 |
+
|
| 774 |
+
|
| 775 |
+
def parse_user_passwd(file_path: str) -> tuple:
|
| 776 |
+
"""
|
| 777 |
+
Parse the user name and password from the file.
|
| 778 |
+
|
| 779 |
+
Inputs:
|
| 780 |
+
- file_path: The file path to read.
|
| 781 |
+
Outputs:
|
| 782 |
+
- tuple_list: The list of tuples of user name and password.
|
| 783 |
+
- content: The content of the file
|
| 784 |
+
"""
|
| 785 |
+
tuple_list = []
|
| 786 |
+
content = ""
|
| 787 |
+
if not file_path:
|
| 788 |
+
return tuple_list, content
|
| 789 |
+
if len(file_path) == 2:
|
| 790 |
+
try:
|
| 791 |
+
with open(file_path[1], "r", encoding="utf-8") as file:
|
| 792 |
+
content = file.read()
|
| 793 |
+
except FileNotFoundError:
|
| 794 |
+
print(f"Error: File '{file_path[1]}' not found.")
|
| 795 |
+
try:
|
| 796 |
+
with open(file_path[0], "r", encoding="utf-8") as file:
|
| 797 |
+
tuple_list = [
|
| 798 |
+
tuple(line.strip().split(",")) for line in file if line.strip()
|
| 799 |
+
]
|
| 800 |
+
except FileNotFoundError:
|
| 801 |
+
print(f"Error: File '{file_path[0]}' not found.")
|
| 802 |
+
return tuple_list, content
|
| 803 |
+
|
| 804 |
+
|
| 805 |
+
def setup_gui(
|
| 806 |
+
share: bool = False, auth_file: list = ["", ""], server_port=7860
|
| 807 |
+
) -> None:
|
| 808 |
+
"""
|
| 809 |
+
Setup the GUI with the given parameters.
|
| 810 |
+
|
| 811 |
+
Inputs:
|
| 812 |
+
- share: Whether to share the GUI.
|
| 813 |
+
- auth_file: The file path to read the user name and password.
|
| 814 |
+
|
| 815 |
+
Outputs:
|
| 816 |
+
- None
|
| 817 |
+
"""
|
| 818 |
+
user_list, html = parse_user_passwd(auth_file)
|
| 819 |
+
if flag_demo:
|
| 820 |
+
demo.launch(server_name="0.0.0.0", max_file_size="5mb", inbrowser=True)
|
| 821 |
+
else:
|
| 822 |
+
if len(user_list) == 0:
|
| 823 |
+
try:
|
| 824 |
+
demo.launch(
|
| 825 |
+
server_name="0.0.0.0",
|
| 826 |
+
debug=True,
|
| 827 |
+
inbrowser=True,
|
| 828 |
+
share=share,
|
| 829 |
+
server_port=server_port,
|
| 830 |
+
)
|
| 831 |
+
except Exception:
|
| 832 |
+
print(
|
| 833 |
+
"Error launching GUI using 0.0.0.0.\nThis may be caused by global mode of proxy software."
|
| 834 |
+
)
|
| 835 |
+
try:
|
| 836 |
+
demo.launch(
|
| 837 |
+
server_name="127.0.0.1",
|
| 838 |
+
debug=True,
|
| 839 |
+
inbrowser=True,
|
| 840 |
+
share=share,
|
| 841 |
+
server_port=server_port,
|
| 842 |
+
)
|
| 843 |
+
except Exception:
|
| 844 |
+
print(
|
| 845 |
+
"Error launching GUI using 127.0.0.1.\nThis may be caused by global mode of proxy software."
|
| 846 |
+
)
|
| 847 |
+
demo.launch(
|
| 848 |
+
debug=True, inbrowser=True, share=True, server_port=server_port
|
| 849 |
+
)
|
| 850 |
+
else:
|
| 851 |
+
try:
|
| 852 |
+
demo.launch(
|
| 853 |
+
server_name="0.0.0.0",
|
| 854 |
+
debug=True,
|
| 855 |
+
inbrowser=True,
|
| 856 |
+
share=share,
|
| 857 |
+
auth=user_list,
|
| 858 |
+
auth_message=html,
|
| 859 |
+
server_port=server_port,
|
| 860 |
+
)
|
| 861 |
+
except Exception:
|
| 862 |
+
print(
|
| 863 |
+
"Error launching GUI using 0.0.0.0.\nThis may be caused by global mode of proxy software."
|
| 864 |
+
)
|
| 865 |
+
try:
|
| 866 |
+
demo.launch(
|
| 867 |
+
server_name="127.0.0.1",
|
| 868 |
+
debug=True,
|
| 869 |
+
inbrowser=True,
|
| 870 |
+
share=share,
|
| 871 |
+
auth=user_list,
|
| 872 |
+
auth_message=html,
|
| 873 |
+
server_port=server_port,
|
| 874 |
+
)
|
| 875 |
+
except Exception:
|
| 876 |
+
print(
|
| 877 |
+
"Error launching GUI using 127.0.0.1.\nThis may be caused by global mode of proxy software."
|
| 878 |
+
)
|
| 879 |
+
demo.launch(
|
| 880 |
+
debug=True,
|
| 881 |
+
inbrowser=True,
|
| 882 |
+
share=True,
|
| 883 |
+
auth=user_list,
|
| 884 |
+
auth_message=html,
|
| 885 |
+
server_port=server_port,
|
| 886 |
+
)
|
| 887 |
+
|
| 888 |
+
|
| 889 |
+
# For auto-reloading while developing
|
| 890 |
+
if __name__ == "__main__":
|
| 891 |
+
logging.basicConfig(level=logging.DEBUG)
|
| 892 |
+
setup_gui()
|
pdf2zh/high_level.py
ADDED
|
@@ -0,0 +1,449 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
import re
|
| 8 |
+
import sys
|
| 9 |
+
import tempfile
|
| 10 |
+
from asyncio import CancelledError
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
from string import Template
|
| 13 |
+
from typing import Any, BinaryIO, Dict, List, Optional
|
| 14 |
+
|
| 15 |
+
import numpy as np
|
| 16 |
+
import requests
|
| 17 |
+
import tqdm
|
| 18 |
+
from babeldoc.assets.assets import get_font_and_metadata
|
| 19 |
+
from pdfminer.pdfdocument import PDFDocument
|
| 20 |
+
from pdfminer.pdfexceptions import PDFValueError
|
| 21 |
+
from pdfminer.pdfinterp import PDFResourceManager
|
| 22 |
+
from pdfminer.pdfpage import PDFPage
|
| 23 |
+
from pdfminer.pdfparser import PDFParser
|
| 24 |
+
from pymupdf import Document, Font
|
| 25 |
+
|
| 26 |
+
from pdf2zh.config import ConfigManager
|
| 27 |
+
from pdf2zh.converter import TranslateConverter
|
| 28 |
+
from pdf2zh.doclayout import OnnxModel
|
| 29 |
+
from pdf2zh.parser.detector import PDFTypeDetector
|
| 30 |
+
from pdf2zh.parser.main import StageAParser
|
| 31 |
+
from pdf2zh.pdfinterp import PDFPageInterpreterEx
|
| 32 |
+
|
| 33 |
+
NOTO_NAME = "noto"
|
| 34 |
+
|
| 35 |
+
logger = logging.getLogger(__name__)
|
| 36 |
+
|
| 37 |
+
noto_list = [
|
| 38 |
+
"am", # Amharic
|
| 39 |
+
"ar", # Arabic
|
| 40 |
+
"bn", # Bengali
|
| 41 |
+
"bg", # Bulgarian
|
| 42 |
+
"chr", # Cherokee
|
| 43 |
+
"el", # Greek
|
| 44 |
+
"gu", # Gujarati
|
| 45 |
+
"iw", # Hebrew
|
| 46 |
+
"hi", # Hindi
|
| 47 |
+
"kn", # Kannada
|
| 48 |
+
"ml", # Malayalam
|
| 49 |
+
"mr", # Marathi
|
| 50 |
+
"ru", # Russian
|
| 51 |
+
"sr", # Serbian
|
| 52 |
+
"ta", # Tamil
|
| 53 |
+
"te", # Telugu
|
| 54 |
+
"th", # Thai
|
| 55 |
+
"ur", # Urdu
|
| 56 |
+
"uk", # Ukrainian
|
| 57 |
+
]
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def check_files(files: List[str]) -> List[str]:
|
| 61 |
+
files = [
|
| 62 |
+
f for f in files if not f.startswith("http://")
|
| 63 |
+
] # exclude online files, http
|
| 64 |
+
files = [
|
| 65 |
+
f for f in files if not f.startswith("https://")
|
| 66 |
+
] # exclude online files, https
|
| 67 |
+
missing_files = [file for file in files if not os.path.exists(file)]
|
| 68 |
+
return missing_files
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def translate_patch(
|
| 72 |
+
inf: BinaryIO,
|
| 73 |
+
pages: Optional[list[int]] = None,
|
| 74 |
+
vfont: str = "",
|
| 75 |
+
vchar: str = "",
|
| 76 |
+
thread: int = 0,
|
| 77 |
+
doc_zh: Document = None,
|
| 78 |
+
lang_in: str = "",
|
| 79 |
+
lang_out: str = "",
|
| 80 |
+
service: str = "",
|
| 81 |
+
noto_name: str = "",
|
| 82 |
+
noto: Font = None,
|
| 83 |
+
callback: object = None,
|
| 84 |
+
cancellation_event: asyncio.Event = None,
|
| 85 |
+
model: OnnxModel = None,
|
| 86 |
+
envs: Dict = None,
|
| 87 |
+
prompt: Template = None,
|
| 88 |
+
ignore_cache: bool = False,
|
| 89 |
+
**kwarg: Any,
|
| 90 |
+
) -> None:
|
| 91 |
+
rsrcmgr = PDFResourceManager()
|
| 92 |
+
layout = {}
|
| 93 |
+
device = TranslateConverter(
|
| 94 |
+
rsrcmgr,
|
| 95 |
+
vfont,
|
| 96 |
+
vchar,
|
| 97 |
+
thread,
|
| 98 |
+
layout,
|
| 99 |
+
lang_in,
|
| 100 |
+
lang_out,
|
| 101 |
+
service,
|
| 102 |
+
noto_name,
|
| 103 |
+
noto,
|
| 104 |
+
envs,
|
| 105 |
+
prompt,
|
| 106 |
+
ignore_cache,
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
assert device is not None
|
| 110 |
+
obj_patch = {}
|
| 111 |
+
interpreter = PDFPageInterpreterEx(rsrcmgr, device, obj_patch)
|
| 112 |
+
if pages:
|
| 113 |
+
total_pages = len(pages)
|
| 114 |
+
else:
|
| 115 |
+
total_pages = doc_zh.page_count
|
| 116 |
+
|
| 117 |
+
parser = PDFParser(inf)
|
| 118 |
+
doc = PDFDocument(parser)
|
| 119 |
+
with tqdm.tqdm(total=total_pages) as progress:
|
| 120 |
+
for pageno, page in enumerate(PDFPage.create_pages(doc)):
|
| 121 |
+
if cancellation_event and cancellation_event.is_set():
|
| 122 |
+
raise CancelledError("task cancelled")
|
| 123 |
+
if pages and (pageno not in pages):
|
| 124 |
+
continue
|
| 125 |
+
progress.update()
|
| 126 |
+
if callback:
|
| 127 |
+
callback(progress)
|
| 128 |
+
page.pageno = pageno
|
| 129 |
+
pix = doc_zh[page.pageno].get_pixmap()
|
| 130 |
+
image = np.frombuffer(pix.samples, np.uint8).reshape(
|
| 131 |
+
pix.height, pix.width, 3
|
| 132 |
+
)[:, :, ::-1]
|
| 133 |
+
page_layout = model.predict(image, imgsz=int(pix.height / 32) * 32)[0]
|
| 134 |
+
# kdtree 是不可能 kdtree 的,不如直接渲染成图片,用空间换时间
|
| 135 |
+
box = np.ones((pix.height, pix.width))
|
| 136 |
+
h, w = box.shape
|
| 137 |
+
vcls = ["abandon", "figure", "table", "isolate_formula", "formula_caption"]
|
| 138 |
+
for i, d in enumerate(page_layout.boxes):
|
| 139 |
+
if page_layout.names[int(d.cls)] not in vcls:
|
| 140 |
+
x0, y0, x1, y1 = d.xyxy.squeeze()
|
| 141 |
+
x0, y0, x1, y1 = (
|
| 142 |
+
np.clip(int(x0 - 1), 0, w - 1),
|
| 143 |
+
np.clip(int(h - y1 - 1), 0, h - 1),
|
| 144 |
+
np.clip(int(x1 + 1), 0, w - 1),
|
| 145 |
+
np.clip(int(h - y0 + 1), 0, h - 1),
|
| 146 |
+
)
|
| 147 |
+
box[y0:y1, x0:x1] = i + 2
|
| 148 |
+
for i, d in enumerate(page_layout.boxes):
|
| 149 |
+
if page_layout.names[int(d.cls)] in vcls:
|
| 150 |
+
x0, y0, x1, y1 = d.xyxy.squeeze()
|
| 151 |
+
x0, y0, x1, y1 = (
|
| 152 |
+
np.clip(int(x0 - 1), 0, w - 1),
|
| 153 |
+
np.clip(int(h - y1 - 1), 0, h - 1),
|
| 154 |
+
np.clip(int(x1 + 1), 0, w - 1),
|
| 155 |
+
np.clip(int(h - y0 + 1), 0, h - 1),
|
| 156 |
+
)
|
| 157 |
+
box[y0:y1, x0:x1] = 0
|
| 158 |
+
layout[page.pageno] = box
|
| 159 |
+
# 新建一个 xref 存放新指令流
|
| 160 |
+
page.page_xref = doc_zh.get_new_xref() # hack 插入页面的新 xref
|
| 161 |
+
doc_zh.update_object(page.page_xref, "<<>>")
|
| 162 |
+
doc_zh.update_stream(page.page_xref, b"")
|
| 163 |
+
doc_zh[page.pageno].set_contents(page.page_xref)
|
| 164 |
+
interpreter.process_page(page)
|
| 165 |
+
|
| 166 |
+
device.close()
|
| 167 |
+
return obj_patch
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def translate_stream(
|
| 171 |
+
stream: bytes,
|
| 172 |
+
pages: Optional[list[int]] = None,
|
| 173 |
+
lang_in: str = "",
|
| 174 |
+
lang_out: str = "",
|
| 175 |
+
service: str = "",
|
| 176 |
+
thread: int = 0,
|
| 177 |
+
vfont: str = "",
|
| 178 |
+
vchar: str = "",
|
| 179 |
+
callback: object = None,
|
| 180 |
+
cancellation_event: asyncio.Event = None,
|
| 181 |
+
model: OnnxModel = None,
|
| 182 |
+
envs: Dict = None,
|
| 183 |
+
prompt: Template = None,
|
| 184 |
+
skip_subset_fonts: bool = False,
|
| 185 |
+
ignore_cache: bool = False,
|
| 186 |
+
**kwarg: Any,
|
| 187 |
+
):
|
| 188 |
+
font_list = [("tiro", None)]
|
| 189 |
+
|
| 190 |
+
font_path = download_remote_fonts(lang_out.lower())
|
| 191 |
+
noto_name = NOTO_NAME
|
| 192 |
+
noto = Font(noto_name, font_path)
|
| 193 |
+
font_list.append((noto_name, font_path))
|
| 194 |
+
|
| 195 |
+
doc_en = Document(stream=stream)
|
| 196 |
+
stream = io.BytesIO()
|
| 197 |
+
doc_en.save(stream)
|
| 198 |
+
doc_zh = Document(stream=stream)
|
| 199 |
+
page_count = doc_zh.page_count
|
| 200 |
+
# font_list = [("GoNotoKurrent-Regular.ttf", font_path), ("tiro", None)]
|
| 201 |
+
font_id = {}
|
| 202 |
+
for page in doc_zh:
|
| 203 |
+
for font in font_list:
|
| 204 |
+
font_id[font[0]] = page.insert_font(font[0], font[1])
|
| 205 |
+
xreflen = doc_zh.xref_length()
|
| 206 |
+
for xref in range(1, xreflen):
|
| 207 |
+
for label in ["Resources/", ""]: # 可能是基于 xobj 的 res
|
| 208 |
+
try: # xref 读写可能出错
|
| 209 |
+
font_res = doc_zh.xref_get_key(xref, f"{label}Font")
|
| 210 |
+
target_key_prefix = f"{label}Font/"
|
| 211 |
+
if font_res[0] == "xref":
|
| 212 |
+
resource_xref_id = re.search("(\\d+) 0 R", font_res[1]).group(1)
|
| 213 |
+
xref = int(resource_xref_id)
|
| 214 |
+
font_res = ("dict", doc_zh.xref_object(xref))
|
| 215 |
+
target_key_prefix = ""
|
| 216 |
+
|
| 217 |
+
if font_res[0] == "dict":
|
| 218 |
+
for font in font_list:
|
| 219 |
+
target_key = f"{target_key_prefix}{font[0]}"
|
| 220 |
+
font_exist = doc_zh.xref_get_key(xref, target_key)
|
| 221 |
+
if font_exist[0] == "null":
|
| 222 |
+
doc_zh.xref_set_key(
|
| 223 |
+
xref,
|
| 224 |
+
target_key,
|
| 225 |
+
f"{font_id[font[0]]} 0 R",
|
| 226 |
+
)
|
| 227 |
+
except Exception:
|
| 228 |
+
pass
|
| 229 |
+
|
| 230 |
+
fp = io.BytesIO()
|
| 231 |
+
|
| 232 |
+
doc_zh.save(fp)
|
| 233 |
+
obj_patch: dict = translate_patch(fp, **locals())
|
| 234 |
+
|
| 235 |
+
for obj_id, ops_new in obj_patch.items():
|
| 236 |
+
# ops_old=doc_en.xref_stream(obj_id)
|
| 237 |
+
# print(obj_id)
|
| 238 |
+
# print(ops_old)
|
| 239 |
+
# print(ops_new.encode())
|
| 240 |
+
doc_zh.update_stream(obj_id, ops_new.encode())
|
| 241 |
+
|
| 242 |
+
doc_en.insert_file(doc_zh)
|
| 243 |
+
for id in range(page_count):
|
| 244 |
+
doc_en.move_page(page_count + id, id * 2 + 1)
|
| 245 |
+
if not skip_subset_fonts:
|
| 246 |
+
doc_zh.subset_fonts(fallback=True)
|
| 247 |
+
doc_en.subset_fonts(fallback=True)
|
| 248 |
+
return (
|
| 249 |
+
doc_zh.write(deflate=True, garbage=3, use_objstms=1),
|
| 250 |
+
doc_en.write(deflate=True, garbage=3, use_objstms=1),
|
| 251 |
+
)
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
def convert_to_pdfa(input_path, output_path):
|
| 255 |
+
"""
|
| 256 |
+
Convert PDF to PDF/A format
|
| 257 |
+
|
| 258 |
+
Args:
|
| 259 |
+
input_path: Path to source PDF file
|
| 260 |
+
output_path: Path to save PDF/A file
|
| 261 |
+
"""
|
| 262 |
+
from pikepdf import Dictionary, Name, Pdf
|
| 263 |
+
|
| 264 |
+
# Open the PDF file
|
| 265 |
+
pdf = Pdf.open(input_path)
|
| 266 |
+
|
| 267 |
+
# Add PDF/A conformance metadata
|
| 268 |
+
metadata = {
|
| 269 |
+
"pdfa_part": "2",
|
| 270 |
+
"pdfa_conformance": "B",
|
| 271 |
+
"title": pdf.docinfo.get("/Title", ""),
|
| 272 |
+
"author": pdf.docinfo.get("/Author", ""),
|
| 273 |
+
"creator": "PDF Math Translate",
|
| 274 |
+
}
|
| 275 |
+
|
| 276 |
+
with pdf.open_metadata() as meta:
|
| 277 |
+
meta.load_from_docinfo(pdf.docinfo)
|
| 278 |
+
meta["pdfaid:part"] = metadata["pdfa_part"]
|
| 279 |
+
meta["pdfaid:conformance"] = metadata["pdfa_conformance"]
|
| 280 |
+
|
| 281 |
+
# Create OutputIntent dictionary
|
| 282 |
+
output_intent = Dictionary(
|
| 283 |
+
{
|
| 284 |
+
"/Type": Name("/OutputIntent"),
|
| 285 |
+
"/S": Name("/GTS_PDFA1"),
|
| 286 |
+
"/OutputConditionIdentifier": "sRGB IEC61966-2.1",
|
| 287 |
+
"/RegistryName": "http://www.color.org",
|
| 288 |
+
"/Info": "sRGB IEC61966-2.1",
|
| 289 |
+
}
|
| 290 |
+
)
|
| 291 |
+
|
| 292 |
+
# Add output intent to PDF root
|
| 293 |
+
if "/OutputIntents" not in pdf.Root:
|
| 294 |
+
pdf.Root.OutputIntents = [output_intent]
|
| 295 |
+
else:
|
| 296 |
+
pdf.Root.OutputIntents.append(output_intent)
|
| 297 |
+
|
| 298 |
+
# Save as PDF/A
|
| 299 |
+
pdf.save(output_path, linearize=True)
|
| 300 |
+
pdf.close()
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
def translate(
|
| 304 |
+
files: list[str],
|
| 305 |
+
output: str = "",
|
| 306 |
+
pages: Optional[list[int]] = None,
|
| 307 |
+
lang_in: str = "",
|
| 308 |
+
lang_out: str = "",
|
| 309 |
+
service: str = "",
|
| 310 |
+
thread: int = 0,
|
| 311 |
+
vfont: str = "",
|
| 312 |
+
vchar: str = "",
|
| 313 |
+
callback: object = None,
|
| 314 |
+
compatible: bool = False,
|
| 315 |
+
cancellation_event: asyncio.Event = None,
|
| 316 |
+
model: OnnxModel = None,
|
| 317 |
+
envs: Dict = None,
|
| 318 |
+
prompt: Template = None,
|
| 319 |
+
skip_subset_fonts: bool = False,
|
| 320 |
+
ignore_cache: bool = False,
|
| 321 |
+
**kwarg: Any,
|
| 322 |
+
):
|
| 323 |
+
if not files:
|
| 324 |
+
raise PDFValueError("No files to process.")
|
| 325 |
+
|
| 326 |
+
missing_files = check_files(files)
|
| 327 |
+
|
| 328 |
+
if missing_files:
|
| 329 |
+
print("The following files do not exist:", file=sys.stderr)
|
| 330 |
+
for file in missing_files:
|
| 331 |
+
print(f" {file}", file=sys.stderr)
|
| 332 |
+
raise PDFValueError("Some files do not exist.")
|
| 333 |
+
|
| 334 |
+
result_files = []
|
| 335 |
+
|
| 336 |
+
for file in files:
|
| 337 |
+
if type(file) is str and (
|
| 338 |
+
file.startswith("http://") or file.startswith("https://")
|
| 339 |
+
):
|
| 340 |
+
print("Online files detected, downloading...")
|
| 341 |
+
try:
|
| 342 |
+
r = requests.get(file, allow_redirects=True)
|
| 343 |
+
if r.status_code == 200:
|
| 344 |
+
with tempfile.NamedTemporaryFile(
|
| 345 |
+
suffix=".pdf", delete=False
|
| 346 |
+
) as tmp_file:
|
| 347 |
+
print(f"Writing the file: {file}...")
|
| 348 |
+
tmp_file.write(r.content)
|
| 349 |
+
file = tmp_file.name
|
| 350 |
+
else:
|
| 351 |
+
r.raise_for_status()
|
| 352 |
+
except Exception as e:
|
| 353 |
+
raise PDFValueError(
|
| 354 |
+
f"Errors occur in downloading the PDF file. Please check the link(s).\nError:\n{e}"
|
| 355 |
+
)
|
| 356 |
+
filename = os.path.splitext(os.path.basename(file))[0]
|
| 357 |
+
|
| 358 |
+
# Stage A: Check if PDF is scanned and route to scanned pipeline
|
| 359 |
+
# NOTE: Stages B, C, D will be wired in subsequent sprints
|
| 360 |
+
try:
|
| 361 |
+
detector = PDFTypeDetector()
|
| 362 |
+
pdf_type = detector.detect(file)
|
| 363 |
+
if pdf_type == "scanned":
|
| 364 |
+
logger.info(f"Detected scanned PDF: {file}, using Stage A parser")
|
| 365 |
+
parser = StageAParser(device="auto")
|
| 366 |
+
output_dir = Path(output) if output else Path(file).parent
|
| 367 |
+
cache_path = output_dir / f"{filename}_stage_a.json"
|
| 368 |
+
parsed_doc = parser.parse_pdf(file, pages=pages)
|
| 369 |
+
cache_path.parent.mkdir(parents=True, exist_ok=True)
|
| 370 |
+
parsed_doc.save(cache_path)
|
| 371 |
+
logger.info(f"Stage A complete: {len(parsed_doc.pages)} pages parsed")
|
| 372 |
+
# For now, return the cache path as placeholder
|
| 373 |
+
# Full translation pipeline (Stages B, C, D) will be added later
|
| 374 |
+
result_files.append((str(cache_path), str(cache_path)))
|
| 375 |
+
continue
|
| 376 |
+
except Exception as e:
|
| 377 |
+
logger.warning(
|
| 378 |
+
f"Scanned PDF detection failed, falling back to digital pipeline: {e}"
|
| 379 |
+
)
|
| 380 |
+
|
| 381 |
+
# If the commandline has specified converting to PDF/A format
|
| 382 |
+
# --compatible / -cp
|
| 383 |
+
if compatible:
|
| 384 |
+
with tempfile.NamedTemporaryFile(
|
| 385 |
+
suffix="-pdfa.pdf", delete=False
|
| 386 |
+
) as tmp_pdfa:
|
| 387 |
+
print(f"Converting {file} to PDF/A format...")
|
| 388 |
+
convert_to_pdfa(file, tmp_pdfa.name)
|
| 389 |
+
doc_raw = open(tmp_pdfa.name, "rb")
|
| 390 |
+
os.unlink(tmp_pdfa.name)
|
| 391 |
+
else:
|
| 392 |
+
doc_raw = open(file, "rb")
|
| 393 |
+
s_raw = doc_raw.read()
|
| 394 |
+
doc_raw.close()
|
| 395 |
+
|
| 396 |
+
temp_dir = Path(tempfile.gettempdir())
|
| 397 |
+
file_path = Path(file)
|
| 398 |
+
try:
|
| 399 |
+
if file_path.exists() and file_path.resolve().is_relative_to(
|
| 400 |
+
temp_dir.resolve()
|
| 401 |
+
):
|
| 402 |
+
file_path.unlink(missing_ok=True)
|
| 403 |
+
logger.debug(f"Cleaned temp file: {file_path}")
|
| 404 |
+
except Exception:
|
| 405 |
+
logger.warning(f"Failed to clean temp file {file_path}", exc_info=True)
|
| 406 |
+
|
| 407 |
+
s_mono, s_dual = translate_stream(
|
| 408 |
+
s_raw,
|
| 409 |
+
**locals(),
|
| 410 |
+
)
|
| 411 |
+
file_mono = Path(output) / f"{filename}-mono.pdf"
|
| 412 |
+
file_dual = Path(output) / f"{filename}-dual.pdf"
|
| 413 |
+
doc_mono = open(file_mono, "wb")
|
| 414 |
+
doc_dual = open(file_dual, "wb")
|
| 415 |
+
doc_mono.write(s_mono)
|
| 416 |
+
doc_dual.write(s_dual)
|
| 417 |
+
doc_mono.close()
|
| 418 |
+
doc_dual.close()
|
| 419 |
+
result_files.append((str(file_mono), str(file_dual)))
|
| 420 |
+
|
| 421 |
+
return result_files
|
| 422 |
+
|
| 423 |
+
|
| 424 |
+
def download_remote_fonts(lang: str):
|
| 425 |
+
lang = lang.lower()
|
| 426 |
+
LANG_NAME_MAP = {
|
| 427 |
+
**{la: "GoNotoKurrent-Regular.ttf" for la in noto_list},
|
| 428 |
+
**{
|
| 429 |
+
la: f"SourceHanSerif{region}-Regular.ttf"
|
| 430 |
+
for region, langs in {
|
| 431 |
+
"CN": ["zh-cn", "zh-hans", "zh"],
|
| 432 |
+
"TW": ["zh-tw", "zh-hant"],
|
| 433 |
+
"JP": ["ja"],
|
| 434 |
+
"KR": ["ko"],
|
| 435 |
+
}.items()
|
| 436 |
+
for la in langs
|
| 437 |
+
},
|
| 438 |
+
}
|
| 439 |
+
font_name = LANG_NAME_MAP.get(lang, "GoNotoKurrent-Regular.ttf")
|
| 440 |
+
|
| 441 |
+
# docker
|
| 442 |
+
font_path = ConfigManager.get("NOTO_FONT_PATH", Path("/app", font_name).as_posix())
|
| 443 |
+
if not Path(font_path).exists():
|
| 444 |
+
font_path, _ = get_font_and_metadata(font_name)
|
| 445 |
+
font_path = font_path.as_posix()
|
| 446 |
+
|
| 447 |
+
logger.info(f"use font: {font_path}")
|
| 448 |
+
|
| 449 |
+
return font_path
|