davanstrien HF Staff commited on
Commit
27a9577
·
verified ·
1 Parent(s): 557fae3

Sync from GitHub via hub-sync

Browse files
Files changed (4) hide show
  1. CLAUDE.md +21 -1
  2. README.md +2 -1
  3. hunyuan-ocr-1.5.py +884 -0
  4. hunyuan-ocr.py +44 -4
CLAUDE.md CHANGED
@@ -79,11 +79,15 @@ Legend: ✅ production-ready · ⚠️ works only with a required pinned image
79
  | `surya-ocr-bucket.py` | ✅+image | vLLM `:v0.20.1` | l4x1 | bucket I/O; pin `surya-ocr==0.20.0` |
80
  | `lift-extract.py` | ✅ | hf / vLLM | a100-large | schema-constrained extraction; naming gotcha |
81
  | `nuextract3.py`, `lfm2-extract.py`, `lfm2-vl-extract.py` | ✅ | vLLM | l4x1 | structured extraction |
82
- | `rolm-ocr.py`, `smoldocling-ocr.py`, `numarkdown-ocr.py`, `hunyuan-ocr.py`, `qianfan-ocr.py`, `firered-ocr.py`, `abot-ocr.py`, `falcon-ocr.py`, `olmocr2-vllm.py`, `dots-mocr.py` | | vLLM | varies | see `README.md` for flags |
 
 
83
  | `pp-ocrv6.py`, `pp-doclayout.py` | ✅ | PaddleOCR / PaddleX | l4x1 | classical det+rec; dataset **or** bucket I/O |
84
 
85
  **License note:** Surya and `lift` ship code as Apache-2.0 but **weights under a modified OpenRAIL-M**
86
  (research/personal/<$5M, no competitive use vs Datalab's API) — surfaced in each docstring + card.
 
 
87
 
88
  ---
89
 
@@ -162,6 +166,19 @@ issue filed ([vllm#28160](https://github.com/vllm-project/vllm/issues/28160) is
162
  needs **nightly** vLLM (`DeepseekOCR2ForCausalLM` not in stable) + `addict`/`matplotlib` (its HF custom
163
  code), plus `limit_mm_per_prompt={"image":1}`.
164
 
 
 
 
 
 
 
 
 
 
 
 
 
 
165
  ### `glm-ocr.py`
166
  Chatty on blank pages / can emit degenerate repeats — that's **model quality, not a crash**; don't
167
  re-debug it as a recipe bug. (The actual historical crash was the `pyarrow<18` cap — see Conventions.)
@@ -244,6 +261,9 @@ ARM wheels) — if a nightly-recipe install fails on resolution, wait and retry
244
 
245
  ## Change log
246
 
 
 
 
247
  - **2026-07-01** — large full-page scan fixes ([#65](https://github.com/davanstrien/uv-scripts-for-ai/pull/65)):
248
  surya vLLM-missing preflight; `dots` 8192→32768 + `--max-pixels`; `lighton-ocr2` 8192→16384; `glm` dropped
249
  `pyarrow<18` (→ `datasets` `Json` load crash) + `VLLM_USE_DEEP_GEMM=0` + `--max-pixels`; `pp-ocrv6`
 
79
  | `surya-ocr-bucket.py` | ✅+image | vLLM `:v0.20.1` | l4x1 | bucket I/O; pin `surya-ocr==0.20.0` |
80
  | `lift-extract.py` | ✅ | hf / vLLM | a100-large | schema-constrained extraction; naming gotcha |
81
  | `nuextract3.py`, `lfm2-extract.py`, `lfm2-vl-extract.py` | ✅ | vLLM | l4x1 | structured extraction |
82
+ | `hunyuan-ocr.py` | | vLLM | l4x1 | **1.0, revision-pinned** (root repo became 1.5 in-place); `transformers<5.13` cap see gotcha |
83
+ | `hunyuan-ocr-1.5.py` | ✅ | vLLM | l4x1 | tracks repo root (=1.5); task-locked prompts; `transformers<5.13` cap — see gotcha |
84
+ | `rolm-ocr.py`, `smoldocling-ocr.py`, `numarkdown-ocr.py`, `qianfan-ocr.py`, `firered-ocr.py`, `abot-ocr.py`, `falcon-ocr.py`, `olmocr2-vllm.py`, `dots-mocr.py` | ✅ | vLLM | varies | see `README.md` for flags |
85
  | `pp-ocrv6.py`, `pp-doclayout.py` | ✅ | PaddleOCR / PaddleX | l4x1 | classical det+rec; dataset **or** bucket I/O |
86
 
87
  **License note:** Surya and `lift` ship code as Apache-2.0 but **weights under a modified OpenRAIL-M**
88
  (research/personal/<$5M, no competitive use vs Datalab's API) — surfaced in each docstring + card.
89
+ HunyuanOCR (1.0 + 1.5) is under the [Tencent Hunyuan Community License](https://huggingface.co/tencent/HunyuanOCR/blob/main/LICENSE)
90
+ (territory excludes EU/UK/South Korea; standard across Tencent's Hunyuan releases) — surfaced in each docstring + card.
91
 
92
  ---
93
 
 
166
  needs **nightly** vLLM (`DeepseekOCR2ForCausalLM` not in stable) + `addict`/`matplotlib` (its HF custom
167
  code), plus `limit_mm_per_prompt={"image":1}`.
168
 
169
+ ### `hunyuan-ocr.py` / `hunyuan-ocr-1.5.py` — upstream replaced the repo root in-place
170
+ On 2026-07-06 Tencent pushed HunyuanOCR-1.5 **into the same repo** `tencent/HunyuanOCR` (1.5 at root,
171
+ 1.0 archived under `v1.0/`, DFlash draft under `dflash/`, **no 1.0 tag or branch**). vLLM can't load a
172
+ repo subfolder, so `hunyuan-ocr.py` pins the last 1.0 commit by `revision` (`f6af82ee…`) — that pin is
173
+ the 1.0 *identity*, never loosen it to `main`; 1.5 is its own recipe (`hunyuan-ocr-1.5.py`, tracks root,
174
+ has `--revision` as insurance against the next in-place swap). Separate breakage, both scripts: stable
175
+ vLLM ≤0.24.0's `hunyuan_vl_image.py` does a string-key `AutoImageProcessor.register(...)` which
176
+ transformers 5.13 rejects (`'str' object has no attribute '__module__'` → "architectures failed to be
177
+ inspected" at engine init) — hence the `transformers<5.13` cap in both; drop it when the vllm#47872 fix
178
+ ships in a stable wheel. 1.5 prompts are task-locked (12 types, Chinese wording, from the official
179
+ client's `hunyuan_tasks.py`) and sampling is card-locked (temp 0.0, rep-penalty 1.08) — don't
180
+ "improve" either; upstream observed hand-tweaked prompts silently degrade quality.
181
+
182
  ### `glm-ocr.py`
183
  Chatty on blank pages / can emit degenerate repeats — that's **model quality, not a crash**; don't
184
  re-debug it as a recipe bug. (The actual historical crash was the `pyarrow<18` cap — see Conventions.)
 
261
 
262
  ## Change log
263
 
264
+ - **2026-07-08** — HunyuanOCR upstream repo swap: pinned `hunyuan-ocr.py` to the last 1.0 revision +
265
+ added `hunyuan-ocr-1.5.py` (12 task types, locked sampling); `transformers<5.13` cap in both for the
266
+ stable-vLLM HunyuanVL register breakage (vllm#47872). See the hunyuan gotcha above.
267
  - **2026-07-01** — large full-page scan fixes ([#65](https://github.com/davanstrien/uv-scripts-for-ai/pull/65)):
268
  surya vLLM-missing preflight; `dots` 8192→32768 + `--max-pixels`; `lighton-ocr2` 8192→16384; `glm` dropped
269
  `pyarrow<18` (→ `datasets` `Json` load crash) + `VLLM_USE_DEEP_GEMM=0` + `--max-pixels`; `pp-ocrv6`
README.md CHANGED
@@ -60,7 +60,8 @@ _Sorted by model size:_
60
  | `paddleocr-vl-1.6.py` | [PaddleOCR-VL-1.6](https://huggingface.co/PaddlePaddle/PaddleOCR-VL-1.6) | 0.9B | vLLM | **96.33% OmniDocBench v1.6** (SOTA), drop-in upgrade of 1.5 |
61
  | `lighton-ocr.py` | [LightOnOCR-1B](https://huggingface.co/lightonai/LightOnOCR-1B-1025) | 1B | vLLM | Fast, 3 vocab sizes |
62
  | `lighton-ocr2.py` | [LightOnOCR-2-1B](https://huggingface.co/lightonai/LightOnOCR-2-1B) | 1B | vLLM | 7× faster than v1, RLVR trained |
63
- | `hunyuan-ocr.py` | [HunyuanOCR](https://huggingface.co/tencent/HunyuanOCR) | 1B | vLLM | Lightweight VLM |
 
64
  | `dots-ocr.py` | [DoTS.ocr](https://huggingface.co/Tencent/DoTS.ocr) | 1.7B | vLLM | 100+ languages |
65
  | `firered-ocr.py` | [FireRed-OCR](https://huggingface.co/FireRedTeam/FireRed-OCR) | 2.1B | vLLM | Qwen3-VL fine-tune, Apache 2.0 |
66
  | `abot-ocr.py` | [ABot-OCR](https://huggingface.co/acvlab/ABot-OCR) | 2B | vLLM | Qwen3-VL based, doc→Markdown (text/LaTeX/HTML tables). Needs `vllm/vllm-openai` image. [paper](https://arxiv.org/abs/2605.27978) |
 
60
  | `paddleocr-vl-1.6.py` | [PaddleOCR-VL-1.6](https://huggingface.co/PaddlePaddle/PaddleOCR-VL-1.6) | 0.9B | vLLM | **96.33% OmniDocBench v1.6** (SOTA), drop-in upgrade of 1.5 |
61
  | `lighton-ocr.py` | [LightOnOCR-1B](https://huggingface.co/lightonai/LightOnOCR-1B-1025) | 1B | vLLM | Fast, 3 vocab sizes |
62
  | `lighton-ocr2.py` | [LightOnOCR-2-1B](https://huggingface.co/lightonai/LightOnOCR-2-1B) | 1B | vLLM | 7× faster than v1, RLVR trained |
63
+ | `hunyuan-ocr.py` | [HunyuanOCR 1.0](https://huggingface.co/tencent/HunyuanOCR/tree/f6af82ee007fe6091b29fb3bb287b491ead41c82) | 1B | vLLM | Lightweight VLM. Pinned to the last 1.0 revision (repo root became 1.5 in-place on 2026-07-06). [Hunyuan Community License](https://huggingface.co/tencent/HunyuanOCR/blob/main/LICENSE) (excludes EU/UK/KR) |
64
+ | `hunyuan-ocr-1.5.py` | [HunyuanOCR-1.5](https://huggingface.co/tencent/HunyuanOCR) | 1B | vLLM | 128K context, 4K images, 12 task types, ancient scripts. ~4-5× faster/page than dots.ocr & DeepSeek-OCR-2 (tech report). [Hunyuan Community License](https://huggingface.co/tencent/HunyuanOCR/blob/main/LICENSE) (excludes EU/UK/KR) |
65
  | `dots-ocr.py` | [DoTS.ocr](https://huggingface.co/Tencent/DoTS.ocr) | 1.7B | vLLM | 100+ languages |
66
  | `firered-ocr.py` | [FireRed-OCR](https://huggingface.co/FireRedTeam/FireRed-OCR) | 2.1B | vLLM | Qwen3-VL fine-tune, Apache 2.0 |
67
  | `abot-ocr.py` | [ABot-OCR](https://huggingface.co/acvlab/ABot-OCR) | 2B | vLLM | Qwen3-VL based, doc→Markdown (text/LaTeX/HTML tables). Needs `vllm/vllm-openai` image. [paper](https://arxiv.org/abs/2605.27978) |
hunyuan-ocr-1.5.py ADDED
@@ -0,0 +1,884 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.11"
3
+ # dependencies = [
4
+ # "datasets>=4.0.0",
5
+ # "huggingface-hub",
6
+ # "pillow",
7
+ # "vllm>=0.18.1",
8
+ # "transformers<5.13", # vLLM ≤0.24.0's HunyuanVL processor breaks on transformers 5.13
9
+ # # (string-key AutoImageProcessor.register; fixed in vllm#47872).
10
+ # # Drop this cap once that fix ships in a stable vLLM release.
11
+ # "tqdm",
12
+ # "toolz",
13
+ # "torch",
14
+ # ]
15
+ # ///
16
+
17
+ """
18
+ Convert document images to markdown using HunyuanOCR-1.5 with vLLM.
19
+
20
+ HunyuanOCR-1.5 is a lightweight ~1B-parameter, end-to-end OCR-specialized VLM
21
+ from Tencent. It keeps the validated 1.0 backbone but extends the max image
22
+ resolution to 4K and the context window to 128K, and adds targeted long-tail
23
+ capabilities (low-resource / ancient-script OCR, multi-image text QA). Per the
24
+ technical report (arXiv:2607.04884) it is faster than dots.ocr / DeepSeek-OCR-2
25
+ and top-tier on OmniDocBench v1.6. This script runs it offline via vLLM.
26
+
27
+ Features:
28
+ - 📝 End-to-end document parsing to markdown (tables → HTML, formulas → LaTeX)
29
+ - 🧩 Structured / layout-aware parsing
30
+ - 📍 Text spotting with coordinates (JSON or Hunyuan format)
31
+ - 📐 Formula (LaTeX) and 📊 table (HTML) recognition
32
+ - 📈 Chart parsing (Mermaid / Markdown)
33
+ - 🌐 Document + general-scene translation (→ zh / → en)
34
+ - 🎯 Compact model (~1B parameters)
35
+
36
+ Model: tencent/HunyuanOCR
37
+ On 2026-07-06 Tencent replaced the repo root in-place with HunyuanOCR-1.5
38
+ (1.0 archived under `v1.0/`, no git tag). So the repo *root* — the default
39
+ here — is now 1.5. The sibling recipe `hunyuan-ocr.py` pins the last 1.0
40
+ commit by revision to keep the 1.0 behavior; this script deliberately tracks
41
+ root (1.5).
42
+
43
+ vLLM: 0.18.1 (release) is the first stable wheel with native
44
+ `HunYuanVLForConditionalGeneration` support for autoregressive decoding — no
45
+ nightly or patch needed for batch OCR. The floor stays at 0.18.1; a bare
46
+ `vllm` resolves to the latest stable (0.24.0 as of 2026-07), which also works
47
+ once transformers is capped <5.13 (see the deps block for why). The DFlash
48
+ speculative-decoding draft (a per-request *latency* win that needs a vLLM
49
+ nightly) is intentionally NOT implemented: it does not change offline batch
50
+ throughput or output distribution.
51
+
52
+ trust_remote_code=True per the model card (the processor ships custom code).
53
+
54
+ License: Tencent Hunyuan Community License (territory excludes EU/UK/South Korea)
55
+ https://huggingface.co/tencent/HunyuanOCR/blob/main/LICENSE
56
+
57
+ Note: batch_size defaults to 16 (untested on this arch as of writing — 1.5 on
58
+ vLLM ≥0.18.1 should batch fine, unlike the 1.0 V1 batching issue; will be
59
+ smoke-tested). Lower it if you hit engine errors.
60
+
61
+ Post-processing note: only the shared tail-repetition cleanup
62
+ (`clean_repeated_substrings`, byte-for-byte from the official toolkit) is
63
+ ported. The upstream doc_parse-only markdown normalization (10 OmniDocBench
64
+ GT-alignment regex passes in `hunyuan_utils.process_one`) is intentionally NOT
65
+ ported — it is benchmark-GT alignment, not general OCR, and would bloat this
66
+ self-contained recipe. For bench-exact output, use Tencent's toolkit directly.
67
+ """
68
+
69
+ import argparse
70
+ import base64
71
+ import io
72
+ import json
73
+ import logging
74
+ import os
75
+ import sys
76
+ import time
77
+ from datetime import datetime
78
+ from typing import Any, Dict, List, Union
79
+
80
+ import torch
81
+ from datasets import load_dataset
82
+ from huggingface_hub import DatasetCard, login
83
+ from PIL import Image
84
+ from toolz import partition_all
85
+ from tqdm.auto import tqdm
86
+
87
+ # Disable vLLM's FlashInfer sampler: it JIT-compiles a CUDA kernel needing nvcc, which the
88
+ # default uv-script image lacks (engine init then crashes). Greedy OCR doesn't use it; this
89
+ # lets the plain default-image command work. On the vllm/vllm-openai image it's a harmless no-op.
90
+ os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0")
91
+ from vllm import LLM, SamplingParams
92
+
93
+ logging.basicConfig(level=logging.INFO)
94
+ logger = logging.getLogger(__name__)
95
+
96
+
97
+ # ────────────────────────────────────────────────────────────────
98
+ # HunyuanOCR-1.5 official task prompts.
99
+ # Reproduced VERBATIM from the shipped client's `hunyuan_tasks.py`:
100
+ # https://github.com/Tencent-Hunyuan/HunyuanOCR (inference/*/hunyuan_tasks.py)
101
+ # The model card only prints the `doc_parse` prompt; the other 11 live only in
102
+ # the client. Prompts are FIXED per task type — upstream deliberately does NOT
103
+ # expose free-form prompt editing because hand-tweaked instructions were
104
+ # observed to silently degrade quality (users pick a *task*, not a prompt).
105
+ # All prompts are Chinese-language, including for English documents — this is
106
+ # the officially recommended wording; the card provides no English variants.
107
+ # ────────────────────────────────────────────────────────────────
108
+
109
+ TASK_PROMPTS = {
110
+ # 端到端文档解析
111
+ "doc_parse": "提取文档图片中正文的所有信息用markdown格式表示,其中页眉、页脚部分忽略,"
112
+ "表格用html格式表达,文档中公式用latex格式表示,按照阅读顺序组织进行解析。",
113
+ # 结构化解析(古文、街景等非文档结构化场景)
114
+ "structured_parse": "提取图中的文字。",
115
+ # Spotting — JSON 格式
116
+ "spotting_json": "检测并识别图中所有的文字行,请按从上到下、从左到右的阅读顺序进行识别。 "
117
+ "输出格式为 JSON 数组,每个元素必须包含:"
118
+ '"box": [xmin, ymin, xmax, ymax](坐标需归一化到 [0, 1000] 范围内);'
119
+ '"text": "识别出的文字内容"。 '
120
+ "注意:请直接输出 JSON 数组,不要包含任何多余的描述性文字。",
121
+ # Spotting — Hunyuan 模式
122
+ "spotting_hunyuan": "检测并识别图片中的文字,将文本坐标格式化输出。",
123
+ # 版式分析
124
+ "layout": "按照阅读顺序解析图中的版式信息。",
125
+ # 版式分析 + 解析
126
+ "layout_parse": "提取文档图片中所有内容用markdown格式表示,表格用html格式表达,"
127
+ "文档中公式用latex格式表示,请按照阅读顺序组织进行全文解析,并输出版式分析信息。",
128
+ # 图表解析
129
+ "chart_parse": "解析图中的图表,对于流程图使用Mermaid格式表示,其他图表使用Markdown格式表示。",
130
+ # 公式解析
131
+ "formula": "识别图片中的公式,用LaTeX格式表示。",
132
+ # 表格解析
133
+ "table": "把图中的表格解析为HTML。",
134
+ # 文档英译中
135
+ "doc_trans_en2zh": "先解析文档,再将文档内容翻译为中文,其中页眉、页脚忽略,"
136
+ "公式用latex格式表示,表格用html格式表示。",
137
+ # 通用场景翻译 other2en
138
+ "trans_other2en": "按照阅读顺序,提取图中文字,公式用latex格式表示,表格用markdown格式表示,"
139
+ "再将文字内容翻译为英文。",
140
+ # 通用场景翻译 other2zh
141
+ "trans_other2zh": "按照阅读顺序,提取图中文字,公式用latex格式表示,表格用markdown格式表示,"
142
+ "再将文字内容翻译为中文。",
143
+ }
144
+
145
+ # English glosses for --help / the no-args banner (upstream ships Chinese ones).
146
+ TASK_DESCRIPTIONS = {
147
+ "doc_parse": "End-to-end doc parse (body→markdown, tables→HTML, formulas→LaTeX, headers/footers ignored). Default.",
148
+ "structured_parse": "Structured parse for non-document scenes (ancient scripts, street signs) — extract all text.",
149
+ "spotting_json": "Text detect+recognize as a JSON array (box normalized to 0-1000 + text).",
150
+ "spotting_hunyuan": "Text detect+recognize in Hunyuan coordinate format.",
151
+ "layout": "Layout analysis in reading order.",
152
+ "layout_parse": "Layout analysis + full-document parse (markdown/HTML/LaTeX).",
153
+ "chart_parse": "Chart parsing (flowcharts→Mermaid, other charts→Markdown).",
154
+ "formula": "Formula recognition → LaTeX.",
155
+ "table": "Table parsing → HTML.",
156
+ "doc_trans_en2zh": "Document translation to Chinese (parse then translate; formulas LaTeX, tables HTML).",
157
+ "trans_other2en": "General-scene extraction + translation to English.",
158
+ "trans_other2zh": "General-scene extraction + translation to Chinese.",
159
+ }
160
+
161
+ DEFAULT_TASK = "doc_parse"
162
+
163
+ # Sampling params LOCKED by the model card across all official setups so outputs
164
+ # are comparable: temperature=0.0, top_p=1.0, top_k=-1, repetition_penalty=1.08.
165
+ # Only repetition_penalty is exposed as a flag (the others are fixed for
166
+ # deterministic OCR); repetition_penalty is the model's built-in anti-repeat.
167
+ DEFAULT_REPETITION_PENALTY = 1.08
168
+
169
+
170
+ def clean_repeated_substrings(text: str, min_repeats: int = 10) -> str:
171
+ """Trim a long repeated suffix as a final safety net against greedy-decoding
172
+ degeneration. Byte-for-byte from the official `hunyuan_utils.py`.
173
+ """
174
+ n = len(text)
175
+ if n < 2000:
176
+ return text
177
+ for length in range(2, n // min_repeats + 1):
178
+ candidate = text[-length:]
179
+ count = 0
180
+ i = n - length
181
+ while i >= 0 and text[i : i + length] == candidate:
182
+ count += 1
183
+ i -= length
184
+ if count >= min_repeats:
185
+ return text[: n - length * (count - 1)]
186
+ return text
187
+
188
+
189
+ def check_cuda_availability():
190
+ """Check if CUDA is available and exit if not."""
191
+ if not torch.cuda.is_available():
192
+ logger.error("CUDA is not available. This script requires a GPU.")
193
+ logger.error("Please run on a machine with a CUDA-capable GPU.")
194
+ sys.exit(1)
195
+ else:
196
+ logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
197
+
198
+
199
+ def ensure_output_columns_free(dataset, columns, overwrite=False):
200
+ """Fail fast if an output column would collide with an existing input column.
201
+
202
+ Adding a column that already exists silently overwrites it (e.g. a ground-truth
203
+ `text`/`markdown` column) or crashes on push with a duplicate-column error only
204
+ *after* inference has run. Catch it up front. With overwrite=True, drop the clashing
205
+ column(s) here instead (logged) so the later add_column is clean.
206
+ """
207
+ clash = [c for c in columns if c in dataset.column_names]
208
+ if not clash:
209
+ return dataset
210
+ if overwrite:
211
+ logger.warning(f"--overwrite: replacing existing column(s) {clash}")
212
+ return dataset.remove_columns(clash)
213
+ logger.error(
214
+ f"Output column(s) {clash} already exist in the input dataset "
215
+ f"(columns: {dataset.column_names})."
216
+ )
217
+ logger.error(
218
+ "Choose a different --output-column, or pass --overwrite to replace them."
219
+ )
220
+ sys.exit(1)
221
+
222
+
223
+ def get_prompt(task_type: str) -> str:
224
+ """Return the official prompt for a task type."""
225
+ if task_type not in TASK_PROMPTS:
226
+ raise ValueError(
227
+ f"Unknown task type: {task_type}. Available: {list(TASK_PROMPTS.keys())}"
228
+ )
229
+ return TASK_PROMPTS[task_type]
230
+
231
+
232
+ def make_ocr_message(
233
+ image: Union[Image.Image, Dict[str, Any], str],
234
+ prompt: str,
235
+ ) -> List[Dict]:
236
+ """Create the chat messages for one image + prompt.
237
+
238
+ Mirrors the official client: an empty system message followed by a user turn
239
+ with the image *before* the text. The empty system content pins "no system
240
+ prompt" (matching how the model is served) rather than letting the chat
241
+ template inject a default.
242
+ """
243
+ # Convert to PIL Image if needed
244
+ if isinstance(image, Image.Image):
245
+ pil_img = image
246
+ elif isinstance(image, dict) and "bytes" in image:
247
+ pil_img = Image.open(io.BytesIO(image["bytes"]))
248
+ elif isinstance(image, str):
249
+ pil_img = Image.open(image)
250
+ else:
251
+ raise ValueError(f"Unsupported image type: {type(image)}")
252
+
253
+ # Convert to RGB
254
+ pil_img = pil_img.convert("RGB")
255
+
256
+ # Convert to base64 data URI
257
+ buf = io.BytesIO()
258
+ pil_img.save(buf, format="PNG")
259
+ data_uri = f"data:image/png;base64,{base64.b64encode(buf.getvalue()).decode()}"
260
+
261
+ return [
262
+ {"role": "system", "content": ""},
263
+ {
264
+ "role": "user",
265
+ "content": [
266
+ {"type": "image_url", "image_url": {"url": data_uri}},
267
+ {"type": "text", "text": prompt},
268
+ ],
269
+ },
270
+ ]
271
+
272
+
273
+ def create_dataset_card(
274
+ source_dataset: str,
275
+ model: str,
276
+ num_samples: int,
277
+ processing_time: str,
278
+ batch_size: int,
279
+ max_model_len: int,
280
+ max_tokens: int,
281
+ repetition_penalty: float,
282
+ gpu_memory_utilization: float,
283
+ image_column: str = "image",
284
+ output_column: str = "markdown",
285
+ split: str = "train",
286
+ task_type: str = "doc_parse",
287
+ ) -> str:
288
+ """Create a dataset card documenting the OCR process."""
289
+ model_name = model.split("/")[-1]
290
+
291
+ return f"""---
292
+ tags:
293
+ - ocr
294
+ - document-processing
295
+ - hunyuan-ocr-1.5
296
+ - multilingual
297
+ - markdown
298
+ - uv-script
299
+ - generated
300
+ ---
301
+
302
+ # Document OCR using {model_name} (HunyuanOCR-1.5)
303
+
304
+ This dataset contains OCR results from images in [{source_dataset}](https://huggingface.co/datasets/{source_dataset}) using HunyuanOCR-1.5, a lightweight ~1B end-to-end OCR VLM from Tencent (128K context, 4K max image resolution).
305
+
306
+ Model license: [Tencent Hunyuan Community License](https://huggingface.co/tencent/HunyuanOCR/blob/main/LICENSE) (territory excludes EU/UK/South Korea).
307
+
308
+ ## Processing Details
309
+
310
+ - **Source Dataset**: [{source_dataset}](https://huggingface.co/datasets/{source_dataset})
311
+ - **Model**: [{model}](https://huggingface.co/{model})
312
+ - **Number of Samples**: {num_samples:,}
313
+ - **Processing Time**: {processing_time}
314
+ - **Processing Date**: {datetime.now().strftime("%Y-%m-%d %H:%M UTC")}
315
+
316
+ ### Configuration
317
+
318
+ - **Image Column**: `{image_column}`
319
+ - **Output Column**: `{output_column}`
320
+ - **Dataset Split**: `{split}`
321
+ - **Task Type**: `{task_type}`
322
+ - **Batch Size**: {batch_size}
323
+ - **Max Model Length**: {max_model_len:,} tokens
324
+ - **Max Output Tokens**: {max_tokens:,}
325
+ - **Repetition Penalty**: {repetition_penalty}
326
+ - **GPU Memory Utilization**: {gpu_memory_utilization:.1%}
327
+
328
+ ## Model Information
329
+
330
+ HunyuanOCR-1.5 is a lightweight end-to-end OCR VLM that excels at:
331
+ - 📝 **Document Parsing** - Full markdown extraction in reading order
332
+ - 🧩 **Structured / Layout Parsing** - Layout-aware full-document parse
333
+ - 📊 **Table Extraction** - HTML format tables
334
+ - 📐 **Formula Recognition** - LaTeX format formulas
335
+ - 📈 **Chart Parsing** - Mermaid / Markdown format
336
+ - 📍 **Text Spotting** - Detection with coordinates (JSON / Hunyuan)
337
+ - 🌐 **Translation** - Document and general-scene translation (→ zh / → en)
338
+
339
+ Per the technical report ([arXiv:2607.04884](https://arxiv.org/pdf/2607.04884)),
340
+ 1.5 is faster than dots.ocr / DeepSeek-OCR-2 and top-tier on OmniDocBench v1.6.
341
+
342
+ ## Task Types Available
343
+
344
+ - `doc_parse` - End-to-end document parsing (default)
345
+ - `structured_parse` - Non-document structured scenes (ancient scripts, street signs)
346
+ - `spotting_json` - Text detection + recognition as JSON array (box 0-1000 + text)
347
+ - `spotting_hunyuan` - Text detection + recognition, Hunyuan coordinate format
348
+ - `layout` - Layout analysis in reading order
349
+ - `layout_parse` - Layout analysis + full-document parse
350
+ - `chart_parse` - Chart parsing (flowcharts → Mermaid, others → Markdown)
351
+ - `formula` - Formula recognition → LaTeX
352
+ - `table` - Table parsing → HTML
353
+ - `doc_trans_en2zh` - Document translation to Chinese
354
+ - `trans_other2en` - General-scene extraction + translation to English
355
+ - `trans_other2zh` - General-scene extraction + translation to Chinese
356
+
357
+ ## Dataset Structure
358
+
359
+ The dataset contains all original columns plus:
360
+ - `{output_column}`: The extracted text (markdown for `doc_parse`, else the task's format)
361
+ - `inference_info`: JSON list tracking all OCR models applied to this dataset
362
+
363
+ ## Usage
364
+
365
+ ```python
366
+ from datasets import load_dataset
367
+ import json
368
+
369
+ # Load the dataset
370
+ dataset = load_dataset("{{output_dataset_id}}", split="{split}")
371
+
372
+ # Access the extracted text
373
+ for example in dataset:
374
+ print(example["{output_column}"])
375
+ break
376
+
377
+ # View all OCR models applied to this dataset
378
+ inference_info = json.loads(dataset[0]["inference_info"])
379
+ for info in inference_info:
380
+ print(f"Column: {{info['column_name']}} - Model: {{info['model_id']}}")
381
+ ```
382
+
383
+ ## Reproduction
384
+
385
+ This dataset was generated using the [uv-scripts/ocr](https://huggingface.co/datasets/uv-scripts/ocr) HunyuanOCR-1.5 script:
386
+
387
+ ```bash
388
+ uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/hunyuan-ocr-1.5.py \\
389
+ {source_dataset} \\
390
+ <output-dataset> \\
391
+ --image-column {image_column} \\
392
+ --batch-size {batch_size} \\
393
+ --task-type {task_type} \\
394
+ --max-model-len {max_model_len} \\
395
+ --max-tokens {max_tokens} \\
396
+ --gpu-memory-utilization {gpu_memory_utilization}
397
+ ```
398
+
399
+ Generated with [UV Scripts](https://huggingface.co/uv-scripts)
400
+ """
401
+
402
+
403
+ def main(
404
+ input_dataset: str,
405
+ output_dataset: str,
406
+ image_column: str = "image",
407
+ batch_size: int = 16,
408
+ model: str = "tencent/HunyuanOCR",
409
+ revision: str = None,
410
+ max_model_len: int = 32768,
411
+ max_tokens: int = 8192,
412
+ repetition_penalty: float = DEFAULT_REPETITION_PENALTY,
413
+ gpu_memory_utilization: float = 0.8,
414
+ hf_token: str = None,
415
+ split: str = "train",
416
+ max_samples: int = None,
417
+ private: bool = False,
418
+ shuffle: bool = False,
419
+ seed: int = 42,
420
+ task_type: str = DEFAULT_TASK,
421
+ custom_prompt: str = None,
422
+ output_column: str = "markdown",
423
+ overwrite: bool = False,
424
+ clean_output: bool = True,
425
+ config: str = None,
426
+ create_pr: bool = False,
427
+ verbose: bool = False,
428
+ ):
429
+ """Process images from an HF dataset through HunyuanOCR-1.5."""
430
+
431
+ # Check CUDA availability first
432
+ check_cuda_availability()
433
+
434
+ # Context-length invariant (config.json): text max_position_embeddings=131072;
435
+ # the vision processor caps a single image at img_max_token_num=16384. So the
436
+ # default budget holds without resizing: 16384 (image) + prompt + 8192 (output)
437
+ # ≈ 25k ≤ 32768 (default max_model_len). Enforce max_tokens ≤ max_model_len ≤ 131072.
438
+ if max_model_len > 131072:
439
+ logger.error(
440
+ f"--max-model-len {max_model_len} exceeds the model's max context (131072)."
441
+ )
442
+ sys.exit(1)
443
+ if max_tokens > max_model_len:
444
+ logger.error(
445
+ f"--max-tokens ({max_tokens}) cannot exceed --max-model-len ({max_model_len})."
446
+ )
447
+ sys.exit(1)
448
+
449
+ # Track processing start time
450
+ start_time = datetime.now()
451
+
452
+ # Login to HF if token provided
453
+ HF_TOKEN = hf_token or os.environ.get("HF_TOKEN")
454
+ if HF_TOKEN:
455
+ login(token=HF_TOKEN)
456
+
457
+ # Determine prompt to use
458
+ if custom_prompt:
459
+ prompt = custom_prompt
460
+ logger.warning(
461
+ "Using --custom-prompt. Note: upstream deliberately locks prompts per "
462
+ "task type — hand-tweaked instructions can silently degrade quality."
463
+ )
464
+ logger.info(f"Custom prompt: {prompt[:60]}...")
465
+ else:
466
+ prompt = get_prompt(task_type)
467
+ logger.info(f"Using task type: {task_type}")
468
+
469
+ # Load dataset
470
+ logger.info(f"Loading dataset: {input_dataset}")
471
+ dataset = load_dataset(input_dataset, split=split)
472
+
473
+ # Validate image column
474
+ if image_column not in dataset.column_names:
475
+ raise ValueError(
476
+ f"Column '{image_column}' not found. Available: {dataset.column_names}"
477
+ )
478
+
479
+ # Fail fast if the output column would collide with an existing input column
480
+ dataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)
481
+
482
+ # Shuffle if requested
483
+ if shuffle:
484
+ logger.info(f"Shuffling dataset with seed {seed}")
485
+ dataset = dataset.shuffle(seed=seed)
486
+
487
+ # Limit samples if requested
488
+ if max_samples:
489
+ dataset = dataset.select(range(min(max_samples, len(dataset))))
490
+ logger.info(f"Limited to {len(dataset)} samples")
491
+
492
+ # Initialize vLLM model
493
+ logger.info(f"Initializing vLLM with model: {model}")
494
+ logger.info("This may take a few minutes on first run...")
495
+
496
+ llm = LLM(
497
+ model=model,
498
+ revision=revision,
499
+ trust_remote_code=True,
500
+ max_model_len=max_model_len,
501
+ gpu_memory_utilization=gpu_memory_utilization,
502
+ limit_mm_per_prompt={"image": 1},
503
+ )
504
+
505
+ # Locked sampling per the model card (deterministic OCR); only repetition_penalty
506
+ # is user-tunable.
507
+ sampling_params = SamplingParams(
508
+ temperature=0.0,
509
+ top_p=1.0,
510
+ top_k=-1,
511
+ repetition_penalty=repetition_penalty,
512
+ max_tokens=max_tokens,
513
+ skip_special_tokens=True,
514
+ )
515
+
516
+ logger.info(f"Processing {len(dataset)} images in batches of {batch_size}")
517
+ logger.info(f"Output will be written to column: {output_column}")
518
+
519
+ # Process images in batches
520
+ all_outputs = []
521
+
522
+ for batch_indices in tqdm(
523
+ partition_all(batch_size, range(len(dataset))),
524
+ total=(len(dataset) + batch_size - 1) // batch_size,
525
+ desc="HunyuanOCR-1.5 processing",
526
+ ):
527
+ batch_indices = list(batch_indices)
528
+ batch_images = [dataset[i][image_column] for i in batch_indices]
529
+
530
+ try:
531
+ # Create messages for batch
532
+ batch_messages = [make_ocr_message(img, prompt) for img in batch_images]
533
+
534
+ # Process with vLLM
535
+ outputs = llm.chat(batch_messages, sampling_params)
536
+
537
+ # Extract outputs
538
+ for output in outputs:
539
+ text = output.outputs[0].text.strip()
540
+ # Clean repeated substrings if enabled
541
+ if clean_output:
542
+ text = clean_repeated_substrings(text)
543
+ all_outputs.append(text)
544
+
545
+ except Exception as e:
546
+ logger.error(f"Error processing batch: {e}")
547
+ # Add error placeholders for failed batch
548
+ all_outputs.extend(["[OCR ERROR]"] * len(batch_images))
549
+
550
+ # Calculate processing time
551
+ processing_duration = datetime.now() - start_time
552
+ processing_time_str = f"{processing_duration.total_seconds() / 60:.1f} min"
553
+
554
+ # Add output column to dataset
555
+ logger.info(f"Adding '{output_column}' column to dataset")
556
+ dataset = dataset.add_column(output_column, all_outputs)
557
+
558
+ # Handle inference_info tracking (for multi-model comparisons)
559
+ inference_entry = {
560
+ "model_id": model,
561
+ "model_name": "HunyuanOCR-1.5",
562
+ "model_revision": revision or "main",
563
+ "column_name": output_column,
564
+ "timestamp": datetime.now().isoformat(),
565
+ "task_type": task_type if not custom_prompt else "custom",
566
+ "repetition_penalty": repetition_penalty,
567
+ }
568
+
569
+ if "inference_info" in dataset.column_names:
570
+ # Append to existing inference info
571
+ logger.info("Updating existing inference_info column")
572
+
573
+ def update_inference_info(example):
574
+ try:
575
+ existing_info = (
576
+ json.loads(example["inference_info"])
577
+ if example["inference_info"]
578
+ else []
579
+ )
580
+ except (json.JSONDecodeError, TypeError):
581
+ existing_info = []
582
+
583
+ existing_info.append(inference_entry)
584
+ return {"inference_info": json.dumps(existing_info)}
585
+
586
+ dataset = dataset.map(update_inference_info)
587
+ else:
588
+ # Create new inference_info column
589
+ logger.info("Creating new inference_info column")
590
+ inference_list = [json.dumps([inference_entry])] * len(dataset)
591
+ dataset = dataset.add_column("inference_info", inference_list)
592
+
593
+ # Push to hub with retry and XET fallback
594
+ logger.info(f"Pushing to {output_dataset}")
595
+ commit_msg = f"Add HunyuanOCR-1.5 OCR results ({len(dataset)} samples)" + (
596
+ f" [{config}]" if config else ""
597
+ )
598
+ max_retries = 3
599
+ for attempt in range(1, max_retries + 1):
600
+ try:
601
+ if attempt > 1:
602
+ logger.warning("Disabling XET (fallback to HTTP upload)")
603
+ os.environ["HF_HUB_DISABLE_XET"] = "1"
604
+ dataset.push_to_hub(
605
+ output_dataset,
606
+ private=private,
607
+ token=HF_TOKEN,
608
+ max_shard_size="500MB",
609
+ **({"config_name": config} if config else {}),
610
+ create_pr=create_pr,
611
+ commit_message=commit_msg,
612
+ )
613
+ break
614
+ except Exception as e:
615
+ logger.error(f"Upload attempt {attempt}/{max_retries} failed: {e}")
616
+ if attempt < max_retries:
617
+ delay = 30 * (2 ** (attempt - 1))
618
+ logger.info(f"Retrying in {delay}s...")
619
+ time.sleep(delay)
620
+ else:
621
+ logger.error("All upload attempts failed. OCR results are lost.")
622
+ sys.exit(1)
623
+
624
+ # Create and push dataset card (skip when creating PR to avoid conflicts)
625
+ if not create_pr:
626
+ logger.info("Creating dataset card")
627
+ card_content = create_dataset_card(
628
+ source_dataset=input_dataset,
629
+ model=model,
630
+ num_samples=len(dataset),
631
+ processing_time=processing_time_str,
632
+ batch_size=batch_size,
633
+ max_model_len=max_model_len,
634
+ max_tokens=max_tokens,
635
+ repetition_penalty=repetition_penalty,
636
+ gpu_memory_utilization=gpu_memory_utilization,
637
+ image_column=image_column,
638
+ output_column=output_column,
639
+ split=split,
640
+ task_type=task_type if not custom_prompt else "custom",
641
+ )
642
+
643
+ card = DatasetCard(card_content)
644
+ card.push_to_hub(output_dataset, token=HF_TOKEN)
645
+
646
+ logger.info("HunyuanOCR-1.5 processing complete!")
647
+ logger.info(
648
+ f"Dataset available at: https://huggingface.co/datasets/{output_dataset}"
649
+ )
650
+ logger.info(f"Processing time: {processing_time_str}")
651
+
652
+ if verbose:
653
+ import importlib.metadata
654
+
655
+ logger.info("--- Resolved package versions ---")
656
+ for pkg in [
657
+ "vllm",
658
+ "transformers",
659
+ "torch",
660
+ "datasets",
661
+ "pyarrow",
662
+ "pillow",
663
+ ]:
664
+ try:
665
+ logger.info(f" {pkg}=={importlib.metadata.version(pkg)}")
666
+ except importlib.metadata.PackageNotFoundError:
667
+ logger.info(f" {pkg}: not installed")
668
+ logger.info("--- End versions ---")
669
+
670
+
671
+ if __name__ == "__main__":
672
+ # Show example usage if no arguments
673
+ if len(sys.argv) == 1:
674
+ print("=" * 80)
675
+ print("HunyuanOCR-1.5 Document Processing")
676
+ print("=" * 80)
677
+ print(
678
+ "\nLightweight ~1B end-to-end OCR VLM from Tencent (128K context, 4K images)"
679
+ )
680
+ print("\nFeatures:")
681
+ print("- 📝 End-to-end document parsing to markdown")
682
+ print("- 📊 Table extraction (HTML format)")
683
+ print("- 📐 Formula recognition (LaTeX format)")
684
+ print("- 📍 Text spotting with coordinates (JSON / Hunyuan)")
685
+ print("- 📈 Chart parsing (Mermaid / Markdown)")
686
+ print("- 🌐 Document + general-scene translation (→ zh / → en)")
687
+ print("\nExample usage:")
688
+ print("\n1. Basic document parsing:")
689
+ print(" uv run hunyuan-ocr-1.5.py input-dataset output-dataset")
690
+ print("\n2. Formula extraction:")
691
+ print(" uv run hunyuan-ocr-1.5.py math-docs formulas --task-type formula")
692
+ print("\n3. Table extraction:")
693
+ print(" uv run hunyuan-ocr-1.5.py docs tables --task-type table")
694
+ print("\n4. Text spotting as JSON (box + text):")
695
+ print(" uv run hunyuan-ocr-1.5.py images spotted --task-type spotting_json")
696
+ print("\n5. Translate a document to Chinese:")
697
+ print(
698
+ " uv run hunyuan-ocr-1.5.py en-docs zh-docs --task-type doc_trans_en2zh"
699
+ )
700
+ print("\n6. Running on HF Jobs:")
701
+ print(" hf jobs uv run --flavor l4x1 \\")
702
+ print(
703
+ ' -e HF_TOKEN=$(python3 -c "from huggingface_hub import get_token; print(get_token())") \\'
704
+ )
705
+ print(
706
+ " https://huggingface.co/datasets/uv-scripts/ocr/raw/main/hunyuan-ocr-1.5.py \\"
707
+ )
708
+ print(" input-dataset output-dataset")
709
+ print("\n" + "=" * 80)
710
+ print("\nFor full help, run: uv run hunyuan-ocr-1.5.py --help")
711
+ sys.exit(0)
712
+
713
+ task_help = "\n".join(f" {k:18s}- {TASK_DESCRIPTIONS[k]}" for k in TASK_PROMPTS)
714
+ parser = argparse.ArgumentParser(
715
+ description="Document OCR using HunyuanOCR-1.5 (lightweight ~1B end-to-end OCR VLM)",
716
+ formatter_class=argparse.RawDescriptionHelpFormatter,
717
+ epilog=f"""
718
+ Task Types (official HunyuanOCR-1.5 prompts, all Chinese-language):
719
+ {task_help}
720
+
721
+ Examples:
722
+ # Basic document OCR (default)
723
+ uv run hunyuan-ocr-1.5.py my-docs analyzed-docs
724
+
725
+ # Extract formulas as LaTeX
726
+ uv run hunyuan-ocr-1.5.py math-papers formulas --task-type formula
727
+
728
+ # Extract tables as HTML
729
+ uv run hunyuan-ocr-1.5.py reports tables --task-type table
730
+
731
+ # Text spotting as JSON (box normalized 0-1000 + text)
732
+ uv run hunyuan-ocr-1.5.py images spotted --task-type spotting_json
733
+
734
+ # Translate documents to Chinese
735
+ uv run hunyuan-ocr-1.5.py en-docs translated --task-type doc_trans_en2zh
736
+
737
+ # Random sampling for testing
738
+ uv run hunyuan-ocr-1.5.py large-dataset test --max-samples 50 --shuffle
739
+ """,
740
+ )
741
+
742
+ parser.add_argument("input_dataset", help="Input dataset ID from Hugging Face Hub")
743
+ parser.add_argument("output_dataset", help="Output dataset ID for Hugging Face Hub")
744
+ parser.add_argument(
745
+ "--image-column",
746
+ default="image",
747
+ help="Column containing images (default: image)",
748
+ )
749
+ parser.add_argument(
750
+ "--batch-size",
751
+ type=int,
752
+ default=16,
753
+ help="Batch size for processing (default: 16; lower it if you hit engine errors)",
754
+ )
755
+ parser.add_argument(
756
+ "--model",
757
+ default="tencent/HunyuanOCR",
758
+ help="Model to use (default: tencent/HunyuanOCR — repo root is 1.5)",
759
+ )
760
+ parser.add_argument(
761
+ "--revision",
762
+ default=None,
763
+ help="Model repo revision (default: main). Tencent has replaced this repo's "
764
+ "root in-place before (1.0 → 1.5); pin a commit hash for reproducible runs.",
765
+ )
766
+ parser.add_argument(
767
+ "--max-model-len",
768
+ type=int,
769
+ default=32768,
770
+ help="Maximum model context length (default: 32768; max 131072). A single "
771
+ "image is capped at ~16384 tokens by the vision processor, so 32768 fits "
772
+ "image + 8192 output; raise for very long outputs.",
773
+ )
774
+ parser.add_argument(
775
+ "--max-tokens",
776
+ type=int,
777
+ default=8192,
778
+ help="Maximum tokens to generate (default: 8192; must be ≤ --max-model-len). "
779
+ "Dense pages may need more — raise toward 32768.",
780
+ )
781
+ parser.add_argument(
782
+ "--repetition-penalty",
783
+ type=float,
784
+ default=DEFAULT_REPETITION_PENALTY,
785
+ help=f"Repetition penalty (default: {DEFAULT_REPETITION_PENALTY}, the model card's locked value)",
786
+ )
787
+ parser.add_argument(
788
+ "--gpu-memory-utilization",
789
+ type=float,
790
+ default=0.8,
791
+ help="GPU memory utilization (default: 0.8)",
792
+ )
793
+ parser.add_argument("--hf-token", help="Hugging Face API token")
794
+ parser.add_argument(
795
+ "--split", default="train", help="Dataset split to use (default: train)"
796
+ )
797
+ parser.add_argument(
798
+ "--max-samples",
799
+ type=int,
800
+ help="Maximum number of samples to process (for testing)",
801
+ )
802
+ parser.add_argument(
803
+ "--private", action="store_true", help="Make output dataset private"
804
+ )
805
+ parser.add_argument(
806
+ "--shuffle", action="store_true", help="Shuffle dataset before processing"
807
+ )
808
+ parser.add_argument(
809
+ "--seed",
810
+ type=int,
811
+ default=42,
812
+ help="Random seed for shuffling (default: 42)",
813
+ )
814
+ parser.add_argument(
815
+ "--task-type",
816
+ choices=list(TASK_PROMPTS.keys()),
817
+ default=DEFAULT_TASK,
818
+ metavar="TASK",
819
+ help=f"Official task type (default: {DEFAULT_TASK}). See the epilog for all types.",
820
+ )
821
+ parser.add_argument(
822
+ "--custom-prompt",
823
+ help="Custom prompt text (overrides --task-type; may degrade quality — upstream "
824
+ "locks prompts per task)",
825
+ )
826
+ parser.add_argument(
827
+ "--output-column",
828
+ default="markdown",
829
+ help="Column name for output text (default: markdown)",
830
+ )
831
+ parser.add_argument(
832
+ "--overwrite",
833
+ action="store_true",
834
+ help="Replace the output column if it already exists in the input dataset "
835
+ "(default: error out to avoid clobbering an existing column).",
836
+ )
837
+ parser.add_argument(
838
+ "--no-clean-output",
839
+ action="store_true",
840
+ help="Disable cleaning of repeated substrings in output",
841
+ )
842
+ parser.add_argument(
843
+ "--config",
844
+ help="Dataset config name for multi-model benchmarks",
845
+ )
846
+ parser.add_argument(
847
+ "--create-pr",
848
+ action="store_true",
849
+ help="Push results as a pull request instead of direct commit",
850
+ )
851
+ parser.add_argument(
852
+ "--verbose",
853
+ action="store_true",
854
+ help="Log resolved package versions at the end of the run",
855
+ )
856
+
857
+ args = parser.parse_args()
858
+
859
+ main(
860
+ input_dataset=args.input_dataset,
861
+ output_dataset=args.output_dataset,
862
+ image_column=args.image_column,
863
+ batch_size=args.batch_size,
864
+ model=args.model,
865
+ revision=args.revision,
866
+ max_model_len=args.max_model_len,
867
+ max_tokens=args.max_tokens,
868
+ repetition_penalty=args.repetition_penalty,
869
+ gpu_memory_utilization=args.gpu_memory_utilization,
870
+ hf_token=args.hf_token,
871
+ split=args.split,
872
+ max_samples=args.max_samples,
873
+ private=args.private,
874
+ shuffle=args.shuffle,
875
+ seed=args.seed,
876
+ task_type=args.task_type,
877
+ custom_prompt=args.custom_prompt,
878
+ output_column=args.output_column,
879
+ overwrite=args.overwrite,
880
+ clean_output=not args.no_clean_output,
881
+ config=args.config,
882
+ create_pr=args.create_pr,
883
+ verbose=args.verbose,
884
+ )
hunyuan-ocr.py CHANGED
@@ -5,6 +5,9 @@
5
  # "huggingface-hub",
6
  # "pillow",
7
  # "vllm>=0.15.1",
 
 
 
8
  # "tqdm",
9
  # "toolz",
10
  # "torch",
@@ -12,11 +15,18 @@
12
  # ///
13
 
14
  """
15
- Convert document images to markdown using HunyuanOCR with vLLM.
16
 
17
  HunyuanOCR is a lightweight 1B parameter VLM from Tencent designed for complex
18
  multilingual document parsing. This script uses vLLM for processing.
19
 
 
 
 
 
 
 
 
20
  Features:
21
  - 📝 Full document parsing to markdown
22
  - 📊 Table extraction (HTML format)
@@ -26,8 +36,10 @@ Features:
26
  - 🌐 Photo translation
27
  - 🎯 Compact model (1B parameters)
28
 
29
- Model: tencent/HunyuanOCR
30
- vLLM: Requires nightly build (trust_remote_code=True)
 
 
31
 
32
  Note: Due to vLLM V1 engine batching issues with HunyuanOCR, batch_size defaults to 1.
33
  """
@@ -58,6 +70,12 @@ from vllm import LLM, SamplingParams
58
  logging.basicConfig(level=logging.INFO)
59
  logger = logging.getLogger(__name__)
60
 
 
 
 
 
 
 
61
 
62
  # ────────────────────────────────────────────────────────────────
63
  # HunyuanOCR Prompt Templates (from official README)
@@ -248,6 +266,7 @@ def make_ocr_message(
248
  def create_dataset_card(
249
  source_dataset: str,
250
  model: str,
 
251
  num_samples: int,
252
  processing_time: str,
253
  batch_size: int,
@@ -277,10 +296,13 @@ tags:
277
 
278
  This dataset contains OCR results from images in [{source_dataset}](https://huggingface.co/datasets/{source_dataset}) using HunyuanOCR, a lightweight 1B VLM from Tencent.
279
 
 
 
280
  ## Processing Details
281
 
282
  - **Source Dataset**: [{source_dataset}](https://huggingface.co/datasets/{source_dataset})
283
  - **Model**: [{model}](https://huggingface.co/{model})
 
284
  - **Number of Samples**: {num_samples:,}
285
  - **Processing Time**: {processing_time}
286
  - **Processing Date**: {datetime.now().strftime("%Y-%m-%d %H:%M UTC")}
@@ -372,6 +394,7 @@ def main(
372
  image_column: str = "image",
373
  batch_size: int = 1, # Default to 1 due to vLLM V1 batching issues with HunyuanOCR
374
  model: str = "tencent/HunyuanOCR",
 
375
  max_model_len: int = 16384,
376
  max_tokens: int = 16384,
377
  gpu_memory_utilization: float = 0.8,
@@ -445,14 +468,21 @@ def main(
445
  dataset = dataset.select(range(min(max_samples, len(dataset))))
446
  logger.info(f"Limited to {len(dataset)} samples")
447
 
 
 
 
 
 
 
448
  # Initialize vLLM model
449
- logger.info(f"Initializing vLLM with model: {model}")
450
  logger.info("This may take a few minutes on first run...")
451
 
452
  # Note: HunyuanOCR has batching issues with vLLM V1 engine when batch_size > 1
453
  # Using limit_mm_per_prompt for stability
454
  llm = LLM(
455
  model=model,
 
456
  trust_remote_code=True,
457
  max_model_len=max_model_len,
458
  gpu_memory_utilization=gpu_memory_utilization,
@@ -511,6 +541,7 @@ def main(
511
  inference_entry = {
512
  "model_id": model,
513
  "model_name": "HunyuanOCR",
 
514
  "column_name": output_column,
515
  "timestamp": datetime.now().isoformat(),
516
  "prompt_mode": prompt_mode if not custom_prompt else "custom",
@@ -578,6 +609,7 @@ def main(
578
  card_content = create_dataset_card(
579
  source_dataset=input_dataset,
580
  model=model,
 
581
  num_samples=len(dataset),
582
  processing_time=processing_time_str,
583
  batch_size=batch_size,
@@ -731,6 +763,13 @@ Examples:
731
  default="tencent/HunyuanOCR",
732
  help="Model to use (default: tencent/HunyuanOCR)",
733
  )
 
 
 
 
 
 
 
734
  parser.add_argument(
735
  "--max-model-len",
736
  type=int,
@@ -851,6 +890,7 @@ Examples:
851
  image_column=args.image_column,
852
  batch_size=args.batch_size,
853
  model=args.model,
 
854
  max_model_len=args.max_model_len,
855
  max_tokens=args.max_tokens,
856
  gpu_memory_utilization=args.gpu_memory_utilization,
 
5
  # "huggingface-hub",
6
  # "pillow",
7
  # "vllm>=0.15.1",
8
+ # "transformers<5.13", # vLLM ≤0.24.0's HunyuanVL processor breaks on transformers 5.13
9
+ # # (string-key AutoImageProcessor.register; fixed in vllm#47872).
10
+ # # Drop this cap once that fix ships in a stable vLLM release.
11
  # "tqdm",
12
  # "toolz",
13
  # "torch",
 
15
  # ///
16
 
17
  """
18
+ Convert document images to markdown using HunyuanOCR (v1.0) with vLLM.
19
 
20
  HunyuanOCR is a lightweight 1B parameter VLM from Tencent designed for complex
21
  multilingual document parsing. This script uses vLLM for processing.
22
 
23
+ ⚠️ This recipe targets HunyuanOCR **1.0**. On 2026-07-06 Tencent pushed
24
+ HunyuanOCR-1.5 into the *same* repo (new weights at root, 1.0 archived under
25
+ `v1.0/`, no git tag), so loading `tencent/HunyuanOCR@main` now yields 1.5 —
26
+ different context length, prompts, and transformers/vLLM requirements. We pin
27
+ the last 1.0 commit by revision to keep this script's validated behavior.
28
+ For 1.5, use the sibling `hunyuan-ocr-1.5.py`.
29
+
30
  Features:
31
  - 📝 Full document parsing to markdown
32
  - 📊 Table extraction (HTML format)
 
36
  - 🌐 Photo translation
37
  - 🎯 Compact model (1B parameters)
38
 
39
+ Model: tencent/HunyuanOCR (pinned to the last 1.0 revision)
40
+
41
+ License: Tencent Hunyuan Community License (territory excludes EU/UK/South Korea)
42
+ https://huggingface.co/tencent/HunyuanOCR/blob/main/LICENSE
43
 
44
  Note: Due to vLLM V1 engine batching issues with HunyuanOCR, batch_size defaults to 1.
45
  """
 
70
  logging.basicConfig(level=logging.INFO)
71
  logger = logging.getLogger(__name__)
72
 
73
+ # Last commit where the repo root held the 1.0 weights (2026-01-13). Not a temporary
74
+ # workaround pin: upstream replaced root with 1.5 in-place (2026-07-06) and left no
75
+ # 1.0 tag/branch, so this revision IS the 1.0 identity. Never loosen to "main" here —
76
+ # 1.5 lives in hunyuan-ocr-1.5.py. Override with --revision only to reproduce old runs.
77
+ DEFAULT_REVISION = "f6af82ee007fe6091b29fb3bb287b491ead41c82"
78
+
79
 
80
  # ────────────────────────────────────────────────────────────────
81
  # HunyuanOCR Prompt Templates (from official README)
 
266
  def create_dataset_card(
267
  source_dataset: str,
268
  model: str,
269
+ revision: str,
270
  num_samples: int,
271
  processing_time: str,
272
  batch_size: int,
 
296
 
297
  This dataset contains OCR results from images in [{source_dataset}](https://huggingface.co/datasets/{source_dataset}) using HunyuanOCR, a lightweight 1B VLM from Tencent.
298
 
299
+ Model license: [Tencent Hunyuan Community License](https://huggingface.co/tencent/HunyuanOCR/blob/main/LICENSE) (territory excludes EU/UK/South Korea).
300
+
301
  ## Processing Details
302
 
303
  - **Source Dataset**: [{source_dataset}](https://huggingface.co/datasets/{source_dataset})
304
  - **Model**: [{model}](https://huggingface.co/{model})
305
+ - **Model Revision**: `{revision}` (HunyuanOCR 1.0 — the repo root holds 1.5 since 2026-07-06)
306
  - **Number of Samples**: {num_samples:,}
307
  - **Processing Time**: {processing_time}
308
  - **Processing Date**: {datetime.now().strftime("%Y-%m-%d %H:%M UTC")}
 
394
  image_column: str = "image",
395
  batch_size: int = 1, # Default to 1 due to vLLM V1 batching issues with HunyuanOCR
396
  model: str = "tencent/HunyuanOCR",
397
+ revision: str = None,
398
  max_model_len: int = 16384,
399
  max_tokens: int = 16384,
400
  gpu_memory_utilization: float = 0.8,
 
468
  dataset = dataset.select(range(min(max_samples, len(dataset))))
469
  logger.info(f"Limited to {len(dataset)} samples")
470
 
471
+ # Pin the 1.0 revision only for the default repo — a user-supplied --model
472
+ # must not inherit a foreign commit hash.
473
+ if revision is None and model == "tencent/HunyuanOCR":
474
+ revision = DEFAULT_REVISION
475
+ logger.info(f"Pinning tencent/HunyuanOCR to 1.0 revision {revision[:8]}")
476
+
477
  # Initialize vLLM model
478
+ logger.info(f"Initializing vLLM: {model} (revision: {revision or 'main'})")
479
  logger.info("This may take a few minutes on first run...")
480
 
481
  # Note: HunyuanOCR has batching issues with vLLM V1 engine when batch_size > 1
482
  # Using limit_mm_per_prompt for stability
483
  llm = LLM(
484
  model=model,
485
+ revision=revision,
486
  trust_remote_code=True,
487
  max_model_len=max_model_len,
488
  gpu_memory_utilization=gpu_memory_utilization,
 
541
  inference_entry = {
542
  "model_id": model,
543
  "model_name": "HunyuanOCR",
544
+ "model_revision": revision or "main",
545
  "column_name": output_column,
546
  "timestamp": datetime.now().isoformat(),
547
  "prompt_mode": prompt_mode if not custom_prompt else "custom",
 
609
  card_content = create_dataset_card(
610
  source_dataset=input_dataset,
611
  model=model,
612
+ revision=revision or "main",
613
  num_samples=len(dataset),
614
  processing_time=processing_time_str,
615
  batch_size=batch_size,
 
763
  default="tencent/HunyuanOCR",
764
  help="Model to use (default: tencent/HunyuanOCR)",
765
  )
766
+ parser.add_argument(
767
+ "--revision",
768
+ default=None,
769
+ help="Model repo revision. Defaults to the last 1.0 commit when --model is "
770
+ "tencent/HunyuanOCR (the repo root now holds 1.5 — see hunyuan-ocr-1.5.py); "
771
+ "defaults to main for any other model.",
772
+ )
773
  parser.add_argument(
774
  "--max-model-len",
775
  type=int,
 
890
  image_column=args.image_column,
891
  batch_size=args.batch_size,
892
  model=args.model,
893
+ revision=args.revision,
894
  max_model_len=args.max_model_len,
895
  max_tokens=args.max_tokens,
896
  gpu_memory_utilization=args.gpu_memory_utilization,