@kw-yeh/vibeflow 4.11.53 → 4.11.55

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -70,6 +70,7 @@ COLLECT_JS = """
70
70
  path: cssPath(el),
71
71
  tag: el.tagName.toLowerCase(),
72
72
  text: ownText(el).replace(/\\s+/g, ' ').trim().slice(0, 120),
73
+ x: Math.round(r.left + scrollX), y: Math.round(r.top + scrollY),
73
74
  w: Math.round(r.width), h: Math.round(r.height),
74
75
  styles,
75
76
  });
@@ -89,6 +90,11 @@ def norm(t):
89
90
 
90
91
 
91
92
  def collect(page, url, wait_selector, extra_wait):
93
+ load(page, url, wait_selector, extra_wait)
94
+ return page.evaluate(COLLECT_JS, PROPS)
95
+
96
+
97
+ def load(page, url, wait_selector, extra_wait):
92
98
  page.goto(url, wait_until="domcontentloaded", timeout=60000)
93
99
  try:
94
100
  page.wait_for_load_state("networkidle", timeout=30000)
@@ -98,7 +104,6 @@ def collect(page, url, wait_selector, extra_wait):
98
104
  page.wait_for_selector(wait_selector, timeout=30000)
99
105
  if extra_wait:
100
106
  page.wait_for_timeout(int(extra_wait * 1000))
101
- return page.evaluate(COLLECT_JS, PROPS)
102
107
 
103
108
 
104
109
  def build_pairs(ref_els, loc_els, manual_map):
@@ -244,6 +249,387 @@ def run_diff(args):
244
249
  return 1 if total_diffs else 0
245
250
 
246
251
 
252
+ # Pixel mode compares screenshots with OpenCV. It answers what the computed-style
253
+ # diff cannot: whether a style difference is visible at all, and which visible
254
+ # differences no compared style explains (images, SVG, pseudo-elements, fonts).
255
+
256
+ STABILIZE_CSS = ("*,*::before,*::after{transition:none!important;animation:none!important;"
257
+ "caret-color:transparent!important;scroll-behavior:auto!important}")
258
+ MASK_COLOR = "#FF00FF"
259
+ # Taller anchors span several layout rows and would smear the row mapping.
260
+ MAX_ANCHOR_HEIGHT = 600
261
+ ALIGN_STRIP = 32
262
+
263
+
264
+ def import_cv():
265
+ try:
266
+ import cv2
267
+ import numpy as np
268
+ except ImportError:
269
+ sys.exit("pixel mode needs OpenCV. Run: pip install opencv-python-headless numpy")
270
+ return cv2, np
271
+
272
+
273
+ def capture(page, url, args, cv2, np):
274
+ load(page, url, args.wait_selector, args.extra_wait)
275
+ page.add_style_tag(content=STABILIZE_CSS)
276
+ page.evaluate("() => document.fonts ? document.fonts.ready.then(() => true) : true")
277
+ data = page.evaluate(COLLECT_JS, PROPS)
278
+ width, height = page.evaluate(
279
+ "() => [document.documentElement.scrollWidth, document.documentElement.scrollHeight]")
280
+ opts = dict(full_page=True, animations="disabled", caret="hide",
281
+ mask=[page.locator(s) for s in args.mask], mask_color=MASK_COLOR)
282
+ if height > args.max_height:
283
+ opts["clip"] = {"x": 0, "y": 0, "width": width, "height": args.max_height}
284
+ png = page.screenshot(**opts)
285
+ return data, cv2.imdecode(np.frombuffer(png, np.uint8), cv2.IMREAD_COLOR)
286
+
287
+
288
+ def delta_e(cv2, np, a, b, chunk=1024):
289
+ """Per-pixel CIE76 colour distance; chunked so tall pages fit in memory."""
290
+ out = np.empty(a.shape[:2], np.float32)
291
+ for y in range(0, a.shape[0], chunk):
292
+ d = (cv2.cvtColor(a[y:y + chunk], cv2.COLOR_BGR2LAB).astype(np.float32)
293
+ - cv2.cvtColor(b[y:y + chunk], cv2.COLOR_BGR2LAB).astype(np.float32))
294
+ d[..., 0] *= 100.0 / 255.0
295
+ out[y:y + chunk] = np.sqrt((d * d).sum(axis=2))
296
+ return out
297
+
298
+
299
+ def mode_color(np, img, step=1):
300
+ px = img[::step, ::step].reshape(-1, 3)
301
+ vals, counts = np.unique(px, axis=0, return_counts=True)
302
+ return vals[counts.argmax()]
303
+
304
+
305
+ def row_offsets(np, ref_g, loc_g, anchors):
306
+ """For every ref row, how far down the same content sits on the local page.
307
+
308
+ Matched elements anchor the mapping, so a block inserted or removed locally
309
+ shifts the comparison instead of flagging everything below it as different.
310
+ """
311
+ H, Hl = ref_g.shape[0], loc_g.shape[0]
312
+ unset = np.iinfo(np.int32).min
313
+ first = np.full(H, unset, np.int32)
314
+ conflicts = defaultdict(set)
315
+ for r, l in anchors:
316
+ y0, y1, dy = max(r["y"], 0), min(r["y"] + r["h"], H), l["y"] - r["y"]
317
+ seg = first[y0:y1]
318
+ for y in (np.flatnonzero((seg != unset) & (seg != dy)) + y0).tolist():
319
+ conflicts[y] |= {int(first[y]), dy}
320
+ seg[seg == unset] = dy
321
+
322
+ def cost(y, d):
323
+ ly = y + d
324
+ return float(np.abs(ref_g[y] - loc_g[ly]).mean()) if 0 <= ly < Hl else float("inf")
325
+
326
+ # Overlapping anchors that disagree (nested layouts moving differently):
327
+ # the offset that lines this row up wins rather than an average of them.
328
+ known = [None if v == unset else v for v in first.tolist()]
329
+ for y, ds in conflicts.items():
330
+ known[y] = min(ds, key=lambda d: cost(y, d))
331
+
332
+ nxt, carry = [None] * H, None
333
+ for y in range(H - 1, -1, -1):
334
+ carry = known[y] if known[y] is not None else carry
335
+ nxt[y] = carry
336
+ dys, prev = np.zeros(H, np.int32), 0
337
+ for y in range(H):
338
+ if known[y] is not None:
339
+ prev = known[y]
340
+ else:
341
+ # Rows between anchors (margins, unpaired images) follow whichever
342
+ # neighbouring offset actually lines the row up.
343
+ # Switching needs a clear win: a blank row matches anything, and
344
+ # would otherwise pull a real change out from under the comparison.
345
+ if nxt[y] not in (None, prev) and cost(y, nxt[y]) < 0.5 * cost(y, prev):
346
+ prev = nxt[y]
347
+ dys[y] = prev
348
+ return dys
349
+
350
+
351
+ def align(np, ref, loc, ref_g, loc_g, pairs):
352
+ """Local page resampled into ref coordinates, one vertical strip at a time.
353
+
354
+ Columns move independently (a card added to one kanban column pushes only
355
+ that column down), so each strip follows only the anchors that overlap it,
356
+ and strips are cut at anchor edges so none straddles two columns.
357
+ """
358
+ H, W = ref_g.shape
359
+ Hl = loc_g.shape[0]
360
+ anchors = [(r, l) for r, l, _ in pairs if 0 < r["h"] <= MAX_ANCHOR_HEIGHT]
361
+ cuts = {0, W} | set(range(0, W, ALIGN_STRIP))
362
+ for r, _ in anchors:
363
+ cuts |= {min(max(r["x"], 0), W), min(max(r["x"] + r["w"], 0), W)}
364
+ edges = sorted(cuts)
365
+ aligned = ref.copy() # rows with no local counterpart compare equal; `compared` says which
366
+ compared = np.zeros((H, W), bool)
367
+ mapped = np.zeros((Hl, W), bool)
368
+ offsets = np.zeros((H, len(edges) - 1), np.int32)
369
+ for i, (x0, x1) in enumerate(zip(edges, edges[1:])):
370
+ mine = [(r, l) for r, l in anchors if r["x"] < x1 and x0 < r["x"] + r["w"]]
371
+ dys = row_offsets(np, ref_g[:, x0:x1], loc_g[:, x0:x1], mine)
372
+ ly = np.arange(H) + dys
373
+ v = (ly >= 0) & (ly < Hl)
374
+ aligned[v, x0:x1] = loc[ly[v], x0:x1]
375
+ compared[v, x0:x1] = True
376
+ mapped[ly[v], x0:x1] = True
377
+ offsets[:, i] = dys
378
+ return aligned, mapped, compared, lambda x, y: int(offsets[y, np.searchsorted(edges, x, side="right") - 1])
379
+
380
+
381
+ def contains(e, cx, cy):
382
+ return e["x"] <= cx < e["x"] + e["w"] and e["y"] <= cy < e["y"] + e["h"]
383
+
384
+
385
+ def innermost(els, cx, cy):
386
+ hits = [e for e in els if contains(e, cx, cy)]
387
+ return min(hits, key=lambda e: e["w"] * e["h"]) if hits else None
388
+
389
+
390
+ def ink_color(np, crop, mask):
391
+ """The changed foreground colour (BGR): masked pixels farthest from the crop's background."""
392
+ px = crop[mask > 0]
393
+ if not len(px):
394
+ return None
395
+ dist = np.abs(px.astype(np.int32) - mode_color(np, crop).astype(np.int32)).sum(axis=1)
396
+ return np.median(px[dist >= np.percentile(dist, 90)], axis=0).astype(np.uint8)
397
+
398
+
399
+ def hex_color(bgr):
400
+ return "?" if bgr is None else "#{:02x}{:02x}{:02x}".format(*(int(c) for c in bgr[::-1]))
401
+
402
+
403
+ def classify(cv2, np, rc, ac, mc, thr):
404
+ g1 = cv2.cvtColor(rc, cv2.COLOR_BGR2GRAY)
405
+ g2 = cv2.cvtColor(ac, cv2.COLOR_BGR2GRAY)
406
+ s1, s2 = float(g1.std()), float(g2.std())
407
+ if s1 < 2 and s2 >= 6:
408
+ return "added", ""
409
+ if s2 < 2 and s1 >= 6:
410
+ return "removed", ""
411
+ h, w = g1.shape
412
+ if min(h, w) >= 8:
413
+ # Correlate the ink, not the paper: a flat background dominates the
414
+ # spectrum and drags the estimate off by a fraction of a pixel.
415
+ bg1 = float(np.median(g1))
416
+ (fx, fy), resp = cv2.phaseCorrelate(np.abs(g1.astype(np.float32) - bg1),
417
+ np.abs(g2.astype(np.float32) - bg1))
418
+ if resp > 0.2:
419
+ def residual(sx, sy):
420
+ back = cv2.warpAffine(ac, np.float32([[1, 0, -sx], [0, 1, -sy]]), (w, h),
421
+ flags=cv2.INTER_NEAREST, borderMode=cv2.BORDER_REPLICATE)
422
+ bx, by = abs(sx) + 1, abs(sy) + 1
423
+ return int((delta_e(cv2, np, rc, back) > thr)[by:h - by, bx:w - bx].sum()), (bx, by)
424
+ cands = {(int(np.floor(fx)) + i, int(np.floor(fy)) + j) for i in (0, 1) for j in (0, 1)}
425
+ cands = [c for c in cands if 0 < max(map(abs, c)) and abs(c[0]) < w // 2 and abs(c[1]) < h // 2]
426
+ if cands:
427
+ (sx, sy), (after, (bx, by)) = min(((c, residual(*c)) for c in cands), key=lambda t: t[1][0])
428
+ before = int(mc[by:h - by, bx:w - bx].sum())
429
+ if before and after <= 0.25 * before:
430
+ return "shift", f"local moved {sx:+d},{sy:+d}px"
431
+ i1, i2 = ink_color(np, rc, mc), ink_color(np, ac, mc)
432
+ if i1 is None or i2 is None or float(delta_e(cv2, np, i1.reshape(1, 1, 3), i2.reshape(1, 1, 3))[0, 0]) <= thr:
433
+ return "content", ""
434
+ colors = f"{hex_color(i1)}→{hex_color(i2)}"
435
+ e1, e2 = cv2.Canny(g1, 50, 150) > 0, cv2.Canny(g2, 50, 150) > 0
436
+ if not e1.any() and not e2.any():
437
+ return "color", colors
438
+ k = np.ones((3, 3), np.uint8)
439
+ d1 = cv2.dilate(e1.astype(np.uint8), k) > 0
440
+ d2 = cv2.dilate(e2.astype(np.uint8), k) > 0
441
+ o1 = (e1 & d2).sum() / max(int(e1.sum()), 1)
442
+ o2 = (e2 & d1).sum() / max(int(e2.sum()), 1)
443
+ if min(o1, o2) >= 0.8:
444
+ return "color", colors
445
+ return "content", ""
446
+
447
+
448
+ def write_montage(cv2, np, regions, ref, aligned, dE, thr, path):
449
+ tiles = []
450
+ for i, rg in enumerate(regions, 1):
451
+ x, y, w, h = rg["box"]
452
+ x0, y0 = max(x - 16, 0), max(y - 16, 0)
453
+ x1, y1 = min(x + w + 16, ref.shape[1]), min(y + h + 16, ref.shape[0])
454
+ r, a = ref[y0:y1, x0:x1], aligned[y0:y1, x0:x1]
455
+ heat = cv2.cvtColor(cv2.cvtColor(r, cv2.COLOR_BGR2GRAY), cv2.COLOR_GRAY2BGR) // 2 + 127
456
+ heat[dE[y0:y1, x0:x1] > thr] = (0, 0, 255)
457
+ sep = np.full((r.shape[0], 6, 3), 255, np.uint8)
458
+ row = np.hstack([r, sep, a, sep, heat])
459
+ scale = min(2.0, 1200 / row.shape[1], 320 / row.shape[0])
460
+ if scale != 1:
461
+ row = cv2.resize(row, None, fx=scale, fy=scale,
462
+ interpolation=cv2.INTER_NEAREST if scale > 1 else cv2.INTER_AREA)
463
+ label = np.full((22, max(row.shape[1], 320), 3), 240, np.uint8)
464
+ cv2.putText(label, f"#{i} {rg['kind']} ref | local | diff", (4, 16),
465
+ cv2.FONT_HERSHEY_SIMPLEX, 0.45, (30, 30, 30), 1, cv2.LINE_AA)
466
+ tiles += [label, row]
467
+ width = max(t.shape[1] for t in tiles)
468
+ padded = [np.hstack([t, np.full((t.shape[0], width - t.shape[1], 3), 255, np.uint8)])
469
+ if t.shape[1] < width else t for t in tiles]
470
+ cv2.imwrite(path, np.vstack(padded))
471
+
472
+
473
+ def run_pixel(args):
474
+ cv2, np = import_cv()
475
+ manual_map = json.load(open(args.map, encoding="utf-8")) if args.map else {}
476
+ stem = os.path.splitext(args.out)[0]
477
+ thr = args.threshold
478
+
479
+ with sync_playwright() as p:
480
+ browser = p.chromium.launch(headless=True)
481
+ ctx = browser.new_context(ignore_https_errors=True, device_scale_factor=1,
482
+ reduced_motion="reduce",
483
+ viewport={"width": args.width, "height": args.height})
484
+ page = ctx.new_page()
485
+ ref_data, ref = capture(page, args.ref, args, cv2, np)
486
+ loc_data, loc = capture(page, args.local, args, cv2, np)
487
+ browser.close()
488
+ cv2.imwrite(stem + "-ref.png", ref)
489
+ cv2.imwrite(stem + "-local.png", loc)
490
+
491
+ notes = []
492
+ W = min(ref.shape[1], loc.shape[1])
493
+ if ref.shape[1] != loc.shape[1]:
494
+ notes.append(f"page widths differ (ref {ref.shape[1]}px, local {loc.shape[1]}px); compared the first {W}px")
495
+ ref, loc = ref[:, :W].copy(), loc[:, :W].copy()
496
+ ref_els, loc_els = ref_data["elements"], loc_data["elements"]
497
+ pairs, missing, _ = build_pairs(ref_els, loc_els, manual_map)
498
+
499
+ ref_g = cv2.cvtColor(ref, cv2.COLOR_BGR2GRAY).astype(np.float32)
500
+ loc_g = cv2.cvtColor(loc, cv2.COLOR_BGR2GRAY).astype(np.float32)
501
+ aligned, mapped, compared, offset_at = align(np, ref, loc, ref_g, loc_g, pairs)
502
+ lost = int((~compared).any(axis=1).sum())
503
+ if lost:
504
+ notes.append(f"{lost} ref rows map below the end of the local page (content pushed out of a "
505
+ "fixed-height layout or clipped by --max-height) and were not compared")
506
+
507
+ def blobs(mask):
508
+ """Changed-pixel clusters as tight (x, y, w, h, count) boxes."""
509
+ contours, _ = cv2.findContours(cv2.dilate(mask, np.ones((9, 9), np.uint8)),
510
+ cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
511
+ for c in contours:
512
+ x, y, w, h = cv2.boundingRect(c)
513
+ inner = mask[y:y + h, x:x + w]
514
+ n = int(inner.sum())
515
+ if n >= args.min_area:
516
+ ys, xs = np.nonzero(inner)
517
+ yield (x + int(xs.min()), y + int(ys.min()),
518
+ int(xs.max() - xs.min()) + 1, int(ys.max() - ys.min()) + 1, n)
519
+
520
+ dE = delta_e(cv2, np, ref, aligned)
521
+ mask = (dE > thr).astype(np.uint8)
522
+ styled = [(r, d) for r, l, _ in pairs if (d := diff_pair(r, l))]
523
+ regions = []
524
+ for x, y, w, h, n in blobs(mask):
525
+ pad = 6
526
+ y0, y1 = max(y - pad, 0), min(y + h + pad, ref.shape[0])
527
+ x0, x1 = max(x - pad, 0), min(x + w + pad, W)
528
+ kind, detail = classify(cv2, np, ref[y0:y1, x0:x1], aligned[y0:y1, x0:x1], mask[y0:y1, x0:x1], thr)
529
+ cx, cy = x + w // 2, y + h // 2
530
+ el = innermost(ref_els, cx, cy)
531
+ limit = 4 * max(w * h, el["w"] * el["h"] if el else 0)
532
+ why = sorted({prop for r, d in styled if contains(r, cx, cy) and r["w"] * r["h"] <= limit
533
+ for prop, _, _ in d})
534
+ regions.append({"box": (x, y, w, h), "local_y": y + offset_at(cx, y), "px": n, "kind": kind,
535
+ "detail": detail, "el": el, "styles": why})
536
+ regions.sort(key=lambda rg: -rg["px"])
537
+
538
+ def hits_region(r):
539
+ return any(r["x"] < x + w and x < r["x"] + r["w"] and r["y"] < y + h and y < r["y"] + r["h"]
540
+ for x, y, w, h in (rg["box"] for rg in regions))
541
+ invisible = Counter(prop for r, d in styled if not hits_region(r) for prop, _, _ in d)
542
+
543
+ # Local pixels nothing in ref maps onto, and that are not just page background.
544
+ added = []
545
+ if not mapped.all():
546
+ bg = np.broadcast_to(mode_color(np, loc, step=4), loc.shape).copy()
547
+ unseen = ((~mapped) & (delta_e(cv2, np, loc, bg) > thr)).astype(np.uint8)
548
+ seen_local = [(rg["box"][0], rg["local_y"], rg["box"][2], rg["box"][3]) for rg in regions]
549
+ for x, y, w, h, n in blobs(unseen):
550
+ if any(x < bx + bw and bx < x + w and y < by + bh and by < y + h for bx, by, bw, bh in seen_local):
551
+ continue # already reported as a visible difference
552
+ added.append({"box": (x, y, w, h), "px": n,
553
+ "el": innermost(loc_els, x + w // 2, y + h // 2)})
554
+ added.sort(key=lambda a: -a["px"])
555
+
556
+ # The first element (in reading order) at each distinct offset is where
557
+ # that part of the layout starts sitting somewhere else.
558
+ drift, seen = [], [(0, 0)]
559
+ for r, l, _ in sorted(pairs, key=lambda t: (t[0]["y"], t[0]["x"])):
560
+ off = (l["x"] - r["x"], l["y"] - r["y"])
561
+ if all(max(abs(off[0] - s[0]), abs(off[1] - s[1])) > BOX_TOLERANCE_PX for s in seen):
562
+ drift.append((r, off))
563
+ seen.append(off)
564
+
565
+ montage = None
566
+ if regions:
567
+ montage = stem + "-montage.png"
568
+ write_montage(cv2, np, regions[:args.top], ref, aligned, dE, thr, montage)
569
+
570
+ def name(e):
571
+ return f"`{e['path']}`" if e else "?"
572
+
573
+ def text(e):
574
+ return (e["text"][:40] if e else "").replace("|", "\\|")
575
+
576
+ explained = sum(1 for rg in regions if rg["styles"])
577
+ summary = (f"{args.width}px: {len(regions)} regions ({explained} style-explained, "
578
+ f"{len(regions) - explained} pixel-only), {len(added)} added-locally, "
579
+ f"{sum(invisible.values())} invisible style diffs, {len(pairs)} matched elements")
580
+ rep = ["# visual-parity pixel\n", f"- ref: {args.ref}", f"- local: {args.local}",
581
+ f"- width: {args.width}px, ΔE threshold {thr}, min area {args.min_area}px",
582
+ f"- masks: {', '.join(args.mask) or 'none'}",
583
+ f"- screenshots: {stem}-ref.png, {stem}-local.png" + (f"; montage: {montage}" if montage else ""),
584
+ f"\n{summary}"]
585
+ rep += [f"\n**note** {n}" for n in notes]
586
+ if drift:
587
+ rep += ["\n## layout drift (first matched element at each new local offset)\n",
588
+ "| ref x,y | element | text | local offset dx,dy |", "|---|---|---|---|"]
589
+ rep += [f"| {r['x']},{r['y']} | {name(r)} | {text(r)} | {o[0]:+d},{o[1]:+d} |" for r, o in drift[:20]]
590
+ if regions:
591
+ rep += ["\n## visible differences (ref coordinates; montage shows the first ones)\n",
592
+ "| # | kind | ref box x,y,w,h | local y | changed px | element | text | detail | style diffs there |",
593
+ "|---|---|---|---|---|---|---|---|---|"]
594
+ for i, rg in enumerate(regions, 1):
595
+ rep.append(f"| {i} | {rg['kind']} | {','.join(map(str, rg['box']))} | {rg['local_y']} | {rg['px']} "
596
+ f"| {name(rg['el'])} | {text(rg['el'])} | {rg['detail']} "
597
+ f"| {', '.join(rg['styles']) or '**none — pixel-only**'} |")
598
+ if added:
599
+ rep += ["\n## added locally (local content no ref area maps onto)\n",
600
+ "| local box x,y,w,h | px | element | text |", "|---|---|---|---|"]
601
+ rep += [f"| {','.join(map(str, a['box']))} | {a['px']} | {name(a['el'])} | {text(a['el'])} |"
602
+ for a in added]
603
+ if invisible:
604
+ rep += ["\n## style diffs with no visible pixel change\n",
605
+ "These differ in computed style but render identically; usually safe to ignore.\n",
606
+ "| property | count |", "|---|---|"]
607
+ rep += [f"| {p_} | {c} |" for p_, c in invisible.most_common()]
608
+ if missing:
609
+ rep.append(f"\n{len(missing)} ref elements have no local counterpart by text; `diff` lists them.")
610
+ with open(args.out, "w", encoding="utf-8") as f:
611
+ f.write("\n".join(rep))
612
+
613
+ print(f"report: {args.out}")
614
+ if montage:
615
+ print(f"montage: {montage} (open only for regions the table below cannot explain)")
616
+ print(f" {summary}")
617
+ for n in notes:
618
+ print(f" WARN {n}")
619
+ for r, o in drift[:3]:
620
+ print(f" drift from ref {r['x']},{r['y']} {name(r)} {text(r)!r}: local offset {o[0]:+d},{o[1]:+d}")
621
+ for i, rg in enumerate(regions[:10], 1):
622
+ print(f" #{i} {rg['kind']:<7} {name(rg['el'])} {text(rg['el'])!r} {rg['detail']} "
623
+ f"[{', '.join(rg['styles']) or 'pixel-only'}]")
624
+ if len(regions) > 10:
625
+ print(f" ...{len(regions) - 10} more in the report")
626
+ for a in added[:5]:
627
+ print(f" added locally at {','.join(map(str, a['box']))} {name(a['el'])} {text(a['el'])!r}")
628
+ if invisible:
629
+ print(" invisible style diffs: " + ", ".join(f"{p_}×{c}" for p_, c in invisible.most_common(5)))
630
+ return 1 if regions or added else 0
631
+
632
+
247
633
  def save_video(video, out_path):
248
634
  """Persist a Playwright video; convert to MP4 when the caller asked for one.
249
635
 
@@ -391,9 +777,58 @@ def selftest():
391
777
  assert "color" in body, "should detect the li color change"
392
778
  assert "Only in ref" in body, "should report the ref-only element as missing locally"
393
779
  assert "`div`" in body or "margin-bottom" in body, "should match p->div across tag change"
780
+ selftest_pixel(d)
394
781
  print("\nselftest OK")
395
782
 
396
783
 
784
+ def selftest_pixel(d):
785
+ import importlib.util
786
+ if importlib.util.find_spec("cv2") is None:
787
+ print("\npixel selftest skipped: opencv-python-headless not installed")
788
+ return
789
+ style = ("<style>body{margin:0;font:16px/1.4 sans-serif} h1,p,div{margin:0 0 16px}"
790
+ ".icon{display:block;width:40px;height:40px;background:#2a6}</style>")
791
+ a = f"""<html><body>{style}<h1>Title</h1><p>Colour copy here</p>
792
+ <div class=box>Shifted box text</div><section><i class=icon></i></section>
793
+ <div style="display:flex;gap:12px"><div style="width:200px"><p>Left one</p><p>Left two</p></div>
794
+ <div style="width:200px"><p>Right one</p><i class=icon></i></div></div>
795
+ <p>Footer stays the same</p><p>Clock <span id=clock>12:00:01</span></p></body></html>"""
796
+ b = f"""<html><body>{style}<div style="height:60px;background:#fd0">New banner</div>
797
+ <h1>Title</h1><p style="color:#c00">Colour copy here</p>
798
+ <div class=box style="padding-left:12px">Shifted box text</div>
799
+ <section><i class=icon style="border-radius:50%"></i></section>
800
+ <div style="display:flex;gap:12px"><div style="width:200px"><p>Left one</p><p>Inserted left</p><p>Left two</p></div>
801
+ <div style="width:200px"><p>Right one</p><i class=icon></i></div></div>
802
+ <p style="padding-right:5px">Footer stays the same</p>
803
+ <p>Clock <span id=clock>12:59:59</span></p></body></html>"""
804
+ for name, html in (("pa.html", a), ("pb.html", b)):
805
+ open(os.path.join(d, name), "w", encoding="utf-8").write(html)
806
+ out = os.path.join(d, "pixel.md")
807
+ args = argparse.Namespace(
808
+ ref="file://" + os.path.join(d, "pa.html"), local="file://" + os.path.join(d, "pb.html"),
809
+ map=None, width=800, height=600, wait_selector=None, extra_wait=0, mask=["#clock"],
810
+ threshold=3.0, min_area=6, max_height=10000, top=6, out=out)
811
+ assert run_pixel(args) == 1
812
+ body = open(out, encoding="utf-8").read()
813
+ rows = [line for line in body.splitlines() if line.startswith("| ") and line[2].isdigit()]
814
+ region_rows = [r for r in rows if r.count("|") >= 10]
815
+ assert any("| color |" in r and "Colour copy" in r and "#cc0000" in r and "color" in r.split("|")[9]
816
+ for r in region_rows), "should classify the text colour change and explain it by `color`"
817
+ assert any("| shift |" in r and "+12,+0" in r and "padding-left" in r for r in region_rows), \
818
+ "should see the box content move 12px and tie it to padding-left"
819
+ assert any("pixel-only" in r and "section" in r for r in region_rows), \
820
+ "the square→circle icon has no text to pair; it must surface as pixel-only"
821
+ assert len(region_rows) <= 4, f"the 60px banner must not cascade into every row below it: {region_rows}"
822
+ added = body.split("## added locally")[1].split("##")[0]
823
+ assert "New banner" in added, "should report the inserted banner"
824
+ assert "Inserted left" in added, "should report the item inserted into the left column"
825
+ assert not any("Right one" in r or "Left two" in r for r in region_rows), \
826
+ "an insertion in one column must not flag the column beside it"
827
+ assert "12:59" not in body,"a masked element must not produce a region"
828
+ assert "| padding-right | 1 |" in body, "an invisible style diff should be reported as such"
829
+ assert os.path.exists(os.path.join(d, "pixel-montage.png"))
830
+
831
+
397
832
  def main():
398
833
  # Windows consoles default to a legacy codepage (e.g. cp950); page text
399
834
  # echoed to stdout must not crash the run.
@@ -432,11 +867,32 @@ def main():
432
867
  f.add_argument("--video-size", default="1280x720", help="WxH of both the recording and the viewport (default 1280x720)")
433
868
  f.add_argument("--video-tail", type=float, default=1.0, help="seconds to keep recording after the last step so trailing animations finish (default 1)")
434
869
 
870
+ x = sub.add_parser("pixel", help="OpenCV screenshot diff, aligned by matched elements and "
871
+ "cross-checked against computed styles")
872
+ x.add_argument("--ref", required=True)
873
+ x.add_argument("--local", required=True)
874
+ x.add_argument("--map", help="same as diff --map; better pairing also means better alignment")
875
+ x.add_argument("--width", type=int, default=1440)
876
+ x.add_argument("--height", type=int, default=900)
877
+ x.add_argument("--wait-selector")
878
+ x.add_argument("--extra-wait", type=float, default=0)
879
+ x.add_argument("--mask", action="append", default=[],
880
+ help="selector painted out on both pages (clocks, ads, avatars); repeatable")
881
+ x.add_argument("--threshold", type=float, default=3.0,
882
+ help="CIE76 ΔE a pixel must exceed to count as changed (default 3, about just-noticeable)")
883
+ x.add_argument("--min-area", type=int, default=6, help="ignore regions with fewer changed pixels")
884
+ x.add_argument("--max-height", type=int, default=10000, help="clip screenshots to this many px")
885
+ x.add_argument("--top", type=int, default=6, help="regions drawn in the montage")
886
+ x.add_argument("--out", default="parity-pixel.md",
887
+ help="report path; screenshots and montage are written next to it")
888
+
435
889
  sub.add_parser("selftest", help="verify the matcher/differ still work")
436
890
 
437
891
  args = ap.parse_args()
438
892
  if args.cmd == "diff":
439
893
  sys.exit(run_diff(args))
894
+ if args.cmd == "pixel":
895
+ sys.exit(run_pixel(args))
440
896
  if args.cmd == "responsive":
441
897
  args.widths, args.width = "375,768,1440", 1440
442
898
  sys.exit(run_diff(args))