davanstrien HF Staff commited on
Commit
808b109
·
verified ·
1 Parent(s): c009b2c

Sync from GitHub via hub-sync

Browse files
Files changed (3) hide show
  1. README.md +2 -1
  2. pp-ocrv6.py +3 -0
  3. tesseract-ocr.py +646 -0
README.md CHANGED
@@ -49,7 +49,8 @@ _Sorted by model size:_
49
 
50
  | Script | Model | Size | Backend | Notes |
51
  |--------|-------|------|---------|-------|
52
- | `pp-ocrv6.py` | [PP-OCRv6](https://huggingface.co/collections/PaddlePaddle/pp-ocrv6) | 1.5–34.5M | PaddleOCR (paddle) | **Smallest by far** — classical det+rec pipeline, not a VLM. Three tiers (`--model-tier tiny\|small\|medium`), plain-text output (not markdown). 50 langs. Runs on `t4-small`. Apache 2.0 |
 
53
  | `falcon-ocr.py` | [Falcon-OCR](https://huggingface.co/tiiuae/Falcon-OCR) | 0.3B | falcon-perception | Smallest VLM in collection. #1 on multi-column docs and tables (olmOCR), Apache 2.0 |
54
  | `smoldocling-ocr.py` | [SmolDocling](https://huggingface.co/ds4sd/SmolDocling-256M-preview) | 256M | Transformers | DocTags structured output |
55
  | `surya-ocr.py` | [Surya OCR 2](https://huggingface.co/datalab-to/surya-ocr-2) | 0.65B | vLLM | **Structured** OCR + `--task layout\|table`: per-block HTML with bboxes & reading order in an extra `surya_blocks` column. 91 langs, top-under-3B on olmOCR-Bench. Modified OpenRAIL-M license. Needs the **pinned** `vllm/vllm-openai:v0.20.1` image |
 
49
 
50
  | Script | Model | Size | Backend | Notes |
51
  |--------|-------|------|---------|-------|
52
+ | `tesseract-ocr.py` | [Tesseract 5](https://github.com/tesseract-ocr/tesseract) | n/a (classical) | pytesseract (CPU) | **The legacy baseline** — no GPU at all, runs on `cpu-upgrade`. Plain-text output, `--lang`/`--psm`/`--oem` exposed, 100+ language packs via apt. Apache 2.0 |
53
+ | `pp-ocrv6.py` | [PP-OCRv6](https://huggingface.co/collections/PaddlePaddle/pp-ocrv6) | 1.5–34.5M | PaddleOCR (paddle) | **Smallest neural** — classical det+rec pipeline, not a VLM. Three tiers (`--model-tier tiny\|small\|medium`), plain-text output (not markdown). 50 langs. Runs on `t4-small`. Apache 2.0 |
54
  | `falcon-ocr.py` | [Falcon-OCR](https://huggingface.co/tiiuae/Falcon-OCR) | 0.3B | falcon-perception | Smallest VLM in collection. #1 on multi-column docs and tables (olmOCR), Apache 2.0 |
55
  | `smoldocling-ocr.py` | [SmolDocling](https://huggingface.co/ds4sd/SmolDocling-256M-preview) | 256M | Transformers | DocTags structured output |
56
  | `surya-ocr.py` | [Surya OCR 2](https://huggingface.co/datalab-to/surya-ocr-2) | 0.65B | vLLM | **Structured** OCR + `--task layout\|table`: per-block HTML with bboxes & reading order in an extra `surya_blocks` column. 91 langs, top-under-3B on olmOCR-Bench. Modified OpenRAIL-M license. Needs the **pinned** `vllm/vllm-openai:v0.20.1` image |
pp-ocrv6.py CHANGED
@@ -701,6 +701,9 @@ def build_inference_entry(tier: str, det_model: str, rec_model: str, args_dict:
701
  "rec_accuracy_pct": TIER_REC.get(tier),
702
  "languages": TIER_LANGUAGES.get(tier, ""),
703
  "engine": "paddle_static",
 
 
 
704
  "output_column": args_dict.get("output_column", "markdown"),
705
  "blocks_column": "pp_ocr_blocks",
706
  "timestamp": datetime.now(timezone.utc).isoformat(),
 
701
  "rec_accuracy_pct": TIER_REC.get(tier),
702
  "languages": TIER_LANGUAGES.get(tier, ""),
703
  "engine": "paddle_static",
704
+ # column_name is the key ocr-bench's column discovery reads; keep
705
+ # output_column too for backward compat with existing outputs.
706
+ "column_name": args_dict.get("output_column", "markdown"),
707
  "output_column": args_dict.get("output_column", "markdown"),
708
  "blocks_column": "pp_ocr_blocks",
709
  "timestamp": datetime.now(timezone.utc).isoformat(),
tesseract-ocr.py ADDED
@@ -0,0 +1,646 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.10"
3
+ # dependencies = [
4
+ # "pytesseract",
5
+ # "datasets>=3.1.0",
6
+ # "huggingface-hub[hf_transfer]",
7
+ # "pillow",
8
+ # "tqdm",
9
+ # ]
10
+ # ///
11
+ """
12
+ Plain-text OCR with **Tesseract** — the classical CPU OCR engine, as a baseline.
13
+
14
+ This is the odd one out in this collection: no GPU, no VLM. It runs Google's
15
+ Tesseract (v5, LSTM) over an image dataset and writes the recognised text to a
16
+ column, so you can put a cheap, fast, no-GPU baseline next to the VLM recipes
17
+ (e.g. in a per-collection leaderboard like ocr-bench). Output is plain text, not
18
+ markdown — Tesseract has no notion of tables/formulas/layout-as-markdown.
19
+
20
+ CPU-ONLY: this recipe deliberately does not require a GPU. Run it on a
21
+ `cpu-basic` / `cpu-upgrade` flavor. `--num-workers` fans OCR out across cores.
22
+
23
+ SYSTEM DEPENDENCY: the `tesseract` binary is NOT in the default Jobs image. On
24
+ startup this script installs it via apt (`tesseract-ocr`; Jobs containers run as
25
+ root). For non-English languages it also tries to install the matching
26
+ `tesseract-ocr-<lang>` data pack. If your Jobs image blocks apt, bake Tesseract
27
+ into a custom `--image` instead.
28
+
29
+ HF Jobs (CPU — no GPU needed):
30
+
31
+ hf jobs uv run --flavor cpu-upgrade -s HF_TOKEN \\
32
+ https://huggingface.co/datasets/uv-scripts/ocr/raw/main/tesseract-ocr.py \\
33
+ input-dataset output-dataset \\
34
+ --max-samples 100 --shuffle
35
+
36
+ Language packs (apt codes are 3-letter ISO 639-2, same as Tesseract's `--lang`):
37
+
38
+ --lang eng English (default; ships with the base package)
39
+ --lang fra French (installs tesseract-ocr-fra)
40
+ --lang eng+fra multiple languages, '+'-joined
41
+
42
+ Engine: Tesseract OCR (https://github.com/tesseract-ocr/tesseract), Apache-2.0.
43
+ """
44
+
45
+ import argparse
46
+ import io
47
+ import json
48
+ import logging
49
+ import os
50
+ import shutil
51
+ import subprocess
52
+ import sys
53
+ import time
54
+ from concurrent.futures import ThreadPoolExecutor
55
+ from datetime import datetime, timezone
56
+ from typing import Any, Dict, List, Union
57
+
58
+ from datasets import load_dataset
59
+ from huggingface_hub import DatasetCard, login
60
+ from PIL import Image
61
+ from tqdm import tqdm
62
+
63
+ logging.basicConfig(level=logging.INFO)
64
+ logger = logging.getLogger(__name__)
65
+
66
+ # Stable leaderboard label. Tesseract is not on the Hub, so this is deliberately
67
+ # NOT an org/name Hub id (faking one would produce broken links in dataset cards
68
+ # and a misleading leaderboard row). The precise installed version is recorded
69
+ # separately in inference_info as `tesseract_version`.
70
+ MODEL_ID = "tesseract-5"
71
+ MODEL_NAME = "Tesseract"
72
+ PROJECT_URL = "https://github.com/tesseract-ocr/tesseract"
73
+
74
+ # Error sentinel written to the output column when a single image fails, so one
75
+ # bad page never sinks the whole run (matches the other recipes in this repo).
76
+ OCR_ERROR = "[OCR ERROR]"
77
+
78
+
79
+ def ensure_tesseract_installed(lang: str) -> None:
80
+ """Install the `tesseract` binary (and language data) if it's missing.
81
+
82
+ The default Jobs image has no `tesseract`. Containers run as root, so apt
83
+ works. The base `tesseract-ocr` package ships English; other languages need
84
+ their own `tesseract-ocr-<code>` data pack. Base install is fatal on
85
+ failure (nothing to OCR with); language-pack installs are best-effort (a
86
+ missing pack surfaces as a clear Tesseract error at OCR time anyway).
87
+ """
88
+ requested = [c.strip() for c in lang.split("+") if c.strip()]
89
+
90
+ if shutil.which("tesseract") is None:
91
+ logger.info("`tesseract` not found — installing via apt (Jobs runs as root)...")
92
+ try:
93
+ subprocess.run(["apt-get", "update", "-qq"], check=True)
94
+ subprocess.run(
95
+ ["apt-get", "install", "-y", "-qq", "tesseract-ocr"], check=True
96
+ )
97
+ except Exception as e:
98
+ logger.error(f"Failed to apt-install tesseract-ocr: {e}")
99
+ logger.error(
100
+ "If this Jobs image blocks apt, run with a custom --image that has "
101
+ "Tesseract preinstalled (apt package `tesseract-ocr`)."
102
+ )
103
+ sys.exit(1)
104
+ if shutil.which("tesseract") is None:
105
+ logger.error("tesseract still not on PATH after install — aborting.")
106
+ sys.exit(1)
107
+ logger.info("Installed tesseract.")
108
+
109
+ # Install any missing non-English language data packs (best-effort).
110
+ try:
111
+ import pytesseract
112
+
113
+ available = set(pytesseract.get_languages(config=""))
114
+ except Exception:
115
+ available = set()
116
+ missing = [c for c in requested if c not in available and c not in ("osd",)]
117
+ if missing:
118
+ pkgs = [f"tesseract-ocr-{c}" for c in missing]
119
+ logger.info(f"Installing language data pack(s): {pkgs}")
120
+ try:
121
+ subprocess.run(["apt-get", "update", "-qq"], check=True)
122
+ subprocess.run(["apt-get", "install", "-y", "-qq", *pkgs], check=True)
123
+ except Exception as e:
124
+ logger.warning(
125
+ f"Could not install language pack(s) {pkgs}: {e}. "
126
+ f"OCR will fail for those languages if the data is absent."
127
+ )
128
+
129
+
130
+ def detect_tesseract_version() -> str:
131
+ """Return the installed Tesseract version string (best-effort)."""
132
+ try:
133
+ import pytesseract
134
+
135
+ return str(pytesseract.get_tesseract_version())
136
+ except Exception:
137
+ return "unknown"
138
+
139
+
140
+ def ensure_output_columns_free(dataset, columns, overwrite=False):
141
+ """Fail fast if an output column would collide with an existing input column.
142
+
143
+ Adding a column that already exists silently overwrites it (e.g. a
144
+ ground-truth `text`/`markdown` column) or crashes on push with a
145
+ duplicate-column error only *after* OCR has run. Catch it up front. With
146
+ overwrite=True, drop the clashing column(s) here instead (logged).
147
+ """
148
+ clash = [c for c in columns if c in dataset.column_names]
149
+ if not clash:
150
+ return dataset
151
+ if overwrite:
152
+ logger.warning(f"--overwrite: replacing existing column(s) {clash}")
153
+ return dataset.remove_columns(clash)
154
+ logger.error(
155
+ f"Output column(s) {clash} already exist in the input dataset "
156
+ f"(columns: {dataset.column_names})."
157
+ )
158
+ logger.error(
159
+ "Choose a different --output-column, or pass --overwrite to replace them."
160
+ )
161
+ sys.exit(1)
162
+
163
+
164
+ def to_pil(image: Union[Image.Image, Dict[str, Any], str]) -> Image.Image:
165
+ """Coerce a datasets image cell to an RGB PIL image.
166
+
167
+ Handles the three shapes a HF image column yields: a decoded PIL image, a
168
+ `{"bytes": ...}` dict, or a file path string.
169
+ """
170
+ if isinstance(image, Image.Image):
171
+ pil_img = image
172
+ elif isinstance(image, dict) and "bytes" in image:
173
+ pil_img = Image.open(io.BytesIO(image["bytes"]))
174
+ elif isinstance(image, str):
175
+ pil_img = Image.open(image)
176
+ else:
177
+ raise ValueError(f"Unsupported image type: {type(image)}")
178
+ return pil_img.convert("RGB")
179
+
180
+
181
+ def ocr_image(
182
+ image: Union[Image.Image, Dict[str, Any], str],
183
+ lang: str,
184
+ config: str,
185
+ ) -> str:
186
+ """Run Tesseract on a single image, returning stripped text (or the error sentinel)."""
187
+ import pytesseract
188
+
189
+ try:
190
+ pil_img = to_pil(image)
191
+ return pytesseract.image_to_string(pil_img, lang=lang, config=config).strip()
192
+ except Exception as e: # noqa: BLE001 — one bad page shouldn't sink the run
193
+ logger.error(f"Error OCR'ing image: {e}")
194
+ return OCR_ERROR
195
+
196
+
197
+ def run_ocr(
198
+ dataset,
199
+ image_column: str,
200
+ lang: str,
201
+ config: str,
202
+ num_workers: int,
203
+ ) -> List[str]:
204
+ """OCR every row's image, preserving dataset order.
205
+
206
+ Tesseract shells out to a subprocess, so ThreadPoolExecutor gives real
207
+ parallelism (the GIL is released during the call). We process in chunks so
208
+ only a chunk's worth of decoded images is held in memory at once — the full
209
+ dataset stays on disk.
210
+ """
211
+ n = len(dataset)
212
+ results: List[str] = []
213
+ chunk = max(num_workers * 4, 16)
214
+
215
+ with tqdm(total=n, desc="OCR", unit="img") as pbar:
216
+ if num_workers <= 1:
217
+ for i in range(n):
218
+ results.append(ocr_image(dataset[i][image_column], lang, config))
219
+ pbar.update(1)
220
+ else:
221
+ with ThreadPoolExecutor(max_workers=num_workers) as pool:
222
+ for start in range(0, n, chunk):
223
+ stop = min(start + chunk, n)
224
+ images = [dataset[i][image_column] for i in range(start, stop)]
225
+ for text in pool.map(
226
+ lambda img: ocr_image(img, lang, config), images
227
+ ):
228
+ results.append(text)
229
+ pbar.update(1)
230
+ return results
231
+
232
+
233
+ def create_dataset_card(
234
+ source_dataset: str,
235
+ num_samples: int,
236
+ processing_time: str,
237
+ tesseract_version: str,
238
+ lang: str,
239
+ psm: int,
240
+ oem: int,
241
+ num_workers: int,
242
+ output_column: str,
243
+ image_column: str = "image",
244
+ split: str = "train",
245
+ ) -> str:
246
+ """Create a dataset card documenting the Tesseract OCR run."""
247
+ return f"""---
248
+ tags:
249
+ - ocr
250
+ - text-recognition
251
+ - tesseract
252
+ - uv-script
253
+ - generated
254
+ ---
255
+
256
+ # Document OCR using Tesseract
257
+
258
+ This dataset contains OCR results from images in [{source_dataset}](https://huggingface.co/datasets/{source_dataset}) using [Tesseract]({PROJECT_URL}), the classical open-source CPU OCR engine — a cheap, no-GPU baseline alongside the VLM OCR recipes.
259
+
260
+ ## Processing Details
261
+
262
+ - **Source Dataset**: [{source_dataset}](https://huggingface.co/datasets/{source_dataset})
263
+ - **Engine**: [Tesseract]({PROJECT_URL}) `{tesseract_version}`
264
+ - **Language(s)**: `{lang}`
265
+ - **Number of Samples**: {num_samples:,}
266
+ - **Processing Time**: {processing_time}
267
+ - **Processing Date**: {datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")}
268
+
269
+ ### Configuration
270
+
271
+ - **Image Column**: `{image_column}`
272
+ - **Output Column**: `{output_column}`
273
+ - **Dataset Split**: `{split}`
274
+ - **Page Segmentation Mode (psm)**: {psm}
275
+ - **OCR Engine Mode (oem)**: {oem}
276
+ - **Workers**: {num_workers}
277
+
278
+ ## Model Information
279
+
280
+ Tesseract is a classical (non-VLM) OCR engine:
281
+ - Runs on CPU — no GPU required
282
+ - v4+ uses an LSTM-based recognition engine
283
+ - 100+ languages via installable data packs
284
+ - Plain-text output (no markdown / table / formula structure)
285
+ - Apache-2.0 licensed
286
+
287
+ ## Dataset Structure
288
+
289
+ The dataset contains all original columns plus:
290
+ - `{output_column}`: The recognised text (plain text)
291
+ - `inference_info`: JSON list tracking all OCR models applied to this dataset
292
+
293
+ ## Reproduction
294
+
295
+ ```bash
296
+ uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/tesseract-ocr.py \\
297
+ {source_dataset} \\
298
+ <output-dataset> \\
299
+ --image-column {image_column} \\
300
+ --lang {lang} \\
301
+ --psm {psm}
302
+ ```
303
+
304
+ Generated with [UV Scripts](https://huggingface.co/uv-scripts)
305
+ """
306
+
307
+
308
+ def main(
309
+ input_dataset: str,
310
+ output_dataset: str,
311
+ image_column: str = "image",
312
+ lang: str = "eng",
313
+ psm: int = 3,
314
+ oem: int = 3,
315
+ num_workers: int = 0,
316
+ hf_token: str = None,
317
+ split: str = "train",
318
+ max_samples: int = None,
319
+ private: bool = False,
320
+ shuffle: bool = False,
321
+ seed: int = 42,
322
+ output_column: str = "markdown",
323
+ overwrite: bool = False,
324
+ dry_run: bool = False,
325
+ verbose: bool = False,
326
+ config: str = None,
327
+ create_pr: bool = False,
328
+ ):
329
+ """Process images from an HF dataset through Tesseract OCR."""
330
+
331
+ start_time = datetime.now(timezone.utc)
332
+
333
+ # Fan-out defaults to all cores. When running >1 worker, cap Tesseract's own
334
+ # OpenMP threads to 1 so N processes don't oversubscribe the CPU (per the
335
+ # Tesseract FAQ). Must be set before the binary is invoked.
336
+ if num_workers <= 0:
337
+ num_workers = os.cpu_count() or 1
338
+ if num_workers > 1:
339
+ os.environ.setdefault("OMP_THREAD_LIMIT", "1")
340
+
341
+ ensure_tesseract_installed(lang)
342
+ tesseract_version = detect_tesseract_version()
343
+ logger.info(
344
+ f"Using Tesseract {tesseract_version} (lang={lang}, psm={psm}, oem={oem})"
345
+ )
346
+ logger.info(f"CPU-only run with {num_workers} worker(s)")
347
+
348
+ HF_TOKEN = hf_token or os.environ.get("HF_TOKEN")
349
+ if HF_TOKEN and not dry_run:
350
+ login(token=HF_TOKEN)
351
+
352
+ # Load dataset
353
+ logger.info(f"Loading dataset: {input_dataset}")
354
+ dataset = load_dataset(input_dataset, split=split)
355
+
356
+ if image_column not in dataset.column_names:
357
+ raise ValueError(
358
+ f"Column '{image_column}' not found. Available: {dataset.column_names}"
359
+ )
360
+
361
+ # Fail fast if the output column would collide with an existing input column
362
+ dataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)
363
+
364
+ if shuffle:
365
+ logger.info(f"Shuffling dataset with seed {seed}")
366
+ dataset = dataset.shuffle(seed=seed)
367
+
368
+ if max_samples:
369
+ dataset = dataset.select(range(min(max_samples, len(dataset))))
370
+ logger.info(f"Limited to {len(dataset)} samples")
371
+
372
+ tess_config = f"--psm {psm} --oem {oem}"
373
+ logger.info(f"Processing {len(dataset)} images -> column '{output_column}'")
374
+
375
+ all_outputs = run_ocr(dataset, image_column, lang, tess_config, num_workers)
376
+
377
+ n_errors = sum(1 for t in all_outputs if t == OCR_ERROR)
378
+ if n_errors:
379
+ logger.warning(f"{n_errors}/{len(all_outputs)} images failed OCR ({OCR_ERROR})")
380
+
381
+ processing_duration = datetime.now(timezone.utc) - start_time
382
+ processing_time_str = f"{processing_duration.total_seconds() / 60:.1f} min"
383
+
384
+ logger.info(f"Adding '{output_column}' column to dataset")
385
+ dataset = dataset.add_column(output_column, all_outputs)
386
+
387
+ # Inference info tracking. `model_id` + `column_name` are the fields consumers
388
+ # (e.g. ocr-bench) read to find the text column and the leaderboard label.
389
+ inference_entry = {
390
+ "model_id": MODEL_ID,
391
+ "model_name": MODEL_NAME,
392
+ "column_name": output_column,
393
+ "timestamp": datetime.now(timezone.utc).isoformat(),
394
+ "engine": "tesseract",
395
+ "tesseract_version": tesseract_version,
396
+ "lang": lang,
397
+ "psm": psm,
398
+ "oem": oem,
399
+ }
400
+
401
+ if "inference_info" in dataset.column_names:
402
+ logger.info("Updating existing inference_info column")
403
+
404
+ def update_inference_info(example):
405
+ try:
406
+ existing_info = (
407
+ json.loads(example["inference_info"])
408
+ if example["inference_info"]
409
+ else []
410
+ )
411
+ except (json.JSONDecodeError, TypeError):
412
+ existing_info = []
413
+ existing_info.append(inference_entry)
414
+ return {"inference_info": json.dumps(existing_info)}
415
+
416
+ dataset = dataset.map(update_inference_info)
417
+ else:
418
+ logger.info("Creating new inference_info column")
419
+ inference_list = [json.dumps([inference_entry])] * len(dataset)
420
+ dataset = dataset.add_column("inference_info", inference_list)
421
+
422
+ if dry_run:
423
+ logger.info("--dry-run: skipping push to Hub.")
424
+ preview = next((t for t in all_outputs if t and t != OCR_ERROR), "")
425
+ logger.info(f"Sample OCR output (first non-empty, truncated):\n{preview[:500]}")
426
+ logger.info(
427
+ f"Done (dry run). {len(dataset)} rows OCR'd in {processing_time_str}."
428
+ )
429
+ return
430
+
431
+ # Push to hub with retry and XET fallback
432
+ logger.info(f"Pushing to {output_dataset}")
433
+ max_retries = 3
434
+ for attempt in range(1, max_retries + 1):
435
+ try:
436
+ if attempt > 1:
437
+ logger.warning("Disabling XET (fallback to HTTP upload)")
438
+ os.environ["HF_HUB_DISABLE_XET"] = "1"
439
+ dataset.push_to_hub(
440
+ output_dataset,
441
+ private=private,
442
+ token=HF_TOKEN,
443
+ max_shard_size="500MB",
444
+ **({"config_name": config} if config else {}),
445
+ create_pr=create_pr,
446
+ commit_message=f"Add {MODEL_ID} OCR results ({len(dataset)} samples)"
447
+ + (f" [{config}]" if config else ""),
448
+ )
449
+ break
450
+ except Exception as e:
451
+ logger.error(f"Upload attempt {attempt}/{max_retries} failed: {e}")
452
+ if attempt < max_retries:
453
+ delay = 30 * (2 ** (attempt - 1))
454
+ logger.info(f"Retrying in {delay}s...")
455
+ time.sleep(delay)
456
+ else:
457
+ logger.error("All upload attempts failed. OCR results are lost.")
458
+ sys.exit(1)
459
+
460
+ # Create and push dataset card
461
+ logger.info("Creating dataset card")
462
+ card_content = create_dataset_card(
463
+ source_dataset=input_dataset,
464
+ num_samples=len(dataset),
465
+ processing_time=processing_time_str,
466
+ tesseract_version=tesseract_version,
467
+ lang=lang,
468
+ psm=psm,
469
+ oem=oem,
470
+ num_workers=num_workers,
471
+ output_column=output_column,
472
+ image_column=image_column,
473
+ split=split,
474
+ )
475
+ card = DatasetCard(card_content)
476
+ card.push_to_hub(output_dataset, token=HF_TOKEN)
477
+
478
+ logger.info("Done! Tesseract OCR processing complete.")
479
+ logger.info(
480
+ f"Dataset available at: https://huggingface.co/datasets/{output_dataset}"
481
+ )
482
+ logger.info(f"Processing time: {processing_time_str}")
483
+ if processing_duration.total_seconds() > 0:
484
+ logger.info(
485
+ f"Processing speed: {len(dataset) / processing_duration.total_seconds():.2f} images/sec"
486
+ )
487
+
488
+ if verbose:
489
+ import importlib.metadata
490
+
491
+ logger.info("--- Resolved package versions ---")
492
+ for pkg in ["pytesseract", "datasets", "pyarrow", "pillow"]:
493
+ try:
494
+ logger.info(f" {pkg}=={importlib.metadata.version(pkg)}")
495
+ except importlib.metadata.PackageNotFoundError:
496
+ logger.info(f" {pkg}: not installed")
497
+ logger.info(f" tesseract=={tesseract_version}")
498
+ logger.info("--- End versions ---")
499
+
500
+
501
+ if __name__ == "__main__":
502
+ if len(sys.argv) == 1:
503
+ print("=" * 70)
504
+ print("Tesseract OCR — CPU baseline")
505
+ print("=" * 70)
506
+ print("\nClassical LSTM OCR engine. No GPU. Plain-text output.")
507
+ print("\nExamples:")
508
+ print("\n1. Basic OCR (English):")
509
+ print(" uv run tesseract-ocr.py input-dataset output-dataset")
510
+ print("\n2. Another language (installs the data pack on Jobs):")
511
+ print(" uv run tesseract-ocr.py docs results --lang fra")
512
+ print("\n3. Test with a small sample, no push:")
513
+ print(" uv run tesseract-ocr.py large-dataset out --max-samples 5 --dry-run")
514
+ print("\n4. Running on HF Jobs (CPU flavor):")
515
+ print(" hf jobs uv run --flavor cpu-upgrade \\")
516
+ print(" -s HF_TOKEN \\")
517
+ print(
518
+ " https://huggingface.co/datasets/uv-scripts/ocr/raw/main/tesseract-ocr.py \\"
519
+ )
520
+ print(" input-dataset output-dataset --max-samples 100 --shuffle")
521
+ print("\nFor full help: uv run tesseract-ocr.py --help")
522
+ sys.exit(0)
523
+
524
+ parser = argparse.ArgumentParser(
525
+ description="CPU OCR baseline using Tesseract (classical LSTM engine, plain text)",
526
+ formatter_class=argparse.RawDescriptionHelpFormatter,
527
+ epilog="""
528
+ Examples:
529
+ uv run tesseract-ocr.py my-docs analyzed-docs
530
+ uv run tesseract-ocr.py docs results --lang eng+fra --psm 4
531
+ uv run tesseract-ocr.py large-dataset test --max-samples 50 --shuffle --dry-run
532
+
533
+ Page segmentation modes (--psm), common ones:
534
+ 3 Fully automatic page segmentation, no OSD (default; good for full pages)
535
+ 4 Assume a single column of text of variable sizes
536
+ 6 Assume a single uniform block of text
537
+ 1 Automatic page segmentation with OSD
538
+ """,
539
+ )
540
+
541
+ parser.add_argument("input_dataset", help="Input dataset ID from Hugging Face Hub")
542
+ parser.add_argument("output_dataset", help="Output dataset ID for Hugging Face Hub")
543
+ parser.add_argument(
544
+ "--image-column",
545
+ default="image",
546
+ help="Column containing images (default: image)",
547
+ )
548
+ parser.add_argument(
549
+ "--lang",
550
+ default="eng",
551
+ help="Tesseract language code(s), '+'-joined (default: eng). "
552
+ "Non-English packs are apt-installed on Jobs.",
553
+ )
554
+ parser.add_argument(
555
+ "--psm",
556
+ type=int,
557
+ default=3,
558
+ help="Page segmentation mode (default: 3, full-page auto)",
559
+ )
560
+ parser.add_argument(
561
+ "--oem",
562
+ type=int,
563
+ default=3,
564
+ help="OCR engine mode (default: 3, based on what's available; 1=LSTM only)",
565
+ )
566
+ parser.add_argument(
567
+ "--num-workers",
568
+ type=int,
569
+ default=0,
570
+ help="Parallel OCR workers (default: 0 = all CPU cores)",
571
+ )
572
+ parser.add_argument("--hf-token", help="Hugging Face API token")
573
+ parser.add_argument(
574
+ "--split", default="train", help="Dataset split to use (default: train)"
575
+ )
576
+ parser.add_argument(
577
+ "--max-samples",
578
+ type=int,
579
+ help="Maximum number of samples to process (for testing)",
580
+ )
581
+ parser.add_argument(
582
+ "--private", action="store_true", help="Make output dataset private"
583
+ )
584
+ parser.add_argument(
585
+ "--config",
586
+ help="Config/subset name when pushing to Hub (for benchmarking multiple models in one repo)",
587
+ )
588
+ parser.add_argument(
589
+ "--create-pr",
590
+ action="store_true",
591
+ help="Create a pull request instead of pushing directly (for parallel benchmarking)",
592
+ )
593
+ parser.add_argument(
594
+ "--shuffle", action="store_true", help="Shuffle dataset before processing"
595
+ )
596
+ parser.add_argument(
597
+ "--seed",
598
+ type=int,
599
+ default=42,
600
+ help="Random seed for shuffling (default: 42)",
601
+ )
602
+ parser.add_argument(
603
+ "--output-column",
604
+ default="markdown",
605
+ help="Column name for output text (default: markdown, for cross-model consistency)",
606
+ )
607
+ parser.add_argument(
608
+ "--overwrite",
609
+ action="store_true",
610
+ help="Replace the output column if it already exists in the input dataset "
611
+ "(default: error out to avoid clobbering an existing column).",
612
+ )
613
+ parser.add_argument(
614
+ "--dry-run",
615
+ action="store_true",
616
+ help="Run OCR but do NOT push to the Hub (local smoke testing).",
617
+ )
618
+ parser.add_argument(
619
+ "--verbose",
620
+ action="store_true",
621
+ help="Log resolved package versions after processing (useful for pinning deps)",
622
+ )
623
+
624
+ args = parser.parse_args()
625
+
626
+ main(
627
+ input_dataset=args.input_dataset,
628
+ output_dataset=args.output_dataset,
629
+ image_column=args.image_column,
630
+ lang=args.lang,
631
+ psm=args.psm,
632
+ oem=args.oem,
633
+ num_workers=args.num_workers,
634
+ hf_token=args.hf_token,
635
+ split=args.split,
636
+ max_samples=args.max_samples,
637
+ private=args.private,
638
+ shuffle=args.shuffle,
639
+ seed=args.seed,
640
+ output_column=args.output_column,
641
+ overwrite=args.overwrite,
642
+ dry_run=args.dry_run,
643
+ verbose=args.verbose,
644
+ config=args.config,
645
+ create_pr=args.create_pr,
646
+ )