File size: 35,372 Bytes
a39d07d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
"""Stage-by-stage HTML view of an InversionRun: the Space's run explorer.

`render_explorer` turns a run (finished or still streaming) into one HTML string:
a header (status, step counter, playback controls, a navigator grouped by phase)
followed by one panel per stage:

    Setup:       Extract scene graph -> Ground on original
    Iteration t: Render proxy -> Verify -> Rewrite failures (absent when the run stopped at t)
    Result:      Verified prompt

Panels are derived from the run itself, so the number of stages follows the run.
Every model-produced string is HTML-escaped. Images are referenced through the
`image_url` callback, so callers decide how renders are served. Navigation, the
metric popovers and Copy are handled client-side by app/explorer.js; this module
only emits markup and data-* hooks, and needs no Gradio.
"""

from __future__ import annotations

import difflib
import html
import re
from dataclasses import dataclass
from typing import Callable

from PIL import Image

from .compiler import ScoredPredicate, compile_predicates
from .engine import InversionRun, IterationRecord
from .schema import GRID_ORDER

LIVE, DONE, PENDING = "live", "done", "pending"


def esc(value) -> str:
    return html.escape(str(value), quote=True)


def _short(model_id: str | None, fallback: str) -> str:
    return str(model_id).rsplit("/", 1)[-1] if model_id else fallback


def _dino_name(models: dict) -> str:
    mid = str(models.get("dino_model", "")).lower()
    return "DINOv3" if "dinov3" in mid else "DINOv2" if "dinov2" in mid else "DINO"


def _plural(n: int, word: str) -> str:
    return f"{n} {word}{'' if n == 1 else 's'}"


# --------------------------------------------------------------------------- icons

def _svg(paths: str, size: int = 16, stroke: str = "currentColor", width: float = 2) -> str:
    return (f'<svg width="{size}" height="{size}" viewBox="0 0 24 24" fill="none" stroke="{stroke}" '
            f'stroke-width="{width}" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">{paths}</svg>')


ICON_CHECK = _svg('<path d="M20 6 9 17l-5-5"/>', 14, width=2.5)
ICON_DOWN = _svg('<path d="M12 5v14"/><path d="m19 12-7 7-7-7"/>', 12, width=2.5)
ICON_PREV = _svg('<path d="m15 18-6-6 6-6"/>', 18)
ICON_NEXT = _svg('<path d="m9 18 6-6-6-6"/>', 18)
ICON_ARROW = _svg('<path d="M5 12h14"/><path d="m13 6 6 6-6 6"/>', 16)
ICON_PAUSE = _svg('<path d="M9 5v14"/><path d="M15 5v14"/>')
ICON_PLAY = _svg('<path d="M7 4.5v15l12-7.5z"/>')
ICON_REPLAY = _svg('<path d="M3 12a9 9 0 1 0 3-6.7L3 8"/><path d="M3 3v5h5"/>')
ICON_COPY = _svg('<rect x="9" y="9" width="12" height="12" rx="2"/>'
                 '<path d="M5 15H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v1"/>')
ICON_DOWNLOAD = _svg('<path d="M12 3v12"/><path d="m7 10 5 5 5-5"/><path d="M5 21h14"/>')
ICON_CHEVRON = _svg('<path d="m6 9 6 6 6-6"/>', 14)


# --------------------------------------------------------------------------- prompt diff

_TOKEN = re.compile(r"\w+|[^\w\s]+|\s+")


def diff_html(old: str, new: str) -> str:
    """Word-level diff of two prompts: inserted text in <ins>, removed text in <del>."""
    a, b = _TOKEN.findall(old), _TOKEN.findall(new)
    out = []
    for op, i1, i2, j1, j2 in difflib.SequenceMatcher(a=a, b=b, autojunk=False).get_opcodes():
        removed, added = "".join(a[i1:i2]), "".join(b[j1:j2])
        if op == "equal":
            out.append(esc(added))
            continue
        if removed.strip():
            out.append(f"<del>{esc(removed)}</del>")
        if added.strip():
            out.append(f"<ins>{esc(added)}</ins>")
        elif added:
            out.append(esc(added))
    return "".join(out)


# --------------------------------------------------------------------------- stage model

@dataclass
class _Stage:
    key: str
    group: str
    label: str
    state: str
    desc: str = ""
    chip: str = ""  # escaped HTML for the header's right side
    body: str = ""
    footer: str = ""
    next_label: str = ""


def _prompt_for(run: InversionRun, t: int) -> str:
    """The prompt rendered at iteration t (1-based), including the iteration in progress."""
    if t <= len(run.iterations):
        return run.iterations[t - 1].prompt
    if t == 1 or not run.iterations:
        return run.canonical_prompt
    prev = run.iterations[t - 2]
    return prev.patch.prompt if prev.patch else prev.prompt


def _status_of(sp: ScoredPredicate, fail_threshold: float) -> str:
    if sp.blocked_by:
        return "blocked"
    return "pass" if sp.effective >= fail_threshold else "fail"


def _gates_met(run: InversionRun, vqa: float, dino: float) -> bool:
    cfg = run.config
    return vqa >= cfg.vqa_gate and dino >= cfg.dino_gate


# --------------------------------------------------------------------------- building blocks

def _skeleton(text: str) -> str:
    return f'<div class="pre-x-skel" role="status"><span class="pre-x-spin" aria-hidden="true"></span>{esc(text)}</div>'


def _figure(url: str | None, alt: str, aspect: tuple[int, int], *, caption: str = "", overlay: str = "",
            cls: str = "", badge: str = "", waiting: str = "Rendering…") -> str:
    w, h = aspect
    inner = (f'<img src="{esc(url)}" alt="{esc(alt)}" loading="lazy">' if url
             else f'<div class="pre-x-wait">{_skeleton(waiting)}</div>')
    badge_html = f'<span class="pre-x-best">{esc(badge)}</span>' if badge else ""
    cap = f"<figcaption>{caption}</figcaption>" if caption else ""
    return (f'<figure class="pre-x-fig {cls}"><div class="pre-x-imgbox" style="aspect-ratio:{w} / {h}">'
            f"{inner}{overlay}{badge_html}</div>{cap}</figure>")


def _cell_box(cell: str, label: str, cls: str, *, strike: bool = False) -> str:
    row, col = divmod(GRID_ORDER.index(cell), 3)
    tag = f"<s>{esc(label)}</s>" if strike else esc(label)
    return (f'<div class="pre-x-cell {cls}" style="left:{col * 33.3333:.4f}%;top:{row * 33.3333:.4f}%">'
            f'<span class="pre-x-tag">{tag}</span></div>')


GRID_LINES = "".join(f'<div class="pre-x-gl {axis}" style="{side}:{pos}%"></div>'
                     for axis, side in (("v", "left"), ("h", "top")) for pos in ("33.3333", "66.6667"))


def _badge(kind: str, text: str) -> str:
    return f'<span class="pre-x-b {kind}">{esc(text)}</span>'


def _row(title: str, detail: str, badge: str, detail_cls: str = "") -> str:
    cls = f' class="{detail_cls}"' if detail_cls else ""
    return (f'<div class="pre-x-row"><div class="pre-x-row-text"><span class="pre-x-row-title">{title}</span>'
            f"<span{cls}>{detail}</span></div>{badge}</div>")


def _toggle(target: str, label_off: str, label_on: str, cls: str = "pre-x-link") -> str:
    return (f'<button type="button" class="{cls}" data-act="toggle" aria-controls="{target}" aria-expanded="false" '
            f'data-on="{esc(label_on)}" data-off="{esc(label_off)}"><span data-role="label">{esc(label_off)}</span>'
            f"{ICON_CHEVRON}</button>")


def _sign(d: float) -> str:
    return ("+" if d >= 0 else "−") + f"{abs(d):.2f}"


def _tile(pid: str, label: str, score: float, digits: int, gate: float | None, note: str, title: str,
          body: str, no_gate_pill: str, no_gate_line: str) -> str:
    has_gate = gate is not None and gate > 0
    ok = has_gate and score >= gate
    cls = "none" if not has_gate else "ok" if ok else "warn"
    if has_gate:
        pill = f"{ICON_CHECK if ok else ICON_DOWN}{'Meets gate' if ok else 'Below gate'} {_sign(score - gate)}"
        gate_line = f"Gate {gate:.2f} · stops the run when met"
        gate_mark = f'<div class="pre-x-meter-gate" style="left:{gate * 100:.0f}%"></div>'
        legend = ('<div class="pre-x-legend"><span class="ok"><i></i>At or above gate</span>'
                  '<span class="warn"><i></i>Below gate</span></div>')
    else:
        pill, gate_line, gate_mark, legend = esc(no_gate_pill), no_gate_line, "", ""
    pct = max(0.0, min(1.0, score)) * 100
    return (
        f'<div class="pre-x-tile {cls}">'
        f'<div class="pre-x-tile-top"><span class="pre-x-tile-label">{esc(label)}</span>'
        f'<button type="button" class="pre-x-help" data-act="toggle" aria-controls="{pid}" aria-expanded="false" '
        f'aria-label="What does {esc(label)} measure?"><span aria-hidden="true">?</span></button></div>'
        f'<div class="pre-x-tile-val"><span class="pre-x-num">{score:.{digits}f}</span>'
        f'<span class="pre-x-note">{esc(note)}</span></div>'
        f'<div class="pre-x-meter"><div class="pre-x-meter-fill" style="width:{pct:.0f}%"></div>{gate_mark}</div>'
        f'<span class="pre-x-pill">{pill}</span>'
        f'<div class="pre-x-pop" id="{pid}" role="region" aria-label="{esc(title)}" hidden>'
        f'<div class="pre-x-pop-title">{esc(title)}</div><p>{esc(body)}</p>'
        f'<div class="pre-x-pop-gate">{esc(gate_line)}</div>{legend}'
        f'<button type="button" class="pre-x-btn sm" data-act="toggle" aria-controls="{pid}">Close</button>'
        f"</div></div>"
    )


# --------------------------------------------------------------------------- stages

def _extract_stage(run: InversionRun, og_url: str, aspect: tuple[int, int]) -> _Stage:
    vlm = _short(run.models.get("vlm_model"), "VLM")
    stage = _Stage("extract", "Setup", "Extract scene graph", LIVE if run.raw_graph is None else DONE,
                   desc="The VLM reads the original and writes medium, palette and every object as a node "
                        "on a 3 × 3 grid.",
                   chip=esc(vlm), next_label="Ground on original")
    g = run.raw_graph
    if g is None:
        stage.body = (f'<div class="pre-x-split">{_figure(og_url, "Original image", aspect)}'
                      f'<div class="pre-x-col">{_skeleton("Extracting the scene graph…")}</div></div>')
        stage.footer = "Extracting…"
        return stage
    cells: dict[str, list[str]] = {}
    for node in g.nodes:
        cells.setdefault(node.grid_cell, []).append(node.id)
    overlay = "".join(_cell_box(cell, ", ".join(ids), "node") for cell, ids in cells.items())
    chips = "".join(f'<span class="pre-x-chiplet">{esc(c)}</span>' for c in g.color_palette) or "—"
    checks = (f"<dt>Checks</dt><dd>{' · '.join(esc(c) for c in g.extra_checks)}</dd>" if g.extra_checks else "")
    rows = []
    for node in g.nodes:
        rels = "; ".join(f"{r.predicate} {r.target_id}" for r in node.relations)
        detail = ", ".join(node.attributes) + (f"; {rels}" if rels else "")
        rows.append(f'<tr><td class="mono">{esc(node.id)}</td><td>{esc(node.entity)}</td>'
                    f'<td>{esc(node.grid_cell)}</td><td class="muted">{esc(detail) or "—"}</td></tr>')
    stage.body = (
        f'<div class="pre-x-split">'
        f'{_figure(og_url, "Original with each node outlined in its grid cell", aspect, overlay=overlay)}'
        f'<div class="pre-x-col">'
        f'<dl class="pre-x-dl"><dt>Medium</dt><dd>{" · ".join(esc(m) for m in g.medium_and_optics) or "—"}</dd>'
        f"<dt>Background</dt><dd>{esc(g.background) or '—'}</dd>"
        f'<dt>Palette</dt><dd class="pre-x-chips">{chips}</dd>{checks}</dl>'
        f'<div class="pre-x-tablewrap"><table class="pre-x-table"><thead><tr><th>Node</th><th>Entity</th>'
        f'<th>Grid cell</th><th>Attributes and relations</th></tr></thead><tbody>{"".join(rows)}</tbody></table></div>'
        f'<div>{_toggle("pre-x-json", "View raw JSON", "Hide raw JSON")}'
        f'<pre class="pre-x-json" id="pre-x-json" hidden>{esc(g.model_dump_json(indent=2))}</pre></div>'
        f"</div></div>"
    )
    stage.footer = (f"{_plural(len(g.nodes), 'node')} → "
                    f"{_plural(len(compile_predicates(g)), 'candidate predicate')} compiled")
    return stage


def _ground_stage(run: InversionRun, og_url: str, aspect: tuple[int, int]) -> _Stage:
    cfg = run.config
    if run.raw_graph is None:
        state = PENDING
    elif run.phase in ("ground", "relocalize"):
        state = LIVE
    else:
        state = DONE
    stage = _Stage("ground", "Setup", "Ground on original", state,
                   desc="Each candidate predicate is scored on the original. Facts it rejects are dropped "
                        "before anything is rendered.",
                   chip="VQA scorer", next_label="Render proxy")
    if state != DONE:
        text = ("Re-localizing entities whose grid cell was rejected…" if run.phase == "relocalize"
                else "Scoring every candidate predicate on the original…")
        stage.body = (f'<div class="pre-x-split">{_figure(og_url, "Original image", aspect)}'
                      f'<div class="pre-x-col">{_skeleton(text)}</div></div>')
        stage.footer = "Grounding…" if state == LIVE else ""
        return stage
    if not cfg.ground:
        stage.body = (f'<div class="pre-x-split">{_figure(og_url, "Original image", aspect)}'
                      f'<div class="pre-x-col"><p class="pre-x-note-box">Grounding is off for this run: all '
                      f"{_plural(len(run.predicates), 'candidate predicate')} were kept without checking them "
                      f"on the original.</p></div></div>")
        stage.footer = f"{_plural(len(run.predicates), 'predicate')} → prompt v1"
        return stage
    overlay = GRID_LINES + "".join(
        _cell_box(m["from"], m["from"], "from", strike=True) + _cell_box(m["to"], m["to"], "to")
        for m in run.relocalized)
    tiles = "".join(
        f'<div class="pre-x-count{" kept" if key == "Kept" else ""}"><span>{key}</span><b>{n}</b></div>'
        for key, n in (("Candidates", len(run.grounding)), ("Removed", len(run.dropped)),
                       ("Moved", len(run.relocalized)), ("Kept", len(run.predicates))))
    rows = [_row(esc(sp.predicate.statement),
                 f"{esc(sp.predicate.kind)} · P(yes) {sp.raw:.2f} on the original", _badge("removed", "Removed"))
            for sp in run.dropped]
    rows += [_row(esc(m["entity"]), f"position · {esc(m['from'])} → {esc(m['to'])} · P(yes) {m['p_yes']:.2f}",
                  _badge("moved", "Re-localized")) for m in run.relocalized]
    listing = "".join(rows) or '<p class="pre-x-note-box">Every candidate held on the original; nothing was removed.</p>'
    stage.body = (
        f'<div class="pre-x-split">'
        f'{_figure(og_url, "Original on a 3 by 3 grid with re-localized cells marked", aspect, overlay=overlay)}'
        f'<div class="pre-x-col"><div class="pre-x-counts">{tiles}</div>'
        f'<div class="pre-x-rows">{listing}</div>'
        f'<p class="pre-x-fine">Pruned when P(yes) on the original &lt; {cfg.grounding_threshold:.2f}.</p></div></div>'
    )
    stage.footer = f"{_plural(len(run.predicates), 'grounded predicate')} → prompt v1"
    return stage


def _render_stage(run: InversionRun, t: int, og_url: str, aspect: tuple[int, int],
                  image_url: Callable[[Image.Image], str]) -> _Stage:
    cfg = run.config
    it = run.iterations[t - 1] if t <= len(run.iterations) else None
    image = it.proxy_image if it else (run.live_proxy if run.phase_t == t else None)
    state = DONE if image is not None else LIVE
    seed = it.seed if it else cfg.base_seed + t - 1
    proxy = _short(run.models.get("proxy_model"), "proxy")
    stage = _Stage(f"render-{t}", f"Iteration {t}", "Render proxy", state,
                   desc=f"Prompt v{t} goes to the proxy generator. The render is what the prompt actually produces.",
                   chip=f'<span class="pre-x-chip mono">{esc(proxy)} · seed {seed}</span>', next_label="Verify")
    steps = run.models.get("proxy_steps")
    render_cap = (f'<span class="pre-x-cap"><b>Render · t = {t}</b>'
                  f'<span class="mono muted">{f"{steps} steps" if steps else ""}</span></span>')
    figs = (_figure(og_url, "Original image", aspect, caption='<span class="pre-x-cap"><b>Original</b>'
                    '<span class="muted">target</span></span>')
            + _figure(image_url(image) if image is not None else None, f"Proxy render, iteration {t}", aspect,
                      caption=render_cap, cls="current"))
    stage.body = (f'<div class="pre-x-stack"><div class="pre-x-pair">{figs}</div>'
                  f'<div class="pre-x-block"><div class="pre-x-block-head"><h3>Prompt v{t}</h3>'
                  f'<span class="muted">{_plural(len(run.predicates), "grounded predicate" if cfg.ground else "predicate")}'
                  f"</span></div>"
                  f'<p class="pre-x-prompt">{esc(_prompt_for(run, t))}</p></div></div>')
    w, h = run.proxy_wh or aspect
    stage.footer = f"Render complete · {w} × {h}" if state == DONE else "Rendering…"
    return stage


def _verify_stage(run: InversionRun, t: int, idx: int) -> _Stage:
    cfg = run.config
    it = run.iterations[t - 1] if t <= len(run.iterations) else None
    dino_name = _dino_name(run.models)
    stage = _Stage(f"verify-{t}", f"Iteration {t}", "Verify", DONE if it else LIVE,
                   desc=f"Every grounded predicate is asked of the render, and layout is compared with {dino_name}.")
    if it is None:
        stage.chip = '<span class="pre-x-chip-plain">Scoring…</span>'
        stage.body = _skeleton(f"Scoring {_plural(len(run.predicates), 'predicate')} and the layout…")
        stage.footer = "Verifying…"
        return stage
    met = _gates_met(run, it.mean_vqa, it.dino_patch)
    verdict = ("Both gates met" if cfg.dino_gate > 0 else "S_VQA gate met") if met else "Gates not met"
    stage.chip = (f'<span class="pre-x-verdict {"ok" if met else "warn"}">'
                  f'{ICON_CHECK if met else ""}{esc(verdict)}</span>')
    vqa_body = ("Share of the checkable facts in the prompt (shapes, colors, positions, relations) that a "
                "vision-language model judges true of the render. Each fact is scored by the model’s "
                "probability of answering “yes”; a fact whose object is missing counts as 0.")
    dino_body = (f"How closely the render’s layout matches the original. Both images are compared patch by "
                 f"patch with {dino_name} features and the cosine similarities are averaged; 1.00 means identical. "
                 f"The score drops when shapes move, resize or flip left to right.")
    joint_body = (f"A weighted blend used to pick the best iteration: {cfg.w_vqa:g} × S_VQA + {cfg.w_dino:g} × "
                  f"S_DINO (the weights are in Advanced settings). It has no gate and never stops the run.")
    best_note = f"best of {len(run.iterations)}" if run.best is it and run.phase == "done" else f"iteration {t}"
    tiles = (
        _tile(f"pre-x-help-{idx}-vqa", "Predicate agreement · S_VQA", it.mean_vqa, 2, cfg.vqa_gate,
              f"gate {cfg.vqa_gate:.2f}", "Predicate agreement (S_VQA)", vqa_body, "No gate", "No gate")
        + _tile(f"pre-x-help-{idx}-dino", "Layout similarity · S_DINO", it.dino_patch, 2, cfg.dino_gate,
                f"gate {cfg.dino_gate:.2f}" if cfg.dino_gate > 0 else "gate off", "Layout similarity (S_DINO)",
                dino_body, "Gate off", "Gate off · the run stops on S_VQA alone")
        + _tile(f"pre-x-help-{idx}-joint", "Joint score", it.joint, 3, None, best_note, "Joint score",
                joint_body, "Picks the best iteration", "No gate"))
    order = {"fail": 0, "blocked": 1, "pass": 2}
    scored = sorted(it.scored, key=lambda sp: (order[_status_of(sp, cfg.fail_threshold)], sp.raw))
    counts = {k: sum(_status_of(sp, cfg.fail_threshold) == k for sp in scored) for k in order}
    first = counts["fail"] + counts["blocked"] + min(3, counts["pass"])
    labels = {"fail": "Fail", "blocked": "Blocked", "pass": "Pass"}

    def tr(sp: ScoredPredicate) -> str:
        status = _status_of(sp, cfg.fail_threshold)
        badge = _badge(status, labels[status] if status != "blocked" else
                       "Blocked by " + ", ".join(b.split(":", 1)[-1] for b in sp.blocked_by))
        return (f'<tr><td class="muted">{esc(sp.predicate.kind)}</td><td>{esc(sp.predicate.statement)}</td>'
                f'<td class="mono">{sp.raw:.2f}</td><td>{badge}</td></tr>')

    rest = scored[first:]
    more_id = f"pre-x-more-{idx}"
    more_body = f'<tbody id="{more_id}" hidden>{"".join(tr(sp) for sp in rest)}</tbody>' if rest else ""
    more_btn = (_toggle(more_id, f"Show all {len(scored)} predicates", "Show fewer") if rest else "")
    table = (f'<div class="pre-x-tablewrap"><table class="pre-x-table"><thead><tr><th>Kind</th><th>Predicate</th>'
             f'<th>P(yes)</th><th>Status</th></tr></thead><tbody>{"".join(tr(sp) for sp in scored[:first])}</tbody>'
             f"{more_body}</table></div>")
    fine = (f'<p class="pre-x-fine">{counts["fail"]} failed · {counts["blocked"]} blocked · {counts["pass"]} passed'
            f" · failure threshold P(yes) &lt; {cfg.fail_threshold:.2f}</p>")
    stage.body = (f'<div class="pre-x-stack"><div class="pre-x-tiles">{tiles}</div>{table}'
                  f'<div class="pre-x-tablefoot">{fine}{more_btn}</div></div>')

    def cmp(v: float, g: float) -> str:
        return f"{v:.2f} {'≥' if v >= g else '<'} {g:.2f}"

    last = t == len(run.iterations)
    if last and run.stop_reason == "converged":
        then = "stop"
    elif last and run.stop_reason == "max_iters" and run.best is not None:
        then = f"max iterations reached → return best (t = {run.best.t})"
    else:
        then = "rewrite"
    dino_part = f"S_DINO {cmp(it.dino_patch, cfg.dino_gate)}" if cfg.dino_gate > 0 else "S_DINO gate off"
    stage.footer = f"S_VQA {cmp(it.mean_vqa, cfg.vqa_gate)} · {dino_part} → {then}"
    stage.next_label = "Rewrite failures" if then == "rewrite" else "Verified prompt"
    return stage


def _rewrite_stage(run: InversionRun, it: IterationRecord) -> _Stage:
    cfg, t = run.config, it.t
    live = it.patch is None and it.rewrite_error is None
    stage = _Stage(f"rewrite-{t}", f"Iteration {t}", "Rewrite failures", LIVE if live else DONE,
                   desc="Only the clauses behind failed predicates change. Everything that passed is left word "
                        "for word.", next_label="Render proxy")
    if live:
        stage.chip = '<span class="pre-x-chip-plain">Rewriting…</span>'
        stage.body = _skeleton(f"Rewriting {_plural(len(it.failed), 'failed predicate')}…")
        stage.footer = "Rewriting…"
        return stage
    sent = [_row(esc(sp.predicate.statement), f"P(yes) {sp.raw:.2f}", _badge("fail", "Failed"), "warn mono")
            for sp in it.failed]
    if it.dino_patch < cfg.dino_gate:
        sent.append(_row("Overall layout", f"S_DINO {it.dino_patch:.2f} &lt; {cfg.dino_gate:.2f}",
                         _badge("fail", "Below gate"), "warn mono"))
    edits: list[str] = []
    if it.patch is not None:
        for ed in it.patch.applied:
            edits.append(_row(f'<span class="mono">{esc(ed["original"])}</span>',
                              f'<span class="mono">→ {esc(ed["revised"])}</span>', _badge("moved", "Edited")))
        for sentence in it.patch.added:
            edits.append(_row(f'<span class="mono">+ {esc(sentence)}</span>', "new sentence",
                              _badge("moved", "Added")))
        for sk in it.patch.skipped:
            text = sk.get("original") or sk.get("addition") or ""
            edits.append(_row(f'<span class="mono">{esc(text)}</span>', esc(sk.get("reason", "")),
                              _badge("removed", "Skipped")))
    if it.rewrite_error:
        edits.append(f'<p class="pre-x-error">The rewriter failed: {esc(it.rewrite_error)}. The next iteration '
                     f"re-renders the same prompt with a new seed.</p>")
    applied = len(it.patch.applied) if it.patch else 0
    added = len(it.patch.added) if it.patch else 0
    skipped = len(it.patch.skipped) if it.patch else 0
    stage.chip = esc(f"{_plural(applied, 'edit')} · {added} added" + (f" · {skipped} skipped" if skipped else ""))
    new_prompt = it.patch.prompt if it.patch else it.prompt
    stage.body = (
        f'<div class="pre-x-stack">'
        f'<div class="pre-x-block"><div class="pre-x-block-head"><h3>Sent to the rewriter</h3></div>'
        f'<div class="pre-x-rows">{"".join(sent) or "<p class=pre-x-note-box>No failed predicates.</p>"}</div></div>'
        f'<div class="pre-x-block"><div class="pre-x-block-head"><h3>Edits</h3></div>'
        f'<div class="pre-x-rows">{"".join(edits) or "<p class=pre-x-note-box>No edits.</p>"}</div></div>'
        f'<div class="pre-x-block"><div class="pre-x-block-head"><h3>Prompt v{t + 1}</h3>'
        f'<span class="muted">changes highlighted</span></div>'
        f'<p class="pre-x-prompt diff">{diff_html(it.prompt, new_prompt)}</p></div></div>'
    )
    stage.footer = f"Iteration {t + 1} uses prompt v{t + 1} and seed {cfg.base_seed + t}"
    return stage


def _result_stage(run: InversionRun, og_url: str, aspect: tuple[int, int],
                  image_url: Callable[[Image.Image], str], report_url: str | None) -> _Stage:
    done = run.phase == "done" and run.best is not None
    stage = _Stage("result", "Result", "Verified prompt", DONE if done else PENDING)
    if not done:
        stage.body = _skeleton("The verified prompt appears when the run finishes.")
        return stage
    best, n = run.best, len(run.iterations)
    stage.desc = (f"From iteration {best.t} of {n} · {_plural(len(run.predicates), 'predicate')} "
                  f"grounded on the original")
    report = (f'<a class="pre-x-btn" href="{esc(report_url)}" download="inversion_report.json">'
              f"{ICON_DOWNLOAD}Report (JSON)</a>" if report_url else "")
    stage.chip = (f'<div class="pre-x-actions"><button type="button" class="pre-x-btn" data-act="copy" '
                  f'data-src="pre-x-final">{ICON_COPY}<span data-role="label">Copy</span></button>{report}</div>')
    proxy = _short(run.models.get("proxy_model"), "proxy")
    figs = [_figure(og_url, "Original image", aspect,
                    caption='<span class="pre-x-cap"><b>Original</b><span class="muted">target</span></span>')]
    for it in run.iterations:
        figs.append(_figure(image_url(it.proxy_image), f"Proxy render, iteration {it.t}", aspect,
                            caption=f'<span class="pre-x-cap"><b>t = {it.t}</b><span class="mono muted">'
                                    f"VQA {it.mean_vqa:.2f} · DINO {it.dino_patch:.2f}</span></span>",
                            cls="current" if it is best else "", badge="Best" if it is best else ""))
    rows = []
    for it in run.iterations:
        if it.rewrite_error:
            rewrite = "Rewrite error"
        elif it.patch is not None:
            rewrite = (f"{_plural(len(it.patch.applied), 'edit')}, {len(it.patch.added)} added, "
                       f"{len(it.patch.skipped)} skipped")
        elif it is run.iterations[-1]:
            rewrite = "Stopped: gates met" if run.stop_reason == "converged" else "Stopped: max iterations"
        else:
            rewrite = "—"
        rows.append(f'<tr><td><b>{it.t}{" · best" if it is best else ""}</b></td><td class="mono">{it.seed}</td>'
                    f'<td class="mono">{it.mean_vqa:.3f}</td><td class="mono">{it.dino_patch:.3f}</td>'
                    f'<td class="mono">{it.joint:.3f}</td><td class="mono">{len(it.failed)}</td>'
                    f'<td class="muted">{esc(rewrite)}</td></tr>')
    stage.body = (
        f'<div class="pre-x-stack"><p class="pre-x-final" id="pre-x-final">{esc(run.best_prompt)}</p>'
        f'<div class="pre-x-block"><div class="pre-x-block-head"><h3>Original vs. proxy renders</h3>'
        f'<span class="muted mono">{esc(proxy)} · seed = {run.config.base_seed - 1} + t</span></div>'
        f'<div class="pre-x-cmp">{"".join(figs)}</div></div>'
        f'<div class="pre-x-block"><div class="pre-x-block-head"><h3>Run summary</h3></div>'
        f'<div class="pre-x-tablewrap"><table class="pre-x-table"><thead><tr><th>Iteration</th><th>Seed</th>'
        f"<th>S_VQA</th><th>S_DINO</th><th>Joint</th><th>Failed</th><th>Rewrite</th></tr></thead>"
        f'<tbody>{"".join(rows)}</tbody></table></div></div></div>'
    )
    return stage


def _stages(run: InversionRun, og_url: str, aspect: tuple[int, int],
            image_url: Callable[[Image.Image], str], report_url: str | None) -> list[_Stage]:
    stages = [_extract_stage(run, og_url, aspect), _ground_stage(run, og_url, aspect)]
    in_loop = run.phase in ("render", "verify", "rewrite", "done")
    n_iters = max(len(run.iterations), run.phase_t if in_loop else 0, 1)
    for t in range(1, n_iters + 1):
        started = in_loop and (t <= len(run.iterations) or run.phase_t == t)
        if not started:
            stages.append(_Stage(f"render-{t}", f"Iteration {t}", "Render proxy", PENDING,
                                 body=_skeleton("Waiting for grounding to finish…")))
            stages.append(_Stage(f"verify-{t}", f"Iteration {t}", "Verify", PENDING,
                                 body=_skeleton("Waiting for the render…")))
            continue
        stages.append(_render_stage(run, t, og_url, aspect, image_url))
        if t <= len(run.iterations) or run.phase == "verify":
            stages.append(_verify_stage(run, t, len(stages)))
        else:
            stages.append(_Stage(f"verify-{t}", f"Iteration {t}", "Verify", PENDING,
                                 body=_skeleton("Waiting for the render…")))
        it = run.iterations[t - 1] if t <= len(run.iterations) else None
        rewrite_live = run.phase == "rewrite" and run.phase_t == t
        if it is not None and (it.patch is not None or it.rewrite_error is not None or rewrite_live):
            stages.append(_rewrite_stage(run, it))
    stages.append(_result_stage(run, og_url, aspect, image_url, report_url))
    return stages


# --------------------------------------------------------------------------- page

def _status_line(run: InversionRun, stages: list[_Stage], live: int) -> str:
    cfg = run.config
    if run.phase == "done" and run.best is not None:
        if run.stop_reason == "converged":
            gates = "Both gates met" if cfg.dino_gate > 0 else "S_VQA gate met"
            return f"{gates} at iteration {run.best.t} of up to {cfg.max_iters}"
        return f"Returning the best of {len(run.iterations)} iterations (t = {run.best.t})"
    stage = stages[live]
    if stage.group == "Setup":
        extra = " · re-localizing" if run.phase == "relocalize" else ""
        return f"Setup · {stage.label}{extra}"
    return f"{stage.group} of up to {cfg.max_iters} · {stage.label}"


def render_explorer(run: InversionRun, *, og_url: str, og_size: tuple[int, int],
                    image_url: Callable[[Image.Image], str], report_url: str | None = None,
                    run_id: str = "") -> str:
    """HTML for the stage-by-stage run explorer (see module docstring)."""
    stages = _stages(run, og_url, og_size, image_url, report_url)
    done = run.phase == "done" and run.best is not None
    if done:
        live = len(stages) - 1
    else:
        live = max((i for i, s in enumerate(stages) if s.state == LIVE), default=0)
    total = len(stages)

    if done and run.stop_reason == "converged":
        badge = f'<span class="pre-badge ok">{ICON_CHECK}Converged</span>'
    elif done:
        badge = '<span class="pre-badge warn">Gates not met</span>'
    else:
        badge = '<span class="pre-badge run"><span class="pre-x-pulse" aria-hidden="true"></span>Running</span>'

    groups: list[tuple[str, list[int]]] = []
    for i, st in enumerate(stages):
        if groups and groups[-1][0] == st.group:
            groups[-1][1].append(i)
        else:
            groups.append((st.group, [i]))
    nav = []
    for name, idxs in groups:
        active = live in idxs
        items = []
        for i in idxs:
            st = stages[i]
            off = " disabled" if st.state == PENDING else ""
            items.append(
                f'<li><button type="button" class="pre-x-step {st.state}" data-go="{i}"{off} '
                f'aria-current="{"step" if i == live else "false"}">'
                f'<span class="pre-x-track"><span class="pre-x-fill"></span></span>'
                f'<span class="pre-x-stepnum">{i + 1:02d}</span><span class="pre-x-steplabel">{esc(st.label)}</span>'
                f"</button></li>")
        nav.append(f'<div class="pre-x-group{" active" if active else ""}" style="flex:{len(idxs)} 1 0">'
                   f'<div class="pre-x-glabel">{esc(name)}</div>'
                   f'<ol style="grid-template-columns:repeat({len(idxs)},minmax(0,1fr))">{"".join(items)}</ol></div>')

    play_state = "replay" if done else "pause"
    play_label = "Replay" if done else "Pause"
    head = (
        f'<section class="pre-x-head" aria-label="Run progress"><div class="pre-x-headrow">'
        f'<div class="pre-x-headstatus">{badge}<span class="pre-x-status" aria-live="polite">'
        f"{esc(_status_line(run, stages, live))}</span></div>"
        f'<div class="pre-x-controls"><span class="pre-x-counter mono">Step <span data-role="stepnum">{live + 1}'
        f"</span> / {total}</span>"
        f'<button type="button" class="pre-x-icon" data-act="prev" aria-label="Previous stage">{ICON_PREV}</button>'
        f'<button type="button" class="pre-x-play" data-act="play" data-state="{play_state}">'
        f'<span class="i-pause">{ICON_PAUSE}</span><span class="i-play">{ICON_PLAY}</span>'
        f'<span class="i-replay">{ICON_REPLAY}</span><span data-role="playlabel">{play_label}</span></button>'
        f'<button type="button" class="pre-x-icon" data-act="next-top" aria-label="Next stage">{ICON_NEXT}</button>'
        f'</div></div><nav class="pre-x-nav" aria-label="Run stages"><div class="pre-x-groups">{"".join(nav)}'
        f"</div></nav></section>"
    )

    panels = []
    for i, st in enumerate(stages):
        nxt = stages[i + 1] if i + 1 < total else None
        if nxt is not None:
            label = "See verified prompt" if nxt.key == "result" else f"Next: {nxt.label}"
            off = " disabled" if nxt.state == PENDING else ""
            next_btn = (f'<button type="button" class="pre-x-next" data-act="next"{off}>{esc(label)}'
                        f"{ICON_ARROW}</button>")
        else:
            next_btn = ""
        foot = (f'<footer class="pre-x-foot"><span>{esc(st.footer)}</span>{next_btn}</footer>'
                if (st.footer or next_btn) and st.state != PENDING else "")
        chip = st.chip if st.chip.startswith("<") else (f'<span class="pre-x-chip">{st.chip}</span>' if st.chip else "")
        desc = f"<p>{esc(st.desc)}</p>" if st.desc else ""
        hidden = "" if i == live else " hidden"
        panels.append(
            f'<section class="pre-x-stage" data-stage="{i}" data-state="{st.state}"{hidden} '
            f'aria-label="{esc(st.group)}: {esc(st.label)}"><header class="pre-x-shead"><div>'
            f'<div class="pre-x-kicker mono">{esc(st.group)} · {i + 1:02d}</div><h2>{esc(st.label)}</h2>{desc}</div>'
            f'{chip}</header><div class="pre-x-body">{st.body}</div>{foot}</section>')

    return (f'<div class="pre-x" data-run="{esc(run_id)}" data-live="{live}" data-done="{1 if done else 0}" '
            f'data-count="{total}">{head}{"".join(panels)}</div>')