File size: 8,041 Bytes
bac741f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
"""
SSIM + Bootstrap CI computation for all benchmark methods.
Works with existing rendered screenshots and per-sample CLIP scores.

Usage:
    python scripts/step_ssim_bootstrap.py --benchmark_dir results/benchmark --ref_dir data/ref_screenshots
    python scripts/step_ssim_bootstrap.py --benchmark_dir results/benchmark_websight --ref_dir data/ref_screenshots_websight
"""

import argparse
import json
import os
import sys
from pathlib import Path

import numpy as np
from PIL import Image

PROJECT_ROOT = Path(__file__).parent.parent


def compute_ssim_pil(img1, img2, win_size=7):
    """Compute SSIM between two PIL images using numpy (no skimage dependency)."""
    target_size = (min(img1.width, img2.width, 512), min(img1.height, img2.height, 512))
    a = np.array(img1.resize(target_size).convert("RGB"), dtype=np.float64)
    b = np.array(img2.resize(target_size).convert("RGB"), dtype=np.float64)

    C1 = (0.01 * 255) ** 2
    C2 = (0.03 * 255) ** 2

    ssims = []
    for ch in range(3):
        mu1 = uniform_filter(a[:, :, ch], win_size)
        mu2 = uniform_filter(b[:, :, ch], win_size)
        mu1_sq = mu1 ** 2
        mu2_sq = mu2 ** 2
        mu1_mu2 = mu1 * mu2
        sigma1_sq = uniform_filter(a[:, :, ch] ** 2, win_size) - mu1_sq
        sigma2_sq = uniform_filter(b[:, :, ch] ** 2, win_size) - mu2_sq
        sigma12 = uniform_filter(a[:, :, ch] * b[:, :, ch], win_size) - mu1_mu2

        ssim_map = ((2 * mu1_mu2 + C1) * (2 * sigma12 + C2)) / \
                   ((mu1_sq + mu2_sq + C1) * (sigma1_sq + sigma2_sq + C2))
        ssims.append(ssim_map.mean())

    return float(np.mean(ssims))


def uniform_filter(arr, size):
    """Simple uniform (box) filter."""
    from scipy.ndimage import uniform_filter as _uf
    return _uf(arr, size=size, mode='reflect')


def render_html_to_screenshot(html_path, out_path, width=1280, height=1024, timeout=15000):
    """Render HTML file to PNG screenshot using Playwright."""
    try:
        from playwright.sync_api import sync_playwright
        with sync_playwright() as p:
            browser = p.chromium.launch(headless=True, args=['--no-sandbox', '--disable-gpu'])
            page = browser.new_page(viewport={"width": width, "height": height})
            page.goto(f"file://{html_path}", wait_until="networkidle", timeout=timeout)
            page.wait_for_timeout(1000)
            page.screenshot(path=str(out_path), full_page=True)
            browser.close()
        return True
    except Exception as e:
        print(f"  Render failed for {html_path}: {e}")
        return False


def compute_ssim_for_method(method_dir, ref_dir, render_cache_dir):
    """Compute per-sample SSIM for a method."""
    html_dir = Path(method_dir) / "html_predictions"
    if not html_dir.exists():
        return None

    ref_dir = Path(ref_dir)
    render_dir = Path(render_cache_dir) / Path(method_dir).name
    render_dir.mkdir(parents=True, exist_ok=True)

    html_files = sorted(html_dir.glob("*.html"))
    per_sample = {}

    for html_path in html_files:
        sample_id = html_path.stem
        ref_path = ref_dir / f"{sample_id}.png"
        if not ref_path.exists():
            continue

        rendered_path = render_dir / f"{sample_id}.png"
        if not rendered_path.exists():
            ok = render_html_to_screenshot(str(html_path.resolve()), str(rendered_path))
            if not ok:
                continue

        try:
            ref_img = Image.open(ref_path).convert("RGB")
            rendered_img = Image.open(rendered_path).convert("RGB")
            ssim = compute_ssim_pil(ref_img, rendered_img)
            per_sample[sample_id] = ssim
        except Exception as e:
            print(f"  SSIM error for {sample_id}: {e}")
            continue

    if not per_sample:
        return None

    return {
        "n_samples": len(per_sample),
        "avg_ssim": round(float(np.mean(list(per_sample.values()))), 4),
        "std_ssim": round(float(np.std(list(per_sample.values()))), 4),
        "per_sample": per_sample,
    }


def bootstrap_ci(scores, n_bootstrap=10000, ci=0.95, seed=42):
    """Compute bootstrap confidence interval."""
    rng = np.random.RandomState(seed)
    scores = np.array(scores)
    n = len(scores)
    boot_means = np.array([
        rng.choice(scores, size=n, replace=True).mean()
        for _ in range(n_bootstrap)
    ])
    alpha = (1 - ci) / 2
    lo = float(np.percentile(boot_means, 100 * alpha))
    hi = float(np.percentile(boot_means, 100 * (1 - alpha)))
    return {
        "mean": float(scores.mean()),
        "ci_lower": round(lo, 4),
        "ci_upper": round(hi, 4),
        "ci_width": round(hi - lo, 4),
        "std": round(float(scores.std()), 4),
        "n": n,
    }


def compute_bootstrap_for_all(benchmark_dir):
    """Compute bootstrap CI for all methods from per-sample CLIP scores."""
    benchmark_dir = Path(benchmark_dir)
    results = {}

    for method_dir in sorted(benchmark_dir.iterdir()):
        if not method_dir.is_dir():
            continue
        clip_file = method_dir / "clip_scores.json"
        if not clip_file.exists():
            continue

        with open(clip_file) as f:
            clip_data = json.load(f)

        per_sample = clip_data.get("per_sample", {})
        if not per_sample:
            continue

        scores = []
        for k, v in per_sample.items():
            if isinstance(v, dict):
                scores.append(v.get("clip_score", 0))
            else:
                scores.append(float(v))

        if not scores:
            continue

        ci_result = bootstrap_ci(scores)
        results[method_dir.name] = ci_result
        print(f"  {method_dir.name}: CLIP={ci_result['mean']:.4f} [{ci_result['ci_lower']:.4f}, {ci_result['ci_upper']:.4f}]")

    return results


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--benchmark_dir", type=str, default=str(PROJECT_ROOT / "results" / "benchmark"))
    parser.add_argument("--ref_dir", type=str, default=str(PROJECT_ROOT / "data" / "ref_screenshots"))
    parser.add_argument("--render_cache", type=str, default=str(PROJECT_ROOT / "results" / "rendered_screenshots"))
    parser.add_argument("--skip_ssim", action="store_true")
    parser.add_argument("--skip_bootstrap", action="store_true")
    args = parser.parse_args()

    benchmark_dir = Path(args.benchmark_dir)
    output = {}

    if not args.skip_bootstrap:
        print("=" * 60)
        print("Computing Bootstrap CI for CLIP scores...")
        print("=" * 60)
        bootstrap_results = compute_bootstrap_for_all(args.benchmark_dir)
        output["bootstrap_ci"] = bootstrap_results

        ci_file = benchmark_dir / "bootstrap_ci.json"
        with open(ci_file, "w") as f:
            json.dump(bootstrap_results, f, indent=2)
        print(f"\nSaved to {ci_file}")

    if not args.skip_ssim:
        print("\n" + "=" * 60)
        print("Computing SSIM scores...")
        print("=" * 60)
        ssim_results = {}
        for method_dir in sorted(benchmark_dir.iterdir()):
            if not method_dir.is_dir():
                continue
            html_dir = method_dir / "html_predictions"
            if not html_dir.exists():
                continue
            print(f"\n  Processing {method_dir.name}...")
            result = compute_ssim_for_method(str(method_dir), args.ref_dir, args.render_cache)
            if result:
                ssim_results[method_dir.name] = {
                    "n_samples": result["n_samples"],
                    "avg_ssim": result["avg_ssim"],
                    "std_ssim": result["std_ssim"],
                }
                print(f"    SSIM={result['avg_ssim']:.4f} ± {result['std_ssim']:.4f} (n={result['n_samples']})")
            output[f"ssim_{method_dir.name}"] = result

        ssim_file = benchmark_dir / "ssim_scores.json"
        with open(ssim_file, "w") as f:
            json.dump(ssim_results, f, indent=2)
        print(f"\nSaved to {ssim_file}")


if __name__ == "__main__":
    main()