#!/usr/bin/env python3
"""Build poster_embed.html for the Trackio logbook.
posterly ships no logbook-embed generator, so this reproduces the behaviour the
ICML-2026 challenge guide specifies:
* the poster image is inlined as a data-URI, so the cell is self-contained
* sections marked `data-logbook-target=""` in poster.html become
accessible click targets (real elements, keyboard reachable)
* hovering/focusing highlights a target; an "Open details" pill is visible
before hover so the affordance is discoverable
* an unknown slug is rejected rather than silently emitted
Hotspot geometry is measured in the same print-emulated Chromium posterly uses
for its `measure` gate, then stored as percentages so the embed scales freely.
Usage:
python3 make_embed.py poster.html poster.png ../.trackio/logbook/logbook.json \
-o poster_embed.html
"""
from __future__ import annotations
import argparse
import base64
import json
import pathlib
import sys
def known_slugs(logbook_json: pathlib.Path) -> set[str]:
"""Page slugs actually present in the logbook (walks the `root` page tree)."""
data = json.loads(logbook_json.read_text())
slugs: set[str] = set()
def walk(node):
if not isinstance(node, dict):
return
if isinstance(node.get("slug"), str):
slugs.add(node["slug"])
for child in node.get("children") or []:
walk(child)
walk(data.get("root"))
if not slugs: # fall back to the on-disk page directories
pages_dir = logbook_json.parent / "pages"
slugs = {p.name for p in pages_dir.iterdir() if p.is_dir()}
return slugs
def measure(poster_html: pathlib.Path) -> list[dict]:
"""Bounding boxes of [data-logbook-target] as fractions of the poster box."""
from playwright.sync_api import sync_playwright
url = poster_html.resolve().as_uri()
with sync_playwright() as pw:
browser = pw.chromium.launch()
page = browser.new_page(viewport={"width": 2400, "height": 1600})
page.emulate_media(media="print")
page.goto(url, wait_until="networkidle")
boxes = page.evaluate(
"""() => {
const root = document.querySelector('.poster') || document.body;
const R = root.getBoundingClientRect();
return [...document.querySelectorAll('[data-logbook-target]')].map(el => {
const b = el.getBoundingClientRect();
const t = el.querySelector('h1,h2,h3,h4,.card-title,.sec-title');
return {
slug: el.getAttribute('data-logbook-target'),
label: (t ? t.textContent : el.textContent).trim()
.replace(/\\s+/g, ' ').slice(0, 90),
left: (b.left - R.left) / R.width * 100,
top: (b.top - R.top) / R.height * 100,
width: b.width / R.width * 100,
height: b.height / R.height * 100,
};
});
}"""
)
browser.close()
return boxes
TEMPLATE = """
Reproduction poster

{hotspots}
"""
HOTSPOT = (
' '
'Open details ↗'
)
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("poster_html", type=pathlib.Path)
ap.add_argument("poster_png", type=pathlib.Path)
ap.add_argument("logbook_json", type=pathlib.Path)
ap.add_argument("-o", "--out", type=pathlib.Path, default=pathlib.Path("poster_embed.html"))
args = ap.parse_args()
valid = known_slugs(args.logbook_json)
boxes = measure(args.poster_html)
bad = sorted({b["slug"] for b in boxes} - valid)
if bad:
print(f"ERROR: unknown logbook slug(s): {bad}", file=sys.stderr)
print(f" known slugs: {sorted(valid)}", file=sys.stderr)
return 1
b64 = base64.b64encode(args.poster_png.read_bytes()).decode()
html = TEMPLATE.format(
b64=b64,
alt="Reproduction poster: Beyond First-order Asymptotics in Sequential Mean Testing",
hotspots="\n".join(
HOTSPOT.format(**{**b, "label": b["label"].replace('"', """)}) for b in boxes
),
)
args.out.write_text(html)
print(f"wrote {args.out} ({len(html)/1024:.0f} KB, {len(boxes)} hotspots)")
for b in boxes:
print(f" -> {b['slug']:70s} {b['label'][:45]}")
if not boxes:
print(" (no data-logbook-target sections; embed has no hotspot buttons)")
return 0
if __name__ == "__main__":
raise SystemExit(main())