Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project : SPIDER — Universal Web Intelligence Engine7# File : benchmarks/ocr/run_benchmark.py8# Module : Benchmarks9# Repository : https://git.spboucher.ai/spider10# Project Website : Not specified11# Created : 2026-12-0412# Last Modified : 2026-12-0413#14# Author : Simon-Pierre Boucher15# Position : Professor of Finance16# Institution : Université du Québec en Outaouais (UQO)17# Organization : SP Boucher18# Website : https://spboucher.ai19# Git : https://git.spboucher.ai20#21# Preferred Contact: contact@spboucher.ai22# Development : dev@spboucher.ai23# Support : support@spboucher.ai24# Security/Admin : admin@spboucher.ai25#26# Copyright (c) 202627# Simon-Pierre Boucher28# All rights reserved where applicable. This file is governed by the29# applicable project license, copyright notices and relevant law.30# Existing third-party rights and notices remain unaffected.31#32# License : ISC33#34# Do not embed credentials, private keys, access tokens,35# certificates or confidential personal information.36#37# =============================================================================38# END OF SP BOUCHER SOURCE HEADER39# =============================================================================4041"""Benchmark the real `spider-ocr` worker on the synthetic FR/EN corpus.4243 .venv/bin/python benchmarks/ocr/run_benchmark.py [--passes 3]4445Writes `benchmarks/ocr/results.json` and `benchmarks/ocr/REPORT.md`. Every number in the report is46measured by this run on this machine; nothing is estimated. The corpus is regenerated first when it47is missing (`make_corpus.py`).4849Method50- Accuracy: for each image the worker's lines, in the order it returns them, are joined and compared51 with the ground-truth lines joined in their reading order. CER and WER use the normalisation of52 `spider.ocr.metrics` (NFC, whitespace collapsed, case and accents significant). Rates per group53 are micro-averages: total edits / total reference length.54- Speed: one `--serve` worker per configuration. One warm-up request (reported as cold start), then55 `--passes` timed passes over the whole corpus. Latency is the client-side round trip of a request56 with a single request in flight; throughput is measured again with two requests in flight.57- Memory: resident set size of the worker process, sampled with `ps` every 50 ms; the peak is kept.58"""59from __future__ import annotations6061import argparse62import asyncio63import datetime as dt64import json65import platform66import statistics67import subprocess68import sys69import time70from collections import defaultdict71from pathlib import Path72from typing import Self7374ROOT = Path(__file__).resolve().parents[2]75sys.path.insert(0, str(ROOT / "src"))76sys.path.insert(0, str(Path(__file__).resolve().parent))7778import make_corpus79import PIL8081from spider.ocr import OcrPage, OcrWorker, available, binary_path, char_errors, word_errors8283HERE = Path(__file__).resolve().parent84CORPUS = make_corpus.CORPUS_DIR858687def sh(*argv: str) -> str:88 try:89 return subprocess.run(argv, capture_output=True, text=True, check=False).stdout.strip()90 except OSError:91 return ""929394def environment(engine: dict) -> dict:95 mem = sh("sysctl", "-n", "hw.memsize")96 return {97 "date": dt.datetime.now(dt.UTC).strftime("%Y-%m-%d %H:%M UTC"),98 "cpu": sh("sysctl", "-n", "machdep.cpu.brand_string"),99 "model": sh("sysctl", "-n", "hw.model"),100 "cores": int(sh("sysctl", "-n", "hw.ncpu") or 0),101 "performance_cores": int(sh("sysctl", "-n", "hw.perflevel0.physicalcpu") or 0),102 "memory_gb": round(int(mem) / 2**30, 1) if mem.isdigit() else None,103 "macos": f"{sh('sw_vers', '-productVersion')} ({sh('sw_vers', '-buildVersion')})",104 "arch": platform.machine(),105 "swift": sh("swift", "--version").splitlines()[0] if sh("swift", "--version") else "",106 "python": platform.python_version(),107 "pillow": PIL.__version__,108 "engine": engine,109 "worker_commit": sh("git", "-C", str(ROOT), "log", "-1", "--format=%h", "--", "services/ocr-worker"),110 }111112113def load_corpus() -> list[dict]:114 truth = CORPUS / "ground_truth.jsonl"115 if not truth.exists():116 make_corpus.write_corpus(CORPUS, None)117 records = [json.loads(line) for line in truth.read_text("utf-8").splitlines()]118 for rec in records:119 rec["path"] = str(CORPUS / rec["file"])120 rec["text"] = "\n".join(line["text"] for line in rec["lines"])121 rec["megapixels"] = rec["width"] * rec["height"] / 1e6122 return records123124125def options_for(rec: dict, fast: bool) -> dict:126 # The one rotated image is recognised with orientation detection, as a caller would do for a127 # page of unknown orientation; every other image uses the defaults.128 return {"fast": fast, "detect_orientation": rec["rotation"] != 0}129130131class RssSampler:132 def __init__(self, worker: OcrWorker):133 self.worker = worker134 self.peak_kb = 0135 self._task: asyncio.Task | None = None136137 async def _run(self) -> None:138 while True:139 pid = self.worker.pid140 if pid is not None:141 proc = await asyncio.create_subprocess_exec("ps", "-o", "rss=", "-p", str(pid),142 stdout=asyncio.subprocess.PIPE,143 stderr=asyncio.subprocess.DEVNULL)144 out, _ = await proc.communicate()145 if out.strip().isdigit():146 self.peak_kb = max(self.peak_kb, int(out.strip()))147 await asyncio.sleep(0.05)148149 async def __aenter__(self) -> Self:150 self._task = asyncio.create_task(self._run())151 return self152153 async def __aexit__(self, *exc: object) -> None:154 assert self._task is not None155 self._task.cancel()156 try:157 await self._task158 except asyncio.CancelledError:159 pass160161162def score(rec: dict, page: OcrPage) -> dict:163 ce, cl = char_errors(rec["text"], page.text)164 we, wl = word_errors(rec["text"], page.text)165 cfe, _ = char_errors(rec["text"], page.text, casefold=True)166 return {"file": rec["file"], "lang": rec["lang"], "kind": rec["kind"], "sizes": rec["sizes"], "font": rec["font"],167 "theme": rec["theme"], "char_errors": ce, "chars": cl, "word_errors": we, "words": wl,168 "char_errors_casefold": cfe, "cer": ce / cl, "wer": we / wl, "lines_found": len(page.lines),169 "lines_expected": len(rec["lines"]), "banded": page.banded, "bands": page.bands,170 "rotation": page.rotation, "worker_ms": page.ms,171 "mean_confidence": round(statistics.fmean(ln.confidence for ln in page.lines), 4) if page.lines else None}172173174def aggregate(rows: list[dict]) -> dict:175 chars, words = sum(r["chars"] for r in rows), sum(r["words"] for r in rows)176 return {"images": len(rows), "chars": chars, "words": words,177 "cer": sum(r["char_errors"] for r in rows) / chars, "wer": sum(r["word_errors"] for r in rows) / words,178 "cer_casefold": sum(r["char_errors_casefold"] for r in rows) / chars,179 "lines_found": sum(r["lines_found"] for r in rows),180 "lines_expected": sum(r["lines_expected"] for r in rows),181 "images_exact": sum(1 for r in rows if r["char_errors"] == 0)}182183184def percentile(values: list[float], q: float) -> float:185 ordered = sorted(values)186 pos = (len(ordered) - 1) * q187 lo, hi = int(pos), min(int(pos) + 1, len(ordered) - 1)188 return ordered[lo] + (ordered[hi] - ordered[lo]) * (pos - lo)189190191async def run_level(records: list[dict], fast: bool, passes: int) -> dict:192 megapixels = sum(r["megapixels"] for r in records)193 out: dict = {"level": "fast" if fast else "accurate"}194195 # ---- sequential: accuracy, latency, memory196 async with OcrWorker(concurrency=1, timeout=300) as worker:197 async with RssSampler(worker) as rss:198 t0 = time.perf_counter()199 await worker.recognize(records[0]["path"], fast=fast)200 out["cold_start_ms"] = round((time.perf_counter() - t0) * 1000, 1)201 latencies: list[float] = []202 walls: list[float] = []203 texts: list[list[str]] = []204 rows: list[dict] = []205 for k in range(passes):206 start = time.perf_counter()207 pass_texts = []208 for rec in records:209 t = time.perf_counter()210 page = await worker.recognize(rec["path"], **options_for(rec, fast))211 latencies.append((time.perf_counter() - t) * 1000)212 pass_texts.append(page.text)213 if k == 0:214 rows.append(score(rec, page))215 walls.append(time.perf_counter() - start)216 texts.append(pass_texts)217 await asyncio.sleep(0.1)218 out["peak_rss_mb_sequential"] = round(rss.peak_kb / 1024, 1)219 out["restarts"] = worker.restarts220 out["deterministic_across_passes"] = all(t == texts[0] for t in texts)221 wall = statistics.median(walls)222 out["sequential"] = {223 "passes": passes, "wall_s_median": round(wall, 3), "images_per_s": round(len(records) / wall, 2),224 "megapixels_per_s": round(megapixels / wall, 2), "latency_ms_p50": round(percentile(latencies, 0.5), 1),225 "latency_ms_p95": round(percentile(latencies, 0.95), 1), "latency_ms_mean": round(statistics.fmean(latencies), 1),226 "latency_ms_max": round(max(latencies), 1), "samples": len(latencies),227 }228229 # ---- two requests in flight: throughput, memory230 async with OcrWorker(concurrency=2, timeout=300) as worker:231 async with RssSampler(worker) as rss:232 await worker.recognize(records[0]["path"], fast=fast)233 walls = []234 for _ in range(passes):235 start = time.perf_counter()236 await asyncio.gather(*(worker.recognize(rec["path"], **options_for(rec, fast)) for rec in records))237 walls.append(time.perf_counter() - start)238 await asyncio.sleep(0.1)239 wall = statistics.median(walls)240 out["concurrency_2"] = {"passes": passes, "wall_s_median": round(wall, 3),241 "images_per_s": round(len(records) / wall, 2),242 "megapixels_per_s": round(megapixels / wall, 2),243 "peak_rss_mb": round(rss.peak_kb / 1024, 1)}244245 out["images"] = rows246 out["overall"] = aggregate(rows)247 groups: dict[str, dict] = {}248 for key in ("lang", "kind"):249 buckets: dict[str, list[dict]] = defaultdict(list)250 for row in rows:251 buckets[row[key]].append(row)252 groups[key] = {name: aggregate(items) for name, items in sorted(buckets.items())}253 by_size: dict[str, list[dict]] = defaultdict(list)254 for row in rows:255 if row["kind"] == "paragraph":256 by_size[f"{row['sizes'][0]:02d}"].append(row)257 groups["paragraph_font_size"] = {name: aggregate(items) for name, items in sorted(by_size.items())}258 by_theme: dict[str, list[dict]] = defaultdict(list)259 for row in rows:260 by_theme["dark" if row["theme"] in ("dark", "navy") else "light"].append(row)261 groups["theme"] = {name: aggregate(items) for name, items in sorted(by_theme.items())}262 by_font: dict[str, list[dict]] = defaultdict(list)263 for row in rows:264 by_font[row["font"]].append(row)265 groups["font"] = {name: aggregate(items) for name, items in sorted(by_font.items())}266 out["groups"] = groups267 return out268269270async def run_banding(records: list[dict]) -> list[dict]:271 """Tall pages: one piece, default banding, and banding forced by a small pixel budget."""272 tall = [r for r in records if r["kind"] == "tall"]273 configs = [274 ("one piece (max_band_aspect=0)", {"max_band_aspect": 0}),275 ("default (max_band_aspect=4)", {}),276 ("max_pixels=1 000 000", {"max_pixels": 1_000_000}),277 ("max_pixels=400 000", {"max_pixels": 400_000}),278 ]279 rows = []280 async with OcrWorker(concurrency=1, timeout=300) as worker:281 await worker.recognize(tall[0]["path"])282 for rec in tall:283 for label, opts in configs:284 samples = []285 for _ in range(3):286 t = time.perf_counter()287 page = await worker.recognize(rec["path"], **opts)288 samples.append((time.perf_counter() - t) * 1000)289 s = score(rec, page)290 rows.append({"file": rec["file"], "size": f"{rec['width']}x{rec['height']}", "config": label,291 "bands": page.bands, "lines_found": s["lines_found"],292 "lines_expected": s["lines_expected"], "cer": s["cer"], "wer": s["wer"],293 "ms_median": round(statistics.median(samples), 1)})294 return rows295296297def pct(value: float) -> str:298 return f"{value * 100:.2f} %"299300301def accuracy_table(title: str, levels: list[dict], group: str | None) -> list[str]:302 lines = [f"### {title}", "",303 "| Level | Group | Images | Ref. chars | CER | WER | CER (case-insensitive) | Lines found / expected | Images with 0 error |",304 "|---|---|---:|---:|---:|---:|---:|---:|---:|"]305 for lvl in levels:306 items = {"all": lvl["overall"]} if group is None else lvl["groups"][group]307 for name, agg in items.items():308 lines.append(f"| {lvl['level']} | {name} | {agg['images']} | {agg['chars']} | {pct(agg['cer'])} | "309 f"{pct(agg['wer'])} | {pct(agg['cer_casefold'])} | {agg['lines_found']} / {agg['lines_expected']} | "310 f"{agg['images_exact']} |")311 return [*lines, ""]312313314def render(results: dict) -> str:315 env, corpus, levels = results["environment"], results["corpus"], results["levels"]316 accurate, fast = levels[0], levels[1]317 speedup = fast["sequential"]["images_per_s"] / accurate["sequential"]["images_per_s"]318 mono = [r for r in accurate["images"] if r["font"] == "Menlo"]319 mono_found, mono_expected = sum(r["lines_found"] for r in mono), sum(r["lines_expected"] for r in mono)320 mono_errors, mono_chars = sum(r["char_errors"] for r in mono), sum(r["chars"] for r in mono)321 all_errors = sum(r["char_errors"] for r in accurate["images"])322 md = ["# spider-ocr benchmark", "",323 (f"Generated by `benchmarks/ocr/run_benchmark.py` on {env['date']}. Every number below was measured by "324 "that run; rerun the script to reproduce."), "",325 ("> **The corpus is synthetic.** Every image is clean text rendered by Pillow in a system font on a flat "326 "background: no JPEG artefacts, no photographs behind the text, no sub-pixel colour fringes, no icons, "327 "no overlapping elements. Error rates on real-world screenshots will be higher: read these results as an "328 "**upper bound on accuracy**, not as an expectation."), "",329 "## Environment", "",330 "| | |", "|---|---|",331 (f"| Machine | {env['model']}, {env['cpu']}, {env['cores']} cores ({env['performance_cores']} performance), "332 f"{env['memory_gb']} GB |"),333 f"| macOS | {env['macos']}, {env['arch']} |",334 f"| OCR engine | Apple Vision `VNRecognizeTextRequest` revision {env['engine'].get('revision')} |",335 f"| Worker | spider-ocr {env['engine'].get('worker')} (commit `{env['worker_commit']}`), {env['swift']} |",336 f"| Client | Python {env['python']}, Pillow {env['pillow']} (corpus rendering) |",337 (f"| Languages requested | {', '.join(results['languages_requested'])} -> given to Vision: "338 f"{', '.join(results['languages_used'])} |"), "",339 "## Corpus", "",340 (f"{corpus['images']} PNG images, {corpus['megapixels']:.1f} megapixels, {corpus['lines']} ground-truth lines, "341 f"{corpus['chars']} reference characters ({corpus['by_lang']['fr']['images']} French images, "342 f"{corpus['by_lang']['en']['images']} English images). Generated by `benchmarks/ocr/make_corpus.py` "343 f"(seed {make_corpus.SEED}); fonts: {', '.join(corpus['fonts'])}."), "",344 "| Kind | Images | Content |", "|---|---:|---|"]345 descriptions = {346 "paragraph": "8 (or 6) lines, one column; sizes 11, 13, 16, 20, 24, 32 px; two fonts per size and language",347 "prices_dates": "prices (`1 250,00 $`, `$1,250.00`) and dates, 18 px, light and dark",348 "multi_column": "two columns of 8 aligned rows, 17 px",349 "table": "6 x 4 table with rules, 16 px",350 "mixed_sizes": "32 px title, 20 px subtitle, 14 px body, 11 px footer; light and dark",351 "monospace": "Menlo 12 px listing",352 "rotated": "page rotated by 90 degrees, recognised with `detect_orientation`",353 "long_page": "30 lines, about 920 px high (also used by the tile tests)",354 "tall": "216 numbered lines, more than 6000 px high (processed in bands)",355 }356 for kind, count in corpus["by_kind"].items():357 md.append(f"| {kind} | {count} | {descriptions.get(kind, '')} |")358 md += ["", ("French text carries é è à ç œ ù ï ê î ô û ü and the `$` after the amount; English text has a few "359 "accented loan words. Themes: white, warm paper, dark grey, navy."), "",360 "## Accuracy", "",361 ("CER = character edits / reference characters; WER = word edits / reference words; micro-averaged. "362 "Normalisation: Unicode NFC and whitespace collapsed; case, accents and punctuation must match."), ""]363 md += accuracy_table("Overall", levels, None)364 md += accuracy_table("By language", levels, "lang")365 md += accuracy_table("By kind of image", levels, "kind")366 md += accuracy_table("By font size (single-column paragraphs)", levels, "paragraph_font_size")367 md += accuracy_table("By theme", levels, "theme")368 md += accuracy_table("By font", levels, "font")369 md += ["### Images with the highest CER", ""]370 for lvl in levels:371 worst = sorted(lvl["images"], key=lambda r: -r["cer"])[:6]372 md.append(f"- **{lvl['level']}**: " + "; ".join(f"`{r['file']}` {pct(r['cer'])}" for r in worst if r["cer"] > 0))373 md += ["", "## Speed and memory", "",374 (f"One `--serve` worker; {levels[0]['sequential']['passes']} passes over the corpus after one warm-up request. "375 "Latency = client-side round trip with one request in flight. The rotated image includes its orientation "376 "probe; the tall images are processed in bands."), "",377 "| Level | In flight | Images/s | Megapixels/s | p50 latency | p95 latency | Mean | Max | Cold start | Peak worker RSS |",378 "|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|"]379 for lvl in levels:380 s, c = lvl["sequential"], lvl["concurrency_2"]381 md.append(f"| {lvl['level']} | 1 | {s['images_per_s']} | {s['megapixels_per_s']} | {s['latency_ms_p50']} ms | "382 f"{s['latency_ms_p95']} ms | {s['latency_ms_mean']} ms | {s['latency_ms_max']} ms | "383 f"{lvl['cold_start_ms']} ms | {lvl['peak_rss_mb_sequential']} MB |")384 md.append(f"| {lvl['level']} | 2 | {c['images_per_s']} | {c['megapixels_per_s']} | | | | | | {c['peak_rss_mb']} MB |")385 md += ["", "Text was identical across passes: "386 + ", ".join(f"{lvl['level']} {'yes' if lvl['deterministic_across_passes'] else 'NO'}" for lvl in levels)387 + ". Worker restarts during the run: " + ", ".join(f"{lvl['level']} {lvl['restarts']}" for lvl in levels) + ".", "",388 "## Tall pages and banding (accurate level)", "",389 "| Image | Size | Configuration | Bands | Lines found / expected | CER | WER | Median time |",390 "|---|---|---|---:|---:|---:|---:|---:|"]391 for row in results["banding"]:392 md.append(f"| `{row['file']}` | {row['size']} | {row['config']} | {row['bands']} | {row['lines_found']} / "393 f"{row['lines_expected']} | {pct(row['cer'])} | {pct(row['wer'])} | {row['ms_median']} ms |")394 md += ["", ("Recognised in one piece, a very tall page loses most or all of its text: Vision scales the image to "395 "its working size and the text becomes unreadable. This is why the worker cuts a page that is more than "396 "four times longer than wide, whatever its pixel count."), "",397 "## Reading the results", "",398 "- Synthetic rendered text: an upper bound on accuracy (see the note at the top).",399 ("- `fr-CA` is not in this Vision revision's language list; the worker substitutes `fr-FR` and says so in "400 "`warnings`."),401 (f"- Fast versus accurate on this corpus: {speedup:.2f} times the images per second (one request in flight), "402 f"CER {pct(fast['overall']['cer'])} against {pct(accurate['overall']['cer'])}; in French "403 f"{pct(fast['groups']['lang']['fr']['cer'])} against {pct(accurate['groups']['lang']['fr']['cer'])}. "404 "The accurate level is the default."),405 ("- Vision returns its own line segmentation. On the monospace font (Menlo) it often splits one printed "406 f"line into several fragments ({mono_found} lines found for {mono_expected} printed), and Menlo accounts "407 f"for {mono_errors} of the accurate level's {all_errors} character errors with "408 f"{mono_chars / accurate['overall']['chars'] * 100:.0f} % of the reference characters. In the tables a lone "409 "digit in a cell can be missed. The worker reports the fragments as they are, in reading order; it does "410 "not glue them together."),411 ("- Latencies include process pipes and JSON, not image capture. Timings vary with thermal state and with "412 "whatever else the machine is doing; this run was not made on an idle, dedicated machine."),413 "- Full per-image data: `benchmarks/ocr/results.json`.", ""]414 return "\n".join(md)415416417async def main_async(passes: int) -> dict:418 if not available():419 raise SystemExit("spider-ocr is not available: build it with services/ocr-worker/build.sh (macOS only)")420 records = load_corpus()421 async with OcrWorker() as probe:422 engine = (await probe.ping())["engine"]423 first = await probe.recognize(records[0]["path"])424 requested, used = probe.languages, first.languages425 by_lang: dict[str, dict] = {}426 for lang in ("fr", "en"):427 items = [r for r in records if r["lang"] == lang]428 by_lang[lang] = {"images": len(items), "chars": sum(char_errors(r["text"], "")[1] for r in items)}429 by_kind: dict[str, int] = defaultdict(int)430 for r in records:431 by_kind[r["kind"]] += 1432 results = {433 "environment": environment(engine),434 "binary": str(binary_path().relative_to(ROOT)) if binary_path().is_relative_to(ROOT) else "spider-ocr",435 "languages_requested": requested, "languages_used": used,436 "corpus": {"images": len(records), "megapixels": sum(r["megapixels"] for r in records),437 "lines": sum(len(r["lines"]) for r in records),438 "chars": sum(v["chars"] for v in by_lang.values()), "by_lang": by_lang, "by_kind": dict(by_kind),439 "bytes": sum(Path(r["path"]).stat().st_size for r in records),440 "fonts": [f[0] for f in make_corpus.available_fonts()], "seed": make_corpus.SEED,441 "synthetic": True,442 "note": "Pillow-rendered text on flat backgrounds; results are an upper bound versus real screenshots."},443 "levels": [await run_level(records, fast=False, passes=passes), await run_level(records, fast=True, passes=passes)],444 "banding": await run_banding(records),445 }446 return results447448449def main() -> None:450 parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])451 parser.add_argument("--passes", type=int, default=3, help="timed passes over the corpus per configuration")452 parser.add_argument("--render-only", action="store_true",453 help="rewrite REPORT.md from the existing results.json without measuring anything")454 args = parser.parse_args()455 if args.render_only:456 results = json.loads((HERE / "results.json").read_text("utf-8"))457 else:458 results = asyncio.run(main_async(max(1, args.passes)))459 (HERE / "results.json").write_text(json.dumps(results, ensure_ascii=False, indent=1) + "\n", "utf-8")460 (HERE / "REPORT.md").write_text(render(results), "utf-8")461 for lvl in results["levels"]:462 o, s = lvl["overall"], lvl["sequential"]463 print(f"{lvl['level']:9s} CER {pct(o['cer'])} WER {pct(o['wer'])} {s['images_per_s']} img/s "464 f"p50 {s['latency_ms_p50']} ms p95 {s['latency_ms_p95']} ms RSS {lvl['peak_rss_mb_sequential']} MB")465466467if __name__ == "__main__":468 main()469