davanstrien HF Staff commited on
Commit
19757f6
·
verified ·
1 Parent(s): 06e3ef4

Sync from GitHub via hub-sync

Browse files
Files changed (3) hide show
  1. README.md +23 -2
  2. lfm2-extract.py +293 -0
  3. lfm2-vl-extract.py +324 -0
README.md CHANGED
@@ -1,13 +1,13 @@
1
  ---
2
  viewer: false
3
- tags: [uv-script, ocr, vision-language-model, document-processing, hf-jobs]
4
  ---
5
 
6
  # OCR UV Scripts
7
 
8
  > Part of [uv-scripts](https://huggingface.co/uv-scripts) — self-contained UV scripts you run on Hugging Face Jobs in one command.
9
 
10
- A model zoo of OCR scripts — one per model — that add a `markdown` column to an image dataset. Pick a model from the table below, point it at your dataset, and run it on a GPU with one command. Two companions sit alongside: `pp-doclayout.py` detects layout regions (bboxes for text/title/table/figure/…) instead of text, and `ocr-vllm-judge.py` compares model outputs head-to-head.
11
 
12
  ## Quick Start
13
 
@@ -69,6 +69,27 @@ _Sorted by model size:_
69
 
70
  **Variants & tools** (same models, different I/O): `glm-ocr-v2.py` adds checkpoint/resume for very large jobs · `glm-ocr-bucket.py` and `falcon-ocr-bucket.py` read images/PDFs from a mounted bucket and write one `.md` per page · `ocr-vllm-judge.py` runs pairwise OCR-quality comparisons.
71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
  ## Layout detection (not OCR)
73
 
74
  `pp-doclayout.py` runs PaddleOCR's [PP-DocLayout-L](https://huggingface.co/PaddlePaddle/PP-DocLayout-L) (or M / S / plus-L) and emits per-image **bounding boxes + region classes** (text, title, table, figure, formula, list, header, footer, ...) — it does NOT extract text. Useful for filtering pages, cropping regions for downstream OCR, dataset analysis, and training-data prep.
 
1
  ---
2
  viewer: false
3
+ tags: [uv-script, ocr, extraction, vision-language-model, document-processing, hf-jobs]
4
  ---
5
 
6
  # OCR UV Scripts
7
 
8
  > Part of [uv-scripts](https://huggingface.co/uv-scripts) — self-contained UV scripts you run on Hugging Face Jobs in one command.
9
 
10
+ A model zoo of OCR scripts — one per model — that add a `markdown` column to an image dataset. Pick a model from the table below, point it at your dataset, and run it on a GPU with one command. A few recipes do **structured extraction** instead — image *or* text → JSON given a schema (see [Structured extraction](#structured-extraction-image-or-text--json) below). Two more companions sit alongside: `pp-doclayout.py` detects layout regions (bboxes for text/title/table/figure/…) instead of text, and `ocr-vllm-judge.py` compares model outputs head-to-head.
11
 
12
  ## Quick Start
13
 
 
69
 
70
  **Variants & tools** (same models, different I/O): `glm-ocr-v2.py` adds checkpoint/resume for very large jobs · `glm-ocr-bucket.py` and `falcon-ocr-bucket.py` read images/PDFs from a mounted bucket and write one `.md` per page · `ocr-vllm-judge.py` runs pairwise OCR-quality comparisons.
71
 
72
+ ## Structured extraction (image or text → JSON)
73
+
74
+ Most scripts here output markdown. These take a **schema** and return **structured data** instead — give them the fields you want, they fill them in:
75
+
76
+ | Script | Model | Size | Input | Output |
77
+ |--------|-------|------|-------|--------|
78
+ | `lfm2-vl-extract.py` | [LFM2.5-VL-1.6B-Extract](https://huggingface.co/LiquidAI/LFM2.5-VL-1.6B-Extract) | 1.6B | image | JSON |
79
+ | `nuextract3.py` | [NuExtract3](https://huggingface.co/numind/NuExtract3) | 4B | image | markdown **or** JSON |
80
+ | `lfm2-extract.py` | [LFM2-1.2B-Extract](https://huggingface.co/LiquidAI/LFM2-1.2B-Extract) | 1.2B | **text** | JSON / XML / YAML |
81
+
82
+ Pass `--schema` (inline JSON, a URL, or a file path). The LFM models are small and fast; run them on the `vllm/vllm-openai` image so the CUDA toolkit is present (each script's docstring has the exact command). Because `lfm2-extract.py` works on a **text** column, you can **chain it after OCR**: a recipe above turns a page into `markdown`, then `lfm2-extract.py` turns that markdown into fields.
83
+
84
+ ```bash
85
+ # image → JSON directly
86
+ hf jobs uv run --flavor l4x1 --secrets HF_TOKEN \
87
+ --image vllm/vllm-openai --python /usr/bin/python3 \
88
+ -e PYTHONPATH=/usr/local/lib/python3.12/dist-packages \
89
+ https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lfm2-vl-extract.py \
90
+ my-images my-fields --schema '{"title": "the document title", "date": "any date shown"}'
91
+ ```
92
+
93
  ## Layout detection (not OCR)
94
 
95
  `pp-doclayout.py` runs PaddleOCR's [PP-DocLayout-L](https://huggingface.co/PaddlePaddle/PP-DocLayout-L) (or M / S / plus-L) and emits per-image **bounding boxes + region classes** (text, title, table, figure, formula, list, header, footer, ...) — it does NOT extract text. Useful for filtering pages, cropping regions for downstream OCR, dataset analysis, and training-data prep.
lfm2-extract.py ADDED
@@ -0,0 +1,293 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.11"
3
+ # dependencies = [
4
+ # "datasets>=4.0.0",
5
+ # "huggingface-hub",
6
+ # "vllm",
7
+ # "transformers",
8
+ # "tqdm",
9
+ # "toolz",
10
+ # "torch",
11
+ # ]
12
+ # ///
13
+ """
14
+ Extract structured data (JSON / XML / YAML) from text using LiquidAI's LFM2-1.2B-Extract.
15
+
16
+ LFM2-1.2B-Extract is a compact 1.2B text-only model purpose-built for turning unstructured
17
+ documents into structured data: give it a schema, it returns JSON, XML, or YAML. It reports
18
+ beating Gemma 3 27B (22x larger) on syntax validity / format accuracy / faithfulness, and
19
+ is multilingual (en, ar, zh, fr, de, ja, ko, pt, es).
20
+
21
+ This is the *text* counterpart to `lfm2-vl-extract.py` (which extracts from images). Pair them:
22
+ OCR a page to markdown with one of the OCR recipes, then extract fields from that text here.
23
+
24
+ Pass `--schema` as inline text/JSON, a URL, or a file path describing the structure to extract:
25
+
26
+ --schema '{"invoice_number": "string", "total": "number", "line_items": "array"}'
27
+
28
+ Model: https://huggingface.co/LiquidAI/LFM2-1.2B-Extract
29
+ Docs: https://docs.liquid.ai/deployment/gpu-inference/vllm
30
+
31
+ HF Jobs note: run on the vLLM image so the CUDA toolkit + prebuilt FlashInfer kernels are
32
+ present and startup is fast (it reuses the image's CUDA-matched vLLM build):
33
+
34
+ hf jobs uv run --flavor l4x1 --secrets HF_TOKEN \
35
+ --image vllm/vllm-openai --python /usr/bin/python3 \
36
+ -e PYTHONPATH=/usr/local/lib/python3.12/dist-packages \
37
+ https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lfm2-extract.py \
38
+ INPUT OUTPUT --text-column text --schema '{"field": "description"}'
39
+
40
+ It also runs on the default uv image, just with a slower first-time vLLM build. Deps are left
41
+ unpinned so uv resolves a recent vLLM; FlashInfer sampling is disabled (see below) so the engine
42
+ never JIT-compiles a kernel that needs nvcc — absent from the default image.
43
+ """
44
+
45
+ import argparse
46
+ import json
47
+ import logging
48
+ import os
49
+ import sys
50
+ from datetime import datetime, timezone
51
+ from typing import List, Optional
52
+ from urllib.request import urlopen
53
+
54
+ # Disable vLLM's FlashInfer sampler before the engine starts: it JIT-compiles at warmup and
55
+ # needs nvcc (absent from the default uv image). Harmless for greedy decoding.
56
+ os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0")
57
+
58
+ import torch
59
+ from datasets import load_dataset
60
+ from huggingface_hub import DatasetCard, login
61
+ from toolz import partition_all
62
+ from tqdm import tqdm
63
+ from vllm import LLM, SamplingParams
64
+
65
+ logging.basicConfig(level=logging.INFO)
66
+ logger = logging.getLogger(__name__)
67
+
68
+ DEFAULT_MODEL = "LiquidAI/LFM2-1.2B-Extract"
69
+ FORMATS = {"json": "JSON", "xml": "XML", "yaml": "YAML"}
70
+
71
+
72
+ def check_cuda_availability() -> None:
73
+ if not torch.cuda.is_available():
74
+ logger.error("CUDA is not available. This script requires a GPU.")
75
+ logger.error("Run on Hugging Face Jobs with: hf jobs uv run --flavor l4x1 ...")
76
+ sys.exit(1)
77
+ logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name()}")
78
+
79
+
80
+ def load_text_arg(value: str) -> str:
81
+ """Resolve --schema (inline text/JSON, URL, or file path) into a string."""
82
+ text = value.strip()
83
+ if text.startswith("http://") or text.startswith("https://"):
84
+ logger.info(f"Loading schema from URL: {text}")
85
+ return urlopen(text).read().decode("utf-8").strip()
86
+ if os.path.exists(text):
87
+ logger.info(f"Loading schema from file: {text}")
88
+ with open(text) as f:
89
+ return f.read().strip()
90
+ return text
91
+
92
+
93
+ def build_system_prompt(schema_text: str, fmt: str) -> str:
94
+ return f"Return data as a {FORMATS[fmt]} object with the following schema:\n\n{schema_text}"
95
+
96
+
97
+ def parse_output(text: str, fmt: str) -> tuple[str, bool]:
98
+ """Strip code fences; for JSON, validate. Returns (cleaned_text, is_valid)."""
99
+ stripped = text.strip()
100
+ if stripped.startswith("```"):
101
+ stripped = stripped.split("\n", 1)[-1]
102
+ if stripped.endswith("```"):
103
+ stripped = stripped.rsplit("```", 1)[0]
104
+ stripped = stripped.strip()
105
+ if fmt == "json":
106
+ try:
107
+ return json.dumps(json.loads(stripped), ensure_ascii=False), True
108
+ except (json.JSONDecodeError, ValueError):
109
+ return stripped, False
110
+ return stripped, True # xml/yaml: store as-is (no strict validator)
111
+
112
+
113
+ def main(
114
+ input_dataset: str,
115
+ output_dataset: str,
116
+ schema: str,
117
+ text_column: str = "text",
118
+ output_column: str = "extraction",
119
+ output_format: str = "json",
120
+ split: str = "train",
121
+ max_samples: Optional[int] = None,
122
+ shuffle: bool = False,
123
+ seed: int = 42,
124
+ batch_size: int = 32,
125
+ model: str = DEFAULT_MODEL,
126
+ max_model_len: int = 8192,
127
+ max_tokens: int = 4096,
128
+ private: bool = False,
129
+ hf_token: Optional[str] = None,
130
+ ) -> None:
131
+ check_cuda_availability()
132
+ if output_format not in FORMATS:
133
+ logger.error(f"--format must be one of {list(FORMATS)}; got {output_format}")
134
+ sys.exit(1)
135
+
136
+ HF_TOKEN = hf_token or os.environ.get("HF_TOKEN")
137
+ if HF_TOKEN:
138
+ login(token=HF_TOKEN)
139
+
140
+ schema_text = load_text_arg(schema)
141
+ system_prompt = build_system_prompt(schema_text, output_format)
142
+
143
+ logger.info(f"Loading dataset: {input_dataset} (split={split})")
144
+ dataset = load_dataset(input_dataset, split=split)
145
+ if shuffle:
146
+ dataset = dataset.shuffle(seed=seed)
147
+ if max_samples:
148
+ dataset = dataset.select(range(min(max_samples, len(dataset))))
149
+ logger.info(f"Processing {len(dataset)} examples; format={output_format}")
150
+
151
+ if text_column not in dataset.column_names:
152
+ logger.error(f"Text column '{text_column}' not found. Columns: {dataset.column_names}")
153
+ sys.exit(1)
154
+
155
+ logger.info(f"Loading model: {model}")
156
+ llm = LLM(model=model, max_model_len=max_model_len, enforce_eager=True)
157
+ sampling_params = SamplingParams(temperature=0.0, max_tokens=max_tokens)
158
+
159
+ all_outputs: List[str] = []
160
+ n_valid = 0
161
+ texts = dataset[text_column]
162
+ for batch in tqdm(list(partition_all(batch_size, texts)), desc="Extracting"):
163
+ batch_messages = [
164
+ [
165
+ {"role": "system", "content": system_prompt},
166
+ {"role": "user", "content": str(doc)},
167
+ ]
168
+ for doc in batch
169
+ ]
170
+ outputs = llm.chat(batch_messages, sampling_params)
171
+ for out in outputs:
172
+ cleaned, ok = parse_output(out.outputs[0].text, output_format)
173
+ n_valid += int(ok)
174
+ all_outputs.append(cleaned)
175
+
176
+ logger.info(f"Valid {output_format.upper()}: {n_valid}/{len(all_outputs)}")
177
+ dataset = dataset.add_column(output_column, all_outputs)
178
+
179
+ inference_entry = {
180
+ "model": model,
181
+ "column_name": output_column,
182
+ "task": "structured extraction",
183
+ "format": output_format,
184
+ "timestamp": datetime.now(timezone.utc).isoformat(),
185
+ "script": "lfm2-extract.py",
186
+ }
187
+ if "inference_info" in dataset.column_names:
188
+ def update_info(example):
189
+ try:
190
+ existing = json.loads(example["inference_info"]) if example["inference_info"] else []
191
+ except (json.JSONDecodeError, TypeError):
192
+ existing = []
193
+ existing.append(inference_entry)
194
+ return {"inference_info": json.dumps(existing)}
195
+ dataset = dataset.map(update_info)
196
+ else:
197
+ dataset = dataset.add_column(
198
+ "inference_info", [json.dumps([inference_entry])] * len(dataset)
199
+ )
200
+
201
+ logger.info(f"Pushing to {output_dataset}")
202
+ dataset.push_to_hub(output_dataset, private=private, token=HF_TOKEN)
203
+
204
+ card_text = f"""---
205
+ tags:
206
+ - uv-script
207
+ - extraction
208
+ - lfm2
209
+ - {output_format}
210
+ ---
211
+
212
+ # Structured extraction with LFM2-1.2B-Extract
213
+
214
+ `{output_format.upper()}` extracted from the `{text_column}` column of
215
+ [{input_dataset}](https://huggingface.co/datasets/{input_dataset})
216
+ using [{model}](https://huggingface.co/{model}).
217
+
218
+ - **Source**: `{input_dataset}` (split `{split}`, column `{text_column}`)
219
+ - **Model**: `{model}`
220
+ - **Format**: `{output_format}`
221
+ - **Output column**: `{output_column}`
222
+ - **Valid {output_format.upper()}**: {n_valid}/{len(all_outputs)}
223
+ - **Date**: {datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")}
224
+
225
+ Generated with the [uv-scripts/ocr](https://huggingface.co/datasets/uv-scripts/ocr) `lfm2-extract.py` script.
226
+ """
227
+ try:
228
+ DatasetCard(card_text).push_to_hub(output_dataset, token=HF_TOKEN)
229
+ except Exception as e:
230
+ logger.warning(f"Could not push dataset card: {e}")
231
+
232
+ logger.info("Done! Extraction complete.")
233
+ logger.info(f"Dataset: https://huggingface.co/datasets/{output_dataset}")
234
+
235
+
236
+ if __name__ == "__main__":
237
+ if len(sys.argv) == 1:
238
+ print("LFM2-1.2B-Extract — structured extraction (JSON/XML/YAML) from text")
239
+ print("\nUsage:")
240
+ print(" uv run lfm2-extract.py INPUT OUTPUT --schema SCHEMA [--text-column text] [--format json]")
241
+ print("\nExample:")
242
+ print(' uv run lfm2-extract.py my-docs my-fields \\')
243
+ print(' --text-column markdown \\')
244
+ print(' --schema \'{"title": "the title", "date": "any date", "summary": "one sentence"}\'')
245
+ print("\n --schema accepts inline text/JSON, a URL, or a file path.")
246
+ print("\nFor full help: uv run lfm2-extract.py --help")
247
+ sys.exit(0)
248
+
249
+ parser = argparse.ArgumentParser(
250
+ description="Structured extraction (JSON/XML/YAML) from text using LFM2-1.2B-Extract",
251
+ )
252
+ parser.add_argument("input_dataset", help="Input dataset ID (with a text column)")
253
+ parser.add_argument("output_dataset", help="Output dataset ID")
254
+ parser.add_argument(
255
+ "--schema", required=True,
256
+ help="Structure to extract: inline text/JSON, a URL, or a file path",
257
+ )
258
+ parser.add_argument("--text-column", default="text", help="Text column (default: text)")
259
+ parser.add_argument("--output-column", default="extraction", help="Output column (default: extraction)")
260
+ parser.add_argument(
261
+ "--format", dest="output_format", default="json", choices=list(FORMATS),
262
+ help="Output format (default: json)",
263
+ )
264
+ parser.add_argument("--split", default="train", help="Dataset split (default: train)")
265
+ parser.add_argument("--max-samples", type=int, help="Limit number of samples")
266
+ parser.add_argument("--shuffle", action="store_true", help="Shuffle before sampling")
267
+ parser.add_argument("--seed", type=int, default=42, help="Shuffle seed (default: 42)")
268
+ parser.add_argument("--batch-size", type=int, default=32, help="Batch size (default: 32)")
269
+ parser.add_argument("--model", default=DEFAULT_MODEL, help=f"Model (default: {DEFAULT_MODEL})")
270
+ parser.add_argument("--max-model-len", type=int, default=8192, help="Max context length (default: 8192)")
271
+ parser.add_argument("--max-tokens", type=int, default=4096, help="Max output tokens (default: 4096)")
272
+ parser.add_argument("--private", action="store_true", help="Make output dataset private")
273
+ parser.add_argument("--hf-token", help="HF token (or set HF_TOKEN)")
274
+ args = parser.parse_args()
275
+
276
+ main(
277
+ input_dataset=args.input_dataset,
278
+ output_dataset=args.output_dataset,
279
+ schema=args.schema,
280
+ text_column=args.text_column,
281
+ output_column=args.output_column,
282
+ output_format=args.output_format,
283
+ split=args.split,
284
+ max_samples=args.max_samples,
285
+ shuffle=args.shuffle,
286
+ seed=args.seed,
287
+ batch_size=args.batch_size,
288
+ model=args.model,
289
+ max_model_len=args.max_model_len,
290
+ max_tokens=args.max_tokens,
291
+ private=args.private,
292
+ hf_token=args.hf_token,
293
+ )
lfm2-vl-extract.py ADDED
@@ -0,0 +1,324 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.11"
3
+ # dependencies = [
4
+ # "datasets>=4.0.0",
5
+ # "huggingface-hub",
6
+ # "pillow",
7
+ # "vllm",
8
+ # "transformers",
9
+ # "tqdm",
10
+ # "toolz",
11
+ # "torch",
12
+ # ]
13
+ # ///
14
+ """
15
+ Extract structured JSON from images using LiquidAI's LFM2.5-VL-1.6B-Extract with vLLM.
16
+
17
+ LFM2.5-VL-1.6B-Extract (1.6B = LFM2 1.2B LM + SigLIP2 0.4B vision) is a compact
18
+ vision-language model purpose-built for *schema-guided* extraction: you give it a
19
+ list of fields, it returns a flat JSON object with those fields filled from the image.
20
+ It reports 99.6 JSON-validity / F1 on its benchmark, beating similarly-sized VLMs.
21
+
22
+ Unlike the markdown-OCR scripts here, this one needs a SCHEMA (a field list). Pass
23
+ `--schema` as inline JSON, a URL, or a file path, mapping field names to short
24
+ descriptions:
25
+
26
+ --schema '{"invoice_number": "the invoice number", "total": "the total amount"}'
27
+
28
+ Model: https://huggingface.co/LiquidAI/LFM2.5-VL-1.6B-Extract
29
+ Docs: https://docs.liquid.ai/deployment/gpu-inference/vllm
30
+
31
+ HF Jobs note: run on the vLLM image so the CUDA toolkit + prebuilt FlashInfer kernels
32
+ are present and startup is fast (it reuses the image's CUDA-matched vLLM build):
33
+
34
+ hf jobs uv run --flavor l4x1 --secrets HF_TOKEN \
35
+ --image vllm/vllm-openai --python /usr/bin/python3 \
36
+ -e PYTHONPATH=/usr/local/lib/python3.12/dist-packages \
37
+ https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lfm2-vl-extract.py \
38
+ INPUT OUTPUT --schema '{"title": "the document title", "date": "any date shown"}'
39
+
40
+ It also runs on the default uv image, just with a slower first-time vLLM build. Deps are
41
+ left unpinned so uv resolves a vLLM that supports the LFM2-VL (transformers 5) architecture,
42
+ and FlashInfer sampling is disabled (VLLM_USE_FLASHINFER_SAMPLER=0, see below) so the engine
43
+ never JIT-compiles a kernel that needs nvcc — absent from the default image.
44
+ """
45
+
46
+ import argparse
47
+ import base64
48
+ import io
49
+ import json
50
+ import logging
51
+ import os
52
+ import sys
53
+ from datetime import datetime, timezone
54
+ from typing import Any, Dict, List, Optional, Union
55
+ from urllib.request import urlopen
56
+
57
+ # Disable vLLM's FlashInfer top-k/top-p sampler before the engine starts: it JIT-compiles
58
+ # at warmup and needs nvcc (absent from the default uv image). Harmless for greedy decoding.
59
+ os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0")
60
+
61
+ import torch
62
+ from datasets import load_dataset
63
+ from huggingface_hub import DatasetCard, login
64
+ from PIL import Image
65
+ from toolz import partition_all
66
+ from tqdm import tqdm
67
+ from vllm import LLM, SamplingParams
68
+
69
+ logging.basicConfig(level=logging.INFO)
70
+ logger = logging.getLogger(__name__)
71
+
72
+ DEFAULT_MODEL = "LiquidAI/LFM2.5-VL-1.6B-Extract"
73
+
74
+
75
+ def check_cuda_availability() -> None:
76
+ if not torch.cuda.is_available():
77
+ logger.error("CUDA is not available. This script requires a GPU.")
78
+ logger.error("Run on Hugging Face Jobs with: hf jobs uv run --flavor l4x1 ...")
79
+ sys.exit(1)
80
+ logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name()}")
81
+
82
+
83
+ def load_schema_arg(value: str) -> Dict[str, str]:
84
+ """Resolve --schema (inline JSON, URL, or file path) into a {field: description} dict."""
85
+ text = value.strip()
86
+ if text.startswith("http://") or text.startswith("https://"):
87
+ logger.info(f"Loading schema from URL: {text}")
88
+ text = urlopen(text).read().decode("utf-8")
89
+ elif not text.startswith("{") and not text.startswith("["):
90
+ if os.path.exists(text):
91
+ logger.info(f"Loading schema from file: {text}")
92
+ with open(text) as f:
93
+ text = f.read()
94
+ parsed = json.loads(text)
95
+ # Accept {"field": "description"} or ["field1", "field2"]
96
+ if isinstance(parsed, list):
97
+ return {str(field): "" for field in parsed}
98
+ if isinstance(parsed, dict):
99
+ return {str(k): str(v) for k, v in parsed.items()}
100
+ raise ValueError("--schema must be a JSON object {field: description} or a JSON list of field names.")
101
+
102
+
103
+ def build_system_prompt(schema: Dict[str, str]) -> str:
104
+ """LFM2.5-VL-Extract prompt: a field list in the system message → flat JSON out."""
105
+ lines = []
106
+ for field, desc in schema.items():
107
+ lines.append(f"{field}: {desc}" if desc else field)
108
+ fields_block = "\n".join(lines)
109
+ return (
110
+ f"Extract the following from the image:\n\n{fields_block}\n\n"
111
+ "Respond with only a JSON object."
112
+ )
113
+
114
+
115
+ def image_to_data_uri(image: Union[Image.Image, Dict[str, Any], str]) -> str:
116
+ if isinstance(image, dict) and "bytes" in image:
117
+ image = Image.open(io.BytesIO(image["bytes"]))
118
+ elif isinstance(image, str):
119
+ image = Image.open(image)
120
+ if image.mode != "RGB":
121
+ image = image.convert("RGB")
122
+ buf = io.BytesIO()
123
+ image.save(buf, format="PNG")
124
+ return f"data:image/png;base64,{base64.b64encode(buf.getvalue()).decode()}"
125
+
126
+
127
+ def make_message(image: Any, system_prompt: str) -> List[Dict]:
128
+ data_uri = image_to_data_uri(image)
129
+ return [
130
+ {"role": "system", "content": system_prompt},
131
+ {"role": "user", "content": [{"type": "image_url", "image_url": {"url": data_uri}}]},
132
+ ]
133
+
134
+
135
+ def parse_json_output(text: str) -> tuple[Optional[Any], bool]:
136
+ """Return (parsed, ok). Strips ```json fences if present."""
137
+ stripped = text.strip()
138
+ if stripped.startswith("```"):
139
+ stripped = stripped.split("\n", 1)[-1]
140
+ if stripped.endswith("```"):
141
+ stripped = stripped.rsplit("```", 1)[0]
142
+ stripped = stripped.strip()
143
+ try:
144
+ return json.loads(stripped), True
145
+ except (json.JSONDecodeError, ValueError):
146
+ return None, False
147
+
148
+
149
+ def main(
150
+ input_dataset: str,
151
+ output_dataset: str,
152
+ schema: str,
153
+ image_column: str = "image",
154
+ output_column: str = "extraction",
155
+ split: str = "train",
156
+ max_samples: Optional[int] = None,
157
+ shuffle: bool = False,
158
+ seed: int = 42,
159
+ batch_size: int = 16,
160
+ model: str = DEFAULT_MODEL,
161
+ max_model_len: int = 4096,
162
+ max_tokens: int = 1024,
163
+ private: bool = False,
164
+ hf_token: Optional[str] = None,
165
+ ) -> None:
166
+ check_cuda_availability()
167
+
168
+ HF_TOKEN = hf_token or os.environ.get("HF_TOKEN")
169
+ if HF_TOKEN:
170
+ login(token=HF_TOKEN)
171
+
172
+ schema_dict = load_schema_arg(schema)
173
+ system_prompt = build_system_prompt(schema_dict)
174
+ logger.info(f"Extraction fields: {list(schema_dict.keys())}")
175
+
176
+ logger.info(f"Loading dataset: {input_dataset} (split={split})")
177
+ dataset = load_dataset(input_dataset, split=split)
178
+ if shuffle:
179
+ dataset = dataset.shuffle(seed=seed)
180
+ if max_samples:
181
+ dataset = dataset.select(range(min(max_samples, len(dataset))))
182
+ logger.info(f"Processing {len(dataset)} examples")
183
+
184
+ if image_column not in dataset.column_names:
185
+ logger.error(f"Image column '{image_column}' not found. Columns: {dataset.column_names}")
186
+ sys.exit(1)
187
+
188
+ logger.info(f"Loading model: {model}")
189
+ llm = LLM(
190
+ model=model,
191
+ max_model_len=max_model_len,
192
+ limit_mm_per_prompt={"image": 1},
193
+ enforce_eager=True,
194
+ )
195
+ sampling_params = SamplingParams(temperature=0.0, max_tokens=max_tokens)
196
+
197
+ all_outputs: List[str] = []
198
+ n_valid = 0
199
+ images = dataset[image_column]
200
+ for batch in tqdm(list(partition_all(batch_size, images)), desc="Extracting"):
201
+ batch_messages = [make_message(img, system_prompt) for img in batch]
202
+ outputs = llm.chat(batch_messages, sampling_params)
203
+ for out in outputs:
204
+ text = out.outputs[0].text.strip()
205
+ parsed, ok = parse_json_output(text)
206
+ if ok:
207
+ n_valid += 1
208
+ all_outputs.append(json.dumps(parsed, ensure_ascii=False))
209
+ else:
210
+ all_outputs.append(text) # keep raw on parse failure
211
+
212
+ logger.info(f"Valid JSON: {n_valid}/{len(all_outputs)}")
213
+
214
+ dataset = dataset.add_column(output_column, all_outputs)
215
+
216
+ inference_entry = {
217
+ "model": model,
218
+ "column_name": output_column,
219
+ "task": "schema-guided extraction",
220
+ "fields": list(schema_dict.keys()),
221
+ "timestamp": datetime.now(timezone.utc).isoformat(),
222
+ "script": "lfm2-vl-extract.py",
223
+ }
224
+ if "inference_info" in dataset.column_names:
225
+ def update_info(example):
226
+ try:
227
+ existing = json.loads(example["inference_info"]) if example["inference_info"] else []
228
+ except (json.JSONDecodeError, TypeError):
229
+ existing = []
230
+ existing.append(inference_entry)
231
+ return {"inference_info": json.dumps(existing)}
232
+ dataset = dataset.map(update_info)
233
+ else:
234
+ dataset = dataset.add_column(
235
+ "inference_info", [json.dumps([inference_entry])] * len(dataset)
236
+ )
237
+
238
+ logger.info(f"Pushing to {output_dataset}")
239
+ dataset.push_to_hub(output_dataset, private=private, token=HF_TOKEN)
240
+
241
+ card_text = f"""---
242
+ tags:
243
+ - uv-script
244
+ - extraction
245
+ - lfm2-vl
246
+ - json
247
+ ---
248
+
249
+ # Structured extraction with LFM2.5-VL-1.6B-Extract
250
+
251
+ JSON fields extracted from images in [{input_dataset}](https://huggingface.co/datasets/{input_dataset})
252
+ using [{model}](https://huggingface.co/{model}).
253
+
254
+ - **Source**: `{input_dataset}` (split `{split}`)
255
+ - **Model**: `{model}`
256
+ - **Fields**: {", ".join(f"`{k}`" for k in schema_dict.keys())}
257
+ - **Output column**: `{output_column}` (JSON string per row)
258
+ - **Valid JSON**: {n_valid}/{len(all_outputs)}
259
+ - **Date**: {datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")}
260
+
261
+ Generated with the [uv-scripts/ocr](https://huggingface.co/datasets/uv-scripts/ocr) `lfm2-vl-extract.py` script.
262
+ """
263
+ try:
264
+ card = DatasetCard(card_text)
265
+ card.push_to_hub(output_dataset, token=HF_TOKEN)
266
+ except Exception as e:
267
+ logger.warning(f"Could not push dataset card: {e}")
268
+
269
+ logger.info("Done! Extraction complete.")
270
+ logger.info(f"Dataset: https://huggingface.co/datasets/{output_dataset}")
271
+
272
+
273
+ if __name__ == "__main__":
274
+ if len(sys.argv) == 1:
275
+ print("LFM2.5-VL-1.6B-Extract — schema-guided JSON extraction from images")
276
+ print("\nUsage:")
277
+ print(" uv run lfm2-vl-extract.py INPUT OUTPUT --schema SCHEMA [options]")
278
+ print("\nExample:")
279
+ print(' uv run lfm2-vl-extract.py my-images my-extractions \\')
280
+ print(' --schema \'{"title": "the document title", "date": "any date shown"}\'')
281
+ print("\n --schema accepts inline JSON, a URL, or a file path.")
282
+ print("\nFor full help: uv run lfm2-vl-extract.py --help")
283
+ sys.exit(0)
284
+
285
+ parser = argparse.ArgumentParser(
286
+ description="Schema-guided JSON extraction from images using LFM2.5-VL-1.6B-Extract",
287
+ )
288
+ parser.add_argument("input_dataset", help="Input dataset ID (with images)")
289
+ parser.add_argument("output_dataset", help="Output dataset ID")
290
+ parser.add_argument(
291
+ "--schema", required=True,
292
+ help="Fields to extract: inline JSON {field: description}, a URL, or a file path",
293
+ )
294
+ parser.add_argument("--image-column", default="image", help="Image column (default: image)")
295
+ parser.add_argument("--output-column", default="extraction", help="Output column (default: extraction)")
296
+ parser.add_argument("--split", default="train", help="Dataset split (default: train)")
297
+ parser.add_argument("--max-samples", type=int, help="Limit number of samples")
298
+ parser.add_argument("--shuffle", action="store_true", help="Shuffle before sampling")
299
+ parser.add_argument("--seed", type=int, default=42, help="Shuffle seed (default: 42)")
300
+ parser.add_argument("--batch-size", type=int, default=16, help="Batch size (default: 16)")
301
+ parser.add_argument("--model", default=DEFAULT_MODEL, help=f"Model (default: {DEFAULT_MODEL})")
302
+ parser.add_argument("--max-model-len", type=int, default=4096, help="Max context length (default: 4096)")
303
+ parser.add_argument("--max-tokens", type=int, default=1024, help="Max output tokens (default: 1024)")
304
+ parser.add_argument("--private", action="store_true", help="Make output dataset private")
305
+ parser.add_argument("--hf-token", help="HF token (or set HF_TOKEN)")
306
+ args = parser.parse_args()
307
+
308
+ main(
309
+ input_dataset=args.input_dataset,
310
+ output_dataset=args.output_dataset,
311
+ schema=args.schema,
312
+ image_column=args.image_column,
313
+ output_column=args.output_column,
314
+ split=args.split,
315
+ max_samples=args.max_samples,
316
+ shuffle=args.shuffle,
317
+ seed=args.seed,
318
+ batch_size=args.batch_size,
319
+ model=args.model,
320
+ max_model_len=args.max_model_len,
321
+ max_tokens=args.max_tokens,
322
+ private=args.private,
323
+ hf_token=args.hf_token,
324
+ )