File size: 11,658 Bytes
19757f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
# /// script
# requires-python = ">=3.11"
# dependencies = [
#     "datasets>=4.0.0",
#     "huggingface-hub",
#     "vllm",
#     "transformers",
#     "tqdm",
#     "toolz",
#     "torch",
# ]
# ///
"""
Extract structured data (JSON / XML / YAML) from text using LiquidAI's LFM2-1.2B-Extract.

LFM2-1.2B-Extract is a compact 1.2B text-only model purpose-built for turning unstructured
documents into structured data: give it a schema, it returns JSON, XML, or YAML. It reports
beating Gemma 3 27B (22x larger) on syntax validity / format accuracy / faithfulness, and
is multilingual (en, ar, zh, fr, de, ja, ko, pt, es).

This is the *text* counterpart to `lfm2-vl-extract.py` (which extracts from images). Pair them:
OCR a page to markdown with one of the OCR recipes, then extract fields from that text here.

Pass `--schema` as inline text/JSON, a URL, or a file path describing the structure to extract:

    --schema '{"invoice_number": "string", "total": "number", "line_items": "array"}'

Model:  https://huggingface.co/LiquidAI/LFM2-1.2B-Extract
Docs:   https://docs.liquid.ai/deployment/gpu-inference/vllm

HF Jobs note: run on the vLLM image so the CUDA toolkit + prebuilt FlashInfer kernels are
present and startup is fast (it reuses the image's CUDA-matched vLLM build):

    hf jobs uv run --flavor l4x1 --secrets HF_TOKEN \
        --image vllm/vllm-openai --python /usr/bin/python3 \
        -e PYTHONPATH=/usr/local/lib/python3.12/dist-packages \
        https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lfm2-extract.py \
        INPUT OUTPUT --text-column text --schema '{"field": "description"}'

It also runs on the default uv image, just with a slower first-time vLLM build. Deps are left
unpinned so uv resolves a recent vLLM; FlashInfer sampling is disabled (see below) so the engine
never JIT-compiles a kernel that needs nvcc — absent from the default image.
"""

import argparse
import json
import logging
import os
import sys
from datetime import datetime, timezone
from typing import List, Optional
from urllib.request import urlopen

# Disable vLLM's FlashInfer sampler before the engine starts: it JIT-compiles at warmup and
# needs nvcc (absent from the default uv image). Harmless for greedy decoding.
os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0")

import torch
from datasets import load_dataset
from huggingface_hub import DatasetCard, login
from toolz import partition_all
from tqdm import tqdm
from vllm import LLM, SamplingParams

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

DEFAULT_MODEL = "LiquidAI/LFM2-1.2B-Extract"
FORMATS = {"json": "JSON", "xml": "XML", "yaml": "YAML"}


def check_cuda_availability() -> None:
    if not torch.cuda.is_available():
        logger.error("CUDA is not available. This script requires a GPU.")
        logger.error("Run on Hugging Face Jobs with: hf jobs uv run --flavor l4x1 ...")
        sys.exit(1)
    logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name()}")


def load_text_arg(value: str) -> str:
    """Resolve --schema (inline text/JSON, URL, or file path) into a string."""
    text = value.strip()
    if text.startswith("http://") or text.startswith("https://"):
        logger.info(f"Loading schema from URL: {text}")
        return urlopen(text).read().decode("utf-8").strip()
    if os.path.exists(text):
        logger.info(f"Loading schema from file: {text}")
        with open(text) as f:
            return f.read().strip()
    return text


def build_system_prompt(schema_text: str, fmt: str) -> str:
    return f"Return data as a {FORMATS[fmt]} object with the following schema:\n\n{schema_text}"


def parse_output(text: str, fmt: str) -> tuple[str, bool]:
    """Strip code fences; for JSON, validate. Returns (cleaned_text, is_valid)."""
    stripped = text.strip()
    if stripped.startswith("```"):
        stripped = stripped.split("\n", 1)[-1]
        if stripped.endswith("```"):
            stripped = stripped.rsplit("```", 1)[0]
    stripped = stripped.strip()
    if fmt == "json":
        try:
            return json.dumps(json.loads(stripped), ensure_ascii=False), True
        except (json.JSONDecodeError, ValueError):
            return stripped, False
    return stripped, True  # xml/yaml: store as-is (no strict validator)


def main(
    input_dataset: str,
    output_dataset: str,
    schema: str,
    text_column: str = "text",
    output_column: str = "extraction",
    output_format: str = "json",
    split: str = "train",
    max_samples: Optional[int] = None,
    shuffle: bool = False,
    seed: int = 42,
    batch_size: int = 32,
    model: str = DEFAULT_MODEL,
    max_model_len: int = 8192,
    max_tokens: int = 4096,
    private: bool = False,
    hf_token: Optional[str] = None,
) -> None:
    check_cuda_availability()
    if output_format not in FORMATS:
        logger.error(f"--format must be one of {list(FORMATS)}; got {output_format}")
        sys.exit(1)

    HF_TOKEN = hf_token or os.environ.get("HF_TOKEN")
    if HF_TOKEN:
        login(token=HF_TOKEN)

    schema_text = load_text_arg(schema)
    system_prompt = build_system_prompt(schema_text, output_format)

    logger.info(f"Loading dataset: {input_dataset} (split={split})")
    dataset = load_dataset(input_dataset, split=split)
    if shuffle:
        dataset = dataset.shuffle(seed=seed)
    if max_samples:
        dataset = dataset.select(range(min(max_samples, len(dataset))))
    logger.info(f"Processing {len(dataset)} examples; format={output_format}")

    if text_column not in dataset.column_names:
        logger.error(f"Text column '{text_column}' not found. Columns: {dataset.column_names}")
        sys.exit(1)

    logger.info(f"Loading model: {model}")
    llm = LLM(model=model, max_model_len=max_model_len, enforce_eager=True)
    sampling_params = SamplingParams(temperature=0.0, max_tokens=max_tokens)

    all_outputs: List[str] = []
    n_valid = 0
    texts = dataset[text_column]
    for batch in tqdm(list(partition_all(batch_size, texts)), desc="Extracting"):
        batch_messages = [
            [
                {"role": "system", "content": system_prompt},
                {"role": "user", "content": str(doc)},
            ]
            for doc in batch
        ]
        outputs = llm.chat(batch_messages, sampling_params)
        for out in outputs:
            cleaned, ok = parse_output(out.outputs[0].text, output_format)
            n_valid += int(ok)
            all_outputs.append(cleaned)

    logger.info(f"Valid {output_format.upper()}: {n_valid}/{len(all_outputs)}")
    dataset = dataset.add_column(output_column, all_outputs)

    inference_entry = {
        "model": model,
        "column_name": output_column,
        "task": "structured extraction",
        "format": output_format,
        "timestamp": datetime.now(timezone.utc).isoformat(),
        "script": "lfm2-extract.py",
    }
    if "inference_info" in dataset.column_names:
        def update_info(example):
            try:
                existing = json.loads(example["inference_info"]) if example["inference_info"] else []
            except (json.JSONDecodeError, TypeError):
                existing = []
            existing.append(inference_entry)
            return {"inference_info": json.dumps(existing)}
        dataset = dataset.map(update_info)
    else:
        dataset = dataset.add_column(
            "inference_info", [json.dumps([inference_entry])] * len(dataset)
        )

    logger.info(f"Pushing to {output_dataset}")
    dataset.push_to_hub(output_dataset, private=private, token=HF_TOKEN)

    card_text = f"""---
tags:
- uv-script
- extraction
- lfm2
- {output_format}
---

# Structured extraction with LFM2-1.2B-Extract

`{output_format.upper()}` extracted from the `{text_column}` column of
[{input_dataset}](https://huggingface.co/datasets/{input_dataset})
using [{model}](https://huggingface.co/{model}).

- **Source**: `{input_dataset}` (split `{split}`, column `{text_column}`)
- **Model**: `{model}`
- **Format**: `{output_format}`
- **Output column**: `{output_column}`
- **Valid {output_format.upper()}**: {n_valid}/{len(all_outputs)}
- **Date**: {datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")}

Generated with the [uv-scripts/ocr](https://huggingface.co/datasets/uv-scripts/ocr) `lfm2-extract.py` script.
"""
    try:
        DatasetCard(card_text).push_to_hub(output_dataset, token=HF_TOKEN)
    except Exception as e:
        logger.warning(f"Could not push dataset card: {e}")

    logger.info("Done! Extraction complete.")
    logger.info(f"Dataset: https://huggingface.co/datasets/{output_dataset}")


if __name__ == "__main__":
    if len(sys.argv) == 1:
        print("LFM2-1.2B-Extract — structured extraction (JSON/XML/YAML) from text")
        print("\nUsage:")
        print("  uv run lfm2-extract.py INPUT OUTPUT --schema SCHEMA [--text-column text] [--format json]")
        print("\nExample:")
        print('  uv run lfm2-extract.py my-docs my-fields \\')
        print('    --text-column markdown \\')
        print('    --schema \'{"title": "the title", "date": "any date", "summary": "one sentence"}\'')
        print("\n  --schema accepts inline text/JSON, a URL, or a file path.")
        print("\nFor full help: uv run lfm2-extract.py --help")
        sys.exit(0)

    parser = argparse.ArgumentParser(
        description="Structured extraction (JSON/XML/YAML) from text using LFM2-1.2B-Extract",
    )
    parser.add_argument("input_dataset", help="Input dataset ID (with a text column)")
    parser.add_argument("output_dataset", help="Output dataset ID")
    parser.add_argument(
        "--schema", required=True,
        help="Structure to extract: inline text/JSON, a URL, or a file path",
    )
    parser.add_argument("--text-column", default="text", help="Text column (default: text)")
    parser.add_argument("--output-column", default="extraction", help="Output column (default: extraction)")
    parser.add_argument(
        "--format", dest="output_format", default="json", choices=list(FORMATS),
        help="Output format (default: json)",
    )
    parser.add_argument("--split", default="train", help="Dataset split (default: train)")
    parser.add_argument("--max-samples", type=int, help="Limit number of samples")
    parser.add_argument("--shuffle", action="store_true", help="Shuffle before sampling")
    parser.add_argument("--seed", type=int, default=42, help="Shuffle seed (default: 42)")
    parser.add_argument("--batch-size", type=int, default=32, help="Batch size (default: 32)")
    parser.add_argument("--model", default=DEFAULT_MODEL, help=f"Model (default: {DEFAULT_MODEL})")
    parser.add_argument("--max-model-len", type=int, default=8192, help="Max context length (default: 8192)")
    parser.add_argument("--max-tokens", type=int, default=4096, help="Max output tokens (default: 4096)")
    parser.add_argument("--private", action="store_true", help="Make output dataset private")
    parser.add_argument("--hf-token", help="HF token (or set HF_TOKEN)")
    args = parser.parse_args()

    main(
        input_dataset=args.input_dataset,
        output_dataset=args.output_dataset,
        schema=args.schema,
        text_column=args.text_column,
        output_column=args.output_column,
        output_format=args.output_format,
        split=args.split,
        max_samples=args.max_samples,
        shuffle=args.shuffle,
        seed=args.seed,
        batch_size=args.batch_size,
        model=args.model,
        max_model_len=args.max_model_len,
        max_tokens=args.max_tokens,
        private=args.private,
        hf_token=args.hf_token,
    )