Spaces:
Running on Zero
Running on Zero
The app starts without the private TrOCR weights (its lane says so) instead of stopping at startup
Browse files- app.py +24 -8
- race_view.css +8 -0
- race_view.js +4 -0
app.py
CHANGED
|
@@ -24,6 +24,7 @@ from uuid import uuid4
|
|
| 24 |
import gradio as gr
|
| 25 |
import torch
|
| 26 |
from huggingface_hub import snapshot_download
|
|
|
|
| 27 |
from PIL import Image
|
| 28 |
from pydantic import BaseModel, Field
|
| 29 |
from rapidfuzz.distance import Levenshtein
|
|
@@ -65,8 +66,16 @@ _eos = reader.generation_config.eos_token_id
|
|
| 65 |
EOS: set[int] = set(_eos) if isinstance(_eos, list) else {int(_eos)}
|
| 66 |
jev_processor = AutoProcessor.from_pretrained(JEV)
|
| 67 |
jev = Qwen3_5ForSequenceClassification.from_pretrained(JEV, num_labels=2, dtype=torch.bfloat16).to("cuda").eval()
|
| 68 |
-
|
| 69 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
|
| 71 |
_engines: dict[int, D.FastDSpark] = {} # per GPU worker process: CUDA graphs belong to the process that captured them
|
| 72 |
_lock = threading.Lock()
|
|
@@ -134,6 +143,7 @@ class Race(BaseModel):
|
|
| 134 |
outlines: list[list[tuple[float, float]]] = Field(default_factory=list)
|
| 135 |
shares: list[float] = Field(default_factory=list)
|
| 136 |
status: str = ""
|
|
|
|
| 137 |
done: bool = False
|
| 138 |
trocr: TrocrLane | None = None
|
| 139 |
plain: ReaderLane | None = None
|
|
@@ -189,13 +199,16 @@ def _trocr_read(lines: list[Image.Image], max_new_tokens: int = 128) -> TrocrLan
|
|
| 189 |
"""TrOCR's greedy readings of a batch of lines, timed from the images to the text, as Riksarkivet's evaluation
|
| 190 |
runs it: the Swedish Lion starts decoding from its config's token (its generation_config names another, which
|
| 191 |
costs about 2 points of CER), and its 192 x 1024 inputs need the position encoding interpolated."""
|
|
|
|
|
|
|
|
|
|
| 192 |
torch.cuda.synchronize()
|
| 193 |
started = time.perf_counter()
|
| 194 |
clock = StepClock()
|
| 195 |
-
pixels =
|
| 196 |
-
ids =
|
| 197 |
pixels,
|
| 198 |
-
decoder_start_token_id=
|
| 199 |
interpolate_pos_encoding=True,
|
| 200 |
num_beams=1,
|
| 201 |
max_new_tokens=max_new_tokens,
|
|
@@ -204,7 +217,7 @@ def _trocr_read(lines: list[Image.Image], max_new_tokens: int = 128) -> TrocrLan
|
|
| 204 |
torch.cuda.synchronize()
|
| 205 |
seconds = time.perf_counter() - started
|
| 206 |
steps = [round(at - started, 4) for at in clock.times]
|
| 207 |
-
tokenizer =
|
| 208 |
read = []
|
| 209 |
for row in ids[:, 1:].tolist(): # after the start token
|
| 210 |
text = tokenizer.decode(row, skip_special_tokens=True).strip()
|
|
@@ -270,7 +283,8 @@ def _engine() -> D.FastDSpark:
|
|
| 270 |
engine = D.FastDSpark(reader, draft, MAX_LEN)
|
| 271 |
warm = Image.open(HERE / "examples" / EXAMPLES[0]["id"] / "region.png").convert("RGB")
|
| 272 |
engine.warm(_region_inputs(warm), EOS)
|
| 273 |
-
|
|
|
|
| 274 |
_jev_score(_jev_crop(warm.crop((0, 0, 200, 40))), "warm")
|
| 275 |
_engines[os.getpid()] = engine
|
| 276 |
return engine
|
|
@@ -338,7 +352,9 @@ def compare(example_id: str, upload: Image.Image | None, with_jev: bool) -> Iter
|
|
| 338 |
limit = REGION_TOKENS
|
| 339 |
whole = "\n".join(truth) if truth else None
|
| 340 |
|
| 341 |
-
if
|
|
|
|
|
|
|
| 342 |
race.status = f"TrOCR is reading the region's {len(lines)} lines…"
|
| 343 |
yield race
|
| 344 |
race.trocr = _trocr_read(lines)
|
|
|
|
| 24 |
import gradio as gr
|
| 25 |
import torch
|
| 26 |
from huggingface_hub import snapshot_download
|
| 27 |
+
from huggingface_hub.errors import HfHubHTTPError
|
| 28 |
from PIL import Image
|
| 29 |
from pydantic import BaseModel, Field
|
| 30 |
from rapidfuzz.distance import Levenshtein
|
|
|
|
| 66 |
EOS: set[int] = set(_eos) if isinstance(_eos, list) else {int(_eos)}
|
| 67 |
jev_processor = AutoProcessor.from_pretrained(JEV)
|
| 68 |
jev = Qwen3_5ForSequenceClassification.from_pretrained(JEV, num_labels=2, dtype=torch.bfloat16).to("cuda").eval()
|
| 69 |
+
try:
|
| 70 |
+
trocr_processor = TrOCRProcessor.from_pretrained(TROCR)
|
| 71 |
+
trocr = VisionEncoderDecoderModel.from_pretrained(TROCR).to("cuda").eval() # float32, as Riksarkivet runs it
|
| 72 |
+
except (OSError, HfHubHTTPError) as error: # its weights are private: without a token the app runs without it
|
| 73 |
+
print(f"TrOCR is not loaded ({type(error).__name__}): the app runs without it", flush=True)
|
| 74 |
+
trocr_processor = trocr = None
|
| 75 |
+
NO_TROCR = (
|
| 76 |
+
"The Swedish Lion TrOCR is not available here: its weights are private, and this Space has no HF_TOKEN secret "
|
| 77 |
+
"that can read them. The reader and its draft run without it; Jev's line-by-line comparison needs both readers."
|
| 78 |
+
)
|
| 79 |
|
| 80 |
_engines: dict[int, D.FastDSpark] = {} # per GPU worker process: CUDA graphs belong to the process that captured them
|
| 81 |
_lock = threading.Lock()
|
|
|
|
| 143 |
outlines: list[list[tuple[float, float]]] = Field(default_factory=list)
|
| 144 |
shares: list[float] = Field(default_factory=list)
|
| 145 |
status: str = ""
|
| 146 |
+
notice: str = ""
|
| 147 |
done: bool = False
|
| 148 |
trocr: TrocrLane | None = None
|
| 149 |
plain: ReaderLane | None = None
|
|
|
|
| 199 |
"""TrOCR's greedy readings of a batch of lines, timed from the images to the text, as Riksarkivet's evaluation
|
| 200 |
runs it: the Swedish Lion starts decoding from its config's token (its generation_config names another, which
|
| 201 |
costs about 2 points of CER), and its 192 x 1024 inputs need the position encoding interpolated."""
|
| 202 |
+
model, images = trocr, trocr_processor
|
| 203 |
+
if model is None or images is None:
|
| 204 |
+
raise RuntimeError("TrOCR is not loaded")
|
| 205 |
torch.cuda.synchronize()
|
| 206 |
started = time.perf_counter()
|
| 207 |
clock = StepClock()
|
| 208 |
+
pixels = images(images=lines, return_tensors="pt").pixel_values.to("cuda")
|
| 209 |
+
ids = model.generate(
|
| 210 |
pixels,
|
| 211 |
+
decoder_start_token_id=model.config.decoder_start_token_id,
|
| 212 |
interpolate_pos_encoding=True,
|
| 213 |
num_beams=1,
|
| 214 |
max_new_tokens=max_new_tokens,
|
|
|
|
| 217 |
torch.cuda.synchronize()
|
| 218 |
seconds = time.perf_counter() - started
|
| 219 |
steps = [round(at - started, 4) for at in clock.times]
|
| 220 |
+
tokenizer = images.tokenizer
|
| 221 |
read = []
|
| 222 |
for row in ids[:, 1:].tolist(): # after the start token
|
| 223 |
text = tokenizer.decode(row, skip_special_tokens=True).strip()
|
|
|
|
| 283 |
engine = D.FastDSpark(reader, draft, MAX_LEN)
|
| 284 |
warm = Image.open(HERE / "examples" / EXAMPLES[0]["id"] / "region.png").convert("RGB")
|
| 285 |
engine.warm(_region_inputs(warm), EOS)
|
| 286 |
+
if trocr is not None:
|
| 287 |
+
_trocr_read([warm.crop((0, 0, 200, 40))], max_new_tokens=4)
|
| 288 |
_jev_score(_jev_crop(warm.crop((0, 0, 200, 40))), "warm")
|
| 289 |
_engines[os.getpid()] = engine
|
| 290 |
return engine
|
|
|
|
| 352 |
limit = REGION_TOKENS
|
| 353 |
whole = "\n".join(truth) if truth else None
|
| 354 |
|
| 355 |
+
if trocr is None:
|
| 356 |
+
race.notice = NO_TROCR
|
| 357 |
+
elif lines:
|
| 358 |
race.status = f"TrOCR is reading the region's {len(lines)} lines…"
|
| 359 |
yield race
|
| 360 |
race.trocr = _trocr_read(lines)
|
race_view.css
CHANGED
|
@@ -17,6 +17,14 @@
|
|
| 17 |
}
|
| 18 |
.rv-root [hidden] { display: none; }
|
| 19 |
.rv-hint, .rv-status { color: var(--rv-muted); margin: 0; }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
.rv-status::before { content: "● "; animation: rv-pulse 1.2s ease-in-out infinite; }
|
| 21 |
.rv-summary { margin: 0; max-width: 90ch; }
|
| 22 |
.rv-k { font-size: 12px; color: var(--rv-muted); letter-spacing: 0.02em; }
|
|
|
|
| 17 |
}
|
| 18 |
.rv-root [hidden] { display: none; }
|
| 19 |
.rv-hint, .rv-status { color: var(--rv-muted); margin: 0; }
|
| 20 |
+
.rv-notice {
|
| 21 |
+
padding: 8px 12px;
|
| 22 |
+
border-radius: 6px;
|
| 23 |
+
border: 1px solid var(--border-color-primary);
|
| 24 |
+
border-left: 4px solid var(--rv-trocr);
|
| 25 |
+
background: var(--background-fill-secondary);
|
| 26 |
+
max-width: 100ch;
|
| 27 |
+
}
|
| 28 |
.rv-status::before { content: "● "; animation: rv-pulse 1.2s ease-in-out infinite; }
|
| 29 |
.rv-summary { margin: 0; max-width: 90ch; }
|
| 30 |
.rv-k { font-size: 12px; color: var(--rv-muted); letter-spacing: 0.02em; }
|
race_view.js
CHANGED
|
@@ -164,6 +164,7 @@ function ensure(race) {
|
|
| 164 |
controls.append(button);
|
| 165 |
}
|
| 166 |
root.replaceChildren(
|
|
|
|
| 167 |
make("div", "rv-status"),
|
| 168 |
track,
|
| 169 |
make("p", "rv-summary"),
|
|
@@ -333,6 +334,9 @@ function draw(now) {
|
|
| 333 |
const status = root.querySelector(".rv-status");
|
| 334 |
status.textContent = race.status || "";
|
| 335 |
status.hidden = !race.status;
|
|
|
|
|
|
|
|
|
|
| 336 |
const summary = root.querySelector(".rv-summary");
|
| 337 |
summary.textContent = race.summary || "";
|
| 338 |
summary.hidden = !race.summary;
|
|
|
|
| 164 |
controls.append(button);
|
| 165 |
}
|
| 166 |
root.replaceChildren(
|
| 167 |
+
make("div", "rv-notice"),
|
| 168 |
make("div", "rv-status"),
|
| 169 |
track,
|
| 170 |
make("p", "rv-summary"),
|
|
|
|
| 334 |
const status = root.querySelector(".rv-status");
|
| 335 |
status.textContent = race.status || "";
|
| 336 |
status.hidden = !race.status;
|
| 337 |
+
const notice = root.querySelector(".rv-notice");
|
| 338 |
+
notice.textContent = race.notice || "";
|
| 339 |
+
notice.hidden = !race.notice;
|
| 340 |
const summary = root.querySelector(".rv-summary");
|
| 341 |
summary.textContent = race.summary || "";
|
| 342 |
summary.hidden = !race.summary;
|