File size: 6,029 Bytes
1bdce62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
#!/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="<slug>"` in poster.html become
    accessible click targets (real <a> 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 = """<!doctype html>
<meta charset="utf-8">
<title>Reproduction poster</title>
<style>
  .lb-poster {{ position: relative; margin: 0 auto; max-width: 100%; line-height: 0; }}
  .lb-poster img {{ width: 100%; height: auto; display: block; }}
  .lb-hot {{
    position: absolute; display: block; border-radius: 10px; text-decoration: none;
    border: 2px solid transparent; transition: background .15s, border-color .15s;
  }}
  .lb-hot:hover, .lb-hot:focus-visible {{
    background: rgba(37, 99, 235, .13); border-color: rgba(37, 99, 235, .85);
    outline: none;
  }}
  .lb-pill {{
    position: absolute; right: 8px; bottom: 8px; line-height: 1.4;
    font: 600 12px/1.4 system-ui, -apple-system, "Segoe UI", sans-serif;
    padding: 3px 9px; border-radius: 999px; white-space: nowrap;
    background: rgba(15, 23, 42, .72); color: #fff; opacity: .82;
    transition: opacity .15s, background .15s;
  }}
  .lb-hot:hover .lb-pill, .lb-hot:focus-visible .lb-pill {{
    opacity: 1; background: rgba(37, 99, 235, .95);
  }}
  @media (prefers-reduced-motion: reduce) {{ .lb-hot, .lb-pill {{ transition: none; }} }}
</style>
<div class="lb-poster">
  <img src="data:image/png;base64,{b64}" alt="{alt}">
{hotspots}
</div>
"""

HOTSPOT = (
    '  <a class="lb-hot" href="#/{slug}" title="{label}" '
    'aria-label="Open logbook page: {label}" '
    'style="left:{left:.3f}%;top:{top:.3f}%;width:{width:.3f}%;height:{height:.3f}%">'
    '<span class="lb-pill">Open details ↗</span></a>'
)


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('"', "&quot;")}) 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())