Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project : SPIDER — Universal Web Intelligence Engine7# File : benchmarks/ocr/make_corpus.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"""Generate the reproducible synthetic FR/EN OCR corpus used by the tests and the benchmark.4243 .venv/bin/python benchmarks/ocr/make_corpus.py # corpus + committed sample44 .venv/bin/python benchmarks/ocr/make_corpus.py --no-sample4546Every image is text rendered with Pillow in a macOS system font, so the ground truth (text and47pixel box of every rendered string) is exact. The corpus is synthetic: clean rendered text is an48easier target than real screenshots, and the benchmark report says so.4950Outputs, per folder: PNG files and `ground_truth.jsonl`, one JSON object per image:51 {"file", "width", "height", "lang", "kind", "theme", "font", "sizes", "rotation",52 "lines": [{"text", "x", "y", "w", "h", "size"}]} # lines are in reading order53`rotation` is the clockwise rotation (degrees) that makes the text upright (0 except one image).54"""55from __future__ import annotations5657import argparse58import json59import random60import shutil61from dataclasses import dataclass, field62from pathlib import Path6364from PIL import Image, ImageDraw, ImageFont6566ROOT = Path(__file__).resolve().parents[2]67CORPUS_DIR = ROOT / "tests" / "fixtures" / "ocr" / "corpus"68SAMPLE_DIR = ROOT / "tests" / "fixtures" / "ocr" / "sample"69SEED = 202612047071FONT_CANDIDATES: list[tuple[str, str, int]] = [72 ("Helvetica", "/System/Library/Fonts/Helvetica.ttc", 0),73 ("Arial", "/System/Library/Fonts/Supplemental/Arial.ttf", 0),74 ("Times New Roman", "/System/Library/Fonts/Supplemental/Times New Roman.ttf", 0),75 ("Menlo", "/System/Library/Fonts/Menlo.ttc", 0),76 ("Georgia", "/System/Library/Fonts/Supplemental/Georgia.ttf", 0),77 ("Verdana", "/System/Library/Fonts/Supplemental/Verdana.ttf", 0),78]7980THEMES: dict[str, tuple[tuple[int, int, int], tuple[int, int, int], tuple[int, int, int]]] = {81 # name: (background, text, rule)82 "light": ((255, 255, 255), (20, 20, 20), (190, 190, 190)),83 "paper": ((247, 245, 240), (45, 42, 38), (200, 195, 185)),84 "dark": ((18, 18, 22), (235, 235, 235), (80, 80, 90)),85 "navy": ((13, 27, 42), (224, 225, 221), (65, 90, 119)),86}8788FR_LINES = [89 "Le cœur de la ville bat à l'heure d'été.",90 "Où se trouve la bibliothèque municipale ?",91 "Noël approche : les enfants naïfs espèrent la neige.",92 "Prix : 1 250,00 $ taxes incluses",93 "Livraison prévue le 14 février 2026",94 "Ce maïs sucré coûte 3,49 $ la douzaine.",95 "Façade rénovée, garçon de café, leçon apprise.",96 "L'œuvre a été créée à Québec en 1998.",97 "Total à payer : 2 847,35 $",98 "Rendez-vous le 2026-03-09 à 14 h 30.",99 "Loyer mensuel : 1 475 $ par mois, chauffé et éclairé.",100 "Hélène préfère où ça ? Près du château, bien sûr.",101 "Superficie : 82,5 m² sur deux étages",102 "Le système a traité 12 480 pages en 37 minutes.",103 "Coïncidence : l'aïeul égoïste a haï ce capharnaüm.",104 "Déjà 45 % des élèves ont réussi l'épreuve.",105 "Téléphone : 819 555-0142, poste 27",106 "Sœur Thérèse a cueilli des bleuets à Saguenay.",107 "Mise à jour du 1er décembre 2025 : aucun arrêt prévu.",108 "Appartement de 4 pièces à louer dès le 1er juillet.",109 "Le reçu no 30917 a été émis à Trois-Rivières.",110 "Où est passé le vœu du maître d'hôtel ?",111 "Taux fixe de 4,89 % garanti pendant 5 ans.",112 "Ouvert du lundi au vendredi, de 8 h à 17 h.",113 "La forêt boréale s'étend à perte de vue.",114 "Dépôt exigé : 500,00 $ à la réservation",115 "Ça y est : la mise à niveau est terminée.",116 "Kilométrage : 68 300 km, année 2019",117 "Un bœuf bourguignon mijoté, servi à 19 h 15.",118 "Dernière vérification effectuée le 30 août 2024.",119]120121EN_LINES = [122 "The quick brown fox jumps over the lazy dog.",123 "Total due: $1,250.00 including taxes",124 "Delivery scheduled for February 14, 2026",125 "Order #48213 shipped on 2026-03-09 at 2:30 PM.",126 "Monthly rent: $1,475 per month, utilities included.",127 "The café's résumé policy was naïve at best.",128 "Revenue grew 12.4% year over year to $3,847,120.",129 "Call 613-555-0178 ext. 27 between 9 AM and 5 PM.",130 "Floor area: 890 sq ft across two storeys",131 "The crawler processed 12,480 pages in 37 minutes.",132 "Fixed rate of 4.89% guaranteed for 5 years.",133 "Open Monday to Friday, from 8:00 to 17:00.",134 "Deposit required: $500.00 at booking",135 "Mileage: 68,300 km, model year 2019",136 "Last verified on August 30, 2024 by the auditor.",137 "Invoice 30917 was issued in Thunder Bay, Ontario.",138 "A journey of a thousand miles begins with one step.",139 "Shipping is free on orders over $75.00.",140 "Your password must contain at least 12 characters.",141 "Three bedrooms, two bathrooms, one heated garage.",142 "Balance carried forward: $2,847.35",143 "The meeting was moved to Thursday, June 18, 2026.",144 "Subscribe before 11:59 PM to keep the 20% discount.",145 "Nearly 45% of students passed the final exam.",146 "Check-in after 3 PM, check-out before 11 AM.",147 "The boreal forest stretches as far as the eye can see.",148 "Unit price: $18.75, quantity: 24, subtotal: $450.00",149 "Download the 2025 annual report (PDF, 3.2 MB).",150 "Warranty expires on 12/31/2027 unless renewed.",151 "Seven wizards quickly judged the boxing match.",152]153154FR_SHORT = [155 "Prix demandé : 389 000 $", "Année : 2019", "Taxes : 3 412,80 $", "Étage : 3e sur 4",156 "Chauffage électrique", "Près du métro Laurier", "Libre le 1er juillet", "Deux chambres fermées",157 "Cuisine rénovée", "Balcon côté cour", "Stationnement inclus", "Visite sur rendez-vous",158 "Aucun animal accepté", "Référence no 2048", "Évaluation : 412 600 $", "Poêle et frigo fournis",159]160EN_SHORT = [161 "Asking price: $389,000", "Year built: 2019", "Taxes: $3,412.80", "Floor: 3rd of 4",162 "Electric heating", "Near Laurier station", "Available July 1st", "Two closed bedrooms",163 "Renovated kitchen", "Balcony facing the yard", "Parking included", "Viewing by appointment",164 "No pets allowed", "Reference no. 2048", "Assessment: $412,600", "Stove and fridge supplied",165]166167FR_TABLE = [168 ["Article", "Quantité", "Prix unitaire", "Total"],169 ["Café moulu", "3", "12,99 $", "38,97 $"],170 ["Thé glacé", "12", "1,75 $", "21,00 $"],171 ["Pâté chinois", "2", "9,50 $", "19,00 $"],172 ["Crème brûlée", "4", "6,25 $", "25,00 $"],173 ["Total", "21", "", "103,97 $"],174]175EN_TABLE = [176 ["Item", "Quantity", "Unit price", "Total"],177 ["Ground coffee", "3", "$12.99", "$38.97"],178 ["Iced tea", "12", "$1.75", "$21.00"],179 ["Shepherd's pie", "2", "$9.50", "$19.00"],180 ["Lemon tart", "4", "$6.25", "$25.00"],181 ["Total", "21", "", "$103.97"],182]183184FR_DATES = [185 "Émis le 3 janvier 2025", "Échéance : 2025-02-17", "Payé le 28 février 2025 : 1 250,00 $",186 "Solde au 31 mars 2025 : 12 480,55 $", "Prochain relevé : 15 avril 2025", "Intérêts : 37,42 $",187 "Versement de 2 000,00 $ reçu le 9 mai 2025", "Frais annuels : 120,00 $",188]189EN_DATES = [190 "Issued on January 3, 2025", "Due date: 2025-02-17", "Paid on February 28, 2025: $1,250.00",191 "Balance as of March 31, 2025: $12,480.55", "Next statement: April 15, 2025", "Interest: $37.42",192 "Payment of $2,000.00 received on May 9, 2025", "Annual fee: $120.00",193]194195FR_PAGE = {196 "title": "Rapport trimestriel",197 "subtitle": "Résultats du deuxième trimestre 2026",198 "footer": "Document généré le 2026-07-04 à 9 h 12, page 1 de 3",199}200EN_PAGE = {201 "title": "Quarterly report",202 "subtitle": "Results for the second quarter of 2026",203 "footer": "Document generated on 2026-07-04 at 9:12 AM, page 1 of 3",204}205206207def available_fonts() -> list[tuple[str, str, int]]:208 return [f for f in FONT_CANDIDATES if Path(f[1]).exists()]209210211_FONT_CACHE: dict[tuple[str, int], ImageFont.FreeTypeFont | ImageFont.ImageFont] = {}212213214def load_font(name: str, size: int):215 key = (name, size)216 if key not in _FONT_CACHE:217 match = next((f for f in FONT_CANDIDATES if f[0] == name and Path(f[1]).exists()), None)218 if match is None: # no system font at all: Pillow's bundled scalable font219 _FONT_CACHE[key] = ImageFont.load_default(size)220 else:221 _FONT_CACHE[key] = ImageFont.truetype(match[1], size, index=match[2])222 return _FONT_CACHE[key]223224225@dataclass226class Sheet:227 """Collects positioned strings, then renders them on a canvas sized to fit."""228 theme: str229 font: str230 margin: int = 32231 items: list[tuple[str, int, int, int]] = field(default_factory=list) # text, x, y, size232 rules: list[tuple[int, int, int, int]] = field(default_factory=list)233 min_width: int = 0234 min_height: int = 0235236 def add(self, text: str, x: int, y: int, size: int) -> None:237 if text:238 self.items.append((text, x, y, size))239240 def width_of(self, text: str, size: int) -> int:241 box = load_font(self.font, size).getbbox(text)242 return int(box[2])243244 def render(self) -> tuple[Image.Image, list[dict]]:245 bg, fg, _ = THEMES[self.theme]246 probe = ImageDraw.Draw(Image.new("RGB", (8, 8)))247 boxes = [probe.textbbox((x, y), t, font=load_font(self.font, s)) for t, x, y, s in self.items]248 width = max(self.min_width, max(b[2] for b in boxes) + self.margin)249 height = max(self.min_height, max(b[3] for b in boxes) + self.margin)250 img = Image.new("RGB", (int(width), int(height)), bg)251 draw = ImageDraw.Draw(img)252 for x0, y0, x1, y1 in self.rules:253 draw.line((x0, y0, x1, y1), fill=THEMES[self.theme][2], width=1)254 lines = []255 for (text, x, y, size), box in zip(self.items, boxes, strict=True):256 draw.text((x, y), text, font=load_font(self.font, size), fill=fg)257 lines.append({"text": text, "x": box[0], "y": box[1], "w": box[2] - box[0], "h": box[3] - box[1],258 "size": size})259 return img, lines260261262def paragraph(texts: list[str], size: int, theme: str, font: str) -> Sheet:263 sheet = Sheet(theme, font)264 pitch = round(size * 1.6)265 for k, text in enumerate(texts):266 sheet.add(text, sheet.margin, sheet.margin + k * pitch, size)267 return sheet268269270def columns(left: list[str], right: list[str], size: int, theme: str, font: str) -> Sheet:271 sheet = Sheet(theme, font)272 pitch = round(size * 1.7)273 gap = 90274 col2 = sheet.margin + max(sheet.width_of(t, size) for t in left) + gap275 for k, (a, b) in enumerate(zip(left, right, strict=True)): # row by row = reading order276 y = sheet.margin + k * pitch277 sheet.add(a, sheet.margin, y, size)278 sheet.add(b, col2, y, size)279 return sheet280281282def table(rows: list[list[str]], size: int, theme: str, font: str) -> Sheet:283 sheet = Sheet(theme, font)284 pad = 18285 widths = [max(sheet.width_of(r[c], size) for r in rows) + 2 * pad for c in range(len(rows[0]))]286 pitch = round(size * 2.2)287 x0 = y0 = sheet.margin288 total_w = sum(widths)289 for r, row in enumerate(rows):290 y = y0 + r * pitch291 sheet.rules.append((x0, y, x0 + total_w, y))292 x = x0293 for c, cell in enumerate(row):294 sheet.add(cell, x + pad, y + round(size * 0.55), size)295 x += widths[c]296 bottom = y0 + len(rows) * pitch297 sheet.rules.append((x0, bottom, x0 + total_w, bottom))298 x = x0299 for w in [0, *widths]:300 x += w301 sheet.rules.append((x, y0, x, bottom))302 sheet.min_width = x0 + total_w + sheet.margin303 sheet.min_height = bottom + sheet.margin304 return sheet305306307def page(meta: dict[str, str], body: list[str], theme: str, font: str) -> Sheet:308 sheet = Sheet(theme, font, margin=40)309 y = sheet.margin310 sheet.add(meta["title"], sheet.margin, y, 32)311 y += 56312 sheet.add(meta["subtitle"], sheet.margin, y, 20)313 y += 46314 for text in body:315 sheet.add(text, sheet.margin, y, 14)316 y += 24317 y += 18318 sheet.add(meta["footer"], sheet.margin, y, 11)319 return sheet320321322def rotate_ccw(img: Image.Image, lines: list[dict]) -> tuple[Image.Image, list[dict]]:323 """Rotate the page 90 degrees counter-clockwise (so it needs +90 clockwise to be upright)."""324 width = img.width325 out = img.rotate(90, expand=True)326 moved = [{**ln, "x": ln["y"], "y": width - (ln["x"] + ln["w"]), "w": ln["h"], "h": ln["w"]} for ln in lines]327 return out, moved328329330def build_specs() -> list[dict]:331 rng = random.Random(SEED)332 fonts = [f[0] for f in available_fonts()] or ["default"]333 themes = list(THEMES)334 specs: list[dict] = []335336 def font_at(k: int) -> str:337 return fonts[k % len(fonts)]338339 def add(name: str, lang: str, kind: str, sheet: Sheet, rotation: int = 0, sample: bool = False) -> None:340 specs.append({"name": name, "lang": lang, "kind": kind, "sheet": sheet, "rotation": rotation,341 "sample": sample})342343 # 24 single-column paragraphs: 2 languages x 6 sizes x 2 fonts, alternating themes.344 k = 0345 for lang, pool in (("fr", FR_LINES), ("en", EN_LINES)):346 for size in (11, 13, 16, 20, 24, 32):347 for variant in range(2):348 theme = themes[k % len(themes)]349 font = font_at(k)350 texts = rng.sample(pool, 8 if size < 24 else 6)351 add(f"para-{lang}-{size:02d}-{variant}", lang, "paragraph", paragraph(texts, size, theme, font),352 sample=(size == 16 and variant == 0) or (lang == "fr" and size == 11 and variant == 1)353 or (lang == "en" and size == 24 and variant == 1))354 k += 1355356 # 4 price/date statements, light and dark.357 for lang, pool in (("fr", FR_DATES), ("en", EN_DATES)):358 for theme in ("light", "dark"):359 add(f"prices-{lang}-{theme}", lang, "prices_dates", paragraph(pool, 18, theme, font_at(k)),360 sample=(lang, theme) in (("fr", "dark"), ("en", "light")))361 k += 1362363 # 2 two-column layouts (rows aligned, so row-major reading order is well defined).364 for lang, pool in (("fr", FR_SHORT), ("en", EN_SHORT)):365 add(f"columns-{lang}", lang, "multi_column", columns(pool[:8], pool[8:], 17, "light" if lang == "fr" else "navy",366 font_at(k)), sample=lang == "en")367 k += 1368369 # 2 small tables.370 for lang, rows in (("fr", FR_TABLE), ("en", EN_TABLE)):371 add(f"table-{lang}", lang, "table", table(rows, 16, "paper" if lang == "fr" else "dark", font_at(k)),372 sample=lang == "fr")373 k += 1374375 # 4 mixed-size pages (32 px title, 20 px subtitle, 14 px body, 11 px footer).376 for lang, meta, pool in (("fr", FR_PAGE, FR_LINES), ("en", EN_PAGE, EN_LINES)):377 for theme in ("light", "dark"):378 add(f"page-{lang}-{theme}", lang, "mixed_sizes", page(meta, rng.sample(pool, 6), theme, font_at(k)),379 sample=(lang, theme) == ("fr", "light"))380 k += 1381382 # 2 monospace listings at small sizes.383 for lang, pool in (("fr", FR_LINES), ("en", EN_LINES)):384 mono = "Menlo" if "Menlo" in fonts else font_at(k)385 add(f"mono-{lang}", lang, "monospace", paragraph(rng.sample(pool, 8), 12, "dark" if lang == "fr" else "paper", mono))386 k += 1387388 # 1 page rotated by 90 degrees.389 add("rotated-en-90", "en", "rotated", paragraph(rng.sample(EN_LINES, 8), 18, "light", font_at(k)), rotation=90,390 sample=True)391 k += 1392393 # 1 medium page used by the tile and banding tests (30 lines, about 1300 px high).394 add("tiles-fr", "fr", "long_page", paragraph(FR_LINES, 18, "light", font_at(k)), sample=True)395 k += 1396397 # 2 tall pages (> 6000 px) to exercise banding.398 for lang, pool in (("fr", FR_LINES), ("en", EN_LINES)):399 texts = [f"{n + 1:03d}. {pool[(n * 7 + 3) % len(pool)]}" for n in range(216)]400 add(f"tall-{lang}", lang, "tall", paragraph(texts, 18, "light" if lang == "fr" else "dark", font_at(k)))401 k += 1402 return specs403404405def write_corpus(out: Path, sample_out: Path | None) -> dict:406 out.mkdir(parents=True, exist_ok=True)407 for old in list(out.glob("*.png")) + list(out.glob("ground_truth.jsonl")):408 old.unlink()409 records = []410 for spec in build_specs():411 sheet: Sheet = spec["sheet"]412 img, lines = sheet.render()413 if spec["rotation"] == 90:414 img, lines = rotate_ccw(img, lines)415 name = spec["name"] + ".png"416 img.save(out / name, optimize=True)417 records.append({418 "file": name, "width": img.width, "height": img.height, "lang": spec["lang"], "kind": spec["kind"],419 "theme": sheet.theme, "font": sheet.font, "sizes": sorted({s for _, _, _, s in sheet.items}),420 "rotation": spec["rotation"], "sample": spec["sample"], "lines": lines,421 })422 with (out / "ground_truth.jsonl").open("w", encoding="utf-8") as fh:423 for rec in records:424 fh.write(json.dumps(rec, ensure_ascii=False) + "\n")425 summary = {"images": len(records), "bytes": sum((out / r["file"]).stat().st_size for r in records),426 "lines": sum(len(r["lines"]) for r in records), "fonts": [f[0] for f in available_fonts()]}427 if sample_out is not None:428 sample_out.mkdir(parents=True, exist_ok=True)429 for old in list(sample_out.glob("*.png")) + list(sample_out.glob("ground_truth.jsonl")):430 old.unlink()431 chosen = [r for r in records if r["sample"]]432 with (sample_out / "ground_truth.jsonl").open("w", encoding="utf-8") as fh:433 for rec in chosen:434 shutil.copyfile(out / rec["file"], sample_out / rec["file"])435 fh.write(json.dumps(rec, ensure_ascii=False) + "\n")436 summary["sample_images"] = len(chosen)437 summary["sample_bytes"] = sum((sample_out / r["file"]).stat().st_size for r in chosen)438 return summary439440441def main() -> None:442 parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])443 parser.add_argument("--out", type=Path, default=CORPUS_DIR)444 parser.add_argument("--sample-out", type=Path, default=SAMPLE_DIR)445 parser.add_argument("--no-sample", action="store_true", help="do not rewrite the committed sample")446 args = parser.parse_args()447 print(json.dumps(write_corpus(args.out, None if args.no_sample else args.sample_out), ensure_ascii=False))448449450if __name__ == "__main__":451 main()452