File size: 8,564 Bytes
daf7aaa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
#!/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: <out>/<name>/{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'<img src="{s["stem"]}.png">' if (out / f"{s['stem']}.png").exists() else "<p>no page</p>"
        errs = "" if r is None else html.escape("; ".join(r["page_errors"][:2]))
        mark = " ★ final" if s["stem"] == final else ""
        cards.append(f'<div class="c"><h3>{s["stem"]}{mark}</h3><a href="{s["stem"]}.html">{img}</a>'
                     f'<p class="e">{errs}</p><a href="{s["stem"]}.answer.md">answer</a></div>')
    (out / "index.html").write_text(
        "<!doctype html><meta charset=utf-8><title>" + html.escape(name) + "</title><style>body{font-family:sans-serif;"
        "margin:20px}.g{display:grid;grid-template-columns:repeat(auto-fill,minmax(360px,1fr));gap:14px}.c img{width:100%;"
        "border:1px solid #ccc}.e{color:#b00;font-size:12px}pre{white-space:pre-wrap;color:#444}</style>"
        f"<h1>{html.escape(name)}</h1><pre>{html.escape(prompt)}</pre><div class=g>{''.join(cards)}</div>",
        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()