UIPress / scripts /step_clip_batch.py
DesonDai's picture
Add files using upload-large-folder tool
7c33ebc verified
"""
Batch CLIP scoring for all benchmark results.
Computes CLIP similarity between generated HTML screenshots and reference images.
Usage:
conda activate uipress-qwen
CUDA_VISIBLE_DEVICES=X PYTHONPATH=. python scripts/step_clip_batch.py
"""
import os
os.environ["HF_ENDPOINT"] = os.environ.get("HF_ENDPOINT", "https://hf-mirror.com")
os.environ["HF_HOME"] = os.environ.get("HF_HOME", "/root/rivermind-data/huggingface")
import json
import sys
import tempfile
from pathlib import Path
import torch
from PIL import Image
from tqdm import tqdm
PROJECT_ROOT = Path(__file__).parent.parent
class CLIPScorer:
def __init__(self, device="cuda"):
import open_clip
self.device = device
self.model, _, self.preprocess = open_clip.create_model_and_transforms(
"ViT-B-32", pretrained="openai"
)
self.model = self.model.to(device).eval()
@torch.no_grad()
def score(self, img1, img2):
t1 = self.preprocess(img1).unsqueeze(0).to(self.device)
t2 = self.preprocess(img2).unsqueeze(0).to(self.device)
f1 = self.model.encode_image(t1)
f2 = self.model.encode_image(t2)
f1 = f1 / f1.norm(dim=-1, keepdim=True)
f2 = f2 / f2.norm(dim=-1, keepdim=True)
return float((f1 * f2).sum())
def render_html(html_path, output_path, width=1280, height=1024):
try:
from playwright.sync_api import sync_playwright
abs_path = os.path.abspath(html_path)
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page(viewport={"width": width, "height": height})
page.goto(f"file://{abs_path}", wait_until="networkidle", timeout=30000)
page.screenshot(path=output_path, full_page=False)
browser.close()
return True
except Exception as e:
try:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
opts = Options()
opts.add_argument("--headless")
opts.add_argument("--no-sandbox")
opts.add_argument(f"--window-size={width},{height}")
driver = webdriver.Chrome(options=opts)
driver.get(f"file://{os.path.abspath(html_path)}")
import time; time.sleep(2)
driver.save_screenshot(output_path)
driver.quit()
return True
except:
return False
def eval_method(method_dir, ref_dir, scorer, tmp_dir):
html_dir = Path(method_dir) / "html_predictions"
if not html_dir.exists():
return None
html_files = sorted(html_dir.glob("*.html"))
if not html_files:
return None
scores = {}
for hf in tqdm(html_files, desc=f"CLIP {html_dir.parent.name}"):
sid = hf.stem
ref_img_path = Path(ref_dir) / f"{sid}.png"
if not ref_img_path.exists():
continue
ref_img = Image.open(ref_img_path).convert("RGB")
pred_img_path = os.path.join(tmp_dir, f"{sid}.png")
ok = render_html(str(hf), pred_img_path)
if ok and os.path.exists(pred_img_path):
pred_img = Image.open(pred_img_path).convert("RGB")
clip = scorer.score(ref_img, pred_img)
else:
clip = 0.0
scores[sid] = clip
if not scores:
return None
vals = list(scores.values())
return {
"n": len(vals),
"avg_clip": round(sum(vals) / len(vals), 4),
"min_clip": round(min(vals), 4),
"max_clip": round(max(vals), 4),
"per_sample": {k: round(v, 4) for k, v in scores.items()},
}
def compute_clip_for_method_dir(
method_dir: str | Path,
ref_dir: str | Path,
device: str = "cuda",
) -> dict | None:
"""Run CLIP on one benchmark folder (contains html_predictions/). Writes clip_scores.json."""
method_dir = Path(method_dir)
ref_dir = Path(ref_dir)
scorer = CLIPScorer(device=device)
with tempfile.TemporaryDirectory() as tmp:
result = eval_method(method_dir, ref_dir, scorer, tmp)
if result and method_dir.is_dir():
clip_file = method_dir / "clip_scores.json"
with open(clip_file, "w") as f:
json.dump(result, f, indent=2)
return result
def main():
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--benchmark_dir", default=str(PROJECT_ROOT / "results" / "benchmark"))
parser.add_argument("--ref_dir", default=str(PROJECT_ROOT / "data" / "ref_screenshots"))
parser.add_argument("--methods", nargs="*", default=None)
parser.add_argument(
"--method_dir",
default=None,
help="If set, only score this folder (must contain html_predictions/) and exit.",
)
parser.add_argument(
"--clip_device",
default="cuda",
choices=["cuda", "cpu"],
help="CLIP ViT device; use cpu if all GPUs are full.",
)
args = parser.parse_args()
if args.method_dir:
r = compute_clip_for_method_dir(
args.method_dir, args.ref_dir, device=args.clip_device,
)
if r:
print(json.dumps(r, indent=2))
else:
print("No scores (missing html_predictions or no matches).", file=sys.stderr)
sys.exit(1)
return
bench_dir = Path(args.benchmark_dir)
ref_dir = Path(args.ref_dir)
if not ref_dir.exists():
print(f"Reference dir not found: {ref_dir}")
sys.exit(1)
scorer = CLIPScorer()
all_clip = {}
methods = args.methods or sorted(
d.name for d in bench_dir.iterdir()
if d.is_dir() and (d / "html_predictions").exists()
)
with tempfile.TemporaryDirectory() as tmp:
for method in methods:
method_dir = bench_dir / method
if not method_dir.exists():
continue
print(f"\n=== {method} ===")
result = eval_method(method_dir, ref_dir, scorer, tmp)
if result:
all_clip[method] = result
print(f" CLIP: {result['avg_clip']:.4f} (n={result['n']})")
clip_file = method_dir / "clip_scores.json"
with open(clip_file, "w") as f:
json.dump(result, f, indent=2)
agg_file = bench_dir / "all_clip_scores.json"
summary = {k: {kk: vv for kk, vv in v.items() if kk != "per_sample"}
for k, v in all_clip.items()}
with open(agg_file, "w") as f:
json.dump(summary, f, indent=2)
print(f"\n{'='*60}")
print(f"{'Method':<20} {'CLIP':>8} {'N':>5}")
print("-" * 40)
for k in sorted(summary, key=lambda x: summary[x]["avg_clip"], reverse=True):
v = summary[k]
print(f"{k:<20} {v['avg_clip']:>8.4f} {v['n']:>5}")
print(f"{'='*60}")
print(f"Saved to: {agg_file}")
if __name__ == "__main__":
main()