davanstrien HF Staff commited on
Commit
e2b0aa5
·
verified ·
1 Parent(s): 9827e45

Sync from davanstrien/uv-scripts via hub-sync

Browse files
Files changed (3) hide show
  1. CLAUDE.md +1 -0
  2. lighton-ocr3-live.py +785 -0
  3. models.json +24 -0
CLAUDE.md CHANGED
@@ -88,6 +88,7 @@ Legend: ✅ production-ready · ⚠️ works only with a required pinned image
88
  | `lighton-ocr2.py` | ✅ | vLLM | a100-large / l4x1 | resize 1540px; `--max-model-len` 16384 |
89
  | `lighton-ocr3-bucket.py` | ✅ | vLLM `:v0.30.0` | a10g-small | `hf://buckets/...` or dir → `.md` (+ `.json` blocks in grounding); bucket I/O via `bucketbag` v0.3.1 (no mount); `.jp2` via imagecodecs; resume-by-skip; failed pages write nothing |
90
  | `lighton-ocr3.py` | ✅ | vLLM `:v0.30.0` | a10g-small | 4B/0.8B Qwen3.5; resize 2048px; `--mode grounding` → `layout_blocks`; pinned upstream `lightonocr` client dep — see gotcha |
 
91
  | `paddleocr-vl-1.5.py` | ✅ | transformers | l4x1 | not vLLM (server-only upstream); single-image |
92
  | `paddleocr-vl-1.6.py` | ✅ | vLLM | l4x1 | smart-resize ~1M px; SOTA OmniDocBench |
93
  | `paddleocr-vl.py` | ✅ | vLLM | l4x1 | |
 
88
  | `lighton-ocr2.py` | ✅ | vLLM | a100-large / l4x1 | resize 1540px; `--max-model-len` 16384 |
89
  | `lighton-ocr3-bucket.py` | ✅ | vLLM `:v0.30.0` | a10g-small | `hf://buckets/...` or dir → `.md` (+ `.json` blocks in grounding); bucket I/O via `bucketbag` v0.3.1 (no mount); `.jp2` via imagecodecs; resume-by-skip; failed pages write nothing |
90
  | `lighton-ocr3.py` | ✅ | vLLM `:v0.30.0` | a10g-small | 4B/0.8B Qwen3.5; resize 2048px; `--mode grounding` → `layout_blocks`; pinned upstream `lightonocr` client dep — see gotcha |
91
+ | `lighton-ocr3-live.py` | 🧪 | saturate + vLLM `:v0.30.0` | rtx-pro-6000 | experimental: `lighton-ocr3-saturate.py` + `--live-port` page (finished pages at the run's pace; `?view=single`) |
92
  | `paddleocr-vl-1.5.py` | ✅ | transformers | l4x1 | not vLLM (server-only upstream); single-image |
93
  | `paddleocr-vl-1.6.py` | ✅ | vLLM | l4x1 | smart-resize ~1M px; SOTA OmniDocBench |
94
  | `paddleocr-vl.py` | ✅ | vLLM | l4x1 | |
lighton-ocr3-live.py ADDED
@@ -0,0 +1,785 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.11"
3
+ # dependencies = [
4
+ # "saturate[hf]==0.3.1",
5
+ # "pillow>=10",
6
+ # # LightOn's official client, pinned to a commit (not on PyPI). Used for its page
7
+ # # resize, grounding parser and dollar-delimiter repair so outputs match upstream.
8
+ # "lightonocr @ https://github.com/lightonai/LightOnOCR/archive/36755d461be079737860a5f03ae0c803501269e9.tar.gz",
9
+ # ]
10
+ #
11
+ # [tool.hf-jobs]
12
+ # image = "vllm/vllm-openai:v0.30.0"
13
+ # flavor = "rtx-pro-6000"
14
+ # timeout = "4h"
15
+ # secrets = ["HF_TOKEN"]
16
+ # ///
17
+ """
18
+ EXPERIMENTAL: lighton-ocr3-saturate.py with a live view you can watch (and screen-record) while the Job runs.
19
+
20
+ Same OCR, flags and output as lighton-ocr3-saturate.py; use that script for normal runs and
21
+ read its description for the model settings, the measured speeds and the repair pass. This
22
+ one adds `--live-port`: a page served from inside the Job that shows every finished page
23
+ moving past at the speed the model reads them, the pages read a second, and the text the
24
+ model wrote for one of them.
25
+
26
+ hf jobs uv run --detach --expose-public 7860 \\
27
+ https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lighton-ocr3-live.py \\
28
+ <input-dataset> <output-dataset> --live-port 7860
29
+
30
+ The Job log prints the link: https://<job id>--7860.hf.jobs (public while the Job runs).
31
+ The header picks rtx-pro-6000, the fastest flavor per dollar in lighton-ocr3-saturate.py's
32
+ table (about 10 pages per second with the 0.8B); add --flavor a10g-small for a small run.
33
+
34
+ What the page shows, and how it is paced:
35
+ - Each tile on the belt is one finished page. A page is shown only after its text came
36
+ back, and the belt moves at the rate the pages finish, so its speed is the throughput.
37
+ The page draws a finished page about 1.5 seconds after the model returned it.
38
+ - "Pages a second" is the number of pages finished in the last 10 seconds, divided by 10.
39
+ It covers reading only, not the server start (about 4 minutes). After the run it is the
40
+ average over the whole reading time.
41
+ - The text under the belt is one recent finished page's text, changed every few seconds.
42
+ It is a sample: at several pages a second most pages are never shown with their text.
43
+ - Add ?view=single to the link for one page at a time: each finished page is laid on the
44
+ last at the same pace, with that page's text beside it.
45
+ - The live view costs a 480 px JPEG per page in the preparation threads and one small
46
+ request per open tab every half second. It never changes what is sent or written.
47
+ - The page shows the main pass. Pages re-sent by --repair-max-tokens are not shown again.
48
+ - The Job, and with it the page, ends 20 seconds after the run. An open tab keeps the
49
+ final numbers on screen.
50
+
51
+ The SERVING dict below is the per-model tuning prior, as in lighton-ocr3-saturate.py.
52
+ """
53
+
54
+ import argparse
55
+ import base64
56
+ import collections
57
+ import hashlib
58
+ import io
59
+ import json
60
+ import os
61
+ import shlex
62
+ import subprocess
63
+ import sys
64
+ import tempfile
65
+ import threading
66
+ import time
67
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
68
+
69
+ # Serving starting values for LightOnOCR-3 (0.8B and 4B). Per-value provenance:
70
+ # - image: vLLM 0.30.0, the version LightOn's client pins and tests (0.27.1 makes the
71
+ # models loop, per the LightOnOCR README).
72
+ # - context 18000 and serve_args: the LightOnOCR README "Models" table for the 0.8B and 4B,
73
+ # plus its `--limit-mm-per-prompt '{"image": 1}'`.
74
+ # - max_tokens/temperature/top_p: the model card's vLLM example, verbatim.
75
+ # - longest_edge 2048: the card's rendering tip and the client's page size for these models.
76
+ # - patch 32: 16 px patches with a 2x2 merge, so a 2048x2048 page is at most 64x64 = 4,096
77
+ # image tokens (used for the context check).
78
+ # - --max-num-batched-tokens 16384: speed only. vLLM 0.30 serves with 2048 on A10G, L4 and
79
+ # A100 (8192 on other GPUs of 70 GB or more), less than one page's image tokens. Measured on a100-large:
80
+ # 6.20 and 6.30 pages/s against 5.83 without it, outputs within the run-to-run noise.
81
+ # - pages_per_gib: see window_cap().
82
+ # - api_servers 4 when CPU_CORES >= 12: speed only. With one vLLM API server, a100-large and
83
+ # rtx-pro-6000 had 128-256 pages in flight but only 36-60 running in the engine and none
84
+ # waiting: the rest queued for image preprocessing in the API process. Measured, 4 API
85
+ # servers against one: a100-large 7.29 and 7.18 against 6.20 and 6.30 pages/s,
86
+ # rtx-pro-6000 10.0 against 9.15, a10g-large 2.74 against 2.49; outputs within the
87
+ # run-to-run noise. Small flavors (a10g-small 3 cores, l4x1 8) keep one, to leave CPU
88
+ # for page preparation.
89
+ SERVING = {
90
+ "models": ["lightonai/LightOnOCR-3-0.8B", "lightonai/LightOnOCR-3-4B"],
91
+ "image": "vllm/vllm-openai:v0.30.0",
92
+ "context": 18000,
93
+ "serve_args": [
94
+ "--default-chat-template-kwargs", '{"enable_thinking": false}',
95
+ "--limit-mm-per-prompt", '{"image": 1}',
96
+ "--mm-processor-cache-gb", "0",
97
+ "--no-enable-prefix-caching",
98
+ "--max-num-batched-tokens", "16384",
99
+ ],
100
+ "pages_per_gib": 6,
101
+ "api_servers": 4,
102
+ "api_servers_min_cores": 12,
103
+ "max_tokens": 4096,
104
+ "temperature": 0.2,
105
+ "top_p": 0.9,
106
+ "repair_temperature": 0.1,
107
+ "longest_edge": 2048,
108
+ "patch": 32,
109
+ }
110
+
111
+
112
+ def window_cap() -> int:
113
+ """Most pages in flight that this machine's memory allows.
114
+
115
+ Every page in flight holds about 0.1 GiB of image data on the host (the client's copy and
116
+ the server's preprocessed image), on top of 7 to 9 GiB for the engine itself. On
117
+ a10g-small (14.9 GiB limit), 64 pages in flight reached the limit and the Job stopped
118
+ making progress; 32 peaked at 12.0 GiB, and up to 39 peaked at 13.0 and 14.8 GiB on two
119
+ runs. So the window may grow by SERVING "pages_per_gib" pages per GiB above 10 GiB: 29 on
120
+ a10g-small (which is GPU-bound from about 20 pages in flight), about 100 on l4x1, the full
121
+ 512 on a100-large. The limit is read from the container (cgroup v2), then from the MEMORY
122
+ variable that HF Jobs sets.
123
+ """
124
+ limit_gib = None
125
+ try:
126
+ with open("/sys/fs/cgroup/memory.max") as handle:
127
+ value = handle.read().strip()
128
+ if value != "max":
129
+ limit_gib = int(value) / 2**30
130
+ except (OSError, ValueError):
131
+ pass
132
+ if limit_gib is None and os.environ.get("MEMORY"):
133
+ try: # e.g. "16.0G" (decimal gigabytes)
134
+ limit_gib = float(os.environ["MEMORY"].upper().rstrip("GIB ")) * 1e9 / 2**30
135
+ except ValueError:
136
+ pass
137
+ if limit_gib is None:
138
+ return 512
139
+ return max(8, min(512, int((limit_gib - 10) * SERVING["pages_per_gib"])))
140
+
141
+
142
+ def flag_value(tokens: list[str], name: str):
143
+ """Last value given for `name` in a `vllm serve` argument list (`--x v` or `--x=v`), else None."""
144
+ value = None
145
+ for index, token in enumerate(tokens):
146
+ if token == name and index + 1 < len(tokens):
147
+ value = tokens[index + 1]
148
+ elif token.startswith(name + "="):
149
+ value = token.split("=", 1)[1]
150
+ return value
151
+
152
+
153
+ def saved_truncations(output_dataset: str) -> set:
154
+ """Ids whose saved result in data/ stopped at max_tokens and that have no saved repair.
155
+
156
+ A restarted run skips rows already in data/, so without this the pages truncated
157
+ before the restart would never reach the repair pass. Reads only three columns.
158
+ """
159
+ import fsspec
160
+ import pyarrow.parquet as pq
161
+
162
+ def records(subdir, columns):
163
+ fs, root = fsspec.core.url_to_fs(f"hf://datasets/{output_dataset}/{subdir}")
164
+ if not fs.exists(root):
165
+ return
166
+ for path in fs.glob(f"{root}/part-*.parquet"):
167
+ with fs.open(path, "rb") as handle:
168
+ yield from pq.read_table(handle, columns=columns).to_pylist()
169
+
170
+ finish = {}
171
+ for record in records("data", ["id", "error", "finish_reason"]):
172
+ if record["error"] is None:
173
+ finish[record["id"]] = record["finish_reason"]
174
+ repaired = {r["id"] for r in records("repair", ["id", "error"]) if r["error"] is None}
175
+ return {row_id for row_id, reason in finish.items() if reason == "length" and row_id not in repaired}
176
+
177
+
178
+ def max_image_tokens(longest_edge: int) -> int:
179
+ """Upper bound on the image tokens of a page fitted to longest_edge (square page)."""
180
+ side = -(-longest_edge // SERVING["patch"])
181
+ return side * side
182
+
183
+
184
+ def to_pil(value):
185
+ from PIL import Image
186
+
187
+ if isinstance(value, Image.Image):
188
+ return value
189
+ if isinstance(value, dict) and value.get("bytes"):
190
+ return Image.open(io.BytesIO(value["bytes"]))
191
+ if isinstance(value, dict) and value.get("path"):
192
+ return Image.open(value["path"])
193
+ if isinstance(value, (bytes, bytearray)):
194
+ return Image.open(io.BytesIO(value))
195
+ raise ValueError(f"unsupported image value: {type(value)}")
196
+
197
+
198
+ def page_png(value, longest_edge: int) -> bytes:
199
+ """RGB page fitted to longest_edge with LightOn's resize, as PNG bytes.
200
+
201
+ compress_level=1 instead of Pillow's default 6: PNG is lossless at every level, so the
202
+ pixels are identical, and level 1 encodes several times faster (CPU is the limit on
203
+ small flavors).
204
+ """
205
+ return png_bytes(fitted_page(value, longest_edge))
206
+
207
+
208
+ def fitted_page(value, longest_edge: int):
209
+ """RGB page fitted to longest_edge with LightOn's resize."""
210
+ from lightonocr import fit
211
+
212
+ return fit(to_pil(value).convert("RGB"), longest_edge)
213
+
214
+
215
+ def png_bytes(image) -> bytes:
216
+ buffer = io.BytesIO()
217
+ image.save(buffer, format="PNG", compress_level=1)
218
+ return buffer.getvalue()
219
+
220
+
221
+ def chat_request(model: str, png: bytes, mode: str, max_tokens: int, temperature: float, top_p: float) -> dict:
222
+ """One page as the client sends it: the image, plus the word "grounding" in grounding mode."""
223
+ from lightonocr import GROUNDING_PROMPT
224
+
225
+ url = "data:image/png;base64," + base64.b64encode(png).decode()
226
+ content = [{"type": "image_url", "image_url": {"url": url}}]
227
+ if mode == "grounding":
228
+ content.append({"type": "text", "text": GROUNDING_PROMPT})
229
+ return {
230
+ "model": model,
231
+ "messages": [{"role": "user", "content": content}],
232
+ "max_tokens": max_tokens,
233
+ "temperature": temperature,
234
+ "top_p": top_p,
235
+ "chat_template_kwargs": {"enable_thinking": False},
236
+ }
237
+
238
+
239
+ def postprocess(raw: str, mode: str, fix_dollars: bool):
240
+ """Return (markdown, layout_blocks JSON or None) for one model output, as lighton-ocr3.py."""
241
+ from lightonocr import fix_escaped_dollars, parse_blocks, to_markdown
242
+
243
+ text = fix_escaped_dollars(raw) if fix_dollars else raw
244
+ if mode != "grounding":
245
+ return text, None
246
+ blocks = parse_blocks(text)
247
+ if not blocks:
248
+ return text, json.dumps([]) # no markers parsed: keep the text so nothing is lost
249
+ return to_markdown(blocks), json.dumps([b.to_dict() for b in blocks], ensure_ascii=False)
250
+
251
+
252
+ def count_pages(dataset: str, config, split: str, limit):
253
+ """Number of rows the run will read, from the dataset's metadata (None if it does not say)."""
254
+ try:
255
+ from datasets import load_dataset_builder
256
+
257
+ total = load_dataset_builder(dataset, name=config).info.splits[split].num_examples
258
+ except Exception as e: # noqa: BLE001 - the count is only shown; the run must not depend on it
259
+ print(f"Live view: page count unknown ({type(e).__name__})", file=sys.stderr)
260
+ return limit
261
+ return min(total, limit) if limit else total
262
+
263
+
264
+ LIVE_PAGE = """<!doctype html><meta charset="utf-8"><title>LightOnOCR-3 live</title>
265
+ <meta name="viewport" content="width=device-width, initial-scale=1">
266
+ <style>
267
+ /* A copy stand: a neutral ground, and the paper is the only colour on it. */
268
+ :root{--ground:#2b2f34;--ink:#f4f2ed;--quiet:#a4aab1;--rule:rgba(244,242,237,.22);--paper:#fbfaf7;
269
+ --lift:0 0 0 1px rgba(0,0,0,.10),0 .7vmin 2vmin rgba(0,0,0,.34)}
270
+ @media (prefers-color-scheme:light){:root{--ground:#c9cdd1;--ink:#15171a;--quiet:#4a4f56;--rule:rgba(21,23,26,.22);
271
+ --lift:0 0 0 1px rgba(0,0,0,.07),0 .5vmin 1.6vmin rgba(0,0,0,.20)}}
272
+ *{box-sizing:border-box}
273
+ html{font-size:clamp(15px,2.1vmin,24px)}
274
+ body{margin:0;height:100vh;overflow:hidden;background:var(--ground);color:var(--ink);
275
+ font-family:"Avenir Next","Helvetica Neue",system-ui,sans-serif;line-height:1.35;
276
+ display:grid;grid-template-rows:minmax(0,1fr) auto}
277
+ #belt{position:relative;display:flex;flex-direction:column;gap:1.7vmin;padding:2.2vmin 0;min-height:0;overflow:hidden}
278
+ .row{position:relative;flex:1;min-height:0}
279
+ .track{position:absolute;inset:0;will-change:transform}
280
+ .track img{position:absolute;top:0;height:100%;object-fit:cover;object-position:top;background:var(--paper);
281
+ border-radius:2px;box-shadow:var(--lift)}
282
+ #progress{height:2px;background:var(--rule)}
283
+ #progress div{height:2px;width:0;background:var(--ink)}
284
+ #band{display:grid;grid-template-columns:minmax(0,1fr);gap:1.1rem;padding:1.5rem 4vmin 1.9rem}
285
+ #rate{font-size:2.55rem;font-weight:600;line-height:1.08;letter-spacing:-.012em;margin:0 0 .45rem;
286
+ font-variant-numeric:tabular-nums;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
287
+ #run,#count{margin:0}
288
+ #count{color:var(--quiet);font-variant-numeric:tabular-nums}
289
+ #sample{margin:0;min-width:0;transition:opacity .4s}
290
+ #sample.out{opacity:0}
291
+ #text{margin:0;font-family:"Iowan Old Style",Charter,Georgia,serif;font-size:1.02rem;line-height:1.5;height:4.5em;
292
+ overflow:hidden;white-space:pre-line}
293
+ #from{margin:.3rem 0 0;color:var(--quiet);font-size:.82rem}
294
+ @media (min-aspect-ratio:13/10){#band{grid-template-columns:minmax(0,5fr) minmax(0,6fr);gap:5vmin;align-items:end}}
295
+ /* ?view=single: one page at a time, each laid on the last, at the same pace */
296
+ .single #belt{display:block;padding:0}
297
+ #pile{position:absolute;inset:3vmin 0 2.4vmin}
298
+ #pile img{position:absolute;left:50%;top:0;height:100%;aspect-ratio:.74;object-fit:cover;object-position:top;
299
+ background:var(--paper);border-radius:3px;box-shadow:var(--lift)}
300
+ .single #text{height:10.5em}
301
+ @media (min-aspect-ratio:13/10){
302
+ body.single{grid-template-columns:minmax(0,9fr) minmax(0,11fr);grid-template-rows:minmax(0,1fr) auto}
303
+ .single #belt{grid-row:1;grid-column:1}.single #progress{grid-row:2;grid-column:1/-1}
304
+ .single #band{grid-row:1;grid-column:2;grid-template-columns:minmax(0,1fr);align-content:center;gap:2.2rem;padding-left:1vmin}
305
+ .single #text{height:12em}}
306
+ </style>
307
+ <section id="belt" aria-label="Pages the model has read"></section>
308
+ <div id="progress"><div id="bar"></div></div>
309
+ <section id="band">
310
+ <div><p id="rate">Starting</p><p id="run"></p><p id="count"></p></div>
311
+ <figure id="sample" class="out"><p id="text"></p><figcaption id="from"></figcaption></figure>
312
+ </section>
313
+ <script>
314
+ const $ = id => document.getElementById(id), fmt = n => Math.round(n).toLocaleString("en-US");
315
+ const clock = s => { s = Number.isFinite(s) ? Math.max(0, Math.round(s)) : 0;
316
+ return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`; };
317
+ const NL = String.fromCharCode(10);
318
+ const LAG = 1.5; // seconds a finished page waits before it is drawn, so the belt moves evenly
319
+ const still = matchMedia("(prefers-reduced-motion: reduce)").matches; // then the belt moves in steps
320
+ const single = new URLSearchParams(location.search).get("view") === "single";
321
+ document.body.classList.toggle("single", single);
322
+ let since = 0, last = null, misses = 0, first = true, stopped = false;
323
+ let rows = [], tileW = 0, pitch = 0, beltW = 0, offset = 0, drawn = 0, speed = 0;
324
+ const waiting = [], ready = []; // finished pages: image still loading, then loaded; oldest first
325
+ let shown = 0, shownWords = 0, recent = [];
326
+
327
+ function layout() {
328
+ if (single) { const pile = document.createElement("div"); pile.id = "pile"; $("belt").replaceChildren(pile); return; }
329
+ const belt = $("belt"), vmin = Math.min(innerWidth, innerHeight), gap = vmin * 0.017;
330
+ const h = belt.clientHeight - vmin * 0.044, n = Math.max(2, Math.min(5, Math.round(h / (vmin * 0.26))));
331
+ const rowH = (h - gap * (n - 1)) / n;
332
+ tileW = Math.round(rowH * 0.74); pitch = tileW + gap; beltW = belt.clientWidth; offset = drawn = 0;
333
+ belt.replaceChildren();
334
+ rows = Array.from({length: n}, () => {
335
+ const row = document.createElement("div"), track = document.createElement("div");
336
+ row.className = "row"; track.className = "track"; row.append(track); belt.append(row);
337
+ return {track, tail: 0, tiles: []};
338
+ });
339
+ }
340
+
341
+ // One finished page becomes one tile, placed at the end of the shortest row.
342
+ function place(p) {
343
+ shown += 1; shownWords += p.words;
344
+ if (p.missing) return;
345
+ const row = rows.reduce((a, b) => b.tail < a.tail ? b : a), x = Math.max(row.tail, offset + beltW);
346
+ p.el.style.left = x + "px"; p.el.style.width = tileW + "px";
347
+ row.track.append(p.el); row.tiles.push({x, el: p.el}); row.tail = x + pitch;
348
+ recent.push(p); if (recent.length > 40) recent.shift();
349
+ }
350
+
351
+ // Single view: the page goes on top of the pile, with a small turn so earlier pages show at the edges.
352
+ let credit = 0;
353
+ function deal(p) {
354
+ shown += 1; shownWords += p.words;
355
+ if (p.missing) return;
356
+ const turn = still ? 0 : (Math.random() - 0.5) * 2.4, dx = (Math.random() - 0.5) * 1.4, dy = (Math.random() - 0.5) * 0.9;
357
+ p.el.style.transform = `translate(calc(-50% + ${dx}vmin), ${dy}vmin) rotate(${turn}deg)`;
358
+ const pile = $("pile"); pile.append(p.el);
359
+ while (pile.children.length > 10) pile.firstChild.remove();
360
+ recent.push(p); if (recent.length > 40) recent.shift();
361
+ write(p);
362
+ }
363
+
364
+ // The belt moves so that the pages waiting to be drawn clear in LAG seconds: while pages
365
+ // finish at a steady rate that is the rate itself, and when none are left it stops.
366
+ let before = performance.now();
367
+ function frame(now) {
368
+ const dt = Math.min(0.1, (now - before) / 1000); before = now;
369
+ const want = ready.length ? Math.max(1, ready.length / LAG) : 0;
370
+ const target = rows.length ? want * pitch / rows.length : 0;
371
+ if (single) { // the same pace, counted in pages instead of distance
372
+ speed += (want - speed) * Math.min(1, dt * 2.5); credit = Math.min(3, credit + speed * dt);
373
+ while (ready.length && (ready[0].missing || credit >= 1)) { if (!ready[0].missing) credit -= 1; deal(ready.shift()); }
374
+ words(); requestAnimationFrame(frame); return;
375
+ }
376
+ speed += (target - speed) * Math.min(1, dt * 2.5);
377
+ offset += speed * dt;
378
+ while (ready.length && (ready[0].missing || Math.min(...rows.map(r => r.tail)) <= offset + beltW)) place(ready.shift());
379
+ if (!still || offset - drawn >= pitch) drawn = offset;
380
+ for (const r of rows) {
381
+ r.track.style.transform = `translateX(${-drawn}px)`;
382
+ while (r.tiles.length && r.tiles[0].x + pitch < drawn) r.tiles.shift().el.remove();
383
+ }
384
+ words();
385
+ requestAnimationFrame(frame);
386
+ }
387
+
388
+ // The three lines under the belt, as sentences.
389
+ function words() {
390
+ const s = last; if (!s) return;
391
+ const all = s.finished && !ready.length && !waiting.length, done = all ? s.pages_done : shown;
392
+ const of = s.pages_total ? ` of ${fmt(s.pages_total)}` : "";
393
+ if (s.pages_total) $("bar").style.width = Math.min(100, 100 * done / s.pages_total) + "%";
394
+ $("run").textContent = s.model.split("/").pop() + (s.gpu_name ? ` on one ${s.gpu_name}, ` : " on ") + "Hugging Face Jobs";
395
+ if (!s.reading) {
396
+ $("rate").textContent = s.phase;
397
+ $("count").textContent = `Started ${clock(s.uptime_s)} ago` + (s.pages_total ? `, ${fmt(s.pages_total)} pages to read` : "");
398
+ } else {
399
+ const rate = s.finished ? s.pages_done / Math.max(1, s.reading_s) : s.rate_pps;
400
+ $("rate").textContent = rate ? `${rate.toFixed(1)} pages a second` : "Reading the first pages";
401
+ $("count").textContent = stopped ? "The Job stopped. Check the Job logs."
402
+ : all ? `All ${fmt(done)} pages read in ${clock(s.reading_s)}`
403
+ : `${fmt(done)}${of} pages read in ${clock(s.reading_s)}`;
404
+ }
405
+ }
406
+
407
+ function ingest(d) {
408
+ const s = d.stats; last = s;
409
+ document.title = s.model.split("/").pop() + " live";
410
+ // A late open or a reload starts from the newest pages, not the whole history.
411
+ let pages = d.pages;
412
+ if (first) { pages = pages.slice(-12); first = false;
413
+ shown = s.pages_done - pages.length; shownWords = s.words - pages.reduce((a, p) => a + p.words, 0); }
414
+ for (const p of d.pages) since = Math.max(since, p.seq);
415
+ for (const p of pages) {
416
+ const el = new Image(); p.el = el; el.alt = "";
417
+ el.onload = () => { p.loaded = true; flush(); };
418
+ el.onerror = () => { // one retry, then the page is counted without a tile
419
+ if (p.retried) { p.missing = true; p.loaded = true; flush(); }
420
+ else { p.retried = true; setTimeout(() => { el.src = "img/" + p.img + "?retry"; }, 400); }
421
+ };
422
+ el.src = "img/" + p.img; waiting.push(p);
423
+ }
424
+ }
425
+
426
+ // Pages enter the belt in the order they finished, each once its image has loaded.
427
+ function flush() { while (waiting.length && waiting[0].loaded) ready.push(waiting.shift()); }
428
+
429
+ // A page's text as the model wrote it, without table and heading markup.
430
+ function write(p) {
431
+ const plain = (p.text || "").replace(/<[^>]+>/g, " ").replace(/^#+ /gm, "").replaceAll("**", "")
432
+ .replace(/ {2,}/g, " ").replace(new RegExp("( ?" + NL + " ?){2,}", "g"), NL).trim();
433
+ $("text").textContent = plain || "(no text on this page)";
434
+ $("from").textContent = single ? "The text of the page on top" : "The text of one of these pages";
435
+ $("sample").classList.remove("out");
436
+ }
437
+
438
+ // Belt view: one recent page's text, changed every few seconds. (Single view writes every page.)
439
+ let sampled = null;
440
+ function sample() {
441
+ if (single) return;
442
+ const withText = recent.filter(p => (p.text || "").length > 200), p = (withText.length ? withText : recent).at(-1);
443
+ if (p && p !== sampled) {
444
+ sampled = p; $("sample").classList.add("out");
445
+ setTimeout(() => write(p), 400);
446
+ }
447
+ setTimeout(sample, 4000);
448
+ }
449
+
450
+ async function poll() {
451
+ try {
452
+ ingest(await (await fetch("feed.json?since=" + since)).json()); misses = 0;
453
+ } catch (e) {
454
+ misses += 1;
455
+ if (misses >= 6 && last && !last.finished) stopped = true;
456
+ }
457
+ setTimeout(poll, 500);
458
+ }
459
+ layout(); addEventListener("resize", layout);
460
+ poll(); sample(); requestAnimationFrame(frame);
461
+ </script>"""
462
+
463
+
464
+ class LiveView:
465
+ """Finished pages and run counters, served as a web page from inside the Job (`--live-port`)."""
466
+
467
+ def __init__(self, port: int, model: str, pages_total, keep: int = 240, stale_s: float = 1800):
468
+ self.model, self.pages_total = model, pages_total
469
+ self.pages = collections.deque(maxlen=keep) # finished pages, newest last
470
+ self.images: dict[str, bytes] = {} # key -> JPEG, for prepared and kept pages
471
+ self.prepared: dict[str, tuple[str, float]] = {} # row id -> (image key, time prepared)
472
+ self.stale_s = stale_s # a prepared page not back after this long failed or was dropped
473
+ self.lock = threading.Lock()
474
+ self.made = self.seq = self.pages_done = self.words = 0
475
+ self.booted = time.time()
476
+ self.started = None # first page prepared: the rate and the clock leave out the server start
477
+ self.finished = None
478
+ self.done_times = collections.deque() # when each recent page finished, for the rolling rate
479
+ self.gpu_name = None
480
+ live = self
481
+
482
+ class Handler(BaseHTTPRequestHandler):
483
+ def do_GET(self):
484
+ try:
485
+ if self.path.startswith("/feed.json"):
486
+ try:
487
+ since = int(self.path.partition("since=")[2] or 0)
488
+ except ValueError:
489
+ since = 0
490
+ self.reply(json.dumps(live.feed(since)).encode(), "application/json")
491
+ elif self.path.startswith("/img/"):
492
+ with live.lock:
493
+ jpeg = live.images.get(self.path[len("/img/"):].partition("?")[0])
494
+ if jpeg is None:
495
+ self.send_error(404)
496
+ else:
497
+ self.reply(jpeg, "image/jpeg", cache="max-age=86400")
498
+ else:
499
+ self.reply(LIVE_PAGE.encode(), "text/html; charset=utf-8")
500
+ except (BrokenPipeError, ConnectionResetError):
501
+ pass # the viewer closed the tab mid-reply
502
+
503
+ def reply(self, body: bytes, ctype: str, cache: str = "no-store"):
504
+ self.send_response(200)
505
+ self.send_header("Content-Type", ctype)
506
+ self.send_header("Cache-Control", cache)
507
+ self.end_headers()
508
+ self.wfile.write(body)
509
+
510
+ def log_message(self, *args): # keep the Job log for the OCR run
511
+ pass
512
+
513
+ class Server(ThreadingHTTPServer):
514
+ request_queue_size = 128 # a tab asks for several page images at once
515
+
516
+ server = Server(("0.0.0.0", port), Handler)
517
+ threading.Thread(target=server.serve_forever, daemon=True).start()
518
+ threading.Thread(target=self.name_gpu, daemon=True).start()
519
+ # An exposed Job port is served at https://<job id>--<port>.hf.jobs.
520
+ where = (f"https://{os.environ['JOB_ID']}--{port}.hf.jobs (needs --expose-public {port})"
521
+ if os.environ.get("JOB_ID") else f"http://localhost:{port}")
522
+ print(f"Live view: {where}", file=sys.stderr, flush=True)
523
+
524
+ def name_gpu(self):
525
+ try:
526
+ out = subprocess.run(["nvidia-smi", "--query-gpu=name", "--format=csv,noheader"],
527
+ capture_output=True, text=True, timeout=10, check=True).stdout.splitlines()
528
+ except (OSError, subprocess.SubprocessError):
529
+ return
530
+ if len(out) == 1: # the page says "one <GPU>": leave it out on a multi-GPU flavor
531
+ with self.lock:
532
+ self.gpu_name = out[0].strip()
533
+
534
+ def add_thumbnail(self, row_id: str, image):
535
+ thumb = image.copy()
536
+ thumb.thumbnail((480, 480))
537
+ buffer = io.BytesIO()
538
+ thumb.save(buffer, format="JPEG", quality=78)
539
+ with self.lock:
540
+ if self.started is None:
541
+ self.started = time.time()
542
+ self.made += 1
543
+ key = f"{self.made}.jpg"
544
+ self.images[key] = buffer.getvalue()
545
+ old = self.prepared.get(row_id)
546
+ if old: # prepared again for a retry: drop the earlier copy
547
+ self.images.pop(old[0], None)
548
+ self.prepared[row_id] = (key, time.time())
549
+
550
+ def add_page(self, row_id: str, text: str):
551
+ now = time.time()
552
+ tail = row_id.rsplit(":", 1)[-1]
553
+ with self.lock:
554
+ key, _ = self.prepared.pop(row_id, ("", now))
555
+ if len(self.pages) == self.pages.maxlen: # the oldest kept page leaves: drop its image
556
+ self.images.pop(self.pages[0]["img"], None)
557
+ words = len(text.split())
558
+ self.seq += 1
559
+ self.pages_done += 1
560
+ self.words += words
561
+ self.done_times.append(now)
562
+ self.pages.append({"seq": self.seq, "img": key, "text": text[:700], "words": words,
563
+ "n": int(tail) + 1 if tail.isdigit() else None})
564
+
565
+ def finish(self):
566
+ with self.lock:
567
+ self.finished = time.time()
568
+
569
+ def feed(self, since: int) -> dict:
570
+ now = time.time()
571
+ with self.lock:
572
+ for row_id, (key, t) in list(self.prepared.items()):
573
+ if now - t > self.stale_s:
574
+ del self.prepared[row_id]
575
+ self.images.pop(key, None)
576
+ while self.done_times and now - self.done_times[0] > 10:
577
+ self.done_times.popleft()
578
+ end = self.finished or now
579
+ reading_s = end - self.started if self.started else 0
580
+ rate = len(self.done_times) / 10 if reading_s >= 10 and not self.finished else 0
581
+ phase = "Finished" if self.finished else "Reading pages" if self.pages_done else \
582
+ "Preparing the first pages" if self.started else "Starting the model server"
583
+ return {"stats": {"model": self.model, "gpu_name": self.gpu_name, "phase": phase,
584
+ "reading": self.pages_done > 0, "finished": self.finished is not None,
585
+ "uptime_s": round(now - self.booted), "reading_s": round(reading_s),
586
+ "pages_total": self.pages_total, "pages_done": self.pages_done,
587
+ "words": self.words, "rate_pps": round(rate, 1)},
588
+ "pages": [p for p in self.pages if p["seq"] > since][-120:]}
589
+
590
+
591
+ def main():
592
+ ap = argparse.ArgumentParser(description="LightOnOCR-3 batch OCR via saturate, with a live view")
593
+ ap.add_argument("input_dataset", help="Input dataset repo id (rows with an image column)")
594
+ ap.add_argument("output_dataset", help="Output dataset repo id (created private if missing)")
595
+ ap.add_argument("--model", default=SERVING["models"][0], choices=SERVING["models"])
596
+ ap.add_argument("--mode", default="plain", choices=["plain", "grounding"],
597
+ help="plain = markdown; grounding = labelled layout blocks with 0-1000 boxes")
598
+ ap.add_argument("--image-column", default="image")
599
+ ap.add_argument("--config", default=None, help="Dataset config name")
600
+ ap.add_argument("--split", default="train")
601
+ ap.add_argument("--id-column", default=None,
602
+ help="Column to use as row id (default: split-index ids)")
603
+ ap.add_argument("--max-samples", "--limit", dest="limit", type=int, default=None,
604
+ help="Process only the first N rows (smoke test)")
605
+ ap.add_argument("--max-tokens", type=int, default=SERVING["max_tokens"],
606
+ help="Output cap per page (default 4096, the model card's)")
607
+ ap.add_argument("--temperature", type=float, default=SERVING["temperature"])
608
+ ap.add_argument("--top-p", type=float, default=SERVING["top_p"],
609
+ help="Default 0.9, the model card's; LightOn's client uses 1.0")
610
+ ap.add_argument("--longest-edge", type=int, default=SERVING["longest_edge"],
611
+ help="Downscale pages to at most this many pixels on the longest edge")
612
+ ap.add_argument("--no-fix-dollars", action="store_true",
613
+ help="Keep the model's text in `markdown` without repairing escaped dollars")
614
+ ap.add_argument("--repair-max-tokens", type=int, default=0,
615
+ help="Re-send pages that hit --max-tokens once, with this cap and "
616
+ "temperature 0.1, into repair/ (default 0: off; 8192 suggested)")
617
+ ap.add_argument("--window", default="auto",
618
+ help="Pages in flight: 'auto' (saturate adapts it) or a fixed number")
619
+ ap.add_argument("--prepare-workers", type=int, default=None,
620
+ help="Threads that decode, resize and encode pages (default: CPU_CORES)")
621
+ ap.add_argument("--serve-args", default="",
622
+ help="Extra `vllm serve` flags, one quoted string, e.g. "
623
+ "\"--max-num-batched-tokens 16384\"")
624
+ ap.add_argument("--retry-errors", action="store_true",
625
+ help="Re-admit rows whose only record is an error row")
626
+ ap.add_argument("--live-port", type=int, default=None,
627
+ help="Serve the live view on this port (on Jobs, also pass --expose-public "
628
+ "with the same port)")
629
+ args = ap.parse_args()
630
+
631
+ user_serve_args = shlex.split(args.serve_args)
632
+ if args.longest_edge < 1:
633
+ ap.error("--longest-edge must be at least 1")
634
+ try: # --serve-args may set its own --max-model-len; vLLM uses the last one given
635
+ context = int(flag_value(user_serve_args, "--max-model-len") or SERVING["context"])
636
+ except ValueError:
637
+ ap.error("--max-model-len in --serve-args must be a whole number of tokens")
638
+ room = context - max_image_tokens(args.longest_edge) - 64
639
+ for flag, value in (("--max-tokens", args.max_tokens), ("--repair-max-tokens", args.repair_max_tokens)):
640
+ if value > room:
641
+ ap.error(f"{flag} {value} can overflow the {context}-token context with a "
642
+ f"{args.longest_edge} px page; use at most {room}")
643
+ if args.max_tokens < 1:
644
+ ap.error("--max-tokens must be at least 1")
645
+ if args.repair_max_tokens and args.repair_max_tokens <= args.max_tokens:
646
+ ap.error("--repair-max-tokens must be larger than --max-tokens")
647
+ if args.window != "auto" and not (args.window.isdigit() and int(args.window) >= 1):
648
+ ap.error("--window must be 'auto' or a number of at least 1")
649
+
650
+ import pyarrow as pa
651
+ from saturate import Auto, Engine, Fixed, dataset_rows, pump
652
+
653
+ if args.id_column is None:
654
+ ids = "index"
655
+ elif args.id_column in ("index", "content"):
656
+ # saturate reads these two names as id strategies, so a column with one of them
657
+ # needs a callable. It returns the raw value, so saturate still refuses a null id.
658
+ def ids(example):
659
+ return example[args.id_column]
660
+ else:
661
+ ids = args.id_column
662
+
663
+ rows = dataset_rows(
664
+ args.input_dataset, config=args.config, split=args.split,
665
+ columns=[args.image_column], ids=ids, limit=args.limit,
666
+ )
667
+
668
+ # Declared, so a part holding only error rows has the same columns as the rest
669
+ # (datasets.load_dataset reads every part with one schema).
670
+ schema = pa.schema([
671
+ ("id", pa.string()), ("error", pa.string()), ("markdown", pa.string()), ("raw", pa.string()),
672
+ ("finish_reason", pa.string()), ("layout_blocks", pa.string()), ("model", pa.string()),
673
+ ("prompt_tokens", pa.int64()), ("completion_tokens", pa.int64()),
674
+ ]) # fmt: skip
675
+
676
+ # Pages that hit --max-tokens, kept on local disk for the repair pass: those truncated
677
+ # in this run (stashed in parse) and those saved as truncated by an earlier, interrupted
678
+ # run (stashed as the stream passes them; the main pass skips them).
679
+ repair_dir = tempfile.mkdtemp(prefix="lighton-ocr3-repair-") if args.repair_max_tokens else None
680
+ earlier = saved_truncations(args.output_dataset) if repair_dir else set()
681
+ truncated = []
682
+
683
+ def stash(row_id, image):
684
+ path = os.path.join(repair_dir, hashlib.sha1(row_id.encode()).hexdigest() + ".png")
685
+ with open(path, "wb") as handle:
686
+ handle.write(page_png(image, args.longest_edge))
687
+ truncated.append((row_id, path))
688
+
689
+ live = None
690
+ if args.live_port:
691
+ live = LiveView(args.live_port, args.model,
692
+ count_pages(args.input_dataset, args.config, args.split, args.limit))
693
+
694
+ def to_request(row):
695
+ image = fitted_page(row[args.image_column], args.longest_edge)
696
+ if live:
697
+ live.add_thumbnail(row["__id"], image)
698
+ return chat_request(args.model, png_bytes(image), args.mode, args.max_tokens, args.temperature, args.top_p)
699
+
700
+ def make_parse(stash_truncated: bool):
701
+ def parse(row, body):
702
+ choice = body["choices"][0]
703
+ raw = (choice["message"].get("content") or "").strip()
704
+ markdown, blocks = postprocess(raw, args.mode, fix_dollars=not args.no_fix_dollars)
705
+ usage = body.get("usage") or {}
706
+ if stash_truncated and choice.get("finish_reason") == "length":
707
+ stash(row["__id"], row[args.image_column])
708
+ if live and "__id" in row: # repair rows carry no id: the live view shows the main pass
709
+ live.add_page(row["__id"], markdown)
710
+ return {
711
+ "markdown": markdown,
712
+ "raw": raw,
713
+ "finish_reason": choice.get("finish_reason"),
714
+ "layout_blocks": blocks,
715
+ "model": args.model,
716
+ "prompt_tokens": usage.get("prompt_tokens"),
717
+ "completion_tokens": usage.get("completion_tokens"),
718
+ }
719
+ return parse
720
+
721
+ def with_ids(source):
722
+ # Keep each row's id on the row, so parse can name the page it stashes for repair.
723
+ for row_id, row in source:
724
+ if row_id in earlier:
725
+ stash(row_id, row[args.image_column])
726
+ yield row_id, {**row, "__id": row_id}
727
+
728
+ cap = window_cap()
729
+ if args.window == "auto":
730
+ window = Auto(initial=min(64, cap), max_limit=cap)
731
+ print(f"window: auto, at most {cap} pages in flight (host memory)", file=sys.stderr)
732
+ else:
733
+ window = Fixed(int(args.window))
734
+ if int(args.window) > cap:
735
+ print(f"warning: --window {args.window} is above the {cap} pages this machine's "
736
+ "memory allows; the Job may run out of memory", file=sys.stderr)
737
+ cores = max(1, int(float(os.environ.get("CPU_CORES") or "4")))
738
+ workers = args.prepare_workers if args.prepare_workers is not None else cores
739
+ extra = [
740
+ "--max-model-len", str(SERVING["context"]),
741
+ *SERVING["serve_args"],
742
+ *user_serve_args,
743
+ ]
744
+ # Several API server processes share the image decoding and preprocessing, which one
745
+ # process cannot keep up with on a fast GPU. Only where there are cores to spare.
746
+ if cores >= SERVING["api_servers_min_cores"] and flag_value(extra, "--api-server-count") is None:
747
+ extra += ["--api-server-count", str(SERVING["api_servers"])]
748
+ print(f"server: --api-server-count {SERVING['api_servers']} ({cores} CPU cores)", file=sys.stderr)
749
+
750
+ output = f"hf://datasets/{args.output_dataset}/data"
751
+ with Engine(args.model, engine="vllm", extra_args=extra) as endpoint:
752
+ stats = pump(with_ids(rows), to_request, make_parse(bool(repair_dir)),
753
+ endpoint, output, window=window, prepare_workers=workers,
754
+ retry_errors=args.retry_errors, schema=schema)
755
+ print("LIGHTON_OCR3_SATURATE " + stats.to_json(), flush=True)
756
+ if live:
757
+ live.finish()
758
+
759
+ if repair_dir and truncated:
760
+ print(f"repair: re-sending {len(truncated)} pages that hit --max-tokens "
761
+ f"with a cap of {args.repair_max_tokens}", file=sys.stderr, flush=True)
762
+
763
+ def repair_rows():
764
+ for row_id, path in truncated:
765
+ with open(path, "rb") as handle:
766
+ yield row_id, {"png": handle.read()}
767
+
768
+ def repair_request(row):
769
+ return chat_request(args.model, row["png"], args.mode, args.repair_max_tokens,
770
+ SERVING["repair_temperature"], args.top_p)
771
+
772
+ repair_stats = pump(repair_rows(), repair_request, make_parse(False), endpoint,
773
+ f"hf://datasets/{args.output_dataset}/repair", window=window,
774
+ retry_errors=args.retry_errors, schema=schema)
775
+ print("LIGHTON_OCR3_SATURATE_REPAIR " + repair_stats.to_json(), flush=True)
776
+
777
+ print(f"https://huggingface.co/datasets/{args.output_dataset} "
778
+ f"({stats.rows_processed} ok, {stats.rows_failed} error rows, "
779
+ f"{len(truncated) if repair_dir else 'n/a'} truncated pages re-sent to repair/)", file=sys.stderr)
780
+ if live:
781
+ time.sleep(20) # the Job (and this page) ends with the script: let open tabs fetch the final numbers
782
+
783
+
784
+ if __name__ == "__main__":
785
+ main()
models.json CHANGED
@@ -415,6 +415,30 @@
415
  ]
416
  }
417
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
418
  "lighton-ocr2-server.py": {
419
  "model_id": "lightonai/LightOnOCR-2-1B",
420
  "params": "1B",
 
415
  ]
416
  }
417
  },
418
+ "lighton-ocr3-live.py": {
419
+ "model_id": "lightonai/LightOnOCR-3-0.8B",
420
+ "params": "0.8B (or 4B via --model)",
421
+ "backend": "saturate (in-job vllm serve + saturate pump)",
422
+ "image": "vllm/vllm-openai:v0.30.0",
423
+ "task": "ocr with a live view of the run",
424
+ "output": "markdown; --mode grounding adds labelled layout blocks with 0-1000 boxes (layout_blocks JSON column)",
425
+ "license": "apache-2.0",
426
+ "notes": "lighton-ocr3-saturate.py plus --live-port: a page served from the Job that shows each finished page moving past at the rate the pages finish, the pages read a second and one page's text; ?view=single shows one page at a time with its text. For watching or screen-recording a run. Measured 2026-11-10 with these settings and the live view open, pages fed from multi-page TIFFs by a one-off source: 14,483 typed pages (about 780 output tokens a page), 7.7 pages/s on rtx-pro-6000, 0 errors.",
427
+ "languages": {
428
+ "evidence": "not-stated",
429
+ "notes": "LightOnOCR-3 cards give no language list (LightOnOCR-2 named 11)."
430
+ },
431
+ "support": "experimental",
432
+ "support_note": "Use lighton-ocr3-saturate.py for normal runs; this adds a live view for demos.",
433
+ "jobs": {
434
+ "image": "vllm/vllm-openai:v0.30.0",
435
+ "flavor": "rtx-pro-6000",
436
+ "timeout": "4h",
437
+ "secrets": [
438
+ "HF_TOKEN"
439
+ ]
440
+ }
441
+ },
442
  "lighton-ocr2-server.py": {
443
  "model_id": "lightonai/LightOnOCR-2-1B",
444
  "params": "1B",