File size: 7,789 Bytes
bee9bbb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
230
231
232
233
234
235
236
237
"""Capture public desktop candidates at the paths declared by the visual spec."""

from __future__ import annotations

import argparse
import json
import socket
import struct
import subprocess
import sys
import time
from contextlib import contextmanager
from dataclasses import dataclass
from pathlib import Path
from urllib.request import urlopen


SITE_ROOT = Path(__file__).resolve().parents[1]
SPEC_PATH = SITE_ROOT / "scope" / "desktop-visual-comparison-current.json"
VIEWPORT = {"width": 1692, "height": 979}
PUBLIC_ROUTE_DETAILS = {
    "home.loaded.desktop": (
        "/",
        ".home-promo-switcher",
        ".wb-header",
        ".wb-footer",
    ),
    "browse.loaded.desktop": (
        "/browse",
        ".source-browse-shell",
        ".wb-header",
        ".wb-footer",
    ),
    "search.results.desktop": (
        "/search?q=Deep+Learning",
        ".search-results-section",
        ".wb-header",
        ".wb-footer",
    ),
    "specialization.loaded.desktop": (
        "/specializations/deep-learning",
        ".source-specialization-hero",
        ".wb-header",
        ".wb-footer",
    ),
    "course.loaded.desktop": (
        "/learn/neural-networks-deep-learning",
        ".source-course-detail-hero",
        ".wb-header",
        ".wb-footer",
    ),
    "login.loaded.desktop": (
        "/login",
        ".source-login-dialog",
        ".wb-header",
        ".wb-footer",
    ),
    "help.loaded.desktop": (
        "/help",
        ".help-article",
        ".help-center-header",
        ".help-feedback",
    ),
    "not-found.loaded.desktop": (
        "/websitebench-not-found-33",
        ".source-not-found-page",
        ".wb-header",
        ".source-not-found",
    ),
}


@dataclass(frozen=True)
class CandidateCapture:
    checkpoint_id: str
    route: str
    landmark: str
    header: str
    lower_landmark: str
    output_path: Path


def _free_loopback_port() -> int:
    with socket.socket() as listener:
        listener.bind(("127.0.0.1", 0))
        return int(listener.getsockname()[1])


@contextmanager
def _clone_server() -> str:
    port = _free_loopback_port()
    process = subprocess.Popen(
        [
            sys.executable,
            "-m",
            "uvicorn",
            "app:app",
            "--host",
            "127.0.0.1",
            "--port",
            str(port),
        ],
        cwd=SITE_ROOT / "clone",
        stdout=subprocess.DEVNULL,
        stderr=subprocess.DEVNULL,
    )
    base_url = f"http://127.0.0.1:{port}"
    try:
        for _ in range(50):
            try:
                with urlopen(f"{base_url}/healthz", timeout=0.2) as response:
                    if response.status == 200:
                        break
            except OSError:
                time.sleep(0.1)
        else:
            raise RuntimeError("the local clone did not become ready for capture")
        yield base_url
    finally:
        process.terminate()
        process.wait(timeout=5)


def _png_size(path: Path) -> tuple[int, int]:
    with path.open("rb") as image:
        if image.read(8) != b"\x89PNG\r\n\x1a\n":
            raise ValueError(f"candidate is not a PNG: {path}")
        if image.read(4) != b"\x00\x00\x00\r" or image.read(4) != b"IHDR":
            raise ValueError(f"candidate has no PNG IHDR: {path}")
        return struct.unpack(">II", image.read(8))


def declared_candidate_capture_plan() -> tuple[CandidateCapture, ...]:
    """Map every declared candidate input to its anonymous public route."""

    spec = json.loads(SPEC_PATH.read_text(encoding="utf-8"))
    captures: list[CandidateCapture] = []
    for checkpoint in spec["checkpoints"]:
        checkpoint_id = checkpoint["id"]
        try:
            route, landmark, header, lower_landmark = PUBLIC_ROUTE_DETAILS[
                checkpoint_id
            ]
        except KeyError as error:
            raise ValueError(f"no public capture route for {checkpoint_id!r}") from error
        output_path = (SPEC_PATH.parent / checkpoint["candidate"]["path"]).resolve()
        expected_root = (SPEC_PATH.parent / "candidate-desktop").resolve()
        if output_path.parent != expected_root:
            raise ValueError(
                f"{checkpoint_id}: candidate path must be inside {expected_root}"
            )
        captures.append(
            CandidateCapture(
                checkpoint_id,
                route,
                landmark,
                header,
                lower_landmark,
                output_path,
            )
        )
    return tuple(captures)


def capture_declared_candidates(*, overwrite: bool = False) -> list[dict[str, str]]:
    """Capture every declared candidate after verifying stable visual landmarks."""

    captures = declared_candidate_capture_plan()
    existing = [capture.output_path for capture in captures if capture.output_path.exists()]
    if existing and not overwrite:
        raise FileExistsError(
            "refusing to overwrite visual candidates; re-run with --overwrite: "
            + ", ".join(str(path) for path in existing)
        )
    try:
        from playwright.sync_api import sync_playwright
    except ImportError as error:  # pragma: no cover - dependency is declared
        raise RuntimeError("Playwright is required to capture visual candidates") from error

    results: list[dict[str, str]] = []
    with sync_playwright() as runtime:
        browser = runtime.chromium.launch()
        context = browser.new_context(viewport=VIEWPORT, device_scale_factor=1)
        try:
            with _clone_server() as base_url:
                for capture in captures:
                    capture.output_path.parent.mkdir(parents=True, exist_ok=True)
                    page = context.new_page()
                    try:
                        response = page.goto(base_url + capture.route, wait_until="networkidle")
                        if response is None or response.status not in {200, 404}:
                            raise RuntimeError(
                                f"{capture.checkpoint_id}: unexpected route response"
                            )
                        for selector in (
                            capture.header,
                            capture.landmark,
                            capture.lower_landmark,
                        ):
                            if not page.locator(selector).is_visible():
                                raise RuntimeError(
                                    f"{capture.checkpoint_id}: missing landmark {selector}"
                                )
                        page.screenshot(path=str(capture.output_path))
                        if _png_size(capture.output_path) != (1692, 979):
                            raise RuntimeError(
                                f"{capture.checkpoint_id}: screenshot was not 1692x979"
                            )
                        results.append(
                            {
                                "checkpoint_id": capture.checkpoint_id,
                                "candidate": str(capture.output_path),
                            }
                        )
                    finally:
                        page.close()
        finally:
            context.close()
            browser.close()
    return results


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        "--overwrite",
        action="store_true",
        help="replace prior local candidate screenshots",
    )
    args = parser.parse_args()
    print(json.dumps(capture_declared_candidates(overwrite=args.overwrite), indent=2))
    return 0


if __name__ == "__main__":  # pragma: no cover - exercised as a local command
    raise SystemExit(main())