Repository Public
1"""Binary assets of the SPIDER fixture website, generated in memory with Pillow.23Everything here is deterministic for a given Pillow version and system font:4no randomness, no timestamps, no network. Assets are built lazily and cached, so5importing this module costs nothing and the server starts instantly.6"""78from __future__ import annotations910import io11import zlib12from collections.abc import Callable13from functools import cache14from pathlib import Path1516from PIL import Image, ImageDraw, ImageFont1718# System fonts able to draw accented Latin text. Pillow's built-in font has no19# accented glyphs, so it is only the last resort.20_FONT_CANDIDATES = (21 "/System/Library/Fonts/Supplemental/Arial.ttf",22 "/Library/Fonts/Arial.ttf",23 "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",24 "/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf",25 "/usr/share/fonts/dejavu/DejaVuSans.ttf",26 "C:/Windows/Fonts/arial.ttf",27)2829INK = (20, 28, 38)30PAPER = (255, 255, 255)31SLATE = (31, 58, 77)32SAND = (236, 229, 214)33RUST = (168, 74, 42)34MOSS = (74, 110, 72)35PALETTE = (SLATE, RUST, MOSS, (120, 96, 150), (196, 150, 52))363738@cache39def font_source() -> str:40 """Path of the font used for pixel text ("pillow-default" when none is found)."""41 for candidate in _FONT_CANDIDATES:42 if Path(candidate).is_file():43 return candidate44 return "pillow-default"454647@cache48def _font(size: int) -> ImageFont.FreeTypeFont | ImageFont.ImageFont:49 source = font_source()50 if source == "pillow-default":51 return ImageFont.load_default(size=size)52 return ImageFont.truetype(source, size)535455def _png(image: Image.Image) -> bytes:56 buffer = io.BytesIO()57 image.save(buffer, format="PNG", optimize=False)58 return buffer.getvalue()596061def _fit_font(draw: ImageDraw.ImageDraw, text: str, max_width: int, size: int):62 while size > 10:63 font = _font(size)64 if draw.textlength(text, font=font) <= max_width:65 return font66 size -= 267 return _font(10)686970def text_image(71 text: str,72 size: tuple[int, int] = (480, 160),73 *,74 font_size: int = 56,75 background: tuple[int, int, int] = PAPER,76 ink: tuple[int, int, int] = INK,77 border: tuple[int, int, int] | None = SLATE,78) -> Image.Image:79 """Image whose only content is ``text`` drawn as pixels (one or several lines)."""80 image = Image.new("RGB", size, background)81 draw = ImageDraw.Draw(image)82 lines = text.split("\n")83 font = min(84 (_fit_font(draw, line, size[0] - 40, font_size) for line in lines),85 key=lambda item: getattr(item, "size", 10),86 )87 line_height = int(getattr(font, "size", 10) * 1.35)88 top = (size[1] - line_height * len(lines)) // 289 for index, line in enumerate(lines):90 width = draw.textlength(line, font=font)91 draw.text(((size[0] - width) / 2, top + index * line_height), line, font=font, fill=ink)92 if border:93 draw.rectangle((0, 0, size[0] - 1, size[1] - 1), outline=border, width=3)94 return image959697def pattern_image(size: tuple[int, int], seed: int, label: str = "") -> Image.Image:98 """Deterministic geometric picture (stripes and discs), optionally labelled."""99 width, height = size100 image = Image.new("RGB", size, SAND)101 draw = ImageDraw.Draw(image)102 stripe = max(8, width // 12)103 for index in range(width // stripe + 1):104 if (index + seed) % 3 == 0:105 draw.rectangle(106 (index * stripe, 0, index * stripe + stripe // 2, height),107 fill=PALETTE[(index + seed) % len(PALETTE)],108 )109 radius = min(width, height) // 4110 cx = width // 2 + ((seed * 37) % 60) - 30111 draw.ellipse((cx - radius, height // 2 - radius, cx + radius, height // 2 + radius), fill=PALETTE[seed % 5])112 if label:113 font = _fit_font(draw, label, width - 20, max(12, height // 8))114 draw.rectangle((0, height - int(height * 0.22), width, height), fill=PAPER)115 draw.text((10, height - int(height * 0.2)), label, font=font, fill=INK)116 return image117118119# ---------------------------------------------------------------------------120# Image catalogue: name -> builder. PIXEL_TEXT is the OCR ground truth.121# ---------------------------------------------------------------------------122123SLIDE_WORDS = ("HERON", "MAPLE", "GLACIER", "LANTERN", "ORCHARD")124GALLERY_WORDS = ("RIVER", "FOREST", "HARBOUR", "SUMMIT")125FR_SENTENCE = "Le héron s’envole à l’aube."126PRODUCT_3_IMAGE_TEXT = "Price: $24.99"127SCAN_LINES = ("SCANNED DOCUMENT 7391", "Page numérisée sans couche texte")128129IMAGES: dict[str, Callable[[], Image.Image]] = {}130PIXEL_TEXT: dict[str, str] = {}131132133def _register(name: str, builder: Callable[[], Image.Image], pixel_text: str | None = None) -> None:134 IMAGES[name] = builder135 if pixel_text is not None:136 PIXEL_TEXT[name] = pixel_text137138139def _build_catalogue() -> None:140 for index, word in enumerate(SLIDE_WORDS, start=1):141 _register(f"slide-{index}.png", lambda w=word: text_image(w, (640, 360), font_size=96), word)142 for index, word in enumerate(GALLERY_WORDS, start=1):143 _register(f"large-{index}.png", lambda w=word: text_image(w, (800, 500), font_size=110), word)144 _register(f"thumb-{index}.png", lambda i=index: pattern_image((120, 80), i))145 for index in range(1, 11):146 text = f"LAZY IMAGE {index:02d}"147 _register(f"lazy-{index}.png", lambda t=text: text_image(t, (300, 120), font_size=34), text)148 for index in range(1, 7):149 _register(f"product-{index}.png", lambda i=index: pattern_image((320, 200), i + 10))150 _register(151 "product-3-price.png",152 lambda: text_image(PRODUCT_3_IMAGE_TEXT, (320, 90), font_size=40, background=(255, 244, 200)),153 PRODUCT_3_IMAGE_TEXT,154 )155 _register("fr-sentence.png", lambda: text_image(FR_SENTENCE, (760, 140), font_size=48), FR_SENTENCE)156 _register("photo-480.png", lambda: pattern_image((480, 270), 3, "photo 480w"))157 _register("photo-960.png", lambda: pattern_image((960, 540), 3, "photo 960w"))158 _register("art-small.png", lambda: pattern_image((400, 400), 5, "art small"))159 _register("art-large.png", lambda: pattern_image((1000, 500), 5, "art large"))160 _register("lazy-media.png", lambda: pattern_image((600, 300), 7, "lazy data-src"))161 _register("placeholder.png", lambda: Image.new("RGB", (16, 9), (221, 226, 232)))162 _register("figure-1.png", lambda: pattern_image((640, 320), 9))163 _register("favicon.png", lambda: pattern_image((32, 32), 1))164165166_build_catalogue()167168169@cache170def image_bytes(name: str) -> bytes | None:171 """PNG bytes of a catalogue image, or ``None`` when the name is unknown."""172 builder = IMAGES.get(name)173 return _png(builder()) if builder else None174175176# ---------------------------------------------------------------------------177# PDF documents, written by hand (no timestamps, fully deterministic layout).178# ---------------------------------------------------------------------------179180REPORT_PAGES: tuple[tuple[str, ...], ...] = (181 (182 "SPIDER Fixture Report",183 "Annual survey of northern weather stations, 2026 edition.",184 "Twelve stations reported complete data for the year.",185 "Mean annual temperature across the network: 3.4 degrees Celsius.",186 "Reference code: REPORT-PAGE-ONE-5521",187 ),188 (189 "Résumé en français",190 "Douze stations ont transmis des données complètes en 2026.",191 "La température moyenne du réseau s'élève à 3,4 degrés Celsius.",192 "Code de référence : REPORT-PAGE-TWO-8834",193 ),194)195196197def _pdf_string(text: str) -> bytes:198 raw = text.encode("cp1252")199 return b"(" + raw.replace(b"\\", b"\\\\").replace(b"(", b"\\(").replace(b")", b"\\)") + b")"200201202def _assemble_pdf(objects: list[bytes]) -> bytes:203 """Serialise numbered objects (1-based, object 1 is the catalog) with an xref table."""204 out = bytearray(b"%PDF-1.4\n%\xe2\xe3\xcf\xd3\n")205 offsets = []206 for number, body in enumerate(objects, start=1):207 offsets.append(len(out))208 out += f"{number} 0 obj\n".encode() + body + b"\nendobj\n"209 xref = len(out)210 out += f"xref\n0 {len(objects) + 1}\n".encode() + b"0000000000 65535 f \n"211 for offset in offsets:212 out += f"{offset:010d} 00000 n \n".encode()213 out += f"trailer\n<< /Size {len(objects) + 1} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n".encode()214 return bytes(out)215216217def _stream(data: bytes, extra: str = "") -> bytes:218 return f"<< /Length {len(data)}{extra} >>\nstream\n".encode() + data + b"\nendstream"219220221@cache222def report_pdf() -> bytes:223 """Two-page PDF with a real text layer (Helvetica, WinAnsi encoding)."""224 objects = [225 b"<< /Type /Catalog /Pages 2 0 R >>",226 b"", # page tree, filled below227 b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>",228 ]229 kids = []230 for lines in REPORT_PAGES:231 content = bytearray(b"BT\n/F1 20 Tf\n72 720 Td\n")232 for index, line in enumerate(lines):233 if index == 1:234 content += b"/F1 12 Tf\n"235 if index:236 content += b"0 -28 Td\n"237 content += _pdf_string(line) + b" Tj\n"238 content += b"ET"239 page_number = len(objects) + 1240 kids.append(f"{page_number} 0 R")241 objects.append(242 f"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] "243 f"/Resources << /Font << /F1 3 0 R >> >> /Contents {page_number + 1} 0 R >>".encode()244 )245 objects.append(_stream(bytes(content)))246 objects[1] = f"<< /Type /Pages /Kids [{' '.join(kids)}] /Count {len(kids)} >>".encode()247 return _assemble_pdf(objects)248249250@cache251def scan_pdf() -> bytes:252 """One-page PDF that is a single greyscale image: no text layer at all."""253 width, height = 850, 1100254 image = text_image("\n".join(SCAN_LINES), (width, height), font_size=54, border=None).convert("L")255 pixels = zlib.compress(image.tobytes(), 9)256 objects = [257 b"<< /Type /Catalog /Pages 2 0 R >>",258 b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>",259 (260 b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] "261 b"/Resources << /XObject << /Im0 5 0 R >> >> /Contents 4 0 R >>"262 ),263 _stream(b"q 612 0 0 792 0 0 cm /Im0 Do Q"),264 _stream(265 pixels,266 f" /Type /XObject /Subtype /Image /Width {width} /Height {height} "267 "/ColorSpace /DeviceGray /BitsPerComponent 8 /Filter /FlateDecode",268 ),269 ]270 return _assemble_pdf(objects)271272273DOCUMENTS: dict[str, Callable[[], bytes]] = {"report.pdf": report_pdf, "scan.pdf": scan_pdf}274275GZIP_BOMB_INFLATED_BYTES = 100 * 1024 * 1024276277278@cache279def gzip_bomb() -> bytes:280 """About 100 kB of gzip that inflates to exactly 100 MiB of zero bytes."""281 compressor = zlib.compressobj(9, zlib.DEFLATED, 31)282 chunk = bytes(1024 * 1024)283 parts = [compressor.compress(chunk) for _ in range(GZIP_BOMB_INFLATED_BYTES // len(chunk))]284 parts.append(compressor.flush())285 return b"".join(parts)286