Download scripts/render_html.py from ramachandrajoshi/LoopedPhai-A1-35B: direct link, hf CLI and curl.
- Browser
- Download file 5.18 kB
-
https://huggingface.co/ramachandrajoshi/LoopedPhai-A1-35B/resolve/main/scripts/render_html.py
- Command line
-
hf download hf://ramachandrajoshi/LoopedPhai-A1-35B/scripts/render_html.py
-
curl -L -o render_html.py https://huggingface.co/ramachandrajoshi/LoopedPhai-A1-35B/resolve/main/scripts/render_html.py
5.18 kB
| #!/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() | |