Sync from davanstrien/uv-scripts via hub-sync
Browse filesFiles changed (6)
- CLAUDE.md+26-1
- README.md+3-2
- falcon-ocr-1.5.pyAdded+623
- falcon-ocr-bucket.py+22-3
- falcon-ocr.py+182-20
- models.json+38-5
111 unmodified lines112113114115116117118173 unmodified lines29229329429529629797 unmodified lines395396397398399400111 unmodified lines| `nuextract3.py`, `lfm2-extract.py`, `lfm2-vl-extract.py` | ✅ | vLLM | l4x1 | structured extraction || `hunyuan-ocr.py` | ✅ | vLLM | l4x1 | **1.0, revision-pinned** (root repo became 1.5 in-place); `transformers<5.13` cap — see gotcha || `hunyuan-ocr-1.5.py` | ✅ | vLLM | l4x1 | tracks repo root (=1.5); task-locked prompts; `transformers<5.13` cap — see gotcha || `rolm-ocr.py`, `smoldocling-ocr.py`, `numarkdown-ocr.py`, `qianfan-ocr.py`, `firered-ocr.py`, `abot-ocr.py`, `falcon-ocr.py`, `olmocr2-vllm.py`, `dots-mocr.py` | ✅ | vLLM | varies | see `README.md` for flags || `pp-ocrv6.py`, `pp-doclayout.py` | ✅ | PaddleOCR / PaddleX | l4x1 | classical det+rec; dataset **or** bucket I/O |**License note:** Surya and `lift` ship code as Apache-2.0 but **weights under a modified OpenRAIL-M**173 unmodified linesclient's `hunyuan_tasks.py`) and sampling is card-locked (temp 0.0, rep-penalty 1.08) — don't"improve" either; upstream observed hand-tweaked prompts silently degrade quality.### `glm-ocr.py`Chatty on blank pages / can emit degenerate repeats — that's **model quality, not a crash**; don'tre-debug it as a recipe bug. (The actual historical crash was the `pyarrow<18` cap — see Conventions.)97 unmodified lines## Change log- **2026-11-05** — added `hpd-parsing-saturate.py` (experimental) for `PaddlePaddle/HPD-Parsing` (1B,Apache-2.0): the July server recipe's serve command and block parser, driven by saturate `==0.3.0`(`Engine(cmd=…)` for the vendor fork), plus a `looped_blocks` flag. Header image111 unmodified lines112113114115116117118119120173 unmodified lines29429529629729829930030130230330430530630730830931031131231331497 unmodified lines412413414415416417418419420421422423424425111 unmodified lines| `nuextract3.py`, `lfm2-extract.py`, `lfm2-vl-extract.py` | ✅ | vLLM | l4x1 | structured extraction || `hunyuan-ocr.py` | ✅ | vLLM | l4x1 | **1.0, revision-pinned** (root repo became 1.5 in-place); `transformers<5.13` cap — see gotcha || `hunyuan-ocr-1.5.py` | ✅ | vLLM | l4x1 | tracks repo root (=1.5); task-locked prompts; `transformers<5.13` cap — see gotcha || `rolm-ocr.py`, `smoldocling-ocr.py`, `numarkdown-ocr.py`, `qianfan-ocr.py`, `firered-ocr.py`, `abot-ocr.py`, `olmocr2-vllm.py`, `dots-mocr.py` | ✅ | vLLM | varies | see `README.md` for flags || `falcon-ocr.py`, `falcon-ocr-bucket.py` | ✅ | falcon-perception | a10g-small | **v1, revision-pinned** (root repo became v1.5 in place); `falcon-ocr.py` frozen — see gotcha || `falcon-ocr-1.5.py` | ✅ | falcon-perception | a10g-small | v1.5 release head, revision-pinned; active — see gotcha || `pp-ocrv6.py`, `pp-doclayout.py` | ✅ | PaddleOCR / PaddleX | l4x1 | classical det+rec; dataset **or** bucket I/O |**License note:** Surya and `lift` ship code as Apache-2.0 but **weights under a modified OpenRAIL-M**173 unmodified linesclient's `hunyuan_tasks.py`) and sampling is card-locked (temp 0.0, rep-penalty 1.08) — don't"improve" either; upstream observed hand-tweaked prompts silently degrade quality.### `falcon-ocr.py` / `falcon-ocr-1.5.py` / `falcon-ocr-bucket.py` — upstream replaced the repo root in placeOn 2026-09-11 TII pushed Falcon OCR **v1.5 onto `main` of `tiiuae/Falcon-OCR`** in three same-daycommits (new `model.safetensors`, then small code edits; no tag, no branch). Until 2026-11-18`falcon-ocr.py` had no pin, so its runs in that window loaded v1.5 while the card said Falcon-OCR. Samefix as HunyuanOCR: **one script per version identity, each pinned by commit.** `falcon-ocr.py` (and thebucket variant) pins the last v1 commit `42ec56b7…`; `falcon-ocr-1.5.py` pins the v1.5 *release head*`fe757d59…`, not `d259a7fb` (the first v1.5 commit, whose code files were replaced the same day). Neverloosen either pin to `main`; `--revision` exists for the caller. The dataset recipes resolve therevision to a commit up front (`HfApi().model_info(...).sha`), load that commit, and write `revision` +`model_commit` into `inference_info` and the card. Same engine, flags and code in both; only the pinand labels differ. `ocr-bench` mirrors the split with `falcon-ocr` / `falcon-ocr-1.5` slugs.Engine gotcha (both versions): the `OCRInferenceEngine` default `max_seq_length=4096` counts imagetokens, so dense pages can truncate without an error. Not changed yet.### `glm-ocr.py`Chatty on blank pages / can emit degenerate repeats — that's **model quality, not a crash**; don'tre-debug it as a recipe bug. (The actual historical crash was the `pyarrow<18` cap — see Conventions.)97 unmodified lines## Change log- **2026-11-18** — Falcon OCR split by version identity (PR #110): `falcon-ocr.py` and`falcon-ocr-bucket.py` pin the last v1 commit; new `falcon-ocr-1.5.py` pins the v1.5 release head. Allthree take `--revision`; the dataset recipes record the resolved commit and carry the canonical provenance stamp.Headers: `a10g-small` on all three; the two dataset recipes also set `1h` and `HF_TOKEN`. `falcon-ocr.py` frozen (superseded by `falcon-ocr-1.5.py`), `falcon-ocr-1.5.py` active.The frozen v1 header pins the default uv image by digest. Smoke-tested on HF Jobs (`l4x1`; `a10g-small` wasnot scheduling), `uv-scripts/ocr-demo`: v1 7/7, v1.5 7/7, bucket variant 7/7 pages, 0 empty or errorrows; the cards and `inference_info` carry the pinned commit and version label.- **2026-11-05** — added `hpd-parsing-saturate.py` (experimental) for `PaddlePaddle/HPD-Parsing` (1B,Apache-2.0): the July server recipe's serve command and block parser, driven by saturate `==0.3.0`(`Engine(cmd=…)` for the vendor fork), plus a `looped_blocks` flag. Header image
81 unmodified lines82838485868716 unmodified lines10410510610710810911014 unmodified lines12512612712812913013181 unmodified lines|--------|-------|------|---------|---------|-----|| [`tesseract-ocr.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/tesseract-ocr.py) | [Tesseract 5](https://github.com/tesseract-ocr/tesseract) | classical | Baseline plain text, no GPU, 100+ language packs (`--lang`) | Apache-2.0 | `cpu-upgrade` || [`pp-ocrv6.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/pp-ocrv6.py) | [PP-OCRv6](https://huggingface.co/collections/PaddlePaddle/pp-ocrv6) | 1.5M–34.5M | Small detection + recognition pipeline, plain text, 48 languages | Apache-2.0 | `t4-small` || [`surya-ocr.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/surya-ocr.py) | [Surya OCR 2](https://huggingface.co/datalab-to/surya-ocr-2) | 0.65B | Per-block HTML with boxes and reading order; layout and table tasks; PDFs | modified OpenRAIL-M | `a10g-small` || [`lighton-ocr3.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/lighton-ocr3.py) | [LightOnOCR-3](https://huggingface.co/collections/lightonai/lightonocr-3) | 0.8B / 4B | 86.3 olmOCR-Bench (4B), 85.5 (0.8B); `--mode grounding` adds labelled layout boxes, image descriptions and chart tables | Apache-2.0 | `a10g-small` || [`glm-ocr.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/glm-ocr.py) | [GLM-OCR](https://huggingface.co/zai-org/GLM-OCR) | 0.9B | 94.62 OmniDocBench v1.5 | MIT | `a10g-small` |16 unmodified linesStart with a model under 2B. Use a larger model only if the output of a small one is not good enough. Check the licence before you use a model: Surya and lift use a modified OpenRAIL-M licence (free for research, personal use and startups under $5M; no competitive use against Datalab's API), and the Hunyuan licence excludes the EU, the UK and South Korea.**Variants and tools:** `glm-ocr-bucket.py`, `surya-ocr-bucket.py` and `lighton-ocr3-bucket.py` read images and PDFs from a Bucket and write one `.md` per page. `lighton-ocr3-bucket.py` also takes `hf://buckets/...` URLs for input and output directly, so it reads large buckets in batches through the Hub API without mounting them. It reads `.jp2`, skips pages that already have output (so a re-run resumes), and in `--mode grounding` writes a `.json` sidecar with the layout blocks. `surya-ocr-bucket.py` also writes a `.json` sidecar with the layout blocks, resumes from existing JSON, and can mount or copy its input (`--io-mode mount|copy`); the dataset version, `surya-ocr.py`, keeps the blocks in a `surya_blocks` column. `lighton-ocr3-saturate.py`, `lighton-ocr2-saturate.py`, `ovis-ocr2-saturate.py` and `xiaomi-ocr-0-saturate.py` are for large runs, and `ocr-vllm-judge.py` compares outputs ([Scaling up](#scaling-up)). `pp-doclayout.py` and `lfm2-extract.py` are described in [Structured extraction and layout](#structured-extraction-and-layout).Which model is best depends on your documents. The public olmOCR-Bench leaderboard is one command away:14 unmodified lines| `glm-ocr-v2.py` | works | `glm-ocr.py`, unless you need its resume support || `lfm2-vl-extract.py` | works | `nuextract3.py` or `lift-extract.py` || `nanonets-ocr2.py` | works on its pinned `vllm/vllm-openai:v0.10.2` image | || `falcon-ocr.py`, `falcon-ocr-bucket.py` | works (Falcon-OCR v1; a v1.5 update is in progress) | || `abot-ocr.py`, `firered-ocr.py`, `numarkdown-ocr.py` | works, little used | || `deepseek-ocr.py` | broken: every row is `None` | `deepseek-ocr-vllm.py` || `hunyuan-ocr.py` | broken on current vLLM | `hunyuan-ocr-1.5.py` |81 unmodified lines828384858687888916 unmodified lines10610710810911011111214 unmodified lines12712812913013113281 unmodified lines|--------|-------|------|---------|---------|-----|| [`tesseract-ocr.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/tesseract-ocr.py) | [Tesseract 5](https://github.com/tesseract-ocr/tesseract) | classical | Baseline plain text, no GPU, 100+ language packs (`--lang`) | Apache-2.0 | `cpu-upgrade` || [`pp-ocrv6.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/pp-ocrv6.py) | [PP-OCRv6](https://huggingface.co/collections/PaddlePaddle/pp-ocrv6) | 1.5M–34.5M | Small detection + recognition pipeline, plain text, 48 languages | Apache-2.0 | `t4-small` || [`falcon-ocr-1.5.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/falcon-ocr-1.5.py) | [Falcon-OCR 1.5](https://huggingface.co/tiiuae/Falcon-OCR) | 0.3B | Smallest VLM here; plain text, LaTeX formulas and HTML tables; pinned to the v1.5 release | Apache-2.0 | `a10g-small` || [`falcon-ocr.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/falcon-ocr.py) | [Falcon-OCR v1](https://huggingface.co/tiiuae/Falcon-OCR/tree/42ec56b72a23984ac059e7c8a6d397a8529423fe) | 0.3B | The v1 weights, pinned by commit, for comparison with earlier runs; frozen, use `falcon-ocr-1.5.py` for new runs | Apache-2.0 | `a10g-small` || [`surya-ocr.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/surya-ocr.py) | [Surya OCR 2](https://huggingface.co/datalab-to/surya-ocr-2) | 0.65B | Per-block HTML with boxes and reading order; layout and table tasks; PDFs | modified OpenRAIL-M | `a10g-small` || [`lighton-ocr3.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/lighton-ocr3.py) | [LightOnOCR-3](https://huggingface.co/collections/lightonai/lightonocr-3) | 0.8B / 4B | 86.3 olmOCR-Bench (4B), 85.5 (0.8B); `--mode grounding` adds labelled layout boxes, image descriptions and chart tables | Apache-2.0 | `a10g-small` || [`glm-ocr.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/glm-ocr.py) | [GLM-OCR](https://huggingface.co/zai-org/GLM-OCR) | 0.9B | 94.62 OmniDocBench v1.5 | MIT | `a10g-small` |16 unmodified linesStart with a model under 2B. Use a larger model only if the output of a small one is not good enough. Check the licence before you use a model: Surya and lift use a modified OpenRAIL-M licence (free for research, personal use and startups under $5M; no competitive use against Datalab's API), and the Hunyuan licence excludes the EU, the UK and South Korea.**Variants and tools:** `glm-ocr-bucket.py`, `surya-ocr-bucket.py`, `lighton-ocr3-bucket.py` and `falcon-ocr-bucket.py` read images and PDFs from a Bucket and write one `.md` per page. `falcon-ocr-bucket.py` runs Falcon-OCR v1 by default; add `--revision fe757d59ecd79d4d68760162306a70a015761ad9` for v1.5. `lighton-ocr3-bucket.py` also takes `hf://buckets/...` URLs for input and output directly, so it reads large buckets in batches through the Hub API without mounting them. It reads `.jp2`, skips pages that already have output (so a re-run resumes), and in `--mode grounding` writes a `.json` sidecar with the layout blocks. `surya-ocr-bucket.py` also writes a `.json` sidecar with the layout blocks, resumes from existing JSON, and can mount or copy its input (`--io-mode mount|copy`); the dataset version, `surya-ocr.py`, keeps the blocks in a `surya_blocks` column. `lighton-ocr3-saturate.py`, `lighton-ocr2-saturate.py`, `ovis-ocr2-saturate.py` and `xiaomi-ocr-0-saturate.py` are for large runs, and `ocr-vllm-judge.py` compares outputs ([Scaling up](#scaling-up)). `pp-doclayout.py` and `lfm2-extract.py` are described in [Structured extraction and layout](#structured-extraction-and-layout).Which model is best depends on your documents. The public olmOCR-Bench leaderboard is one command away:14 unmodified lines| `glm-ocr-v2.py` | works | `glm-ocr.py`, unless you need its resume support || `lfm2-vl-extract.py` | works | `nuextract3.py` or `lift-extract.py` || `nanonets-ocr2.py` | works on its pinned `vllm/vllm-openai:v0.10.2` image | || `abot-ocr.py`, `firered-ocr.py`, `numarkdown-ocr.py` | works, little used | || `deepseek-ocr.py` | broken: every row is `None` | `deepseek-ocr-vllm.py` || `hunyuan-ocr.py` | broken on current vLLM | `hunyuan-ocr-1.5.py` |
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623# /// script# requires-python = ">=3.11"# dependencies = [# "datasets>=4.0.0",# "huggingface-hub",# "pillow",# "torch>=2.5",# "torchvision",# "falcon-perception",# ]## [tool.uv-scripts]# maintenance = "active"## [tool.hf-jobs]# flavor = "a10g-small"# timeout = "1h"# secrets = ["HF_TOKEN"]# ///
"""Convert document images to text using Falcon OCR 1.5 with the falcon-perception engine.
Uses the optimized OCRInferenceEngine with CUDA graphs and paged inferencefor much faster throughput than the raw transformers API.
Features:- Compact: Only 0.3B parameters- Fast: Optimized inference with CUDA graphs- Multi-format: Plain text, LaTeX formulas, HTML tables
Model: tiiuae/Falcon-OCR (pinned to the v1.5 release head)Backend: falcon-perception (OCRInferenceEngine)License: Apache 2.0
Versions: TII released Falcon OCR v1.5 on 2026-09-11 by overwriting the weights on`main` of the same repo (no tag, no branch). This script is the **v1.5** recipe: it pinsthe v1.5 release head (fe757d59…, the third of three same-day commits — the first one,d259a7fb, has older code files) so the next in-place swap cannot change it silently.v1 is its own recipe, `falcon-ocr.py`. `--revision` overrides the pin (`--revision main`tracks whatever the repo root holds); the resolved commit is always recorded in`inference_info` and on the dataset card.
Launch config: the `[tool.hf-jobs]` header sets the flavor (a10g-small), a 1h timeout andthe HF_TOKEN secret. The hf CLI reads it from version 1.32; older CLIs and plain `uv run`ignore it. Explicit flags win.
Examples: # Basic text OCR uv run falcon-ocr-1.5.py input-dataset output-dataset
# Test with small sample uv run falcon-ocr-1.5.py dataset test --max-samples 5 --shuffle
# Track the repo root instead of the v1.5 pin uv run falcon-ocr-1.5.py dataset out --revision main
# Run on HF Jobs (flavor + HF_TOKEN come from the [tool.hf-jobs] header on hf >= 1.32) hf jobs uv run falcon-ocr-1.5.py input-dataset output-dataset --max-samples 10
# Older hf CLI: pass the launch flags yourself hf jobs uv run --flavor a10g-small -s HF_TOKEN falcon-ocr-1.5.py input-dataset output-dataset"""
import argparseimport ioimport jsonimport loggingimport osimport reimport sysimport timefrom datetime import datetimefrom typing import Any, Dict, Union
import torchfrom datasets import load_datasetfrom huggingface_hub import DatasetCard, HfApi, loginfrom PIL import Image
logging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)
MODEL_ID = "tiiuae/Falcon-OCR"# Upstream swapped the weights in place (v1 -> v1.5) on 2026-09-11 with no tag or# branch, so `main` is a moving target. This pin IS this script's v1.5 identity — the# release head, not the first v1.5 commit (d259a7fb) whose code files were superseded# the same day. Never loosen it to "main" here; v1 lives in falcon-ocr.py. Override# with --revision only to reproduce old runs or to follow the repo root deliberately.DEFAULT_REVISION = "fe757d59ecd79d4d68760162306a70a015761ad9" # v1.5 release head, 2026-09-11MODEL_LABEL = "Falcon-OCR-1.5"
TASK_MODES = { "plain": "Full-page text extraction",}
def resolve_commit(revision: str) -> str: """Return the full commit sha for a branch, tag or commit of MODEL_ID.""" if re.fullmatch(r"[0-9a-f]{40}", revision): return revision return HfApi().model_info(MODEL_ID, revision=revision).sha
def label_for_commit(model_commit: str) -> str: """The version label applies only to this recipe's pinned commit; anything else is named by commit.""" if model_commit == DEFAULT_REVISION: return MODEL_LABEL return f"Falcon-OCR@{model_commit[:8]}"
def check_cuda_availability(): if not torch.cuda.is_available(): logger.error("CUDA is not available. This script requires a GPU.") logger.error("For cloud execution, use HF Jobs with --flavor a10g-small or similar.") sys.exit(1) else: logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
def ensure_output_columns_free(dataset, columns, overwrite=False): """Fail fast if an output column would collide with an existing input column.
Adding a column that already exists silently overwrites it (e.g. a ground-truth `text`/`markdown` column) or crashes on push with a duplicate-column error only *after* inference has run. Catch it up front. With overwrite=True, drop the clashing column(s) here instead (logged) so the later add_column is clean. """ clash = [c for c in columns if c in dataset.column_names] if not clash: return dataset if overwrite: logger.warning(f"--overwrite: replacing existing column(s) {clash}") return dataset.remove_columns(clash) logger.error( f"Output column(s) {clash} already exist in the input dataset " f"(columns: {dataset.column_names})." ) logger.error("Choose a different --output-column, or pass --overwrite to replace them.") sys.exit(1)
def prepare_image(image: Union[Image.Image, Dict[str, Any], str]) -> Image.Image: if isinstance(image, Image.Image): pil_img = image elif isinstance(image, dict) and "bytes" in image: pil_img = Image.open(io.BytesIO(image["bytes"])) elif isinstance(image, str): pil_img = Image.open(image) else: raise ValueError(f"Unsupported image type: {type(image)}") return pil_img.convert("RGB")
def jobs_flavor() -> str: """Return the HF Jobs hardware flavor this run is on, or "" when it cannot be told.
HF Jobs sets ACCELERATOR to "cpu" or "gpu", not the flavor name, so the flavor is looked up in the public Jobs hardware list: first by GPU model and count, then by the CPU_CORES and MEMORY values that Jobs sets in the container (to tell a10g-small from a10g-large, or cpu-basic from cpu-upgrade). Any failure (no network, older huggingface_hub) returns "". """ hardware = os.environ.get("ACCELERATOR") or "" if "-" in hardware or any(character.isdigit() for character in hardware): return hardware # already a flavor name try: from huggingface_hub import HfApi
gpu_name, gpu_count = "", 0 try: import torch
if torch.cuda.is_available(): gpu_name = torch.cuda.get_device_name(0) gpu_count = torch.cuda.device_count() except ImportError: # Torch-free drivers (e.g. the -server recipes): ask nvidia-smi instead. import subprocess
try: listed = subprocess.run( ["nvidia-smi", "--query-gpu=name", "--format=csv,noheader"], capture_output=True, text=True, timeout=10, check=True, ).stdout names = [line.strip() for line in listed.splitlines() if line.strip()] if names: gpu_name, gpu_count = names[0], len(names) except (OSError, subprocess.SubprocessError): pass if gpu_count == 0 and hardware == "gpu": return "" # a GPU run whose GPU cannot be identified: do not guess a CPU flavor
# Whole-word match, so "L4" does not match "NVIDIA L40S" ("NVIDIA A100-SXM4-80GB" -> A100). gpu_words = gpu_name.upper().replace("-", " ").split() candidates = [] for flavor in HfApi(token=False).list_jobs_hardware(): accelerator = flavor.accelerator if gpu_count == 0 and accelerator is None: candidates.append(flavor) elif ( gpu_count > 0 and accelerator is not None and accelerator.model.upper() in gpu_words and int(accelerator.quantity) == gpu_count ): candidates.append(flavor) if not candidates: return ""
cores = float(os.environ.get("CPU_CORES") or 0) memory_gb = float((os.environ.get("MEMORY") or "0").upper().rstrip("GIB ") or 0)
def distance(flavor) -> float: # Relative gap to the listed vCPUs and RAM; Jobs reports slightly different numbers. listed_cores = float(flavor.cpu.split()[0]) listed_memory = float(flavor.ram.split()[0]) return abs(listed_cores - cores) / listed_cores + abs(listed_memory - memory_gb) / listed_memory
return min(candidates, key=distance).name except Exception: return ""
def create_dataset_card( source_dataset: str, task_mode: str, num_samples: int, processing_time: str, image_column: str = "image", split: str = "train", revision: str = "main", model_commit: str = "",) -> str: task_description = TASK_MODES[task_mode] commit_note = f" (resolved to `{model_commit}`)" # Canonical provenance stamp (see AGENTS.md): Jobs claim gated on JOB_ID, set by HF Jobs in-container. on_jobs = os.environ.get("JOB_ID") is not None hw = jobs_flavor() # flavor name, e.g. "a10g-small"; "" on CPU origin = ( "Produced on [Hugging Face Jobs](https://huggingface.co/docs/huggingface_hub/guides/jobs)" + (f" (`{hw}`)" if hw else "") ) if on_jobs else "Generated" jobs_tag = "\n- hf-jobs" if on_jobs else "" if model_commit == DEFAULT_REVISION: card_name, version_tag, version_note = 'Falcon OCR 1.5', 'falcon-ocr-1.5', ' (v1.5 weights released 2026-09-11)' else: card_name = f"Falcon OCR at {model_commit[:8]}" version_tag = "falcon-ocr-other-revision" version_note = f" (revision `{revision}`, not the pinned Falcon OCR 1.5 commit this recipe is named for)" return f"""---tags:- ocr- document-processing- falcon-ocr- {version_tag}- {task_mode}- uv-script{jobs_tag}- generated---
# Document Processing using {card_name} ({task_mode} mode)
This dataset contains OCR results from images in [{source_dataset}](https://huggingface.co/datasets/{source_dataset}) using [{card_name}](https://huggingface.co/tiiuae/Falcon-OCR), a 0.3B early-fusion vision-language model{version_note}.
## Processing Details
- **Source Dataset**: [{source_dataset}](https://huggingface.co/datasets/{source_dataset})- **Model**: [{MODEL_ID}](https://huggingface.co/{MODEL_ID})- **Model Revision**: `{revision}`{commit_note}- **Task Mode**: `{task_mode}` - {task_description}- **Number of Samples**: {num_samples:,}- **Processing Time**: {processing_time}- **Processing Date**: {datetime.now().strftime("%Y-%m-%d %H:%M UTC")}- **Backend**: falcon-perception (OCRInferenceEngine)
## Reproduction
{origin} with the [`falcon-ocr-1.5.py`](https://huggingface.co/datasets/uv-scripts/ocr/raw/main/falcon-ocr-1.5.py) recipe from [uv-scripts](https://huggingface.co/uv-scripts). Run it yourself:
```bashhf jobs uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/falcon-ocr-1.5.py \\ {source_dataset} \\ <output-dataset> \\ --task-mode {task_mode} \\ --image-column {image_column} \\ --revision {model_commit or revision}```"""
def main( input_dataset: str, output_dataset: str, image_column: str = "image", task_mode: str = "plain", hf_token: str = None, split: str = "train", max_samples: int = None, private: bool = False, shuffle: bool = False, seed: int = 42, output_column: str = "markdown", overwrite: bool = False, config: str = None, create_pr: bool = False, compile: bool = True, cudagraph: bool = True, progress: bool = False, verbose: bool = False, revision: str | None = None,): check_cuda_availability() if revision is None: revision = DEFAULT_REVISION logger.info(f"Pinning {MODEL_ID} to {MODEL_LABEL} revision {revision[:8]}") start_time = datetime.now()
HF_TOKEN = hf_token or os.environ.get("HF_TOKEN") if HF_TOKEN: login(token=HF_TOKEN)
if task_mode not in TASK_MODES: raise ValueError( f"Invalid task_mode '{task_mode}'. Choose from: {list(TASK_MODES.keys())}" )
logger.info(f"Task mode: {task_mode} - {TASK_MODES[task_mode]}") logger.info(f"Output column: {output_column}")
# Load dataset logger.info(f"Loading dataset: {input_dataset}") dataset = load_dataset(input_dataset, split=split)
if image_column not in dataset.column_names: raise ValueError( f"Column '{image_column}' not found. Available: {dataset.column_names}" )
# Fail fast if the output column would collide with an existing input column dataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)
if shuffle: logger.info(f"Shuffling dataset with seed {seed}") dataset = dataset.shuffle(seed=seed)
if max_samples: dataset = dataset.select(range(min(max_samples, len(dataset)))) logger.info(f"Limited to {len(dataset)} samples")
# Resolve the revision to a commit sha up front so the run is reproducible even # when `main` moves again (it did on 2026-09-11: v1 -> v1.5, same repo). # A failure here stops the run: loading a moving branch without a recorded commit is # the problem this recipe exists to prevent. model_commit = resolve_commit(revision) model_label = label_for_commit(model_commit) logger.info(f"Model revision: {revision} -> {model_commit} ({model_label})")
# Load model using falcon-perception logger.info(f"Loading model: {MODEL_ID} via falcon-perception engine") from falcon_perception import load_and_prepare_model from falcon_perception.data import ImageProcessor from falcon_perception.paged_ocr_inference import OCRInferenceEngine
model, tokenizer, model_args = load_and_prepare_model( hf_model_id=MODEL_ID, hf_revision=model_commit, # load the commit that inference_info records device="cuda", dtype="bfloat16", compile=compile, )
image_processor = ImageProcessor(patch_size=16, merge_size=1) engine = OCRInferenceEngine( model, tokenizer, image_processor, capture_cudagraph=cudagraph ) logger.info(f"Engine loaded. compile={compile}, cudagraph={cudagraph}")
# Prepare all images logger.info(f"Processing {len(dataset)} images...") all_outputs = []
# Batch plain OCR for better throughput batch_size = 8 total_batches = (len(dataset) + batch_size - 1) // batch_size for batch_idx, batch_start in enumerate(range(0, len(dataset), batch_size), 1): batch_end = min(batch_start + batch_size, len(dataset)) logger.info(f"Batch {batch_idx}/{total_batches} ({batch_start}/{len(dataset)} done)") batch_images = [] for i in range(batch_start, batch_end): try: batch_images.append(prepare_image(dataset[i][image_column])) except Exception as e: logger.error(f"Error preparing image {i}: {e}") batch_images.append(Image.new("RGB", (100, 100)))
try: texts = engine.generate_plain( images=batch_images, use_tqdm=progress ) all_outputs.extend(texts) except Exception as e: logger.error(f"Error processing batch {batch_start}-{batch_end}: {e}") all_outputs.extend( [f"[OCR ERROR: {str(e)[:200]}]"] * len(batch_images) )
# Calculate processing time processing_duration = datetime.now() - start_time processing_time_str = f"{processing_duration.total_seconds() / 60:.1f} min"
# Add output column logger.info(f"Adding '{output_column}' column to dataset") dataset = dataset.add_column(output_column, all_outputs)
# Track inference info inference_entry = { "model_id": MODEL_ID, "model_name": model_label, "model_size": "0.3B", "revision": revision, "model_commit": model_commit, "task_mode": task_mode, "column_name": output_column, "timestamp": datetime.now().isoformat(), "backend": "falcon-perception", }
if "inference_info" in dataset.column_names: def update_inference_info(example): try: existing_info = ( json.loads(example["inference_info"]) if example["inference_info"] else [] ) except (json.JSONDecodeError, TypeError): existing_info = [] existing_info.append(inference_entry) return {"inference_info": json.dumps(existing_info)}
dataset = dataset.map(update_inference_info) else: inference_list = [json.dumps([inference_entry])] * len(dataset) dataset = dataset.add_column("inference_info", inference_list)
# Push to hub logger.info(f"Pushing to {output_dataset}") max_retries = 3 for attempt in range(1, max_retries + 1): try: if attempt > 1: logger.warning("Disabling XET (fallback to HTTP upload)") os.environ["HF_HUB_DISABLE_XET"] = "1" dataset.push_to_hub( output_dataset, private=private, token=HF_TOKEN, max_shard_size="500MB", **({"config_name": config} if config else {}), create_pr=create_pr, commit_message=f"Add {MODEL_ID} OCR results ({len(dataset)} samples)" + (f" [{config}]" if config else ""), ) break except Exception as e: logger.error(f"Upload attempt {attempt}/{max_retries} failed: {e}") if attempt < max_retries: delay = 30 * (2 ** (attempt - 1)) logger.info(f"Retrying in {delay}s...") time.sleep(delay) else: logger.error("All upload attempts failed. OCR results are lost.") sys.exit(1)
# Create and push dataset card logger.info("Creating dataset card") card_content = create_dataset_card( source_dataset=input_dataset, task_mode=task_mode, num_samples=len(dataset), processing_time=processing_time_str, image_column=image_column, split=split, revision=revision, model_commit=model_commit, ) card = DatasetCard(card_content) card.push_to_hub(output_dataset, token=HF_TOKEN)
logger.info("Falcon OCR processing complete!") logger.info( f"Dataset available at: https://huggingface.co/datasets/{output_dataset}" ) logger.info(f"Processing time: {processing_time_str}") logger.info( f"Speed: {len(dataset) / processing_duration.total_seconds():.2f} images/sec" )
if verbose: import importlib.metadata
logger.info("--- Resolved package versions ---") for pkg in [ "falcon-perception", "transformers", "torch", "datasets", "pillow" ]: try: logger.info(f" {pkg}=={importlib.metadata.version(pkg)}") except importlib.metadata.PackageNotFoundError: logger.info(f" {pkg}: not installed")
if __name__ == "__main__": if len(sys.argv) == 1: print("=" * 70) print("Falcon OCR 1.5 - 0.3B Document OCR (falcon-perception engine)") print("=" * 70) print(f"\nModel: {MODEL_ID} @ {DEFAULT_REVISION[:10]} ({MODEL_LABEL}; --revision to override)") print("License: Apache 2.0") print("\nTask Modes:") for mode, description in TASK_MODES.items(): print(f" {mode:10} - {description}") print("\nExamples:") print(" uv run falcon-ocr-1.5.py input-dataset output-dataset") print("\nFor full help: uv run falcon-ocr-1.5.py --help") sys.exit(0)
parser = argparse.ArgumentParser( description="Document OCR using Falcon OCR (0.3B, falcon-perception engine)", formatter_class=argparse.RawDescriptionHelpFormatter, epilog=__doc__, )
parser.add_argument("input_dataset", help="Input dataset ID from Hugging Face Hub") parser.add_argument("output_dataset", help="Output dataset ID for Hugging Face Hub") parser.add_argument( "--image-column", default="image", help="Column containing images (default: image)", ) parser.add_argument( "--task-mode", choices=list(TASK_MODES.keys()), default="plain", help="Task type: plain (the only mode)", ) parser.add_argument("--hf-token", help="Hugging Face API token") parser.add_argument( "--split", default="train", help="Dataset split (default: train)", ) parser.add_argument( "--max-samples", type=int, help="Maximum number of samples to process (for testing)", ) parser.add_argument( "--private", action="store_true", help="Make output dataset private", ) parser.add_argument( "--shuffle", action="store_true", help="Shuffle dataset before processing", ) parser.add_argument( "--seed", type=int, default=42, help="Random seed for shuffling (default: 42)", ) parser.add_argument( "--output-column", default="markdown", help="Column name for output text (default: markdown)", ) parser.add_argument( "--overwrite", action="store_true", help="Replace the output column if it already exists in the input dataset " "(default: error out to avoid clobbering an existing column).", ) parser.add_argument( "--config", help="Config/subset name for Hub (for benchmarking multiple models)", ) parser.add_argument( "--create-pr", action="store_true", help="Create a pull request instead of pushing directly", ) parser.add_argument( "--no-compile", action="store_true", help="Disable torch.compile", ) parser.add_argument( "--no-cudagraph", action="store_true", help="Disable CUDA graph capture", ) parser.add_argument( "--progress", action="store_true", help="Show per-image progress bar from the inference engine", ) parser.add_argument( "--verbose", action="store_true", help="Log resolved package versions", ) parser.add_argument( "--revision", default=None, help=f"Model repo revision (branch, tag or commit sha). Default: the {MODEL_LABEL} " f"pin {DEFAULT_REVISION[:10]}. Pass 'main' to follow the repo root (v1.5 since " "2026-09-11; same as this pin today) or any commit to reproduce a run; the resolved commit is recorded " "in inference_info.", )
args = parser.parse_args()
main( input_dataset=args.input_dataset, output_dataset=args.output_dataset, image_column=args.image_column, task_mode=args.task_mode, hf_token=args.hf_token, split=args.split, max_samples=args.max_samples, private=args.private, shuffle=args.shuffle, seed=args.seed, output_column=args.output_column, overwrite=args.overwrite, config=args.config, create_pr=args.create_pr, compile=not args.no_compile, cudagraph=not args.no_cudagraph, progress=args.progress, verbose=args.verbose, revision=args.revision, )6 unmodified lines78910111217 unmodified lines303132333435362 unmodified lines3940414243449 unmodified lines54555657585997 unmodified lines15715815916016116237 unmodified lines2002012022032042052063 unmodified lines21021121221321421573 unmodified lines2892902912922932942956 unmodified lines# "torchvision",# "falcon-perception[ocr]",# ]# ///"""17 unmodified linesuv run falcon-ocr-bucket.py ./test-images ./test-output# HF Jobs with bucket volumeshf jobs uv run --flavor l4x1 \\-s HF_TOKEN \\-v hf://buckets/user/ocr-input:/input:ro \\-v hf://buckets/user/ocr-output:/output \\2 unmodified linesModel: tiiuae/Falcon-OCR (0.3B, 80.3% olmOCR, Apache 2.0)Backend: falcon-perception (OCRInferenceEngine with CUDA graphs)"""import argparse9 unmodified lineslogger = logging.getLogger(__name__)MODEL_ID = "tiiuae/Falcon-OCR"IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".tiff", ".tif", ".bmp", ".webp"}97 unmodified linesparser.add_argument("--verbose", action="store_true", help="Print resolved package versions",)args = parser.parse_args()37 unmodified lineslogger.info(f"Total images to OCR: {len(items)}")# Load modellogger.info(f"Loading {MODEL_ID} via falcon-perception engine...")from falcon_perception import load_and_prepare_modelfrom falcon_perception.data import ImageProcessorfrom falcon_perception.paged_ocr_inference import OCRInferenceEngine3 unmodified linesmodel, tokenizer, model_args = load_and_prepare_model(hf_model_id=MODEL_ID,device="cuda",dtype="bfloat16",compile=do_compile,73 unmodified linesprint(" uv run falcon-ocr-bucket.py ./images ./output")print()print("HF Jobs with bucket volumes:")print(" hf jobs uv run --flavor l4x1 -s HF_TOKEN \\")print(" -v hf://buckets/user/ocr-input:/input:ro \\")print(" -v hf://buckets/user/ocr-output:/output \\")print(6 unmodified lines78910111213141517 unmodified lines333435363738392 unmodified lines4243444546474849505152539 unmodified lines63646566676869707197 unmodified lines16917017117217317417517617717817918037 unmodified lines2182192202212222232243 unmodified lines22822923023123223323473 unmodified lines3083093103113123133146 unmodified lines# "torchvision",# "falcon-perception[ocr]",# ]## [tool.hf-jobs]# flavor = "a10g-small"# ///"""17 unmodified linesuv run falcon-ocr-bucket.py ./test-images ./test-output# HF Jobs with bucket volumeshf jobs uv run --flavor a10g-small \\-s HF_TOKEN \\-v hf://buckets/user/ocr-input:/input:ro \\-v hf://buckets/user/ocr-output:/output \\2 unmodified linesModel: tiiuae/Falcon-OCR (0.3B, 80.3% olmOCR, Apache 2.0)Backend: falcon-perception (OCRInferenceEngine with CUDA graphs)Versions: upstream overwrote `main` with the v1.5 weights on 2026-09-11 (same repo, notag). Like falcon-ocr.py this variant pins the last **v1** commit (42ec56b7…) by default;`--revision fe757d59ecd79d4d68760162306a70a015761ad9` runs the v1.5 release head and`--revision main` follows the repo root. The `[tool.hf-jobs]` header supplies the defaultflavor on hf >= 1.32; add `-s HF_TOKEN` yourself only if the bucket mounts need it."""import argparse9 unmodified lineslogger = logging.getLogger(__name__)MODEL_ID = "tiiuae/Falcon-OCR"# Upstream swapped the weights in place (v1 -> v1.5) on 2026-09-11; this pin is the v1# identity shared with falcon-ocr.py. v1.5 release head = fe757d59ecd79d4d68760162306a70a015761ad9.DEFAULT_REVISION = "42ec56b72a23984ac059e7c8a6d397a8529423fe" # last v1 commit, 2026-07-03IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".tiff", ".tif", ".bmp", ".webp"}97 unmodified linesparser.add_argument("--verbose", action="store_true", help="Print resolved package versions",)parser.add_argument("--revision", default=DEFAULT_REVISION,help=f"Model repo revision (branch, tag or commit sha). Default: the v1 pin "f"{DEFAULT_REVISION[:10]}. Pass fe757d59ec for the v1.5 release head or 'main' ""to follow the repo root (v1.5 since 2026-09-11).",)args = parser.parse_args()37 unmodified lineslogger.info(f"Total images to OCR: {len(items)}")# Load modellogger.info(f"Loading {MODEL_ID} (revision {args.revision}) via falcon-perception engine...")from falcon_perception import load_and_prepare_modelfrom falcon_perception.data import ImageProcessorfrom falcon_perception.paged_ocr_inference import OCRInferenceEngine3 unmodified linesmodel, tokenizer, model_args = load_and_prepare_model(hf_model_id=MODEL_ID,hf_revision=args.revision,device="cuda",dtype="bfloat16",compile=do_compile,73 unmodified linesprint(" uv run falcon-ocr-bucket.py ./images ./output")print()print("HF Jobs with bucket volumes:")print(" hf jobs uv run --flavor a10g-small -s HF_TOKEN \\")print(" -v hf://buckets/user/ocr-input:/input:ro \\")print(" -v hf://buckets/user/ocr-output:/output \\")print(
7 unmodified lines89101112136 unmodified lines2021222324252627282930311 unmodified line33343536373839404142431 unmodified line4546474849501 unmodified line525354555657585960616263646566676869707172737433 unmodified lines1081091101111121131 unmodified line1151161171181191201211221231241251261271281291301311321331341351361371381391402 unmodified lines14314414514614714814915015115215315415515615716 unmodified lines17417517617717817918018128 unmodified lines2102112122132142152 unmodified lines21821922022122222345 unmodified lines26927027127227327427527656 unmodified lines33333433533633733825 unmodified lines36436536636736836937037137237337437537637711 unmodified lines38939039139239339439545 unmodified lines44144244344444544616 unmodified lines4634644654667 unmodified lines# "torchvision",# "falcon-perception",# ]# ///"""6 unmodified lines- Compact: Only 0.3B parameters- Fast: Optimized inference with CUDA graphs- Multi-format: Plain text, LaTeX formulas, HTML tables- Layout-aware: Optional 2-stage pipeline (layout detection + per-region OCR)Model: tiiuae/Falcon-OCRBackend: falcon-perception (OCRInferenceEngine)License: Apache 2.0Examples:# Basic text OCRuv run falcon-ocr.py input-dataset output-dataset1 unmodified line# Test with small sampleuv run falcon-ocr.py dataset test --max-samples 5 --shuffle# Run on HF Jobs with GPUhf jobs uv run --flavor l4x1 \\-s HF_TOKEN \\falcon-ocr.py \\input-dataset output-dataset --max-samples 10"""import argparse1 unmodified lineimport jsonimport loggingimport osimport sysimport timefrom datetime import datetime1 unmodified lineimport torchfrom datasets import load_datasetfrom huggingface_hub import DatasetCard, loginfrom PIL import Imagelogging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)MODEL_ID = "tiiuae/Falcon-OCR"TASK_MODES = {"plain": "Full-page text extraction",}def check_cuda_availability():if not torch.cuda.is_available():logger.error("CUDA is not available. This script requires a GPU.")logger.error("For cloud execution, use HF Jobs with --flavor l4x1 or similar.")sys.exit(1)else:logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")33 unmodified linesreturn pil_img.convert("RGB")def create_dataset_card(source_dataset: str,task_mode: str,1 unmodified lineprocessing_time: str,image_column: str = "image",split: str = "train",) -> str:task_description = TASK_MODES[task_mode]return f"""---tags:- ocr- document-processing- falcon-ocr- {task_mode}- uv-script- generated---# Document Processing using Falcon OCR ({task_mode} mode)This dataset contains OCR results from images in [{source_dataset}](https://huggingface.co/datasets/{source_dataset}) using [Falcon OCR](https://huggingface.co/tiiuae/Falcon-OCR), a 0.3B early-fusion vision-language model.## Processing Details- **Source Dataset**: [{source_dataset}](https://huggingface.co/datasets/{source_dataset})- **Model**: [{MODEL_ID}](https://huggingface.co/{MODEL_ID})- **Task Mode**: `{task_mode}` - {task_description}- **Number of Samples**: {num_samples:,}- **Processing Time**: {processing_time}2 unmodified lines## Reproduction```bashuv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/falcon-ocr.py \\{source_dataset} \\<output-dataset> \\--task-mode {task_mode} \\--image-column {image_column}```Generated with [UV Scripts](https://huggingface.co/uv-scripts)"""16 unmodified linescudagraph: bool = True,progress: bool = False,verbose: bool = False,):check_cuda_availability()start_time = datetime.now()HF_TOKEN = hf_token or os.environ.get("HF_TOKEN")28 unmodified linesdataset = dataset.select(range(min(max_samples, len(dataset))))logger.info(f"Limited to {len(dataset)} samples")# Load model using falcon-perceptionlogger.info(f"Loading model: {MODEL_ID} via falcon-perception engine")from falcon_perception import load_and_prepare_model2 unmodified linesmodel, tokenizer, model_args = load_and_prepare_model(hf_model_id=MODEL_ID,device="cuda",dtype="bfloat16",compile=compile,45 unmodified lines# Track inference infoinference_entry = {"model_id": MODEL_ID,"model_name": "Falcon-OCR","model_size": "0.3B","task_mode": task_mode,"column_name": output_column,"timestamp": datetime.now().isoformat(),56 unmodified linesprocessing_time=processing_time_str,image_column=image_column,split=split,)card = DatasetCard(card_content)card.push_to_hub(output_dataset, token=HF_TOKEN)25 unmodified linesprint("=" * 70)print("Falcon OCR - 0.3B Document OCR (falcon-perception engine)")print("=" * 70)print(f"\nModel: {MODEL_ID}")print("License: Apache 2.0")print("\nTask Modes:")for mode, description in TASK_MODES.items():print(f" {mode:10} - {description}")print("\nExamples:")print(" uv run falcon-ocr.py input-dataset output-dataset")print(" uv run falcon-ocr.py dense-docs output --task-mode layout")print("\nFor full help: uv run falcon-ocr.py --help")sys.exit(0)11 unmodified lines)parser.add_argument("--task-mode", choices=list(TASK_MODES.keys()), default="plain",help="Task type: plain (default), layout",)parser.add_argument("--hf-token", help="Hugging Face API token")parser.add_argument(45 unmodified linesparser.add_argument("--verbose", action="store_true", help="Log resolved package versions",)args = parser.parse_args()16 unmodified linescudagraph=not args.no_cudagraph,progress=args.progress,verbose=args.verbose,)7 unmodified lines891011121314151617181920212223242526276 unmodified lines34353637383940414243444546474849505152535455561 unmodified line58596061626364656667686970711 unmodified line737475767778791 unmodified line8182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212333 unmodified lines1571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302311 unmodified line2332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772 unmodified lines28028128228328428528628728828929029129229329429516 unmodified lines31231331431531631731831932032132232328 unmodified lines3523533543553563573583593603613623633643652 unmodified lines36836937037137237337445 unmodified lines42042142242342442542642742842956 unmodified lines48648748848949049149249325 unmodified lines51952052152252352452552652752852953053111 unmodified lines54354454554654754854945 unmodified lines59559659759859960060160260360460560660716 unmodified lines6246256266276287 unmodified lines# "torchvision",# "falcon-perception",# ]## [tool.uv]# exclude-newer = "2026-11-18T00:00:00Z" # frozen: resolve packages as on this date## [tool.uv-scripts]# maintenance = "frozen"# frozen_on = "2026-11-18"# superseded_by = "falcon-ocr-1.5.py"## [tool.hf-jobs]# image = "ghcr.io/astral-sh/uv@sha256:85d4cb1afa769a7338e095b927bee941cf5ec92266c7424b3f6c0f2748567248" # python3.12-bookworm, the Jobs default for uv run# flavor = "a10g-small"# timeout = "1h"# secrets = ["HF_TOKEN"]# ///"""6 unmodified lines- Compact: Only 0.3B parameters- Fast: Optimized inference with CUDA graphs- Multi-format: Plain text, LaTeX formulas, HTML tablesModel: tiiuae/Falcon-OCR (pinned to the last v1 revision)Frozen recipe: for Falcon OCR v1.5, use falcon-ocr-1.5.py.Backend: falcon-perception (OCRInferenceEngine)License: Apache 2.0Versions: TII released Falcon OCR v1.5 on 2026-09-11 by overwriting the weights on`main` of the same repo (no tag, no branch). This script is the **v1** recipe: it pinsthe last v1 commit (42ec56b7…) so its behaviour does not change under you. v1.5 is itsown recipe, `falcon-ocr-1.5.py`. `--revision` overrides the pin (`--revision main`tracks whatever the repo root holds); the resolved commit is always recorded in`inference_info` and on the dataset card.Launch config: the `[tool.hf-jobs]` header sets the flavor (a10g-small), a 1h timeout andthe HF_TOKEN secret. The hf CLI reads it from version 1.32; older CLIs and plain `uv run`ignore it. Explicit flags win.Examples:# Basic text OCRuv run falcon-ocr.py input-dataset output-dataset1 unmodified line# Test with small sampleuv run falcon-ocr.py dataset test --max-samples 5 --shuffle# Track the repo root instead of the v1 pin (v1.5 at the time of writing)uv run falcon-ocr.py dataset out --revision main# Run on HF Jobs (flavor + HF_TOKEN come from the [tool.hf-jobs] header on hf >= 1.32)hf jobs uv run falcon-ocr.py input-dataset output-dataset --max-samples 10# Older hf CLI: pass the launch flags yourselfhf jobs uv run --flavor a10g-small -s HF_TOKEN falcon-ocr.py input-dataset output-dataset"""import argparse1 unmodified lineimport jsonimport loggingimport osimport reimport sysimport timefrom datetime import datetime1 unmodified lineimport torchfrom datasets import load_datasetfrom huggingface_hub import DatasetCard, HfApi, loginfrom PIL import Imagelogging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)MODEL_ID = "tiiuae/Falcon-OCR"# Upstream swapped the weights in place (v1 -> v1.5) on 2026-09-11 with no tag or# branch, so `main` is a moving target. This pin IS this script's v1 identity — never# loosen it to "main" here; v1.5 lives in falcon-ocr-1.5.py. Override with --revision# only to reproduce old runs or to follow the repo root deliberately.DEFAULT_REVISION = "42ec56b72a23984ac059e7c8a6d397a8529423fe" # last v1 commit, 2026-07-03MODEL_LABEL = "Falcon-OCR"TASK_MODES = {"plain": "Full-page text extraction",}def resolve_commit(revision: str) -> str:"""Return the full commit sha for a branch, tag or commit of MODEL_ID."""if re.fullmatch(r"[0-9a-f]{40}", revision):return revisionreturn HfApi().model_info(MODEL_ID, revision=revision).shadef label_for_commit(model_commit: str) -> str:"""The version label applies only to this recipe's pinned commit; anything else is named by commit."""if model_commit == DEFAULT_REVISION:return MODEL_LABELreturn f"Falcon-OCR@{model_commit[:8]}"def check_cuda_availability():if not torch.cuda.is_available():logger.error("CUDA is not available. This script requires a GPU.")logger.error("For cloud execution, use HF Jobs with --flavor a10g-small or similar.")sys.exit(1)else:logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")33 unmodified linesreturn pil_img.convert("RGB")def jobs_flavor() -> str:"""Return the HF Jobs hardware flavor this run is on, or "" when it cannot be told.HF Jobs sets ACCELERATOR to "cpu" or "gpu", not the flavor name, so the flavor is looked upin the public Jobs hardware list: first by GPU model and count, then by the CPU_CORES andMEMORY values that Jobs sets in the container (to tell a10g-small from a10g-large, orcpu-basic from cpu-upgrade). Any failure (no network, older huggingface_hub) returns ""."""hardware = os.environ.get("ACCELERATOR") or ""if "-" in hardware or any(character.isdigit() for character in hardware):return hardware # already a flavor nametry:from huggingface_hub import HfApigpu_name, gpu_count = "", 0try:import torchif torch.cuda.is_available():gpu_name = torch.cuda.get_device_name(0)gpu_count = torch.cuda.device_count()except ImportError:# Torch-free drivers (e.g. the -server recipes): ask nvidia-smi instead.import subprocesstry:listed = subprocess.run(["nvidia-smi", "--query-gpu=name", "--format=csv,noheader"],capture_output=True, text=True, timeout=10, check=True,).stdoutnames = [line.strip() for line in listed.splitlines() if line.strip()]if names:gpu_name, gpu_count = names[0], len(names)except (OSError, subprocess.SubprocessError):passif gpu_count == 0 and hardware == "gpu":return "" # a GPU run whose GPU cannot be identified: do not guess a CPU flavor# Whole-word match, so "L4" does not match "NVIDIA L40S" ("NVIDIA A100-SXM4-80GB" -> A100).gpu_words = gpu_name.upper().replace("-", " ").split()candidates = []for flavor in HfApi(token=False).list_jobs_hardware():accelerator = flavor.acceleratorif gpu_count == 0 and accelerator is None:candidates.append(flavor)elif (gpu_count > 0and accelerator is not Noneand accelerator.model.upper() in gpu_wordsand int(accelerator.quantity) == gpu_count):candidates.append(flavor)if not candidates:return ""cores = float(os.environ.get("CPU_CORES") or 0)memory_gb = float((os.environ.get("MEMORY") or "0").upper().rstrip("GIB ") or 0)def distance(flavor) -> float:# Relative gap to the listed vCPUs and RAM; Jobs reports slightly different numbers.listed_cores = float(flavor.cpu.split()[0])listed_memory = float(flavor.ram.split()[0])return abs(listed_cores - cores) / listed_cores + abs(listed_memory - memory_gb) / listed_memoryreturn min(candidates, key=distance).nameexcept Exception:return ""def create_dataset_card(source_dataset: str,task_mode: str,1 unmodified lineprocessing_time: str,image_column: str = "image",split: str = "train",revision: str = "main",model_commit: str = "",) -> str:task_description = TASK_MODES[task_mode]commit_note = f" (resolved to `{model_commit}`)"# Canonical provenance stamp (see AGENTS.md): Jobs claim gated on JOB_ID, set by HF Jobs in-container.on_jobs = os.environ.get("JOB_ID") is not Nonehw = jobs_flavor() # flavor name, e.g. "a10g-small"; "" on CPUorigin = ("Produced on [Hugging Face Jobs](https://huggingface.co/docs/huggingface_hub/guides/jobs)"+ (f" (`{hw}`)" if hw else "")) if on_jobs else "Generated"jobs_tag = "\n- hf-jobs" if on_jobs else ""if model_commit == DEFAULT_REVISION:card_name, version_tag, version_note = 'Falcon OCR v1', 'falcon-ocr-v1', ''else:card_name = f"Falcon OCR at {model_commit[:8]}"version_tag = "falcon-ocr-other-revision"version_note = f" (revision `{revision}`, not the pinned Falcon OCR v1 commit this recipe is named for)"return f"""---tags:- ocr- document-processing- falcon-ocr- {version_tag}- {task_mode}- uv-script{jobs_tag}- generated---# Document Processing using {card_name} ({task_mode} mode)This dataset contains OCR results from images in [{source_dataset}](https://huggingface.co/datasets/{source_dataset}) using [{card_name}](https://huggingface.co/tiiuae/Falcon-OCR), a 0.3B early-fusion vision-language model{version_note}.## Processing Details- **Source Dataset**: [{source_dataset}](https://huggingface.co/datasets/{source_dataset})- **Model**: [{MODEL_ID}](https://huggingface.co/{MODEL_ID})- **Model Revision**: `{revision}`{commit_note}- **Task Mode**: `{task_mode}` - {task_description}- **Number of Samples**: {num_samples:,}- **Processing Time**: {processing_time}2 unmodified lines## Reproduction{origin} with the [`falcon-ocr.py`](https://huggingface.co/datasets/uv-scripts/ocr/raw/main/falcon-ocr.py) recipe from [uv-scripts](https://huggingface.co/uv-scripts). Run it yourself:```bashhf jobs uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/falcon-ocr.py \\{source_dataset} \\<output-dataset> \\--task-mode {task_mode} \\--image-column {image_column} \\--revision {model_commit or revision}```"""16 unmodified linescudagraph: bool = True,progress: bool = False,verbose: bool = False,revision: str | None = None,):check_cuda_availability()if revision is None:revision = DEFAULT_REVISIONlogger.info(f"Pinning {MODEL_ID} to {MODEL_LABEL} revision {revision[:8]}")start_time = datetime.now()HF_TOKEN = hf_token or os.environ.get("HF_TOKEN")28 unmodified linesdataset = dataset.select(range(min(max_samples, len(dataset))))logger.info(f"Limited to {len(dataset)} samples")# Resolve the revision to a commit sha up front so the run is reproducible even# when `main` moves again (it did on 2026-09-11: v1 -> v1.5, same repo).# A failure here stops the run: loading a moving branch without a recorded commit is# the problem this recipe exists to prevent.model_commit = resolve_commit(revision)model_label = label_for_commit(model_commit)logger.info(f"Model revision: {revision} -> {model_commit} ({model_label})")# Load model using falcon-perceptionlogger.info(f"Loading model: {MODEL_ID} via falcon-perception engine")from falcon_perception import load_and_prepare_model2 unmodified linesmodel, tokenizer, model_args = load_and_prepare_model(hf_model_id=MODEL_ID,hf_revision=model_commit, # load the commit that inference_info recordsdevice="cuda",dtype="bfloat16",compile=compile,45 unmodified lines# Track inference infoinference_entry = {"model_id": MODEL_ID,"model_name": model_label,"model_size": "0.3B","revision": revision,"model_commit": model_commit,"task_mode": task_mode,"column_name": output_column,"timestamp": datetime.now().isoformat(),56 unmodified linesprocessing_time=processing_time_str,image_column=image_column,split=split,revision=revision,model_commit=model_commit,)card = DatasetCard(card_content)card.push_to_hub(output_dataset, token=HF_TOKEN)25 unmodified linesprint("=" * 70)print("Falcon OCR - 0.3B Document OCR (falcon-perception engine)")print("=" * 70)print(f"\nModel: {MODEL_ID} @ {DEFAULT_REVISION[:10]} ({MODEL_LABEL}; --revision to override)")print("License: Apache 2.0")print("\nTask Modes:")for mode, description in TASK_MODES.items():print(f" {mode:10} - {description}")print("\nExamples:")print(" uv run falcon-ocr.py input-dataset output-dataset")print("\nFor full help: uv run falcon-ocr.py --help")sys.exit(0)11 unmodified lines)parser.add_argument("--task-mode", choices=list(TASK_MODES.keys()), default="plain",help="Task type: plain (the only mode)",)parser.add_argument("--hf-token", help="Hugging Face API token")parser.add_argument(45 unmodified linesparser.add_argument("--verbose", action="store_true", help="Log resolved package versions",)parser.add_argument("--revision", default=None,help=f"Model repo revision (branch, tag or commit sha). Default: the {MODEL_LABEL} "f"pin {DEFAULT_REVISION[:10]}. Pass 'main' to follow the repo root (v1.5 since ""2026-09-11) or any commit to reproduce a run; the resolved commit is recorded ""in inference_info.",)args = parser.parse_args()16 unmodified linescudagraph=not args.no_cudagraph,progress=args.progress,verbose=args.verbose,revision=args.revision,)
123456754 unmodified lines6263646566676869998 unmodified lines10681069107010711072107310741075{"_meta": {"description": "Machine-readable catalog of the OCR recipes in this directory: script -> model, params, backend, support level, the tested Jobs launch config (the script's [tool.hf-jobs] header), and what the model's own card claims about language coverage. Human-readable language notes: LANGUAGES.md. Language evidence levels, strongest first: per-language-benchmark | count-claim | named-list | multilingual-unspecified | english-only | not-stated | not-applicable. Claims come from model cards (compiled 2026-07-15) - treat as claims, not guarantees.","updated": "2026-11-06","run_pattern": "hf jobs uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/<script> <input-dataset> <output-dataset> (hf CLI >= 1.32 reads image/flavor/secrets from the script's [tool.hf-jobs] header; add --timeout for long runs. Scripts without a `jobs` entry need --flavor/-s HF_TOKEN (and any --image in their docstring).)","support_levels": {"core": "Maintained. Smoke-tested flagless on HF Jobs on 2026-09-23/24 with the pinned launch config in `jobs`.",54 unmodified lines"languages": {"evidence": "not-stated"},"support": "legacy","support_note": "Falcon-OCR v1; v1.5 work is in PR #110."},"smoldocling-ocr.py": {"model_id": "ds4sd/SmolDocling-256M-preview",998 unmodified lines"falcon-ocr-bucket.py": {"variant_of": "falcon-ocr.py","notes": "Reads images/PDFs from a mounted bucket, writes one .md per page.","support": "legacy","support_note": "Falcon-OCR v1; v1.5 work is in PR #110. --max-samples counts files, not pages."},"surya-ocr-bucket.py": {"variant_of": "surya-ocr.py",123456754 unmodified lines6263646566676869707172737475767778798081828384858687888990919293949596979899998 unmodified lines10981099110011011102110311041105110611071108{"_meta": {"description": "Machine-readable catalog of the OCR recipes in this directory: script -> model, params, backend, support level, the tested Jobs launch config (the script's [tool.hf-jobs] header), and what the model's own card claims about language coverage. Human-readable language notes: LANGUAGES.md. Language evidence levels, strongest first: per-language-benchmark | count-claim | named-list | multilingual-unspecified | english-only | not-stated | not-applicable. Claims come from model cards (compiled 2026-07-15) - treat as claims, not guarantees.","updated": "2026-11-18","run_pattern": "hf jobs uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/<script> <input-dataset> <output-dataset> (hf CLI >= 1.32 reads image/flavor/secrets from the script's [tool.hf-jobs] header; add --timeout for long runs. Scripts without a `jobs` entry need --flavor/-s HF_TOKEN (and any --image in their docstring).)","support_levels": {"core": "Maintained. Smoke-tested flagless on HF Jobs on 2026-09-23/24 with the pinned launch config in `jobs`.",54 unmodified lines"languages": {"evidence": "not-stated"},"support": "core","support_note": "Falcon-OCR v1. Frozen 2026-11-18 (superseded by falcon-ocr-1.5.py): package cutoff and model revision pinned; fixed only when it breaks. Upstream replaced the repo root with v1.5 on 2026-09-11, so this recipe pins the last v1 commit. Use falcon-ocr-1.5.py for new runs.","revision": "42ec56b72a23984ac059e7c8a6d397a8529423fe","jobs": {"image": "ghcr.io/astral-sh/uv@sha256:85d4cb1afa769a7338e095b927bee941cf5ec92266c7424b3f6c0f2748567248","flavor": "a10g-small","timeout": "1h","secrets": ["HF_TOKEN"]}},"falcon-ocr-1.5.py": {"model_id": "tiiuae/Falcon-OCR","params": "0.3B","backend": "falcon-perception","task": "ocr","output": "markdown","license": "apache-2.0","languages": {"evidence": "not-stated"},"support": "core","support_note": "Falcon-OCR v1.5, pinned to the release head (fe757d59; the first v1.5 commit d259a7fb has older code files). --revision overrides the pin.","revision": "fe757d59ecd79d4d68760162306a70a015761ad9","jobs": {"flavor": "a10g-small","timeout": "1h","secrets": ["HF_TOKEN"]}},"smoldocling-ocr.py": {"model_id": "ds4sd/SmolDocling-256M-preview",998 unmodified lines"falcon-ocr-bucket.py": {"variant_of": "falcon-ocr.py","notes": "Reads images/PDFs from a mounted bucket, writes one .md per page.","support": "core","support_note": "Falcon-OCR v1 by default (pinned like falcon-ocr.py); --revision fe757d59ecd79d4d68760162306a70a015761ad9 runs v1.5. --max-samples counts files, not pages.","jobs": {"flavor": "a10g-small"}},"surya-ocr-bucket.py": {"variant_of": "surya-ocr.py",
CLAUDE.md+26-1
README.md+3-2
falcon-ocr-1.5.pyAdded+623
falcon-ocr-bucket.py+22-3
falcon-ocr.py+182-20
models.json+38-5