File size: 5,178 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
#!/usr/bin/env python3
"""Render a model-written single-file HTML page in headless Chromium and screenshot it.

Used by the visual coding eval (`eval_code_api.py --bench visual`) and the render-and-look
refinement loop (`visual_refine.py`).

Safety: the page is untrusted model output. It runs in Chromium's own renderer sandbox, every
network request except to a small allow-list of JS/CSS CDNs (three.js, d3, ...) is aborted,
downloads are refused, and nothing on the local disk is served to it.

Setup (once):
    pip install playwright && python -m playwright install chromium
    sudo python -m playwright install-deps chromium      # system libraries
On a machine without sudo, missing .so files (e.g. libasound.so.2 from `apt-get download
libasound2t64 && dpkg -x`) can be put in ~/.cache/ms-playwright/extra-libs; they are picked up here.

    python scripts/render_html.py page.html out.png      # quick manual check
"""
from __future__ import annotations

import json
import os
import re
import sys
from pathlib import Path
from typing import Optional
from urllib.parse import urlparse

CDN_HOSTS = {
    "cdn.jsdelivr.net", "unpkg.com", "cdnjs.cloudflare.com", "esm.sh", "cdn.skypack.dev", "ga.jspm.io",
    "threejs.org", "cdn.tailwindcss.com", "fonts.googleapis.com", "fonts.gstatic.com", "d3js.org",
    "cdn.babylonjs.com", "code.jquery.com",
}
EXTRA_LIBS = Path.home() / ".cache" / "ms-playwright" / "extra-libs"

_HTML_BLOCK = re.compile(r"```(?:html|HTML)?[ \t]*\n(.*?)```", re.S)


def extract_html(text: str) -> Optional[str]:
    """The page from a model answer: the longest ```html block, or the raw answer if it is HTML."""
    final = text.split("</think>")[-1]
    blocks = [b for b in _HTML_BLOCK.findall(final) if "<" in b]
    if blocks:
        return max(blocks, key=len)
    s = final.strip()
    if s.lower().startswith(("<!doctype html", "<html")):
        return s
    return None


class Renderer:
    """One headless browser reused across pages (create once, call `render` many times)."""

    def __init__(self, width: int = 1280, height: int = 800) -> None:
        from playwright.sync_api import sync_playwright

        env = dict(os.environ)
        if EXTRA_LIBS.is_dir():
            env["LD_LIBRARY_PATH"] = f"{EXTRA_LIBS}:{env.get('LD_LIBRARY_PATH', '')}".rstrip(":")
        self._pw = sync_playwright().start()
        # SwiftShader = software WebGL, so three.js scenes render without a GPU in the browser.
        self._browser = self._pw.chromium.launch(args=["--use-angle=swiftshader", "--enable-unsafe-swiftshader"],
                                                 env=env)
        self.size = {"width": width, "height": height}

    def close(self) -> None:
        self._browser.close()
        self._pw.stop()

    def __enter__(self) -> "Renderer":
        return self

    def __exit__(self, *exc) -> None:
        self.close()

    def render(self, html: str, png_path: str | Path, wait_ms: int = 3000) -> dict:
        """Load `html`, let it run for `wait_ms`, screenshot to `png_path`.

        Returns {"ok", "page_errors", "console_errors", "blocked", "blank", "pixel_std"}; ok means
        the page loaded, threw no uncaught error and is not a blank/uniform screen."""
        ctx = self._browser.new_context(viewport=self.size, accept_downloads=False)
        page = ctx.new_page()
        page_errors, console_errors, blocked = [], [], []
        page.on("pageerror", lambda e: page_errors.append(str(e)[:300]))
        page.on("console", lambda m: console_errors.append(m.text[:300]) if m.type == "error" else None)

        def route(r):
            u = urlparse(r.request.url)
            if u.scheme in ("data", "blob", "about") or (u.scheme == "https" and u.hostname in CDN_HOSTS):
                return r.continue_()
            blocked.append(r.request.url[:200])
            return r.abort()

        page.route("**/*", route)
        load_error = None
        try:
            page.set_content(html, wait_until="load", timeout=30000)
            page.wait_for_timeout(wait_ms)
            page.screenshot(path=str(png_path))
        except Exception as e:  # noqa: BLE001  (timeouts, crashes of the page)
            load_error = f"{type(e).__name__}: {str(e)[:300]}"
        finally:
            ctx.close()
        std = _pixel_std(png_path) if load_error is None else 0.0
        blank = std < 2.0
        return {"ok": load_error is None and not page_errors and not blank, "load_error": load_error,
                "page_errors": page_errors[:10], "console_errors": console_errors[:10], "blocked": blocked[:10],
                "blank": blank, "pixel_std": round(std, 2)}


def _pixel_std(png_path: str | Path) -> float:
    """Std-dev of grey levels: ~0 for an empty/uniform page."""
    from PIL import Image, ImageStat

    with Image.open(png_path) as im:
        return float(ImageStat.Stat(im.convert("L")).stddev[0])


def main() -> None:
    if len(sys.argv) != 3:
        raise SystemExit("usage: render_html.py page.html out.png")
    with Renderer() as r:
        print(json.dumps(r.render(Path(sys.argv[1]).read_text(), sys.argv[2]), indent=2))


if __name__ == "__main__":
    main()