#!/usr/bin/env python3 """Render-and-look refinement for visual coding tasks (three.js scenes, canvas, SVG pages). The model writes a page; the page is rendered in headless Chromium; the screenshot and any JavaScript errors are sent back to the model (which has a vision tower), which critiques its own output against the request and returns a corrected page. Repeat for a few rounds. export OPENAI_BASE_URL=http://localhost:8000/v1 OPENAI_API_KEY=none python scripts/visual_refine.py --model looped-phai --id pagoda --best-of 4 --rounds 3 python scripts/visual_refine.py --model looped-phai --prompt "Using three.js, build ..." --name my_scene python scripts/visual_refine.py --model looped-phai --all # every prompt in data/visual_prompts.jsonl Needs a server that accepts images: vLLM with the default `...ForConditionalGeneration` architecture (not the text-only `--hf-overrides` variant), or llama.cpp `llama-server` with the model's `--mmproj`. Without vision use --no-vision (only JS errors are fed back). Output: //{cand_k,round_r}.{html,png,json} and index.html showing the progression. """ from __future__ import annotations import argparse import base64 import html import json import os import sys from concurrent.futures import ThreadPoolExecutor from pathlib import Path HERE = Path(__file__).resolve().parent sys.path.insert(0, str(HERE)) from eval_code_api import make_caller # noqa: E402 from render_html import Renderer, extract_html # noqa: E402 CRITIQUE = """Above is a screenshot of how your page actually renders (1280x800 viewport, about 3 seconds after load). {errors} Compare the screenshot carefully with the original request. First list every concrete problem you can see: missing or wrong parts, wrong shapes, proportions or positions, parts floating or intersecting, wrong colours, bad lighting, camera framing (is the whole subject visible and centred?), missing animation, overlapping text. Then output the COMPLETE corrected HTML file in a single ```html code block (not a diff).""" def rank_key(r: dict) -> tuple: """Best candidate: renders without errors, then the most visual content (pixel std).""" return (r is not None and r["ok"], not (r or {}).get("page_errors"), (r or {}).get("pixel_std", 0.0)) def image_part(png: Path) -> dict: b64 = base64.b64encode(png.read_bytes()).decode() return {"type": "image_url", "image_url": {"url": f"data:image/png;base64,{b64}"}} def refine_one(name: str, prompt: str, args, call, renderer: Renderer) -> dict: out = Path(args.out) / name out.mkdir(parents=True, exist_ok=True) steps = [] def save(stem: str, gen: dict) -> dict: page = extract_html(gen["answer"]) rec = {"stem": stem, "tokens": gen.get("completion_tokens"), "finish": gen.get("finish")} (out / f"{stem}.answer.md").write_text(gen["answer"], encoding="utf-8") if page is None: rec["render"] = None else: (out / f"{stem}.html").write_text(page, encoding="utf-8") rec["render"] = renderer.render(page, out / f"{stem}.png") (out / f"{stem}.json").write_text(json.dumps(rec, indent=2)) rec["answer"] = gen["answer"] steps.append(rec) r = rec["render"] status = "no html" if r is None else ("ok" if r["ok"] else f"errors={len(r['page_errors'])} blank={r['blank']}") print(f"[refine] {name} {stem}: {status} tokens={rec['tokens']}", flush=True) return rec # 1) best-of-N first drafts (generated in parallel, rendered one by one) with ThreadPoolExecutor(args.best_of) as pool: gens = list(pool.map(lambda k: call([{"role": "user", "content": prompt}], seed=args.seed + k), range(args.best_of))) cands = [save(f"cand_{k}", g) for k, g in enumerate(gens)] best = max(cands, key=lambda r: rank_key(r["render"])) print(f"[refine] {name}: start from {best['stem']}", flush=True) # 2) look-and-fix rounds cur = best for rnd in range(1, args.rounds + 1): r = cur["render"] if r is None: fb = [{"type": "text", "text": "Your answer did not contain a ```html code block. Output the COMPLETE " "HTML file in a single ```html code block."}] else: errs = r["page_errors"] + ([r["load_error"]] if r.get("load_error") else []) err_txt = ("JavaScript errors while loading:\n" + "\n".join(f"- {e}" for e in errs[:8]) if errs else "There were no JavaScript errors.") if r["blank"]: err_txt += "\nThe page rendered as an empty/uniform screen." text = CRITIQUE.format(errors=err_txt) png = out / f"{cur['stem']}.png" fb = ([image_part(png)] if not args.no_vision and png.exists() else []) + [{"type": "text", "text": text}] if args.no_vision: fb[-1]["text"] = text.replace("Above is a screenshot of", "You cannot see the screenshot of") msgs = [{"role": "user", "content": prompt}, {"role": "assistant", "content": cur["answer"]}, {"role": "user", "content": fb}] nxt = save(f"round_{rnd}", call(msgs, seed=args.seed + 100 + rnd)) # keep the new version unless it broke a page that worked if rank_key(nxt["render"])[:2] >= rank_key(cur["render"])[:2]: cur = nxt write_index(out, name, prompt, steps, cur["stem"]) return {"name": name, "final": cur["stem"], "final_ok": bool(cur["render"] and cur["render"]["ok"])} def write_index(out: Path, name: str, prompt: str, steps: list[dict], final: str) -> None: cards = [] for s in steps: r = s["render"] img = f'' if (out / f"{s['stem']}.png").exists() else "

no page

" errs = "" if r is None else html.escape("; ".join(r["page_errors"][:2])) mark = " ★ final" if s["stem"] == final else "" cards.append(f'

{s["stem"]}{mark}

{img}' f'

{errs}

answer
') (out / "index.html").write_text( "" + html.escape(name) + "" f"

{html.escape(name)}

{html.escape(prompt)}
{''.join(cards)}
", encoding="utf-8") def main() -> None: ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("--model", required=True) ap.add_argument("--base-url", default=os.environ.get("OPENAI_BASE_URL")) g = ap.add_mutually_exclusive_group(required=True) g.add_argument("--id", help="a prompt id from --visual-file (e.g. pagoda)") g.add_argument("--prompt", help="your own prompt (use --name to name the output folder)") g.add_argument("--all", action="store_true") ap.add_argument("--name", default="custom") ap.add_argument("--visual-file", default=str(HERE.parent / "data" / "visual_prompts.jsonl")) ap.add_argument("--best-of", type=int, default=4) ap.add_argument("--rounds", type=int, default=3) ap.add_argument("--no-vision", action="store_true") ap.add_argument("--max-tokens", type=int, default=32768) ap.add_argument("--temperature", type=float, default=1.0) ap.add_argument("--greedy", action="store_true") ap.add_argument("--no-thinking", action="store_true") ap.add_argument("--seed", type=int, default=0) ap.add_argument("--out", default="runs/visual_refine") args = ap.parse_args() if not args.base_url: raise SystemExit("set OPENAI_BASE_URL or --base-url") prompts = {r["id"]: r["prompt"] for r in map(json.loads, open(args.visual_file, encoding="utf-8"))} if args.prompt: todo = [(args.name, args.prompt)] elif args.all: todo = list(prompts.items()) else: todo = [(args.id, prompts[args.id])] call = make_caller(args) results = [] with Renderer() as renderer: for name, prompt in todo: results.append(refine_one(name, prompt, args, call, renderer)) print(json.dumps(results, indent=2)) if __name__ == "__main__": main()