{E(ex["title"])}
' f'{E(ex["shows"])}
' f'{headline}' f'details
' f'teaches{E(ex["teaches"])}
' f'"""The example gallery: one card per ability of the decider, click to fill the ask bar and run.
Data lives in examples/examples.json (+ images); the look in static/examples.css; the click
handling in static/examples.js. `app.py` renders `gallery_html()` above the status line and
listens on a hidden textbox for the clicked id. Nothing here touches answer().
Public API
load_examples() -> dict (the parsed examples.json, measured blocks included)
gallery_html() -> str (server-rendered gallery; static/examples.js makes it clickable)
example_by_id(id) -> dict | None
fill_values(ex, registry) -> dict with everything the ask bar needs to be filled from one example:
state, questions[{type, instructions, options}], image (str path|None -- a path, not PIL: see fill_values),
models (list[str] -- ONLY the vision models for vision_only examples)
CSS / JS -> file contents for app.py to append to its launch(css=, js=)
Standalone preview: python examples.py --demo [--dark|--light] > demo.html
"""
from __future__ import annotations
import base64
import html
import json
import re
import sys
from pathlib import Path
from typing import Any
HERE = Path(__file__).resolve().parent
EX_DIR = HERE / "examples"
EX_JSON = EX_DIR / "examples.json"
STATIC = HERE / "static"
_CACHE: dict | None = None
def load_examples() -> dict:
"""Parsed examples.json (cached)."""
global _CACHE
if _CACHE is None:
_CACHE = json.loads(EX_JSON.read_text())
return _CACHE
def example_by_id(ex_id: str) -> dict | None:
"""The example record with this id, or None."""
return next((e for e in load_examples()["examples"] if e["id"] == ex_id), None)
def image_path(ex: dict) -> Path | None:
"""Absolute path of the example's image, if it has one."""
return (EX_DIR / ex["image"]) if ex.get("image") else None
def fill_values(ex: dict, registry: list[Any] | None = None) -> dict:
"""Everything the ask bar needs. `registry` = app.REGISTRY (ModelInfo with .name/.vision)."""
# The image goes to the gr.Image component as a FILE PATH, never as a PIL object: gr.Image's
# default output format is lossy WebP (gradio 6.30: Image().format == "webp"), and a PIL value
# is re-encoded through it before the model sees it. MEASURED: form_signed.png as PIL -> model
# read P(true) 0.5510; the precomputed answer on the original bytes is 0.6868. A path is served as-is.
img: str | None = None
p = image_path(ex)
if p is not None:
img = str(p)
models: list[str] | None = None
if registry is not None:
if ex.get("vision_only"):
models = [m.name for m in registry if getattr(m, "vision", False)]
else:
models = [m.name for m in registry]
return {
"id": ex["id"],
"state": ex.get("state", ""),
"questions": [dict(q) for q in ex["questions"]],
"image": img,
"models": models,
"vision_only": bool(ex.get("vision_only")),
}
# ---------------------------------------------------------------------------------
# rendering
# ---------------------------------------------------------------------------------
E = html.escape
_TYPE_LABEL = {"noul": "yes/no", "choice": "choice", "score": "score"}
def _thumb(ex: dict) -> str:
"""Inline 96 px thumbnail of the example image (data URI), or an empty string."""
p = image_path(ex)
if p is None or not p.exists():
return ""
b64 = base64.b64encode(p.read_bytes()).decode("ascii")
return (f'')
def _fmt(v: Any, nd: int = 3) -> str:
"""Fixed-point text; non-numbers are escaped as-is."""
try:
return f"{float(v):.{nd}f}"
except (TypeError, ValueError):
return E(str(v))
def _answer_html(qid: str, a: dict, q: dict | None) -> str:
"""One measured answer -> value line + mini distribution. Numbers are read, never computed."""
t = a.get("type") or (q or {}).get("type") or ""
conf = a.get("confidence")
probs = a.get("probs") or {}
display = a.get("display", a.get("value"))
if t == "noul":
p = probs.get("true", probs.get("yes"))
if p is None:
try:
p = float(display)
except (TypeError, ValueError):
p = None
pct = f"{p * 100:.1f}" if isinstance(p, float) else "0"
head = f'P(true){_fmt(p, 4) if p is not None else E(str(display))}'
bar = (f'
{E(ex["state"])}(empty — the image is the state)
{E(ex["shows"])}
' f'{headline}' f'teaches{E(ex["teaches"])}
' f'