Datasets:
File size: 3,817 Bytes
1e6582e 10d623c 1e6582e 10d623c 1e6582e | 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 | """Capture many pages for detector training: for each URL a light screenshot at the top, one scrolled a screen down,
and a dark-mode one, each with labels from collect2.js. No model calls.
Usage: uv run --with playwright python build.py urls.txt [concurrency]
Writes data/raw/<id>_<variant>.png and .json. Re-running skips URLs already done.
"""
import asyncio, hashlib, json, os, sys
from pathlib import Path
from playwright.async_api import async_playwright
HERE = Path(__file__).parent
NEW = (HERE / "collect2.js").read_text()
RAW = HERE / "data" / os.environ.get("RAW", "raw")
W, H = 1440, 900
FREEZE = "*,*::before,*::after{animation:none!important;transition:none!important;caret-color:transparent!important;scroll-behavior:auto!important}"
async def shot(page, uid, variant, url):
before = await page.evaluate(NEW)
png = RAW / f"{uid}_{variant}.png"
await page.screenshot(path=str(png))
after = await page.evaluate(NEW)
after.update(id=f"{uid}_{variant}", source_url=url, variant=variant,
stable=[e["rect"] for e in before["els"]] == [e["rect"] for e in after["els"]])
(RAW / f"{uid}_{variant}.json").write_text(json.dumps(after))
return after
async def one(browser, url, sem, log):
uid = hashlib.sha1(url.encode()).hexdigest()[:10]
done = RAW / f"{uid}.done"
if done.exists():
return
async with sem:
ctx = await browser.new_context(viewport={"width": W, "height": H}, device_scale_factor=1, color_scheme="light",
locale="en-GB", reduced_motion="reduce")
page = await ctx.new_page()
note = ""
try:
await page.goto(url, wait_until="domcontentloaded", timeout=40000)
try:
await page.wait_for_load_state("networkidle", timeout=10000)
except Exception:
pass
try:
await page.add_style_tag(content=FREEZE)
except Exception:
cdp = await ctx.new_cdp_session(page)
await cdp.send("Animation.enable")
await cdp.send("Animation.setPlaybackRate", {"playbackRate": 0})
await page.wait_for_timeout(1500)
top = await shot(page, uid, "top", url)
n = [top["n"]]
height = await page.evaluate("document.documentElement.scrollHeight")
if height > H * 1.6:
await page.evaluate(f"window.scrollTo(0, {H})")
await page.wait_for_timeout(900)
n.append((await shot(page, uid, "scroll", url))["n"])
await page.evaluate("window.scrollTo(0, 0)")
await page.emulate_media(color_scheme="dark", reduced_motion="reduce")
await page.wait_for_timeout(900)
n.append((await shot(page, uid, "dark", url))["n"])
note = f"labels {n}"
except Exception as e:
note = f"FAILED {type(e).__name__}: {str(e)[:90]}"
finally:
done.write_text(note)
log(f"{uid} {url[:70]:70s} {note}")
await ctx.close()
async def main():
RAW.mkdir(parents=True, exist_ok=True)
urls = [u.strip() for u in Path(sys.argv[1]).read_text().splitlines() if u.strip() and not u.startswith("#")]
sem = asyncio.Semaphore(int(sys.argv[2]) if len(sys.argv) > 2 else 6)
count = [0]
def log(msg):
count[0] += 1
print(f"[{count[0]}/{len(urls)}] {msg}", flush=True)
async with async_playwright() as p:
browser = await p.chromium.launch(channel="chrome", headless=True)
tasks = [asyncio.wait_for(one(browser, u, sem, log), timeout=None) for u in urls]
await asyncio.gather(*tasks, return_exceptions=True)
await browser.close()
if __name__ == "__main__":
asyncio.run(main())
|