Spaces:
Running on Zero
Running on Zero
Download tests/test_explorer.py from glarr/Prompt-Reverse-Engineer: direct link, hf CLI and curl.
- Browser
- Download file 6.82 kB
-
https://huggingface.co/spaces/glarr/Prompt-Reverse-Engineer/resolve/main/tests/test_explorer.py
- Command line
-
hf download hf://spaces/glarr/Prompt-Reverse-Engineer/tests/test_explorer.py
-
curl -L -o test_explorer.py https://huggingface.co/spaces/glarr/Prompt-Reverse-Engineer/resolve/main/tests/test_explorer.py
6.82 kB
| """Run explorer (inversion/explorer.py): stages follow the run, model text is escaped, gates are coloured.""" | |
| import re | |
| import pytest | |
| from inversion import DSGSceneSchema, EngineConfig, RewritePatch, iter_inversion | |
| from inversion.explorer import diff_html, render_explorer | |
| from test_engine import GRAPH, StubWorld | |
| GATES = dict(vqa_gate=0.90, dino_gate=0.80) | |
| def render(run, **kw): | |
| return render_explorer(run, og_url="OG.webp", og_size=(640, 480), image_url=lambda im: f"IMG-{id(im)}", | |
| run_id="run-1", **kw) | |
| def stages(html): | |
| """[(label, state)] in navigator order.""" | |
| found = re.findall(r'class="pre-x-step (\w+)"[^>]*>.*?<span class="pre-x-steplabel">([^<]+)</span>', html) | |
| return [(label, state) for state, label in found] | |
| def live(html): | |
| return int(re.search(r'data-live="(\d+)"', html).group(1)) | |
| def snapshots(world, cfg): | |
| """Explorer HTML and (phase, phase_t) at every streamed yield.""" | |
| out = [] | |
| for run in iter_inversion(world.og, world.backends(), cfg): | |
| out.append((run.phase, run.phase_t, render(run))) | |
| return run, out | |
| def test_phase_is_set_at_every_yield(): | |
| _, snaps = snapshots(StubWorld(), EngineConfig(max_iters=5, **GATES)) | |
| assert [(p, t) for p, t, _ in snaps] == [ | |
| ("extract", 0), ("ground", 0), ("render", 1), ("verify", 1), ("rewrite", 1), | |
| ("render", 2), ("verify", 2), ("done", 2)] | |
| def test_stages_follow_the_run_and_live_stage_is_never_pending(): | |
| run, snaps = snapshots(StubWorld(), EngineConfig(max_iters=5, **GATES)) | |
| for phase, _, html in snaps: | |
| st = stages(html) | |
| assert st[live(html)][1] != "pending", phase | |
| first, last = snaps[0][2], snaps[-1][2] | |
| assert stages(first) == [("Extract scene graph", "live"), ("Ground on original", "pending"), | |
| ("Render proxy", "pending"), ("Verify", "pending"), ("Verified prompt", "pending")] | |
| assert stages(last) == [(label, "done") for label in ( | |
| "Extract scene graph", "Ground on original", "Render proxy", "Verify", "Rewrite failures", | |
| "Render proxy", "Verify", "Verified prompt")] | |
| assert live(last) == len(stages(last)) - 1 | |
| assert 'data-done="1"' in last and "Converged" in last | |
| def test_render_stage_shows_the_image_while_it_is_being_scored(): | |
| world = StubWorld() | |
| for run in iter_inversion(world.og, world.backends(), EngineConfig(max_iters=1, **GATES)): | |
| if run.phase == "verify": | |
| html = render(run) | |
| assert f"IMG-{id(run.live_proxy)}" in html | |
| assert stages(html)[2:4] == [("Render proxy", "done"), ("Verify", "live")] | |
| break | |
| else: | |
| pytest.fail("no verify phase") | |
| def test_verify_tiles_are_coloured_against_the_gates(): | |
| run, snaps = snapshots(StubWorld(), EngineConfig(max_iters=5, **GATES)) | |
| html = snaps[-1][2] | |
| # t=1: S_VQA 0.87 < 0.90 -> warn; S_DINO 1.00 >= 0.80 -> ok; joint has no gate. | |
| verify1 = html.split('aria-label="Iteration 1: Verify"')[1].split("</section>")[0] | |
| tiles = re.findall(r'class="pre-x-tile (\w+)"', verify1) | |
| assert tiles == ["warn", "ok", "none"] | |
| assert "Below gate −0.03" in verify1 and "Meets gate +0.20" in verify1 | |
| assert verify1.count('class="pre-x-help"') == 3 and verify1.count('class="pre-x-pop"') == 3 | |
| assert "&lt;" not in verify1 # footer text is escaped once, not twice | |
| assert "S_VQA 0.87 < 0.90 · S_DINO 1.00 ≥ 0.80 → rewrite" in verify1 | |
| def test_dino_gate_off_and_max_iters_wording(): | |
| world = StubWorld(fix_on_rewrite=False) | |
| run, snaps = snapshots(world, EngineConfig(max_iters=2, vqa_gate=0.90, dino_gate=0.0)) | |
| html = snaps[-1][2] | |
| assert run.stop_reason == "max_iters" | |
| assert "Gates not met" in html and "Returning the best of 2 iterations" in html | |
| assert "Gate off" in html and "S_DINO gate off" in html | |
| assert "max iterations reached → return best (t = 1)" in html | |
| # the rewriter's unusable edit is shown as skipped, with its reason | |
| assert "original span not found verbatim" in html and ">Skipped<" in html | |
| def test_grounding_off_and_rewrite_error(): | |
| world = StubWorld() | |
| def boom(*args): | |
| raise RuntimeError("rewriter offline") | |
| backends = world.backends() | |
| backends.rewrite = boom | |
| run = None | |
| for run in iter_inversion(world.og, backends, EngineConfig(max_iters=2, ground=False, **GATES)): | |
| pass | |
| html = render(run) | |
| assert "Grounding is off for this run" in html | |
| assert "The rewriter failed: RuntimeError: rewriter offline" in html | |
| def test_model_text_is_escaped(): | |
| world = StubWorld() | |
| evil = {**GRAPH, "background": 'a <script>alert("x")</script> wall', | |
| "nodes": [{**GRAPH["nodes"][0], "entity": 'a <img src=x onerror=alert(1)> circle'}] + GRAPH["nodes"][1:]} | |
| world.extract = lambda image: DSGSceneSchema.model_validate(evil) | |
| run, snaps = snapshots(world, EngineConfig(max_iters=1, ground=False, **GATES)) | |
| html = snaps[-1][2] | |
| assert "<script>" not in html and "<img src=x" not in html | |
| assert "<script>alert("x")</script>" in html | |
| def test_image_urls_come_from_the_callback_and_report_link_only_when_given(): | |
| run, snaps = snapshots(StubWorld(), EngineConfig(max_iters=5, **GATES)) | |
| html = snaps[-1][2] | |
| for it in run.iterations: | |
| assert f'src="IMG-{id(it.proxy_image)}"' in html | |
| assert 'src="OG.webp"' in html | |
| assert "download=" not in html | |
| assert 'href="files/report.json"' in render(run, report_url="files/report.json") | |
| def test_diff_marks_insertions_and_removals(): | |
| new = "a large red circle (sharp edges; one third)." | |
| out = diff_html("a red circle (sharp edges).", new) | |
| assert re.findall(r"<ins>(.*?)</ins>", out) == [" large", "; one third"] and "<del>" not in out | |
| assert re.sub(r"</?ins>", "", out) == new # nothing lost or duplicated | |
| assert diff_html("rotated 45 degrees", "rotated 30 degrees") == "rotated <del>45</del><ins>30</ins> degrees" | |
| assert "<b>" in diff_html("x", "x <b>") | |
| def test_rewrite_stage_lists_edits_and_prompt_diff(): | |
| run, snaps = snapshots(StubWorld(), EngineConfig(max_iters=5, **GATES)) | |
| html = snaps[-1][2] | |
| rewrite = html.split('aria-label="Iteration 1: Rewrite failures"')[1].split("</section>")[0] | |
| assert "1 edit · 0 added" in rewrite | |
| assert "rotated 45 degrees" in rewrite and "<ins>, clearly</ins>" in rewrite | |
| assert "Iteration 2 uses prompt v2 and seed 43" in rewrite | |
| def test_patch_skips_are_reported_on_results(monkeypatch): | |
| patch = RewritePatch(edits=[{"original": "zero drop shadows", "revised": "vintage shadows"}]) | |
| world = StubWorld() | |
| world.rewrite = lambda *a: patch | |
| run, snaps = snapshots(world, EngineConfig(max_iters=2, **GATES)) | |
| assert "unverified style/era terms" in snaps[-1][2] | |