Spaces:
Running on Zero
Running on Zero
UI Redesign
Browse files- README.md +26 -19
- app.py +100 -154
- app/explorer.css +229 -0
- app/explorer.js +182 -0
- app/theme.css +268 -72
- cli.py +4 -4
- inversion/engine.py +25 -11
- inversion/explorer.py +630 -0
- tests/test_engine.py +2 -2
- tests/test_explorer.py +156 -0
README.md
CHANGED
|
@@ -123,7 +123,7 @@ The proxy renderer is the forward model the loop optimizes the prompt against, s
|
|
| 123 |
|
| 124 |
```bash
|
| 125 |
# Invert a folder of images
|
| 126 |
-
python cli.py invert --input stimuli/ --out runs/ --max-iters
|
| 127 |
|
| 128 |
# Select DINO medoid render per condition folder
|
| 129 |
python cli.py medoid --input renders/ --out medoids.json --key patch --copy-to medoids/
|
|
@@ -133,10 +133,10 @@ python cli.py medoid --input renders/ --out medoids.json --key patch --copy-to m
|
|
| 133 |
|------|--------|---------|
|
| 134 |
| `--input PATH` | Image file or directory | required |
|
| 135 |
| `--out DIR` | Output root for runs/ | `runs/` |
|
| 136 |
-
| `--max-iters N` | Max rewrite iterations | `
|
| 137 |
-
| `--vqa-gate F` | S_VQA convergence gate | `0.
|
| 138 |
-
| `--dino-gate F` | S_DINO convergence gate (0 = disable) | `0.
|
| 139 |
-
| `--fail-threshold F` | Predicate failure threshold for rewrite | `0.
|
| 140 |
| `--w-vqa F` | Weight on S_VQA for best-iteration selection | `0.7` |
|
| 141 |
| `--seed N` | Base seed (proxy seed = base + t) | `42` |
|
| 142 |
| `--no-ground` | Skip grounding on original (not recommended) | off |
|
|
@@ -209,7 +209,7 @@ All model backends and runtime knobs are controlled via environment variables (s
|
|
| 209 |
| `PROXY_FP8` | Store the FLUX transformer in float8, compute in bf16 | `0` | Saves ~3.9 GB of resident weights with klein-4B (~33.9 → ~30 GB) and ~12 GB with schnell (~51.6 → ~40 GB); slightly changes proxy renders |
|
| 210 |
| `ZEROGPU_SIZE` | `auto`, `large` or `xlarge` | `auto` | Size of every `@spaces.GPU` call; `auto` picks `xlarge` when resident weights exceed 42 GB (logged at startup) |
|
| 211 |
| `FAL_ENDPOINT` | FAL endpoint | `fal-ai/flux/schnell` | If `PROXY_BACKEND=fal` |
|
| 212 |
-
| `DINO_MODEL_ID` | DINO model | `facebook/dinov2-base` | DINOv2-B (ungated). Any DINOv2/DINOv3 checkpoint works; `facebook/dinov3-*` is gated with manual approval, and the
|
| 213 |
| `DINO_DEVICE` | `cuda` or `cpu` | auto (CUDA if available) | |
|
| 214 |
| `VQA_MODE` | `normalized` or `yes` | `normalized` | `normalized` = P(yes) / (P(yes) + P(no)); `yes` = the original VQAScore, P("Yes") only (thresholds not comparable) |
|
| 215 |
|
|
@@ -217,16 +217,16 @@ All model backends and runtime knobs are controlled via environment variables (s
|
|
| 217 |
|
| 218 |
| Key | Meaning | Default | UI range |
|
| 219 |
|-----|---------|---------|-------|
|
| 220 |
-
| `max_iters` | Max proxy renders (render → verify → rewrite rounds) | `
|
| 221 |
-
| `vqa_gate` | S_VQA convergence threshold | `0.
|
| 222 |
-
| `dino_gate` | S_DINO convergence threshold (`0` = stop on S_VQA alone
|
| 223 |
-
| `fail_threshold` | Predicates scoring below this are sent to the rewriter | `0.
|
| 224 |
| `parent_gate` | DSG rule: children of an entity scoring below this score 0 | `0.5` | — |
|
| 225 |
| `ground` | Enable grounding on original | `True` | — |
|
| 226 |
-
| `grounding_threshold` | P(yes) on the original below which a predicate is pruned; also the minimum for re-localizing a grid cell | `0.
|
| 227 |
| `w_vqa` / `w_dino` | Weights of the joint score used to pick the best iteration | `0.7` / `0.3` | 0.0–1.0 |
|
| 228 |
| `base_seed` | Base seed (proxy seed = base + t) | `42` | — |
|
| 229 |
-
| `proxy_long_side` | Proxy render long side (px) | `
|
| 230 |
|
| 231 |
---
|
| 232 |
|
|
@@ -246,10 +246,10 @@ backends = components.backends()
|
|
| 246 |
|
| 247 |
# Configure run
|
| 248 |
cfg = EngineConfig(
|
| 249 |
-
max_iters=
|
| 250 |
-
vqa_gate=0.
|
| 251 |
-
dino_gate=0.
|
| 252 |
-
fail_threshold=0.
|
| 253 |
w_vqa=0.7,
|
| 254 |
base_seed=42,
|
| 255 |
ground=True,
|
|
@@ -273,11 +273,18 @@ save_run(run, "runs/my_image", og)
|
|
| 273 |
|
| 274 |
The Space UI exposes:
|
| 275 |
|
| 276 |
-
- Image upload (drag-drop, file picker, clipboard paste)
|
| 277 |
- Stopping rule sliders: max iterations, S_VQA gate, S_DINO gate
|
| 278 |
- Advanced accordion: failure threshold, S_VQA weight, base seed, grounding toggle
|
| 279 |
-
-
|
| 280 |
-
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 281 |
|
| 282 |
---
|
| 283 |
|
|
|
|
| 123 |
|
| 124 |
```bash
|
| 125 |
# Invert a folder of images
|
| 126 |
+
python cli.py invert --input stimuli/ --out runs/ --max-iters 3 --vqa-gate 0.82 --dino-gate 0.65
|
| 127 |
|
| 128 |
# Select DINO medoid render per condition folder
|
| 129 |
python cli.py medoid --input renders/ --out medoids.json --key patch --copy-to medoids/
|
|
|
|
| 133 |
|------|--------|---------|
|
| 134 |
| `--input PATH` | Image file or directory | required |
|
| 135 |
| `--out DIR` | Output root for runs/ | `runs/` |
|
| 136 |
+
| `--max-iters N` | Max rewrite iterations | `3` |
|
| 137 |
+
| `--vqa-gate F` | S_VQA convergence gate | `0.82` |
|
| 138 |
+
| `--dino-gate F` | S_DINO convergence gate (0 = disable) | `0.65` |
|
| 139 |
+
| `--fail-threshold F` | Predicate failure threshold for rewrite | `0.70` |
|
| 140 |
| `--w-vqa F` | Weight on S_VQA for best-iteration selection | `0.7` |
|
| 141 |
| `--seed N` | Base seed (proxy seed = base + t) | `42` |
|
| 142 |
| `--no-ground` | Skip grounding on original (not recommended) | off |
|
|
|
|
| 209 |
| `PROXY_FP8` | Store the FLUX transformer in float8, compute in bf16 | `0` | Saves ~3.9 GB of resident weights with klein-4B (~33.9 → ~30 GB) and ~12 GB with schnell (~51.6 → ~40 GB); slightly changes proxy renders |
|
| 210 |
| `ZEROGPU_SIZE` | `auto`, `large` or `xlarge` | `auto` | Size of every `@spaces.GPU` call; `auto` picks `xlarge` when resident weights exceed 42 GB (logged at startup) |
|
| 211 |
| `FAL_ENDPOINT` | FAL endpoint | `fal-ai/flux/schnell` | If `PROXY_BACKEND=fal` |
|
| 212 |
+
| `DINO_MODEL_ID` | DINO model | `facebook/dinov2-base` | DINOv2-B (ungated). Any DINOv2/DINOv3 checkpoint works; `facebook/dinov3-*` is gated with manual approval, and the `dino_gate` value is not transferable between backbones |
|
| 213 |
| `DINO_DEVICE` | `cuda` or `cpu` | auto (CUDA if available) | |
|
| 214 |
| `VQA_MODE` | `normalized` or `yes` | `normalized` | `normalized` = P(yes) / (P(yes) + P(no)); `yes` = the original VQAScore, P("Yes") only (thresholds not comparable) |
|
| 215 |
|
|
|
|
| 217 |
|
| 218 |
| Key | Meaning | Default | UI range |
|
| 219 |
|-----|---------|---------|-------|
|
| 220 |
+
| `max_iters` | Max proxy renders (render → verify → rewrite rounds) | `3` | 1–8 |
|
| 221 |
+
| `vqa_gate` | S_VQA convergence threshold | `0.82` | 0.5–1.0 |
|
| 222 |
+
| `dino_gate` | S_DINO convergence threshold (`0` = stop on S_VQA alone) | `0.65` | 0.0–1.0 |
|
| 223 |
+
| `fail_threshold` | Predicates scoring below this are sent to the rewriter | `0.70` | 0.3–0.95 |
|
| 224 |
| `parent_gate` | DSG rule: children of an entity scoring below this score 0 | `0.5` | — |
|
| 225 |
| `ground` | Enable grounding on original | `True` | — |
|
| 226 |
+
| `grounding_threshold` | P(yes) on the original below which a predicate is pruned; also the minimum for re-localizing a grid cell | `0.65` | — |
|
| 227 |
| `w_vqa` / `w_dino` | Weights of the joint score used to pick the best iteration | `0.7` / `0.3` | 0.0–1.0 |
|
| 228 |
| `base_seed` | Base seed (proxy seed = base + t) | `42` | — |
|
| 229 |
+
| `proxy_long_side` | Proxy render long side (px) | `512` | — |
|
| 230 |
|
| 231 |
---
|
| 232 |
|
|
|
|
| 246 |
|
| 247 |
# Configure run
|
| 248 |
cfg = EngineConfig(
|
| 249 |
+
max_iters=3,
|
| 250 |
+
vqa_gate=0.82,
|
| 251 |
+
dino_gate=0.65,
|
| 252 |
+
fail_threshold=0.70,
|
| 253 |
w_vqa=0.7,
|
| 254 |
base_seed=42,
|
| 255 |
ground=True,
|
|
|
|
| 273 |
|
| 274 |
The Space UI exposes:
|
| 275 |
|
| 276 |
+
- Image upload (drag-drop, file picker, clipboard paste). **Invert image** stays disabled until an image is uploaded and becomes **Run again** after a run
|
| 277 |
- Stopping rule sliders: max iterations, S_VQA gate, S_DINO gate
|
| 278 |
- Advanced accordion: failure threshold, S_VQA weight, base seed, grounding toggle
|
| 279 |
+
- A **run explorer** that walks through the run one stage at a time: *Extract scene graph → Ground on original → (Render proxy → Verify → Rewrite failures) per iteration → Verified prompt*
|
| 280 |
+
- While a run streams, it follows the newest stage. Navigating back pauses following, and **Play** resumes it. After the run, **Replay** steps through every stage.
|
| 281 |
+
- Extract: medium, palette, nodes outlined in their grid cells, raw scene-graph JSON. Ground: candidates / removed / moved / kept, with re-localized cells marked
|
| 282 |
+
- Render: original next to the render and the exact prompt it came from. Verify: S_VQA, S_DINO and joint tiles, green or orange against their gates, each with a `?` explanation, and every predicate (failed first)
|
| 283 |
+
- Rewrite: what was sent to the rewriter, each edit (applied, added or skipped with its reason), and the next prompt with changes highlighted
|
| 284 |
+
- Result: the verified prompt (Copy), every render with the best marked, the run summary, and the JSON report
|
| 285 |
+
- API (`gradio_client`): `/invert` still returns the verified prompt string and the report file (hidden components), alongside the explorer HTML
|
| 286 |
+
|
| 287 |
+
The explorer is rendered by `inversion/explorer.py` (pure HTML, no Gradio), driven by `app/explorer.js` and styled by `app/explorer.css`. Each run's images and report are written to a temporary folder served as a Gradio static path, and folders are pruned after 6 hours.
|
| 288 |
|
| 289 |
---
|
| 290 |
|
app.py
CHANGED
|
@@ -1,14 +1,20 @@
|
|
| 1 |
import html
|
| 2 |
import json
|
|
|
|
| 3 |
import tempfile
|
|
|
|
|
|
|
| 4 |
from pathlib import Path
|
|
|
|
| 5 |
|
| 6 |
import gradio as gr
|
| 7 |
import spaces
|
|
|
|
| 8 |
|
| 9 |
from inversion import EngineConfig, iter_inversion
|
| 10 |
from inversion.backends import BackendSettings, choose_gpu_size, load_components
|
| 11 |
from inversion.engine import Backends
|
|
|
|
| 12 |
|
| 13 |
SETTINGS = BackendSettings()
|
| 14 |
C = load_components(SETTINGS)
|
|
@@ -108,13 +114,63 @@ THEME = gr.themes.Base(
|
|
| 108 |
section_header_text_weight="600",
|
| 109 |
)
|
| 110 |
|
| 111 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
|
| 113 |
LOGO = ('<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke-width="2" stroke-linecap="round" '
|
| 114 |
'stroke-linejoin="round" aria-hidden="true"><path d="M3 12a9 9 0 0 1 15.5-6.2L21 8"/><path d="M21 3v5h-5"/>'
|
| 115 |
'<path d="M21 12a9 9 0 0 1-15.5 6.2L3 16"/><path d="M3 21v-5h5"/></svg>')
|
| 116 |
-
CHECK = ('<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" '
|
| 117 |
-
'stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M20 6 9 17l-5-5"/></svg>')
|
| 118 |
|
| 119 |
HEADER_HTML = f"""
|
| 120 |
<div class="pre-header">
|
|
@@ -151,124 +207,18 @@ INTRO_HTML = """
|
|
| 151 |
<span>The verified prompt, proxy renders and per-fact scores stream in as each step finishes.</span></div>
|
| 152 |
"""
|
| 153 |
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
# --------------------------------------------------------------------------- rendering
|
| 161 |
-
|
| 162 |
-
def _stage(run) -> int:
|
| 163 |
-
"""Index of the active pipeline stage (5 = finished)."""
|
| 164 |
-
s = run.status
|
| 165 |
-
if s.startswith("Done"):
|
| 166 |
-
return 5
|
| 167 |
-
for i, key in enumerate(("Module 1", "Module 2", "Module 3", "Module 4", "targeted rewrite")):
|
| 168 |
-
if key in s:
|
| 169 |
-
return i
|
| 170 |
-
return 0
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
def _meter(value, gate=None):
|
| 174 |
-
fill = f'<div class="pre-meter-fill" style="width:{max(0.0, min(1.0, value)) * 100:.0f}%"></div>'
|
| 175 |
-
mark = "" if gate is None else f'<div class="pre-meter-gate" style="left:{gate * 100:.0f}%"></div>'
|
| 176 |
-
return f'<div class="pre-meter">{fill}{mark}</div>'
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
def _tile(label, value, note, fraction, gate=None):
|
| 180 |
-
return (f'<div class="pre-tile"><div class="pre-tile-label">{label}</div>'
|
| 181 |
-
f'<div><span class="pre-tile-value">{value}</span> <span class="pre-muted" style="font-size:12px">'
|
| 182 |
-
f'{note}</span></div>{_meter(fraction, gate)}</div>')
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
def _status_html(run) -> str:
|
| 186 |
-
cfg, best, stage = run.config, run.best, _stage(run)
|
| 187 |
-
if stage == 5 and run.stop_reason == "converged":
|
| 188 |
-
badge = f'<span class="pre-badge ok">{CHECK}Converged</span>'
|
| 189 |
-
line = f"Both gates met at iteration {best.t} of {cfg.max_iters}"
|
| 190 |
-
elif stage == 5:
|
| 191 |
-
badge = '<span class="pre-badge warn">Gates not met</span>'
|
| 192 |
-
line = f"Returning the best of {len(run.iterations)} iterations (t = {best.t})"
|
| 193 |
-
else:
|
| 194 |
-
badge = '<span class="pre-badge run">Running</span>'
|
| 195 |
-
line = html.escape(run.status)
|
| 196 |
-
stages = "".join(
|
| 197 |
-
f'<li class="{"done" if i < stage else "active" if i == stage else "pending"}"><div class="pre-bar"></div>'
|
| 198 |
-
f'<div class="pre-n">{i + 1:02d}</div><div class="pre-stage-label">{name}</div></li>'
|
| 199 |
-
for i, name in enumerate(STAGES))
|
| 200 |
-
if best:
|
| 201 |
-
tiles = (_tile("Predicate agreement · S_VQA", f"{best.mean_vqa:.2f}", f"gate {cfg.vqa_gate:.2f}",
|
| 202 |
-
best.mean_vqa, cfg.vqa_gate)
|
| 203 |
-
+ _tile("Layout similarity · S_DINO", f"{best.dino_patch:.2f}", f"gate {cfg.dino_gate:.2f}",
|
| 204 |
-
best.dino_patch, cfg.dino_gate)
|
| 205 |
-
+ _tile("Joint score", f"{best.joint:.3f}", f"best of {len(run.iterations)}", best.joint))
|
| 206 |
-
else:
|
| 207 |
-
tiles = (_tile("Predicate agreement · S_VQA", "—", f"gate {cfg.vqa_gate:.2f}", 0, cfg.vqa_gate)
|
| 208 |
-
+ _tile("Layout similarity · S_DINO", "—", f"gate {cfg.dino_gate:.2f}", 0, cfg.dino_gate)
|
| 209 |
-
+ _tile("Joint score", "—", "", 0))
|
| 210 |
-
weights = f"Best = {cfg.w_vqa:g} · S_VQA + {cfg.w_dino:g} · S_DINO"
|
| 211 |
-
return (f'<div class="pre-card"><div class="pre-row"><div class="pre-row" style="justify-content:flex-start">'
|
| 212 |
-
f'{badge}<span class="pre-muted">{line}</span></div><span class="pre-muted" style="font-size:12px">'
|
| 213 |
-
f'{weights}</span></div><ol class="pre-stages">{stages}</ol><div class="pre-tiles">{tiles}</div></div>')
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
def _iteration_rows(run):
|
| 217 |
-
rows = []
|
| 218 |
-
for it in run.iterations:
|
| 219 |
-
if it.rewrite_error:
|
| 220 |
-
rewrite = "Rewrite error"
|
| 221 |
-
elif it.patch is not None:
|
| 222 |
-
rewrite = f"{len(it.patch.applied)} edits, {len(it.patch.added)} added, {len(it.patch.skipped)} skipped"
|
| 223 |
-
elif it is run.iterations[-1] and run.stop_reason:
|
| 224 |
-
rewrite = "Stopped: gates met" if run.stop_reason == "converged" else "Stopped: max iterations"
|
| 225 |
-
else:
|
| 226 |
-
rewrite = "…"
|
| 227 |
-
label = f"{it.t} · best" if it is run.best else str(it.t)
|
| 228 |
-
rows.append([label, it.seed, round(it.mean_vqa, 3), round(it.dino_patch, 3), round(it.joint, 3),
|
| 229 |
-
len(it.failed), rewrite])
|
| 230 |
-
return rows
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
def _predicate_rows(run, fail_threshold):
|
| 234 |
-
best = run.best
|
| 235 |
-
if best is None:
|
| 236 |
-
return [[p.kind, p.statement, None, None, "Pending"] for p in run.predicates]
|
| 237 |
-
rows = []
|
| 238 |
-
for sp in best.scored:
|
| 239 |
-
status = ("Blocked by " + ", ".join(sp.blocked_by)) if sp.blocked_by else (
|
| 240 |
-
"Pass" if sp.effective >= fail_threshold else "Fail")
|
| 241 |
-
rows.append([sp.predicate.kind, sp.predicate.statement, round(sp.raw, 3), round(sp.effective, 3), status])
|
| 242 |
-
return rows
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
def _grounding_rows(run):
|
| 246 |
-
rows = [[sp.predicate.statement, f"{sp.predicate.kind} · P(yes) {sp.raw:.2f} on the original", "Removed"]
|
| 247 |
-
for sp in run.dropped]
|
| 248 |
-
rows += [[m["entity"], f"position · {m['from']} → {m['to']} · P(yes) {m['p_yes']:.2f}", "Re-localized"]
|
| 249 |
-
for m in run.relocalized]
|
| 250 |
-
return rows
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
def _gallery(og, run):
|
| 254 |
-
items = [(og, "Original")]
|
| 255 |
-
items += [(it.proxy_image, f"t = {it.t} · VQA {it.mean_vqa:.2f} · DINO {it.dino_patch:.2f}"
|
| 256 |
-
+ (" · best" if it is run.best else "")) for it in run.iterations]
|
| 257 |
-
return items
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
def _outputs(og, run, fail_threshold, report_path=None):
|
| 261 |
return (
|
| 262 |
gr.update(visible=False), # intro
|
| 263 |
gr.update(visible=True), # results
|
| 264 |
-
|
| 265 |
-
run.best_prompt,
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
_iteration_rows(run),
|
| 269 |
-
_predicate_rows(run, fail_threshold),
|
| 270 |
-
run.graph.model_dump() if run.graph else None,
|
| 271 |
-
_grounding_rows(run),
|
| 272 |
)
|
| 273 |
|
| 274 |
|
|
@@ -278,14 +228,25 @@ def invert(image, max_iters, vqa_gate, dino_gate, fail_threshold, w_vqa, base_se
|
|
| 278 |
cfg = EngineConfig(max_iters=int(max_iters), vqa_gate=vqa_gate, dino_gate=dino_gate,
|
| 279 |
fail_threshold=fail_threshold, w_vqa=w_vqa, w_dino=round(1 - w_vqa, 4),
|
| 280 |
base_seed=int(base_seed), ground=bool(ground))
|
|
|
|
|
|
|
|
|
|
|
|
|
| 281 |
run = None
|
| 282 |
-
for run in iter_inversion(
|
| 283 |
-
yield _outputs(
|
| 284 |
assert run is not None
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 289 |
|
| 290 |
|
| 291 |
# --------------------------------------------------------------------------- layout
|
|
@@ -301,43 +262,27 @@ with gr.Blocks(title="Prompt Reverse Engineer") as demo:
|
|
| 301 |
sources=["upload", "clipboard"], height=320, elem_classes="pre-image")
|
| 302 |
with gr.Group(elem_classes="pre-group"):
|
| 303 |
gr.HTML('<p class="pre-step-title">2 · Stopping rule</p>', elem_classes="pre-group-title")
|
| 304 |
-
max_iters = gr.Slider(1, 8, value=
|
| 305 |
-
vqa_gate = gr.Slider(0.5, 1.0, value=0.
|
| 306 |
-
dino_gate = gr.Slider(0.0, 1.0, value=0.
|
| 307 |
info="Set to 0 to stop on S_VQA alone.")
|
| 308 |
with gr.Accordion("Advanced settings", open=False):
|
| 309 |
-
fail_threshold = gr.Slider(0.3, 0.95, value=0.
|
| 310 |
info="Facts scoring below this are sent to the rewriter.")
|
| 311 |
w_vqa = gr.Slider(0.0, 1.0, value=0.7, step=0.05, label="Weight on S_VQA",
|
| 312 |
info="Picks the best iteration; the rest of the weight goes to S_DINO.")
|
| 313 |
-
base_seed = gr.Number(value=42, precision=0, label="Base seed", info="
|
| 314 |
ground = gr.Checkbox(value=True, label="Ground predicates on the original",
|
| 315 |
info="Removes facts the scorer rejects on the original image.")
|
| 316 |
-
run_button = gr.Button("Invert image", variant="primary", size="lg")
|
|
|
|
| 317 |
|
| 318 |
with gr.Column(scale=3, min_width=560):
|
| 319 |
intro = gr.HTML(INTRO_HTML)
|
| 320 |
-
with gr.Column(visible=False
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
report = gr.DownloadButton("Download report (JSON)", value=None, interactive=False,
|
| 325 |
-
variant="secondary", size="sm", elem_classes="pre-dl")
|
| 326 |
-
gallery = gr.Gallery(label="Original vs. proxy renders", columns=3, rows=1, height=310,
|
| 327 |
-
object_fit="contain", allow_preview=True)
|
| 328 |
-
with gr.Column(elem_classes="pre-panel"), gr.Tabs():
|
| 329 |
-
with gr.Tab("Iterations"):
|
| 330 |
-
iterations = gr.Dataframe(headers=ITER_HEADERS, interactive=False, show_label=False)
|
| 331 |
-
with gr.Tab("Predicates"):
|
| 332 |
-
predicates = gr.Dataframe(headers=PRED_HEADERS, interactive=False, wrap=True,
|
| 333 |
-
show_label=False, max_height=480)
|
| 334 |
-
with gr.Tab("Scene graph"):
|
| 335 |
-
graph_json = gr.JSON(show_label=False)
|
| 336 |
-
with gr.Tab("Grounding"):
|
| 337 |
-
gr.Markdown("Facts the scorer rejected on the original image. They are removed from the "
|
| 338 |
-
"prompt, or moved to the grid cell the scorer supports, before rendering.")
|
| 339 |
-
grounding = gr.Dataframe(headers=GROUND_HEADERS, interactive=False, wrap=True,
|
| 340 |
-
show_label=False)
|
| 341 |
|
| 342 |
with gr.Accordion("Cite", open=False, elem_id="cite"):
|
| 343 |
gr.Markdown("""Author: Larrain, G
|
|
@@ -395,11 +340,12 @@ with gr.Blocks(title="Prompt Reverse Engineer") as demo:
|
|
| 395 |
}
|
| 396 |
```""")
|
| 397 |
|
|
|
|
| 398 |
run_button.click(
|
| 399 |
invert,
|
| 400 |
[image, max_iters, vqa_gate, dino_gate, fail_threshold, w_vqa, base_seed, ground],
|
| 401 |
-
[intro, results,
|
| 402 |
-
)
|
| 403 |
|
| 404 |
if __name__ == "__main__":
|
| 405 |
-
demo.launch(theme=THEME, css_paths=
|
|
|
|
| 1 |
import html
|
| 2 |
import json
|
| 3 |
+
import shutil
|
| 4 |
import tempfile
|
| 5 |
+
import time
|
| 6 |
+
import uuid
|
| 7 |
from pathlib import Path
|
| 8 |
+
from urllib.parse import quote
|
| 9 |
|
| 10 |
import gradio as gr
|
| 11 |
import spaces
|
| 12 |
+
from PIL import Image, features
|
| 13 |
|
| 14 |
from inversion import EngineConfig, iter_inversion
|
| 15 |
from inversion.backends import BackendSettings, choose_gpu_size, load_components
|
| 16 |
from inversion.engine import Backends
|
| 17 |
+
from inversion.explorer import render_explorer
|
| 18 |
|
| 19 |
SETTINGS = BackendSettings()
|
| 20 |
C = load_components(SETTINGS)
|
|
|
|
| 114 |
section_header_text_weight="600",
|
| 115 |
)
|
| 116 |
|
| 117 |
+
APP_DIR = Path(__file__).parent / "app"
|
| 118 |
+
CSS_PATHS = [APP_DIR / "theme.css", APP_DIR / "explorer.css"] # loaded via launch(css_paths=...)
|
| 119 |
+
EXPLORER_JS = (APP_DIR / "explorer.js").read_text(encoding="utf-8") # run explorer behaviour (gr.HTML js_on_load)
|
| 120 |
+
|
| 121 |
+
# Each run's original, proxy renders and report live in their own folder and are served by URL
|
| 122 |
+
# (a Gradio static path), so the explorer HTML stays small while it streams.
|
| 123 |
+
RUNS_ROOT = Path(tempfile.mkdtemp(prefix="pre_runs_"))
|
| 124 |
+
gr.set_static_paths([str(RUNS_ROOT)])
|
| 125 |
+
RUN_TTL_S = 6 * 3600
|
| 126 |
+
IMAGE_EXT = "webp" if features.check("webp") else "png"
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def _file_url(path: Path) -> str:
|
| 130 |
+
return "gradio_api/file=" + quote(path.resolve().as_posix(), safe="/:")
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
class _RunFiles:
|
| 134 |
+
"""One run's folder: every image is written once and then referenced by URL."""
|
| 135 |
+
|
| 136 |
+
def __init__(self):
|
| 137 |
+
self.dir = RUNS_ROOT / uuid.uuid4().hex
|
| 138 |
+
self.dir.mkdir(parents=True)
|
| 139 |
+
self._urls: dict[int, tuple[Image.Image, str]] = {}
|
| 140 |
+
|
| 141 |
+
@property
|
| 142 |
+
def run_id(self) -> str:
|
| 143 |
+
return self.dir.name
|
| 144 |
+
|
| 145 |
+
def url(self, image: Image.Image, name: str | None = None) -> str:
|
| 146 |
+
hit = self._urls.get(id(image))
|
| 147 |
+
if hit is not None and hit[0] is image:
|
| 148 |
+
return hit[1]
|
| 149 |
+
path = self.dir / f"{name or f'render_{len(self._urls)}'}.{IMAGE_EXT}"
|
| 150 |
+
image.convert("RGB").save(path, quality=90) if IMAGE_EXT == "webp" else image.convert("RGB").save(path)
|
| 151 |
+
url = _file_url(path)
|
| 152 |
+
self._urls[id(image)] = (image, url) # keep the image alive so its id() is never reused
|
| 153 |
+
return url
|
| 154 |
+
|
| 155 |
+
def write_report(self, run) -> Path:
|
| 156 |
+
path = self.dir / "report.json"
|
| 157 |
+
path.write_text(json.dumps(run.to_dict(), indent=2), encoding="utf-8")
|
| 158 |
+
return path
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def _prune_runs() -> None:
|
| 162 |
+
cutoff = time.time() - RUN_TTL_S
|
| 163 |
+
for folder in RUNS_ROOT.iterdir():
|
| 164 |
+
try:
|
| 165 |
+
if folder.is_dir() and folder.stat().st_mtime < cutoff:
|
| 166 |
+
shutil.rmtree(folder, ignore_errors=True)
|
| 167 |
+
except OSError:
|
| 168 |
+
pass
|
| 169 |
+
|
| 170 |
|
| 171 |
LOGO = ('<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke-width="2" stroke-linecap="round" '
|
| 172 |
'stroke-linejoin="round" aria-hidden="true"><path d="M3 12a9 9 0 0 1 15.5-6.2L21 8"/><path d="M21 3v5h-5"/>'
|
| 173 |
'<path d="M21 12a9 9 0 0 1-15.5 6.2L3 16"/><path d="M3 21v-5h5"/></svg>')
|
|
|
|
|
|
|
| 174 |
|
| 175 |
HEADER_HTML = f"""
|
| 176 |
<div class="pre-header">
|
|
|
|
| 207 |
<span>The verified prompt, proxy renders and per-fact scores stream in as each step finishes.</span></div>
|
| 208 |
"""
|
| 209 |
|
| 210 |
+
# --------------------------------------------------------------------------- run
|
| 211 |
+
|
| 212 |
+
def _outputs(run, files: _RunFiles, og_url: str, og_size: tuple[int, int], report: Path | None = None):
|
| 213 |
+
explorer = render_explorer(run, og_url=og_url, og_size=og_size, image_url=files.url,
|
| 214 |
+
report_url=_file_url(report) if report else None, run_id=files.run_id)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 215 |
return (
|
| 216 |
gr.update(visible=False), # intro
|
| 217 |
gr.update(visible=True), # results
|
| 218 |
+
explorer,
|
| 219 |
+
run.best_prompt, # hidden: keeps the API returning the prompt string
|
| 220 |
+
str(report) if report else None, # hidden: and the JSON report
|
| 221 |
+
gr.update(value="Running…", interactive=False),
|
|
|
|
|
|
|
|
|
|
|
|
|
| 222 |
)
|
| 223 |
|
| 224 |
|
|
|
|
| 228 |
cfg = EngineConfig(max_iters=int(max_iters), vqa_gate=vqa_gate, dino_gate=dino_gate,
|
| 229 |
fail_threshold=fail_threshold, w_vqa=w_vqa, w_dino=round(1 - w_vqa, 4),
|
| 230 |
base_seed=int(base_seed), ground=bool(ground))
|
| 231 |
+
_prune_runs()
|
| 232 |
+
files = _RunFiles()
|
| 233 |
+
og = image.convert("RGB")
|
| 234 |
+
og_url = files.url(og, "original")
|
| 235 |
run = None
|
| 236 |
+
for run in iter_inversion(og, BACKENDS, cfg):
|
| 237 |
+
yield _outputs(run, files, og_url, og.size)
|
| 238 |
assert run is not None
|
| 239 |
+
yield _outputs(run, files, og_url, og.size, files.write_report(run))
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
def _on_image(img):
|
| 243 |
+
has = img is not None
|
| 244 |
+
return gr.update(value="Invert image", interactive=has), gr.update(visible=not has)
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
def _after_run(img):
|
| 248 |
+
# Runs after every run, including failed ones, so the button never stays disabled.
|
| 249 |
+
return gr.update(value="Run again" if img is not None else "Invert image", interactive=img is not None)
|
| 250 |
|
| 251 |
|
| 252 |
# --------------------------------------------------------------------------- layout
|
|
|
|
| 262 |
sources=["upload", "clipboard"], height=320, elem_classes="pre-image")
|
| 263 |
with gr.Group(elem_classes="pre-group"):
|
| 264 |
gr.HTML('<p class="pre-step-title">2 · Stopping rule</p>', elem_classes="pre-group-title")
|
| 265 |
+
max_iters = gr.Slider(1, 8, value=3, step=1, label="Max iterations")
|
| 266 |
+
vqa_gate = gr.Slider(0.5, 1.0, value=0.82, step=0.01, label="Min. predicate agreement (S_VQA)")
|
| 267 |
+
dino_gate = gr.Slider(0.0, 1.0, value=0.65, step=0.01, label="Min. layout similarity (S_DINO)",
|
| 268 |
info="Set to 0 to stop on S_VQA alone.")
|
| 269 |
with gr.Accordion("Advanced settings", open=False):
|
| 270 |
+
fail_threshold = gr.Slider(0.3, 0.95, value=0.70, step=0.01, label="Failure threshold",
|
| 271 |
info="Facts scoring below this are sent to the rewriter.")
|
| 272 |
w_vqa = gr.Slider(0.0, 1.0, value=0.7, step=0.05, label="Weight on S_VQA",
|
| 273 |
info="Picks the best iteration; the rest of the weight goes to S_DINO.")
|
| 274 |
+
base_seed = gr.Number(value=42, precision=0, label="Base seed", info="Iteration t uses seed base + t − 1.")
|
| 275 |
ground = gr.Checkbox(value=True, label="Ground predicates on the original",
|
| 276 |
info="Removes facts the scorer rejects on the original image.")
|
| 277 |
+
run_button = gr.Button("Invert image", variant="primary", size="lg", interactive=False)
|
| 278 |
+
hint = gr.HTML('<p class="pre-hint">Upload an image to start.</p>')
|
| 279 |
|
| 280 |
with gr.Column(scale=3, min_width=560):
|
| 281 |
intro = gr.HTML(INTRO_HTML)
|
| 282 |
+
with gr.Column(visible=False) as results:
|
| 283 |
+
explorer = gr.HTML(js_on_load=EXPLORER_JS)
|
| 284 |
+
best_prompt = gr.Textbox(label="Verified prompt", visible=False)
|
| 285 |
+
report = gr.File(label="Run report (JSON)", visible=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 286 |
|
| 287 |
with gr.Accordion("Cite", open=False, elem_id="cite"):
|
| 288 |
gr.Markdown("""Author: Larrain, G
|
|
|
|
| 340 |
}
|
| 341 |
```""")
|
| 342 |
|
| 343 |
+
image.change(_on_image, [image], [run_button, hint])
|
| 344 |
run_button.click(
|
| 345 |
invert,
|
| 346 |
[image, max_iters, vqa_gate, dino_gate, fail_threshold, w_vqa, base_seed, ground],
|
| 347 |
+
[intro, results, explorer, best_prompt, report, run_button],
|
| 348 |
+
).then(_after_run, [image], [run_button])
|
| 349 |
|
| 350 |
if __name__ == "__main__":
|
| 351 |
+
demo.launch(theme=THEME, css_paths=CSS_PATHS)
|
app/explorer.css
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/* Run explorer (markup: inversion/explorer.py, behaviour: app/explorer.js). Colors come from the --pre-* tokens. */
|
| 2 |
+
:root{--pre-subtle:#FAFBFC;--pre-input-line:#D3D7DE;--pre-neutral-bg:#EEF0F3;--pre-neutral-fg:#3F4552;
|
| 3 |
+
--pre-accent-strong:#1E4297;--pre-pass-fill:#1F8A5B;--pre-pass-line:#BFE3CF;--pre-pass-tint:#F7FCF9;
|
| 4 |
+
--pre-warn-fill:#C2570C;--pre-warn-line:#F0C9A6;--pre-warn-tint:#FFFAF5;--pre-solid:#2B59C3;--pre-info-bg:#EAF0FC}
|
| 5 |
+
.dark{--pre-subtle:#1C2027;--pre-input-line:#3A404B;--pre-neutral-bg:#262B33;--pre-neutral-fg:#C5CAD3;
|
| 6 |
+
--pre-accent-strong:#A9C1F5;--pre-pass-fill:#3FAF7A;--pre-pass-line:#24533F;--pre-pass-tint:#13261E;
|
| 7 |
+
--pre-warn-fill:#E08A45;--pre-warn-line:#5A3A1E;--pre-warn-tint:#271B11;--pre-solid:#2B59C3;--pre-info-bg:#1D2A45}
|
| 8 |
+
|
| 9 |
+
.pre-hint{font-size:12px;color:var(--pre-muted);text-align:center;margin:-4px 0 0}
|
| 10 |
+
|
| 11 |
+
.pre-x{display:flex;flex-direction:column;gap:16px;color:var(--pre-text);font-size:14px;line-height:1.5}
|
| 12 |
+
.pre-x [hidden]{display:none !important}
|
| 13 |
+
.pre-x .mono{font-family:var(--font-mono)}
|
| 14 |
+
.pre-x .muted{color:var(--pre-muted)}
|
| 15 |
+
.pre-x h2,.pre-x h3,.pre-x p{margin:0}
|
| 16 |
+
.pre-x button:focus-visible,.pre-x a:focus-visible{outline:2px solid var(--pre-accent);outline-offset:2px}
|
| 17 |
+
|
| 18 |
+
/* header: status, controls, navigator */
|
| 19 |
+
.pre-x-head,.pre-x-stage{background:var(--pre-card);border:1px solid var(--pre-line);border-radius:12px}
|
| 20 |
+
.pre-x-head{padding:18px 24px 16px;display:flex;flex-direction:column;gap:16px}
|
| 21 |
+
.pre-x-headrow{display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:12px}
|
| 22 |
+
.pre-x-headstatus{display:flex;flex-wrap:wrap;align-items:center;gap:12px;min-width:0}
|
| 23 |
+
.pre-x-status{color:var(--pre-muted)}
|
| 24 |
+
.pre-x-pulse{width:7px;height:7px;border-radius:999px;background:currentColor;animation:pre-pulse 1.2s ease-in-out infinite}
|
| 25 |
+
.pre-x-controls{display:flex;align-items:center;gap:8px}
|
| 26 |
+
.pre-x-counter{font-size:12px;color:var(--pre-muted);margin-right:4px}
|
| 27 |
+
.pre-x-icon,.pre-x-play{height:44px;display:inline-flex;align-items:center;justify-content:center;
|
| 28 |
+
border:1px solid var(--pre-input-line);border-radius:8px;background:var(--pre-card);color:var(--pre-text);cursor:pointer}
|
| 29 |
+
.pre-x-icon{width:44px}
|
| 30 |
+
.pre-x-icon:disabled{opacity:.4;cursor:default}
|
| 31 |
+
.pre-x-play{min-width:104px;gap:8px;padding:0 14px;font-size:13px;font-weight:600}
|
| 32 |
+
.pre-x-play .i-pause,.pre-x-play .i-play,.pre-x-play .i-replay{display:none;line-height:0}
|
| 33 |
+
.pre-x-play[data-state="pause"] .i-pause,.pre-x-play[data-state="play"] .i-play,
|
| 34 |
+
.pre-x-play[data-state="replay"] .i-replay{display:inline-flex}
|
| 35 |
+
|
| 36 |
+
.pre-x-nav{overflow-x:auto}
|
| 37 |
+
.pre-x-groups{display:flex;gap:20px;min-width:640px}
|
| 38 |
+
.pre-x-group{display:flex;flex-direction:column;gap:6px;min-width:0}
|
| 39 |
+
.pre-x-glabel{font-size:11px;font-weight:600;letter-spacing:.04em;text-transform:uppercase;color:var(--pre-muted)}
|
| 40 |
+
.pre-x-group.active .pre-x-glabel{color:var(--pre-accent)}
|
| 41 |
+
.pre-x-group ol{list-style:none;margin:0;padding:0;display:grid;gap:8px}
|
| 42 |
+
.pre-x-group li{margin:0;min-width:0}
|
| 43 |
+
.pre-x-step{display:flex;flex-direction:column;gap:6px;width:100%;min-height:44px;padding:4px 0;background:none;
|
| 44 |
+
border:0;text-align:left;cursor:pointer;font:inherit;color:inherit}
|
| 45 |
+
.pre-x-step:disabled{cursor:default}
|
| 46 |
+
.pre-x-track{position:relative;display:block;height:4px;border-radius:999px;overflow:hidden;background:var(--pre-line)}
|
| 47 |
+
.pre-x-fill{position:absolute;inset:0;border-radius:999px;background:var(--pre-accent);transform-origin:left center;transform:scaleX(0)}
|
| 48 |
+
.pre-x-step.done .pre-x-track{background:var(--pre-accent)}
|
| 49 |
+
.pre-x-step.live .pre-x-track{background:var(--pre-accent);opacity:.45;animation:pre-pulse 1.2s ease-in-out infinite}
|
| 50 |
+
.pre-x.replaying .pre-x-step .pre-x-track{background:var(--pre-line);opacity:1;animation:none}
|
| 51 |
+
.pre-x.replaying .pre-x-step.before .pre-x-track{background:var(--pre-accent)}
|
| 52 |
+
.pre-x-step.is-timed .pre-x-fill{animation:pre-x-seg var(--pre-x-dwell,3200ms) linear both}
|
| 53 |
+
.pre-x-stepnum{font-family:var(--font-mono);font-size:12px;color:var(--pre-muted)}
|
| 54 |
+
.pre-x-steplabel{font-size:13px;line-height:1.3;font-weight:500}
|
| 55 |
+
.pre-x-step.pending .pre-x-steplabel{color:var(--pre-muted)}
|
| 56 |
+
.pre-x-step.is-current .pre-x-stepnum{color:var(--pre-accent)}
|
| 57 |
+
.pre-x-step.is-current .pre-x-steplabel{font-weight:600}
|
| 58 |
+
|
| 59 |
+
/* stage panel */
|
| 60 |
+
.pre-x-stage{overflow:hidden}
|
| 61 |
+
.pre-x-stage.pre-x-enter{animation:pre-x-in .28s ease-out both}
|
| 62 |
+
.pre-x-shead{display:flex;flex-wrap:wrap;align-items:flex-start;justify-content:space-between;gap:12px;
|
| 63 |
+
padding:18px 24px;border-bottom:1px solid var(--pre-line)}
|
| 64 |
+
.pre-x-shead>div:first-child{display:flex;flex-direction:column;gap:2px;min-width:0}
|
| 65 |
+
.pre-x-kicker{font-size:12px;color:var(--pre-muted)}
|
| 66 |
+
.pre-x-shead h2{font-size:18px;font-weight:600;line-height:1.3}
|
| 67 |
+
.pre-x-shead p{font-size:13px;color:var(--pre-muted);max-width:70ch}
|
| 68 |
+
.pre-x-chip{padding:4px 10px;border:1px solid var(--pre-line);border-radius:999px;font-size:12px;color:var(--pre-muted);white-space:nowrap}
|
| 69 |
+
.pre-x-chip-plain{font-size:12px;color:var(--pre-muted)}
|
| 70 |
+
.pre-x-verdict{display:inline-flex;align-items:center;gap:6px;padding:4px 10px;border-radius:999px;font-size:13px;font-weight:600;white-space:nowrap}
|
| 71 |
+
.pre-x-verdict.ok{background:var(--pre-pass-bg);color:var(--pre-pass)}
|
| 72 |
+
.pre-x-verdict.warn{background:var(--pre-warn-bg);color:var(--pre-warn)}
|
| 73 |
+
.pre-x-body{padding:24px}
|
| 74 |
+
.pre-x-foot{display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:12px;padding:14px 24px;
|
| 75 |
+
border-top:1px solid var(--pre-line);background:var(--pre-subtle);font-size:13px;color:var(--pre-muted)}
|
| 76 |
+
.pre-x-next{min-height:40px;display:inline-flex;align-items:center;gap:6px;padding:0 14px;border:0;border-radius:8px;
|
| 77 |
+
background:var(--pre-solid);color:#FFFFFF;font-size:13px;font-weight:600;cursor:pointer}
|
| 78 |
+
.pre-x-next:disabled{background:var(--pre-neutral-bg);color:var(--pre-muted);cursor:default}
|
| 79 |
+
.pre-x-btn{min-height:40px;display:inline-flex;align-items:center;gap:8px;padding:0 14px;border:1px solid var(--pre-input-line);
|
| 80 |
+
border-radius:8px;background:var(--pre-card);color:var(--pre-text);font-size:13px;font-weight:500;cursor:pointer;text-decoration:none}
|
| 81 |
+
.pre-x-btn.sm{min-height:36px;padding:0 12px;align-self:flex-end}
|
| 82 |
+
.pre-x-actions{display:flex;flex-wrap:wrap;gap:8px}
|
| 83 |
+
.pre-x-link{display:inline-flex;align-items:center;gap:6px;min-height:36px;padding:0;background:none;border:0;
|
| 84 |
+
color:var(--pre-accent);font-size:13px;font-weight:500;cursor:pointer}
|
| 85 |
+
.pre-x-link svg{transition:transform .15s}
|
| 86 |
+
.pre-x-link[aria-expanded="true"] svg{transform:rotate(180deg)}
|
| 87 |
+
|
| 88 |
+
/* layouts */
|
| 89 |
+
.pre-x-split{display:flex;flex-wrap:wrap;gap:24px}
|
| 90 |
+
.pre-x-split>.pre-x-fig{flex:1 1 260px;max-width:360px;min-width:0}
|
| 91 |
+
.pre-x-col{flex:1 1 300px;min-width:0;display:flex;flex-direction:column;gap:16px}
|
| 92 |
+
.pre-x-stack{display:flex;flex-direction:column;gap:20px}
|
| 93 |
+
.pre-x-pair{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:16px;max-width:720px}
|
| 94 |
+
.pre-x-cmp{display:grid;grid-template-columns:repeat(auto-fill,minmax(180px,1fr));gap:16px}
|
| 95 |
+
|
| 96 |
+
/* figures and grid overlays */
|
| 97 |
+
.pre-x-fig{margin:0;display:flex;flex-direction:column;gap:8px}
|
| 98 |
+
.pre-x-imgbox{position:relative;width:100%;border-radius:8px;overflow:hidden;background:var(--pre-subtle);border:1px solid var(--pre-line)}
|
| 99 |
+
.pre-x-fig.current .pre-x-imgbox{border:2px solid var(--pre-solid)}
|
| 100 |
+
.pre-x-imgbox img{position:absolute;inset:0;width:100%;height:100%;object-fit:contain;display:block}
|
| 101 |
+
.pre-x-wait{position:absolute;inset:0;display:flex;align-items:center;justify-content:center}
|
| 102 |
+
.pre-x-wait .pre-x-skel{border:0;background:none}
|
| 103 |
+
.pre-x-fig figcaption{font-size:13px}
|
| 104 |
+
.pre-x-cap{display:flex;justify-content:space-between;gap:8px}
|
| 105 |
+
.pre-x-cmp .pre-x-cap{flex-direction:column;gap:2px}
|
| 106 |
+
.pre-x-best{position:absolute;top:8px;left:8px;padding:2px 8px;border-radius:999px;background:var(--pre-solid);color:#FFFFFF;font-size:11px;font-weight:600}
|
| 107 |
+
.pre-x-cell{position:absolute;width:33.3333%;height:33.3333%;box-sizing:border-box}
|
| 108 |
+
.pre-x-cell.node{border:1.5px dashed var(--pre-solid);background:rgba(43,89,195,.06)}
|
| 109 |
+
.pre-x-cell.from{border:2px dashed #8A92A1}
|
| 110 |
+
.pre-x-cell.to{border:2px solid var(--pre-solid);background:rgba(43,89,195,.10)}
|
| 111 |
+
.pre-x-tag{position:absolute;left:4px;top:4px;max-width:calc(100% - 8px);padding:1px 6px;border-radius:4px;background:var(--pre-solid);
|
| 112 |
+
color:#FFFFFF;font-family:var(--font-mono);font-size:11px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
| 113 |
+
.pre-x-cell.from .pre-x-tag{background:#FFFFFF;color:#3F4552}
|
| 114 |
+
.pre-x-cell.to .pre-x-tag{top:auto;bottom:4px}
|
| 115 |
+
.pre-x-gl{position:absolute;background:rgba(20,23,31,.22)}
|
| 116 |
+
.pre-x-gl.v{top:0;bottom:0;width:1px}
|
| 117 |
+
.pre-x-gl.h{left:0;right:0;height:1px}
|
| 118 |
+
|
| 119 |
+
/* text blocks */
|
| 120 |
+
.pre-x-dl{margin:0;display:grid;grid-template-columns:96px minmax(0,1fr);gap:10px 16px;font-size:13px}
|
| 121 |
+
.pre-x-dl dt{color:var(--pre-muted)}
|
| 122 |
+
.pre-x-dl dd{margin:0;overflow-wrap:anywhere}
|
| 123 |
+
.pre-x-chips{display:flex;flex-wrap:wrap;gap:6px}
|
| 124 |
+
.pre-x-chiplet{padding:2px 8px;border:1px solid var(--pre-line);border-radius:999px;font-size:12px}
|
| 125 |
+
.pre-x-json{margin:8px 0 0;padding:14px 16px;border:1px solid var(--pre-line);border-radius:8px;font-family:var(--font-mono);
|
| 126 |
+
font-size:12px;line-height:1.6;background:var(--pre-subtle);color:var(--pre-text);overflow:auto;white-space:pre;max-height:420px}
|
| 127 |
+
.pre-x-block{display:flex;flex-direction:column;gap:8px}
|
| 128 |
+
.pre-x-block-head{display:flex;flex-wrap:wrap;justify-content:space-between;align-items:baseline;gap:12px}
|
| 129 |
+
.pre-x-block-head h3{font-size:13px;font-weight:600}
|
| 130 |
+
.pre-x-block-head span{font-size:12px}
|
| 131 |
+
.pre-x-prompt{padding:14px 16px;border:1px solid var(--pre-line);border-radius:8px;background:var(--pre-subtle);
|
| 132 |
+
font-size:14px;line-height:1.7;max-width:78ch;white-space:pre-wrap;overflow-wrap:anywhere}
|
| 133 |
+
.pre-x-prompt ins{text-decoration:none;background:var(--pre-pass-bg);color:var(--pre-pass);border-radius:3px;padding:1px 2px}
|
| 134 |
+
.pre-x-prompt del{background:var(--pre-warn-bg);color:var(--pre-warn);border-radius:3px;padding:1px 2px}
|
| 135 |
+
.pre-x-final{font-size:15px;line-height:1.7;max-width:78ch;white-space:pre-wrap;overflow-wrap:anywhere}
|
| 136 |
+
.pre-x-note-box{padding:12px 14px;border:1px dashed var(--pre-line);border-radius:8px;color:var(--pre-muted);font-size:13px}
|
| 137 |
+
.pre-x-fine{font-size:12px;color:var(--pre-muted)}
|
| 138 |
+
.pre-x-error{padding:12px 14px;border-radius:8px;background:var(--pre-warn-bg);color:var(--pre-warn);font-size:13px;overflow-wrap:anywhere}
|
| 139 |
+
|
| 140 |
+
/* rows, badges, counts */
|
| 141 |
+
.pre-x-rows{display:flex;flex-direction:column;gap:8px}
|
| 142 |
+
.pre-x-row{display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:12px;padding:12px 14px;
|
| 143 |
+
border:1px solid var(--pre-line);border-radius:8px}
|
| 144 |
+
.pre-x-row-text{display:flex;flex-direction:column;gap:2px;min-width:0;flex:1 1 240px}
|
| 145 |
+
.pre-x-row-title{font-weight:500;overflow-wrap:anywhere}
|
| 146 |
+
.pre-x-row-text>span:last-child{font-size:12px;color:var(--pre-muted);overflow-wrap:anywhere}
|
| 147 |
+
.pre-x-row-text>span.warn{color:var(--pre-warn)}
|
| 148 |
+
.pre-x-b{display:inline-block;padding:2px 8px;border-radius:999px;font-size:12px;font-weight:600;white-space:nowrap}
|
| 149 |
+
.pre-x-b.pass{background:var(--pre-pass-bg);color:var(--pre-pass)}
|
| 150 |
+
.pre-x-b.fail{background:var(--pre-warn-bg);color:var(--pre-warn)}
|
| 151 |
+
.pre-x-b.blocked,.pre-x-b.removed{background:var(--pre-neutral-bg);color:var(--pre-neutral-fg)}
|
| 152 |
+
.pre-x-b.moved{background:var(--pre-info-bg);color:var(--pre-accent-strong)}
|
| 153 |
+
.pre-x-counts{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:8px}
|
| 154 |
+
.pre-x-count{border:1px solid var(--pre-line);border-radius:10px;padding:10px 12px;display:flex;flex-direction:column}
|
| 155 |
+
.pre-x-count span{font-size:12px;color:var(--pre-muted)}
|
| 156 |
+
.pre-x-count b{font-family:var(--font-mono);font-size:22px;font-weight:600}
|
| 157 |
+
.pre-x-count.kept{border-color:var(--pre-solid);background:var(--pre-info-bg)}
|
| 158 |
+
.pre-x-count.kept span,.pre-x-count.kept b{color:var(--pre-accent-strong)}
|
| 159 |
+
|
| 160 |
+
/* tables */
|
| 161 |
+
.pre-x-tablewrap{border:1px solid var(--pre-line);border-radius:10px;overflow-x:auto}
|
| 162 |
+
.pre-x-table{width:100%;border-collapse:collapse;font-size:13px;min-width:520px;margin:0;border:0}
|
| 163 |
+
.pre-x-table thead,.pre-x-table tbody,.pre-x-table tr{border:0;background:none}
|
| 164 |
+
.pre-x-table th{text-align:left;font-weight:500;font-size:12px;color:var(--pre-muted);background:var(--pre-subtle);padding:10px 12px;border:0}
|
| 165 |
+
.pre-x-table td{padding:10px 12px;border:0;border-top:1px solid var(--pre-line);vertical-align:top;overflow-wrap:anywhere}
|
| 166 |
+
.pre-x-table td.muted{color:var(--pre-muted)}
|
| 167 |
+
.pre-x-tablefoot{display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:8px;margin-top:-8px}
|
| 168 |
+
|
| 169 |
+
/* metric tiles with gate colors and ? popovers */
|
| 170 |
+
.pre-x-tiles{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:12px}
|
| 171 |
+
.pre-x-tile{position:relative;border:1px solid var(--pre-line);background:var(--pre-card);border-radius:10px;padding:14px 16px;
|
| 172 |
+
display:flex;flex-direction:column;gap:8px}
|
| 173 |
+
.pre-x-tile.ok{border-color:var(--pre-pass-line);background:var(--pre-pass-tint)}
|
| 174 |
+
.pre-x-tile.warn{border-color:var(--pre-warn-line);background:var(--pre-warn-tint)}
|
| 175 |
+
.pre-x-tile-top{display:flex;align-items:center;justify-content:space-between;gap:8px}
|
| 176 |
+
.pre-x-tile-label{font-size:12px;color:var(--pre-muted)}
|
| 177 |
+
.pre-x-help{width:44px;height:44px;margin:-14px -12px -14px 0;padding:0;background:none;border:0;display:flex;
|
| 178 |
+
align-items:center;justify-content:center;cursor:pointer;flex:none}
|
| 179 |
+
.pre-x-help span{width:20px;height:20px;border-radius:999px;box-sizing:border-box;display:flex;align-items:center;
|
| 180 |
+
justify-content:center;font-size:12px;font-weight:600;border:1.5px solid var(--pre-muted);background:var(--pre-card);color:var(--pre-text)}
|
| 181 |
+
.pre-x-help[aria-expanded="true"] span{border-color:var(--pre-solid);background:var(--pre-solid);color:#FFFFFF}
|
| 182 |
+
.pre-x-tile-val{display:flex;align-items:baseline;gap:8px}
|
| 183 |
+
.pre-x-num{font-family:var(--font-mono);font-size:28px;font-weight:600;letter-spacing:-.02em}
|
| 184 |
+
.pre-x-tile.ok .pre-x-num{color:var(--pre-pass)}
|
| 185 |
+
.pre-x-tile.warn .pre-x-num{color:var(--pre-warn)}
|
| 186 |
+
.pre-x-note{font-size:12px;color:var(--pre-muted)}
|
| 187 |
+
.pre-x-meter{position:relative;height:6px;border-radius:999px;background:var(--pre-track)}
|
| 188 |
+
.pre-x-meter-fill{position:absolute;left:0;top:0;bottom:0;border-radius:999px;background:var(--pre-accent)}
|
| 189 |
+
.pre-x-tile.ok .pre-x-meter-fill{background:var(--pre-pass-fill)}
|
| 190 |
+
.pre-x-tile.warn .pre-x-meter-fill{background:var(--pre-warn-fill)}
|
| 191 |
+
.pre-x-meter-gate{position:absolute;top:-3px;width:2px;height:12px;background:var(--pre-text)}
|
| 192 |
+
.pre-x-pill{display:inline-flex;align-items:center;gap:6px;align-self:flex-start;padding:3px 8px;border-radius:999px;
|
| 193 |
+
font-size:12px;font-weight:600;background:var(--pre-neutral-bg);color:var(--pre-text)}
|
| 194 |
+
.pre-x-tile.ok .pre-x-pill{background:var(--pre-pass-bg);color:var(--pre-pass)}
|
| 195 |
+
.pre-x-tile.warn .pre-x-pill{background:var(--pre-warn-bg);color:var(--pre-warn)}
|
| 196 |
+
.pre-x-pop{position:absolute;z-index:10;top:44px;right:8px;width:264px;max-width:calc(100vw - 48px);box-sizing:border-box;
|
| 197 |
+
background:var(--pre-card);border:1px solid var(--pre-input-line);border-radius:10px;padding:14px 16px;
|
| 198 |
+
box-shadow:0 8px 24px rgba(20,23,31,.14);display:flex;flex-direction:column;gap:8px}
|
| 199 |
+
.pre-x-pop-title{font-size:13px;font-weight:600}
|
| 200 |
+
.pre-x-pop p{font-size:13px;line-height:1.5}
|
| 201 |
+
.pre-x-pop-gate{font-size:12px;color:var(--pre-muted);font-family:var(--font-mono)}
|
| 202 |
+
.pre-x-legend{display:flex;flex-wrap:wrap;gap:4px 14px;font-size:12px;font-weight:500}
|
| 203 |
+
.pre-x-legend span{display:inline-flex;align-items:center;gap:6px}
|
| 204 |
+
.pre-x-legend .ok{color:var(--pre-pass)}
|
| 205 |
+
.pre-x-legend .warn{color:var(--pre-warn)}
|
| 206 |
+
.pre-x-legend i{width:8px;height:8px;border-radius:999px;display:inline-block}
|
| 207 |
+
.pre-x-legend .ok i{background:var(--pre-pass-fill)}
|
| 208 |
+
.pre-x-legend .warn i{background:var(--pre-warn-fill)}
|
| 209 |
+
|
| 210 |
+
/* waiting states */
|
| 211 |
+
.pre-x-skel{display:flex;align-items:center;gap:10px;padding:16px;border:1px dashed var(--pre-line);border-radius:10px;
|
| 212 |
+
color:var(--pre-muted);font-size:13px}
|
| 213 |
+
.pre-x-spin{width:14px;height:14px;border-radius:999px;border:2px solid var(--pre-line);border-top-color:var(--pre-accent);
|
| 214 |
+
animation:pre-x-spin .8s linear infinite;flex:none}
|
| 215 |
+
|
| 216 |
+
@keyframes pre-x-spin{to{transform:rotate(360deg)}}
|
| 217 |
+
@keyframes pre-x-in{from{opacity:0;transform:translateY(6px)}to{opacity:1;transform:none}}
|
| 218 |
+
@keyframes pre-x-seg{from{transform:scaleX(0)}to{transform:scaleX(1)}}
|
| 219 |
+
@media (prefers-reduced-motion:reduce){.pre-x,.pre-x *{animation:none !important;transition:none !important}}
|
| 220 |
+
|
| 221 |
+
@media (max-width:720px){
|
| 222 |
+
.pre-x-head{padding:16px}
|
| 223 |
+
.pre-x-shead,.pre-x-body{padding:16px}
|
| 224 |
+
.pre-x-foot{padding:12px 16px}
|
| 225 |
+
.pre-x-controls{width:100%;justify-content:flex-end}
|
| 226 |
+
.pre-x-tiles{grid-template-columns:minmax(0,1fr);gap:8px}
|
| 227 |
+
.pre-x-num{font-size:24px}
|
| 228 |
+
.pre-x-counts{grid-template-columns:repeat(2,minmax(0,1fr))}
|
| 229 |
+
}
|
app/explorer.js
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Run explorer behaviour, loaded via gr.HTML(js_on_load=...). Markup comes from inversion/explorer.py.
|
| 2 |
+
// `element` is the component root; it survives re-renders, so one delegated listener handles everything.
|
| 3 |
+
//
|
| 4 |
+
// Navigation: stage panels are <section data-stage>; one is shown at a time.
|
| 5 |
+
// Live follow: while a run streams, the view follows the newest stage until the user navigates away;
|
| 6 |
+
// Play resumes following. Each re-render re-applies the user's stage (watch('value')).
|
| 7 |
+
// Replay: once the run is done, Replay steps through every stage with the design's 3.2 s dwell.
|
| 8 |
+
|
| 9 |
+
const DWELL_MS = 3200;
|
| 10 |
+
const S = { run: null, cur: -1, shown: -1, follow: true, replay: false, timer: null, copyTimer: null, busy: false };
|
| 11 |
+
const $ = (sel) => element.querySelector(sel);
|
| 12 |
+
const $$ = (sel) => Array.from(element.querySelectorAll(sel));
|
| 13 |
+
|
| 14 |
+
const root = () => $('.pre-x');
|
| 15 |
+
const panels = () => $$('.pre-x-stage');
|
| 16 |
+
const isDone = () => { const r = root(); return !!r && r.dataset.done === '1'; };
|
| 17 |
+
const liveIndex = () => { const r = root(); return r ? Number(r.dataset.live || 0) : 0; };
|
| 18 |
+
const usable = (i) => { const p = panels()[i]; return !!p && p.dataset.state !== 'pending'; };
|
| 19 |
+
|
| 20 |
+
function stopReplay() {
|
| 21 |
+
S.replay = false;
|
| 22 |
+
clearTimeout(S.timer);
|
| 23 |
+
S.timer = null;
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
function apply() {
|
| 27 |
+
const r = root();
|
| 28 |
+
if (!r) return;
|
| 29 |
+
S.busy = true;
|
| 30 |
+
const list = panels();
|
| 31 |
+
if (S.cur < 0 || S.cur >= list.length || !usable(S.cur)) S.cur = liveIndex();
|
| 32 |
+
list.forEach((p, i) => {
|
| 33 |
+
p.hidden = i !== S.cur;
|
| 34 |
+
if (i === S.cur && S.shown !== S.cur) {
|
| 35 |
+
p.classList.add('pre-x-enter');
|
| 36 |
+
p.addEventListener('animationend', () => p.classList.remove('pre-x-enter'), { once: true });
|
| 37 |
+
}
|
| 38 |
+
});
|
| 39 |
+
S.shown = S.cur;
|
| 40 |
+
r.classList.toggle('replaying', S.replay);
|
| 41 |
+
r.style.setProperty('--pre-x-dwell', DWELL_MS + 'ms');
|
| 42 |
+
$$('[data-go]').forEach((b) => {
|
| 43 |
+
const i = Number(b.dataset.go);
|
| 44 |
+
const on = i === S.cur;
|
| 45 |
+
b.setAttribute('aria-current', on ? 'step' : 'false');
|
| 46 |
+
b.classList.toggle('is-current', on);
|
| 47 |
+
b.classList.toggle('before', i < S.cur);
|
| 48 |
+
b.classList.toggle('is-timed', on && S.replay);
|
| 49 |
+
});
|
| 50 |
+
$$('.pre-x-group').forEach((g) => g.classList.toggle('active', !!g.querySelector('.is-current')));
|
| 51 |
+
const num = $('[data-role="stepnum"]');
|
| 52 |
+
if (num) num.textContent = String(S.cur + 1);
|
| 53 |
+
const prev = $('[data-act="prev"]');
|
| 54 |
+
const next = $('[data-act="next-top"]');
|
| 55 |
+
if (prev) prev.disabled = S.cur <= 0;
|
| 56 |
+
if (next) next.disabled = !usable(S.cur + 1);
|
| 57 |
+
const play = $('[data-act="play"]');
|
| 58 |
+
if (play) {
|
| 59 |
+
let state;
|
| 60 |
+
let label;
|
| 61 |
+
if (isDone()) { state = S.replay ? 'pause' : 'replay'; label = S.replay ? 'Pause' : 'Replay'; }
|
| 62 |
+
else { state = S.follow ? 'pause' : 'play'; label = S.follow ? 'Pause' : 'Play'; }
|
| 63 |
+
play.dataset.state = state;
|
| 64 |
+
play.setAttribute('aria-label', isDone() ? (S.replay ? 'Pause replay' : 'Replay the run')
|
| 65 |
+
: (S.follow ? 'Stop following the live stage' : 'Follow the live stage'));
|
| 66 |
+
const lbl = play.querySelector('[data-role="playlabel"]');
|
| 67 |
+
if (lbl) lbl.textContent = label;
|
| 68 |
+
}
|
| 69 |
+
S.busy = false;
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
function go(i) {
|
| 73 |
+
if (i < 0 || i >= panels().length || !usable(i)) return;
|
| 74 |
+
stopReplay();
|
| 75 |
+
S.cur = i;
|
| 76 |
+
S.follow = !isDone() && i === liveIndex();
|
| 77 |
+
apply();
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
function scheduleReplay() {
|
| 81 |
+
clearTimeout(S.timer);
|
| 82 |
+
if (!S.replay) return;
|
| 83 |
+
S.timer = setTimeout(() => {
|
| 84 |
+
if (!S.replay) return;
|
| 85 |
+
const last = panels().length - 1;
|
| 86 |
+
if (S.cur >= last) { stopReplay(); apply(); return; }
|
| 87 |
+
S.cur += 1;
|
| 88 |
+
apply();
|
| 89 |
+
scheduleReplay();
|
| 90 |
+
}, DWELL_MS);
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
function togglePlay() {
|
| 94 |
+
if (isDone()) {
|
| 95 |
+
if (S.replay) stopReplay();
|
| 96 |
+
else { S.replay = true; S.cur = 0; }
|
| 97 |
+
apply();
|
| 98 |
+
scheduleReplay();
|
| 99 |
+
return;
|
| 100 |
+
}
|
| 101 |
+
S.follow = !S.follow;
|
| 102 |
+
if (S.follow) S.cur = liveIndex();
|
| 103 |
+
apply();
|
| 104 |
+
}
|
| 105 |
+
|
| 106 |
+
function toggleTarget(btn) {
|
| 107 |
+
const id = btn.getAttribute('aria-controls');
|
| 108 |
+
const el = id ? element.querySelector('#' + id) : null;
|
| 109 |
+
if (!el) return;
|
| 110 |
+
el.hidden = !el.hidden;
|
| 111 |
+
$$('[aria-controls="' + id + '"]').forEach((b) => {
|
| 112 |
+
b.setAttribute('aria-expanded', String(!el.hidden));
|
| 113 |
+
const lbl = b.querySelector('[data-role="label"]');
|
| 114 |
+
if (lbl && b.dataset.on) lbl.textContent = el.hidden ? b.dataset.off : b.dataset.on;
|
| 115 |
+
});
|
| 116 |
+
}
|
| 117 |
+
|
| 118 |
+
function copy(btn) {
|
| 119 |
+
const src = btn.dataset.src ? element.querySelector('#' + btn.dataset.src) : null;
|
| 120 |
+
const text = src ? src.textContent : '';
|
| 121 |
+
const done = () => {
|
| 122 |
+
const lbl = btn.querySelector('[data-role="label"]');
|
| 123 |
+
if (!lbl) return;
|
| 124 |
+
lbl.textContent = 'Copied';
|
| 125 |
+
clearTimeout(S.copyTimer);
|
| 126 |
+
S.copyTimer = setTimeout(() => { lbl.textContent = 'Copy'; }, 1600);
|
| 127 |
+
};
|
| 128 |
+
const fallback = () => {
|
| 129 |
+
const ta = document.createElement('textarea');
|
| 130 |
+
ta.value = text;
|
| 131 |
+
ta.setAttribute('readonly', '');
|
| 132 |
+
ta.style.position = 'fixed';
|
| 133 |
+
ta.style.opacity = '0';
|
| 134 |
+
document.body.appendChild(ta);
|
| 135 |
+
ta.select();
|
| 136 |
+
try { if (document.execCommand('copy')) done(); } catch (err) { /* clipboard unavailable */ }
|
| 137 |
+
ta.remove();
|
| 138 |
+
};
|
| 139 |
+
if (navigator.clipboard && window.isSecureContext) navigator.clipboard.writeText(text).then(done, fallback);
|
| 140 |
+
else fallback();
|
| 141 |
+
}
|
| 142 |
+
|
| 143 |
+
element.addEventListener('click', (ev) => {
|
| 144 |
+
const t = ev.target.closest('[data-act], [data-go]');
|
| 145 |
+
if (!t || !element.contains(t) || t.disabled) return;
|
| 146 |
+
if (t.hasAttribute('data-go')) { go(Number(t.dataset.go)); return; }
|
| 147 |
+
const act = t.dataset.act;
|
| 148 |
+
if (act === 'prev') go(S.cur - 1);
|
| 149 |
+
else if (act === 'next' || act === 'next-top') go(S.cur + 1);
|
| 150 |
+
else if (act === 'play') togglePlay();
|
| 151 |
+
else if (act === 'toggle') toggleTarget(t);
|
| 152 |
+
else if (act === 'copy') copy(t);
|
| 153 |
+
});
|
| 154 |
+
|
| 155 |
+
element.addEventListener('keydown', (ev) => {
|
| 156 |
+
if (ev.key !== 'Escape') return;
|
| 157 |
+
$$('.pre-x-pop:not([hidden])').forEach((pop) => {
|
| 158 |
+
const opener = element.querySelector('.pre-x-help[aria-controls="' + pop.id + '"]');
|
| 159 |
+
if (opener) { toggleTarget(opener); opener.focus(); }
|
| 160 |
+
});
|
| 161 |
+
});
|
| 162 |
+
|
| 163 |
+
function onValue() {
|
| 164 |
+
const r = root();
|
| 165 |
+
const id = r ? r.dataset.run : null;
|
| 166 |
+
if (id !== S.run) {
|
| 167 |
+
S.run = id;
|
| 168 |
+
S.cur = -1;
|
| 169 |
+
S.shown = -1;
|
| 170 |
+
S.follow = true;
|
| 171 |
+
stopReplay();
|
| 172 |
+
}
|
| 173 |
+
if (S.follow && !S.replay) S.cur = liveIndex();
|
| 174 |
+
apply();
|
| 175 |
+
}
|
| 176 |
+
|
| 177 |
+
if (typeof watch === 'function') {
|
| 178 |
+
watch('value', onValue);
|
| 179 |
+
} else {
|
| 180 |
+
new MutationObserver(() => { if (!S.busy) onValue(); }).observe(element, { childList: true });
|
| 181 |
+
}
|
| 182 |
+
onValue();
|
app/theme.css
CHANGED
|
@@ -1,74 +1,270 @@
|
|
| 1 |
-
:root{
|
| 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 |
-
.pre-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
.pre-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
/* Gradio component polish */
|
| 54 |
-
.pre-group
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
.pre-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
}
|
|
|
|
| 1 |
+
:root {
|
| 2 |
+
--pre-text: #14171F;
|
| 3 |
+
--pre-muted: #5B6270;
|
| 4 |
+
--pre-line: #E3E6EB;
|
| 5 |
+
--pre-track: #EEF0F3;
|
| 6 |
+
--pre-card: #FFFFFF;
|
| 7 |
+
--pre-accent: #2B59C3;
|
| 8 |
+
--pre-accent-soft: #EAF0FC;
|
| 9 |
+
--pre-pass: #176B45;
|
| 10 |
+
--pre-pass-bg: #E6F4EC;
|
| 11 |
+
--pre-warn: #9A4508;
|
| 12 |
+
--pre-warn-bg: #FDF0E3
|
| 13 |
+
}
|
| 14 |
+
|
| 15 |
+
.dark {
|
| 16 |
+
--pre-text: #E8EAEE;
|
| 17 |
+
--pre-muted: #A3AAB8;
|
| 18 |
+
--pre-line: #2E333D;
|
| 19 |
+
--pre-track: #2A2F38;
|
| 20 |
+
--pre-card: #171A20;
|
| 21 |
+
--pre-accent: #7FA2F0;
|
| 22 |
+
--pre-accent-soft: #678cda;
|
| 23 |
+
--pre-pass: #7AD3A4;
|
| 24 |
+
--pre-pass-bg: #16332A;
|
| 25 |
+
--pre-warn: #F3B37A;
|
| 26 |
+
--pre-warn-bg: #3A2716
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
.gradio-container {
|
| 30 |
+
max-width: 1280px !important;
|
| 31 |
+
margin: 0 auto !important
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
footer {
|
| 35 |
+
display: none !important
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
.pre-header {
|
| 39 |
+
display: flex;
|
| 40 |
+
flex-wrap: wrap;
|
| 41 |
+
align-items: center;
|
| 42 |
+
justify-content: space-between;
|
| 43 |
+
gap: 12px;
|
| 44 |
+
padding: 8px 0 4px
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
.pre-brand {
|
| 48 |
+
display: flex;
|
| 49 |
+
align-items: center;
|
| 50 |
+
gap: 12px
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
.pre-logo {
|
| 54 |
+
width: 32px;
|
| 55 |
+
height: 32px;
|
| 56 |
+
border-radius: 8px;
|
| 57 |
+
background: var(--pre-text);
|
| 58 |
+
display: flex;
|
| 59 |
+
align-items: center;
|
| 60 |
+
justify-content: center
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
.pre-logo svg {
|
| 64 |
+
stroke: var(--pre-card)
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
.pre-title {
|
| 68 |
+
font-weight: 600;
|
| 69 |
+
font-size: 15px;
|
| 70 |
+
line-height: 1.2;
|
| 71 |
+
color: var(--pre-text)
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
.pre-sub {
|
| 75 |
+
font-size: 12px;
|
| 76 |
+
color: var(--pre-muted)
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
.pre-nav {
|
| 80 |
+
display: flex;
|
| 81 |
+
align-items: center;
|
| 82 |
+
gap: 20px;
|
| 83 |
+
font-size: 13px
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
.pre-nav a {
|
| 87 |
+
text-decoration: none;
|
| 88 |
+
font-weight: 500;
|
| 89 |
+
color: var(--pre-accent)
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
.pre-chip {
|
| 93 |
+
display: inline-flex;
|
| 94 |
+
align-items: center;
|
| 95 |
+
gap: 6px;
|
| 96 |
+
padding: 4px 10px;
|
| 97 |
+
border: 1px solid var(--pre-line);
|
| 98 |
+
border-radius: 999px;
|
| 99 |
+
color: var(--pre-muted);
|
| 100 |
+
font-size: 12px
|
| 101 |
+
}
|
| 102 |
+
|
| 103 |
+
.pre-dot {
|
| 104 |
+
width: 6px;
|
| 105 |
+
height: 6px;
|
| 106 |
+
border-radius: 999px;
|
| 107 |
+
background: #1F8A5B
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
.pre-step-title {
|
| 111 |
+
margin: 0 0 2px;
|
| 112 |
+
font-size: 12px;
|
| 113 |
+
font-weight: 600;
|
| 114 |
+
letter-spacing: .04em;
|
| 115 |
+
text-transform: uppercase;
|
| 116 |
+
color: var(--pre-muted)
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
.pre-card {
|
| 120 |
+
background: var(--pre-card);
|
| 121 |
+
border: 1px solid var(--pre-line);
|
| 122 |
+
border-radius: 12px;
|
| 123 |
+
padding: 20px 24px;
|
| 124 |
+
color: var(--pre-text)
|
| 125 |
+
}
|
| 126 |
+
|
| 127 |
+
.pre-badge {
|
| 128 |
+
display: inline-flex;
|
| 129 |
+
align-items: center;
|
| 130 |
+
gap: 6px;
|
| 131 |
+
padding: 4px 10px;
|
| 132 |
+
border-radius: 999px;
|
| 133 |
+
font-size: 13px;
|
| 134 |
+
font-weight: 600
|
| 135 |
+
}
|
| 136 |
+
|
| 137 |
+
.pre-badge.ok {
|
| 138 |
+
background: var(--pre-pass-bg);
|
| 139 |
+
color: var(--pre-pass)
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
.pre-badge.warn {
|
| 143 |
+
background: var(--pre-warn-bg);
|
| 144 |
+
color: var(--pre-warn)
|
| 145 |
+
}
|
| 146 |
+
|
| 147 |
+
.pre-badge.run {
|
| 148 |
+
background: var(--pre-accent-soft);
|
| 149 |
+
color: var(--pre-accent)
|
| 150 |
+
}
|
| 151 |
+
|
| 152 |
+
@keyframes pre-pulse {
|
| 153 |
+
50% {
|
| 154 |
+
opacity: 1
|
| 155 |
+
}
|
| 156 |
+
}
|
| 157 |
+
|
| 158 |
+
.pre-n {
|
| 159 |
+
font-family: var(--font-mono);
|
| 160 |
+
font-size: 12px;
|
| 161 |
+
color: var(--pre-muted)
|
| 162 |
+
}
|
| 163 |
+
|
| 164 |
+
.pre-intro h1 {
|
| 165 |
+
margin: 0 0 8px;
|
| 166 |
+
font-size: 26px;
|
| 167 |
+
line-height: 1.25;
|
| 168 |
+
font-weight: 600;
|
| 169 |
+
letter-spacing: -.01em
|
| 170 |
+
}
|
| 171 |
+
|
| 172 |
+
.pre-intro p {
|
| 173 |
+
margin: 0;
|
| 174 |
+
max-width: 62ch;
|
| 175 |
+
font-size: 15px;
|
| 176 |
+
color: var(--pre-muted)
|
| 177 |
+
}
|
| 178 |
+
|
| 179 |
+
.pre-how {
|
| 180 |
+
list-style: none;
|
| 181 |
+
margin: 24px 0 0;
|
| 182 |
+
padding: 0;
|
| 183 |
+
display: grid;
|
| 184 |
+
grid-template-columns: repeat(2, minmax(0, 1fr));
|
| 185 |
+
gap: 16px
|
| 186 |
+
}
|
| 187 |
+
|
| 188 |
+
.pre-how li {
|
| 189 |
+
border: 1px solid var(--pre-line);
|
| 190 |
+
border-radius: 10px;
|
| 191 |
+
padding: 18px;
|
| 192 |
+
display: flex;
|
| 193 |
+
flex-direction: column;
|
| 194 |
+
gap: 6px;
|
| 195 |
+
margin: 0
|
| 196 |
+
}
|
| 197 |
+
|
| 198 |
+
.pre-how .pre-n {
|
| 199 |
+
color: var(--pre-accent);
|
| 200 |
+
font-weight: 500
|
| 201 |
+
}
|
| 202 |
+
|
| 203 |
+
.pre-how b {
|
| 204 |
+
font-weight: 600
|
| 205 |
+
}
|
| 206 |
+
|
| 207 |
+
.pre-how span {
|
| 208 |
+
font-size: 13px;
|
| 209 |
+
color: var(--pre-muted)
|
| 210 |
+
}
|
| 211 |
+
|
| 212 |
+
.pre-placeholder {
|
| 213 |
+
margin-top: 16px;
|
| 214 |
+
border: 1.5px dashed var(--pre-line);
|
| 215 |
+
border-radius: 12px;
|
| 216 |
+
min-height: 180px;
|
| 217 |
+
display: flex;
|
| 218 |
+
flex-direction: column;
|
| 219 |
+
align-items: center;
|
| 220 |
+
justify-content: center;
|
| 221 |
+
gap: 6px;
|
| 222 |
+
text-align: center;
|
| 223 |
+
padding: 32px
|
| 224 |
+
}
|
| 225 |
+
|
| 226 |
+
.pre-placeholder span {
|
| 227 |
+
font-size: 13px;
|
| 228 |
+
color: var(--pre-muted);
|
| 229 |
+
max-width: 46ch
|
| 230 |
+
}
|
| 231 |
+
|
| 232 |
/* Gradio component polish */
|
| 233 |
+
.pre-group {
|
| 234 |
+
border-radius: 12px !important;
|
| 235 |
+
overflow: hidden
|
| 236 |
+
}
|
| 237 |
+
|
| 238 |
+
.pre-group-title {
|
| 239 |
+
background: var(--block-background-fill) !important;
|
| 240 |
+
padding: 0 !important;
|
| 241 |
+
min-height: 0 !important
|
| 242 |
+
}
|
| 243 |
+
|
| 244 |
+
.pre-group-title .pre-step-title {
|
| 245 |
+
margin: 0;
|
| 246 |
+
padding: 14px 12px 8px
|
| 247 |
+
}
|
| 248 |
+
|
| 249 |
+
.pre-image {
|
| 250 |
+
border: 1.5px dashed var(--pre-drop) !important;
|
| 251 |
+
border-radius: 8px !important
|
| 252 |
+
}
|
| 253 |
+
|
| 254 |
+
:root {
|
| 255 |
+
--pre-drop: #B9C0CC
|
| 256 |
+
}
|
| 257 |
+
|
| 258 |
+
.dark {
|
| 259 |
+
--pre-drop: #4A5160
|
| 260 |
+
}
|
| 261 |
+
|
| 262 |
+
@media (max-width:720px) {
|
| 263 |
+
.pre-how {
|
| 264 |
+
grid-template-columns: repeat(1, minmax(0, 1fr))
|
| 265 |
+
}
|
| 266 |
+
|
| 267 |
+
.pre-card {
|
| 268 |
+
padding: 16px
|
| 269 |
+
}
|
| 270 |
}
|
cli.py
CHANGED
|
@@ -100,10 +100,10 @@ def main(argv: list[str] | None = None) -> int:
|
|
| 100 |
inv = sub.add_parser("invert", help="run the closed-loop inversion on an image or a folder of images")
|
| 101 |
inv.add_argument("--input", required=True)
|
| 102 |
inv.add_argument("--out", default="runs")
|
| 103 |
-
inv.add_argument("--max-iters", type=int, default=
|
| 104 |
-
inv.add_argument("--vqa-gate", type=float, default=0.
|
| 105 |
-
inv.add_argument("--dino-gate", type=float, default=0.
|
| 106 |
-
inv.add_argument("--fail-threshold", type=float, default=0.
|
| 107 |
inv.add_argument("--w-vqa", type=float, default=0.7)
|
| 108 |
inv.add_argument("--seed", type=int, default=42)
|
| 109 |
inv.add_argument("--no-ground", action="store_true", help="skip pruning predicates false on the original")
|
|
|
|
| 100 |
inv = sub.add_parser("invert", help="run the closed-loop inversion on an image or a folder of images")
|
| 101 |
inv.add_argument("--input", required=True)
|
| 102 |
inv.add_argument("--out", default="runs")
|
| 103 |
+
inv.add_argument("--max-iters", type=int, default=3)
|
| 104 |
+
inv.add_argument("--vqa-gate", type=float, default=0.82)
|
| 105 |
+
inv.add_argument("--dino-gate", type=float, default=0.65)
|
| 106 |
+
inv.add_argument("--fail-threshold", type=float, default=0.70)
|
| 107 |
inv.add_argument("--w-vqa", type=float, default=0.7)
|
| 108 |
inv.add_argument("--seed", type=int, default=42)
|
| 109 |
inv.add_argument("--no-ground", action="store_true", help="skip pruning predicates false on the original")
|
inversion/engine.py
CHANGED
|
@@ -25,17 +25,17 @@ from .vlm import VQA_TEMPLATE
|
|
| 25 |
|
| 26 |
@dataclass
|
| 27 |
class EngineConfig:
|
| 28 |
-
max_iters: int = 3
|
| 29 |
-
vqa_gate: float = 0.82
|
| 30 |
-
dino_gate: float = 0.65
|
| 31 |
-
fail_threshold: float = 0.70
|
| 32 |
-
parent_gate: float = 0.50
|
| 33 |
-
ground: bool = True
|
| 34 |
-
grounding_threshold: float = 0.65
|
| 35 |
-
w_vqa: float = 0.70
|
| 36 |
-
w_dino: float = 0.30
|
| 37 |
-
base_seed: int = 42
|
| 38 |
-
proxy_long_side: int = 512
|
| 39 |
question_template: str = VQA_TEMPLATE
|
| 40 |
|
| 41 |
|
|
@@ -83,6 +83,12 @@ class InversionRun:
|
|
| 83 |
config: EngineConfig
|
| 84 |
models: dict = field(default_factory=dict)
|
| 85 |
status: str = ""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
raw_graph: DSGSceneSchema | None = None
|
| 87 |
graph: DSGSceneSchema | None = None
|
| 88 |
predicates: list[Predicate] = field(default_factory=list)
|
|
@@ -155,6 +161,7 @@ def iter_inversion(og_image: Image.Image, backends: Backends,
|
|
| 155 |
run = InversionRun(config=cfg, models=dict(backends.meta))
|
| 156 |
|
| 157 |
# ---- Module 1: constrained DSG extraction
|
|
|
|
| 158 |
run.status = "Module 1 · extracting constrained scene graph"
|
| 159 |
yield run
|
| 160 |
run.raw_graph = backends.extract_dsg(og)
|
|
@@ -162,6 +169,7 @@ def iter_inversion(og_image: Image.Image, backends: Backends,
|
|
| 162 |
|
| 163 |
# ---- Anti-hallucination grounding: facts false on the OG itself are unfixable
|
| 164 |
if cfg.ground:
|
|
|
|
| 165 |
run.status = f"Module 2 · grounding {len(predicates)} predicates on the original image"
|
| 166 |
yield run
|
| 167 |
og_scores = backends.vqa_scores(og, [p.statement for p in predicates], cfg.question_template)
|
|
@@ -169,6 +177,7 @@ def iter_inversion(og_image: Image.Image, backends: Backends,
|
|
| 169 |
run.graph, run.predicates, run.dropped = prune_hallucinations(
|
| 170 |
run.raw_graph, run.grounding, cfg.grounding_threshold)
|
| 171 |
if any(sp.predicate.kind == "position" for sp in run.dropped):
|
|
|
|
| 172 |
run.status = "Module 2 · re-localizing entities whose grid cell was rejected on the original"
|
| 173 |
yield run
|
| 174 |
_relocalize(run, og, backends, cfg)
|
|
@@ -184,11 +193,13 @@ def iter_inversion(og_image: Image.Image, backends: Backends,
|
|
| 184 |
for t in range(cfg.max_iters):
|
| 185 |
seed = cfg.base_seed + t
|
| 186 |
# ---- Module 3: proxy render
|
|
|
|
| 187 |
run.status = f"t={t + 1}/{cfg.max_iters} · Module 3 · rendering proxy (seed {seed})"
|
| 188 |
yield run
|
| 189 |
proxy = backends.render(prompt, seed, width, height)
|
| 190 |
|
| 191 |
# ---- Module 4: dual verification
|
|
|
|
| 192 |
run.status = f"t={t + 1}/{cfg.max_iters} · Module 4 · scoring {len(statements)} predicates + DINO layout"
|
| 193 |
yield run
|
| 194 |
raw = backends.vqa_scores(proxy, statements, cfg.question_template)
|
|
@@ -201,6 +212,7 @@ def iter_inversion(og_image: Image.Image, backends: Backends,
|
|
| 201 |
|
| 202 |
rec = IterationRecord(t + 1, seed, prompt, proxy, scored, mean_vqa, sim["patch"], sim["cls"], joint, failed)
|
| 203 |
run.iterations.append(rec)
|
|
|
|
| 204 |
if run.best is None or joint > run.best.joint:
|
| 205 |
run.best_index = len(run.iterations) - 1
|
| 206 |
|
|
@@ -217,6 +229,7 @@ def iter_inversion(og_image: Image.Image, backends: Backends,
|
|
| 217 |
notes.append(f"the overall layout: every shape occupies the same position, size, and proportion of the "
|
| 218 |
f"frame as in the original (layout similarity {sim['patch']:.2f} < {cfg.dino_gate:.2f})")
|
| 219 |
rec.rewrite_notes = notes
|
|
|
|
| 220 |
run.status = f"t={t + 1}/{cfg.max_iters} · targeted rewrite of {len(failed)} failed predicate(s)"
|
| 221 |
yield run
|
| 222 |
try:
|
|
@@ -226,6 +239,7 @@ def iter_inversion(og_image: Image.Image, backends: Backends,
|
|
| 226 |
rec.rewrite_error = f"{type(err).__name__}: {err}"
|
| 227 |
|
| 228 |
best = run.best
|
|
|
|
| 229 |
run.status = (f"Done · {run.stop_reason} · best t={best.t}: S_VQA={best.mean_vqa:.3f}, "
|
| 230 |
f"S_DINO={best.dino_patch:.3f}, joint={best.joint:.3f}")
|
| 231 |
yield run
|
|
|
|
| 25 |
|
| 26 |
@dataclass
|
| 27 |
class EngineConfig:
|
| 28 |
+
max_iters: int = 3
|
| 29 |
+
vqa_gate: float = 0.82
|
| 30 |
+
dino_gate: float = 0.65
|
| 31 |
+
fail_threshold: float = 0.70
|
| 32 |
+
parent_gate: float = 0.50
|
| 33 |
+
ground: bool = True
|
| 34 |
+
grounding_threshold: float = 0.65
|
| 35 |
+
w_vqa: float = 0.70
|
| 36 |
+
w_dino: float = 0.30
|
| 37 |
+
base_seed: int = 42
|
| 38 |
+
proxy_long_side: int = 512
|
| 39 |
question_template: str = VQA_TEMPLATE
|
| 40 |
|
| 41 |
|
|
|
|
| 83 |
config: EngineConfig
|
| 84 |
models: dict = field(default_factory=dict)
|
| 85 |
status: str = ""
|
| 86 |
+
# Machine-readable stage for UIs: extract | ground | relocalize | render | verify | rewrite | done,
|
| 87 |
+
# and the 1-based iteration it belongs to (0 before the loop).
|
| 88 |
+
phase: str = "extract"
|
| 89 |
+
phase_t: int = 0
|
| 90 |
+
# Render of the iteration in progress, available while it is being scored (not serialized).
|
| 91 |
+
live_proxy: Image.Image | None = None
|
| 92 |
raw_graph: DSGSceneSchema | None = None
|
| 93 |
graph: DSGSceneSchema | None = None
|
| 94 |
predicates: list[Predicate] = field(default_factory=list)
|
|
|
|
| 161 |
run = InversionRun(config=cfg, models=dict(backends.meta))
|
| 162 |
|
| 163 |
# ---- Module 1: constrained DSG extraction
|
| 164 |
+
run.phase, run.phase_t = "extract", 0
|
| 165 |
run.status = "Module 1 · extracting constrained scene graph"
|
| 166 |
yield run
|
| 167 |
run.raw_graph = backends.extract_dsg(og)
|
|
|
|
| 169 |
|
| 170 |
# ---- Anti-hallucination grounding: facts false on the OG itself are unfixable
|
| 171 |
if cfg.ground:
|
| 172 |
+
run.phase = "ground"
|
| 173 |
run.status = f"Module 2 · grounding {len(predicates)} predicates on the original image"
|
| 174 |
yield run
|
| 175 |
og_scores = backends.vqa_scores(og, [p.statement for p in predicates], cfg.question_template)
|
|
|
|
| 177 |
run.graph, run.predicates, run.dropped = prune_hallucinations(
|
| 178 |
run.raw_graph, run.grounding, cfg.grounding_threshold)
|
| 179 |
if any(sp.predicate.kind == "position" for sp in run.dropped):
|
| 180 |
+
run.phase = "relocalize"
|
| 181 |
run.status = "Module 2 · re-localizing entities whose grid cell was rejected on the original"
|
| 182 |
yield run
|
| 183 |
_relocalize(run, og, backends, cfg)
|
|
|
|
| 193 |
for t in range(cfg.max_iters):
|
| 194 |
seed = cfg.base_seed + t
|
| 195 |
# ---- Module 3: proxy render
|
| 196 |
+
run.phase, run.phase_t, run.live_proxy = "render", t + 1, None
|
| 197 |
run.status = f"t={t + 1}/{cfg.max_iters} · Module 3 · rendering proxy (seed {seed})"
|
| 198 |
yield run
|
| 199 |
proxy = backends.render(prompt, seed, width, height)
|
| 200 |
|
| 201 |
# ---- Module 4: dual verification
|
| 202 |
+
run.phase, run.live_proxy = "verify", proxy
|
| 203 |
run.status = f"t={t + 1}/{cfg.max_iters} · Module 4 · scoring {len(statements)} predicates + DINO layout"
|
| 204 |
yield run
|
| 205 |
raw = backends.vqa_scores(proxy, statements, cfg.question_template)
|
|
|
|
| 212 |
|
| 213 |
rec = IterationRecord(t + 1, seed, prompt, proxy, scored, mean_vqa, sim["patch"], sim["cls"], joint, failed)
|
| 214 |
run.iterations.append(rec)
|
| 215 |
+
run.live_proxy = None
|
| 216 |
if run.best is None or joint > run.best.joint:
|
| 217 |
run.best_index = len(run.iterations) - 1
|
| 218 |
|
|
|
|
| 229 |
notes.append(f"the overall layout: every shape occupies the same position, size, and proportion of the "
|
| 230 |
f"frame as in the original (layout similarity {sim['patch']:.2f} < {cfg.dino_gate:.2f})")
|
| 231 |
rec.rewrite_notes = notes
|
| 232 |
+
run.phase = "rewrite"
|
| 233 |
run.status = f"t={t + 1}/{cfg.max_iters} · targeted rewrite of {len(failed)} failed predicate(s)"
|
| 234 |
yield run
|
| 235 |
try:
|
|
|
|
| 239 |
rec.rewrite_error = f"{type(err).__name__}: {err}"
|
| 240 |
|
| 241 |
best = run.best
|
| 242 |
+
run.phase = "done"
|
| 243 |
run.status = (f"Done · {run.stop_reason} · best t={best.t}: S_VQA={best.mean_vqa:.3f}, "
|
| 244 |
f"S_DINO={best.dino_patch:.3f}, joint={best.joint:.3f}")
|
| 245 |
yield run
|
inversion/explorer.py
ADDED
|
@@ -0,0 +1,630 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Stage-by-stage HTML view of an InversionRun: the Space's run explorer.
|
| 2 |
+
|
| 3 |
+
`render_explorer` turns a run (finished or still streaming) into one HTML string:
|
| 4 |
+
a header (status, step counter, playback controls, a navigator grouped by phase)
|
| 5 |
+
followed by one panel per stage:
|
| 6 |
+
|
| 7 |
+
Setup: Extract scene graph -> Ground on original
|
| 8 |
+
Iteration t: Render proxy -> Verify -> Rewrite failures (absent when the run stopped at t)
|
| 9 |
+
Result: Verified prompt
|
| 10 |
+
|
| 11 |
+
Panels are derived from the run itself, so the number of stages follows the run.
|
| 12 |
+
Every model-produced string is HTML-escaped. Images are referenced through the
|
| 13 |
+
`image_url` callback, so callers decide how renders are served. Navigation, the
|
| 14 |
+
metric popovers and Copy are handled client-side by app/explorer.js; this module
|
| 15 |
+
only emits markup and data-* hooks, and needs no Gradio.
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
from __future__ import annotations
|
| 19 |
+
|
| 20 |
+
import difflib
|
| 21 |
+
import html
|
| 22 |
+
import re
|
| 23 |
+
from dataclasses import dataclass
|
| 24 |
+
from typing import Callable
|
| 25 |
+
|
| 26 |
+
from PIL import Image
|
| 27 |
+
|
| 28 |
+
from .compiler import ScoredPredicate, compile_predicates
|
| 29 |
+
from .engine import InversionRun, IterationRecord
|
| 30 |
+
from .schema import GRID_ORDER
|
| 31 |
+
|
| 32 |
+
LIVE, DONE, PENDING = "live", "done", "pending"
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def esc(value) -> str:
|
| 36 |
+
return html.escape(str(value), quote=True)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def _short(model_id: str | None, fallback: str) -> str:
|
| 40 |
+
return str(model_id).rsplit("/", 1)[-1] if model_id else fallback
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def _dino_name(models: dict) -> str:
|
| 44 |
+
mid = str(models.get("dino_model", "")).lower()
|
| 45 |
+
return "DINOv3" if "dinov3" in mid else "DINOv2" if "dinov2" in mid else "DINO"
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def _plural(n: int, word: str) -> str:
|
| 49 |
+
return f"{n} {word}{'' if n == 1 else 's'}"
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
# --------------------------------------------------------------------------- icons
|
| 53 |
+
|
| 54 |
+
def _svg(paths: str, size: int = 16, stroke: str = "currentColor", width: float = 2) -> str:
|
| 55 |
+
return (f'<svg width="{size}" height="{size}" viewBox="0 0 24 24" fill="none" stroke="{stroke}" '
|
| 56 |
+
f'stroke-width="{width}" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">{paths}</svg>')
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
ICON_CHECK = _svg('<path d="M20 6 9 17l-5-5"/>', 14, width=2.5)
|
| 60 |
+
ICON_DOWN = _svg('<path d="M12 5v14"/><path d="m19 12-7 7-7-7"/>', 12, width=2.5)
|
| 61 |
+
ICON_PREV = _svg('<path d="m15 18-6-6 6-6"/>', 18)
|
| 62 |
+
ICON_NEXT = _svg('<path d="m9 18 6-6-6-6"/>', 18)
|
| 63 |
+
ICON_ARROW = _svg('<path d="M5 12h14"/><path d="m13 6 6 6-6 6"/>', 16)
|
| 64 |
+
ICON_PAUSE = _svg('<path d="M9 5v14"/><path d="M15 5v14"/>')
|
| 65 |
+
ICON_PLAY = _svg('<path d="M7 4.5v15l12-7.5z"/>')
|
| 66 |
+
ICON_REPLAY = _svg('<path d="M3 12a9 9 0 1 0 3-6.7L3 8"/><path d="M3 3v5h5"/>')
|
| 67 |
+
ICON_COPY = _svg('<rect x="9" y="9" width="12" height="12" rx="2"/>'
|
| 68 |
+
'<path d="M5 15H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v1"/>')
|
| 69 |
+
ICON_DOWNLOAD = _svg('<path d="M12 3v12"/><path d="m7 10 5 5 5-5"/><path d="M5 21h14"/>')
|
| 70 |
+
ICON_CHEVRON = _svg('<path d="m6 9 6 6 6-6"/>', 14)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
# --------------------------------------------------------------------------- prompt diff
|
| 74 |
+
|
| 75 |
+
_TOKEN = re.compile(r"\w+|[^\w\s]+|\s+")
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def diff_html(old: str, new: str) -> str:
|
| 79 |
+
"""Word-level diff of two prompts: inserted text in <ins>, removed text in <del>."""
|
| 80 |
+
a, b = _TOKEN.findall(old), _TOKEN.findall(new)
|
| 81 |
+
out = []
|
| 82 |
+
for op, i1, i2, j1, j2 in difflib.SequenceMatcher(a=a, b=b, autojunk=False).get_opcodes():
|
| 83 |
+
removed, added = "".join(a[i1:i2]), "".join(b[j1:j2])
|
| 84 |
+
if op == "equal":
|
| 85 |
+
out.append(esc(added))
|
| 86 |
+
continue
|
| 87 |
+
if removed.strip():
|
| 88 |
+
out.append(f"<del>{esc(removed)}</del>")
|
| 89 |
+
if added.strip():
|
| 90 |
+
out.append(f"<ins>{esc(added)}</ins>")
|
| 91 |
+
elif added:
|
| 92 |
+
out.append(esc(added))
|
| 93 |
+
return "".join(out)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
# --------------------------------------------------------------------------- stage model
|
| 97 |
+
|
| 98 |
+
@dataclass
|
| 99 |
+
class _Stage:
|
| 100 |
+
key: str
|
| 101 |
+
group: str
|
| 102 |
+
label: str
|
| 103 |
+
state: str
|
| 104 |
+
desc: str = ""
|
| 105 |
+
chip: str = "" # escaped HTML for the header's right side
|
| 106 |
+
body: str = ""
|
| 107 |
+
footer: str = ""
|
| 108 |
+
next_label: str = ""
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def _prompt_for(run: InversionRun, t: int) -> str:
|
| 112 |
+
"""The prompt rendered at iteration t (1-based), including the iteration in progress."""
|
| 113 |
+
if t <= len(run.iterations):
|
| 114 |
+
return run.iterations[t - 1].prompt
|
| 115 |
+
if t == 1 or not run.iterations:
|
| 116 |
+
return run.canonical_prompt
|
| 117 |
+
prev = run.iterations[t - 2]
|
| 118 |
+
return prev.patch.prompt if prev.patch else prev.prompt
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def _status_of(sp: ScoredPredicate, fail_threshold: float) -> str:
|
| 122 |
+
if sp.blocked_by:
|
| 123 |
+
return "blocked"
|
| 124 |
+
return "pass" if sp.effective >= fail_threshold else "fail"
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def _gates_met(run: InversionRun, vqa: float, dino: float) -> bool:
|
| 128 |
+
cfg = run.config
|
| 129 |
+
return vqa >= cfg.vqa_gate and dino >= cfg.dino_gate
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
# --------------------------------------------------------------------------- building blocks
|
| 133 |
+
|
| 134 |
+
def _skeleton(text: str) -> str:
|
| 135 |
+
return f'<div class="pre-x-skel" role="status"><span class="pre-x-spin" aria-hidden="true"></span>{esc(text)}</div>'
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def _figure(url: str | None, alt: str, aspect: tuple[int, int], *, caption: str = "", overlay: str = "",
|
| 139 |
+
cls: str = "", badge: str = "", waiting: str = "Rendering…") -> str:
|
| 140 |
+
w, h = aspect
|
| 141 |
+
inner = (f'<img src="{esc(url)}" alt="{esc(alt)}" loading="lazy">' if url
|
| 142 |
+
else f'<div class="pre-x-wait">{_skeleton(waiting)}</div>')
|
| 143 |
+
badge_html = f'<span class="pre-x-best">{esc(badge)}</span>' if badge else ""
|
| 144 |
+
cap = f"<figcaption>{caption}</figcaption>" if caption else ""
|
| 145 |
+
return (f'<figure class="pre-x-fig {cls}"><div class="pre-x-imgbox" style="aspect-ratio:{w} / {h}">'
|
| 146 |
+
f"{inner}{overlay}{badge_html}</div>{cap}</figure>")
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def _cell_box(cell: str, label: str, cls: str, *, strike: bool = False) -> str:
|
| 150 |
+
row, col = divmod(GRID_ORDER.index(cell), 3)
|
| 151 |
+
tag = f"<s>{esc(label)}</s>" if strike else esc(label)
|
| 152 |
+
return (f'<div class="pre-x-cell {cls}" style="left:{col * 33.3333:.4f}%;top:{row * 33.3333:.4f}%">'
|
| 153 |
+
f'<span class="pre-x-tag">{tag}</span></div>')
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
GRID_LINES = "".join(f'<div class="pre-x-gl {axis}" style="{side}:{pos}%"></div>'
|
| 157 |
+
for axis, side in (("v", "left"), ("h", "top")) for pos in ("33.3333", "66.6667"))
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def _badge(kind: str, text: str) -> str:
|
| 161 |
+
return f'<span class="pre-x-b {kind}">{esc(text)}</span>'
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def _row(title: str, detail: str, badge: str, detail_cls: str = "") -> str:
|
| 165 |
+
cls = f' class="{detail_cls}"' if detail_cls else ""
|
| 166 |
+
return (f'<div class="pre-x-row"><div class="pre-x-row-text"><span class="pre-x-row-title">{title}</span>'
|
| 167 |
+
f"<span{cls}>{detail}</span></div>{badge}</div>")
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def _toggle(target: str, label_off: str, label_on: str, cls: str = "pre-x-link") -> str:
|
| 171 |
+
return (f'<button type="button" class="{cls}" data-act="toggle" aria-controls="{target}" aria-expanded="false" '
|
| 172 |
+
f'data-on="{esc(label_on)}" data-off="{esc(label_off)}"><span data-role="label">{esc(label_off)}</span>'
|
| 173 |
+
f"{ICON_CHEVRON}</button>")
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def _sign(d: float) -> str:
|
| 177 |
+
return ("+" if d >= 0 else "−") + f"{abs(d):.2f}"
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def _tile(pid: str, label: str, score: float, digits: int, gate: float | None, note: str, title: str,
|
| 181 |
+
body: str, no_gate_pill: str, no_gate_line: str) -> str:
|
| 182 |
+
has_gate = gate is not None and gate > 0
|
| 183 |
+
ok = has_gate and score >= gate
|
| 184 |
+
cls = "none" if not has_gate else "ok" if ok else "warn"
|
| 185 |
+
if has_gate:
|
| 186 |
+
pill = f"{ICON_CHECK if ok else ICON_DOWN}{'Meets gate' if ok else 'Below gate'} {_sign(score - gate)}"
|
| 187 |
+
gate_line = f"Gate {gate:.2f} · stops the run when met"
|
| 188 |
+
gate_mark = f'<div class="pre-x-meter-gate" style="left:{gate * 100:.0f}%"></div>'
|
| 189 |
+
legend = ('<div class="pre-x-legend"><span class="ok"><i></i>At or above gate</span>'
|
| 190 |
+
'<span class="warn"><i></i>Below gate</span></div>')
|
| 191 |
+
else:
|
| 192 |
+
pill, gate_line, gate_mark, legend = esc(no_gate_pill), no_gate_line, "", ""
|
| 193 |
+
pct = max(0.0, min(1.0, score)) * 100
|
| 194 |
+
return (
|
| 195 |
+
f'<div class="pre-x-tile {cls}">'
|
| 196 |
+
f'<div class="pre-x-tile-top"><span class="pre-x-tile-label">{esc(label)}</span>'
|
| 197 |
+
f'<button type="button" class="pre-x-help" data-act="toggle" aria-controls="{pid}" aria-expanded="false" '
|
| 198 |
+
f'aria-label="What does {esc(label)} measure?"><span aria-hidden="true">?</span></button></div>'
|
| 199 |
+
f'<div class="pre-x-tile-val"><span class="pre-x-num">{score:.{digits}f}</span>'
|
| 200 |
+
f'<span class="pre-x-note">{esc(note)}</span></div>'
|
| 201 |
+
f'<div class="pre-x-meter"><div class="pre-x-meter-fill" style="width:{pct:.0f}%"></div>{gate_mark}</div>'
|
| 202 |
+
f'<span class="pre-x-pill">{pill}</span>'
|
| 203 |
+
f'<div class="pre-x-pop" id="{pid}" role="region" aria-label="{esc(title)}" hidden>'
|
| 204 |
+
f'<div class="pre-x-pop-title">{esc(title)}</div><p>{esc(body)}</p>'
|
| 205 |
+
f'<div class="pre-x-pop-gate">{esc(gate_line)}</div>{legend}'
|
| 206 |
+
f'<button type="button" class="pre-x-btn sm" data-act="toggle" aria-controls="{pid}">Close</button>'
|
| 207 |
+
f"</div></div>"
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
# --------------------------------------------------------------------------- stages
|
| 212 |
+
|
| 213 |
+
def _extract_stage(run: InversionRun, og_url: str, aspect: tuple[int, int]) -> _Stage:
|
| 214 |
+
vlm = _short(run.models.get("vlm_model"), "VLM")
|
| 215 |
+
stage = _Stage("extract", "Setup", "Extract scene graph", LIVE if run.raw_graph is None else DONE,
|
| 216 |
+
desc="The VLM reads the original and writes medium, palette and every object as a node "
|
| 217 |
+
"on a 3 × 3 grid.",
|
| 218 |
+
chip=esc(vlm), next_label="Ground on original")
|
| 219 |
+
g = run.raw_graph
|
| 220 |
+
if g is None:
|
| 221 |
+
stage.body = (f'<div class="pre-x-split">{_figure(og_url, "Original image", aspect)}'
|
| 222 |
+
f'<div class="pre-x-col">{_skeleton("Extracting the scene graph…")}</div></div>')
|
| 223 |
+
stage.footer = "Extracting…"
|
| 224 |
+
return stage
|
| 225 |
+
cells: dict[str, list[str]] = {}
|
| 226 |
+
for node in g.nodes:
|
| 227 |
+
cells.setdefault(node.grid_cell, []).append(node.id)
|
| 228 |
+
overlay = "".join(_cell_box(cell, ", ".join(ids), "node") for cell, ids in cells.items())
|
| 229 |
+
chips = "".join(f'<span class="pre-x-chiplet">{esc(c)}</span>' for c in g.color_palette) or "—"
|
| 230 |
+
checks = (f"<dt>Checks</dt><dd>{' · '.join(esc(c) for c in g.extra_checks)}</dd>" if g.extra_checks else "")
|
| 231 |
+
rows = []
|
| 232 |
+
for node in g.nodes:
|
| 233 |
+
rels = "; ".join(f"{r.predicate} {r.target_id}" for r in node.relations)
|
| 234 |
+
detail = ", ".join(node.attributes) + (f"; {rels}" if rels else "")
|
| 235 |
+
rows.append(f'<tr><td class="mono">{esc(node.id)}</td><td>{esc(node.entity)}</td>'
|
| 236 |
+
f'<td>{esc(node.grid_cell)}</td><td class="muted">{esc(detail) or "—"}</td></tr>')
|
| 237 |
+
stage.body = (
|
| 238 |
+
f'<div class="pre-x-split">'
|
| 239 |
+
f'{_figure(og_url, "Original with each node outlined in its grid cell", aspect, overlay=overlay)}'
|
| 240 |
+
f'<div class="pre-x-col">'
|
| 241 |
+
f'<dl class="pre-x-dl"><dt>Medium</dt><dd>{" · ".join(esc(m) for m in g.medium_and_optics) or "—"}</dd>'
|
| 242 |
+
f"<dt>Background</dt><dd>{esc(g.background) or '—'}</dd>"
|
| 243 |
+
f'<dt>Palette</dt><dd class="pre-x-chips">{chips}</dd>{checks}</dl>'
|
| 244 |
+
f'<div class="pre-x-tablewrap"><table class="pre-x-table"><thead><tr><th>Node</th><th>Entity</th>'
|
| 245 |
+
f'<th>Grid cell</th><th>Attributes and relations</th></tr></thead><tbody>{"".join(rows)}</tbody></table></div>'
|
| 246 |
+
f'<div>{_toggle("pre-x-json", "View raw JSON", "Hide raw JSON")}'
|
| 247 |
+
f'<pre class="pre-x-json" id="pre-x-json" hidden>{esc(g.model_dump_json(indent=2))}</pre></div>'
|
| 248 |
+
f"</div></div>"
|
| 249 |
+
)
|
| 250 |
+
stage.footer = (f"{_plural(len(g.nodes), 'node')} → "
|
| 251 |
+
f"{_plural(len(compile_predicates(g)), 'candidate predicate')} compiled")
|
| 252 |
+
return stage
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
def _ground_stage(run: InversionRun, og_url: str, aspect: tuple[int, int]) -> _Stage:
|
| 256 |
+
cfg = run.config
|
| 257 |
+
if run.raw_graph is None:
|
| 258 |
+
state = PENDING
|
| 259 |
+
elif run.phase in ("ground", "relocalize"):
|
| 260 |
+
state = LIVE
|
| 261 |
+
else:
|
| 262 |
+
state = DONE
|
| 263 |
+
stage = _Stage("ground", "Setup", "Ground on original", state,
|
| 264 |
+
desc="Each candidate predicate is scored on the original. Facts it rejects are dropped "
|
| 265 |
+
"before anything is rendered.",
|
| 266 |
+
chip="VQA scorer", next_label="Render proxy")
|
| 267 |
+
if state != DONE:
|
| 268 |
+
text = ("Re-localizing entities whose grid cell was rejected…" if run.phase == "relocalize"
|
| 269 |
+
else "Scoring every candidate predicate on the original…")
|
| 270 |
+
stage.body = (f'<div class="pre-x-split">{_figure(og_url, "Original image", aspect)}'
|
| 271 |
+
f'<div class="pre-x-col">{_skeleton(text)}</div></div>')
|
| 272 |
+
stage.footer = "Grounding…" if state == LIVE else ""
|
| 273 |
+
return stage
|
| 274 |
+
if not cfg.ground:
|
| 275 |
+
stage.body = (f'<div class="pre-x-split">{_figure(og_url, "Original image", aspect)}'
|
| 276 |
+
f'<div class="pre-x-col"><p class="pre-x-note-box">Grounding is off for this run: all '
|
| 277 |
+
f"{_plural(len(run.predicates), 'candidate predicate')} were kept without checking them "
|
| 278 |
+
f"on the original.</p></div></div>")
|
| 279 |
+
stage.footer = f"{_plural(len(run.predicates), 'predicate')} → prompt v1"
|
| 280 |
+
return stage
|
| 281 |
+
overlay = GRID_LINES + "".join(
|
| 282 |
+
_cell_box(m["from"], m["from"], "from", strike=True) + _cell_box(m["to"], m["to"], "to")
|
| 283 |
+
for m in run.relocalized)
|
| 284 |
+
tiles = "".join(
|
| 285 |
+
f'<div class="pre-x-count{" kept" if key == "Kept" else ""}"><span>{key}</span><b>{n}</b></div>'
|
| 286 |
+
for key, n in (("Candidates", len(run.grounding)), ("Removed", len(run.dropped)),
|
| 287 |
+
("Moved", len(run.relocalized)), ("Kept", len(run.predicates))))
|
| 288 |
+
rows = [_row(esc(sp.predicate.statement),
|
| 289 |
+
f"{esc(sp.predicate.kind)} · P(yes) {sp.raw:.2f} on the original", _badge("removed", "Removed"))
|
| 290 |
+
for sp in run.dropped]
|
| 291 |
+
rows += [_row(esc(m["entity"]), f"position · {esc(m['from'])} → {esc(m['to'])} · P(yes) {m['p_yes']:.2f}",
|
| 292 |
+
_badge("moved", "Re-localized")) for m in run.relocalized]
|
| 293 |
+
listing = "".join(rows) or '<p class="pre-x-note-box">Every candidate held on the original; nothing was removed.</p>'
|
| 294 |
+
stage.body = (
|
| 295 |
+
f'<div class="pre-x-split">'
|
| 296 |
+
f'{_figure(og_url, "Original on a 3 by 3 grid with re-localized cells marked", aspect, overlay=overlay)}'
|
| 297 |
+
f'<div class="pre-x-col"><div class="pre-x-counts">{tiles}</div>'
|
| 298 |
+
f'<div class="pre-x-rows">{listing}</div>'
|
| 299 |
+
f'<p class="pre-x-fine">Pruned when P(yes) on the original < {cfg.grounding_threshold:.2f}.</p></div></div>'
|
| 300 |
+
)
|
| 301 |
+
stage.footer = f"{_plural(len(run.predicates), 'grounded predicate')} → prompt v1"
|
| 302 |
+
return stage
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
def _render_stage(run: InversionRun, t: int, og_url: str, aspect: tuple[int, int],
|
| 306 |
+
image_url: Callable[[Image.Image], str]) -> _Stage:
|
| 307 |
+
cfg = run.config
|
| 308 |
+
it = run.iterations[t - 1] if t <= len(run.iterations) else None
|
| 309 |
+
image = it.proxy_image if it else (run.live_proxy if run.phase_t == t else None)
|
| 310 |
+
state = DONE if image is not None else LIVE
|
| 311 |
+
seed = it.seed if it else cfg.base_seed + t - 1
|
| 312 |
+
proxy = _short(run.models.get("proxy_model"), "proxy")
|
| 313 |
+
stage = _Stage(f"render-{t}", f"Iteration {t}", "Render proxy", state,
|
| 314 |
+
desc=f"Prompt v{t} goes to the proxy generator. The render is what the prompt actually produces.",
|
| 315 |
+
chip=f'<span class="pre-x-chip mono">{esc(proxy)} · seed {seed}</span>', next_label="Verify")
|
| 316 |
+
steps = run.models.get("proxy_steps")
|
| 317 |
+
render_cap = (f'<span class="pre-x-cap"><b>Render · t = {t}</b>'
|
| 318 |
+
f'<span class="mono muted">{f"{steps} steps" if steps else ""}</span></span>')
|
| 319 |
+
figs = (_figure(og_url, "Original image", aspect, caption='<span class="pre-x-cap"><b>Original</b>'
|
| 320 |
+
'<span class="muted">target</span></span>')
|
| 321 |
+
+ _figure(image_url(image) if image is not None else None, f"Proxy render, iteration {t}", aspect,
|
| 322 |
+
caption=render_cap, cls="current"))
|
| 323 |
+
stage.body = (f'<div class="pre-x-stack"><div class="pre-x-pair">{figs}</div>'
|
| 324 |
+
f'<div class="pre-x-block"><div class="pre-x-block-head"><h3>Prompt v{t}</h3>'
|
| 325 |
+
f'<span class="muted">{_plural(len(run.predicates), "grounded predicate" if cfg.ground else "predicate")}'
|
| 326 |
+
f"</span></div>"
|
| 327 |
+
f'<p class="pre-x-prompt">{esc(_prompt_for(run, t))}</p></div></div>')
|
| 328 |
+
w, h = run.proxy_wh or aspect
|
| 329 |
+
stage.footer = f"Render complete · {w} × {h}" if state == DONE else "Rendering…"
|
| 330 |
+
return stage
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
def _verify_stage(run: InversionRun, t: int, idx: int) -> _Stage:
|
| 334 |
+
cfg = run.config
|
| 335 |
+
it = run.iterations[t - 1] if t <= len(run.iterations) else None
|
| 336 |
+
dino_name = _dino_name(run.models)
|
| 337 |
+
stage = _Stage(f"verify-{t}", f"Iteration {t}", "Verify", DONE if it else LIVE,
|
| 338 |
+
desc=f"Every grounded predicate is asked of the render, and layout is compared with {dino_name}.")
|
| 339 |
+
if it is None:
|
| 340 |
+
stage.chip = '<span class="pre-x-chip-plain">Scoring…</span>'
|
| 341 |
+
stage.body = _skeleton(f"Scoring {_plural(len(run.predicates), 'predicate')} and the layout…")
|
| 342 |
+
stage.footer = "Verifying…"
|
| 343 |
+
return stage
|
| 344 |
+
met = _gates_met(run, it.mean_vqa, it.dino_patch)
|
| 345 |
+
verdict = ("Both gates met" if cfg.dino_gate > 0 else "S_VQA gate met") if met else "Gates not met"
|
| 346 |
+
stage.chip = (f'<span class="pre-x-verdict {"ok" if met else "warn"}">'
|
| 347 |
+
f'{ICON_CHECK if met else ""}{esc(verdict)}</span>')
|
| 348 |
+
vqa_body = ("Share of the checkable facts in the prompt (shapes, colors, positions, relations) that a "
|
| 349 |
+
"vision-language model judges true of the render. Each fact is scored by the model’s "
|
| 350 |
+
"probability of answering “yes”; a fact whose object is missing counts as 0.")
|
| 351 |
+
dino_body = (f"How closely the render’s layout matches the original. Both images are compared patch by "
|
| 352 |
+
f"patch with {dino_name} features and the cosine similarities are averaged; 1.00 means identical. "
|
| 353 |
+
f"The score drops when shapes move, resize or flip left to right.")
|
| 354 |
+
joint_body = (f"A weighted blend used to pick the best iteration: {cfg.w_vqa:g} × S_VQA + {cfg.w_dino:g} × "
|
| 355 |
+
f"S_DINO (the weights are in Advanced settings). It has no gate and never stops the run.")
|
| 356 |
+
best_note = f"best of {len(run.iterations)}" if run.best is it and run.phase == "done" else f"iteration {t}"
|
| 357 |
+
tiles = (
|
| 358 |
+
_tile(f"pre-x-help-{idx}-vqa", "Predicate agreement · S_VQA", it.mean_vqa, 2, cfg.vqa_gate,
|
| 359 |
+
f"gate {cfg.vqa_gate:.2f}", "Predicate agreement (S_VQA)", vqa_body, "No gate", "No gate")
|
| 360 |
+
+ _tile(f"pre-x-help-{idx}-dino", "Layout similarity · S_DINO", it.dino_patch, 2, cfg.dino_gate,
|
| 361 |
+
f"gate {cfg.dino_gate:.2f}" if cfg.dino_gate > 0 else "gate off", "Layout similarity (S_DINO)",
|
| 362 |
+
dino_body, "Gate off", "Gate off · the run stops on S_VQA alone")
|
| 363 |
+
+ _tile(f"pre-x-help-{idx}-joint", "Joint score", it.joint, 3, None, best_note, "Joint score",
|
| 364 |
+
joint_body, "Picks the best iteration", "No gate"))
|
| 365 |
+
order = {"fail": 0, "blocked": 1, "pass": 2}
|
| 366 |
+
scored = sorted(it.scored, key=lambda sp: (order[_status_of(sp, cfg.fail_threshold)], sp.raw))
|
| 367 |
+
counts = {k: sum(_status_of(sp, cfg.fail_threshold) == k for sp in scored) for k in order}
|
| 368 |
+
first = counts["fail"] + counts["blocked"] + min(3, counts["pass"])
|
| 369 |
+
labels = {"fail": "Fail", "blocked": "Blocked", "pass": "Pass"}
|
| 370 |
+
|
| 371 |
+
def tr(sp: ScoredPredicate) -> str:
|
| 372 |
+
status = _status_of(sp, cfg.fail_threshold)
|
| 373 |
+
badge = _badge(status, labels[status] if status != "blocked" else
|
| 374 |
+
"Blocked by " + ", ".join(b.split(":", 1)[-1] for b in sp.blocked_by))
|
| 375 |
+
return (f'<tr><td class="muted">{esc(sp.predicate.kind)}</td><td>{esc(sp.predicate.statement)}</td>'
|
| 376 |
+
f'<td class="mono">{sp.raw:.2f}</td><td>{badge}</td></tr>')
|
| 377 |
+
|
| 378 |
+
rest = scored[first:]
|
| 379 |
+
more_id = f"pre-x-more-{idx}"
|
| 380 |
+
more_body = f'<tbody id="{more_id}" hidden>{"".join(tr(sp) for sp in rest)}</tbody>' if rest else ""
|
| 381 |
+
more_btn = (_toggle(more_id, f"Show all {len(scored)} predicates", "Show fewer") if rest else "")
|
| 382 |
+
table = (f'<div class="pre-x-tablewrap"><table class="pre-x-table"><thead><tr><th>Kind</th><th>Predicate</th>'
|
| 383 |
+
f'<th>P(yes)</th><th>Status</th></tr></thead><tbody>{"".join(tr(sp) for sp in scored[:first])}</tbody>'
|
| 384 |
+
f"{more_body}</table></div>")
|
| 385 |
+
fine = (f'<p class="pre-x-fine">{counts["fail"]} failed · {counts["blocked"]} blocked · {counts["pass"]} passed'
|
| 386 |
+
f" · failure threshold P(yes) < {cfg.fail_threshold:.2f}</p>")
|
| 387 |
+
stage.body = (f'<div class="pre-x-stack"><div class="pre-x-tiles">{tiles}</div>{table}'
|
| 388 |
+
f'<div class="pre-x-tablefoot">{fine}{more_btn}</div></div>')
|
| 389 |
+
|
| 390 |
+
def cmp(v: float, g: float) -> str:
|
| 391 |
+
return f"{v:.2f} {'≥' if v >= g else '<'} {g:.2f}"
|
| 392 |
+
|
| 393 |
+
last = t == len(run.iterations)
|
| 394 |
+
if last and run.stop_reason == "converged":
|
| 395 |
+
then = "stop"
|
| 396 |
+
elif last and run.stop_reason == "max_iters" and run.best is not None:
|
| 397 |
+
then = f"max iterations reached → return best (t = {run.best.t})"
|
| 398 |
+
else:
|
| 399 |
+
then = "rewrite"
|
| 400 |
+
dino_part = f"S_DINO {cmp(it.dino_patch, cfg.dino_gate)}" if cfg.dino_gate > 0 else "S_DINO gate off"
|
| 401 |
+
stage.footer = f"S_VQA {cmp(it.mean_vqa, cfg.vqa_gate)} · {dino_part} → {then}"
|
| 402 |
+
stage.next_label = "Rewrite failures" if then == "rewrite" else "Verified prompt"
|
| 403 |
+
return stage
|
| 404 |
+
|
| 405 |
+
|
| 406 |
+
def _rewrite_stage(run: InversionRun, it: IterationRecord) -> _Stage:
|
| 407 |
+
cfg, t = run.config, it.t
|
| 408 |
+
live = it.patch is None and it.rewrite_error is None
|
| 409 |
+
stage = _Stage(f"rewrite-{t}", f"Iteration {t}", "Rewrite failures", LIVE if live else DONE,
|
| 410 |
+
desc="Only the clauses behind failed predicates change. Everything that passed is left word "
|
| 411 |
+
"for word.", next_label="Render proxy")
|
| 412 |
+
if live:
|
| 413 |
+
stage.chip = '<span class="pre-x-chip-plain">Rewriting…</span>'
|
| 414 |
+
stage.body = _skeleton(f"Rewriting {_plural(len(it.failed), 'failed predicate')}…")
|
| 415 |
+
stage.footer = "Rewriting…"
|
| 416 |
+
return stage
|
| 417 |
+
sent = [_row(esc(sp.predicate.statement), f"P(yes) {sp.raw:.2f}", _badge("fail", "Failed"), "warn mono")
|
| 418 |
+
for sp in it.failed]
|
| 419 |
+
if it.dino_patch < cfg.dino_gate:
|
| 420 |
+
sent.append(_row("Overall layout", f"S_DINO {it.dino_patch:.2f} < {cfg.dino_gate:.2f}",
|
| 421 |
+
_badge("fail", "Below gate"), "warn mono"))
|
| 422 |
+
edits: list[str] = []
|
| 423 |
+
if it.patch is not None:
|
| 424 |
+
for ed in it.patch.applied:
|
| 425 |
+
edits.append(_row(f'<span class="mono">{esc(ed["original"])}</span>',
|
| 426 |
+
f'<span class="mono">→ {esc(ed["revised"])}</span>', _badge("moved", "Edited")))
|
| 427 |
+
for sentence in it.patch.added:
|
| 428 |
+
edits.append(_row(f'<span class="mono">+ {esc(sentence)}</span>', "new sentence",
|
| 429 |
+
_badge("moved", "Added")))
|
| 430 |
+
for sk in it.patch.skipped:
|
| 431 |
+
text = sk.get("original") or sk.get("addition") or ""
|
| 432 |
+
edits.append(_row(f'<span class="mono">{esc(text)}</span>', esc(sk.get("reason", "")),
|
| 433 |
+
_badge("removed", "Skipped")))
|
| 434 |
+
if it.rewrite_error:
|
| 435 |
+
edits.append(f'<p class="pre-x-error">The rewriter failed: {esc(it.rewrite_error)}. The next iteration '
|
| 436 |
+
f"re-renders the same prompt with a new seed.</p>")
|
| 437 |
+
applied = len(it.patch.applied) if it.patch else 0
|
| 438 |
+
added = len(it.patch.added) if it.patch else 0
|
| 439 |
+
skipped = len(it.patch.skipped) if it.patch else 0
|
| 440 |
+
stage.chip = esc(f"{_plural(applied, 'edit')} · {added} added" + (f" · {skipped} skipped" if skipped else ""))
|
| 441 |
+
new_prompt = it.patch.prompt if it.patch else it.prompt
|
| 442 |
+
stage.body = (
|
| 443 |
+
f'<div class="pre-x-stack">'
|
| 444 |
+
f'<div class="pre-x-block"><div class="pre-x-block-head"><h3>Sent to the rewriter</h3></div>'
|
| 445 |
+
f'<div class="pre-x-rows">{"".join(sent) or "<p class=pre-x-note-box>No failed predicates.</p>"}</div></div>'
|
| 446 |
+
f'<div class="pre-x-block"><div class="pre-x-block-head"><h3>Edits</h3></div>'
|
| 447 |
+
f'<div class="pre-x-rows">{"".join(edits) or "<p class=pre-x-note-box>No edits.</p>"}</div></div>'
|
| 448 |
+
f'<div class="pre-x-block"><div class="pre-x-block-head"><h3>Prompt v{t + 1}</h3>'
|
| 449 |
+
f'<span class="muted">changes highlighted</span></div>'
|
| 450 |
+
f'<p class="pre-x-prompt diff">{diff_html(it.prompt, new_prompt)}</p></div></div>'
|
| 451 |
+
)
|
| 452 |
+
stage.footer = f"Iteration {t + 1} uses prompt v{t + 1} and seed {cfg.base_seed + t}"
|
| 453 |
+
return stage
|
| 454 |
+
|
| 455 |
+
|
| 456 |
+
def _result_stage(run: InversionRun, og_url: str, aspect: tuple[int, int],
|
| 457 |
+
image_url: Callable[[Image.Image], str], report_url: str | None) -> _Stage:
|
| 458 |
+
done = run.phase == "done" and run.best is not None
|
| 459 |
+
stage = _Stage("result", "Result", "Verified prompt", DONE if done else PENDING)
|
| 460 |
+
if not done:
|
| 461 |
+
stage.body = _skeleton("The verified prompt appears when the run finishes.")
|
| 462 |
+
return stage
|
| 463 |
+
best, n = run.best, len(run.iterations)
|
| 464 |
+
stage.desc = (f"From iteration {best.t} of {n} · {_plural(len(run.predicates), 'predicate')} "
|
| 465 |
+
f"grounded on the original")
|
| 466 |
+
report = (f'<a class="pre-x-btn" href="{esc(report_url)}" download="inversion_report.json">'
|
| 467 |
+
f"{ICON_DOWNLOAD}Report (JSON)</a>" if report_url else "")
|
| 468 |
+
stage.chip = (f'<div class="pre-x-actions"><button type="button" class="pre-x-btn" data-act="copy" '
|
| 469 |
+
f'data-src="pre-x-final">{ICON_COPY}<span data-role="label">Copy</span></button>{report}</div>')
|
| 470 |
+
proxy = _short(run.models.get("proxy_model"), "proxy")
|
| 471 |
+
figs = [_figure(og_url, "Original image", aspect,
|
| 472 |
+
caption='<span class="pre-x-cap"><b>Original</b><span class="muted">target</span></span>')]
|
| 473 |
+
for it in run.iterations:
|
| 474 |
+
figs.append(_figure(image_url(it.proxy_image), f"Proxy render, iteration {it.t}", aspect,
|
| 475 |
+
caption=f'<span class="pre-x-cap"><b>t = {it.t}</b><span class="mono muted">'
|
| 476 |
+
f"VQA {it.mean_vqa:.2f} · DINO {it.dino_patch:.2f}</span></span>",
|
| 477 |
+
cls="current" if it is best else "", badge="Best" if it is best else ""))
|
| 478 |
+
rows = []
|
| 479 |
+
for it in run.iterations:
|
| 480 |
+
if it.rewrite_error:
|
| 481 |
+
rewrite = "Rewrite error"
|
| 482 |
+
elif it.patch is not None:
|
| 483 |
+
rewrite = (f"{_plural(len(it.patch.applied), 'edit')}, {len(it.patch.added)} added, "
|
| 484 |
+
f"{len(it.patch.skipped)} skipped")
|
| 485 |
+
elif it is run.iterations[-1]:
|
| 486 |
+
rewrite = "Stopped: gates met" if run.stop_reason == "converged" else "Stopped: max iterations"
|
| 487 |
+
else:
|
| 488 |
+
rewrite = "—"
|
| 489 |
+
rows.append(f'<tr><td><b>{it.t}{" · best" if it is best else ""}</b></td><td class="mono">{it.seed}</td>'
|
| 490 |
+
f'<td class="mono">{it.mean_vqa:.3f}</td><td class="mono">{it.dino_patch:.3f}</td>'
|
| 491 |
+
f'<td class="mono">{it.joint:.3f}</td><td class="mono">{len(it.failed)}</td>'
|
| 492 |
+
f'<td class="muted">{esc(rewrite)}</td></tr>')
|
| 493 |
+
stage.body = (
|
| 494 |
+
f'<div class="pre-x-stack"><p class="pre-x-final" id="pre-x-final">{esc(run.best_prompt)}</p>'
|
| 495 |
+
f'<div class="pre-x-block"><div class="pre-x-block-head"><h3>Original vs. proxy renders</h3>'
|
| 496 |
+
f'<span class="muted mono">{esc(proxy)} · seed = {run.config.base_seed - 1} + t</span></div>'
|
| 497 |
+
f'<div class="pre-x-cmp">{"".join(figs)}</div></div>'
|
| 498 |
+
f'<div class="pre-x-block"><div class="pre-x-block-head"><h3>Run summary</h3></div>'
|
| 499 |
+
f'<div class="pre-x-tablewrap"><table class="pre-x-table"><thead><tr><th>Iteration</th><th>Seed</th>'
|
| 500 |
+
f"<th>S_VQA</th><th>S_DINO</th><th>Joint</th><th>Failed</th><th>Rewrite</th></tr></thead>"
|
| 501 |
+
f'<tbody>{"".join(rows)}</tbody></table></div></div></div>'
|
| 502 |
+
)
|
| 503 |
+
return stage
|
| 504 |
+
|
| 505 |
+
|
| 506 |
+
def _stages(run: InversionRun, og_url: str, aspect: tuple[int, int],
|
| 507 |
+
image_url: Callable[[Image.Image], str], report_url: str | None) -> list[_Stage]:
|
| 508 |
+
stages = [_extract_stage(run, og_url, aspect), _ground_stage(run, og_url, aspect)]
|
| 509 |
+
in_loop = run.phase in ("render", "verify", "rewrite", "done")
|
| 510 |
+
n_iters = max(len(run.iterations), run.phase_t if in_loop else 0, 1)
|
| 511 |
+
for t in range(1, n_iters + 1):
|
| 512 |
+
started = in_loop and (t <= len(run.iterations) or run.phase_t == t)
|
| 513 |
+
if not started:
|
| 514 |
+
stages.append(_Stage(f"render-{t}", f"Iteration {t}", "Render proxy", PENDING,
|
| 515 |
+
body=_skeleton("Waiting for grounding to finish…")))
|
| 516 |
+
stages.append(_Stage(f"verify-{t}", f"Iteration {t}", "Verify", PENDING,
|
| 517 |
+
body=_skeleton("Waiting for the render…")))
|
| 518 |
+
continue
|
| 519 |
+
stages.append(_render_stage(run, t, og_url, aspect, image_url))
|
| 520 |
+
if t <= len(run.iterations) or run.phase == "verify":
|
| 521 |
+
stages.append(_verify_stage(run, t, len(stages)))
|
| 522 |
+
else:
|
| 523 |
+
stages.append(_Stage(f"verify-{t}", f"Iteration {t}", "Verify", PENDING,
|
| 524 |
+
body=_skeleton("Waiting for the render…")))
|
| 525 |
+
it = run.iterations[t - 1] if t <= len(run.iterations) else None
|
| 526 |
+
rewrite_live = run.phase == "rewrite" and run.phase_t == t
|
| 527 |
+
if it is not None and (it.patch is not None or it.rewrite_error is not None or rewrite_live):
|
| 528 |
+
stages.append(_rewrite_stage(run, it))
|
| 529 |
+
stages.append(_result_stage(run, og_url, aspect, image_url, report_url))
|
| 530 |
+
return stages
|
| 531 |
+
|
| 532 |
+
|
| 533 |
+
# --------------------------------------------------------------------------- page
|
| 534 |
+
|
| 535 |
+
def _status_line(run: InversionRun, stages: list[_Stage], live: int) -> str:
|
| 536 |
+
cfg = run.config
|
| 537 |
+
if run.phase == "done" and run.best is not None:
|
| 538 |
+
if run.stop_reason == "converged":
|
| 539 |
+
gates = "Both gates met" if cfg.dino_gate > 0 else "S_VQA gate met"
|
| 540 |
+
return f"{gates} at iteration {run.best.t} of up to {cfg.max_iters}"
|
| 541 |
+
return f"Returning the best of {len(run.iterations)} iterations (t = {run.best.t})"
|
| 542 |
+
stage = stages[live]
|
| 543 |
+
if stage.group == "Setup":
|
| 544 |
+
extra = " · re-localizing" if run.phase == "relocalize" else ""
|
| 545 |
+
return f"Setup · {stage.label}{extra}"
|
| 546 |
+
return f"{stage.group} of up to {cfg.max_iters} · {stage.label}"
|
| 547 |
+
|
| 548 |
+
|
| 549 |
+
def render_explorer(run: InversionRun, *, og_url: str, og_size: tuple[int, int],
|
| 550 |
+
image_url: Callable[[Image.Image], str], report_url: str | None = None,
|
| 551 |
+
run_id: str = "") -> str:
|
| 552 |
+
"""HTML for the stage-by-stage run explorer (see module docstring)."""
|
| 553 |
+
stages = _stages(run, og_url, og_size, image_url, report_url)
|
| 554 |
+
done = run.phase == "done" and run.best is not None
|
| 555 |
+
if done:
|
| 556 |
+
live = len(stages) - 1
|
| 557 |
+
else:
|
| 558 |
+
live = max((i for i, s in enumerate(stages) if s.state == LIVE), default=0)
|
| 559 |
+
total = len(stages)
|
| 560 |
+
|
| 561 |
+
if done and run.stop_reason == "converged":
|
| 562 |
+
badge = f'<span class="pre-badge ok">{ICON_CHECK}Converged</span>'
|
| 563 |
+
elif done:
|
| 564 |
+
badge = '<span class="pre-badge warn">Gates not met</span>'
|
| 565 |
+
else:
|
| 566 |
+
badge = '<span class="pre-badge run"><span class="pre-x-pulse" aria-hidden="true"></span>Running</span>'
|
| 567 |
+
|
| 568 |
+
groups: list[tuple[str, list[int]]] = []
|
| 569 |
+
for i, st in enumerate(stages):
|
| 570 |
+
if groups and groups[-1][0] == st.group:
|
| 571 |
+
groups[-1][1].append(i)
|
| 572 |
+
else:
|
| 573 |
+
groups.append((st.group, [i]))
|
| 574 |
+
nav = []
|
| 575 |
+
for name, idxs in groups:
|
| 576 |
+
active = live in idxs
|
| 577 |
+
items = []
|
| 578 |
+
for i in idxs:
|
| 579 |
+
st = stages[i]
|
| 580 |
+
off = " disabled" if st.state == PENDING else ""
|
| 581 |
+
items.append(
|
| 582 |
+
f'<li><button type="button" class="pre-x-step {st.state}" data-go="{i}"{off} '
|
| 583 |
+
f'aria-current="{"step" if i == live else "false"}">'
|
| 584 |
+
f'<span class="pre-x-track"><span class="pre-x-fill"></span></span>'
|
| 585 |
+
f'<span class="pre-x-stepnum">{i + 1:02d}</span><span class="pre-x-steplabel">{esc(st.label)}</span>'
|
| 586 |
+
f"</button></li>")
|
| 587 |
+
nav.append(f'<div class="pre-x-group{" active" if active else ""}" style="flex:{len(idxs)} 1 0">'
|
| 588 |
+
f'<div class="pre-x-glabel">{esc(name)}</div>'
|
| 589 |
+
f'<ol style="grid-template-columns:repeat({len(idxs)},minmax(0,1fr))">{"".join(items)}</ol></div>')
|
| 590 |
+
|
| 591 |
+
play_state = "replay" if done else "pause"
|
| 592 |
+
play_label = "Replay" if done else "Pause"
|
| 593 |
+
head = (
|
| 594 |
+
f'<section class="pre-x-head" aria-label="Run progress"><div class="pre-x-headrow">'
|
| 595 |
+
f'<div class="pre-x-headstatus">{badge}<span class="pre-x-status" aria-live="polite">'
|
| 596 |
+
f"{esc(_status_line(run, stages, live))}</span></div>"
|
| 597 |
+
f'<div class="pre-x-controls"><span class="pre-x-counter mono">Step <span data-role="stepnum">{live + 1}'
|
| 598 |
+
f"</span> / {total}</span>"
|
| 599 |
+
f'<button type="button" class="pre-x-icon" data-act="prev" aria-label="Previous stage">{ICON_PREV}</button>'
|
| 600 |
+
f'<button type="button" class="pre-x-play" data-act="play" data-state="{play_state}">'
|
| 601 |
+
f'<span class="i-pause">{ICON_PAUSE}</span><span class="i-play">{ICON_PLAY}</span>'
|
| 602 |
+
f'<span class="i-replay">{ICON_REPLAY}</span><span data-role="playlabel">{play_label}</span></button>'
|
| 603 |
+
f'<button type="button" class="pre-x-icon" data-act="next-top" aria-label="Next stage">{ICON_NEXT}</button>'
|
| 604 |
+
f'</div></div><nav class="pre-x-nav" aria-label="Run stages"><div class="pre-x-groups">{"".join(nav)}'
|
| 605 |
+
f"</div></nav></section>"
|
| 606 |
+
)
|
| 607 |
+
|
| 608 |
+
panels = []
|
| 609 |
+
for i, st in enumerate(stages):
|
| 610 |
+
nxt = stages[i + 1] if i + 1 < total else None
|
| 611 |
+
if nxt is not None:
|
| 612 |
+
label = "See verified prompt" if nxt.key == "result" else f"Next: {nxt.label}"
|
| 613 |
+
off = " disabled" if nxt.state == PENDING else ""
|
| 614 |
+
next_btn = (f'<button type="button" class="pre-x-next" data-act="next"{off}>{esc(label)}'
|
| 615 |
+
f"{ICON_ARROW}</button>")
|
| 616 |
+
else:
|
| 617 |
+
next_btn = ""
|
| 618 |
+
foot = (f'<footer class="pre-x-foot"><span>{esc(st.footer)}</span>{next_btn}</footer>'
|
| 619 |
+
if (st.footer or next_btn) and st.state != PENDING else "")
|
| 620 |
+
chip = st.chip if st.chip.startswith("<") else (f'<span class="pre-x-chip">{st.chip}</span>' if st.chip else "")
|
| 621 |
+
desc = f"<p>{esc(st.desc)}</p>" if st.desc else ""
|
| 622 |
+
hidden = "" if i == live else " hidden"
|
| 623 |
+
panels.append(
|
| 624 |
+
f'<section class="pre-x-stage" data-stage="{i}" data-state="{st.state}"{hidden} '
|
| 625 |
+
f'aria-label="{esc(st.group)}: {esc(st.label)}"><header class="pre-x-shead"><div>'
|
| 626 |
+
f'<div class="pre-x-kicker mono">{esc(st.group)} · {i + 1:02d}</div><h2>{esc(st.label)}</h2>{desc}</div>'
|
| 627 |
+
f'{chip}</header><div class="pre-x-body">{st.body}</div>{foot}</section>')
|
| 628 |
+
|
| 629 |
+
return (f'<div class="pre-x" data-run="{esc(run_id)}" data-live="{live}" data-done="{1 if done else 0}" '
|
| 630 |
+
f'data-count="{total}">{head}{"".join(panels)}</div>')
|
tests/test_engine.py
CHANGED
|
@@ -251,7 +251,7 @@ class StubWorld:
|
|
| 251 |
|
| 252 |
def test_loop_converges_after_targeted_rewrite():
|
| 253 |
world = StubWorld()
|
| 254 |
-
run = invert_image_to_verified_prompt(world.og, world.backends(), EngineConfig(max_iters=5))
|
| 255 |
assert run.stop_reason == "converged"
|
| 256 |
assert len(run.iterations) == 2 and world.rewrites == 1
|
| 257 |
assert "ochre" not in run.canonical_prompt # pruned during grounding
|
|
@@ -289,7 +289,7 @@ def test_grounding_relocalizes_rejected_grid_cell(sign_really_at, expect_move):
|
|
| 289 |
|
| 290 |
def test_loop_hits_max_iters_and_keeps_best():
|
| 291 |
world = StubWorld(fix_on_rewrite=False)
|
| 292 |
-
run = invert_image_to_verified_prompt(world.og, world.backends(), EngineConfig(max_iters=3))
|
| 293 |
assert run.stop_reason == "max_iters"
|
| 294 |
assert len(run.iterations) == 3 and world.rewrites == 2 # no rewrite after the final render
|
| 295 |
assert run.iterations[0].patch.skipped and run.best_prompt == run.canonical_prompt
|
|
|
|
| 251 |
|
| 252 |
def test_loop_converges_after_targeted_rewrite():
|
| 253 |
world = StubWorld()
|
| 254 |
+
run = invert_image_to_verified_prompt(world.og, world.backends(), EngineConfig(max_iters=5, vqa_gate=0.90, dino_gate=0.80))
|
| 255 |
assert run.stop_reason == "converged"
|
| 256 |
assert len(run.iterations) == 2 and world.rewrites == 1
|
| 257 |
assert "ochre" not in run.canonical_prompt # pruned during grounding
|
|
|
|
| 289 |
|
| 290 |
def test_loop_hits_max_iters_and_keeps_best():
|
| 291 |
world = StubWorld(fix_on_rewrite=False)
|
| 292 |
+
run = invert_image_to_verified_prompt(world.og, world.backends(), EngineConfig(max_iters=3, vqa_gate=0.90, dino_gate=0.80))
|
| 293 |
assert run.stop_reason == "max_iters"
|
| 294 |
assert len(run.iterations) == 3 and world.rewrites == 2 # no rewrite after the final render
|
| 295 |
assert run.iterations[0].patch.skipped and run.best_prompt == run.canonical_prompt
|
tests/test_explorer.py
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Run explorer (inversion/explorer.py): stages follow the run, model text is escaped, gates are coloured."""
|
| 2 |
+
|
| 3 |
+
import re
|
| 4 |
+
|
| 5 |
+
import pytest
|
| 6 |
+
|
| 7 |
+
from inversion import DSGSceneSchema, EngineConfig, RewritePatch, iter_inversion
|
| 8 |
+
from inversion.explorer import diff_html, render_explorer
|
| 9 |
+
from test_engine import GRAPH, StubWorld
|
| 10 |
+
|
| 11 |
+
GATES = dict(vqa_gate=0.90, dino_gate=0.80)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def render(run, **kw):
|
| 15 |
+
return render_explorer(run, og_url="OG.webp", og_size=(640, 480), image_url=lambda im: f"IMG-{id(im)}",
|
| 16 |
+
run_id="run-1", **kw)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def stages(html):
|
| 20 |
+
"""[(label, state)] in navigator order."""
|
| 21 |
+
found = re.findall(r'class="pre-x-step (\w+)"[^>]*>.*?<span class="pre-x-steplabel">([^<]+)</span>', html)
|
| 22 |
+
return [(label, state) for state, label in found]
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def live(html):
|
| 26 |
+
return int(re.search(r'data-live="(\d+)"', html).group(1))
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def snapshots(world, cfg):
|
| 30 |
+
"""Explorer HTML and (phase, phase_t) at every streamed yield."""
|
| 31 |
+
out = []
|
| 32 |
+
for run in iter_inversion(world.og, world.backends(), cfg):
|
| 33 |
+
out.append((run.phase, run.phase_t, render(run)))
|
| 34 |
+
return run, out
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def test_phase_is_set_at_every_yield():
|
| 38 |
+
_, snaps = snapshots(StubWorld(), EngineConfig(max_iters=5, **GATES))
|
| 39 |
+
assert [(p, t) for p, t, _ in snaps] == [
|
| 40 |
+
("extract", 0), ("ground", 0), ("render", 1), ("verify", 1), ("rewrite", 1),
|
| 41 |
+
("render", 2), ("verify", 2), ("done", 2)]
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def test_stages_follow_the_run_and_live_stage_is_never_pending():
|
| 45 |
+
run, snaps = snapshots(StubWorld(), EngineConfig(max_iters=5, **GATES))
|
| 46 |
+
for phase, _, html in snaps:
|
| 47 |
+
st = stages(html)
|
| 48 |
+
assert st[live(html)][1] != "pending", phase
|
| 49 |
+
first, last = snaps[0][2], snaps[-1][2]
|
| 50 |
+
assert stages(first) == [("Extract scene graph", "live"), ("Ground on original", "pending"),
|
| 51 |
+
("Render proxy", "pending"), ("Verify", "pending"), ("Verified prompt", "pending")]
|
| 52 |
+
assert stages(last) == [(label, "done") for label in (
|
| 53 |
+
"Extract scene graph", "Ground on original", "Render proxy", "Verify", "Rewrite failures",
|
| 54 |
+
"Render proxy", "Verify", "Verified prompt")]
|
| 55 |
+
assert live(last) == len(stages(last)) - 1
|
| 56 |
+
assert 'data-done="1"' in last and "Converged" in last
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def test_render_stage_shows_the_image_while_it_is_being_scored():
|
| 60 |
+
world = StubWorld()
|
| 61 |
+
for run in iter_inversion(world.og, world.backends(), EngineConfig(max_iters=1, **GATES)):
|
| 62 |
+
if run.phase == "verify":
|
| 63 |
+
html = render(run)
|
| 64 |
+
assert f"IMG-{id(run.live_proxy)}" in html
|
| 65 |
+
assert stages(html)[2:4] == [("Render proxy", "done"), ("Verify", "live")]
|
| 66 |
+
break
|
| 67 |
+
else:
|
| 68 |
+
pytest.fail("no verify phase")
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def test_verify_tiles_are_coloured_against_the_gates():
|
| 72 |
+
run, snaps = snapshots(StubWorld(), EngineConfig(max_iters=5, **GATES))
|
| 73 |
+
html = snaps[-1][2]
|
| 74 |
+
# t=1: S_VQA 0.87 < 0.90 -> warn; S_DINO 1.00 >= 0.80 -> ok; joint has no gate.
|
| 75 |
+
verify1 = html.split('aria-label="Iteration 1: Verify"')[1].split("</section>")[0]
|
| 76 |
+
tiles = re.findall(r'class="pre-x-tile (\w+)"', verify1)
|
| 77 |
+
assert tiles == ["warn", "ok", "none"]
|
| 78 |
+
assert "Below gate −0.03" in verify1 and "Meets gate +0.20" in verify1
|
| 79 |
+
assert verify1.count('class="pre-x-help"') == 3 and verify1.count('class="pre-x-pop"') == 3
|
| 80 |
+
assert "&lt;" not in verify1 # footer text is escaped once, not twice
|
| 81 |
+
assert "S_VQA 0.87 < 0.90 · S_DINO 1.00 ≥ 0.80 → rewrite" in verify1
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def test_dino_gate_off_and_max_iters_wording():
|
| 85 |
+
world = StubWorld(fix_on_rewrite=False)
|
| 86 |
+
run, snaps = snapshots(world, EngineConfig(max_iters=2, vqa_gate=0.90, dino_gate=0.0))
|
| 87 |
+
html = snaps[-1][2]
|
| 88 |
+
assert run.stop_reason == "max_iters"
|
| 89 |
+
assert "Gates not met" in html and "Returning the best of 2 iterations" in html
|
| 90 |
+
assert "Gate off" in html and "S_DINO gate off" in html
|
| 91 |
+
assert "max iterations reached → return best (t = 1)" in html
|
| 92 |
+
# the rewriter's unusable edit is shown as skipped, with its reason
|
| 93 |
+
assert "original span not found verbatim" in html and ">Skipped<" in html
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def test_grounding_off_and_rewrite_error():
|
| 97 |
+
world = StubWorld()
|
| 98 |
+
|
| 99 |
+
def boom(*args):
|
| 100 |
+
raise RuntimeError("rewriter offline")
|
| 101 |
+
|
| 102 |
+
backends = world.backends()
|
| 103 |
+
backends.rewrite = boom
|
| 104 |
+
run = None
|
| 105 |
+
for run in iter_inversion(world.og, backends, EngineConfig(max_iters=2, ground=False, **GATES)):
|
| 106 |
+
pass
|
| 107 |
+
html = render(run)
|
| 108 |
+
assert "Grounding is off for this run" in html
|
| 109 |
+
assert "The rewriter failed: RuntimeError: rewriter offline" in html
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def test_model_text_is_escaped():
|
| 113 |
+
world = StubWorld()
|
| 114 |
+
evil = {**GRAPH, "background": 'a <script>alert("x")</script> wall',
|
| 115 |
+
"nodes": [{**GRAPH["nodes"][0], "entity": 'a <img src=x onerror=alert(1)> circle'}] + GRAPH["nodes"][1:]}
|
| 116 |
+
world.extract = lambda image: DSGSceneSchema.model_validate(evil)
|
| 117 |
+
run, snaps = snapshots(world, EngineConfig(max_iters=1, ground=False, **GATES))
|
| 118 |
+
html = snaps[-1][2]
|
| 119 |
+
assert "<script>" not in html and "<img src=x" not in html
|
| 120 |
+
assert "<script>alert("x")</script>" in html
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def test_image_urls_come_from_the_callback_and_report_link_only_when_given():
|
| 124 |
+
run, snaps = snapshots(StubWorld(), EngineConfig(max_iters=5, **GATES))
|
| 125 |
+
html = snaps[-1][2]
|
| 126 |
+
for it in run.iterations:
|
| 127 |
+
assert f'src="IMG-{id(it.proxy_image)}"' in html
|
| 128 |
+
assert 'src="OG.webp"' in html
|
| 129 |
+
assert "download=" not in html
|
| 130 |
+
assert 'href="files/report.json"' in render(run, report_url="files/report.json")
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def test_diff_marks_insertions_and_removals():
|
| 134 |
+
new = "a large red circle (sharp edges; one third)."
|
| 135 |
+
out = diff_html("a red circle (sharp edges).", new)
|
| 136 |
+
assert re.findall(r"<ins>(.*?)</ins>", out) == [" large", "; one third"] and "<del>" not in out
|
| 137 |
+
assert re.sub(r"</?ins>", "", out) == new # nothing lost or duplicated
|
| 138 |
+
assert diff_html("rotated 45 degrees", "rotated 30 degrees") == "rotated <del>45</del><ins>30</ins> degrees"
|
| 139 |
+
assert "<b>" in diff_html("x", "x <b>")
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def test_rewrite_stage_lists_edits_and_prompt_diff():
|
| 143 |
+
run, snaps = snapshots(StubWorld(), EngineConfig(max_iters=5, **GATES))
|
| 144 |
+
html = snaps[-1][2]
|
| 145 |
+
rewrite = html.split('aria-label="Iteration 1: Rewrite failures"')[1].split("</section>")[0]
|
| 146 |
+
assert "1 edit · 0 added" in rewrite
|
| 147 |
+
assert "rotated 45 degrees" in rewrite and "<ins>, clearly</ins>" in rewrite
|
| 148 |
+
assert "Iteration 2 uses prompt v2 and seed 43" in rewrite
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def test_patch_skips_are_reported_on_results(monkeypatch):
|
| 152 |
+
patch = RewritePatch(edits=[{"original": "zero drop shadows", "revised": "vintage shadows"}])
|
| 153 |
+
world = StubWorld()
|
| 154 |
+
world.rewrite = lambda *a: patch
|
| 155 |
+
run, snaps = snapshots(world, EngineConfig(max_iters=2, **GATES))
|
| 156 |
+
assert "unverified style/era terms" in snaps[-1][2]
|