davanstrien HF Staff commited on
Commit
0ee733c
·
verified ·
1 Parent(s): 290b6d3

Fix GLM-OCR-v2: pin vllm>=0.16.0 stable, restore transformers>=5.1.0 override

Browse files
Files changed (1) hide show
  1. ocr/glm-ocr-v2.py +1000 -0
ocr/glm-ocr-v2.py ADDED
@@ -0,0 +1,1000 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.11"
3
+ # dependencies = [
4
+ # "datasets>=3.1.0",
5
+ # "pyarrow>=17.0.0,<18.0.0",
6
+ # "huggingface-hub",
7
+ # "pillow",
8
+ # "vllm>=0.16.0",
9
+ # "toolz",
10
+ # "torch",
11
+ # ]
12
+ #
13
+ # [tool.uv]
14
+ # override-dependencies = ["transformers>=5.1.0"]
15
+ # ///
16
+
17
+ """
18
+ Convert document images to markdown using GLM-OCR with vLLM.
19
+
20
+ v2: Incremental uploads via CommitScheduler + checkpoint/resume support.
21
+ Results are saved as parquet shards per batch and uploaded in the background,
22
+ so a crash or upload failure never loses completed OCR work. Use --resume to
23
+ pick up from the last completed batch after an interruption.
24
+
25
+ GLM-OCR is a compact 0.9B parameter OCR model achieving 94.62% on OmniDocBench V1.5.
26
+ Uses CogViT visual encoder with GLM-0.5B language decoder and Multi-Token Prediction
27
+ (MTP) loss for fast, accurate document parsing.
28
+
29
+ NOTE: Requires vLLM nightly wheels from cu129 variant (GLM-OCR added in v0.16.0,
30
+ PR #33005) and transformers>=5.1.0 (GLM-OCR support landed in stable release).
31
+ Uses https://wheels.vllm.ai/nightly/cu129 which has x86_64 wheels.
32
+ First run may take a few minutes to download and install dependencies.
33
+
34
+ Features:
35
+ - 0.9B parameters (ultra-compact)
36
+ - 94.62% on OmniDocBench V1.5 (SOTA for sub-1B models)
37
+ - Text recognition with markdown output
38
+ - LaTeX formula recognition
39
+ - Table extraction (HTML format)
40
+ - Multilingual: zh, en, fr, es, ru, de, ja, ko
41
+ - MIT licensed
42
+ - Incremental parquet uploads (v2) — never lose results
43
+ - Checkpoint/resume (v2) — pick up where you left off
44
+
45
+ Model: zai-org/GLM-OCR
46
+ vLLM: Requires vLLM nightly build + transformers>=5.1.0
47
+ Performance: 94.62% on OmniDocBench V1.5
48
+ """
49
+
50
+ import argparse
51
+ import base64
52
+ import io
53
+ import json
54
+ import logging
55
+ import os
56
+ import sys
57
+ import tempfile
58
+ import time
59
+ from datetime import datetime
60
+ from pathlib import Path
61
+ from typing import Any, Dict, List, Union
62
+
63
+ import torch
64
+ from datasets import load_dataset
65
+ from huggingface_hub import CommitScheduler, DatasetCard, HfApi, login
66
+ from PIL import Image
67
+ from toolz import partition_all
68
+ from vllm import LLM, SamplingParams
69
+
70
+ logging.basicConfig(level=logging.INFO)
71
+ logger = logging.getLogger(__name__)
72
+
73
+ MODEL = "zai-org/GLM-OCR"
74
+
75
+ # Task prompts as specified by the model
76
+ TASK_PROMPTS = {
77
+ "ocr": "Text Recognition:",
78
+ "formula": "Formula Recognition:",
79
+ "table": "Table Recognition:",
80
+ }
81
+
82
+ # Metadata keys that must match between runs for --resume
83
+ _RESUMABLE_KEYS = [
84
+ "input_dataset",
85
+ "split",
86
+ "shuffle",
87
+ "seed",
88
+ "max_samples",
89
+ "batch_size",
90
+ "source_dataset_sha",
91
+ "temperature",
92
+ "top_p",
93
+ "repetition_penalty",
94
+ "max_tokens",
95
+ "task",
96
+ "gpu_memory_utilization",
97
+ "max_model_len",
98
+ ]
99
+
100
+ METADATA_FILENAME = "_run_metadata.json"
101
+
102
+
103
+ class CleanupScheduler(CommitScheduler):
104
+ """CommitScheduler that deletes local parquet files after successful upload.
105
+
106
+ Prevents disk from filling up on long-running HF Jobs.
107
+ """
108
+
109
+ def push_to_hub(self):
110
+ parquet_files = list(self.folder_path.glob("train-*.parquet"))
111
+ if not parquet_files:
112
+ return None
113
+ result = super().push_to_hub()
114
+ if result is not None:
115
+ for f in parquet_files:
116
+ f.unlink(missing_ok=True)
117
+ logger.info(f"Cleaned up uploaded shard: {f.name}")
118
+ return result
119
+
120
+
121
+ def check_cuda_availability():
122
+ """Check if CUDA is available and exit if not."""
123
+ if not torch.cuda.is_available():
124
+ logger.error("CUDA is not available. This script requires a GPU.")
125
+ logger.error("Please run on a machine with a CUDA-capable GPU.")
126
+ sys.exit(1)
127
+ else:
128
+ logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
129
+
130
+
131
+ def make_ocr_message(
132
+ image: Union[Image.Image, Dict[str, Any], str],
133
+ task: str = "ocr",
134
+ ) -> List[Dict]:
135
+ """
136
+ Create chat message for OCR processing.
137
+
138
+ GLM-OCR uses a chat format with an image and a task prompt prefix.
139
+ Supported tasks: ocr, formula, table.
140
+ """
141
+ # Convert to PIL Image if needed
142
+ if isinstance(image, Image.Image):
143
+ pil_img = image
144
+ elif isinstance(image, dict) and "bytes" in image:
145
+ pil_img = Image.open(io.BytesIO(image["bytes"]))
146
+ elif isinstance(image, str):
147
+ pil_img = Image.open(image)
148
+ else:
149
+ raise ValueError(f"Unsupported image type: {type(image)}")
150
+
151
+ # Convert to RGB
152
+ pil_img = pil_img.convert("RGB")
153
+
154
+ # Convert to base64 data URI
155
+ buf = io.BytesIO()
156
+ pil_img.save(buf, format="PNG")
157
+ data_uri = f"data:image/png;base64,{base64.b64encode(buf.getvalue()).decode()}"
158
+
159
+ prompt_text = TASK_PROMPTS.get(task, TASK_PROMPTS["ocr"])
160
+
161
+ return [
162
+ {
163
+ "role": "user",
164
+ "content": [
165
+ {"type": "image_url", "image_url": {"url": data_uri}},
166
+ {"type": "text", "text": prompt_text},
167
+ ],
168
+ }
169
+ ]
170
+
171
+
172
+ def build_run_metadata(
173
+ *,
174
+ input_dataset: str,
175
+ split: str,
176
+ shuffle: bool,
177
+ seed: int,
178
+ max_samples: int | None,
179
+ batch_size: int,
180
+ source_dataset_sha: str,
181
+ temperature: float,
182
+ top_p: float,
183
+ repetition_penalty: float,
184
+ max_tokens: int,
185
+ task: str,
186
+ gpu_memory_utilization: float,
187
+ max_model_len: int,
188
+ total_batches: int,
189
+ total_samples: int,
190
+ model: str = MODEL,
191
+ ) -> dict:
192
+ """Build the run metadata dict for persistence."""
193
+ return {
194
+ "input_dataset": input_dataset,
195
+ "split": split,
196
+ "shuffle": shuffle,
197
+ "seed": seed,
198
+ "max_samples": max_samples,
199
+ "batch_size": batch_size,
200
+ "source_dataset_sha": source_dataset_sha,
201
+ "temperature": temperature,
202
+ "top_p": top_p,
203
+ "repetition_penalty": repetition_penalty,
204
+ "max_tokens": max_tokens,
205
+ "task": task,
206
+ "gpu_memory_utilization": gpu_memory_utilization,
207
+ "max_model_len": max_model_len,
208
+ "total_batches": total_batches,
209
+ "total_samples": total_samples,
210
+ "model": model,
211
+ "script": "glm-ocr-v2.py",
212
+ "created_at": datetime.now().isoformat(),
213
+ }
214
+
215
+
216
+ def save_run_metadata(metadata: dict, folder: Path) -> Path:
217
+ """Save run metadata to the staging folder."""
218
+ path = folder / METADATA_FILENAME
219
+ path.write_text(json.dumps(metadata, indent=2))
220
+ return path
221
+
222
+
223
+ def fetch_remote_metadata(api: HfApi, repo_id: str, token: str | None) -> dict | None:
224
+ """Download _run_metadata.json from the Hub dataset repo. Returns None if missing."""
225
+ try:
226
+ from huggingface_hub.utils import EntryNotFoundError
227
+
228
+ local_path = api.hf_hub_download(
229
+ repo_id=repo_id,
230
+ filename=f"data/{METADATA_FILENAME}",
231
+ repo_type="dataset",
232
+ token=token,
233
+ )
234
+ return json.loads(Path(local_path).read_text())
235
+ except (EntryNotFoundError, Exception) as e:
236
+ logger.debug(f"Could not fetch remote metadata: {e}")
237
+ return None
238
+
239
+
240
+ def find_completed_batches(api: HfApi, repo_id: str, token: str | None) -> set[int]:
241
+ """List completed batch numbers from existing parquet files on the Hub."""
242
+ completed = set()
243
+ try:
244
+ files = api.list_repo_tree(
245
+ repo_id=repo_id, path_in_repo="data", repo_type="dataset", token=token
246
+ )
247
+ for item in files:
248
+ name = item.rfilename if hasattr(item, "rfilename") else str(item)
249
+ # Extract batch number from e.g. "data/train-00003-of-00043.parquet"
250
+ basename = name.split("/")[-1] if "/" in name else name
251
+ if basename.startswith("train-") and basename.endswith(".parquet"):
252
+ try:
253
+ batch_num = int(basename.split("-")[1])
254
+ completed.add(batch_num)
255
+ except (IndexError, ValueError):
256
+ continue
257
+ except Exception as e:
258
+ logger.warning(f"Could not list remote files: {e}")
259
+ return completed
260
+
261
+
262
+ def verify_run_metadata(current: dict, remote: dict) -> list[str]:
263
+ """Compare current run params against saved metadata. Returns list of mismatches."""
264
+ mismatches = []
265
+ for key in _RESUMABLE_KEYS:
266
+ current_val = current.get(key)
267
+ remote_val = remote.get(key)
268
+ if current_val != remote_val:
269
+ mismatches.append(f" {key}: current={current_val!r}, saved={remote_val!r}")
270
+ return mismatches
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
+ gpu_memory_utilization: float,
282
+ temperature: float,
283
+ top_p: float,
284
+ task: str,
285
+ image_column: str = "image",
286
+ split: str = "train",
287
+ ) -> str:
288
+ """Create a dataset card documenting the OCR process."""
289
+ model_name = model.split("/")[-1]
290
+ task_desc = {
291
+ "ocr": "text recognition",
292
+ "formula": "formula recognition",
293
+ "table": "table recognition",
294
+ }
295
+
296
+ return f"""---
297
+ tags:
298
+ - ocr
299
+ - document-processing
300
+ - glm-ocr
301
+ - markdown
302
+ - uv-script
303
+ - generated
304
+ ---
305
+
306
+ # Document OCR using {model_name}
307
+
308
+ This dataset contains OCR results from images in [{source_dataset}](https://huggingface.co/datasets/{source_dataset}) using GLM-OCR, a compact 0.9B OCR model achieving SOTA performance.
309
+
310
+ ## Processing Details
311
+
312
+ - **Source Dataset**: [{source_dataset}](https://huggingface.co/datasets/{source_dataset})
313
+ - **Model**: [{model}](https://huggingface.co/{model})
314
+ - **Task**: {task_desc.get(task, task)}
315
+ - **Number of Samples**: {num_samples:,}
316
+ - **Processing Time**: {processing_time}
317
+ - **Processing Date**: {datetime.now().strftime("%Y-%m-%d %H:%M UTC")}
318
+
319
+ ### Configuration
320
+
321
+ - **Image Column**: `{image_column}`
322
+ - **Output Column**: `markdown`
323
+ - **Dataset Split**: `{split}`
324
+ - **Batch Size**: {batch_size}
325
+ - **Max Model Length**: {max_model_len:,} tokens
326
+ - **Max Output Tokens**: {max_tokens:,}
327
+ - **Temperature**: {temperature}
328
+ - **Top P**: {top_p}
329
+ - **GPU Memory Utilization**: {gpu_memory_utilization:.1%}
330
+
331
+ ## Model Information
332
+
333
+ GLM-OCR is a compact, high-performance OCR model:
334
+ - 0.9B parameters
335
+ - 94.62% on OmniDocBench V1.5
336
+ - CogViT visual encoder + GLM-0.5B language decoder
337
+ - Multi-Token Prediction (MTP) loss for efficiency
338
+ - Multilingual: zh, en, fr, es, ru, de, ja, ko
339
+ - MIT licensed
340
+
341
+ ## Dataset Structure
342
+
343
+ The dataset contains all original columns plus:
344
+ - `markdown`: The extracted text in markdown format
345
+ - `inference_info`: JSON list tracking all OCR models applied to this dataset
346
+
347
+ ## Reproduction
348
+
349
+ ```bash
350
+ uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/glm-ocr-v2.py \\
351
+ {source_dataset} \\
352
+ <output-dataset> \\
353
+ --image-column {image_column} \\
354
+ --batch-size {batch_size} \\
355
+ --task {task}
356
+ ```
357
+
358
+ Generated with [UV Scripts](https://huggingface.co/uv-scripts) (glm-ocr-v2.py)
359
+ """
360
+
361
+
362
+ def main(
363
+ input_dataset: str,
364
+ output_dataset: str,
365
+ image_column: str = "image",
366
+ batch_size: int = 16,
367
+ max_model_len: int = 8192,
368
+ max_tokens: int = 8192,
369
+ temperature: float = 0.01,
370
+ top_p: float = 0.00001,
371
+ repetition_penalty: float = 1.1,
372
+ gpu_memory_utilization: float = 0.8,
373
+ task: str = "ocr",
374
+ hf_token: str = None,
375
+ split: str = "train",
376
+ max_samples: int = None,
377
+ private: bool = False,
378
+ shuffle: bool = False,
379
+ seed: int = 42,
380
+ output_column: str = "markdown",
381
+ verbose: bool = False,
382
+ config: str = None,
383
+ create_pr: bool = False,
384
+ resume: bool = False,
385
+ force: bool = False,
386
+ upload_every: int = 5,
387
+ ):
388
+ """Process images from HF dataset through GLM-OCR model with incremental uploads."""
389
+
390
+ check_cuda_availability()
391
+
392
+ start_time = datetime.now()
393
+
394
+ HF_TOKEN = hf_token or os.environ.get("HF_TOKEN")
395
+ if HF_TOKEN:
396
+ login(token=HF_TOKEN)
397
+
398
+ api = HfApi(token=HF_TOKEN)
399
+
400
+ # Validate task
401
+ if task not in TASK_PROMPTS:
402
+ logger.error(f"Unknown task '{task}'. Supported: {list(TASK_PROMPTS.keys())}")
403
+ sys.exit(1)
404
+
405
+ # Warn about --create-pr fallback
406
+ if create_pr:
407
+ logger.warning(
408
+ "CommitScheduler does not support PRs. "
409
+ "Falling back to v1 behavior (single push_to_hub at end)."
410
+ )
411
+ if resume:
412
+ logger.error("--resume is not compatible with --create-pr (v1 fallback).")
413
+ sys.exit(1)
414
+
415
+ logger.info(f"Using model: {MODEL}")
416
+ logger.info(f"Task: {task} (prompt: '{TASK_PROMPTS[task]}')")
417
+
418
+ # Get source dataset SHA for resume verification
419
+ logger.info(f"Fetching source dataset info: {input_dataset}")
420
+ source_info = api.dataset_info(input_dataset, token=HF_TOKEN)
421
+ source_sha = source_info.sha
422
+ logger.info(f"Source dataset SHA: {source_sha}")
423
+
424
+ # Load dataset
425
+ logger.info(f"Loading dataset: {input_dataset}")
426
+ dataset = load_dataset(input_dataset, split=split)
427
+
428
+ if image_column not in dataset.column_names:
429
+ raise ValueError(
430
+ f"Column '{image_column}' not found. Available: {dataset.column_names}"
431
+ )
432
+
433
+ if shuffle:
434
+ logger.info(f"Shuffling dataset with seed {seed}")
435
+ dataset = dataset.shuffle(seed=seed)
436
+
437
+ if max_samples:
438
+ dataset = dataset.select(range(min(max_samples, len(dataset))))
439
+ logger.info(f"Limited to {len(dataset)} samples")
440
+
441
+ total_samples = len(dataset)
442
+ total_batches = (total_samples + batch_size - 1) // batch_size
443
+
444
+ # Build metadata for this run
445
+ run_metadata = build_run_metadata(
446
+ input_dataset=input_dataset,
447
+ split=split,
448
+ shuffle=shuffle,
449
+ seed=seed,
450
+ max_samples=max_samples,
451
+ batch_size=batch_size,
452
+ source_dataset_sha=source_sha,
453
+ temperature=temperature,
454
+ top_p=top_p,
455
+ repetition_penalty=repetition_penalty,
456
+ max_tokens=max_tokens,
457
+ task=task,
458
+ gpu_memory_utilization=gpu_memory_utilization,
459
+ max_model_len=max_model_len,
460
+ total_batches=total_batches,
461
+ total_samples=total_samples,
462
+ )
463
+
464
+ # Resume logic
465
+ completed_batches: set[int] = set()
466
+ if resume and not force:
467
+ logger.info("Checking for existing run to resume...")
468
+ remote_meta = fetch_remote_metadata(api, output_dataset, HF_TOKEN)
469
+ if remote_meta is None:
470
+ logger.error(
471
+ f"No existing metadata found at {output_dataset}. "
472
+ "Cannot resume. Run without --resume to start fresh."
473
+ )
474
+ sys.exit(1)
475
+
476
+ mismatches = verify_run_metadata(run_metadata, remote_meta)
477
+ if mismatches:
478
+ logger.error("Run parameters do not match saved metadata:")
479
+ for m in mismatches:
480
+ logger.error(m)
481
+ logger.error("Use --force to ignore and start fresh.")
482
+ sys.exit(1)
483
+
484
+ completed_batches = find_completed_batches(api, output_dataset, HF_TOKEN)
485
+ if completed_batches:
486
+ logger.info(
487
+ f"Found {len(completed_batches)} completed batches: "
488
+ f"{sorted(completed_batches)}"
489
+ )
490
+ else:
491
+ logger.info("No completed batches found. Starting from beginning.")
492
+ elif force:
493
+ logger.info("--force: ignoring any existing data, starting fresh.")
494
+
495
+ # Initialize vLLM
496
+ logger.info("Initializing vLLM with GLM-OCR")
497
+ logger.info("This may take a few minutes on first run...")
498
+ llm = LLM(
499
+ model=MODEL,
500
+ trust_remote_code=True,
501
+ max_model_len=max_model_len,
502
+ gpu_memory_utilization=gpu_memory_utilization,
503
+ limit_mm_per_prompt={"image": 1},
504
+ )
505
+
506
+ sampling_params = SamplingParams(
507
+ temperature=temperature,
508
+ top_p=top_p,
509
+ max_tokens=max_tokens,
510
+ repetition_penalty=repetition_penalty,
511
+ )
512
+
513
+ # Inference info entry for this run
514
+ inference_entry = {
515
+ "model_id": MODEL,
516
+ "model_name": "GLM-OCR",
517
+ "column_name": output_column,
518
+ "timestamp": datetime.now().isoformat(),
519
+ "task": task,
520
+ "temperature": temperature,
521
+ "top_p": top_p,
522
+ "repetition_penalty": repetition_penalty,
523
+ "max_tokens": max_tokens,
524
+ }
525
+
526
+ logger.info(f"Processing {total_samples} images in batches of {batch_size}")
527
+ logger.info(f"Output will be written to column: {output_column}")
528
+
529
+ # --- create-pr fallback: v1 behavior (collect all, push once) ---
530
+ if create_pr:
531
+ all_outputs = []
532
+ processed = 0
533
+
534
+ for batch_num, batch_indices in enumerate(
535
+ partition_all(batch_size, range(total_samples))
536
+ ):
537
+ batch_indices = list(batch_indices)
538
+ batch_images = [dataset[i][image_column] for i in batch_indices]
539
+
540
+ logger.info(
541
+ f"Batch {batch_num + 1}/{total_batches} "
542
+ f"({processed}/{total_samples} images done)"
543
+ )
544
+
545
+ try:
546
+ batch_messages = [
547
+ make_ocr_message(img, task=task) for img in batch_images
548
+ ]
549
+ outputs = llm.chat(batch_messages, sampling_params)
550
+ for output in outputs:
551
+ text = output.outputs[0].text.strip()
552
+ all_outputs.append(text)
553
+ processed += len(batch_images)
554
+ except Exception as e:
555
+ logger.error(f"Error processing batch: {e}")
556
+ all_outputs.extend(["[OCR ERROR]"] * len(batch_images))
557
+ processed += len(batch_images)
558
+
559
+ processing_duration = datetime.now() - start_time
560
+ processing_time_str = f"{processing_duration.total_seconds() / 60:.1f} min"
561
+
562
+ dataset = dataset.add_column(output_column, all_outputs)
563
+
564
+ # Inference info
565
+ if "inference_info" in dataset.column_names:
566
+
567
+ def update_inference_info(example):
568
+ try:
569
+ existing = (
570
+ json.loads(example["inference_info"])
571
+ if example["inference_info"]
572
+ else []
573
+ )
574
+ except (json.JSONDecodeError, TypeError):
575
+ existing = []
576
+ existing.append(inference_entry)
577
+ return {"inference_info": json.dumps(existing)}
578
+
579
+ dataset = dataset.map(update_inference_info)
580
+ else:
581
+ inference_list = [json.dumps([inference_entry])] * len(dataset)
582
+ dataset = dataset.add_column("inference_info", inference_list)
583
+
584
+ logger.info(f"Pushing to {output_dataset} (create-pr mode)")
585
+ max_retries = 3
586
+ for attempt in range(1, max_retries + 1):
587
+ try:
588
+ if attempt > 1:
589
+ logger.warning("Disabling XET (fallback to HTTP upload)")
590
+ os.environ["HF_HUB_DISABLE_XET"] = "1"
591
+ dataset.push_to_hub(
592
+ output_dataset,
593
+ private=private,
594
+ token=HF_TOKEN,
595
+ max_shard_size="500MB",
596
+ **({"config_name": config} if config else {}),
597
+ create_pr=True,
598
+ commit_message=f"Add {MODEL} OCR results ({len(dataset)} samples)"
599
+ + (f" [{config}]" if config else ""),
600
+ )
601
+ break
602
+ except Exception as e:
603
+ logger.error(f"Upload attempt {attempt}/{max_retries} failed: {e}")
604
+ if attempt < max_retries:
605
+ delay = 30 * (2 ** (attempt - 1))
606
+ logger.info(f"Retrying in {delay}s...")
607
+ time.sleep(delay)
608
+ else:
609
+ logger.error("All upload attempts failed.")
610
+ sys.exit(1)
611
+
612
+ _push_dataset_card(
613
+ output_dataset=output_dataset,
614
+ input_dataset=input_dataset,
615
+ num_samples=total_samples,
616
+ processing_time=processing_time_str,
617
+ batch_size=batch_size,
618
+ max_model_len=max_model_len,
619
+ max_tokens=max_tokens,
620
+ gpu_memory_utilization=gpu_memory_utilization,
621
+ temperature=temperature,
622
+ top_p=top_p,
623
+ task=task,
624
+ image_column=image_column,
625
+ split=split,
626
+ token=HF_TOKEN,
627
+ )
628
+ _log_completion(
629
+ total_samples, processing_duration, processing_time_str, output_dataset
630
+ )
631
+ return
632
+
633
+ # --- v2 behavior: incremental parquet uploads via CommitScheduler ---
634
+ staging_dir = Path(tempfile.mkdtemp(prefix="glm-ocr-v2-"))
635
+ logger.info(f"Staging directory: {staging_dir}")
636
+
637
+ # Save metadata to staging dir so it gets uploaded with the first commit
638
+ save_run_metadata(run_metadata, staging_dir)
639
+
640
+ processed = 0
641
+ skipped = 0
642
+
643
+ with CleanupScheduler(
644
+ repo_id=output_dataset,
645
+ repo_type="dataset",
646
+ folder_path=staging_dir,
647
+ path_in_repo="data",
648
+ every=upload_every,
649
+ private=private,
650
+ token=HF_TOKEN,
651
+ ) as _scheduler: # noqa: F841
652
+ for batch_num, batch_indices in enumerate(
653
+ partition_all(batch_size, range(total_samples))
654
+ ):
655
+ batch_indices = list(batch_indices)
656
+
657
+ # Skip already-completed batches on resume
658
+ if batch_num in completed_batches:
659
+ skipped += len(batch_indices)
660
+ logger.info(
661
+ f"Batch {batch_num + 1}/{total_batches} — skipped (already uploaded)"
662
+ )
663
+ continue
664
+
665
+ batch_images = [dataset[i][image_column] for i in batch_indices]
666
+
667
+ logger.info(
668
+ f"Batch {batch_num + 1}/{total_batches} "
669
+ f"({processed + skipped}/{total_samples} images done, "
670
+ f"{skipped} skipped)"
671
+ )
672
+
673
+ try:
674
+ batch_messages = [
675
+ make_ocr_message(img, task=task) for img in batch_images
676
+ ]
677
+ outputs = llm.chat(batch_messages, sampling_params)
678
+ batch_texts = [o.outputs[0].text.strip() for o in outputs]
679
+ except Exception as e:
680
+ logger.error(f"Error processing batch {batch_num + 1}: {e}")
681
+ batch_texts = ["[OCR ERROR]"] * len(batch_images)
682
+
683
+ # Build batch dataset from the source subset
684
+ batch_ds = dataset.select(batch_indices)
685
+ batch_ds = batch_ds.add_column(output_column, batch_texts)
686
+
687
+ # Handle inference_info per row
688
+ if "inference_info" in batch_ds.column_names:
689
+ info_values = []
690
+ for i in range(len(batch_ds)):
691
+ raw = batch_ds[i]["inference_info"]
692
+ try:
693
+ existing = json.loads(raw) if raw else []
694
+ except (json.JSONDecodeError, TypeError):
695
+ existing = []
696
+ existing.append(inference_entry)
697
+ info_values.append(json.dumps(existing))
698
+ batch_ds = batch_ds.remove_columns("inference_info")
699
+ batch_ds = batch_ds.add_column("inference_info", info_values)
700
+ else:
701
+ info_values = [json.dumps([inference_entry])] * len(batch_ds)
702
+ batch_ds = batch_ds.add_column("inference_info", info_values)
703
+
704
+ # Save shard to staging dir
705
+ shard_name = f"train-{batch_num:05d}-of-{total_batches:05d}.parquet"
706
+ shard_path = staging_dir / shard_name
707
+ batch_ds.to_parquet(shard_path)
708
+ logger.info(f"Saved shard: {shard_name} ({len(batch_ds)} rows)")
709
+
710
+ processed += len(batch_indices)
711
+
712
+ # Context manager exit triggers final flush — blocks until upload completes
713
+ logger.info("All batches processed. Final upload flush complete.")
714
+
715
+ processing_duration = datetime.now() - start_time
716
+ processing_time_str = f"{processing_duration.total_seconds() / 60:.1f} min"
717
+
718
+ # Push dataset card as separate commit
719
+ _push_dataset_card(
720
+ output_dataset=output_dataset,
721
+ input_dataset=input_dataset,
722
+ num_samples=total_samples,
723
+ processing_time=processing_time_str,
724
+ batch_size=batch_size,
725
+ max_model_len=max_model_len,
726
+ max_tokens=max_tokens,
727
+ gpu_memory_utilization=gpu_memory_utilization,
728
+ temperature=temperature,
729
+ top_p=top_p,
730
+ task=task,
731
+ image_column=image_column,
732
+ split=split,
733
+ token=HF_TOKEN,
734
+ )
735
+
736
+ _log_completion(
737
+ total_samples, processing_duration, processing_time_str, output_dataset
738
+ )
739
+
740
+ if verbose:
741
+ import importlib.metadata
742
+
743
+ logger.info("--- Resolved package versions ---")
744
+ for pkg in ["vllm", "transformers", "torch", "datasets", "pyarrow", "pillow"]:
745
+ try:
746
+ logger.info(f" {pkg}=={importlib.metadata.version(pkg)}")
747
+ except importlib.metadata.PackageNotFoundError:
748
+ logger.info(f" {pkg}: not installed")
749
+ logger.info("--- End versions ---")
750
+
751
+
752
+ def _push_dataset_card(
753
+ *,
754
+ output_dataset: str,
755
+ input_dataset: str,
756
+ num_samples: int,
757
+ processing_time: str,
758
+ batch_size: int,
759
+ max_model_len: int,
760
+ max_tokens: int,
761
+ gpu_memory_utilization: float,
762
+ temperature: float,
763
+ top_p: float,
764
+ task: str,
765
+ image_column: str,
766
+ split: str,
767
+ token: str | None,
768
+ ):
769
+ """Create and push the dataset card."""
770
+ logger.info("Creating dataset card")
771
+ card_content = create_dataset_card(
772
+ source_dataset=input_dataset,
773
+ model=MODEL,
774
+ num_samples=num_samples,
775
+ processing_time=processing_time,
776
+ batch_size=batch_size,
777
+ max_model_len=max_model_len,
778
+ max_tokens=max_tokens,
779
+ gpu_memory_utilization=gpu_memory_utilization,
780
+ temperature=temperature,
781
+ top_p=top_p,
782
+ task=task,
783
+ image_column=image_column,
784
+ split=split,
785
+ )
786
+ card = DatasetCard(card_content)
787
+ card.push_to_hub(output_dataset, token=token)
788
+
789
+
790
+ def _log_completion(
791
+ total_samples: int,
792
+ processing_duration,
793
+ processing_time_str: str,
794
+ output_dataset: str,
795
+ ):
796
+ """Log final completion stats."""
797
+ logger.info("Done! GLM-OCR processing complete.")
798
+ logger.info(
799
+ f"Dataset available at: https://huggingface.co/datasets/{output_dataset}"
800
+ )
801
+ logger.info(f"Processing time: {processing_time_str}")
802
+ if processing_duration.total_seconds() > 0:
803
+ logger.info(
804
+ f"Processing speed: "
805
+ f"{total_samples / processing_duration.total_seconds():.2f} images/sec"
806
+ )
807
+
808
+
809
+ if __name__ == "__main__":
810
+ if len(sys.argv) == 1:
811
+ print("=" * 70)
812
+ print("GLM-OCR Document Processing (v2 — incremental uploads)")
813
+ print("=" * 70)
814
+ print("\n0.9B OCR model - 94.62% on OmniDocBench V1.5")
815
+ print("\nv2 improvements:")
816
+ print(" - Incremental parquet uploads (never lose results)")
817
+ print(" - Checkpoint/resume (--resume)")
818
+ print(" - Background upload every N minutes (--upload-every)")
819
+ print("\nTask modes:")
820
+ print(" ocr - Text recognition (default)")
821
+ print(" formula - LaTeX formula recognition")
822
+ print(" table - Table extraction")
823
+ print("\nExamples:")
824
+ print("\n1. Basic OCR:")
825
+ print(" uv run glm-ocr-v2.py input-dataset output-dataset")
826
+ print("\n2. Resume after interruption:")
827
+ print(" uv run glm-ocr-v2.py input-dataset output-dataset --resume")
828
+ print("\n3. Running on HF Jobs:")
829
+ print(" hf jobs uv run --flavor l4x1 \\")
830
+ print(" -s HF_TOKEN \\")
831
+ print(
832
+ " https://huggingface.co/datasets/uv-scripts/ocr/raw/main/glm-ocr-v2.py \\"
833
+ )
834
+ print(" input-dataset output-dataset --batch-size 16")
835
+ print("\nFor full help: uv run glm-ocr-v2.py --help")
836
+ sys.exit(0)
837
+
838
+ parser = argparse.ArgumentParser(
839
+ description="Document OCR using GLM-OCR v2 (incremental uploads + resume)",
840
+ formatter_class=argparse.RawDescriptionHelpFormatter,
841
+ epilog="""
842
+ Task modes:
843
+ ocr Text recognition to markdown (default)
844
+ formula LaTeX formula recognition
845
+ table Table extraction
846
+
847
+ v2 features:
848
+ Parquet shards uploaded incrementally via CommitScheduler.
849
+ Use --resume to pick up from the last completed batch.
850
+ Use --force to ignore existing data and start fresh.
851
+
852
+ Examples:
853
+ uv run glm-ocr-v2.py my-docs analyzed-docs
854
+ uv run glm-ocr-v2.py docs results --task formula
855
+ uv run glm-ocr-v2.py large-dataset test --max-samples 50 --shuffle
856
+ uv run glm-ocr-v2.py large-dataset test --resume
857
+ """,
858
+ )
859
+
860
+ parser.add_argument("input_dataset", help="Input dataset ID from Hugging Face Hub")
861
+ parser.add_argument("output_dataset", help="Output dataset ID for Hugging Face Hub")
862
+ parser.add_argument(
863
+ "--image-column",
864
+ default="image",
865
+ help="Column containing images (default: image)",
866
+ )
867
+ parser.add_argument(
868
+ "--batch-size",
869
+ type=int,
870
+ default=16,
871
+ help="Batch size for processing (default: 16)",
872
+ )
873
+ parser.add_argument(
874
+ "--max-model-len",
875
+ type=int,
876
+ default=8192,
877
+ help="Maximum model context length (default: 8192)",
878
+ )
879
+ parser.add_argument(
880
+ "--max-tokens",
881
+ type=int,
882
+ default=8192,
883
+ help="Maximum tokens to generate (default: 8192, capped by max-model-len)",
884
+ )
885
+ parser.add_argument(
886
+ "--temperature",
887
+ type=float,
888
+ default=0.01,
889
+ help="Sampling temperature (default: 0.01, near-greedy for OCR accuracy)",
890
+ )
891
+ parser.add_argument(
892
+ "--top-p",
893
+ type=float,
894
+ default=0.00001,
895
+ help="Top-p sampling parameter (default: 0.00001, near-greedy)",
896
+ )
897
+ parser.add_argument(
898
+ "--repetition-penalty",
899
+ type=float,
900
+ default=1.1,
901
+ help="Repetition penalty to prevent loops (default: 1.1)",
902
+ )
903
+ parser.add_argument(
904
+ "--gpu-memory-utilization",
905
+ type=float,
906
+ default=0.8,
907
+ help="GPU memory utilization (default: 0.8)",
908
+ )
909
+ parser.add_argument(
910
+ "--task",
911
+ choices=["ocr", "formula", "table"],
912
+ default="ocr",
913
+ help="OCR task mode (default: ocr)",
914
+ )
915
+ parser.add_argument("--hf-token", help="Hugging Face API token")
916
+ parser.add_argument(
917
+ "--split", default="train", help="Dataset split to use (default: train)"
918
+ )
919
+ parser.add_argument(
920
+ "--max-samples",
921
+ type=int,
922
+ help="Maximum number of samples to process (for testing)",
923
+ )
924
+ parser.add_argument(
925
+ "--private", action="store_true", help="Make output dataset private"
926
+ )
927
+ parser.add_argument(
928
+ "--config",
929
+ help="Config/subset name when pushing to Hub (for benchmarking multiple models in one repo)",
930
+ )
931
+ parser.add_argument(
932
+ "--create-pr",
933
+ action="store_true",
934
+ help="Create a pull request instead of pushing directly (falls back to v1 single-push behavior)",
935
+ )
936
+ parser.add_argument(
937
+ "--shuffle", action="store_true", help="Shuffle dataset before processing"
938
+ )
939
+ parser.add_argument(
940
+ "--seed",
941
+ type=int,
942
+ default=42,
943
+ help="Random seed for shuffling (default: 42)",
944
+ )
945
+ parser.add_argument(
946
+ "--output-column",
947
+ default="markdown",
948
+ help="Column name for output text (default: markdown)",
949
+ )
950
+ parser.add_argument(
951
+ "--verbose",
952
+ action="store_true",
953
+ help="Log resolved package versions after processing (useful for pinning deps)",
954
+ )
955
+ # v2-specific args
956
+ parser.add_argument(
957
+ "--resume",
958
+ action="store_true",
959
+ help="Resume from last completed batch (requires matching run metadata on Hub)",
960
+ )
961
+ parser.add_argument(
962
+ "--force",
963
+ action="store_true",
964
+ help="Ignore existing data on Hub and start fresh (skips metadata check)",
965
+ )
966
+ parser.add_argument(
967
+ "--upload-every",
968
+ type=int,
969
+ default=5,
970
+ help="CommitScheduler upload interval in minutes (default: 5)",
971
+ )
972
+
973
+ args = parser.parse_args()
974
+
975
+ main(
976
+ input_dataset=args.input_dataset,
977
+ output_dataset=args.output_dataset,
978
+ image_column=args.image_column,
979
+ batch_size=args.batch_size,
980
+ max_model_len=args.max_model_len,
981
+ max_tokens=args.max_tokens,
982
+ temperature=args.temperature,
983
+ top_p=args.top_p,
984
+ repetition_penalty=args.repetition_penalty,
985
+ gpu_memory_utilization=args.gpu_memory_utilization,
986
+ task=args.task,
987
+ hf_token=args.hf_token,
988
+ split=args.split,
989
+ max_samples=args.max_samples,
990
+ private=args.private,
991
+ shuffle=args.shuffle,
992
+ seed=args.seed,
993
+ output_column=args.output_column,
994
+ verbose=args.verbose,
995
+ config=args.config,
996
+ create_pr=args.create_pr,
997
+ resume=args.resume,
998
+ force=args.force,
999
+ upload_every=args.upload_every,
1000
+ )