#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ pixel_gate.py — 像素门四档自查脚本 v1 零装包原则:只用 python3 标准库 + 系统自带 file / ffmpeg。 PIL 存在时用于解码与精确裁切(快);不存在时自动退回纯标准库 PNG 解码 (支持 8/16-bit、非隔行;JPEG 在无 PIL 时只能读尺寸,不能做像素分析)。 四档(与 procedure「像素门判读四档」一一对应): gate1 定档 量承载信息构件的最小字高;<= --threshold 判 1:1 不可判,给升档倍数 gate1b 升档 --zoom N 裁切并放大落盘,打印裁剪坐标与滤波器 gate2 抽帧 ffmpeg 抽一帧落盘,实读;不采信「已渲染/已通过」自报 gate3 双径 两路全量下载:先 magic-byte 嗅探,再比 sha256 gate4 落行 sha256 / mime / dims / bytes 一行,mime 以 file 实判 退出码: 0 全过 1 任一档 FAIL(明确红) 2 无 FAIL,但存在 INDETERMINATE(1:1 不可判,必须先升档) 64 用法错误 用法示例: python3 pixel_gate.py --image shot.png python3 pixel_gate.py --image shot.png --zoom 4 --crop 40,120,200,60 python3 pixel_gate.py --video clip.mp4 --at 12.5 python3 pixel_gate.py --urlA --urlB python3 pixel_gate.py --self-test """ import argparse import hashlib import http.server import os import socketserver import struct import subprocess import sys import threading import zlib from urllib.parse import urlparse from urllib.request import Request, urlopen VERSION = "1.0" THRESHOLD_PX = 21 # 过程序约定的 1:1 不可判门限 ZOOM_FLOOR = 4 # 过程序约定:升档至少 4x PNG_SIG = b"\x89PNG\r\n\x1a\n" EXIT_PASS, EXIT_FAIL, EXIT_INDET, EXIT_USAGE = 0, 1, 2, 64 # -------------------------------------------------------------------------- # 小工具 # -------------------------------------------------------------------------- def sha256_file(path, chunk=1 << 20): h = hashlib.sha256() with open(path, "rb") as f: while True: b = f.read(chunk) if not b: break h.update(b) return h.hexdigest() def mime_of(path): """file 实判,不信扩展名。返回 (mime, raw_line)""" try: m = subprocess.run(["file", "-b", "--mime-type", path], capture_output=True, text=True, timeout=30) r = subprocess.run(["file", "-b", path], capture_output=True, text=True, timeout=30) return (m.stdout.strip() or "unknown"), (r.stdout.strip() or "") except Exception as e: # noqa: BLE001 return "unknown", "file 调用失败: %s" % e def sniff(head): """magic-byte 嗅探。head 至少 16 字节。返回 (kind, is_media)""" if head.startswith(b"\x89PNG\r\n\x1a\n"): return "png", True if head.startswith(b"\xff\xd8\xff"): return "jpeg", True if head.startswith(b"GIF87a") or head.startswith(b"GIF89a"): return "gif", True if head.startswith(b"PK\x03\x04") or head.startswith(b"PK\x05\x06"): return "zip", True if len(head) >= 12 and head[4:8] == b"ftyp": return "mp4", True if len(head) >= 12 and head[0:4] == b"RIFF" and head[8:12] == b"WEBP": return "webp", True if head[:1] in (b"{", b"["): return "json-body", False if head.startswith(b"H", b[i + 2:i + 4])[0] if m in (0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7, 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF): h, w = struct.unpack(">HH", b[i + 5:i + 9]) return w, h i += 2 + seg raise ValueError("JPEG 未找到 SOF 段") def dims_of(path): """尺寸:PNG 读 IHDR,JPEG 读 SOF;其它退回 sips。返回 (w,h,how)""" with open(path, "rb") as f: head = f.read(4096) if head.startswith(PNG_SIG) and len(head) >= 24: w, h = struct.unpack(">II", head[16:24]) return w, h, "png-ihdr" if head.startswith(b"\xff\xd8\xff"): w, h = jpeg_dims(head) return w, h, "jpeg-sof" try: out = subprocess.run(["sips", "-g", "pixelWidth", "-g", "pixelHeight", path], capture_output=True, text=True, timeout=30).stdout w = h = None for line in out.splitlines(): line = line.strip() if line.startswith("pixelWidth:"): w = int(line.split(":")[1]) elif line.startswith("pixelHeight:"): h = int(line.split(":")[1]) if w and h: return w, h, "sips" except Exception: # noqa: BLE001 pass raise ValueError("无法读取尺寸: %s" % path) # -------------------------------------------------------------------------- # 图片解码:PIL 优先,纯标准库兜底 # -------------------------------------------------------------------------- def have_pil(): try: import PIL # noqa: F401 return True except Exception: # noqa: BLE001 return False def _unfilter(raw, h, stride, bpp): out = bytearray(h * stride) prev = bytearray(stride) pos = 0 for y in range(h): ft = raw[pos] pos += 1 line = bytearray(raw[pos:pos + stride]) pos += stride if ft == 1: for i in range(bpp, stride): line[i] = (line[i] + line[i - bpp]) & 0xFF elif ft == 2: for i in range(stride): line[i] = (line[i] + prev[i]) & 0xFF elif ft == 3: for i in range(stride): a = line[i - bpp] if i >= bpp else 0 line[i] = (line[i] + ((a + prev[i]) >> 1)) & 0xFF elif ft == 4: for i in range(stride): a = line[i - bpp] if i >= bpp else 0 b = prev[i] c = prev[i - bpp] if i >= bpp else 0 p = a + b - c pa, pb, pc = abs(p - a), abs(p - b), abs(p - c) pr = a if (pa <= pb and pa <= pc) else (b if pb <= pc else c) line[i] = (line[i] + pr) & 0xFF elif ft != 0: raise ValueError("未知 PNG 行滤波类型 %d" % ft) out[y * stride:(y + 1) * stride] = line prev = line return out def decode_png_stdlib(path): """返回 (w, h, rgb: bytearray)。仅支持 8/16-bit 非隔行。""" data = open(path, "rb").read() if not data.startswith(PNG_SIG): raise ValueError("不是 PNG") i, idat, plte, ihdr = 8, bytearray(), None, None while i + 8 <= len(data): ln = struct.unpack(">I", data[i:i + 4])[0] typ = data[i + 4:i + 8] body = data[i + 8:i + 8 + ln] i += 12 + ln if typ == b"IHDR": ihdr = struct.unpack(">IIBBBBB", body) elif typ == b"PLTE": plte = body elif typ == b"IDAT": idat += body elif typ == b"IEND": break if ihdr is None: raise ValueError("PNG 缺 IHDR") w, h, bd, ct, _comp, _filt, inter = ihdr if inter: raise ValueError("隔行(Adam7) PNG 不支持纯标准库路径") if bd not in (8, 16): raise ValueError("位深 %d 不支持纯标准库路径" % bd) ch = {0: 1, 2: 3, 3: 1, 4: 2, 6: 4}.get(ct) if ch is None: raise ValueError("色彩类型 %d 不支持" % ct) step = bd // 8 bpp = ch * step stride = w * bpp raw = zlib.decompress(bytes(idat)) px = _unfilter(raw, h, stride, bpp) rgb = bytearray(w * h * 3) if ct == 2: if step == 1: rgb[:] = px else: for p in range(w * h): o = p * 6 rgb[p * 3:p * 3 + 3] = px[o:o + 3] return w, h, rgb for p in range(w * h): o = p * bpp if ct == 0: g = px[o] rgb[p * 3] = rgb[p * 3 + 1] = rgb[p * 3 + 2] = g elif ct == 4: g = px[o] rgb[p * 3] = rgb[p * 3 + 1] = rgb[p * 3 + 2] = g elif ct == 6: rgb[p * 3:p * 3 + 3] = px[o:o + 3] elif ct == 3: idx = px[o] if plte is None: raise ValueError("调色板 PNG 缺 PLTE") rgb[p * 3:p * 3 + 3] = plte[idx * 3:idx * 3 + 3] return w, h, rgb def load_luma(path, engine="auto", crop=None): """返回 (w, h, luma, decoder_name)。crop=(x,y,w,h) 时只解码该区域。""" want_pil = (engine in ("auto", "pil")) and have_pil() if want_pil: from PIL import Image im = Image.open(path).convert("RGB") if crop: x, y, cw, ch = crop im = im.crop((x, y, x + cw, y + ch)) luma = im.convert("L").tobytes() return im.size[0], im.size[1], luma, "pil" if engine == "pil": raise ValueError("指定 --engine pil 但 PIL 不可用") w, h, rgb = decode_png_stdlib(path) if crop: x, y, cw, ch = crop if x < 0 or y < 0 or cw <= 0 or ch <= 0 or x + cw > w or y + ch > h: raise ValueError("crop 越界: %s 对 %dx%d" % (crop, w, h)) sub = bytearray(cw * ch * 3) for oy in range(ch): s = ((y + oy) * w + x) * 3 sub[oy * cw * 3:(oy + 1) * cw * 3] = rgb[s:s + cw * 3] rgb, w, h = sub, cw, ch luma = bytearray(w * h) for p in range(w * h): q = p * 3 luma[p] = (rgb[q] * 77 + rgb[q + 1] * 150 + rgb[q + 2] * 29) >> 8 return w, h, luma, "stdlib" # -------------------------------------------------------------------------- # gate1 定档:构件尺寸估计 # -------------------------------------------------------------------------- def analyze_components(luma, w, h): """ 保守估计「承载信息的最小构件高度」。 判据(可复算): 1. bg = 亮度直方图 32 桶里最满那桶的中位亮度 2. d = |L - bg|,取 99 分位 d99 3. thr = clamp(0.15 * d99, 20, 96) —— 下限 20 防止把噪声当墨 4. ink = d > thr 5. 8 连通取组件,丢弃:贴边、面积<4、高<3、高>0.6H、宽>0.9W、填充率不在 [0.08,0.95] 6. min_text_px = 剩余组件高度的 20 分位(向下取整) 取 20 分位而不是最小值:标点、i 的点、装饰点会给出 2-3px 的尾段, 用最小值会让判据长期误红;20 分位仍然偏保守。 """ n = w * h hist = [0] * 256 for v in luma: hist[v] += 1 buckets = [0] * 32 for v in range(256): buckets[v >> 3] += hist[v] bmax = max(range(32), key=lambda k: buckets[k]) lo, hi = bmax * 8, bmax * 8 + 7 tot = sum(hist[lo:hi + 1]) or 1 acc = 0 bg = lo for v in range(lo, hi + 1): acc += hist[v] if acc * 2 >= tot: bg = v break dhist = [0] * 256 ink_total = 0 for v in luma: d = v - bg if d < 0: d = -d dhist[d] += 1 target = int(n * 0.99) acc = 0 d99 = 255 for d in range(256): acc += dhist[d] if acc >= target: d99 = d break thr = int(max(20, min(96, 0.15 * d99))) mask = bytearray(n) for i in range(n): d = luma[i] - bg if d < 0: d = -d if d > thr: mask[i] = 1 ink_total += 1 heights = [] comps = 0 for start in range(n): if mask[start] != 1: continue stack = [start] mask[start] = 2 area = 0 minx, maxx = w, -1 miny, maxy = h, -1 border = False while stack: p = stack.pop() area += 1 y = p // w x = p - y * w if x < minx: minx = x if x > maxx: maxx = x if y < miny: miny = y if y > maxy: maxy = y if x == 0 or y == 0 or x == w - 1 or y == h - 1: border = True if x > 0 and mask[p - 1] == 1: mask[p - 1] = 2 stack.append(p - 1) if x < w - 1 and mask[p + 1] == 1: mask[p + 1] = 2 stack.append(p + 1) if y > 0: q = p - w if mask[q] == 1: mask[q] = 2 stack.append(q) if x > 0 and mask[q - 1] == 1: mask[q - 1] = 2 stack.append(q - 1) if x < w - 1 and mask[q + 1] == 1: mask[q + 1] = 2 stack.append(q + 1) if y < h - 1: q = p + w if mask[q] == 1: mask[q] = 2 stack.append(q) if x > 0 and mask[q - 1] == 1: mask[q - 1] = 2 stack.append(q - 1) if x < w - 1 and mask[q + 1] == 1: mask[q + 1] = 2 stack.append(q + 1) comps += 1 if border or area < 4: continue bh = maxy - miny + 1 bw = maxx - minx + 1 if bh < 3 or bh > 0.6 * h or bw > 0.9 * w: continue fill = area / float(bw * bh) if fill < 0.08 or fill > 0.95: continue heights.append(bh) heights.sort() if not heights: return dict(bg=bg, thr=thr, ink=ink_total, comps=comps, n=0, hmin=None, p20=None, hmed=None, hmax=None) k = max(0, int(len(heights) * 0.20) - 1) return dict(bg=bg, thr=thr, ink=ink_total, comps=comps, n=len(heights), hmin=heights[0], p20=heights[k], hmed=heights[len(heights) // 2], hmax=heights[-1]) def suggested_zoom(min_text_px): if not min_text_px: return ZOOM_FLOOR need = -(-THRESHOLD_PX // int(min_text_px)) return max(ZOOM_FLOOR, min(16, need)) # -------------------------------------------------------------------------- # 输出收集 # -------------------------------------------------------------------------- class Report: def __init__(self): self.rows = [] def add(self, gate, verdict, line): self.rows.append((gate, verdict, line)) print(line) def code(self): vs = [v for (_g, v, _l) in self.rows] if "FAIL" in vs: return EXIT_FAIL if "INDETERMINATE" in vs: return EXIT_INDET return EXIT_PASS def counts(self): out = {"PASS": 0, "FAIL": 0, "INDETERMINATE": 0, "INFO": 0} for _g, v, _l in self.rows: out[v] = out.get(v, 0) + 1 return out def rc_name(code): return {0: "PASS(0)", 1: "FAIL(1)", 2: "INDETERMINATE(2)", 64: "USAGE(64)"}.get(code, str(code)) # -------------------------------------------------------------------------- # gate1 / gate1b # -------------------------------------------------------------------------- def gate1(rep, path, min_text_px_declared, engine, threshold, crop=None): try: w, h, luma, dec = load_luma(path, engine, crop) except Exception as e: # noqa: BLE001 rep.add("gate1", "FAIL", "[gate1] verdict=FAIL reason=decode_error detail=%s" % e) return if w * h > 12_000_000: rep.add("gate1", "INDETERMINATE", "[gate1] verdict=INDETERMINATE reason=too_large %dx%d px>12M,请先 --crop 或 --zoom" % (w, h)) return a = analyze_components(luma, w, h) region = ("region=%d,%d,%d,%d" % crop) if crop else "region=full" rep.add("gate1", "INFO", "[gate1] file=%s %s dims=%dx%d decoder=%s" % (path, region, w, h, dec)) rep.add("gate1", "INFO", "[gate1] bg_luma=%d ink_thr=%d ink_px=%d comps=%d glyph_comps=%d" % (a["bg"], a["thr"], a["ink"], a["comps"], a["n"])) if min_text_px_declared: m = int(min_text_px_declared) src = "declared" rep.add("gate1", "INFO", "[gate1] heights=skip(none) 使用 --min-text-px 声明值") else: m = a["p20"] src = "measured" if a["n"] == 0: rep.add("gate1", "FAIL", "[gate1] verdict=FAIL reason=no_glyph_component " "未找到字形成分;纯色/纯图形件请用 --min-text-px 显式声明,或改用 gate4 只落行") return rep.add("gate1", "INFO", "[gate1] heights min=%d p20=%d median=%d max=%d n=%d" % (a["hmin"], a["p20"], a["hmed"], a["hmax"], a["n"])) z = suggested_zoom(m) rep.add("gate1", "INFO", "[gate1] min_text_px=%d source=%s threshold_px=%d suggested_zoom=%d " "rule=max(%d,ceil(%d/min_text_px))" % (m, src, threshold, z, ZOOM_FLOOR, threshold)) if m <= threshold: rep.add("gate1", "INDETERMINATE", "[gate1] verdict=INDETERMINATE reason=min_text_px<=threshold " "-> 1:1 不可判,先 --zoom %d 升档再读;该构件上任何 1:1 结论(绿/红)不采信" % z) else: rep.add("gate1", "PASS", "[gate1] verdict=PASS reason=min_text_px>threshold -> 1:1 可判 (%d>%d)" % (m, threshold)) def gate1b(rep, path, zoom, crop, engine, outdir): try: w, h, _luma, dec = load_luma(path, engine) except Exception as e: # noqa: BLE001 rep.add("gate1b", "FAIL", "[gate1b] verdict=FAIL reason=decode_error detail=%s" % e) return if crop: x, y, cw, ch = crop else: x, y, cw, ch = 0, 0, w, h if x < 0 or y < 0 or cw <= 0 or ch <= 0 or x + cw > w or y + ch > h: rep.add("gate1b", "FAIL", "[gate1b] verdict=FAIL reason=crop_out_of_bounds crop=%d,%d,%d,%d src=%dx%d" % (x, y, cw, ch, w, h)) return ow, oh = cw * zoom, ch * zoom os.makedirs(outdir, exist_ok=True) tag = os.path.splitext(os.path.basename(path))[0] out = os.path.join(outdir, "%s_zoom%dx.png" % (tag, zoom)) if dec == "pil": from PIL import Image im = Image.open(path).convert("RGB").crop((x, y, x + cw, y + ch)) im.resize((ow, oh), Image.NEAREST).save(out) how = "PIL crop((%d,%d,%d,%d)).resize((%d,%d), NEAREST)" % (x, y, x + cw, y + ch, ow, oh) else: sw, sh, rgb = decode_png_stdlib(path) buf = bytearray(ow * oh * 3) for oy in range(oh): sy = y + oy // zoom row = sy * sw for ox in range(ow): sx = x + ox // zoom s = (row + sx) * 3 d = (oy * ow + ox) * 3 buf[d:d + 3] = rgb[s:s + 3] write_png(out, ow, oh, buf) how = "stdlib nearest sx=x+ox//%d sy=y+oy//%d" % (zoom, zoom) rep.add("gate1b", "INFO", "[gate1b] src=%s dims=%dx%d crop=%d,%d,%d,%d zoom=%d filter=nearest engine=%s" % (path, w, h, x, y, cw, ch, zoom, dec)) rep.add("gate1b", "INFO", "[gate1b] out=%s out_dims=%dx%d how=%s" % (out, ow, oh, how)) rep.add("gate1b", "INFO", "[gate1b] sha256=%s" % sha256_file(out)) rep.add("gate1b", "PASS", "[gate1b] verdict=PASS reason=upscaled 落盘可复算") def write_png(path, w, h, rgb): raw = bytearray() for y in range(h): raw.append(0) raw += rgb[y * w * 3:(y + 1) * w * 3] def chunk(t, d): return struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d) & 0xFFFFFFFF) data = (PNG_SIG + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 2, 0, 0, 0)) + chunk(b"IDAT", zlib.compress(bytes(raw), 9)) + chunk(b"IEND", b"")) with open(path, "wb") as f: f.write(data) # -------------------------------------------------------------------------- # gate2 抽帧 # -------------------------------------------------------------------------- def gate2(rep, video, at, accurate, outdir): if not os.path.exists(video): rep.add("gate2", "FAIL", "[gate2] verdict=FAIL reason=video_missing path=%s" % video) return ff = None for cand in ("ffmpeg", "/opt/homebrew/bin/ffmpeg", "/usr/local/bin/ffmpeg", "/usr/bin/ffmpeg"): if os.path.sep in cand: if os.path.exists(cand): ff = cand break else: for p in os.environ.get("PATH", "").split(os.pathsep): if os.path.exists(os.path.join(p, cand)): ff = os.path.join(p, cand) break if ff: break if not ff: rep.add("gate2", "FAIL", "[gate2] verdict=FAIL reason=ffmpeg_missing 无法抽帧,不可用『已渲染』代替") return os.makedirs(outdir, exist_ok=True) tag = os.path.splitext(os.path.basename(video))[0] out = os.path.join(outdir, "%s_at%ss.png" % (tag, ("%g" % at).replace(".", "p"))) cmd = [ff, "-hide_banner", "-loglevel", "error", "-y"] if accurate: cmd += ["-i", video, "-ss", "%g" % at] else: cmd += ["-ss", "%g" % at, "-i", video] cmd += ["-frames:v", "1", "-update", "1", out] rep.add("gate2", "INFO", "[gate2] cmd=%s" % " ".join(cmd)) try: p = subprocess.run(cmd, capture_output=True, text=True, timeout=120) except Exception as e: # noqa: BLE001 rep.add("gate2", "FAIL", "[gate2] verdict=FAIL reason=ffmpeg_error detail=%s" % e) return if p.returncode != 0 or not os.path.exists(out) or os.path.getsize(out) < 64: rep.add("gate2", "FAIL", "[gate2] verdict=FAIL reason=no_frame rc=%d stderr=%s" % (p.returncode, (p.stderr or "").strip()[:300] or "(empty)")) return with open(out, "rb") as f: head = f.read(16) kind, ok = sniff(head) if not ok: rep.add("gate2", "FAIL", "[gate2] verdict=FAIL reason=bad_magic kind=%s %s" % (kind, printable_head(head))) return w, h, how = dims_of(out) rep.add("gate2", "INFO", "[gate2] out=%s kind=%s dims=%dx%d(%s) bytes=%d accurate=%d" % (out, kind, w, h, how, os.path.getsize(out), int(bool(accurate)))) rep.add("gate2", "INFO", "[gate2] sha256=%s" % sha256_file(out)) rep.add("gate2", "PASS", "[gate2] verdict=PASS reason=frame_dropped 请实读该帧,不采信自报") # -------------------------------------------------------------------------- # gate3 双径 # -------------------------------------------------------------------------- def fetch(url, timeout): req = Request(url, headers={"User-Agent": "pixel-gate/1.0"}) with urlopen(req, timeout=timeout) as r: body = r.read() return dict(status=getattr(r, "status", 200), final=r.geturl(), body=body, ctype=r.headers.get("Content-Type", "")) def gate3(rep, urlA, urlB, timeout, outdir, same_origin_fatal=False): os.makedirs(outdir, exist_ok=True) recs = [] for name, url in (("A", urlA), ("B", urlB)): try: r = fetch(url, timeout) except Exception as e: # noqa: BLE001 rep.add("gate3", "FAIL", "[gate3] route%s verdict=FAIL reason=fetch_error url=%s detail=%s" % (name, url, e)) return head = r["body"][:32] kind, ok = sniff(head) host = urlparse(r["final"]).hostname or "?" rec = dict(name=name, url=url, status=r["status"], final=r["final"], host=host, size=len(r["body"]), kind=kind, media=ok, head=head, sha=hashlib.sha256(r["body"]).hexdigest()) recs.append(rec) if ok: rep.add("gate3", "INFO", "[gate3] route%s status=%d final=%s host=%s bytes=%d magic=%s head_ok=1" % (name, r["status"], r["final"], host, rec["size"], kind)) else: rep.add("gate3", "INFO", "[gate3] route%s status=%d final=%s host=%s bytes=%d magic=%s head_ok=0" % (name, r["status"], r["final"], host, rec["size"], kind)) rep.add("gate3", "INFO", "[gate3] route%s first32 %s" % (name, printable_head(head))) rep.add("gate3", "FAIL", "[gate3] verdict=FAIL reason=non_media_body route=%s bytes=%d magic=%s " "(HTTP 200 不等于正文;72B JSON 错误体即此格)" % (name, rec["size"], kind)) return a, b = recs sa, sb = a["sha"], b["sha"] rep.add("gate3", "INFO", "[gate3] sha256 A=%s bytes=%d" % (sa, a["size"])) rep.add("gate3", "INFO", "[gate3] sha256 B=%s bytes=%d" % (sb, b["size"])) if a["host"] == b["host"]: rep.add("gate3", "INFO", "[gate3] warn=same_origin 两径落到同一 host(%s):sha256 相等属自证,不构成交叉验证;" "要交叉必须两径服务端不同源" % a["host"]) if sa != sb: rep.add("gate3", "FAIL", "[gate3] verdict=FAIL reason=sha256_mismatch A=%s B=%s bytes %d vs %d" % (sa[:16], sb[:16], a["size"], b["size"])) return rep.add("gate3", "PASS", "[gate3] verdict=PASS reason=magic_ok+sha256_equal sha256=%s bytes=%d 件本身未坏" % (sa, a["size"])) return sa # -------------------------------------------------------------------------- # gate4 落行 # -------------------------------------------------------------------------- def gate4(rep, path): if not os.path.exists(path): rep.add("gate4", "FAIL", "[gate4] verdict=FAIL reason=file_missing path=%s" % path) return size = os.path.getsize(path) sha = sha256_file(path) mime, raw = mime_of(path) try: w, h, how = dims_of(path) dims = "%dx%d" % (w, h) except Exception: # noqa: BLE001 dims = "?x?" how = "unavailable" rep.add("gate4", "INFO", "[gate4] file=%s file_raw=%s dims_src=%s" % (path, raw, how)) ext = os.path.splitext(path)[1].lower().lstrip(".") extmap = {"png": "image/png", "jpg": "image/jpeg", "jpeg": "image/jpeg", "gif": "image/gif", "webp": "image/webp", "mp4": "video/mp4", "zip": "application/zip"} if ext in extmap and extmap[ext] != mime: rep.add("gate4", "INFO", "[gate4] warn=ext_mismatch ext=.%s 期望 %s 实判 %s(以 file 为准)" % (ext, extmap[ext], mime)) line = "sha256=%s mime=%s dims=%s bytes=%d" % (sha, mime, dims, size) rep.add("gate4", "INFO", "[gate4] " + line) if mime.startswith("image/") or mime.startswith("video/"): rep.add("gate4", "PASS", "[gate4] verdict=PASS reason=line_emitted") else: rep.add("gate4", "FAIL", "[gate4] verdict=FAIL reason=not_media mime=%s" % mime) # -------------------------------------------------------------------------- # 自测 # -------------------------------------------------------------------------- FONT = { "A": ["01110", "10001", "10001", "11111", "10001", "10001", "10001"], "B": ["11110", "10001", "10001", "11110", "10001", "10001", "11110"], "C": ["01110", "10001", "10000", "10000", "10000", "10001", "01110"], "P": ["11110", "10001", "10001", "11110", "10000", "10000", "10000"], "X": ["10001", "10001", "01010", "00100", "01010", "10001", "10001"], "1": ["00100", "01100", "00100", "00100", "00100", "00100", "01110"], "4": ["00010", "00110", "01010", "10010", "11111", "00010", "00010"], ":": ["00000", "00100", "00100", "00000", "00100", "00100", "00000"], " ": ["00000"] * 7, } def render_text_png(path, text, cap_px, W=640, H=360, margin=40, aa=False, ss=4): """ 用内置 5x7 点阵渲染一行字,缩放倍数取 cap_px/7(必须整除)。 aa=False:硬边(每个点阵像素 = s x s 实心块) aa=True :先在 ss 倍画布上画,再按 ss x ss 盒式降采样——边缘得到真实的 部分覆盖率像素(灰度 = 255*(1-coverage)),复刻「α≈0.5 的笔画像素」 这一层,而不是只测硬边字形。 """ if cap_px % 7 != 0: raise ValueError("cap_px 必须是 7 的倍数") s = cap_px // 7 rects, tw, th = [], 0, 7 * s x = 0 for ch in text: g = FONT.get(ch) if g is None: raise ValueError("字体缺字符: %r" % ch) for ry, row in enumerate(g): for rx, bit in enumerate(row): if bit == "1": rects.append((x + rx * s, ry * s, s, s)) x += 6 * s tw = max(1, x - s) if aa: # 关键:整体偏移半个输出像素,让笔画边缘落在像素中间, # 这样边缘像素才是真实的部分覆盖率(α≈0.5),而不是恰好对齐的硬边。 pad = 1 tw, th = tw + pad, th + pad sw, sh = tw * ss, th * ss off = ss // 2 cov = bytearray(sw * sh) # 0 = 未覆盖, 1 = 覆盖 for (rx0, ry0, rw, rh) in rects: for yy in range(ry0 * ss + off, (ry0 + rh) * ss + off): if yy < 0 or yy >= sh: continue base = yy * sw for xx in range(rx0 * ss + off, (rx0 + rw) * ss + off): if 0 <= xx < sw: cov[base + xx] = 1 tile = bytearray(tw * th) area = ss * ss for oy in range(th): for ox in range(tw): hit = 0 for dy in range(ss): base = (oy * ss + dy) * sw + ox * ss for dx in range(ss): hit += cov[base + dx] tile[oy * tw + ox] = 255 - (255 * hit) // area else: tile = bytearray(b"\xff" * (tw * th)) for (rx0, ry0, rw, rh) in rects: for yy in range(ry0, ry0 + rh): base = yy * tw for xx in range(rx0, rx0 + rw): tile[base + xx] = 0 rgb = bytearray(b"\xff" * (W * H * 3)) ox0 = margin oy0 = (H - th) // 2 for oy in range(th): py = oy0 + oy if py < 0 or py >= H: continue for ox in range(tw): px = ox0 + ox if px < 0 or px >= W: continue v = tile[oy * tw + ox] o = (py * W + px) * 3 rgb[o] = rgb[o + 1] = rgb[o + 2] = v write_png(path, W, H, rgb) return W, H def _tiny_server(routes): """返回 (server, port)。routes: {path: (status, content_type, body)}""" class H(http.server.BaseHTTPRequestHandler): def do_GET(self): # noqa: N802 spec = routes.get(self.path) if spec is None: body = b'{"code":40400,"message":"not found"}' self.send_response(404) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) return status, ctype, body = spec self.send_response(status) self.send_header("Content-Type", ctype) self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) def log_message(self, *a): # noqa: D401 return srv = socketserver.TCPServer(("127.0.0.1", 0), H) srv.daemon_threads = True threading.Thread(target=srv.serve_forever, daemon=True).start() return srv, srv.server_address[1] def selftest(outdir): os.makedirs(outdir, exist_ok=True) import tempfile ws = tempfile.mkdtemp(prefix="pixelgate-selftest-", dir=outdir) me = os.path.abspath(__file__) results = [] def run_cli(args): p = subprocess.run([sys.executable, me] + args, capture_output=True, text=True, timeout=300) return p.returncode, p.stdout, p.stderr def check(case, expect, got, out, note=""): ok = (expect == got) results.append(ok) print("[selftest] case=%-14s expect=%s got=%s -> %s %s" % (case, rc_name(expect), rc_name(got), "PASS" if ok else "FAIL", note)) if not ok: for line in (out or "").strip().splitlines()[-8:]: print("[selftest] | " + line) small = os.path.join(ws, "small14.png") small_aa = os.path.join(ws, "small14_aa.png") large = os.path.join(ws, "large56.png") try: render_text_png(small, "ABC 1:1 14PX", 14, aa=False) render_text_png(small_aa, "ABC 1:1 14PX", 14, aa=True) render_text_png(large, "ABC 1:1", 56, aa=True) except Exception as e: # noqa: BLE001 print("[selftest] FATAL 生成测试图失败: %s" % e) return EXIT_FAIL # ---- case 1:14px 小字(硬边),判据必须先能红 rc, out, err = run_cli(["--image", small, "--out", ws, "--engine", "auto"]) check("small_14px", EXIT_INDET, rc, out) sug = "" for line in out.splitlines(): if "suggested_zoom=" in line: sug = line.split("suggested_zoom=")[1].split()[0] ok = sug.isdigit() and int(sug) >= ZOOM_FLOOR results.append(ok) print("[selftest] expect suggested_zoom>=%d got=%s -> %s" % (ZOOM_FLOOR, sug or "(none)", "PASS" if ok else "FAIL")) # ---- case 1b:14px 小字(4x 超采样,带部分覆盖边缘),仍须红 rc, out, err = run_cli(["--image", small_aa, "--out", ws, "--engine", "auto"]) check("small_14px_aa", EXIT_INDET, rc, out) # ---- case 2:大字号必须能绿,证明判据不是恒红 rc, out, err = run_cli(["--image", large, "--out", ws, "--engine", "auto"]) check("large_56px", EXIT_PASS, rc, out) # ---- case 3/4:双径 # 复刻 AI_Sunny 踩过的形态:HTTP 200 + 72 字节 JSON 错误体(错误码 40400) _prefix = b'{"code":40400,"message":"route suffix not routable","pad":"' err_body = _prefix + b"x" * (72 - len(_prefix) - 2) + b'"}' if len(err_body) != 72: print("[selftest] FATAL 72B 错误体构造失败 len=%d" % len(err_body)) return EXIT_FAIL srv, port = _tiny_server({ "/good.png": (200, "image/png", open(small, "rb").read()), "/err72.json": (200, "application/json", err_body), }) try: a = "http://127.0.0.1:%d/good.png" % port e = "http://127.0.0.1:%d/err72.json" % port rc, out, err = run_cli(["--urlA", a, "--urlB", a, "--out", ws]) check("dual_ok", EXIT_PASS, rc, out) rc, out, err = run_cli(["--urlA", a, "--urlB", e, "--out", ws]) check("dual_json_body", EXIT_FAIL, rc, out) ok = ("first32" in out) and ("bytes=%d" % len(err_body) in out) results.append(bool(ok)) print("[selftest] expect 打印前32字节且字节数=%d got=%s -> %s" % (len(err_body), "yes" if ok else "no", "PASS" if ok else "FAIL")) # ---- case exit_codes:退出码语义三态断言(v1.1 新增) # 防的是「判不了(2)」被下游归并为「判红(1)」:A 输入走存在 FAIL 的 # 路径须退 1,B 输入无 FAIL 但存在 INDETERMINATE 须退 2,两枚退出码 # 互不等值;若实现把 B 倒置/归并成 1,此 case 必红。 try: # A 输入:双径 72B 错误体(存在 FAIL)→ 预期退出码 1 rc_a, out_a, err_a = run_cli(["--urlA", a, "--urlB", e, "--out", ws]) # B 输入:14px 小字定档(无 FAIL,有 INDETERMINATE)→ 预期退出码 2 rc_b, out_b, err_b = run_cli(["--image", small, "--out", ws, "--engine", "auto"]) # 输出行的行数也被记录:INDETERMINATE 路径不得空跑(保证 B 真跑了判据) b_rows = len([l for l in out_b.splitlines() if l.startswith("[gate")]) consts_ok = (EXIT_FAIL != EXIT_INDET) and (EXIT_INDET != EXIT_PASS) collapse_ok = rc_b != rc_a # B 不得归并为 A(1==1 即崩) pair_ok = (rc_a == EXIT_FAIL) and (rc_b == EXIT_INDET) \ and consts_ok and collapse_ok and (b_rows > 0) results.append(bool(pair_ok)) print("[selftest] case=%-14s expect=%s got=%s -> %s %s" % ("exit_codes", "A=FAIL(1) B=INDETERMINATE(2) 且 A!=B", "A=%s B=%s rows=%d" % (rc_name(rc_a), rc_name(rc_b), b_rows), "PASS" if pair_ok else "FAIL", "三态断言")) if not pair_ok: if not consts_ok: print("[selftest] | 常量别名: EXIT_FAIL==EXIT_INDET") if rc_b == rc_a: print("[selftest] | B 被归并进 A 的退出码: %s" % rc_name(rc_a)) except Exception as _ex: # noqa: BLE001 results.append(False) print("[selftest] case=exit_codes FATAL %r -> FAIL" % _ex) finally: srv.shutdown() # ---- case 5:抽帧(有 ffmpeg 才跑,否则 SKIP 不计入) ff = None for p in os.environ.get("PATH", "").split(os.pathsep): if os.path.exists(os.path.join(p, "ffmpeg")): ff = os.path.join(p, "ffmpeg") break if ff: clip = os.path.join(ws, "clip.mp4") gen = subprocess.run([ff, "-hide_banner", "-loglevel", "error", "-y", "-f", "lavfi", "-i", "testsrc=size=320x240:rate=10:duration=3", "-pix_fmt", "yuv420p", clip], capture_output=True, text=True) if gen.returncode == 0 and os.path.exists(clip): rc, out, err = run_cli(["--video", clip, "--at", "1.5", "--out", ws]) check("frame_at_1p5s", EXIT_PASS, rc, out) rc, out, err = run_cli(["--video", clip, "--at", "99", "--out", ws]) check("frame_beyond_end", EXIT_FAIL, rc, out) else: print("[selftest] case=frame SKIP 无法生成测试视频: %s" % (gen.stderr or "")[:200]) else: print("[selftest] case=frame SKIP ffmpeg 不在 PATH") npass = sum(1 for r in results if r) ntot = len(results) print("[selftest] SUMMARY cases=%d pass=%d fail=%d" % (ntot, npass, ntot - npass)) return EXIT_PASS if npass == ntot else EXIT_FAIL # -------------------------------------------------------------------------- # main # -------------------------------------------------------------------------- def parse_crop(s): parts = [int(x) for x in s.replace(" ", "").split(",")] if len(parts) != 4: raise argparse.ArgumentTypeError("--crop 需要 x,y,w,h 四个整数") return tuple(parts) def main(): ap = argparse.ArgumentParser( description="像素门四档自查 v%s(零装包:python3 stdlib + file/ffmpeg)" % VERSION) ap.add_argument("--image", help="gate1/gate1b/gate4 目标图片") ap.add_argument("--min-text-px", type=int, default=0, help="显式声明最小承载信息构件高度,覆盖自动估计") ap.add_argument("--threshold", type=int, default=THRESHOLD_PX, help="1:1 不可判门限,默认 %d" % THRESHOLD_PX) ap.add_argument("--zoom", type=int, default=0, help="gate1b 放大倍数") ap.add_argument("--crop", type=parse_crop, default=None, help="gate1b 裁剪 x,y,w,h") ap.add_argument("--engine", default="auto", choices=["auto", "pil", "stdlib"]) ap.add_argument("--video", help="gate2 源视频") ap.add_argument("--at", type=float, default=0.0, help="gate2 抽帧时间点(秒)") ap.add_argument("--accurate", action="store_true", help="gate2 精确寻帧(-ss 放在 -i 之后,慢)") ap.add_argument("--urlA", help="gate3 直读径") ap.add_argument("--urlB", help="gate3 中继径") ap.add_argument("--timeout", type=float, default=30.0) ap.add_argument("--out", default=".", help="输出目录") ap.add_argument("--self-test", action="store_true") ap.add_argument("--version", action="version", version="pixel_gate %s" % VERSION) args = ap.parse_args() if args.self_test: return selftest(args.out) if not any([args.image, args.video, args.urlA or args.urlB]): ap.print_usage(sys.stderr) print("用法错误:至少给 --image / --video / --urlA+--urlB 之一,或 --self-test", file=sys.stderr) return EXIT_USAGE print("[pixel_gate] v%s python=%s pil=%s" % (VERSION, sys.version.split()[0], have_pil())) rep = Report() if args.image: gate1(rep, args.image, args.min_text_px, args.engine, args.threshold, args.crop) if args.zoom: gate1b(rep, args.image, args.zoom, args.crop, args.engine, args.out) gate4(rep, args.image) if args.video: gate2(rep, args.video, args.at, args.accurate, args.out) if args.urlA or args.urlB: if not (args.urlA and args.urlB): print("用法错误:--urlA 与 --urlB 必须成对给出", file=sys.stderr) return EXIT_USAGE gate3(rep, args.urlA, args.urlB, args.timeout, args.out) c = rep.counts() code = rep.code() print("[pixel_gate] SUMMARY pass=%d fail=%d indet=%d exit=%s" % (c["PASS"], c["FAIL"], c["INDETERMINATE"], rc_name(code))) return code if __name__ == "__main__": sys.exit(main())