"""Coarse pixel comparison of screenshots, with the standard library only. Decodes 8-bit, non-interlaced gray, gray+alpha, RGB and RGBA PNGs, which is what Chrome captures; palette, 16-bit and interlaced images raise ValueError. """ from __future__ import annotations import math import struct import zlib CHANNELS = {0: 1, 2: 3, 4: 2, 6: 4} # Pixels per block side. At half scale Chrome averages each 2x2 itself, so a # block covers 8 page pixels or more and dither inside it cancels out. BLOCK = 4 # Most pixels one comparison captures: about 10 ms to decode and average. SAMPLES = 40_000 def scale(width: float, height: float) -> float: return min(0.5, math.sqrt(SAMPLES / (width * height))) def decode(png: bytes) -> tuple[int, int, int, bytes]: """Width, height, channels per pixel and raw rows of an 8-bit PNG.""" if png[:8] != b"\x89PNG\r\n\x1a\n" or png[12:16] != b"IHDR": raise ValueError("not a PNG") width, height, depth, colour, _, _, interlace = struct.unpack( ">IIBBBBB", png[16:29] ) if depth != 8 or colour not in CHANNELS or interlace: raise ValueError("only 8-bit, non-interlaced, non-palette PNGs decode here") at, data = 8, bytearray() while at + 8 <= len(png): size, chunk = struct.unpack_from(">I4s", png, at) if chunk == b"IDAT": data += png[at + 8 : at + 8 + size] at += 12 + size raw = zlib.decompress(data) step = CHANNELS[colour] stride = width * step out = bytearray(stride * height) prior = bytearray(stride) for y in range(height): start = y * (stride + 1) method = raw[start] row = bytearray(raw[start + 1 : start + 1 + stride]) if method == 1: for i in range(step, stride): row[i] = (row[i] + row[i - step]) & 255 elif method == 2: for i in range(stride): row[i] = (row[i] + prior[i]) & 255 elif method == 3: for i in range(stride): left = row[i - step] if i >= step else 0 row[i] = (row[i] + ((left + prior[i]) >> 1)) & 255 elif method == 4: for i in range(stride): a = row[i - step] if i >= step else 0 b = prior[i] c = prior[i - step] if i >= step else 0 p = a + b - c pa, pb, pc = abs(p - a), abs(p - b), abs(p - c) row[i] = ( row[i] + (a if pa <= pb and pa <= pc else b if pb <= pc else c) ) & 255 out[y * stride : (y + 1) * stride] = row prior = row return width, height, step, bytes(out) def blocks(png: bytes) -> list[tuple[float, ...]]: """Mean colour of each BLOCK x BLOCK square, row by row, alpha ignored.""" width, height, step, pixels = decode(png) colours = 3 if step >= 3 else 1 stride = width * step means: list[tuple[float, ...]] = [] for top in range(0, height, BLOCK): rows = range(top, min(top + BLOCK, height)) for left in range(0, width, BLOCK): right = min(left + BLOCK, width) count = len(rows) * (right - left) means.append( tuple( sum( sum( pixels[ y * stride + left * step + c : y * stride + right * step : step ] ) for y in rows ) / count for c in range(colours) ) ) return means def difference(a: list[tuple[float, ...]], b: list[tuple[float, ...]]) -> list[float]: """How far each block's colour moved, in 0-255 channel units.""" return [max(abs(x - y) for x, y in zip(p, q)) for p, q in zip(a, b)] class ChangeDetector: """Decides wait_for_change from block frames, with no clock or browser. The first frame fed is the reference. The next `calibration` frames learn how far each block moves on its own; from then on a block counts as changed when it has moved more than that plus `tolerance`. The `floor` frames after them measure the fraction that changes anyway, the noise floor. Each later frame has changed enough once its fraction reaches the noise floor plus `min_change`. """ def __init__( self, min_change: float, tolerance: float, calibration: int, floor: int, ) -> None: self.min_change = min_change self.tolerance = tolerance self.calibration = calibration self.floor_frames = floor self.fed = 0 self.first: list[tuple[float, ...]] = [] self.noise: list[float] = [] self.limits: list[float] = [] self.floor: float | None = None self.most = 0.0 @property def measuring(self) -> bool: """Whether the next frame still calibrates or measures the floor.""" return self.fed <= self.calibration + self.floor_frames def changed(self, frame: list[tuple[float, ...]]) -> float: """The fraction of blocks that moved past their limits.""" moved = difference(self.first, frame) return sum(m > limit for m, limit in zip(moved, self.limits)) / len(moved) def feed(self, frame: list[tuple[float, ...]]) -> float | None: """Take the next frame. Returns the changed fraction once a frame after calibration changed enough, otherwise None.""" self.fed += 1 if self.fed == 1: self.first = frame self.noise = [0.0] * len(frame) elif self.fed <= 1 + self.calibration: self.noise = list(map(max, self.noise, difference(self.first, frame))) if self.fed == 1 + self.calibration: self.limits = [n + self.tolerance for n in self.noise] self.floor = 0.0 if self.fed <= 1 + self.calibration: return None floor = self.floor or 0.0 if self.fed <= 1 + self.calibration + self.floor_frames: self.floor = max(floor, self.changed(frame)) return None fraction = self.changed(frame) self.most = max(self.most, fraction) if fraction >= floor + self.min_change: return fraction return None def shortfall(self) -> str: """What a wait that timed out saw, for its error.""" measured = "unmeasured" if self.floor is None else f"{self.floor:.1%}" return ( f"Region did not change enough: max change {self.most:.1%}," f" noise floor {measured}, wanted {self.min_change:.1%}." )