davanstrien HF Staff commited on
Commit
0bf9a5e
·
verified ·
1 Parent(s): f43b67e

Sync from GitHub via hub-sync

Browse files
Files changed (3) hide show
  1. CLAUDE.md +71 -0
  2. README.md +11 -0
  3. lift-extract.py +812 -0
CLAUDE.md CHANGED
@@ -202,6 +202,77 @@ hf jobs uv run --flavor l4x1 \
202
  ### PaddleOCR-VL (`paddleocr-vl.py`)
203
  ✅ Working
204
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
205
  ---
206
 
207
  ## Future: OCR Smoke Test Dataset
 
202
  ### PaddleOCR-VL (`paddleocr-vl.py`)
203
  ✅ Working
204
 
205
+ ### lift (`lift-extract.py`)
206
+ ✅ **Both backends validated on Jobs** (added 2026-06-22)
207
+
208
+ Datalab's `lift` (9B, Qwen3.5-based) for **schema-constrained** structured extraction:
209
+ image *or* multi-page PDF + JSON Schema → JSON. Sits alongside `nuextract3.py` /
210
+ `lfm2-vl-extract.py` in the structured-extraction group, but it's the only one that
211
+ ingests PDFs directly (one row = one document, multi-page collapsed into one extraction).
212
+
213
+ **Shared rendering** comes from lift: we reuse `lift.input.load_file` (auto-detects PDF vs
214
+ image by content; `pypdfium2`, DPI/min-dim, `--page-range`) via a temp file per row. Each row
215
+ → a list of page images → one extraction. Both backends share this.
216
+
217
+ **Backends (`--method`)** — both **in-process, single command** (no server):
218
+ - `hf` (default): drives the `lift-pdf` package directly — `InferenceManager(method="hf")` →
219
+ `AutoModelForImageTextToText`, bf16, batches a list of `BatchInputItem` conversations with
220
+ left padding. **No** constrained decoding (plain `model.generate`); trusts lift's training.
221
+ Runs on the **default** uv image. Simplest path; best for small jobs.
222
+ - `vllm`: vLLM's **offline `LLM()` engine** + `llm.chat()` with structured outputs — the
223
+ repo's standard fast-batch pattern. We reproduce lift's *own* vLLM recipe (their `generate_vllm`)
224
+ rather than calling the package: `PROMPT_MAPPING["direct"]`, `scale_to_fit`,
225
+ `mm_processor_kwargs={min_pixels:3136,max_pixels:861696}`, and the guided JSON schema
226
+ (`json_schema_to_pydantic.create_model` → `make_properties_nullable` → `StructuredOutputsParams`,
227
+ with the version shim from `ocr-vllm-judge.py`). Sampling matches lift exactly: `temperature=0.0,
228
+ top_p=0.1, max_tokens=12384`. Needs the `vllm/vllm-openai` image (vLLM not in our deps; reused
229
+ from the image via `PYTHONPATH`, which also wins the torch version → no clash). **Not mirrored:**
230
+ lift's repeat-token retry loop (re-runs looped items at higher temp) — less critical here since
231
+ the grammar constraint already prevents runaway repetition.
232
+
233
+ > **History:** the first `--method vllm` used the package's path, which is an OpenAI *client* →
234
+ > server (lift's `lift_vllm` shells out to `sudo docker run`, unusable in a Job). We built+validated
235
+ > an auto-launched `vllm serve` subprocess for it, then replaced the whole thing with the offline
236
+ > `LLM()` engine — cleaner single command, no HTTP, and the repo's established pattern.
237
+
238
+ **Model id:** card repo is `datalab-to/lift` (9.65B, license `openrail`, not gated). The
239
+ installed package's internal default was `datalab-to/lift-extract`; we pin `--model
240
+ datalab-to/lift` via the `MODEL_CHECKPOINT` env (set *before* importing lift, since settings
241
+ read env at import). Confirmed in the smoke test: `datalab-to/lift` (commit `3129597…`) loads.
242
+
243
+ **Naming gotcha:** the script must NOT be named `lift.py` — that shadows the installed `lift`
244
+ package (`import lift` resolves to the script itself → `ImportError: cannot import name
245
+ 'resolve_schema'`). Hence `lift-extract.py`. Hit this on the first Jobs run.
246
+
247
+ **License:** code Apache-2.0, **weights modified OpenRAIL-M** (research/personal/<$5M, no
248
+ competitive use vs Datalab API). Surfaced in the docstring, the README entry, and the output
249
+ dataset card.
250
+
251
+ **Benchmark both backends:** `--config hf --create-pr` vs `--config vllm --create-pr` into one
252
+ repo (same multi-config pattern as the other OCR scripts).
253
+
254
+ **Smoke-test results (2026-06-22, `davanstrien/ufo-ColPali`, 3 samples, a100-large):**
255
+ - **HF backend** (default image): 3/3 valid JSON, batched (1 chunk of 3 at `--batch-size 8`, no
256
+ padding/image-count issues), 1.8 min. Output `davanstrien/lift-smoke-hf`. Resolved
257
+ `lift-pdf==0.1.1, transformers==5.12.1, torch==2.12.1, datasets==5.0.0`.
258
+ - **vLLM offline backend** (`vllm/vllm-openai` image): `LLM()` engine loaded (weights 18 GiB /
259
+ 59s via Xet high-perf), `llm.chat` batched all 3 prompts in one call (538 tok/s in), 3/3 valid
260
+ JSON via `StructuredOutputsParams`, clean engine shutdown, 5.2 min (engine init + torch.compile
261
+ warmup dominates at 3 samples; wins at scale). `vllm==0.23.0`, image's `torch==2.11.0+cu130` (no
262
+ clash). Output `davanstrien/lift-smoke-vllm-offline`.
263
+ - (The earlier server-subprocess vLLM also passed — `davanstrien/lift-smoke-vllm`, 5.3 min — but
264
+ was replaced by the offline engine; see History above.)
265
+ - **All paths produce valid schema-shaped JSON**, e.g.
266
+ `{"title": "OUT OF THIS WORLD UFO FlyBys in Middle Tennessee", "date": "Oct. 26, 1995"}`;
267
+ absent fields → `null` (nullable-leaf transform). `parse_error_rate: 0.0`. Outputs agree across
268
+ backends except minor low-temp content drift (offline-vLLM recovered a Spanish title hf left null).
269
+
270
+ **Still untested (lower risk — reuses lift's `load_file`, exercised on the image path):**
271
+ - PDF column path (`--pdf-column`, `--page-range`) on a real PDF-bytes dataset.
272
+ - `l4x1` for the hf backend (9B bf16 ≈ 19GB; default `a100-large` confirmed comfortable).
273
+
274
+ Requires Python ≥3.12 (lift-pdf constraint) — fine on the standard images.
275
+
276
  ---
277
 
278
  ## Future: OCR Smoke Test Dataset
README.md CHANGED
@@ -80,9 +80,20 @@ Most scripts here output markdown. These take a **schema** and return **structur
80
  | `lfm2-vl-extract.py` | [LFM2.5-VL-1.6B-Extract](https://huggingface.co/LiquidAI/LFM2.5-VL-1.6B-Extract) | 1.6B | image | JSON |
81
  | `nuextract3.py` | [NuExtract3](https://huggingface.co/numind/NuExtract3) | 4B | image | markdown **or** JSON |
82
  | `lfm2-extract.py` | [LFM2-1.2B-Extract](https://huggingface.co/LiquidAI/LFM2-1.2B-Extract) | 1.2B | **text** | JSON / XML / YAML |
 
83
 
84
  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.
85
 
 
 
 
 
 
 
 
 
 
 
86
  ```bash
87
  # image → JSON directly
88
  hf jobs uv run --flavor l4x1 --secrets HF_TOKEN \
 
80
  | `lfm2-vl-extract.py` | [LFM2.5-VL-1.6B-Extract](https://huggingface.co/LiquidAI/LFM2.5-VL-1.6B-Extract) | 1.6B | image | JSON |
81
  | `nuextract3.py` | [NuExtract3](https://huggingface.co/numind/NuExtract3) | 4B | image | markdown **or** JSON |
82
  | `lfm2-extract.py` | [LFM2-1.2B-Extract](https://huggingface.co/LiquidAI/LFM2-1.2B-Extract) | 1.2B | **text** | JSON / XML / YAML |
83
+ | `lift-extract.py` | [lift](https://huggingface.co/datalab-to/lift) | 9B | image **or** PDF | JSON |
84
 
85
  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.
86
 
87
+ `lift-extract.py` is the heavyweight of the group: Datalab's 9B model does **schema-constrained** decoding (output is guaranteed valid against your JSON Schema) and is the only recipe here that takes **multi-page PDFs** directly — a whole document (`--pdf-column`, `--page-range`) collapses into one extraction. It runs in-process two ways — `--method hf` (Transformers, default image, best for small jobs) or `--method vllm` (vLLM's offline engine on the `vllm/vllm-openai` image, faster at scale via continuous batching) — both single-command, no server. The vLLM path mirrors lift's own structured-output recipe (schema-constrained JSON decoding); benchmark the two by pushing each to one repo with `--config hf` / `--config vllm`. **License:** the code is Apache-2.0 but the weights are a modified OpenRAIL-M (free for research, personal use, and startups under $5M funding/revenue; no competitive use against Datalab's API) — confirm you're within those terms.
88
+
89
+ ```bash
90
+ # images or multi-page PDFs → schema-constrained JSON (9B, runs on the default image)
91
+ hf jobs uv run --flavor a100-large --secrets HF_TOKEN \
92
+ https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lift-extract.py \
93
+ your-input-dataset your-output-dataset \
94
+ --schema '{"type":"object","properties":{"title":{"type":"string"}}}' --max-samples 5
95
+ ```
96
+
97
  ```bash
98
  # image → JSON directly
99
  hf jobs uv run --flavor l4x1 --secrets HF_TOKEN \
lift-extract.py ADDED
@@ -0,0 +1,812 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.12"
3
+ # dependencies = [
4
+ # "lift-pdf[hf]",
5
+ # "datasets>=3.1.0",
6
+ # "huggingface-hub",
7
+ # "pillow",
8
+ # "toolz",
9
+ # "tqdm",
10
+ # ]
11
+ # ///
12
+ """
13
+ Extract structured JSON from document images OR multi-page PDFs using Datalab's
14
+ `lift` model (`datalab-to/lift`, 9B, Qwen3.5-based).
15
+
16
+ Unlike the markdown-OCR scripts here, lift does *schema-constrained* extraction:
17
+ you give it a JSON Schema, it returns a JSON object matching that schema. It
18
+ natively handles multi-page documents — a whole PDF is collapsed into a single
19
+ extraction.
20
+
21
+ Two in-process backends, selected with `--method` (no server, single command):
22
+
23
+ --method hf (default) Transformers via the `lift-pdf` package. Runs on the
24
+ default uv image. Simplest path; best for small jobs.
25
+ --method vllm vLLM's offline `LLM()` engine (`llm.chat`) with
26
+ structured-output decoding — the fast batched path the
27
+ other vLLM OCR scripts here use. Needs the
28
+ `vllm/vllm-openai` image (which ships vLLM). Reproduces
29
+ lift's own prompt + guided-JSON recipe against the
30
+ offline engine. Wins on large jobs via continuous batching.
31
+
32
+ Benchmark the two by pushing each to one repo with `--config hf` / `--config vllm`.
33
+
34
+ Input is one document per row:
35
+ --image-column COL (default `image`) one image per row -> one extraction
36
+ --pdf-column COL PDF bytes per row -> one extraction
37
+ (multi-page; respects --page-range)
38
+
39
+ Pass `--schema` as inline JSON, a URL, or a file path (standard JSON Schema):
40
+
41
+ --schema '{"type":"object","properties":{"invoice_number":{"type":"string"},
42
+ "total":{"type":"number"}},"required":["invoice_number"]}'
43
+
44
+ LICENSE NOTE: lift's *code* is Apache-2.0 but the *weights* are a modified
45
+ OpenRAIL-M license — free for research, personal use, and startups under $5M
46
+ funding/revenue, but restricted from competitive use against Datalab's API.
47
+ Confirm you are within those terms before using it. https://huggingface.co/datalab-to/lift
48
+
49
+ HF Jobs — HF backend (default image is fine; 9B needs a roomy GPU):
50
+
51
+ hf jobs uv run --flavor a100-large -s HF_TOKEN \\
52
+ https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lift-extract.py \\
53
+ INPUT_DATASET OUTPUT_DATASET \\
54
+ --schema '{"type":"object","properties":{"title":{"type":"string"}}}' \\
55
+ --max-samples 5 --shuffle --seed 42
56
+
57
+ HF Jobs — vLLM offline backend (use the vllm image so vLLM is present):
58
+
59
+ hf jobs uv run --flavor a100-large -s HF_TOKEN \\
60
+ --image vllm/vllm-openai --python /usr/bin/python3 \\
61
+ -e PYTHONPATH=/usr/local/lib/python3.12/dist-packages \\
62
+ https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lift-extract.py \\
63
+ INPUT_DATASET OUTPUT_DATASET --method vllm \\
64
+ --schema '{"type":"object","properties":{"title":{"type":"string"}}}' \\
65
+ --max-samples 5
66
+
67
+ Model: datalab-to/lift (package: lift-pdf, https://github.com/datalab-to/lift)
68
+ """
69
+
70
+ import argparse
71
+ import base64
72
+ import io
73
+ import json
74
+ import logging
75
+ import os
76
+ import sys
77
+ import tempfile
78
+ import time
79
+ from datetime import datetime, timezone
80
+ from typing import Any, Dict, List, Optional, Tuple
81
+ from urllib.request import urlopen
82
+
83
+ from datasets import load_dataset
84
+ from huggingface_hub import DatasetCard, login
85
+ from PIL import Image
86
+ from toolz import partition_all
87
+ from tqdm import tqdm
88
+
89
+ logging.basicConfig(level=logging.INFO)
90
+ logger = logging.getLogger(__name__)
91
+
92
+ # The package default checkpoint drifts between releases (e.g. "datalab-to/lift-extract");
93
+ # pin to the canonical card repo so the script is stable across lift-pdf versions.
94
+ DEFAULT_MODEL = "datalab-to/lift"
95
+ DEFAULT_MAX_TOKENS = 12384 # lift-pdf's own MAX_OUTPUT_TOKENS default
96
+
97
+ # A processed document: (parsed JSON or None, error flag, raw model text).
98
+ DocResult = Tuple[Optional[Any], bool, str]
99
+
100
+
101
+ def check_cuda_availability() -> None:
102
+ """Exit early with a clear message if there's no GPU."""
103
+ import torch
104
+
105
+ if not torch.cuda.is_available():
106
+ logger.error("CUDA is not available. This script requires a GPU.")
107
+ logger.error(
108
+ "Run on Hugging Face Jobs with: hf jobs uv run --flavor a100-large ..."
109
+ )
110
+ sys.exit(1)
111
+ logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
112
+
113
+
114
+ def load_schema_arg(value: str) -> Dict[str, Any]:
115
+ """Resolve --schema (inline JSON, a URL, or a file path) into a JSON Schema dict."""
116
+ text = value.strip()
117
+ if text.startswith(("http://", "https://")):
118
+ logger.info(f"Loading schema from URL: {text}")
119
+ text = urlopen(text).read().decode("utf-8") # noqa: S310
120
+ elif not text.startswith("{"):
121
+ # Looks like a path (inline JSON would start with "{"); read it if it exists.
122
+ if os.path.isfile(text):
123
+ logger.info(f"Loading schema from file: {text}")
124
+ with open(text) as f:
125
+ text = f.read()
126
+ try:
127
+ parsed = json.loads(text)
128
+ except json.JSONDecodeError as e:
129
+ raise ValueError(
130
+ f"Could not parse --schema as JSON (tried URL/path/inline): {e}"
131
+ ) from e
132
+ if not isinstance(parsed, dict):
133
+ raise ValueError("--schema must be a JSON object (a JSON Schema).")
134
+ return parsed
135
+
136
+
137
+ def cell_to_bytes(cell: Any) -> bytes:
138
+ """Normalize an HF dataset cell (image or document) to raw file bytes.
139
+
140
+ Handles decoded PIL images (Image feature), {"bytes"/"path"} dicts, raw bytes
141
+ (e.g. a binary PDF column), and string paths/URLs.
142
+ """
143
+ if isinstance(cell, Image.Image):
144
+ buf = io.BytesIO()
145
+ cell.convert("RGB").save(buf, format="PNG")
146
+ return buf.getvalue()
147
+ if isinstance(cell, dict):
148
+ if cell.get("bytes"):
149
+ return cell["bytes"]
150
+ if cell.get("path"):
151
+ with open(cell["path"], "rb") as f:
152
+ return f.read()
153
+ raise ValueError(
154
+ f"Unsupported image/document dict (no bytes/path): {list(cell)}"
155
+ )
156
+ if isinstance(cell, (bytes, bytearray)):
157
+ return bytes(cell)
158
+ if isinstance(cell, str):
159
+ if cell.startswith(("http://", "https://")):
160
+ return urlopen(cell).read() # noqa: S310
161
+ with open(cell, "rb") as f:
162
+ return f.read()
163
+ raise ValueError(f"Unsupported cell type: {type(cell)}")
164
+
165
+
166
+ def load_document_images(
167
+ load_file, cell: Any, page_range: Optional[str]
168
+ ) -> List[Image.Image]:
169
+ """Render one dataset cell into the page images lift expects.
170
+
171
+ Reuses lift's own `load_file`, which auto-detects PDF vs image by content
172
+ (pypdfium2 for PDFs, with the model's DPI/min-dim and page-range handling).
173
+ """
174
+ data = cell_to_bytes(cell)
175
+ # load_file detects type from content, so the temp file needs no extension.
176
+ with tempfile.NamedTemporaryFile(delete=False) as tmp:
177
+ tmp.write(data)
178
+ path = tmp.name
179
+ try:
180
+ config = {"page_range": page_range} if page_range else {}
181
+ return load_file(path, config)
182
+ finally:
183
+ os.unlink(path)
184
+
185
+
186
+ def pil_to_data_uri(img: Image.Image) -> str:
187
+ """PNG data URI for an OpenAI-format image content block."""
188
+ if img.mode != "RGB":
189
+ img = img.convert("RGB")
190
+ buf = io.BytesIO()
191
+ img.save(buf, format="PNG")
192
+ return f"data:image/png;base64,{base64.b64encode(buf.getvalue()).decode()}"
193
+
194
+
195
+ def parse_json_output(text: str) -> Tuple[Optional[Any], bool]:
196
+ """Return (parsed, ok). Strips ```json fences if present."""
197
+ stripped = text.strip()
198
+ if stripped.startswith("```"):
199
+ stripped = stripped.split("\n", 1)[-1] if "\n" in stripped else stripped[3:]
200
+ if stripped.endswith("```"):
201
+ stripped = stripped[:-3].rstrip()
202
+ try:
203
+ return json.loads(stripped), True
204
+ except (json.JSONDecodeError, ValueError):
205
+ return None, False
206
+
207
+
208
+ # --- HF backend (lift-pdf package, in-process Transformers) ---
209
+ def make_hf_processor(schema: Dict[str, Any], max_tokens: Optional[int]):
210
+ """Load lift via the package's HF backend; return a batch-processing closure."""
211
+ from lift.model import InferenceManager
212
+ from lift.model.schema import BatchInputItem
213
+
214
+ logger.info("Loading lift via Transformers (method=hf)...")
215
+ manager = InferenceManager(method="hf")
216
+
217
+ def process(image_lists: List[List[Image.Image]]) -> List[DocResult]:
218
+ items = [
219
+ BatchInputItem(images=imgs, schema=schema, prompt_type="direct")
220
+ for imgs in image_lists
221
+ ]
222
+ results = manager.generate(items, max_output_tokens=max_tokens)
223
+ return [(r.extraction, bool(r.error), r.raw) for r in results]
224
+
225
+ return process
226
+
227
+
228
+ # --- vLLM backend (offline LLM() engine + structured outputs) ---
229
+ def build_guided_schema(schema: Dict[str, Any]) -> Dict[str, Any]:
230
+ """Reproduce lift's vLLM guided-decoding schema: JSON Schema -> pydantic ->
231
+ json_schema with every leaf made nullable (so absent fields can be null,
232
+ matching lift's own server-side behavior)."""
233
+ from json_schema_to_pydantic import create_model
234
+ from lift.model.vllm import make_properties_nullable
235
+
236
+ schema_model = create_model(schema)
237
+ json_schema = schema_model.model_json_schema()
238
+ make_properties_nullable(json_schema)
239
+ return json_schema
240
+
241
+
242
+ def make_sampling_params(json_schema: Dict[str, Any], max_tokens: int):
243
+ """SamplingParams with structured JSON output, across vLLM API versions.
244
+
245
+ lift uses greedy-ish decoding (temperature 0.0, top_p 0.1).
246
+ """
247
+ from vllm import SamplingParams
248
+
249
+ # vLLM >= 0.12
250
+ try:
251
+ from vllm.sampling_params import StructuredOutputsParams
252
+
253
+ return SamplingParams(
254
+ temperature=0.0,
255
+ top_p=0.1,
256
+ max_tokens=max_tokens,
257
+ structured_outputs=StructuredOutputsParams(json=json_schema),
258
+ )
259
+ except (ImportError, TypeError):
260
+ pass
261
+ # Older vLLM
262
+ try:
263
+ from vllm.sampling_params import GuidedDecodingParams
264
+
265
+ return SamplingParams(
266
+ temperature=0.0,
267
+ top_p=0.1,
268
+ max_tokens=max_tokens,
269
+ guided_decoding=GuidedDecodingParams(json=json_schema),
270
+ )
271
+ except (ImportError, TypeError):
272
+ pass
273
+ logger.warning(
274
+ "Structured output unavailable in this vLLM version; relying on lift's "
275
+ "training to emit valid JSON."
276
+ )
277
+ return SamplingParams(temperature=0.0, top_p=0.1, max_tokens=max_tokens)
278
+
279
+
280
+ def make_vllm_processor(
281
+ schema: Dict[str, Any],
282
+ model: str,
283
+ max_tokens: Optional[int],
284
+ max_model_len: int,
285
+ gpu_memory_utilization: float,
286
+ max_images_per_doc: int,
287
+ ):
288
+ """Load lift into vLLM's offline engine; return a batch-processing closure."""
289
+ try:
290
+ from vllm import LLM
291
+ except ImportError as e:
292
+ raise RuntimeError(
293
+ "--method vllm needs vLLM. Run on the vllm/vllm-openai image: "
294
+ "--image vllm/vllm-openai --python /usr/bin/python3 "
295
+ "-e PYTHONPATH=/usr/local/lib/python3.12/dist-packages"
296
+ ) from e
297
+ from lift.model.util import scale_to_fit
298
+ from lift.prompts import PROMPT_MAPPING
299
+
300
+ json_schema = build_guided_schema(schema)
301
+ prompt = PROMPT_MAPPING["direct"].replace("{schema}", json.dumps(schema, indent=2))
302
+
303
+ logger.info("Loading lift via vLLM offline engine (method=vllm)...")
304
+ llm = LLM(
305
+ model=model,
306
+ trust_remote_code=True,
307
+ max_model_len=max_model_len,
308
+ gpu_memory_utilization=gpu_memory_utilization,
309
+ limit_mm_per_prompt={"image": max_images_per_doc},
310
+ # lift's own server-side image bounds, applied by the offline processor too.
311
+ mm_processor_kwargs={"min_pixels": 3136, "max_pixels": 861696},
312
+ )
313
+ sampling_params = make_sampling_params(
314
+ json_schema, max_tokens or DEFAULT_MAX_TOKENS
315
+ )
316
+
317
+ def process(image_lists: List[List[Image.Image]]) -> List[DocResult]:
318
+ messages = []
319
+ for imgs in image_lists:
320
+ content = [
321
+ {
322
+ "type": "image_url",
323
+ "image_url": {"url": pil_to_data_uri(scale_to_fit(img))},
324
+ }
325
+ for img in imgs
326
+ ]
327
+ content.append({"type": "text", "text": prompt})
328
+ messages.append([{"role": "user", "content": content}])
329
+ outputs = llm.chat(
330
+ messages, sampling_params, chat_template_content_format="openai"
331
+ )
332
+ results: List[DocResult] = []
333
+ for o in outputs:
334
+ raw = o.outputs[0].text
335
+ parsed, ok = parse_json_output(raw)
336
+ results.append((parsed if ok else None, not ok, raw))
337
+ return results
338
+
339
+ return process
340
+
341
+
342
+ def create_dataset_card(
343
+ source_dataset: str,
344
+ model: str,
345
+ method: str,
346
+ schema: Dict[str, Any],
347
+ num_samples: int,
348
+ n_valid: int,
349
+ source_column: str,
350
+ is_pdf: bool,
351
+ page_range: Optional[str],
352
+ output_column: str,
353
+ split: str,
354
+ processing_time: str,
355
+ ) -> str:
356
+ """Build the output dataset card documenting the lift run."""
357
+ schema_block = json.dumps(schema, indent=2)
358
+ input_kind = "PDF documents" if is_pdf else "images"
359
+ col_desc = "PDF" if is_pdf else "image"
360
+ if page_range:
361
+ col_desc += f", pages {page_range}"
362
+ backend_desc = (
363
+ "vLLM offline engine" if method == "vllm" else "Transformers (lift-pdf)"
364
+ )
365
+ return f"""---
366
+ tags:
367
+ - ocr
368
+ - structured-extraction
369
+ - document-processing
370
+ - lift
371
+ - json
372
+ - uv-script
373
+ - generated
374
+ ---
375
+
376
+ # lift structured extraction on {source_dataset}
377
+
378
+ Schema-constrained JSON extracted from {input_kind} in
379
+ [{source_dataset}](https://huggingface.co/datasets/{source_dataset}) using
380
+ [lift](https://huggingface.co/{model}) (9B, Qwen3.5-based) by Datalab, via the
381
+ [`lift-pdf`](https://github.com/datalab-to/lift) package.
382
+
383
+ ## Processing Details
384
+
385
+ - **Source Dataset**: [{source_dataset}](https://huggingface.co/datasets/{source_dataset})
386
+ - **Model**: [{model}](https://huggingface.co/{model})
387
+ - **Backend**: `{method}` ({backend_desc})
388
+ - **Input column**: `{source_column}` ({col_desc})
389
+ - **Output column**: `{output_column}` (JSON string per row)
390
+ - **Split**: `{split}`
391
+ - **Samples**: {num_samples:,}
392
+ - **Valid JSON**: {n_valid:,} / {num_samples:,}
393
+ - **Processing time**: {processing_time}
394
+ - **Date**: {datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")}
395
+
396
+ ### Extraction Schema
397
+
398
+ ```json
399
+ {schema_block}
400
+ ```
401
+
402
+ ## License note
403
+
404
+ lift's code is Apache-2.0, but the model **weights** use a modified OpenRAIL-M
405
+ license: free for research, personal use, and startups under $5M funding/revenue,
406
+ restricted from competitive use against Datalab's API. See the
407
+ [model card](https://huggingface.co/{model}).
408
+
409
+ ## Dataset Structure
410
+
411
+ Original columns plus:
412
+ - `{output_column}`: lift output (JSON string; raw text kept on parse failure)
413
+ - `inference_info`: JSON list tracking models applied to this dataset
414
+
415
+ Generated with [UV Scripts](https://huggingface.co/uv-scripts).
416
+ """
417
+
418
+
419
+ def main(
420
+ input_dataset: str,
421
+ output_dataset: str,
422
+ schema_arg: str,
423
+ image_column: str = "image",
424
+ pdf_column: Optional[str] = None,
425
+ output_column: str = "extraction",
426
+ method: str = "hf",
427
+ page_range: Optional[str] = None,
428
+ split: str = "train",
429
+ max_samples: Optional[int] = None,
430
+ shuffle: bool = False,
431
+ seed: int = 42,
432
+ batch_size: int = 8,
433
+ max_tokens: Optional[int] = None,
434
+ max_model_len: int = 32768,
435
+ gpu_memory_utilization: float = 0.9,
436
+ max_images_per_doc: Optional[int] = None,
437
+ model: str = DEFAULT_MODEL,
438
+ private: bool = False,
439
+ config: Optional[str] = None,
440
+ create_pr: bool = False,
441
+ hf_token: Optional[str] = None,
442
+ verbose: bool = False,
443
+ ) -> None:
444
+ # Unlock full Xet bandwidth for the 9B (~19GB) model download (repo convention).
445
+ os.environ["HF_XET_HIGH_PERFORMANCE"] = "1"
446
+ check_cuda_availability()
447
+ start_time = datetime.now(timezone.utc)
448
+
449
+ HF_TOKEN = hf_token or os.environ.get("HF_TOKEN")
450
+ if HF_TOKEN:
451
+ login(token=HF_TOKEN)
452
+
453
+ schema = load_schema_arg(schema_arg)
454
+
455
+ # lift reads the checkpoint from env (pydantic-settings) at import time; set it first.
456
+ os.environ["MODEL_CHECKPOINT"] = model
457
+
458
+ # Import lift only after env is set so settings pick up the right checkpoint.
459
+ from lift import resolve_schema
460
+ from lift.input import load_file
461
+
462
+ schema = resolve_schema(schema) # validates and normalizes
463
+ fields = list(schema.get("properties", {}).keys())
464
+
465
+ source_column = pdf_column or image_column
466
+ is_pdf = pdf_column is not None
467
+ # vLLM caps images per prompt at init; PDFs need headroom for multiple pages.
468
+ if max_images_per_doc is None:
469
+ max_images_per_doc = 30 if is_pdf else 1
470
+
471
+ logger.info(f"Model: {model} Backend: {method}")
472
+ logger.info(f"Schema top-level fields: {fields}")
473
+
474
+ logger.info(f"Loading dataset: {input_dataset} (split={split})")
475
+ dataset = load_dataset(input_dataset, split=split)
476
+ if source_column not in dataset.column_names:
477
+ logger.error(
478
+ f"Column '{source_column}' not found. Available: {dataset.column_names}"
479
+ )
480
+ sys.exit(1)
481
+ if shuffle:
482
+ dataset = dataset.shuffle(seed=seed)
483
+ if max_samples:
484
+ dataset = dataset.select(range(min(max_samples, len(dataset))))
485
+ logger.info(f"Processing {len(dataset)} documents from column '{source_column}'")
486
+
487
+ if method == "vllm":
488
+ process_batch = make_vllm_processor(
489
+ schema,
490
+ model,
491
+ max_tokens,
492
+ max_model_len,
493
+ gpu_memory_utilization,
494
+ max_images_per_doc,
495
+ )
496
+ else:
497
+ process_batch = make_hf_processor(schema, max_tokens)
498
+
499
+ extractions: List[Optional[str]] = [None] * len(dataset)
500
+ error_flags: List[bool] = [True] * len(dataset)
501
+
502
+ chunks = list(partition_all(batch_size, range(len(dataset))))
503
+ for chunk in tqdm(chunks, desc="Extracting"):
504
+ chunk = list(chunk)
505
+ rendered: Dict[int, List[Image.Image]] = {}
506
+ for i in chunk:
507
+ try:
508
+ rendered[i] = load_document_images(
509
+ load_file, dataset[i][source_column], page_range
510
+ )
511
+ except Exception as e:
512
+ logger.warning(f"Row {i}: failed to load document: {e}")
513
+ extractions[i] = f"[LIFT LOAD ERROR] {e}"
514
+ error_flags[i] = True
515
+ if not rendered:
516
+ continue
517
+
518
+ idxs = list(rendered.keys())
519
+ try:
520
+ results = process_batch([rendered[i] for i in idxs])
521
+ except Exception as e:
522
+ logger.error(f"Batch generate failed: {e}")
523
+ for i in idxs:
524
+ extractions[i] = "[LIFT GENERATE ERROR]"
525
+ error_flags[i] = True
526
+ continue
527
+
528
+ for i, (parsed, err, raw) in zip(idxs, results):
529
+ if parsed is not None and not err:
530
+ extractions[i] = json.dumps(parsed, ensure_ascii=False)
531
+ error_flags[i] = False
532
+ else:
533
+ extractions[i] = raw if raw else "[LIFT EMPTY OUTPUT]"
534
+ error_flags[i] = True
535
+
536
+ n_valid = sum(not f for f in error_flags)
537
+ logger.info(f"Valid JSON: {n_valid}/{len(dataset)}")
538
+
539
+ dataset = dataset.add_column(output_column, extractions)
540
+
541
+ inference_entry = {
542
+ "model": model,
543
+ "model_name": "lift",
544
+ "column_name": output_column,
545
+ "task": "schema-constrained extraction",
546
+ "backend": method,
547
+ "fields": fields,
548
+ "page_range": page_range,
549
+ "parse_error_rate": (len(dataset) - n_valid) / len(dataset)
550
+ if len(dataset)
551
+ else 0.0,
552
+ "timestamp": datetime.now(timezone.utc).isoformat(),
553
+ "script": "lift-extract.py",
554
+ }
555
+ if "inference_info" in dataset.column_names:
556
+
557
+ def update_info(example):
558
+ try:
559
+ existing = (
560
+ json.loads(example["inference_info"])
561
+ if example["inference_info"]
562
+ else []
563
+ )
564
+ except (json.JSONDecodeError, TypeError):
565
+ existing = []
566
+ existing.append(inference_entry)
567
+ return {"inference_info": json.dumps(existing)}
568
+
569
+ dataset = dataset.map(update_info)
570
+ else:
571
+ dataset = dataset.add_column(
572
+ "inference_info", [json.dumps([inference_entry])] * len(dataset)
573
+ )
574
+
575
+ processing_time = (
576
+ f"{(datetime.now(timezone.utc) - start_time).total_seconds() / 60:.1f} min"
577
+ )
578
+
579
+ logger.info(f"Pushing to {output_dataset}")
580
+ max_retries = 3
581
+ for attempt in range(1, max_retries + 1):
582
+ try:
583
+ if attempt > 1:
584
+ logger.warning("Disabling XET (fallback to HTTP upload)")
585
+ os.environ["HF_HUB_DISABLE_XET"] = "1"
586
+ dataset.push_to_hub(
587
+ output_dataset,
588
+ private=private,
589
+ token=HF_TOKEN,
590
+ max_shard_size="500MB",
591
+ create_pr=create_pr,
592
+ **({"config_name": config} if config else {}),
593
+ commit_message=f"Add lift extraction results ({len(dataset)} samples)"
594
+ + (f" [{config}]" if config else ""),
595
+ )
596
+ break
597
+ except Exception as e:
598
+ logger.error(f"Upload attempt {attempt}/{max_retries} failed: {e}")
599
+ if attempt < max_retries:
600
+ delay = 30 * (2 ** (attempt - 1))
601
+ logger.info(f"Retrying in {delay}s...")
602
+ time.sleep(delay)
603
+ else:
604
+ logger.error("All upload attempts failed. Results are lost.")
605
+ sys.exit(1)
606
+
607
+ try:
608
+ card = DatasetCard(
609
+ create_dataset_card(
610
+ source_dataset=input_dataset,
611
+ model=model,
612
+ method=method,
613
+ schema=schema,
614
+ num_samples=len(dataset),
615
+ n_valid=n_valid,
616
+ source_column=source_column,
617
+ is_pdf=is_pdf,
618
+ page_range=page_range,
619
+ output_column=output_column,
620
+ split=split,
621
+ processing_time=processing_time,
622
+ )
623
+ )
624
+ card.push_to_hub(output_dataset, token=HF_TOKEN)
625
+ except Exception as e:
626
+ logger.warning(f"Could not push dataset card: {e}")
627
+
628
+ logger.info("Done! lift extraction complete.")
629
+ logger.info(f"Dataset: https://huggingface.co/datasets/{output_dataset}")
630
+ logger.info(f"Processing time: {processing_time}")
631
+
632
+ if verbose:
633
+ import importlib.metadata
634
+
635
+ logger.info("--- Resolved package versions ---")
636
+ pkgs = ["lift-pdf", "transformers", "torch", "datasets", "pillow", "openai"]
637
+ if method == "vllm":
638
+ pkgs.append("vllm")
639
+ for pkg in pkgs:
640
+ try:
641
+ logger.info(f" {pkg}=={importlib.metadata.version(pkg)}")
642
+ except importlib.metadata.PackageNotFoundError:
643
+ logger.info(f" {pkg}: not installed")
644
+
645
+
646
+ if __name__ == "__main__":
647
+ if len(sys.argv) == 1:
648
+ print("lift — schema-constrained JSON extraction from images & PDFs (9B)")
649
+ print("\nUsage:")
650
+ print(" uv run lift-extract.py INPUT OUTPUT --schema SCHEMA [options]")
651
+ print("\nExamples:")
652
+ print(" # image column -> JSON")
653
+ print(" uv run lift-extract.py my-images my-fields \\")
654
+ print(
655
+ ' --schema \'{"type":"object","properties":{"title":{"type":"string"}}}\''
656
+ )
657
+ print("\n # multi-page PDFs -> JSON (one extraction per document)")
658
+ print(
659
+ " uv run lift-extract.py my-pdfs my-fields --pdf-column pdf --page-range 0-5 \\"
660
+ )
661
+ print(" --schema schema.json")
662
+ print("\n --schema accepts inline JSON, a URL, or a file path.")
663
+ print(
664
+ " --method hf (default) | vllm (offline LLM engine; needs the vllm image)"
665
+ )
666
+ print("\nFor full help: uv run lift-extract.py --help")
667
+ sys.exit(0)
668
+
669
+ parser = argparse.ArgumentParser(
670
+ description="Schema-constrained JSON extraction from images & PDFs using datalab-to/lift",
671
+ formatter_class=argparse.RawDescriptionHelpFormatter,
672
+ epilog="""
673
+ Backends (both in-process, single command):
674
+ --method hf Transformers via lift-pdf (default). Simplest; default image.
675
+ --method vllm vLLM offline LLM() engine with structured outputs. Faster on
676
+ large jobs. Needs the vllm/vllm-openai image.
677
+
678
+ Input (one document per row):
679
+ --image-column COL one image per row (default: image)
680
+ --pdf-column COL PDF bytes per row (multi-page; honors --page-range)
681
+ """,
682
+ )
683
+ parser.add_argument(
684
+ "input_dataset", help="Input dataset ID from the Hugging Face Hub"
685
+ )
686
+ parser.add_argument(
687
+ "output_dataset", help="Output dataset ID for the Hugging Face Hub"
688
+ )
689
+ parser.add_argument(
690
+ "--schema",
691
+ required=True,
692
+ help="JSON Schema: inline JSON, a URL, or a file path",
693
+ )
694
+ parser.add_argument(
695
+ "--image-column", default="image", help="Image column (default: image)"
696
+ )
697
+ parser.add_argument(
698
+ "--pdf-column",
699
+ default=None,
700
+ help="PDF column (bytes/path). Mutually exclusive with --image-column.",
701
+ )
702
+ parser.add_argument(
703
+ "--output-column",
704
+ default="extraction",
705
+ help="Output column (default: extraction)",
706
+ )
707
+ parser.add_argument(
708
+ "--method",
709
+ choices=["hf", "vllm"],
710
+ default="hf",
711
+ help="Inference backend (default: hf)",
712
+ )
713
+ parser.add_argument(
714
+ "--page-range",
715
+ default=None,
716
+ help="Pages to extract from PDFs, e.g. '0-5,7' (PDF column only)",
717
+ )
718
+ parser.add_argument(
719
+ "--split", default="train", help="Dataset split (default: train)"
720
+ )
721
+ parser.add_argument(
722
+ "--max-samples", type=int, help="Limit number of documents (for testing)"
723
+ )
724
+ parser.add_argument(
725
+ "--shuffle", action="store_true", help="Shuffle before sampling"
726
+ )
727
+ parser.add_argument(
728
+ "--seed", type=int, default=42, help="Shuffle seed (default: 42)"
729
+ )
730
+ parser.add_argument(
731
+ "--batch-size",
732
+ type=int,
733
+ default=8,
734
+ help="Documents per generate() call (default: 8; lower for big multi-page PDFs)",
735
+ )
736
+ parser.add_argument(
737
+ "--max-tokens",
738
+ type=int,
739
+ default=None,
740
+ help=f"Max output tokens (default: lift's {DEFAULT_MAX_TOKENS})",
741
+ )
742
+ parser.add_argument(
743
+ "--max-model-len",
744
+ type=int,
745
+ default=32768,
746
+ help="vLLM context length (default: 32768; raise for long multi-page PDFs)",
747
+ )
748
+ parser.add_argument(
749
+ "--gpu-memory-utilization",
750
+ type=float,
751
+ default=0.9,
752
+ help="vLLM GPU memory fraction (default: 0.9)",
753
+ )
754
+ parser.add_argument(
755
+ "--max-images-per-doc",
756
+ type=int,
757
+ default=None,
758
+ help="vLLM images-per-prompt cap (default: 1 for images, 30 for PDFs)",
759
+ )
760
+ parser.add_argument(
761
+ "--model", default=DEFAULT_MODEL, help=f"Model ID (default: {DEFAULT_MODEL})"
762
+ )
763
+ parser.add_argument(
764
+ "--private", action="store_true", help="Make output dataset private"
765
+ )
766
+ parser.add_argument(
767
+ "--config",
768
+ default=None,
769
+ help="Config/subset name when pushing (for benchmarking backends in one repo)",
770
+ )
771
+ parser.add_argument(
772
+ "--create-pr",
773
+ action="store_true",
774
+ help="Push as a pull request instead of directly (for parallel benchmarking)",
775
+ )
776
+ parser.add_argument("--hf-token", help="Hugging Face API token (or set HF_TOKEN)")
777
+ parser.add_argument(
778
+ "--verbose",
779
+ action="store_true",
780
+ help="Log resolved package versions after processing",
781
+ )
782
+
783
+ args = parser.parse_args()
784
+
785
+ if args.pdf_column and args.image_column != "image":
786
+ parser.error("--image-column and --pdf-column are mutually exclusive.")
787
+
788
+ main(
789
+ input_dataset=args.input_dataset,
790
+ output_dataset=args.output_dataset,
791
+ schema_arg=args.schema,
792
+ image_column=args.image_column,
793
+ pdf_column=args.pdf_column,
794
+ output_column=args.output_column,
795
+ method=args.method,
796
+ page_range=args.page_range,
797
+ split=args.split,
798
+ max_samples=args.max_samples,
799
+ shuffle=args.shuffle,
800
+ seed=args.seed,
801
+ batch_size=args.batch_size,
802
+ max_tokens=args.max_tokens,
803
+ max_model_len=args.max_model_len,
804
+ gpu_memory_utilization=args.gpu_memory_utilization,
805
+ max_images_per_doc=args.max_images_per_doc,
806
+ model=args.model,
807
+ private=args.private,
808
+ config=args.config,
809
+ create_pr=args.create_pr,
810
+ hf_token=args.hf_token,
811
+ verbose=args.verbose,
812
+ )