davanstrien HF Staff commited on
Commit
d540881
·
verified ·
1 Parent(s): 5fd3fbe

Sync from GitHub via hub-sync

Browse files
Files changed (2) hide show
  1. README.md +3 -1
  2. pp-ocrv6.py +1041 -0
README.md CHANGED
@@ -49,7 +49,8 @@ _Sorted by model size:_
49
 
50
  | Script | Model | Size | Backend | Notes |
51
  |--------|-------|------|---------|-------|
52
- | `falcon-ocr.py` | [Falcon-OCR](https://huggingface.co/tiiuae/Falcon-OCR) | 0.3B | falcon-perception | Smallest in collection. #1 on multi-column docs and tables (olmOCR), Apache 2.0 |
 
53
  | `smoldocling-ocr.py` | [SmolDocling](https://huggingface.co/ds4sd/SmolDocling-256M-preview) | 256M | Transformers | DocTags structured output |
54
  | `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 |
55
  | `glm-ocr.py` | [GLM-OCR](https://huggingface.co/zai-org/GLM-OCR) | 0.9B | vLLM | 94.62% OmniDocBench V1.5 |
@@ -202,6 +203,7 @@ Beyond the shared flags, some models add their own. Run `--help` on any script f
202
  | Script | Extra options |
203
  |--------|---------------|
204
  | `surya-ocr.py` | `--task ocr\|layout\|table`, `--table-mode full\|simple`, `--pdf-column`/`--page-range`, `--blocks-column` |
 
205
  | `glm-ocr.py` | `--task ocr\|formula\|table` |
206
  | `paddleocr-vl.py` | `--task-mode ocr\|table\|formula\|chart` |
207
  | `paddleocr-vl-1.5.py` | `--task-mode ocr\|table\|formula\|chart\|spotting\|seal` |
 
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 |
56
  | `glm-ocr.py` | [GLM-OCR](https://huggingface.co/zai-org/GLM-OCR) | 0.9B | vLLM | 94.62% OmniDocBench V1.5 |
 
203
  | Script | Extra options |
204
  |--------|---------------|
205
  | `surya-ocr.py` | `--task ocr\|layout\|table`, `--table-mode full\|simple`, `--pdf-column`/`--page-range`, `--blocks-column` |
206
+ | `pp-ocrv6.py` | `--model-tier tiny\|small\|medium` (1.5M–34.5M params) |
207
  | `glm-ocr.py` | `--task ocr\|formula\|table` |
208
  | `paddleocr-vl.py` | `--task-mode ocr\|table\|formula\|chart` |
209
  | `paddleocr-vl-1.5.py` | `--task-mode ocr\|table\|formula\|chart\|spotting\|seal` |
pp-ocrv6.py ADDED
@@ -0,0 +1,1041 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.10"
3
+ # dependencies = [
4
+ # "paddlepaddle-gpu>=3.0.0",
5
+ # "paddleocr>=3.7.0",
6
+ # "paddlex[ocr]>=3.7.0",
7
+ # "opencv-contrib-python-headless",
8
+ # "datasets>=3.1.0",
9
+ # "huggingface-hub",
10
+ # "pillow",
11
+ # "numpy",
12
+ # "tqdm",
13
+ # ]
14
+ #
15
+ # [tool.uv]
16
+ # # PaddleOCR/PaddleX pull in opencv-contrib-python (full) which needs system
17
+ # # libGL.so.1 — not present in the slim uv-on-bookworm image used by HF Jobs.
18
+ # # Swap to the headless cv2 variant (same `import cv2`, no GUI deps). A matching
19
+ # # importlib.metadata patch in main() makes paddlex recognise the headless name.
20
+ # override-dependencies = [
21
+ # "opencv-contrib-python ; python_version < '0'",
22
+ # "opencv-python ; python_version < '0'",
23
+ # ]
24
+ #
25
+ # [[tool.uv.index]]
26
+ # name = "paddle"
27
+ # url = "https://www.paddlepaddle.org.cn/packages/stable/cu126/"
28
+ # explicit = true
29
+ #
30
+ # [tool.uv.sources]
31
+ # paddlepaddle-gpu = { index = "paddle" }
32
+ # ///
33
+ """
34
+ OCR images with PP-OCRv6 — a lightweight detection+recognition pipeline from
35
+ PaddlePaddle. Three tiers from **1.5M to 34.5M parameters**.
36
+
37
+ Unlike the VLM-based OCR recipes here, PP-OCRv6 is a **classical det+rec pipeline**
38
+ that outputs **plain text** (not markdown). At 1.5M-34.5M params it's far smaller
39
+ than the VLM OCRs and runs on a cheap t4-small GPU.
40
+
41
+ Model tiers (pick with `--model-tier`):
42
+ tiny 1.5M params (0.4M det + 1.1M rec) 49 languages, ~73% recognition
43
+ small 7.7M params (2.5M det + 5.3M rec) 50 languages, ~81% recognition
44
+ medium 34.5M params (22M det + 19M rec) 50 languages, ~83% recognition
45
+
46
+ All tiers are Apache 2.0 licensed. Runs via PaddleOCR's default Paddle engine
47
+ (`paddle_static`) — same proven header pattern as `pp-doclayout.py`.
48
+
49
+ HF Jobs examples:
50
+
51
+ # Tiny on a cheap GPU
52
+ hf jobs uv run --flavor t4-small -s HF_TOKEN \\
53
+ https://huggingface.co/datasets/uv-scripts/ocr/raw/main/pp-ocrv6.py \\
54
+ INPUT_DATASET OUTPUT_DATASET \\
55
+ --model-tier tiny --max-samples 5
56
+
57
+ # Medium on a small GPU (recommended for quality)
58
+ hf jobs uv run --flavor t4-small -s HF_TOKEN \\
59
+ https://huggingface.co/datasets/uv-scripts/ocr/raw/main/pp-ocrv6.py \\
60
+ INPUT_DATASET OUTPUT_DATASET \\
61
+ --model-tier medium --max-samples 10
62
+
63
+ Models: PaddlePaddle/PP-OCRv6_<tier>_det + PP-OCRv6_<tier>_rec
64
+ Blog: https://huggingface.co/blog/PaddlePaddle/pp-ocrv6
65
+ """
66
+
67
+ import argparse
68
+ import io
69
+ import json
70
+ import logging
71
+ import os
72
+ import time
73
+ from dataclasses import dataclass
74
+ from datetime import datetime, timezone
75
+ from pathlib import Path
76
+ from typing import Any, Dict, Iterator, List, Optional, Tuple, Union
77
+
78
+ import numpy as np
79
+ from PIL import Image, UnidentifiedImageError
80
+ from tqdm.auto import tqdm
81
+
82
+ logging.basicConfig(level=logging.INFO)
83
+ logger = logging.getLogger(__name__)
84
+
85
+
86
+ # ---------------------------------------------------------------------------
87
+ # Constants
88
+ # ---------------------------------------------------------------------------
89
+
90
+ TIER_MODELS = {
91
+ "tiny": ("PP-OCRv6_tiny_det", "PP-OCRv6_tiny_rec"),
92
+ "small": ("PP-OCRv6_small_det", "PP-OCRv6_small_rec"),
93
+ "medium": ("PP-OCRv6_medium_det", "PP-OCRv6_medium_rec"),
94
+ }
95
+
96
+ TIER_PARAMS = {
97
+ "tiny": "1.5M (0.4M det + 1.1M rec)",
98
+ "small": "7.7M (2.5M det + 5.3M rec)",
99
+ "medium": "34.5M (22M det + 19M rec)",
100
+ }
101
+
102
+ TIER_LANGUAGES = {
103
+ "tiny": "49 languages (zh, zh-Hant, en + 46 Latin-script — no Japanese)",
104
+ "small": "50 languages (zh, zh-Hant, en, ja + 46 Latin-script)",
105
+ "medium": "50 languages (zh, zh-Hant, en, ja + 46 Latin-script)",
106
+ }
107
+
108
+ TIER_REC = {
109
+ "tiny": 73.5,
110
+ "small": 81.3,
111
+ "medium": 83.2,
112
+ }
113
+
114
+ BUCKET_PREFIX = "hf://buckets/"
115
+
116
+ IMAGE_EXTENSIONS = {
117
+ ".jpg", ".jpeg", ".png", ".tif", ".tiff", ".webp", ".bmp", ".jp2", ".j2k",
118
+ }
119
+
120
+
121
+ # ---------------------------------------------------------------------------
122
+ # URL helpers
123
+ # ---------------------------------------------------------------------------
124
+
125
+ def is_bucket_url(s: str) -> bool:
126
+ return s.startswith(BUCKET_PREFIX)
127
+
128
+
129
+ def parse_bucket_url(url: str) -> Tuple[str, str]:
130
+ if not is_bucket_url(url):
131
+ raise ValueError(f"Not a bucket URL: {url}")
132
+ rest = url[len(BUCKET_PREFIX):].strip("/")
133
+ parts = rest.split("/", 2)
134
+ if len(parts) < 2:
135
+ raise ValueError(f"Bucket URL must include namespace and bucket name: {url}")
136
+ bucket_id = f"{parts[0]}/{parts[1]}"
137
+ prefix = parts[2] if len(parts) > 2 else ""
138
+ return bucket_id, prefix
139
+
140
+
141
+ # ---------------------------------------------------------------------------
142
+ # Image helpers
143
+ # ---------------------------------------------------------------------------
144
+
145
+ def to_pil(image: Union[Image.Image, Dict[str, Any], str, bytes]) -> Image.Image:
146
+ if isinstance(image, Image.Image):
147
+ return image.convert("RGB")
148
+ if isinstance(image, dict) and "bytes" in image:
149
+ return Image.open(io.BytesIO(image["bytes"])).convert("RGB")
150
+ if isinstance(image, (bytes, bytearray)):
151
+ return Image.open(io.BytesIO(image)).convert("RGB")
152
+ if isinstance(image, str):
153
+ return Image.open(image).convert("RGB")
154
+ raise ValueError(f"Unsupported image type: {type(image)}")
155
+
156
+
157
+ def pil_to_array(pil_img: Image.Image) -> np.ndarray:
158
+ return np.asarray(pil_img, dtype=np.uint8)
159
+
160
+
161
+ # ---------------------------------------------------------------------------
162
+ # Result extraction
163
+ # ---------------------------------------------------------------------------
164
+
165
+ def extract_text(result: Any) -> Tuple[str, List[Dict[str, Any]]]:
166
+ """Pull text and per-line details from a PaddleOCR predict result.
167
+
168
+ Returns (concatenated_text, per_line_details) where per_line_details is
169
+ a list of dicts with keys: text, score, bbox (4-point detection polygon as
170
+ [[x1,y1],[x2,y2],[x3,y3],[x4,y4]] in input-image pixel coordinates).
171
+ """
172
+ payload = result.json if hasattr(result, "json") else result
173
+ res = payload.get("res", payload) if isinstance(payload, dict) else {}
174
+ rec_texts = res.get("rec_texts", []) or []
175
+ rec_scores = res.get("rec_scores", []) or []
176
+ dt_polys = res.get("dt_polys", []) or []
177
+
178
+ # Concatenate reading-order text lines (PaddleOCR returns them in order)
179
+ text = "\n".join(rec_texts)
180
+
181
+ per_line = []
182
+ for i, t in enumerate(rec_texts):
183
+ entry = {"text": t}
184
+ if i < len(rec_scores):
185
+ entry["score"] = float(rec_scores[i])
186
+ if i < len(dt_polys):
187
+ entry["bbox"] = [[float(c) for c in point] for point in dt_polys[i]]
188
+ per_line.append(entry)
189
+
190
+ return text, per_line
191
+
192
+
193
+ # ---------------------------------------------------------------------------
194
+ # Sources
195
+ # ---------------------------------------------------------------------------
196
+
197
+ @dataclass
198
+ class SourceItem:
199
+ key: str
200
+ image: Optional[Image.Image]
201
+ extras: Dict[str, Any]
202
+
203
+
204
+ def iter_dataset_images(
205
+ dataset_id: str,
206
+ image_column: str,
207
+ split: str,
208
+ shuffle: bool,
209
+ seed: int,
210
+ max_samples: Optional[int],
211
+ ):
212
+ from datasets import load_dataset
213
+
214
+ logger.info(f"Loading dataset: {dataset_id} (split={split})")
215
+ ds = load_dataset(dataset_id, split=split)
216
+
217
+ if image_column not in ds.column_names:
218
+ raise ValueError(
219
+ f"Column '{image_column}' not found. Available: {ds.column_names}"
220
+ )
221
+
222
+ if shuffle:
223
+ logger.info(f"Shuffling with seed {seed}")
224
+ ds = ds.shuffle(seed=seed)
225
+ if max_samples:
226
+ ds = ds.select(range(min(max_samples, len(ds))))
227
+ logger.info(f"Limited to {len(ds)} samples")
228
+
229
+ total = len(ds)
230
+
231
+ def gen() -> Iterator[SourceItem]:
232
+ failed = 0
233
+ for i in range(total):
234
+ try:
235
+ row = ds[i]
236
+ image = to_pil(row[image_column])
237
+ except (UnidentifiedImageError, OSError) as e:
238
+ # Still yield a placeholder so the output row stays aligned with
239
+ # the source row (the dataset sink writes results positionally).
240
+ failed += 1
241
+ logger.warning(
242
+ f"Unreadable image at row {i}: {type(e).__name__}: {e} "
243
+ f"— writing empty result"
244
+ )
245
+ yield SourceItem(key=f"row-{i:08d}", image=None, extras={"failed": True})
246
+ continue
247
+ yield SourceItem(key=f"row-{i:08d}", image=image, extras={})
248
+ if failed:
249
+ logger.info(f"{failed} unreadable image(s) written as empty results")
250
+
251
+ return gen(), total, ds
252
+
253
+
254
+ SOURCE_PATHS_SNAPSHOT = "_source_paths.json"
255
+
256
+
257
+ def _bucket_snapshot_path(output_url: str) -> Tuple[str, str]:
258
+ out_bucket_id, out_prefix = parse_bucket_url(output_url)
259
+ snapshot_key = (
260
+ f"{out_prefix}/{SOURCE_PATHS_SNAPSHOT}".lstrip("/")
261
+ if out_prefix
262
+ else SOURCE_PATHS_SNAPSHOT
263
+ )
264
+ return out_bucket_id, snapshot_key
265
+
266
+
267
+ def iter_bucket_images(
268
+ bucket_url: str,
269
+ shuffle: bool,
270
+ seed: int,
271
+ max_samples: Optional[int],
272
+ hf_token: Optional[str],
273
+ output_url: Optional[str] = None,
274
+ ) -> Tuple[Iterator[SourceItem], int]:
275
+ from huggingface_hub import HfApi, HfFileSystem
276
+
277
+ bucket_id, prefix = parse_bucket_url(bucket_url)
278
+ fs = HfFileSystem(token=hf_token)
279
+ base = f"{BUCKET_PREFIX}{bucket_id}/{prefix}".rstrip("/")
280
+
281
+ snapshot_bucket_id: Optional[str] = None
282
+ snapshot_key: Optional[str] = None
283
+ cached_paths: Optional[List[str]] = None
284
+
285
+ if output_url and is_bucket_url(output_url):
286
+ snapshot_bucket_id, snapshot_key = _bucket_snapshot_path(output_url)
287
+ snapshot_url = f"{BUCKET_PREFIX}{snapshot_bucket_id}/{snapshot_key}"
288
+ try:
289
+ with fs.open(snapshot_url, "rb") as f:
290
+ snapshot = json.load(f)
291
+ mismatches = []
292
+ if snapshot.get("source_url") != bucket_url:
293
+ mismatches.append(
294
+ f"source_url ({snapshot.get('source_url')!r} vs {bucket_url!r})"
295
+ )
296
+ if snapshot.get("shuffle") != shuffle:
297
+ mismatches.append(f"shuffle ({snapshot.get('shuffle')} vs {shuffle})")
298
+ if shuffle and snapshot.get("seed") != seed:
299
+ mismatches.append(f"seed ({snapshot.get('seed')} vs {seed})")
300
+ if snapshot.get("max_samples") != max_samples:
301
+ mismatches.append(
302
+ f"max_samples ({snapshot.get('max_samples')} vs {max_samples})"
303
+ )
304
+ if mismatches:
305
+ logger.warning(
306
+ "Existing snapshot params differ from this run ("
307
+ + "; ".join(mismatches)
308
+ + "); ignoring snapshot and re-listing."
309
+ )
310
+ else:
311
+ cached_paths = snapshot["paths"]
312
+ logger.info(
313
+ f"Reusing existing snapshot of {len(cached_paths)} source paths "
314
+ f"(written {snapshot.get('created_at', 'unknown')})"
315
+ )
316
+ except FileNotFoundError:
317
+ pass
318
+ except Exception as e:
319
+ logger.warning(f"Could not read existing snapshot ({e}); re-listing.")
320
+
321
+ if cached_paths is not None:
322
+ all_paths = cached_paths
323
+ else:
324
+ logger.info(f"Listing images under {base}")
325
+ all_paths = []
326
+ try:
327
+ for entry in fs.find(base, detail=False):
328
+ ext = Path(entry).suffix.lower()
329
+ if ext in IMAGE_EXTENSIONS:
330
+ all_paths.append(entry)
331
+ except FileNotFoundError as e:
332
+ raise ValueError(f"Bucket prefix not found: {base}") from e
333
+
334
+ if not all_paths:
335
+ raise ValueError(
336
+ f"No image files (any of {sorted(IMAGE_EXTENSIONS)}) under {base}"
337
+ )
338
+
339
+ all_paths.sort()
340
+ if shuffle:
341
+ rng = np.random.default_rng(seed)
342
+ rng.shuffle(all_paths)
343
+ if max_samples:
344
+ all_paths = all_paths[:max_samples]
345
+
346
+ if snapshot_bucket_id is not None and snapshot_key is not None:
347
+ api = HfApi(token=hf_token)
348
+ payload = {
349
+ "source_url": bucket_url,
350
+ "shuffle": shuffle,
351
+ "seed": seed,
352
+ "max_samples": max_samples,
353
+ "created_at": datetime.now(timezone.utc).isoformat(),
354
+ "paths": all_paths,
355
+ }
356
+ api.batch_bucket_files(
357
+ snapshot_bucket_id,
358
+ add=[(json.dumps(payload).encode(), snapshot_key)],
359
+ token=hf_token,
360
+ )
361
+ logger.info(
362
+ f"Wrote source-path snapshot ({len(all_paths)} paths) to "
363
+ f"hf://buckets/{snapshot_bucket_id}/{snapshot_key}"
364
+ )
365
+
366
+ total = len(all_paths)
367
+ logger.info(f"Found {total} images in bucket")
368
+
369
+ def key_for(path: str) -> str:
370
+ return path
371
+
372
+ def gen() -> Iterator[SourceItem]:
373
+ skipped = 0
374
+ for path in all_paths:
375
+ try:
376
+ with fs.open(path, "rb") as f:
377
+ data = f.read()
378
+ image = to_pil(data)
379
+ except (UnidentifiedImageError, OSError) as e:
380
+ skipped += 1
381
+ logger.warning(
382
+ f"Skipping unreadable image {path}: {type(e).__name__}: {e}"
383
+ )
384
+ continue
385
+ yield SourceItem(key=key_for(path), image=image, extras={})
386
+ if skipped:
387
+ logger.info(f"Skipped {skipped} unreadable image(s) total")
388
+
389
+ return gen(), total
390
+
391
+
392
+ # ---------------------------------------------------------------------------
393
+ # Sinks
394
+ # ---------------------------------------------------------------------------
395
+
396
+ class DatasetRepoSink:
397
+ def __init__(
398
+ self,
399
+ repo_id: str,
400
+ *,
401
+ hf_token: Optional[str],
402
+ private: bool,
403
+ config: Optional[str],
404
+ create_pr: bool,
405
+ source_id: str,
406
+ original_dataset=None,
407
+ ):
408
+ self.repo_id = repo_id
409
+ self.hf_token = hf_token
410
+ self.private = private
411
+ self.config = config
412
+ self.create_pr = create_pr
413
+ self.source_id = source_id
414
+ self.original_dataset = original_dataset
415
+ self._texts: List[str] = []
416
+ self._blocks: List[str] = []
417
+
418
+ @property
419
+ def kind(self) -> str:
420
+ return "dataset"
421
+
422
+ def already_done(self) -> set:
423
+ return set()
424
+
425
+ def write(self, key: str, text: str, blocks: List[Dict[str, Any]]) -> None:
426
+ self._texts.append(text)
427
+ self._blocks.append(json.dumps(blocks, ensure_ascii=False))
428
+
429
+ def finalize(self, tier: str, det_model: str, rec_model: str, args_dict: Dict[str, Any]) -> None:
430
+ from datasets import Dataset
431
+
432
+ if self.original_dataset is not None:
433
+ if len(self._texts) != len(self.original_dataset):
434
+ logger.warning(
435
+ f"Text count ({len(self._texts)}) != dataset rows "
436
+ f"({len(self.original_dataset)}); padding with empty strings."
437
+ )
438
+ while len(self._texts) < len(self.original_dataset):
439
+ self._texts.append("")
440
+ self._blocks.append("[]")
441
+ ds = self.original_dataset.add_column("text", self._texts)
442
+ ds = ds.add_column("pp_ocr_blocks", self._blocks)
443
+ else:
444
+ if not self._texts:
445
+ logger.warning("No rows produced; nothing to push.")
446
+ return
447
+ ds = Dataset.from_list([
448
+ {"source_path": None, "text": t, "pp_ocr_blocks": b}
449
+ for t, b in zip(self._texts, self._blocks)
450
+ ])
451
+
452
+ inference_entry = build_inference_entry(tier, det_model, rec_model, args_dict)
453
+
454
+ if "inference_info" in ds.column_names:
455
+ logger.info("Updating existing inference_info column")
456
+
457
+ def _update(example):
458
+ try:
459
+ existing = (
460
+ json.loads(example["inference_info"])
461
+ if example["inference_info"]
462
+ else []
463
+ )
464
+ except (json.JSONDecodeError, TypeError):
465
+ existing = []
466
+ existing.append(inference_entry)
467
+ return {"inference_info": json.dumps(existing)}
468
+
469
+ ds = ds.map(_update)
470
+ else:
471
+ ds = ds.add_column(
472
+ "inference_info", [json.dumps([inference_entry])] * len(ds)
473
+ )
474
+
475
+ logger.info(f"Pushing {len(ds)} rows to {self.repo_id}")
476
+ push_kwargs = {
477
+ "private": self.private,
478
+ "token": self.hf_token,
479
+ "max_shard_size": "500MB",
480
+ "create_pr": self.create_pr,
481
+ "commit_message": f"Add PP-OCRv6-{tier} OCR results ({len(ds)} samples)"
482
+ + (f" [{self.config}]" if self.config else ""),
483
+ }
484
+ if self.config:
485
+ push_kwargs["config_name"] = self.config
486
+
487
+ max_retries = 3
488
+ for attempt in range(1, max_retries + 1):
489
+ try:
490
+ if attempt > 1:
491
+ logger.warning("Disabling XET (fallback to HTTP upload)")
492
+ os.environ["HF_HUB_DISABLE_XET"] = "1"
493
+ ds.push_to_hub(self.repo_id, **push_kwargs)
494
+ break
495
+ except Exception as e:
496
+ logger.error(f"Upload attempt {attempt}/{max_retries} failed: {e}")
497
+ if attempt == max_retries:
498
+ logger.error("All upload attempts failed.")
499
+ raise
500
+ time.sleep(30 * (2 ** (attempt - 1)))
501
+
502
+ from huggingface_hub import DatasetCard
503
+
504
+ card = DatasetCard(
505
+ create_dataset_card(
506
+ source=self.source_id,
507
+ tier=tier,
508
+ det_model=det_model,
509
+ rec_model=rec_model,
510
+ num_samples=len(ds),
511
+ processing_time=args_dict["processing_time"],
512
+ engine=args_dict.get("engine", "paddle_static"),
513
+ output_id=self.repo_id,
514
+ )
515
+ )
516
+ card.push_to_hub(self.repo_id, token=self.hf_token)
517
+ logger.info(f"Done: https://huggingface.co/datasets/{self.repo_id}")
518
+
519
+
520
+ class BucketShardSink:
521
+ METADATA_FILE = "_metadata.json"
522
+ SHARD_PATTERN = "shard-{:05d}.parquet"
523
+
524
+ def __init__(
525
+ self,
526
+ bucket_url: str,
527
+ *,
528
+ hf_token: Optional[str],
529
+ shard_size: int,
530
+ resume: bool,
531
+ source_id: str,
532
+ ):
533
+ from huggingface_hub import HfApi, HfFileSystem, create_bucket
534
+
535
+ self.bucket_url = bucket_url
536
+ self.bucket_id, self.prefix = parse_bucket_url(bucket_url)
537
+ self.hf_token = hf_token
538
+ self.shard_size = shard_size
539
+ self.resume = resume
540
+ self.source_id = source_id
541
+
542
+ self._api = HfApi(token=hf_token)
543
+ self._fs = HfFileSystem(token=hf_token)
544
+
545
+ try:
546
+ create_bucket(self.bucket_id, exist_ok=True, token=hf_token)
547
+ except Exception as e:
548
+ logger.warning(f"create_bucket('{self.bucket_id}') warning: {e}")
549
+
550
+ self._buffer: List[Dict[str, Any]] = []
551
+ self._next_shard_idx = self._discover_next_shard_idx()
552
+ self._completed_keys = self._discover_completed_keys() if resume else set()
553
+ if self._completed_keys:
554
+ logger.info(
555
+ f"Resume: found {len(self._completed_keys)} already-processed keys, will skip them"
556
+ )
557
+
558
+ @property
559
+ def kind(self) -> str:
560
+ return "bucket"
561
+
562
+ def already_done(self) -> set:
563
+ return self._completed_keys
564
+
565
+ def _shard_path(self, idx: int) -> str:
566
+ return self._join(self.SHARD_PATTERN.format(idx))
567
+
568
+ def _join(self, name: str) -> str:
569
+ return f"{self.prefix}/{name}".lstrip("/") if self.prefix else name
570
+
571
+ def _list_existing_shards(self) -> List[str]:
572
+ try:
573
+ tree = self._api.list_bucket_tree(
574
+ self.bucket_id, prefix=self.prefix or None, recursive=True
575
+ )
576
+ except Exception:
577
+ return []
578
+ shards: List[str] = []
579
+ for item in tree:
580
+ path = getattr(item, "path", None)
581
+ ftype = getattr(item, "type", None)
582
+ if not path or ftype not in (None, "file"):
583
+ continue
584
+ base = Path(path).name
585
+ if base.startswith("shard-") and base.endswith(".parquet"):
586
+ shards.append(path)
587
+ return sorted(shards)
588
+
589
+ def _discover_next_shard_idx(self) -> int:
590
+ shards = self._list_existing_shards()
591
+ max_idx = -1
592
+ for s in shards:
593
+ stem = Path(s).stem
594
+ try:
595
+ max_idx = max(max_idx, int(stem.split("-")[-1]))
596
+ except ValueError:
597
+ continue
598
+ return max_idx + 1
599
+
600
+ def _discover_completed_keys(self) -> set:
601
+ import pyarrow.parquet as pq
602
+
603
+ keys: set = set()
604
+ for shard_path in self._list_existing_shards():
605
+ full = f"{BUCKET_PREFIX}{self.bucket_id}/{shard_path}"
606
+ try:
607
+ with self._fs.open(full, "rb") as f:
608
+ table = pq.read_table(f, columns=["__source_key"])
609
+ keys.update(table.column("__source_key").to_pylist())
610
+ except Exception as e:
611
+ logger.warning(f"Could not read keys from {shard_path}: {e}")
612
+ return keys
613
+
614
+ def _flush(self) -> None:
615
+ if not self._buffer:
616
+ return
617
+ import pyarrow as pa
618
+ import pyarrow.parquet as pq
619
+
620
+ columns = ["__source_key", "text", "pp_ocr_blocks"]
621
+ table_dict = {c: [row.get(c) for row in self._buffer] for c in columns}
622
+ table = pa.Table.from_pydict(table_dict)
623
+
624
+ buf = io.BytesIO()
625
+ pq.write_table(table, buf, compression="zstd")
626
+ data = buf.getvalue()
627
+
628
+ shard_remote = self._shard_path(self._next_shard_idx)
629
+ logger.info(
630
+ f"Writing shard {self._next_shard_idx} ({len(self._buffer)} rows, "
631
+ f"{len(data) / 1024 / 1024:.1f} MiB) to {shard_remote}"
632
+ )
633
+ self._api.batch_bucket_files(
634
+ self.bucket_id, add=[(data, shard_remote)], token=self.hf_token
635
+ )
636
+ self._next_shard_idx += 1
637
+ self._buffer.clear()
638
+
639
+ def write(self, key: str, text: str, blocks: List[Dict[str, Any]]) -> None:
640
+ row: Dict[str, Any] = {
641
+ "__source_key": key,
642
+ "text": text,
643
+ "pp_ocr_blocks": json.dumps(blocks, ensure_ascii=False),
644
+ }
645
+ self._buffer.append(row)
646
+ if len(self._buffer) >= self.shard_size:
647
+ self._flush()
648
+
649
+ def finalize(self, tier: str, det_model: str, rec_model: str, args_dict: Dict[str, Any]) -> None:
650
+ self._flush()
651
+ meta = {
652
+ "model": f"PP-OCRv6_{tier}",
653
+ "det_model": det_model,
654
+ "rec_model": rec_model,
655
+ "tier": tier,
656
+ "engine": "paddle_static",
657
+ "source": self.source_id,
658
+ "shard_size": args_dict["shard_size"],
659
+ "last_run_at": datetime.now(timezone.utc).isoformat(),
660
+ "processing_time": args_dict.get("processing_time"),
661
+ }
662
+ meta_bytes = json.dumps(meta, indent=2).encode("utf-8")
663
+ meta_path = self._join(self.METADATA_FILE)
664
+ self._api.batch_bucket_files(
665
+ self.bucket_id, add=[(meta_bytes, meta_path)], token=self.hf_token
666
+ )
667
+ logger.info(
668
+ f"Done: https://huggingface.co/buckets/{self.bucket_id}"
669
+ + (f"/{self.prefix}" if self.prefix else "")
670
+ )
671
+
672
+
673
+ # ---------------------------------------------------------------------------
674
+ # inference_info + dataset card
675
+ # ---------------------------------------------------------------------------
676
+
677
+ def build_inference_entry(tier: str, det_model: str, rec_model: str, args_dict: Dict[str, Any]) -> Dict[str, Any]:
678
+ return {
679
+ "model_id": f"PaddlePaddle/PP-OCRv6_{tier}",
680
+ "det_model": det_model,
681
+ "rec_model": rec_model,
682
+ "tier": tier,
683
+ "params": TIER_PARAMS.get(tier, "unknown"),
684
+ "rec_accuracy_pct": TIER_REC.get(tier),
685
+ "languages": TIER_LANGUAGES.get(tier, ""),
686
+ "engine": "paddle_static",
687
+ "output_column": "text",
688
+ "blocks_column": "pp_ocr_blocks",
689
+ "timestamp": datetime.now(timezone.utc).isoformat(),
690
+ }
691
+
692
+
693
+ def create_dataset_card(
694
+ source: str,
695
+ tier: str,
696
+ det_model: str,
697
+ rec_model: str,
698
+ num_samples: int,
699
+ processing_time: str,
700
+ engine: str,
701
+ output_id: str,
702
+ ) -> str:
703
+ tier_display = tier.upper() if tier == "tiny" else tier.capitalize()
704
+ if is_bucket_url(source):
705
+ source_link = f"[{source}]({source})"
706
+ else:
707
+ source_link = f"[{source}](https://huggingface.co/datasets/{source})"
708
+
709
+ return f"""---
710
+ tags:
711
+ - ocr
712
+ - text-recognition
713
+ - paddleocr
714
+ - pp-ocrv6
715
+ - uv-script
716
+ - generated
717
+ ---
718
+
719
+ # OCR with PP-OCRv6 {tier_display}
720
+
721
+ Plain-text OCR results for images from {source_link}, produced by
722
+ PaddlePaddle's [PP-OCRv6](https://huggingface.co/collections/PaddlePaddle/pp-ocrv6)
723
+ {tier} pipeline ({TIER_PARAMS.get(tier, "unknown")}).
724
+
725
+ ## Processing details
726
+
727
+ - **Source**: {source_link}
728
+ - **Model**: PP-OCRv6_{tier} ({det_model} + {rec_model})
729
+ - **Tier**: {tier} ({TIER_PARAMS.get(tier, "unknown")})
730
+ - **Recognition accuracy**: {TIER_REC.get(tier, "?"):.1f}%
731
+ - **Languages**: {TIER_LANGUAGES.get(tier, "")}
732
+ - **Engine**: {engine}
733
+ - **Samples**: {num_samples:,}
734
+ - **Processing time**: {processing_time}
735
+ - **Processing date**: {datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")}
736
+ - **License**: Apache 2.0 (models)
737
+
738
+ ## Schema
739
+
740
+ Each row contains the original columns plus:
741
+
742
+ - `text`: Plain text extracted from the image (reading-order concatenation of
743
+ detected text lines, newline-separated).
744
+ - `pp_ocr_blocks`: JSON list, one dict per detected text line:
745
+ ```json
746
+ [
747
+ {{
748
+ "text": "recognized text",
749
+ "score": 0.987,
750
+ "bbox": [[x1, y1], [x2, y2], [x3, y3], [x4, y4]]
751
+ }}
752
+ ]
753
+ ```
754
+ `score` is the recognition confidence and `bbox` is the detection polygon
755
+ (4-point quadrilateral in input-image pixel coordinates).
756
+ - `inference_info`: JSON list tracking every model applied to this dataset.
757
+
758
+ > **Note:** PP-OCRv6 is a classical detection+recognition pipeline, not a VLM.
759
+ > It outputs **plain text** rather than markdown. Per-line bounding boxes and
760
+ > confidence scores are available in `pp_ocr_blocks`.
761
+
762
+ ## Usage
763
+
764
+ ```python
765
+ import json
766
+ from datasets import load_dataset
767
+
768
+ ds = load_dataset("{output_id}", split="train")
769
+ print(ds[0]["text"])
770
+ for block in json.loads(ds[0]["pp_ocr_blocks"]):
771
+ print(block["text"], block["score"])
772
+ ```
773
+
774
+ ## Reproduction
775
+
776
+ ```bash
777
+ hf jobs uv run --flavor t4-small -s HF_TOKEN \\
778
+ https://huggingface.co/datasets/uv-scripts/ocr/raw/main/pp-ocrv6.py \\
779
+ {source} <output> --model-tier {tier}
780
+ ```
781
+
782
+ Generated with [UV Scripts](https://huggingface.co/uv-scripts).
783
+ """
784
+
785
+
786
+ # ---------------------------------------------------------------------------
787
+ # Main
788
+ # ---------------------------------------------------------------------------
789
+
790
+ def main(args: argparse.Namespace) -> None:
791
+ from huggingface_hub import login
792
+
793
+ start_time = datetime.now()
794
+ hf_token = args.hf_token or os.environ.get("HF_TOKEN")
795
+ if hf_token:
796
+ login(token=hf_token)
797
+
798
+ # ---------- tier → model names ----------
799
+ if args.model_tier not in TIER_MODELS:
800
+ raise ValueError(
801
+ f"Invalid tier {args.model_tier!r}. Choose from: {list(TIER_MODELS)}"
802
+ )
803
+ det_model, rec_model = TIER_MODELS[args.model_tier]
804
+ tier = args.model_tier
805
+ logger.info(f"PP-OCRv6 {tier}: {det_model} + {rec_model}")
806
+
807
+ # ---------- source ----------
808
+ original_dataset = None
809
+ if is_bucket_url(args.input_source):
810
+ src_iter, total = iter_bucket_images(
811
+ args.input_source,
812
+ shuffle=args.shuffle,
813
+ seed=args.seed,
814
+ max_samples=args.max_samples,
815
+ hf_token=hf_token,
816
+ output_url=args.output_target,
817
+ )
818
+ else:
819
+ src_iter, total, original_dataset = iter_dataset_images(
820
+ args.input_source,
821
+ image_column=args.image_column,
822
+ split=args.split,
823
+ shuffle=args.shuffle,
824
+ seed=args.seed,
825
+ max_samples=args.max_samples,
826
+ )
827
+
828
+ # ---------- sink ----------
829
+ if is_bucket_url(args.output_target):
830
+ sink: Union[BucketShardSink, DatasetRepoSink] = BucketShardSink(
831
+ args.output_target,
832
+ hf_token=hf_token,
833
+ shard_size=args.shard_size,
834
+ resume=not args.no_resume,
835
+ source_id=args.input_source,
836
+ )
837
+ else:
838
+ sink = DatasetRepoSink(
839
+ args.output_target,
840
+ hf_token=hf_token,
841
+ private=args.private,
842
+ config=args.config,
843
+ create_pr=args.create_pr,
844
+ source_id=args.input_source,
845
+ original_dataset=original_dataset,
846
+ )
847
+
848
+ completed = sink.already_done()
849
+
850
+ # ---------- model ----------
851
+ # PaddleX gates `import cv2` at module load time on
852
+ # `is_dep_available("opencv-contrib-python")`, which checks
853
+ # `importlib.metadata.version(...)`. We ship `opencv-contrib-python-headless`
854
+ # (same `cv2`, no system libGL.so.1 needed) — but that's a different
855
+ # distribution name, so the gate fails and the OCR pipeline's `ocr` extra
856
+ # check returns False. Patch the metadata lookup to alias the GUI cv2 distros
857
+ # to the headless variant before importing paddleocr; this lets paddlex's own
858
+ # `import cv2` succeed and `is_extra_available('ocr')` return True.
859
+ import importlib.metadata as _metadata
860
+
861
+ _orig_metadata_version = _metadata.version
862
+
863
+ def _patched_metadata_version(dep_name):
864
+ if dep_name in ("opencv-contrib-python", "opencv-python"):
865
+ for headless_alias in (
866
+ "opencv-contrib-python-headless",
867
+ "opencv-python-headless",
868
+ ):
869
+ try:
870
+ return _orig_metadata_version(headless_alias)
871
+ except _metadata.PackageNotFoundError:
872
+ continue
873
+ return _orig_metadata_version(dep_name)
874
+
875
+ _metadata.version = _patched_metadata_version
876
+
877
+ # Silence the connectivity check for speed (not needed in a Job)
878
+ os.environ.setdefault("PADDLE_PDX_DISABLE_MODEL_SOURCE_CHECK", "True")
879
+
880
+ from paddleocr import PaddleOCR
881
+
882
+ ocr = PaddleOCR(
883
+ text_detection_model_name=det_model,
884
+ text_recognition_model_name=rec_model,
885
+ use_doc_orientation_classify=False,
886
+ use_doc_unwarping=False,
887
+ use_textline_orientation=False,
888
+ )
889
+
890
+ # ---------- loop ----------
891
+ processed = 0
892
+ skipped = 0
893
+ errors = 0
894
+ pbar = tqdm(src_iter, total=total, desc=f"PP-OCRv6 {tier}")
895
+ for item in pbar:
896
+ if item.key in completed:
897
+ skipped += 1
898
+ continue
899
+ if item.extras.get("failed") or item.image is None:
900
+ # Unreadable source image — write an empty result in position so the
901
+ # output stays row-aligned with the source dataset.
902
+ sink.write(item.key, "", [])
903
+ errors += 1
904
+ processed += 1
905
+ continue
906
+ try:
907
+ arr = pil_to_array(item.image)
908
+ result = ocr.predict(arr)
909
+ if result:
910
+ text, blocks = extract_text(result[0])
911
+ else:
912
+ text, blocks = "", []
913
+ except Exception as e:
914
+ logger.error(f"Error on {item.key}: {e}")
915
+ text, blocks = "", []
916
+ errors += 1
917
+
918
+ sink.write(item.key, text, blocks)
919
+ processed += 1
920
+
921
+ duration = datetime.now() - start_time
922
+ processing_time_str = f"{duration.total_seconds() / 60:.2f} min"
923
+ logger.info(
924
+ f"Processed {processed} (skipped {skipped}, errors {errors}) in {processing_time_str}"
925
+ )
926
+
927
+ args_dict = {
928
+ "tier": tier,
929
+ "det_model": det_model,
930
+ "rec_model": rec_model,
931
+ "engine": "paddle_static",
932
+ "shard_size": args.shard_size,
933
+ "processing_time": processing_time_str,
934
+ }
935
+ sink.finalize(
936
+ tier=tier,
937
+ det_model=det_model,
938
+ rec_model=rec_model,
939
+ args_dict=args_dict,
940
+ )
941
+
942
+ if args.verbose:
943
+ import importlib.metadata
944
+
945
+ logger.info("--- Resolved package versions ---")
946
+ for pkg in [
947
+ "paddleocr",
948
+ "paddlex",
949
+ "paddlepaddle-gpu",
950
+ "huggingface-hub",
951
+ "datasets",
952
+ "pillow",
953
+ "numpy",
954
+ ]:
955
+ try:
956
+ logger.info(f" {pkg}=={importlib.metadata.version(pkg)}")
957
+ except importlib.metadata.PackageNotFoundError:
958
+ logger.info(f" {pkg}: not installed")
959
+ logger.info("--- End versions ---")
960
+
961
+
962
+ # ---------------------------------------------------------------------------
963
+ # CLI
964
+ # ---------------------------------------------------------------------------
965
+
966
+ def build_parser() -> argparse.ArgumentParser:
967
+ p = argparse.ArgumentParser(
968
+ description="PP-OCRv6 OCR over an HF dataset or bucket of images.",
969
+ formatter_class=argparse.RawDescriptionHelpFormatter,
970
+ )
971
+ p.add_argument(
972
+ "input_source",
973
+ help="HF dataset id (namespace/dataset) OR hf://buckets/ns/bucket[/prefix]",
974
+ )
975
+ p.add_argument(
976
+ "output_target",
977
+ help="HF dataset id (namespace/dataset) OR hf://buckets/ns/bucket/run-name",
978
+ )
979
+ p.add_argument(
980
+ "--model-tier",
981
+ default="medium",
982
+ choices=list(TIER_MODELS),
983
+ help="PP-OCRv6 model tier: tiny (1.5M), small (7.7M), medium (34.5M). Default: medium.",
984
+ )
985
+ # Dataset-source-specific
986
+ p.add_argument(
987
+ "--image-column",
988
+ default="image",
989
+ help="Column containing images (dataset-repo source only, default: image)",
990
+ )
991
+ p.add_argument(
992
+ "--split",
993
+ default="train",
994
+ help="Dataset split (dataset-repo source only, default: train)",
995
+ )
996
+ p.add_argument(
997
+ "--max-samples", type=int, help="Limit number of samples (for testing)"
998
+ )
999
+ p.add_argument(
1000
+ "--shuffle", action="store_true", help="Shuffle source before processing"
1001
+ )
1002
+ p.add_argument(
1003
+ "--seed", type=int, default=42, help="Random seed for shuffle (default: 42)"
1004
+ )
1005
+ # Dataset-sink-specific
1006
+ p.add_argument(
1007
+ "--private", action="store_true", help="Private dataset output (dataset sink only)"
1008
+ )
1009
+ p.add_argument(
1010
+ "--config",
1011
+ help="Config/subset name when pushing to Hub (dataset sink only)",
1012
+ )
1013
+ p.add_argument(
1014
+ "--create-pr",
1015
+ action="store_true",
1016
+ help="Create PR instead of direct push (dataset sink only)",
1017
+ )
1018
+ # Bucket-sink-specific
1019
+ p.add_argument(
1020
+ "--shard-size",
1021
+ type=int,
1022
+ default=256,
1023
+ help="Rows per parquet shard for bucket sink (default: 256)",
1024
+ )
1025
+ p.add_argument(
1026
+ "--no-resume",
1027
+ action="store_true",
1028
+ help="Disable resume scan when writing to a bucket sink",
1029
+ )
1030
+ # Auth + diagnostics
1031
+ p.add_argument("--hf-token", help="Hugging Face API token (else uses HF_TOKEN env)")
1032
+ p.add_argument(
1033
+ "--verbose",
1034
+ action="store_true",
1035
+ help="Log resolved package versions at the end",
1036
+ )
1037
+ return p
1038
+
1039
+
1040
+ if __name__ == "__main__":
1041
+ main(build_parser().parse_args())