"""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'')
ICON_CHECK = _svg('', 14, width=2.5)
ICON_DOWN = _svg('', 12, width=2.5)
ICON_PREV = _svg('', 18)
ICON_NEXT = _svg('', 18)
ICON_ARROW = _svg('', 16)
ICON_PAUSE = _svg('')
ICON_PLAY = _svg('')
ICON_REPLAY = _svg('')
ICON_COPY = _svg(''
'')
ICON_DOWNLOAD = _svg('')
ICON_CHEVRON = _svg('', 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 , removed text in ."""
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"{esc(removed)}")
if added.strip():
out.append(f"{esc(added)}")
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'
"
)
# --------------------------------------------------------------------------- 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'
{_figure(og_url, "Original image", aspect)}'
f'
{_skeleton("Extracting the scene graph…")}
')
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'{esc(c)}' for c in g.color_palette) or "—"
checks = (f"
Checks
{' · '.join(esc(c) for c in g.extra_checks)}
" 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'
{esc(node.id)}
{esc(node.entity)}
'
f'
{esc(node.grid_cell)}
{esc(detail) or "—"}
')
stage.body = (
f'
'
f'{_figure(og_url, "Original with each node outlined in its grid cell", aspect, overlay=overlay)}'
f'
'
f'
Medium
{" · ".join(esc(m) for m in g.medium_and_optics) or "—"}
'
f"
Background
{esc(g.background) or '—'}
"
f'
Palette
{chips}
{checks}
'
f'
Node
Entity
'
f'
Grid cell
Attributes and relations
{"".join(rows)}
'
f'
{_toggle("pre-x-json", "View raw JSON", "Hide raw JSON")}'
f'
{esc(g.model_dump_json(indent=2))}
'
f"
"
)
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'
{_figure(og_url, "Original image", aspect)}'
f'
{_skeleton(text)}
')
stage.footer = "Grounding…" if state == LIVE else ""
return stage
if not cfg.ground:
stage.body = (f'
{_figure(og_url, "Original image", aspect)}'
f'
Grounding is off for this run: all '
f"{_plural(len(run.predicates), 'candidate predicate')} were kept without checking them "
f"on the original.
")
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'
{key}{n}
'
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 '
Every candidate held on the original; nothing was removed.
'
stage.body = (
f'
'
f'{_figure(og_url, "Original on a 3 by 3 grid with re-localized cells marked", aspect, overlay=overlay)}'
f'
{tiles}
'
f'
{listing}
'
f'
Pruned when P(yes) on the original < {cfg.grounding_threshold:.2f}.
'
)
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'{esc(proxy)} · seed {seed}', next_label="Verify")
steps = run.models.get("proxy_steps")
render_cap = (f'Render · t = {t}'
f'{f"{steps} steps" if steps else ""}')
figs = (_figure(og_url, "Original image", aspect, caption='Original'
'target')
+ _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'
{figs}
'
f'
Prompt v{t}
'
f'{_plural(len(run.predicates), "grounded predicate" if cfg.ground else "predicate")}'
f"
"
f'
{esc(_prompt_for(run, t))}
')
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 = 'Scoring…'
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''
f'{ICON_CHECK if met else ""}{esc(verdict)}')
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'
{esc(sp.predicate.kind)}
{esc(sp.predicate.statement)}
'
f'
{sp.raw:.2f}
{badge}
')
rest = scored[first:]
more_id = f"pre-x-more-{idx}"
more_body = f'{"".join(tr(sp) for sp in rest)}' if rest else ""
more_btn = (_toggle(more_id, f"Show all {len(scored)} predicates", "Show fewer") if rest else "")
table = (f'
Kind
Predicate
'
f'
P(yes)
Status
{"".join(tr(sp) for sp in scored[:first])}'
f"{more_body}
')
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 = 'Rewriting…'
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} < {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'{esc(ed["original"])}',
f'→ {esc(ed["revised"])}', _badge("moved", "Edited")))
for sentence in it.patch.added:
edits.append(_row(f'+ {esc(sentence)}', "new sentence",
_badge("moved", "Added")))
for sk in it.patch.skipped:
text = sk.get("original") or sk.get("addition") or ""
edits.append(_row(f'{esc(text)}', esc(sk.get("reason", "")),
_badge("removed", "Skipped")))
if it.rewrite_error:
edits.append(f'
The rewriter failed: {esc(it.rewrite_error)}. The next iteration '
f"re-renders the same prompt with a new seed.
")
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'
'
f'
Sent to the rewriter
'
f'
{"".join(sent) or "
No failed predicates.
"}
'
f'
Edits
'
f'
{"".join(edits) or "
No edits.
"}
'
f'
Prompt v{t + 1}
'
f'changes highlighted
'
f'
{diff_html(it.prompt, new_prompt)}
'
)
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''
f"{ICON_DOWNLOAD}Report (JSON)" if report_url else "")
stage.chip = (f'
{report}
')
proxy = _short(run.models.get("proxy_model"), "proxy")
figs = [_figure(og_url, "Original image", aspect,
caption='Originaltarget')]
for it in run.iterations:
figs.append(_figure(image_url(it.proxy_image), f"Proxy render, iteration {it.t}", aspect,
caption=f't = {it.t}'
f"VQA {it.mean_vqa:.2f} · DINO {it.dino_patch:.2f}",
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'
{it.t}{" · best" if it is best else ""}
{it.seed}
'
f'
{it.mean_vqa:.3f}
{it.dino_patch:.3f}
'
f'
{it.joint:.3f}
{len(it.failed)}
'
f'
{esc(rewrite)}
')
stage.body = (
f'
{esc(run.best_prompt)}
'
f'
Original vs. proxy renders
'
f'{esc(proxy)} · seed = {run.config.base_seed - 1} + t
'
f'
{"".join(figs)}
'
f'
Run summary
'
f'
Iteration
Seed
'
f"
S_VQA
S_DINO
Joint
Failed
Rewrite
"
f'{"".join(rows)}
'
)
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'{ICON_CHECK}Converged'
elif done:
badge = 'Gates not met'
else:
badge = 'Running'
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'")
nav.append(f'
'
f'
{esc(name)}
'
f'{"".join(items)}
')
play_state = "replay" if done else "pause"
play_label = "Replay" if done else "Pause"
head = (
f'
'
f'
{badge}'
f"{esc(_status_line(run, stages, live))}
"
f'
Step {live + 1}'
f" / {total}"
f''
f''
f''
f'
"
)
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'")
else:
next_btn = ""
foot = (f''
if (st.footer or next_btn) and st.state != PENDING else "")
chip = st.chip if st.chip.startswith("<") else (f'{st.chip}' if st.chip else "")
desc = f"
{esc(st.desc)}
" if st.desc else ""
hidden = "" if i == live else " hidden"
panels.append(
f'