yxma commited on
Commit
349f068
·
verified ·
1 Parent(s): 421cfca

scripts: publish what the READMEs tell you to run

Browse files
Files changed (1) hide show
  1. scripts/test_site.py +309 -0
scripts/test_site.py ADDED
@@ -0,0 +1,309 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The published Space renders, and its pages agree with the data and each other.
2
+
3
+ Two failures this suite exists for, both of which shipped:
4
+
5
+ * /probes/ was rendered from its own sampling run, so it showed clips of
6
+ probes that were not in the published set, including one from a session
7
+ the set excludes. Two pages, one dataset, opposite answers.
8
+ * a tile's <img> was 464x480 while its <canvas> was 464x348, so every
9
+ overlay sat 93 px from the sensor it annotated while every arithmetic
10
+ check stayed green.
11
+
12
+ So this checks three things a screenshot cannot: that each page loads clean,
13
+ that what it displays matches the published artefacts it describes, and that
14
+ overlay canvases actually cover their images.
15
+
16
+ python scripts/test_site.py [--base URL]
17
+ """
18
+ from __future__ import annotations
19
+
20
+ import argparse
21
+ import asyncio
22
+ import json
23
+ import sys
24
+ import tempfile
25
+ import urllib.error
26
+ import urllib.request
27
+ from pathlib import Path
28
+
29
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
30
+
31
+ RESULTS: list[tuple[bool, str, str]] = []
32
+ BASE = "https://yxma-react-force-recovery.static.hf.space"
33
+ PAGES = ["testset/index.html", "probes/index.html",
34
+ "calib/a/index.html", "calib/pre/index.html"]
35
+
36
+
37
+ def check(ok: bool, name: str, evidence: str) -> None:
38
+ RESULTS.append((bool(ok), name, evidence))
39
+
40
+
41
+ async def audit(base, pages):
42
+ from playwright.async_api import async_playwright
43
+ out = {}
44
+ async with async_playwright() as pw:
45
+ b = await pw.chromium.launch()
46
+ for p in pages:
47
+ pg = await b.new_page(viewport={"width": 1440, "height": 1000})
48
+ errs, bad = [], []
49
+ pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None)
50
+ # the FULL url. Storing the basename and rebuilding
51
+ # f"{base}/{dir}/{name}" dropped the subdirectory, so the retry
52
+ # fetched /testset/run4_trans-y.jpg for a file that lives at
53
+ # /testset/overlays/... — a 404 on a URL that never existed, which
54
+ # I read as a missing file when all 72 were present.
55
+ pg.on("response", lambda r: bad.append((r.status, r.url))
56
+ if r.status >= 400 else None)
57
+ r = await pg.goto(f"{base}/{p}", wait_until="networkidle", timeout=90000)
58
+ await pg.evaluate("window.scrollTo(0, document.body.scrollHeight)")
59
+ await pg.wait_for_timeout(3500)
60
+ d = await pg.evaluate("""(() => {
61
+ const im = [...document.querySelectorAll('img')];
62
+ const cv = [...document.querySelectorAll('.tile, .zoomwrap')].map(t => {
63
+ const i = t.querySelector('img'), c = t.querySelector('canvas');
64
+ if (!i || !c) return 0;
65
+ const a = i.getBoundingClientRect(), b = c.getBoundingClientRect();
66
+ return Math.max(Math.abs(a.x-b.x), Math.abs(a.y-b.y),
67
+ Math.abs(a.width-b.width), Math.abs(a.height-b.height));
68
+ });
69
+ const vd = [...document.querySelectorAll('video')];
70
+ return {imgs: im.length,
71
+ broken: im.filter(x => x.naturalWidth === 0 && x.getAttribute('src')).length,
72
+ videos: vd.length,
73
+ vsrc: vd.length ? vd[0].currentSrc || vd[0].src : null,
74
+ overflow: document.documentElement.scrollWidth > window.innerWidth,
75
+ canvasGap: cv.length ? Math.max(...cv) : null,
76
+ title: document.title};
77
+ })()""")
78
+ out[p] = {"status": r.status, "errs": errs, "bad": bad, **d}
79
+ await pg.close()
80
+ await b.close()
81
+ return out
82
+
83
+
84
+ def main() -> int:
85
+ ap = argparse.ArgumentParser()
86
+ ap.add_argument("--base", default=BASE)
87
+ a = ap.parse_args()
88
+
89
+ au = asyncio.run(audit(a.base, PAGES))
90
+
91
+ # 1 — every page loads clean.
92
+ #
93
+ # A sub-resource failure is RE-REQUESTED before it counts. The static Space
94
+ # returns transient 429/503 under a cold start, and the first version of
95
+ # this check reported 4 failures on a page whose files were all present —
96
+ # a re-run showed zero. A flaky check that cries wolf is worse than none,
97
+ # because the next real failure gets waved through.
98
+ persist = []
99
+ for pg_, v in au.items():
100
+ for st, url in v["bad"]:
101
+ name = url.rsplit("/", 1)[-1]
102
+ try:
103
+ again = urllib.request.urlopen(url, timeout=45).status
104
+ except urllib.error.HTTPError as e:
105
+ again = e.code
106
+ except Exception:
107
+ again = 0
108
+ if again >= 400 or again == 0:
109
+ persist.append(f"{pg_}: {name} -> {st} then {again}")
110
+ bad = [f"{p_}: HTTP {v['status']}" for p_, v in au.items() if v["status"] != 200]
111
+ bad += persist
112
+ # A console error CAUSED by a transient 4xx is that 4xx counted twice. The
113
+ # browser logs "Failed to load resource" for the same request `persist`
114
+ # already adjudicated, so only errors that are not about a re-fetchable
115
+ # sub-resource count as page defects.
116
+ def real_errs(v):
117
+ urls = {u.rsplit("/", 1)[-1] for _, u in v["bad"]}
118
+ return [e for e in v["errs"]
119
+ if not any(u and u in e for u in urls)
120
+ and "Failed to load resource" not in e]
121
+ bad += [f"{p_}: {len(real_errs(v))} console errors {real_errs(v)[:1]}"
122
+ for p_, v in au.items() if real_errs(v)]
123
+ transient = sum(len(v["bad"]) for v in au.values()) - len(persist)
124
+ check(not bad, "every page loads with no persistent 4xx and no console errors",
125
+ f"{len(PAGES)} pages, all HTTP 200, 0 persistent sub-resource failures, "
126
+ f"0 console errors"
127
+ + (f" ({transient} transient, re-requested OK)" if transient else "")
128
+ + (f"; {bad[:3]}" if bad else ""))
129
+
130
+ # 2 — nothing broken or overflowing
131
+ # RE-FETCH before calling an image broken. One that lost a race with a
132
+ # cold-start 429 reports naturalWidth 0 while its file is perfectly there —
133
+ # measured, 4 of them on one run and 0 on the next. My first attempt at
134
+ # this patch searched for `p_` where the file said `p`, so `.replace()`
135
+ # silently did nothing and the run that happened not to hit a 429 reported
136
+ # a clean pass. Every edit here now asserts its anchor.
137
+ br = []
138
+ for p_, v in au.items():
139
+ if not v["broken"]:
140
+ continue
141
+ still = 0
142
+ for st, url in v["bad"]:
143
+ if url.endswith((".jpg", ".jpeg", ".png", ".webp", ".gif")):
144
+ try:
145
+ if urllib.request.urlopen(url, timeout=45).status >= 400:
146
+ still += 1
147
+ except Exception:
148
+ still += 1
149
+ if still:
150
+ br.append(f"{p_}: {still} genuinely broken imgs")
151
+ ov = [p_ for p_, v in au.items() if v["overflow"]]
152
+ n_transient_img = sum(v["broken"] for v in au.values())
153
+ check(not br and not ov, "no broken media and no horizontal overflow",
154
+ f"{sum(v['imgs'] for v in au.values())} images, "
155
+ f"{sum(v['videos'] for v in au.values())} videos, 0 persistently broken, "
156
+ f"0 overflowing"
157
+ + (f" ({n_transient_img} lost a race with a cold-start 429, all "
158
+ f"re-fetched OK)" if n_transient_img else "")
159
+ + (f"; {br + ov}" if (br or ov) else ""))
160
+
161
+ # 3 — VIDEOS ACTUALLY DECODE. Counting <video> elements says nothing: the
162
+ # element exists whether or not the browser can play what is inside it.
163
+ # 72 clips shipped as mpeg4/mp4v Simple Profile, which Chromium refuses
164
+ # (canPlayType returns ""), while every file was present, served as
165
+ # video/mp4 with the right byte count — and unplayable. This check
166
+ # loads one and waits for real decoded dimensions.
167
+ async def probe_video(url):
168
+ from playwright.async_api import async_playwright
169
+ async with async_playwright() as pw:
170
+ b = await pw.chromium.launch()
171
+ pg = await b.new_page()
172
+ await pg.goto("about:blank")
173
+ r = await pg.evaluate("""async (u) => {
174
+ const v = document.createElement('video');
175
+ v.src = u; v.muted = true; v.preload = 'auto';
176
+ document.body.appendChild(v);
177
+ const ok = await new Promise(res => {
178
+ v.onloadeddata = () => res(true);
179
+ v.onerror = () => res(false);
180
+ setTimeout(() => res(false), 20000);
181
+ });
182
+ return {ok, w: v.videoWidth, h: v.videoHeight,
183
+ state: v.readyState,
184
+ err: v.error ? v.error.code : null};
185
+ }""", url)
186
+ await b.close()
187
+ return r
188
+
189
+ # ...and on a phone viewport, where the failure was first reported.
190
+ #
191
+ # Playwright's Linux WebKit is not a stand-in for Safari, but NOT for the
192
+ # reason I first wrote here. I claimed it lacked the proprietary H.264
193
+ # decoder; measured, its canPlayType returns "probably" for baseline, for
194
+ # high, AND for mp4v — the codec real Safari refuses and that broke this
195
+ # page. It is over-permissive, so it would have passed the original bug.
196
+ # Chromium under a mobile device profile exercises the small-screen layout
197
+ # and the lazy-load path; neither engine here can certify Safari playback.
198
+ vids = [(p_, v["vsrc"]) for p_, v in au.items() if v.get("vsrc")]
199
+ vres = []
200
+ for p_, src in vids:
201
+ vres.append((p_, asyncio.run(probe_video(src))))
202
+ okv = [r for _, r in vres if r["ok"] and r["w"] > 0]
203
+ check(vres and len(okv) == len(vres),
204
+ "videos actually decode, not merely exist as elements",
205
+ "; ".join(f"{p_.split('/')[0]} {r['w']}x{r['h']} readyState={r['state']}"
206
+ + (f" ERR{r['err']}" if r.get("err") else "")
207
+ for p_, r in vres) or "no <video> found")
208
+
209
+ # 4 — OVERLAY CANVASES COVER THEIR IMAGES. The defect that left every
210
+ # arithmetic check green while the overlay sat 93 px off.
211
+ gaps = {p: v["canvasGap"] for p, v in au.items() if v["canvasGap"] is not None}
212
+ worst = max(gaps.values()) if gaps else 0.0
213
+ check(gaps and worst <= 1.0,
214
+ "overlay canvases cover their images exactly",
215
+ f"{len(gaps)} pages with overlays, worst image/canvas box mismatch "
216
+ f"{worst:.1f} px")
217
+
218
+ # ...and the video grid must not fetch every clip up front. 72 videos
219
+ # preloading at once is what a phone chokes on: WebKit could not even
220
+ # finish `load` on the page before this changed.
221
+ async def first_paint(url):
222
+ from playwright.async_api import async_playwright
223
+ async with async_playwright() as pw:
224
+ b = await pw.chromium.launch()
225
+ ctx = await b.new_context(**pw.devices["iPhone 13"])
226
+ pg = await ctx.new_page()
227
+ got = []
228
+ pg.on("response", lambda r: got.append(r.url.rsplit("/", 1)[-1]))
229
+ await pg.goto(url, wait_until="networkidle", timeout=90000)
230
+ await pg.wait_for_timeout(2500)
231
+ d = await pg.evaluate("""(() => {const v=[...document.querySelectorAll('video')];
232
+ return {n: v.length, preload: v.length ? v[0].getAttribute('preload') : null,
233
+ posters: v.filter(x => x.getAttribute('poster')).length};})()""")
234
+ await b.close()
235
+ return d, sum(1 for g in got if g.endswith(".mp4"))
236
+
237
+ clip_page = f"{a.base}/probes/index.html"
238
+ d, n_mp4 = asyncio.run(first_paint(clip_page))
239
+ check(d["n"] > 0 and n_mp4 == 0 and d["posters"] == d["n"],
240
+ "the clip grid shows posters and fetches no video until asked",
241
+ f"iPhone viewport: {d['n']} videos, preload={d['preload']}, "
242
+ f"{d['posters']} with posters, {n_mp4} mp4 requests on first paint")
243
+
244
+ # 6 — THE CLIP PAGE SHOWS THE PUBLISHED SET, not a second sampling.
245
+ from huggingface_hub import hf_hub_download
246
+ d = tempfile.mkdtemp()
247
+ man = json.loads(Path(hf_hub_download(
248
+ "yxma/React", "test_sets/probes_v1/manifest.json",
249
+ repo_type="dataset", local_dir=d)).read_text())
250
+ live = json.loads(urllib.request.urlopen(f"{a.base}/probes/probes.json",
251
+ timeout=60).read())
252
+ page_runs = {(x["run"], x["episode"]) for x in live}
253
+ set_runs = {(x["run"], x["episode"]) for x in man["probes"]}
254
+ check(page_runs == set_runs and len(live) == man["n_probes"],
255
+ "the clip page animates the published set, not a second sampling",
256
+ f"{len(live)} clips vs {man['n_probes']} published probes; "
257
+ f"start frames identical: {page_runs == set_runs}")
258
+
259
+ # 7 — THE PAGE'S STATED POLICY MATCHES THE MANIFEST. Check 8 below compares
260
+ # run SETS and passed while the prose said "2026-05-19 is excluded"
261
+ # months after that call was reversed: the draw had simply not selected
262
+ # it, and the sentence promoted an accident of sampling into a policy a
263
+ # reader would act on. Sets are not claims; sentences are.
264
+ async def page_text(url):
265
+ from playwright.async_api import async_playwright
266
+ async with async_playwright() as pw:
267
+ b = await pw.chromium.launch(); pg = await b.new_page()
268
+ await pg.goto(url, wait_until="domcontentloaded", timeout=90000)
269
+ t = await pg.inner_text("body")
270
+ await b.close()
271
+ return t
272
+
273
+ elig = set(man.get("trusted_sessions", []))
274
+ excl = set(man.get("excluded_sessions") or {})
275
+ prose = []
276
+ for pg_ in ("testset/index.html", "probes/index.html"):
277
+ t = asyncio.run(page_text(f"{a.base}/{pg_}"))
278
+ for sess in elig - excl:
279
+ # an eligible session must never be described as excluded
280
+ for phrase in (f"{sess} is excluded", f"{sess} is left out",
281
+ f"excluded: {sess}"):
282
+ if phrase.lower() in t.lower():
283
+ prose.append(f"{pg_}: says '{phrase}' but manifest lists it eligible")
284
+ for sess in excl:
285
+ if sess not in t:
286
+ prose.append(f"{pg_}: excludes {sess} but never says so")
287
+ check(not prose, "the page's stated session policy matches the manifest",
288
+ f"eligible {sorted(elig)}, excluded {sorted(excl) or 'none'}; both pages "
289
+ f"agree" + (f"; {prose[:2]}" if prose else ""))
290
+
291
+ # 8 — and no page uses a session the set excludes
292
+ excl = set(man.get("excluded_sessions") or {})
293
+ leaked = sorted({e.split("/")[0] for _, e in page_runs} & excl)
294
+ check(not leaked, "no page shows an excluded session",
295
+ f"sessions on the page: {sorted({e.split('/')[0] for _, e in page_runs})}; "
296
+ f"excluded by the set: {sorted(excl) or 'none'}"
297
+ + (f"; LEAKED {leaked}" if leaked else ""))
298
+
299
+ w = max(len(x) for _, x, _ in RESULTS)
300
+ print()
301
+ for ok, name, ev in RESULTS:
302
+ print(f" [{'ok' if ok else 'FAIL'}] {name:<{w}} {ev}")
303
+ n = sum(not ok for ok, _, _ in RESULTS)
304
+ print(f"\nsite: {len(RESULTS)} checks, {n} failing")
305
+ return 1 if n else 0
306
+
307
+
308
+ if __name__ == "__main__":
309
+ raise SystemExit(main())