davanstrien HF Staff commited on
Commit
f837801
·
verified ·
1 Parent(s): 1261d34

Sync from GitHub via hub-sync

Browse files
Files changed (4) hide show
  1. CLAUDE.md +1 -0
  2. README.md +1 -1
  3. models.json +23 -0
  4. unlimited-ocr2-live.py +761 -0
CLAUDE.md CHANGED
@@ -94,6 +94,7 @@ Legend: ✅ production-ready · ⚠️ works only with a required pinned image
94
  | `unlimited-ocr-vllm.py` | ✅+image | vLLM `:unlimited-ocr` | l4x1 | single-image; multi-page → serve |
95
  | `unlimited-ocr2.py` | ✅+image | SGLang (Baidu wheel) on `lmsysorg/sglang:v0.5.20-cu130` | rtx-pro-6000 | 16-page windows; ≥48 GB GPU |
96
  | `unlimited-ocr2-saturate.py` | 🧪+image | same | rtx-pro-6000 | tuned/experimental: repair pass, JP2 fast decode, PDFs |
 
97
  | `surya-ocr.py` | ✅+image | vLLM `:v0.20.1` | l4x1 | offline backend inject; site-packages PYTHONPATH |
98
  | `surya-ocr-bucket.py` | ✅+image | vLLM `:v0.20.1` | l4x1 | bucket I/O; pin `surya-ocr==0.20.0` |
99
  | `lift-extract.py` | ✅ | hf / vLLM | a100-large | schema-constrained extraction; naming gotcha |
 
94
  | `unlimited-ocr-vllm.py` | ✅+image | vLLM `:unlimited-ocr` | l4x1 | single-image; multi-page → serve |
95
  | `unlimited-ocr2.py` | ✅+image | SGLang (Baidu wheel) on `lmsysorg/sglang:v0.5.20-cu130` | rtx-pro-6000 | 16-page windows; ≥48 GB GPU |
96
  | `unlimited-ocr2-saturate.py` | 🧪+image | same | rtx-pro-6000 | tuned/experimental: repair pass, JP2 fast decode, PDFs |
97
+ | `unlimited-ocr2-live.py` | 🧪+image | same | rtx-pro-6000 | experimental: minimal script + `--live-port` dashboard (streams the page being read) |
98
  | `surya-ocr.py` | ✅+image | vLLM `:v0.20.1` | l4x1 | offline backend inject; site-packages PYTHONPATH |
99
  | `surya-ocr-bucket.py` | ✅+image | vLLM `:v0.20.1` | l4x1 | bucket I/O; pin `surya-ocr==0.20.0` |
100
  | `lift-extract.py` | ✅ | hf / vLLM | a100-large | schema-constrained extraction; naming gotcha |
README.md CHANGED
@@ -230,7 +230,7 @@ hf jobs uv run --detach \
230
  your-username/britannica-1771
231
  ```
232
 
233
- The header picks `rtx-pro-6000` (the fastest per dollar in our tests; 24 GB GPUs are too small for 16-page requests). Results are one row per 16-page window. About 2% of pages in 18th-century print (mostly mathematics) send the model into a loop; `unlimited-ocr2-saturate.py`, an experimental tuned version, reads those pages again one at a time and adds PDF input and faster JPEG 2000 decoding.
234
 
235
  ```bash
236
  hf jobs uv run --detach --timeout 4h \
 
230
  your-username/britannica-1771
231
  ```
232
 
233
+ The header picks `rtx-pro-6000` (the fastest per dollar in our tests; 24 GB GPUs are too small for 16-page requests). Results are one row per 16-page window. About 2% of pages in 18th-century print (mostly mathematics) send the model into a loop; `unlimited-ocr2-saturate.py`, an experimental tuned version, reads those pages again one at a time and adds PDF input and faster JPEG 2000 decoding. `unlimited-ocr2-live.py`, also experimental, is the minimal script plus a live view you can open while the Job runs (add `--live-port 7860` and `--expose-public 7860`): the page being read with its text streaming in, finished pages, pages per minute and GPU load.
234
 
235
  ```bash
236
  hf jobs uv run --detach --timeout 4h \
models.json CHANGED
@@ -715,6 +715,29 @@
715
  ]
716
  }
717
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
718
  "unlimited-ocr-vllm.py": {
719
  "model_id": "baidu/Unlimited-OCR",
720
  "params": "3.3B",
 
715
  ]
716
  }
717
  },
718
+ "unlimited-ocr2-live.py": {
719
+ "model_id": "baidu/Unlimited-OCR-2",
720
+ "params": "3.3B (MoE, 0.5B active)",
721
+ "backend": "saturate (in-job SGLang from Baidu's wheel + saturate pump)",
722
+ "image": "lmsysorg/sglang:v0.5.20-cu130",
723
+ "task": "ocr (multi-page documents) with a live view of the run",
724
+ "output": "markdown per page + layout-grounded raw, one row per 16-page window",
725
+ "license": "mit",
726
+ "notes": "unlimited-ocr2.py plus --live-port: a dashboard served from the Job (start-up steps, the page being read with its text streaming in, finished pages, pages/min, GPU load) for watching or screen-recording a run. Also reduced-resolution JPEG 2000 decode, preparation threads from the CPU quota and an 8000-token page cap. Measured on 1,456 Wellcome Library pages: ~130 pages/min on rtx-pro-6000.",
727
+ "languages": {
728
+ "evidence": "multilingual-unspecified"
729
+ },
730
+ "support": "experimental",
731
+ "support_note": "Use unlimited-ocr2.py for normal runs; this adds a live view for demos.",
732
+ "jobs": {
733
+ "image": "lmsysorg/sglang:v0.5.20-cu130",
734
+ "flavor": "rtx-pro-6000",
735
+ "timeout": "4h",
736
+ "secrets": [
737
+ "HF_TOKEN"
738
+ ]
739
+ }
740
+ },
741
  "unlimited-ocr-vllm.py": {
742
  "model_id": "baidu/Unlimited-OCR",
743
  "params": "3.3B",
unlimited-ocr2-live.py ADDED
@@ -0,0 +1,761 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.11"
3
+ # dependencies = [
4
+ # "saturate[hf]==0.2.0",
5
+ # "pillow>=10",
6
+ # ]
7
+ #
8
+ # [tool.hf-jobs]
9
+ # image = "lmsysorg/sglang:v0.5.20-cu130"
10
+ # flavor = "rtx-pro-6000"
11
+ # timeout = "4h"
12
+ # secrets = ["HF_TOKEN"]
13
+ # ///
14
+ """
15
+ EXPERIMENTAL: unlimited-ocr2.py with a live view you can watch (and screen-record) while the Job runs.
16
+
17
+ Same OCR and output as unlimited-ocr2.py; use that script for normal runs. This one adds
18
+ `--live-port`: a page served from inside the Job showing start-up steps, the page the model is
19
+ reading right now with its text streaming in, every finished page, pages per minute and GPU load.
20
+ It also decodes JPEG 2000 at reduced resolution, sizes its preparation threads from the Job's
21
+ CPU quota and caps a page at 8000 output tokens (beyond that is a repetition loop).
22
+
23
+ hf jobs uv run --detach --expose-public 7860 \\
24
+ https://huggingface.co/datasets/uv-scripts/ocr/raw/main/unlimited-ocr2-live.py \\
25
+ "hf://buckets/biglam/britannica/source/pages/1771EncyclopediaBritannicaNLS/*.jp2" \\
26
+ <user>/britannica-1771 --live-port 7860
27
+
28
+ The Job log prints the link: https://<job id>--7860.hf.jobs (public while the Job runs).
29
+
30
+ What follows is unlimited-ocr2.py's description.
31
+
32
+ OCR whole documents (book volumes, folders of scans) with Baidu Unlimited-OCR-2.
33
+
34
+ Unlimited-OCR-2 reads many pages in ONE request and keeps context across page
35
+ breaks: a paragraph that runs onto the next page comes back tagged as a
36
+ continuation, not as two fragments. This script groups page images into
37
+ documents and sends 16 consecutive pages per request.
38
+
39
+ hf jobs uv run --detach \\
40
+ https://huggingface.co/datasets/uv-scripts/ocr/raw/main/unlimited-ocr2-live.py \\
41
+ "hf://buckets/biglam/britannica/source/pages/1771EncyclopediaBritannicaNLS/*.jp2" \\
42
+ <user>/britannica-1771
43
+
44
+ The [tool.hf-jobs] table above sets the image, GPU, timeout and HF_TOKEN.
45
+ The GPU needs >= 48 GB: on 24 GB cards a 16-page request (~31k tokens of KV)
46
+ thrashes the cache. rtx-pro-6000 was the fastest per dollar in our tests.
47
+
48
+ Input: a glob or folder of page images (a Bucket, a mounted dir, a local dir).
49
+ A document is the parent folder plus the file name without its trailing page
50
+ number (`Volume 1, A-B_0007.jp2` -> `Volume 1, A-B`); pages sort by that number.
51
+
52
+ Output: `data/part-*.parquet`, one row per 16-page window:
53
+ `{id, doc_id, first_page, page_files, status, page_markdown, raw, ...}`.
54
+ `page_markdown` lines up with `page_files`; `raw` is the model's output with its
55
+ layout blocks and boxes. `status` is `truncated` or `page_mismatch` when the model
56
+ ran out of budget or lost a page boundary (then `page_markdown` is empty and only
57
+ `raw` is kept). Re-running the same command resumes where it stopped.
58
+
59
+
60
+ About 2% of dense 18th-century pages (mostly mathematics) send the model into a
61
+ loop. `unlimited-ocr2-saturate.py` is the tuned version of this script: it
62
+ re-reads those pages one at a time, decodes JPEG 2000 faster, reads PDFs and adds
63
+ Baidu's own Markdown post-processing. It may change more often.
64
+
65
+ How it runs: Unlimited-OCR-2 needs Baidu's own SGLang build (no vLLM support).
66
+ The script installs that wheel into the image's Python, starts the server in the
67
+ Job, and sends requests with saturate (adaptive concurrency, resumable output).
68
+
69
+ Model: https://huggingface.co/baidu/Unlimited-OCR-2 (3.3B, MIT)
70
+ """
71
+
72
+ import argparse
73
+ import base64
74
+ import collections
75
+ import io
76
+ import json
77
+ import os
78
+ import re
79
+ import shutil
80
+ import subprocess
81
+ import sys
82
+ import threading
83
+ import time
84
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
85
+
86
+ # The model card's launch settings. The image is the SGLang release whose pins
87
+ # match Baidu's wheel (torch 2.13.0, transformers 5.12.1); move both together.
88
+ SERVING = {
89
+ "model": "baidu/Unlimited-OCR-2",
90
+ "served_name": "Unlimited-OCR-2",
91
+ "wheel": "https://huggingface.co/baidu/Unlimited-OCR-2/resolve/main/wheel/"
92
+ "sglang-0.5.20.dev10%2Bg8d62f5fb9c-py3-none-any.whl",
93
+ "extra_pip": ["fastokens==0.3.2"],
94
+ "env": {
95
+ "SGLANG_UOCR_EANABLE_DOC_LIMIT": "1", # (sic) upstream spelling
96
+ "SGLANG_UOCR_DOC_GUNDAM_PAGE_WINDOW": "10",
97
+ "SGLANG_UOCR_DOC_BASE_PAGE_WINDOW": "10",
98
+ # Per-page output cap. A normal book page is ~2,000 characters (p99 ~6,700); the
99
+ # tokens past 8000 on a page are repetition loops, which held whole runs' tails.
100
+ "SGLANG_UOCR_MAX_PAGE_TOKENS": "8000",
101
+ "SGLANG_OPT_UOCR_SAM_REL_POS_BIAS_MB": "64",
102
+ "SGLANG_UOCR_SHM_WRAP_MODEL_DATA": "1",
103
+ "SGLANG_UOCR_SHM_WRAP_MIN_MB": "1",
104
+ "SGLANG_VLM_CACHE_SIZE_MB": "0",
105
+ "PYTORCH_CUDA_ALLOC_CONF": "expandable_segments:True",
106
+ },
107
+ "serve_args": [
108
+ "--chat-template", "unlimited-ocr",
109
+ "--tokenizer-backend", "fastokens", "--tokenizer-worker-num", "8",
110
+ "--mem-fraction-static", "0.7",
111
+ "--max-running-requests", "64",
112
+ "--max-prefill-tokens", "2048",
113
+ "--enable-custom-logit-processor", "--enable-streaming-session",
114
+ "--allow-auto-truncate", "--disable-radix-cache",
115
+ "--mm-preprocess-cache-size-mb", "0",
116
+ "--cuda-graph-backend-decode", "full", "--cuda-graph-max-bs-decode", "64",
117
+ "--cuda-graph-backend-prefill", "full",
118
+ "--cuda-graph-max-bs-prefill", "16384",
119
+ "--cuda-graph-bs-prefill", "1024", "2048",
120
+ "--cuda-graph-config", '{"prefill": {"backend": "full", "full_prefill_max_req": 64}}',
121
+ ],
122
+ }
123
+
124
+ # The card's no-repeat n-gram guard: DeepseekOCRNoRepeatNGramLogitProcessor.to_str(),
125
+ # i.e. json({"callable": dill.dumps(cls).hex()}). dill pickles an importable class
126
+ # by reference (module + name), so this is a fixed string and needs no sglang here.
127
+ NGRAM_PROCESSOR = json.dumps({"callable": (
128
+ "80059559000000000000008c2a73676c616e672e7372742e73616d706c696e672e637573746f6d5f6c6f6769"
129
+ "745f70726f636573736f72948c26446565707365656b4f43524e6f5265706561744e4772616d4c6f67697450"
130
+ "726f636573736f729493942e")})
131
+
132
+ PAGE_EXTS = (".jp2", ".jpg", ".jpeg", ".png", ".tif", ".tiff", ".webp")
133
+ FURNITURE = {"page_number", "header", "footer"}
134
+ BLOCK_RE = re.compile(r"<BLOCK>(?P<type>[a-z_]+)(?:<LEVEL(?P<level>\d)>)?\[[\d, ]*\]<FORK>")
135
+
136
+
137
+ def natural_key(s: str):
138
+ return [int(t) if t.isdigit() else t for t in re.split(r"(\d+)", s)]
139
+
140
+
141
+ def doc_key(rel_path: str) -> str:
142
+ """`item/Volume 1, A-B_0007.jp2` -> `item/Volume 1, A-B`; bare `0007.jp2` -> `.`."""
143
+ stem = rel_path.rsplit(".", 1)[0]
144
+ doc = re.sub(r"[_\-. ]?\d+$", "", stem)
145
+ return doc if doc and not doc.endswith("/") else (doc or ".")
146
+
147
+
148
+ def list_windows(pattern: str, pages_per_request: int, max_pages):
149
+ """List page files, group them into documents, cut each into windows -> (id, row)."""
150
+ from saturate import bucket_rows
151
+
152
+ if not re.search(r"[*?\[]", pattern):
153
+ pattern = pattern.rstrip("/") + "/**"
154
+ docs: dict[str, list[tuple[str, str]]] = {}
155
+ for rid, row in bucket_rows(pattern, read=False):
156
+ if rid.lower().endswith(PAGE_EXTS):
157
+ docs.setdefault(doc_key(rid), []).append((rid, row["path"]))
158
+ if not docs:
159
+ sys.exit(f"no page images matched {pattern!r}")
160
+
161
+ n_pages = 0
162
+ for doc in sorted(docs, key=natural_key):
163
+ pages = sorted(docs[doc], key=lambda p: natural_key(p[0]))
164
+ for start in range(0, len(pages), pages_per_request):
165
+ if max_pages is not None and n_pages >= max_pages:
166
+ return
167
+ window = pages[start: start + pages_per_request]
168
+ if max_pages is not None:
169
+ window = window[: max_pages - n_pages]
170
+ n_pages += len(window)
171
+ # The id encodes the page range, so a --max-pages-truncated window is not
172
+ # mistaken for the full window when a later run resumes.
173
+ yield f"{doc}@{start:06d}-{start + len(window):06d}", {
174
+ "doc_id": doc, "first_page": start,
175
+ "page_files": [rid for rid, _ in window],
176
+ "paths": [p for _, p in window],
177
+ }
178
+
179
+
180
+ def load_page(fs, path: str, max_side: int, live=None) -> str:
181
+ """Read one page image, downscale it, return base64 JPEG (and give the live view a thumbnail)."""
182
+ from PIL import Image
183
+
184
+ with fs.open(path, "rb") as f:
185
+ data = f.read()
186
+ img = Image.open(io.BytesIO(data))
187
+ if img.format == "JPEG2000":
188
+ # Decode straight at a lower wavelet level while the page stays >= max_side: the
189
+ # same pixels after downscaling, for a fraction of the CPU. Some codestreams fail
190
+ # at a reduced level, so step back towards a full decode until one works.
191
+ reduce = 0
192
+ while max(img.size) >> (reduce + 1) >= max_side:
193
+ reduce += 1
194
+ while True:
195
+ try:
196
+ img = Image.open(io.BytesIO(data))
197
+ img.reduce = reduce
198
+ img.load()
199
+ break
200
+ except OSError:
201
+ if reduce == 0:
202
+ raise
203
+ reduce -= 1
204
+ else:
205
+ img.load()
206
+ img = img.convert("RGB")
207
+ img.thumbnail((max_side, max_side), Image.LANCZOS)
208
+ if live is not None:
209
+ live.add_thumbnail(path, img)
210
+ buf = io.BytesIO()
211
+ img.save(buf, format="JPEG", quality=90)
212
+ b64 = base64.b64encode(buf.getvalue()).decode()
213
+ if live is not None:
214
+ live.offer(path, b64)
215
+ return b64
216
+
217
+
218
+ def page_request(images_b64: list[str], stream: bool = False) -> dict:
219
+ """The chat request for consecutive pages, with the model card's sampling and guard settings."""
220
+ n = len(images_b64)
221
+ content = [{"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{b64}"}} for b64 in images_b64]
222
+ content.append({"type": "text", "text": "<PAGE><image>" * n + "Multi page parsing."})
223
+ return {
224
+ "model": SERVING["served_name"],
225
+ "messages": [{"role": "user", "content": content}],
226
+ "max_tokens": 8000 * n, # output budget for the whole window
227
+ "temperature": 0,
228
+ "skip_special_tokens": False, # <PAGE>/<BLOCK> markers are the structure
229
+ "images_config": {"crop_mode": False}, # base mode: one 1024 px view per page
230
+ "custom_logit_processor": NGRAM_PROCESSOR,
231
+ "custom_params": {
232
+ "ngram_size": 35, "window_size": 1024 if n > 1 else 128,
233
+ "page_token_id": 128827, "eos_token_id": 1, "max_page_tokens": 8000,
234
+ },
235
+ "stream": stream,
236
+ }
237
+
238
+
239
+ LIVE_PAGE = """<!doctype html><meta charset="utf-8"><title>Unlimited-OCR-2 live</title>
240
+ <meta name="viewport" content="width=device-width, initial-scale=1">
241
+ <style>
242
+ :root{--bg:#f4f2ee;--fg:#1c1c1e;--muted:#66645f;--card:#fff;--line:#dfdcd5;--accent:#d9622b;--ok:#2f7d5b}
243
+ @media (prefers-color-scheme:dark){:root{--bg:#101113;--fg:#ececef;--muted:#9096a0;--card:#191b1f;--line:#2b2e34;--accent:#ff8a3d;--ok:#5cc29a}}
244
+ *{box-sizing:border-box}
245
+ body{margin:0;background:var(--bg);color:var(--fg);font:16px/1.45 system-ui,sans-serif;height:100vh;
246
+ display:grid;grid-template-rows:auto auto minmax(0,1fr) auto;overflow:hidden}
247
+ header{display:flex;align-items:center;gap:14px;padding:14px 20px 6px;min-width:0}
248
+ h1{font-size:20px;margin:0;font-weight:650;white-space:nowrap}
249
+ #banner{font-size:14px;padding:3px 10px;border-radius:4px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;min-width:0}
250
+ #banner.done{background:var(--ok);color:#fff}#banner.stop{background:var(--accent);color:#fff}
251
+ .label{font-size:13px;letter-spacing:.06em;text-transform:uppercase;color:var(--muted)}
252
+ #flight{display:flex;align-items:center;gap:12px;padding:6px 20px 10px;border-bottom:1px solid var(--line);min-height:80px;min-width:0}
253
+ #flightThumbs{display:flex;gap:6px;overflow:hidden;flex:1;min-width:0}
254
+ #flightThumbs img{width:46px;aspect-ratio:3/4;object-fit:cover;background:var(--line);border:1px solid var(--line);opacity:.55;animation:pulse 1.6s ease-in-out infinite}
255
+ @keyframes pulse{50%{opacity:.95}}
256
+ #middle{display:grid;grid-template-columns:minmax(0,1fr) 300px;min-height:0}
257
+ #spot{display:grid;grid-template-columns:minmax(0,45%) minmax(0,1fr);gap:24px;padding:16px 20px;min-height:0}
258
+ #spotImg{max-width:100%;max-height:100%;object-fit:contain;justify-self:center;border:1px solid var(--line);background:var(--card)}
259
+ #spotRight{display:flex;flex-direction:column;min-height:0;min-width:0}
260
+ #spotMeta{font-size:14px;color:var(--muted);margin-bottom:8px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
261
+ #spotMeta.live::before{content:"● ";color:var(--accent);animation:blink 1s steps(1) infinite}
262
+ #spotText{flex:1;overflow:hidden;white-space:pre-wrap;font:19px/1.55 Georgia,serif;max-width:62ch;
263
+ -webkit-mask-image:linear-gradient(transparent,#000 12%);mask-image:linear-gradient(transparent,#000 12%)}
264
+ .fade{animation:fade .5s ease-out}@keyframes fade{from{opacity:0}}
265
+ #wait{grid-column:1/-1;display:flex;flex-direction:column;gap:16px;min-height:0;min-width:0}
266
+ #steps{font-size:17px;color:var(--muted);display:flex;flex-wrap:wrap;gap:6px 22px}
267
+ #steps .now{color:var(--fg);font-weight:600}#steps .now::before{content:"● ";color:var(--accent);animation:blink 1s steps(1) infinite}
268
+ #steps .past::before{content:"✓ ";color:var(--ok)}#steps b{font-weight:inherit;font-variant-numeric:tabular-nums;margin-left:6px}
269
+ @keyframes blink{50%{opacity:0}}
270
+ #prep{display:flex;flex-wrap:wrap;gap:10px;overflow:hidden;align-content:flex-start;min-height:0}
271
+ #prep img{height:190px;aspect-ratio:3/4;object-fit:cover;background:var(--line);border:1px solid var(--line);animation:pulse 1.6s ease-in-out infinite}
272
+ aside{border-left:1px solid var(--line);padding:16px 20px;display:flex;flex-direction:column;gap:16px;min-width:0}
273
+ .big{font-size:52px;font-weight:650;font-variant-numeric:tabular-nums;line-height:1.05}
274
+ .mid{font-size:26px;font-weight:600;font-variant-numeric:tabular-nums}
275
+ .bar{height:8px;background:var(--line);border-radius:4px;margin-top:6px}.bar div{height:8px;background:var(--accent);border-radius:4px;width:0;transition:width .8s}
276
+ #spark{width:100%;height:44px;display:block}.bad{color:var(--accent)}
277
+ #strip{display:flex;gap:8px;padding:10px 20px 14px;border-top:1px solid var(--line);overflow:hidden;height:150px}
278
+ #strip figure{margin:0;flex:none;animation:enter .6s ease-out}
279
+ #strip img{width:80px;aspect-ratio:3/4;object-fit:cover;background:var(--line);border:1px solid var(--line);display:block}
280
+ #strip figcaption{font-size:13px;color:var(--muted);text-align:center;width:80px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
281
+ @keyframes enter{from{opacity:0;transform:translateX(-30px)}}
282
+ @media (max-width:800px){body{overflow:auto;height:auto;display:block}#middle,#spot{grid-template-columns:minmax(0,1fr)}
283
+ aside>div{min-width:0}
284
+ aside{order:-1;border-left:0;display:grid;grid-template-columns:1fr 1fr}#spotImg{max-height:40vh}#strip{height:auto}
285
+ #prep img{height:120px}.big{font-size:40px}}
286
+ </style>
287
+ <header><h1>Unlimited-OCR-2 · live</h1><span id="banner"></span></header>
288
+ <section id="flight"><span class="label">Ready for the model<br><span id="flightN" class="mid">0</span></span><div id="flightThumbs"></div></section>
289
+ <section id="middle">
290
+ <div id="spot"><div id="wait"><div id="steps"></div><div id="prep"></div></div></div>
291
+ <aside>
292
+ <div><div class="label">Pages per minute</div><div class="big" id="rate">–</div>
293
+ <svg id="spark" viewBox="0 0 100 40" preserveAspectRatio="none"></svg></div>
294
+ <div><div class="label">Pages read</div><div class="mid" id="done">0</div><div class="label" id="of"></div>
295
+ <div class="bar"><div id="bar"></div></div></div>
296
+ <div><div class="label">GPU load</div><div class="mid" id="gpu">–</div><div class="bar"><div id="gpuBar"></div></div></div>
297
+ <div><div class="label">Words extracted</div><div class="mid" id="words">0</div></div>
298
+ <div><div class="label">Reading for</div><div class="mid" id="elapsed">0:00</div></div>
299
+ <div id="failedBox" hidden><div class="label">Needs a retry</div><div class="mid bad" id="failed">0</div></div>
300
+ </aside>
301
+ </section>
302
+ <section id="strip"></section>
303
+ <script>
304
+ const $ = id => document.getElementById(id), fmt = n => n.toLocaleString();
305
+ const clock = s => { s = Number.isFinite(s) ? Math.max(0, Math.round(s)) : 0;
306
+ return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`; };
307
+ let since = 0, last = null, misses = 0, newest = null, shown = null, spotReady = false;
308
+ const flight = new Map();
309
+
310
+ function showWaiting(s) {
311
+ const steps = $("steps"); steps.replaceChildren();
312
+ s.phases.forEach((p, i) => {
313
+ const now = i === s.phases.length - 1, el = document.createElement("span"), t = document.createElement("b");
314
+ el.className = now ? "now" : "past"; el.textContent = p.name;
315
+ t.textContent = clock((now ? s.uptime_s : s.phases[i + 1].at_s) - p.at_s); el.append(t); steps.append(el);
316
+ });
317
+ }
318
+
319
+ function buildSpot() {
320
+ $("spot").innerHTML = '<img id="spotImg" alt=""><div id="spotRight"><div id="spotMeta"></div><div id="spotText"></div></div>';
321
+ spotReady = true;
322
+ }
323
+
324
+ function ingest(d) {
325
+ const s = d.stats; last = s;
326
+ if (!spotReady && d.pages.length) buildSpot();
327
+ if (!spotReady) showWaiting(s);
328
+ $("rate").textContent = s.rate_ppm ? s.rate_ppm.toFixed(0) : "–";
329
+ $("done").textContent = fmt(s.pages_done);
330
+ $("of").textContent = `of ${fmt(s.pages_total)}`;
331
+ $("bar").style.width = (100 * s.pages_done / Math.max(1, s.pages_total)) + "%";
332
+ $("elapsed").textContent = clock(s.reading_s);
333
+ $("words").textContent = fmt(s.words);
334
+ $("failed").textContent = fmt(s.pages_failed); $("failedBox").hidden = !s.pages_failed;
335
+ if (s.gpu) { $("gpu").textContent = `${s.gpu.util}%`; $("gpuBar").style.width = s.gpu.util + "%"; }
336
+ drawSpark(s.spark);
337
+ $("flightN").textContent = fmt(s.in_flight);
338
+ const keep = new Set(d.in_flight);
339
+ for (const [k, imgs] of flight) if (!keep.has(k)) { imgs.forEach(i => i.remove()); flight.delete(k); }
340
+ for (const k of d.in_flight) if (!flight.has(k)) {
341
+ const a = new Image(); a.src = "img/" + k; $("flightThumbs").append(a);
342
+ const imgs = [a];
343
+ if (!spotReady) { const b = new Image(); b.src = "img/" + k; $("prep").append(b); imgs.push(b); }
344
+ flight.set(k, imgs);
345
+ }
346
+ // Every finished page goes on the strip, so its motion is the real throughput.
347
+ // A late open or reload starts from the latest window, not the whole history.
348
+ const fresh = since === 0 ? d.pages.slice(-16) : d.pages;
349
+ for (const p of d.pages) since = Math.max(since, p.seq);
350
+ for (const p of fresh) addToStrip(p);
351
+ // Spotlight the newest page that has text; blank leaves and plates only when nothing else came back.
352
+ const withText = fresh.filter(p => (p.text || "").length > 200);
353
+ if (fresh.length) newest = (withText.length ? withText : fresh).at(-1);
354
+ if (s.pages_total && s.pages_done >= s.pages_total) banner("done", `Finished · ${fmt(s.pages_done)} pages in ${clock(s.reading_s)}`);
355
+ else banner("", s.phase);
356
+ }
357
+
358
+ function banner(cls, text) { $("banner").className = cls; $("banner").textContent = text; }
359
+
360
+ function drawSpark(v) {
361
+ if (!v || v.length < 2 || Math.max(...v) === 0) { $("spark").innerHTML = ""; return; }
362
+ const max = Math.max(...v);
363
+ const path = v.map((y, i) => `${i ? "L" : "M"}${(i / (v.length - 1) * 100).toFixed(1)},${(38 - y / max * 34).toFixed(1)}`).join("");
364
+ $("spark").innerHTML = `<path d="${path}" fill="none" stroke="var(--accent)" stroke-width="2" vector-effect="non-scaling-stroke"/>`;
365
+ }
366
+
367
+ function addToStrip(p) {
368
+ const f = document.createElement("figure"), i = new Image(), c = document.createElement("figcaption");
369
+ i.src = "img/" + p.img; c.textContent = "p. " + p.page + (p.status === "ok" ? "" : " · retry");
370
+ f.title = p.doc; f.append(i, c); $("strip").prepend(f);
371
+ while ($("strip").children.length > 40) $("strip").lastChild.remove();
372
+ }
373
+
374
+ // Spotlight: the page the model is reading right now, its text arriving token by token (one
375
+ // streaming request beside the batch). Between live pages: the newest finished page.
376
+ let live = null, liveImg = "";
377
+ async function pollStream() {
378
+ try {
379
+ live = await (await fetch("stream.json")).json();
380
+ if (live && !spotReady) buildSpot();
381
+ if (live && spotReady) {
382
+ if (live.img && live.img !== liveImg) { liveImg = live.img; $("spotImg").src = "img/" + live.img; }
383
+ $("spotMeta").className = live.done ? "" : "live";
384
+ $("spotMeta").textContent = (live.done ? "Just read · " : `Reading now · ${live.tok_s} tokens/s · `) + `${live.doc} · page ${live.page}`;
385
+ const el = $("spotText");
386
+ el.textContent = live.text.replace(/^#+ /gm, "") || "…";
387
+ el.scrollTop = el.scrollHeight;
388
+ }
389
+ } catch (e) {}
390
+ setTimeout(pollStream, live && !live.done ? 250 : 1000);
391
+ }
392
+
393
+ function spotlight() {
394
+ if (spotReady && !live && newest && newest !== shown) {
395
+ const p = newest; shown = p;
396
+ $("spotImg").src = "img/" + p.img;
397
+ $("spotMeta").textContent = `${p.doc} · page ${p.page}` + (p.status === "ok" ? "" : ` · ${p.status}`);
398
+ $("spotMeta").className = p.status === "ok" ? "" : "bad";
399
+ const el = $("spotText");
400
+ el.textContent = (p.text || "(no text on this page)").replace(/^#+ /gm, "").slice(0, 1500);
401
+ el.classList.remove("fade"); void el.offsetWidth; el.classList.add("fade");
402
+ }
403
+ setTimeout(spotlight, 2500);
404
+ }
405
+
406
+ async function poll() {
407
+ try {
408
+ ingest(await (await fetch("feed.json?since=" + since)).json()); misses = 0;
409
+ } catch (e) {
410
+ misses += 1;
411
+ if (misses >= 3 && last) {
412
+ if (last.pages_total && last.pages_done >= last.pages_total) banner("done", `Finished · ${fmt(last.pages_done)} pages in ${clock(last.reading_s)} · the Job has exited`);
413
+ else banner("stop", "Job stopped · check the Job logs");
414
+ }
415
+ }
416
+ setTimeout(poll, 2000);
417
+ }
418
+ poll(); spotlight(); pollStream();
419
+ </script>"""
420
+
421
+
422
+ class LiveView:
423
+ """The last pages read, served as a web page from inside the Job (`--live-port`)."""
424
+
425
+ def __init__(self, port: int, pages_total: int, names: dict, keep: int = 300, stale_s: float = 3600):
426
+ self.pages = collections.deque(maxlen=keep)
427
+ self.images: dict[str, bytes] = {} # key -> JPEG, for in-flight and kept pages
428
+ self.in_flight: dict[str, tuple[str, float]] = {} # page path -> (image key, time loaded)
429
+ self.stale_s = stale_s # a window not back after this long was given up on
430
+ self.lock = threading.Lock()
431
+ self.seq = 0
432
+ self.pages_total, self.pages_done, self.pages_failed, self.words = pages_total, 0, 0, 0
433
+ self.booted = time.time()
434
+ self.started = None # first page loaded: the rate and elapsed time leave out server start-up
435
+ self.phases = []
436
+ self.recent = collections.deque() # (time, pages) of finished windows, for the rolling rate
437
+ self.spark = collections.deque(maxlen=30) # pages per minute in 60 s buckets
438
+ self.gpu = None
439
+ self.names = names # page path -> (document, page number)
440
+ self.offered = None # (path, base64 JPEG) of the newest prepared page
441
+ self.stream = None # the page being read live, token by token
442
+ live = self
443
+
444
+ class Handler(BaseHTTPRequestHandler):
445
+ def do_GET(self):
446
+ try:
447
+ if self.path.startswith("/stream.json"):
448
+ with live.lock:
449
+ body = json.dumps(live.stream)
450
+ self.reply(body.encode(), "application/json")
451
+ elif self.path.startswith("/feed.json"):
452
+ try:
453
+ since = int(self.path.partition("since=")[2] or 0)
454
+ except ValueError:
455
+ since = 0
456
+ self.reply(json.dumps(live.feed(since)).encode(), "application/json")
457
+ elif self.path.startswith("/img/"):
458
+ with live.lock:
459
+ jpeg = live.images.get(self.path[len("/img/"):])
460
+ if jpeg is None:
461
+ self.send_error(404)
462
+ else:
463
+ self.reply(jpeg, "image/jpeg", cache="max-age=86400")
464
+ else:
465
+ self.reply(LIVE_PAGE.encode(), "text/html; charset=utf-8")
466
+ except (BrokenPipeError, ConnectionResetError):
467
+ pass # the viewer closed the tab mid-reply
468
+
469
+ def reply(self, body: bytes, ctype: str, cache: str = "no-store"):
470
+ self.send_response(200)
471
+ self.send_header("Content-Type", ctype)
472
+ self.send_header("Cache-Control", cache)
473
+ self.end_headers()
474
+ self.wfile.write(body)
475
+
476
+ def log_message(self, *args): # keep the Job log for the OCR run
477
+ pass
478
+
479
+ server = ThreadingHTTPServer(("0.0.0.0", port), Handler)
480
+ threading.Thread(target=server.serve_forever, daemon=True).start()
481
+ threading.Thread(target=self.tick, daemon=True).start()
482
+ # An exposed Job port is served at https://<job id>--<port>.hf.jobs.
483
+ where = (f"https://{os.environ['JOB_ID']}--{port}.hf.jobs (needs --expose-public {port})"
484
+ if os.environ.get("JOB_ID") else f"http://localhost:{port}")
485
+ print(f"Live view: {where}", file=sys.stderr, flush=True)
486
+
487
+ def offer(self, path: str, b64: str):
488
+ with self.lock:
489
+ self.offered = (path, b64)
490
+
491
+ def start_streaming(self, url: str):
492
+ """Read one page at a time with streaming on, so the page can show the model's text as it is produced.
493
+
494
+ This is one extra single-page request beside the batch (a few percent of the GPU); its
495
+ output is only shown, never written.
496
+ """
497
+ threading.Thread(target=self._stream_loop, args=(url,), daemon=True).start()
498
+
499
+ def _stream_loop(self, url: str):
500
+ import urllib.request
501
+
502
+ while True:
503
+ with self.lock:
504
+ offered, self.offered = self.offered, None
505
+ key = self.in_flight.get(offered[0], ("",))[0] if offered else ""
506
+ if not offered:
507
+ time.sleep(0.5)
508
+ continue
509
+ path, b64 = offered
510
+ doc, page = self.names.get(path, ("", 0))
511
+ raw, tokens, t0 = "", 0, time.time()
512
+ with self.lock:
513
+ self.stream = {"img": key, "doc": doc, "page": page, "text": "", "tok_s": 0, "done": False}
514
+ try:
515
+ req = urllib.request.Request(f"{url}/v1/chat/completions",
516
+ data=json.dumps(page_request([b64], stream=True)).encode(),
517
+ headers={"Content-Type": "application/json"})
518
+ with urllib.request.urlopen(req, timeout=600) as resp:
519
+ for line in resp:
520
+ line = line.decode("utf-8", "replace").strip()
521
+ if not line.startswith("data: ") or line == "data: [DONE]":
522
+ continue
523
+ delta = (json.loads(line[6:])["choices"][0].get("delta") or {}).get("content") or ""
524
+ raw += delta
525
+ tokens += 1
526
+ text = clean_page(raw.split("<PAGE>")[-1], keep_furniture=False)
527
+ with self.lock:
528
+ self.stream.update(text=text[-1500:], tok_s=round(tokens / max(0.1, time.time() - t0)))
529
+ except (OSError, ValueError, KeyError, IndexError) as e: # the live view must never affect the run
530
+ print(f"Live view stream: {type(e).__name__}: {e}", file=sys.stderr)
531
+ time.sleep(5)
532
+ with self.lock:
533
+ self.stream["done"] = True
534
+ time.sleep(3) # leave the finished page on screen for a moment
535
+
536
+ def phase(self, name: str):
537
+ with self.lock:
538
+ self.phases.append({"name": name, "at_s": round(time.time() - self.booted)})
539
+
540
+ def tick(self):
541
+ """Every few seconds: GPU memory and load (so start-up visibly moves), and the sparkline."""
542
+ last_bucket, done_then = time.time(), 0
543
+ while True:
544
+ try:
545
+ out = subprocess.run(["nvidia-smi", "--query-gpu=utilization.gpu,memory.used,memory.total",
546
+ "--format=csv,noheader,nounits"], capture_output=True, text=True,
547
+ timeout=10, check=True).stdout.splitlines()[0]
548
+ util, used, total = (float(x) for x in out.split(","))
549
+ gpu = {"util": round(util), "mem_used_gb": used / 1024, "mem_total_gb": total / 1024}
550
+ except (OSError, subprocess.SubprocessError, ValueError, IndexError):
551
+ gpu = None
552
+ with self.lock:
553
+ self.gpu = gpu
554
+ if self.started and time.time() - last_bucket >= 60:
555
+ self.spark.append(round((self.pages_done - done_then) * 60 / (time.time() - last_bucket), 1))
556
+ last_bucket, done_then = time.time(), self.pages_done
557
+ time.sleep(3)
558
+
559
+ def add_thumbnail(self, path: str, img):
560
+ thumb = img.copy()
561
+ thumb.thumbnail((600, 600))
562
+ buf = io.BytesIO()
563
+ thumb.save(buf, format="JPEG", quality=80)
564
+ with self.lock:
565
+ if self.started is None:
566
+ self.started = time.time()
567
+ self.phases.append({"name": "Reading pages", "at_s": round(self.started - self.booted)})
568
+ self.seq += 1
569
+ key = f"{self.seq}.jpg"
570
+ self.images[key] = buf.getvalue()
571
+ old = self.in_flight.get(path)
572
+ if old: # prepared again for a retry: drop the earlier copy
573
+ self.images.pop(old[0], None)
574
+ self.in_flight[path] = (key, time.time())
575
+
576
+ def add_window(self, row: dict, status: str, texts):
577
+ now = time.time()
578
+ with self.lock:
579
+ self.pages_done += len(row["paths"])
580
+ self.recent.append((now, len(row["paths"])))
581
+ for i, (path, rid) in enumerate(zip(row["paths"], row["page_files"], strict=True)):
582
+ text = texts[i] if texts and i < len(texts) else ""
583
+ self.words += len(text.split())
584
+ self.pages_failed += status != "ok"
585
+ if len(self.pages) == self.pages.maxlen: # the oldest kept page leaves: drop its image
586
+ self.images.pop(self.pages[0]["img"], None)
587
+ self.seq += 1
588
+ key, _ = self.in_flight.pop(path, ("", now))
589
+ self.pages.append({"seq": self.seq, "doc": row["doc_id"].rsplit("/", 1)[-1],
590
+ "page": row["first_page"] + i + 1, "file": rid, "status": status,
591
+ "text": text[:4000], "img": key})
592
+
593
+ def feed(self, since: int) -> dict:
594
+ now = time.time()
595
+ with self.lock:
596
+ for path, (key, t) in list(self.in_flight.items()):
597
+ if now - t > self.stale_s: # never came back: stop showing it as being read
598
+ del self.in_flight[path]
599
+ self.images.pop(key, None)
600
+ while self.recent and now - self.recent[0][0] > 300:
601
+ self.recent.popleft()
602
+ span = min(300, now - self.started) if self.started else 0
603
+ rate = sum(n for _, n in self.recent) * 60 / span if span >= 20 else 0
604
+ return {"stats": {"phase": self.phases[-1]["name"] if self.phases else "Starting",
605
+ "phases": self.phases,
606
+ "uptime_s": round(now - self.booted),
607
+ "reading_s": round(now - self.started) if self.started else 0,
608
+ "pages_total": self.pages_total, "pages_done": self.pages_done,
609
+ "pages_failed": self.pages_failed, "words": self.words,
610
+ "in_flight": len(self.in_flight), "rate_ppm": round(rate, 1),
611
+ "spark": list(self.spark), "gpu": self.gpu},
612
+ "in_flight": [key for key, _ in self.in_flight.values()][-24:],
613
+ "pages": [p for p in self.pages if p["seq"] > since]}
614
+
615
+
616
+ def clean_page(raw_page: str, keep_furniture: bool) -> str:
617
+ """One page of model output -> plain markdown.
618
+
619
+ Drops block tags and boxes, turns titles into `#` headings, drops page
620
+ numbers and running heads, and joins `<MERGE>`d blocks (e.g. verse lines).
621
+ """
622
+ blocks: list[str] = []
623
+ merge_next = False
624
+ matches = list(BLOCK_RE.finditer(raw_page))
625
+ for i, m in enumerate(matches):
626
+ end = matches[i + 1].start() if i + 1 < len(matches) else len(raw_page)
627
+ body = raw_page[m.end(): end].strip()
628
+ merge_prev, merge_next = merge_next, body.endswith("<MERGE>")
629
+ body = body.removesuffix("<MERGE>").strip()
630
+ kind = m.group("type")
631
+ if not body or (kind in FURNITURE and not keep_furniture):
632
+ continue
633
+ if kind == "title" and m.group("level"):
634
+ body = "#" * int(m.group("level")) + " " + body
635
+ if merge_prev and blocks:
636
+ blocks[-1] += "\n" + body
637
+ else:
638
+ blocks.append(body)
639
+ return "\n\n".join(blocks)
640
+
641
+
642
+ def prepare_workers() -> int:
643
+ """Threads that decode and encode pages: enough to keep ~40 requests fed, within the Job's CPU quota.
644
+
645
+ os.cpu_count() reports the host's cores (190 on a Jobs node), not the quota; that many
646
+ threads starve the loop that sends requests. Jobs sets CPU_CORES to the quota.
647
+ """
648
+ cores = int(os.environ.get("CPU_CORES") or len(os.sched_getaffinity(0)))
649
+ return max(4, min(16, cores - 6)) # leave cores for SGLang's tokenizer and scheduler
650
+
651
+
652
+ def start_server_cmd() -> list[str]:
653
+ """Install Baidu's wheel into the image's sglang Python and return the server command."""
654
+ # The SGLang image keeps sglang in its own venv (/opt/sglang/bin), first on PATH;
655
+ # `uv run` puts this script's venv in front, so look past it.
656
+ own_bin = os.path.realpath(os.path.join(sys.prefix, "bin"))
657
+ path = os.pathsep.join(p for p in os.environ.get("PATH", "").split(os.pathsep)
658
+ if os.path.realpath(p) != own_bin)
659
+ py = shutil.which("python3", path=path)
660
+ if not py or subprocess.run([py, "-c", "import sglang"], check=False,
661
+ capture_output=True).returncode != 0:
662
+ sys.exit("No Python with sglang found: run this on the lmsysorg/sglang image "
663
+ "(`hf jobs uv run` picks it up from the script's [tool.hf-jobs] table).")
664
+ env = {k: v for k, v in os.environ.items() if k != "VIRTUAL_ENV"}
665
+ pip = ["uv", "pip", "install", "-q", "--python", py]
666
+ subprocess.run([*pip, "--no-deps", SERVING["wheel"]], check=True, env=env)
667
+ subprocess.run([*pip, *SERVING["extra_pip"]], check=True, env=env)
668
+ os.environ.update(SERVING["env"]) # inherited by the server process
669
+ return [py, "-m", "sglang.launch_server", "--model-path", SERVING["model"],
670
+ "--served-model-name", SERVING["served_name"], *SERVING["serve_args"],
671
+ "--enable-metrics", "--host", "127.0.0.1", "--port", "8000"]
672
+
673
+
674
+ def main():
675
+ ap = argparse.ArgumentParser(description="Unlimited-OCR-2 document OCR on HF Jobs")
676
+ ap.add_argument("input", help="Glob or folder of page images: hf://buckets/..., a mounted dir, ...")
677
+ ap.add_argument("output", help="Output dataset id (org/name) or fsspec URI (hf://buckets/...)")
678
+ ap.add_argument("--pages-per-request", type=int, default=16,
679
+ help="Consecutive pages per request (default 16)")
680
+ ap.add_argument("--max-pages", type=int, default=None, help="Stop after N pages (for a test run)")
681
+ ap.add_argument("--max-side", type=int, default=1280,
682
+ help="Long side (px) pages are sent at. The model resizes each page to a "
683
+ "1024 px view, so more pixels only make the requests bigger")
684
+ ap.add_argument("--keep-furniture", action="store_true",
685
+ help="Keep page numbers and running heads in page_markdown")
686
+ ap.add_argument("--retry-errors", action="store_true", help="Retry windows recorded as errors")
687
+ ap.add_argument("--live-port", type=int, default=None,
688
+ help="Serve a live view of pages as they are read on this port "
689
+ "(on Jobs, also pass --expose-public with the same port)")
690
+ args = ap.parse_args()
691
+
692
+ import fsspec
693
+ import saturate.transport
694
+ from saturate import Auto, Engine, pump
695
+
696
+ rows = list(list_windows(args.input, args.pages_per_request, args.max_pages))
697
+ print(f"{len({r['doc_id'] for _, r in rows})} documents, "
698
+ f"{sum(len(r['paths']) for _, r in rows)} pages, {len(rows)} requests", file=sys.stderr)
699
+ fs = fsspec.core.url_to_fs(args.input.split("*")[0] or ".")[0]
700
+ live = None
701
+ if args.live_port:
702
+ names = {p: (r["doc_id"].rsplit("/", 1)[-1], r["first_page"] + i + 1)
703
+ for _, r in rows for i, p in enumerate(r["paths"])}
704
+ live = LiveView(args.live_port, sum(len(r["paths"]) for _, r in rows), names)
705
+
706
+ def to_request(row):
707
+ return page_request([load_page(fs, p, args.max_side, live) for p in row["paths"]])
708
+
709
+ def parse(row, body):
710
+ choice = body["choices"][0]
711
+ raw = choice["message"]["content"]
712
+ raw_pages = raw.split("<PAGE>")[1:]
713
+ if choice.get("finish_reason") == "length":
714
+ status = "truncated"
715
+ elif len(raw_pages) != len(row["paths"]):
716
+ status = "page_mismatch"
717
+ else:
718
+ status = "ok"
719
+ usage = body.get("usage") or {}
720
+ page_markdown = [clean_page(p, args.keep_furniture) for p in raw_pages] if status == "ok" else None
721
+ if live is not None:
722
+ live.add_window(row, status, page_markdown)
723
+ return {
724
+ "doc_id": row["doc_id"],
725
+ "first_page": row["first_page"],
726
+ "page_files": row["page_files"],
727
+ "status": status,
728
+ "page_markdown": page_markdown,
729
+ "raw": raw,
730
+ "model": SERVING["model"],
731
+ "prompt_tokens": usage.get("prompt_tokens"),
732
+ "completion_tokens": usage.get("completion_tokens"),
733
+ }
734
+
735
+ is_repo_id = re.fullmatch(r"[\w-][\w.-]*/[\w.-]*[\w-]", args.output) and not os.path.exists(args.output)
736
+ output = f"hf://datasets/{args.output}/data" if is_repo_id else args.output
737
+
738
+ # One request is minutes of decoding. saturate 0.2.0 caps a request's retries at
739
+ # 300 s in total, which a retried 16-page request never fits in; match the read timeout.
740
+ saturate.transport.RETRY_BUDGET_S = 3600.0
741
+ if live is not None:
742
+ live.phase("Installing Baidu's SGLang build")
743
+ cmd = start_server_cmd()
744
+ if live is not None:
745
+ live.phase("Loading the model")
746
+ with Engine(SERVING["model"], engine="sglang", cmd=cmd) as endpoint:
747
+ if live is not None:
748
+ live.start_streaming("http://127.0.0.1:8000")
749
+ stats = pump(rows, to_request, parse, endpoint, output,
750
+ window=Auto(initial=32, max_limit=64), # long requests: start wide
751
+ flush_every=4, # each row is minutes of GPU time; write often
752
+ read_timeout=3600, prepare_workers=prepare_workers(), retry_errors=args.retry_errors)
753
+ print(f"{output}: {stats.rows_processed} windows written, {stats.rows_failed} errors", file=sys.stderr)
754
+ if live is not None:
755
+ live.phase("Finished")
756
+ time.sleep(60) # keep the final numbers on screen for a minute before the Job exits
757
+ print("UNLIMITED_OCR2 " + stats.to_json(), flush=True)
758
+
759
+
760
+ if __name__ == "__main__":
761
+ main()