Elffuss BraidHub

kikocis/VibeCodeViewer public

main · 6.9 KiB · executableRawPermalink
1#!/usr/bin/env python3
2import argparse
3import json
4from pathlib import Path
5
6import numpy as np
7from PIL import Image, ImageDraw
8
9
10def components(mask):
11 h, w = mask.shape
12 seen = np.zeros_like(mask, dtype=bool)
13 comps = []
14 for y0, x0 in np.argwhere(mask & ~seen):
15 if seen[y0, x0]:
16 continue
17 stack = [(int(y0), int(x0))]
18 seen[y0, x0] = True
19 minx = maxx = int(x0)
20 miny = maxy = int(y0)
21 area = 0
22 while stack:
23 y, x = stack.pop()
24 area += 1
25 minx = min(minx, x)
26 maxx = max(maxx, x)
27 miny = min(miny, y)
28 maxy = max(maxy, y)
29 for ny in (y - 1, y, y + 1):
30 for nx in (x - 1, x, x + 1):
31 if ny == y and nx == x:
32 continue
33 if 0 <= ny < h and 0 <= nx < w and mask[ny, nx] and not seen[ny, nx]:
34 seen[ny, nx] = True
35 stack.append((ny, nx))
36 comps.append((area, minx, miny, maxx + 1, maxy + 1))
37 return comps
38
39
40def rect_sum(ii, x1, y1, x2, y2):
41 return ii[y2, x2] - ii[y1, x2] - ii[y2, x1] + ii[y1, x1]
42
43
44def downsample(mask, factor):
45 h, w = mask.shape
46 h2 = h // factor
47 w2 = w // factor
48 trimmed = mask[: h2 * factor, : w2 * factor]
49 return trimmed.reshape(h2, factor, w2, factor).mean(axis=(1, 3)) > 0.98
50
51
52def detect(path, out_dir=None, threshold=35, scan_windows=False):
53 img = Image.open(path).convert("RGB")
54 arr = np.asarray(img)
55 h, w = arr.shape[:2]
56
57 luminance = arr[:, :, 0] * 0.2126 + arr[:, :, 1] * 0.7152 + arr[:, :, 2] * 0.0722
58 dark = luminance <= threshold
59
60 # Ignore fixed HUD bands enough to keep the detector focused on the WebGL scene.
61 hud = np.zeros((h, w), dtype=bool)
62 hud[: int(h * 0.09), :] = True
63 hud[int(h * 0.92) :, :] = True
64 hud[:, : int(w * 0.08)] = True
65 hud[:, int(w * 0.92) :] = True
66 scene_dark = dark & ~hud
67
68 dark_i = np.pad(scene_dark.astype(np.float32).cumsum(axis=0).cumsum(axis=1), ((1, 0), (1, 0)))
69 lum_i = np.pad(luminance.astype(np.float64).cumsum(axis=0).cumsum(axis=1), ((1, 0), (1, 0)))
70 lum2_i = np.pad((luminance.astype(np.float64) ** 2).cumsum(axis=0).cumsum(axis=1), ((1, 0), (1, 0)))
71 window_hits = []
72 if scan_windows:
73 for wf, hf in ((0.26, 0.22), (0.34, 0.26), (0.42, 0.30)):
74 bw = int(w * wf)
75 bh = int(h * hf)
76 step = max(24, min(bw, bh) // 7)
77 for y1 in range(int(h * 0.16), int(h * 0.82) - bh, step):
78 y2 = y1 + bh
79 if y2 < h * 0.48:
80 continue
81 for x1 in range(int(w * 0.08), int(w * 0.92) - bw, step):
82 x2 = x1 + bw
83 area = bw * bh
84 dark_ratio = rect_sum(dark_i, x1, y1, x2, y2) / area
85 if dark_ratio < 0.985:
86 continue
87 mean = rect_sum(lum_i, x1, y1, x2, y2) / area
88 mean2 = rect_sum(lum2_i, x1, y1, x2, y2) / area
89 std = max(0.0, mean2 - mean * mean) ** 0.5
90 if mean <= threshold * 0.55 and std <= threshold * 0.65:
91 window_hits.append({
92 "bbox": [int(x1), int(y1), int(x2), int(y2)],
93 "area_ratio": round(area / (w * h), 4),
94 "dark_ratio": round(float(dark_ratio), 4),
95 "kind": "dark_window",
96 })
97 break
98 if window_hits:
99 break
100 if window_hits:
101 break
102
103 coarse = downsample(scene_dark, 8)
104 hits = []
105 for area, x1, y1, x2, y2 in components(coarse):
106 x1 *= 8
107 y1 *= 8
108 x2 *= 8
109 y2 *= 8
110 bw = x2 - x1
111 bh = y2 - y1
112 full_area = bw * bh
113 if full_area < w * h * 0.035:
114 continue
115 if bw < w * 0.12 or bh < h * 0.12:
116 continue
117 fill = scene_dark[y1:min(y2, h), x1:min(x2, w)].mean()
118 if fill < 0.97:
119 continue
120 hits.append({
121 "bbox": [x1, y1, min(x2, w), min(y2, h)],
122 "area_ratio": round(full_area / (w * h), 4),
123 "fill": round(float(fill), 4),
124 })
125
126 edge_hits = []
127 win = 18
128 for y in range(int(h * 0.14), int(h * 0.92) - win):
129 above = scene_dark[max(0, y - win):y, :].mean(axis=0) > 0.92
130 below = scene_dark[y:y + win, :].mean(axis=0) < 0.45
131 edge = above & below
132 x = 0
133 while x < w:
134 if not edge[x]:
135 x += 1
136 continue
137 x1 = x
138 while x < w and edge[x]:
139 x += 1
140 x2 = x
141 bw = x2 - x1
142 if bw < w * 0.18 or bw > w * 0.82:
143 continue
144 if x1 < w * 0.08 or x2 > w * 0.92:
145 continue
146 top = y
147 while top > int(h * 0.06) and scene_dark[top - 1, x1:x2].mean() > 0.88:
148 top -= 1
149 bh = y - top
150 if bh < h * 0.18:
151 continue
152 edge_hits.append({
153 "bbox": [int(x1), int(top), int(x2), int(y)],
154 "area_ratio": round((bw * bh) / (w * h), 4),
155 "kind": "lower_edge",
156 })
157
158 if out_dir and hits:
159 out = Path(out_dir)
160 out.mkdir(parents=True, exist_ok=True)
161 overlay = img.copy()
162 d = ImageDraw.Draw(overlay)
163 for hit in hits:
164 d.rectangle(hit["bbox"], outline=(255, 0, 0), width=5)
165 overlay.save(out / f"{Path(path).stem}-black-rect.png")
166
167 all_hits = window_hits + hits + edge_hits
168 if out_dir and edge_hits:
169 out = Path(out_dir)
170 out.mkdir(parents=True, exist_ok=True)
171 overlay = img.copy()
172 d = ImageDraw.Draw(overlay)
173 for hit in all_hits:
174 d.rectangle(hit["bbox"], outline=(255, 0, 0), width=5)
175 overlay.save(out / f"{Path(path).stem}-black-rect.png")
176
177 return {"file": str(path), "hits": all_hits}
178
179
180def main():
181 p = argparse.ArgumentParser()
182 p.add_argument("paths", nargs="+")
183 p.add_argument("--overlay-dir")
184 p.add_argument("--threshold", type=int, default=35)
185 p.add_argument("--scan-windows", action="store_true")
186 args = p.parse_args()
187
188 all_results = []
189 failed = False
190 for raw in args.paths:
191 path = Path(raw)
192 files = sorted(path.glob("*.png")) if path.is_dir() else [path]
193 for f in files:
194 result = detect(f, args.overlay_dir, args.threshold, args.scan_windows)
195 if result["hits"]:
196 failed = True
197 print(json.dumps(result, ensure_ascii=False))
198 all_results.append(result)
199 summary = {
200 "frames": len(all_results),
201 "bad_frames": sum(1 for r in all_results if r["hits"]),
202 }
203 print(json.dumps(summary, ensure_ascii=False))
204 raise SystemExit(1 if failed else 0)
205
206
207if __name__ == "__main__":
208 main()