@snap/valdi 1.0.8 → 1.1.5

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.
Files changed (121) hide show
  1. package/.bootstrap/apps/cli_application/BUILD.bazel.template +7 -0
  2. package/.bootstrap/apps/cli_application/modules/{{MODULE_NAME}}/BUILD.bazel.template +11 -0
  3. package/.bootstrap/apps/cli_application/modules/{{MODULE_NAME}}/src/index.ts +1 -0
  4. package/.bootstrap/apps/ui_application/.eslint.rc +27 -0
  5. package/.bootstrap/apps/ui_application/BUILD.bazel.template +19 -0
  6. package/.bootstrap/apps/ui_application/modules/{{MODULE_NAME}}/BUILD.bazel.template +21 -0
  7. package/.bootstrap/apps/ui_application/modules/{{MODULE_NAME}}/res/valdi@3x.png +0 -0
  8. package/.bootstrap/apps/ui_application/modules/{{MODULE_NAME}}/src/App.tsx +133 -0
  9. package/.bootstrap/apps/ui_application/package.json +24 -0
  10. package/.bootstrap/modules/polyglot_bridge_module/BUILD.bazel.template +54 -0
  11. package/.bootstrap/modules/polyglot_bridge_module/android/CalculatorModuleFactory.kt.template +18 -0
  12. package/.bootstrap/modules/polyglot_bridge_module/ios/SCCCalculatorModuleFactory.m.template +31 -0
  13. package/.bootstrap/modules/polyglot_bridge_module/src/Calculator.d.ts +4 -0
  14. package/.bootstrap/modules/polyglot_bridge_module/web/Calculator.ts +11 -0
  15. package/.bootstrap/modules/polyglot_bridge_module/web/tsconfig.json +16 -0
  16. package/.bootstrap/modules/polyglot_view_module/BUILD.bazel.template +75 -0
  17. package/.bootstrap/modules/polyglot_view_module/android/PolyglotNativeView.kt.template +41 -0
  18. package/.bootstrap/modules/polyglot_view_module/android/PolyglotNativeViewAttributesBinder.kt.template +17 -0
  19. package/.bootstrap/modules/polyglot_view_module/ios/SCPolyglotView.h +8 -0
  20. package/.bootstrap/modules/polyglot_view_module/ios/SCPolyglotView.m +23 -0
  21. package/.bootstrap/modules/polyglot_view_module/macos/SCPolyglotView.h +8 -0
  22. package/.bootstrap/modules/polyglot_view_module/macos/SCPolyglotView.m +23 -0
  23. package/.bootstrap/modules/polyglot_view_module/src/PolyglotCustomView.tsx.template +23 -0
  24. package/.bootstrap/modules/polyglot_view_module/web/PolyglotWeb.ts.template +30 -0
  25. package/.bootstrap/modules/polyglot_view_module/web/tsconfig.json +16 -0
  26. package/.bootstrap/modules/ui_component/BUILD.bazel.template +34 -0
  27. package/.bootstrap/modules/ui_component/src/NewModuleComponent.tsx +45 -0
  28. package/.metadata/.bazelrc.template +92 -0
  29. package/.metadata/.bazelversion.template +1 -0
  30. package/.metadata/.editorconfig.template +37 -0
  31. package/.metadata/.eslintrc.js.template +27 -0
  32. package/.metadata/.gitignore.template +4 -0
  33. package/.metadata/.prettierrc.json.template +7 -0
  34. package/.metadata/.watchmanconfig.template +8 -0
  35. package/.metadata/AGENTS.md.template +16 -0
  36. package/.metadata/MODULE.bazel.template +62 -0
  37. package/.metadata/README.md.template +31 -0
  38. package/.metadata/config.yaml.template +1 -0
  39. package/.metadata/package.json.template +23 -0
  40. package/.metadata/skill-reference.tsx.template +8 -0
  41. package/.metadata/skill-tests-BUILD.bazel.template +21 -0
  42. package/.metadata/skill-tests-README.md.template +17 -0
  43. package/.metadata/skill.md.template +27 -0
  44. package/bundled-skills/registry.json +14 -2
  45. package/bundled-skills/skills/valdi-animations/skill.md +197 -0
  46. package/bundled-skills/skills/valdi-async/tests/src/reference.tsx +1 -1
  47. package/bundled-skills/skills/valdi-bazel/skill.md +21 -2
  48. package/bundled-skills/skills/valdi-component-dedup/skill.md +263 -0
  49. package/bundled-skills/skills/valdi-component-tests/tests/test/ProfileCardTest.spec.tsx +1 -1
  50. package/bundled-skills/skills/valdi-custom-view/skill.md +49 -5
  51. package/bundled-skills/skills/valdi-error-handling/skill.md +238 -0
  52. package/bundled-skills/skills/valdi-gestures/skill.md +198 -0
  53. package/bundled-skills/skills/valdi-inspect/skill.md +217 -0
  54. package/bundled-skills/skills/valdi-localization/skill.md +142 -0
  55. package/bundled-skills/skills/valdi-mock-breakdown/skill.md +327 -0
  56. package/bundled-skills/skills/valdi-mock-iterate/skill.md +216 -0
  57. package/bundled-skills/skills/valdi-mock-to-module/scripts/diff.py +392 -0
  58. package/bundled-skills/skills/valdi-mock-to-module/scripts/extract_colors.py +277 -0
  59. package/bundled-skills/skills/valdi-mock-to-module/scripts/find_icon.py +303 -0
  60. package/bundled-skills/skills/valdi-mock-to-module/scripts/snapshot-and-diff.sh +53 -0
  61. package/bundled-skills/skills/valdi-mock-to-module/scripts/test_diff.py +207 -0
  62. package/bundled-skills/skills/valdi-mock-to-module/scripts/test_extract_colors.py +167 -0
  63. package/bundled-skills/skills/valdi-mock-to-module/scripts/test_find_icon.py +188 -0
  64. package/bundled-skills/skills/valdi-mock-to-module/scripts/watch-and-diff.sh +181 -0
  65. package/bundled-skills/skills/valdi-mock-to-module/skill.md +451 -0
  66. package/bundled-skills/skills/valdi-navigation/skill.md +187 -0
  67. package/bundled-skills/skills/valdi-overview/skill.md +7 -4
  68. package/bundled-skills/skills/valdi-perf/skill.md +223 -0
  69. package/bundled-skills/skills/valdi-polyglot-module/skill.md +131 -12
  70. package/bundled-skills/skills/valdi-preview/skill.md +303 -0
  71. package/bundled-skills/skills/valdi-profile/skill.md +126 -0
  72. package/bundled-skills/skills/valdi-setup/skill.md +55 -5
  73. package/bundled-skills/skills/valdi-testing/skill.md +23 -7
  74. package/bundled-skills/skills/valdi-tsx/skill.md +69 -5
  75. package/bundled-skills/skills/valdi-tsx/tests/src/reference.tsx +29 -5
  76. package/dist/commands/agentCheck.js +184 -0
  77. package/dist/commands/analyze.js +16 -0
  78. package/dist/commands/analyze_commands/duplicates.js +134 -0
  79. package/dist/commands/bootstrap.js +57 -73
  80. package/dist/commands/doctor.js +40 -203
  81. package/dist/commands/hotreload.js +15 -0
  82. package/dist/commands/inspect.js +16 -0
  83. package/dist/commands/inspect_commands/contexts.js +55 -0
  84. package/dist/commands/inspect_commands/devices.js +53 -0
  85. package/dist/commands/inspect_commands/heap.js +59 -0
  86. package/dist/commands/inspect_commands/select.js +43 -0
  87. package/dist/commands/inspect_commands/snapshot.js +129 -0
  88. package/dist/commands/inspect_commands/snapshot.spec.js +105 -0
  89. package/dist/commands/inspect_commands/status.js +68 -0
  90. package/dist/commands/inspect_commands/tree.js +86 -0
  91. package/dist/commands/preview.js +81 -0
  92. package/dist/commands/profile.js +16 -0
  93. package/dist/commands/profile_commands/capture.js +106 -0
  94. package/dist/commands/projectsync.js +9 -7
  95. package/dist/commands/skills_commands/install.js +6 -1
  96. package/dist/commands/skills_commands/update.js +2 -1
  97. package/dist/core/analyze/clusterer.js +150 -0
  98. package/dist/core/analyze/fingerprint.js +2 -0
  99. package/dist/core/analyze/knownPatterns.js +76 -0
  100. package/dist/core/analyze/parser.js +177 -0
  101. package/dist/core/analyze/reporter.js +83 -0
  102. package/dist/core/analyze/scanner.js +172 -0
  103. package/dist/core/analyze/similarity.js +56 -0
  104. package/dist/core/constants.js +1 -1
  105. package/dist/core/packageFiles.spec.js +29 -0
  106. package/dist/preview/previewGenerator.js +240 -0
  107. package/dist/preview/previewGenerator.spec.js +203 -0
  108. package/dist/preview/viewModelParser.js +86 -0
  109. package/dist/preview/viewModelParser.spec.js +171 -0
  110. package/dist/setup/DevSetupHelper.js +0 -51
  111. package/dist/setup/linuxSetup.js +0 -2
  112. package/dist/setup/macOSSetup.js +1 -4
  113. package/dist/utils/BazelClient.js +15 -0
  114. package/dist/utils/daemonClient.js +344 -0
  115. package/dist/utils/hermesClient.js +252 -0
  116. package/dist/utils/skillsAdapters.js +86 -5
  117. package/dist/utils/skillsAdapters.spec.js +60 -0
  118. package/dist/utils/skillsRegistry.js +8 -0
  119. package/dist/utils/stringUtils.spec.js +1 -1
  120. package/package.json +30 -12
  121. package/dist/setup/versions.js +0 -8
@@ -0,0 +1,392 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ Generate a pixel diff between a design mock and a Valdi render snapshot,
4
+ including shadow detection, region masking, and per-segment breakdown.
5
+
6
+ Usage:
7
+ python3 diff.py <mock_path> <render_path> [--output <output_path>]
8
+
9
+ # Mask thumbnail regions (exclude photos from diff)
10
+ python3 diff.py mock.png render.png --mask "10,5,35,35" "10,50,35,35"
11
+
12
+ # Per-region breakdown (find which section of the screen needs work)
13
+ python3 diff.py mock.png render.png --segments 4
14
+
15
+ Produces a side-by-side image: mock | render | amplified diff | shadow diff
16
+ - Panel 3 (amplified diff): bright pixels = color/content mismatches
17
+ - Panel 4 (shadow diff): blue = shadows present in mock but missing in render
18
+ """
19
+
20
+ import argparse
21
+ import os
22
+ import sys
23
+
24
+ try:
25
+ from PIL import Image, ImageChops, ImageEnhance, ImageFilter
26
+ except ImportError:
27
+ print("Pillow not installed. Run: pip3 install Pillow", file=sys.stderr)
28
+ sys.exit(1)
29
+
30
+
31
+ def _crop_to_phone_frame(render: Image.Image) -> Image.Image:
32
+ """
33
+ Crop the desktop render to just the phone frame column.
34
+
35
+ The PreviewRoot centers a white 390px phone frame on a #333 background.
36
+ Scan the middle row for the white content region and crop to it.
37
+ Falls back to the full image if no frame is detected.
38
+ """
39
+ render_rgb = render.convert("RGB")
40
+ mid_y = render.height // 2
41
+ row = [render_rgb.getpixel((x, mid_y)) for x in range(render.width)]
42
+
43
+ # The phone frame background is white (#FFFFFF); the outer bg is #333.
44
+ # Find the leftmost and rightmost bright columns.
45
+ bg_threshold = 100 # below this = dark background
46
+ left = None
47
+ right = None
48
+ for x, (r, g, b) in enumerate(row):
49
+ if r > bg_threshold and g > bg_threshold and b > bg_threshold:
50
+ if left is None:
51
+ left = x
52
+ right = x
53
+
54
+ if left is not None and right is not None and (right - left) > 50:
55
+ # Add small padding so we don't clip shadow edges
56
+ pad = 4
57
+ left = max(0, left - pad)
58
+ right = min(render.width, right + pad)
59
+ return render.crop((left, 0, right, render.height))
60
+
61
+ # Fallback: no phone frame detected, return full image
62
+ return render
63
+
64
+
65
+ def detect_missing_shadows(mock_rgb: Image.Image, render_rgb: Image.Image):
66
+ """
67
+ Detect shadow regions present in the mock but missing in the render.
68
+
69
+ Shadows are soft, low-frequency luminance drops near element edges.
70
+ Strategy:
71
+ 1. Convert both to grayscale.
72
+ 2. Heavy blur to isolate low-frequency luminance (shadow shapes).
73
+ 3. Detect edges in the un-blurred image (element boundaries).
74
+ 4. Dilate edges to create a "near-edge" zone where shadows live.
75
+ 5. In that zone, find where mock is notably darker than render
76
+ (mock has shadow, render doesn't).
77
+ 6. Return a visualization image and count of shadow pixels.
78
+ """
79
+ mock_gray = mock_rgb.convert("L")
80
+ render_gray = render_rgb.convert("L")
81
+
82
+ # Step 1: Heavy blur to extract the low-frequency (shadow) component.
83
+ # Shadows are gradual darkening, not sharp detail.
84
+ blur_radius = 8
85
+ mock_blurred = mock_gray.filter(ImageFilter.GaussianBlur(radius=blur_radius))
86
+ render_blurred = render_gray.filter(ImageFilter.GaussianBlur(radius=blur_radius))
87
+
88
+ # Step 2: Find element edges in the render (these are where shadows should appear).
89
+ # Use a lighter blur + edge detection to find element boundaries.
90
+ render_edges = render_gray.filter(ImageFilter.GaussianBlur(radius=1))
91
+ render_edges = render_edges.filter(ImageFilter.FIND_EDGES)
92
+
93
+ # Step 3: Dilate edges to create a "shadow zone" — the area near edges
94
+ # where we'd expect drop shadows to appear (below/right of elements).
95
+ # MaxFilter expands bright regions, effectively dilating the edge map.
96
+ shadow_zone = render_edges.filter(ImageFilter.MaxFilter(size=11))
97
+ # Also do the same from mock edges to catch elements that only exist in mock
98
+ mock_edges = mock_gray.filter(ImageFilter.GaussianBlur(radius=1))
99
+ mock_edges = mock_edges.filter(ImageFilter.FIND_EDGES)
100
+ mock_zone = mock_edges.filter(ImageFilter.MaxFilter(size=11))
101
+
102
+ # Combine both edge zones
103
+ shadow_zone_bytes = list(shadow_zone.tobytes())
104
+ mock_zone_bytes = list(mock_zone.tobytes())
105
+ combined_zone = bytes(max(a, b) for a, b in zip(shadow_zone_bytes, mock_zone_bytes))
106
+ shadow_zone = Image.frombytes("L", render_gray.size, combined_zone)
107
+
108
+ # Step 4: Compare blurred luminance. Where mock is darker than render
109
+ # near edges = shadow present in mock but missing in render.
110
+ mock_blur_bytes = list(mock_blurred.tobytes())
111
+ render_blur_bytes = list(render_blurred.tobytes())
112
+ zone_bytes = list(shadow_zone.tobytes())
113
+
114
+ # Thresholds — tuned to avoid false positives from content/color differences.
115
+ # Only flag genuine shadow gradients: soft darkening near hard edges.
116
+ darkness_threshold = 25 # mock must be at least this much darker than render
117
+ edge_threshold = 30 # minimum edge strength to consider "near an edge"
118
+
119
+ shadow_pixels = []
120
+ missing_count = 0
121
+ for i in range(len(mock_blur_bytes)):
122
+ mock_val = mock_blur_bytes[i]
123
+ render_val = render_blur_bytes[i]
124
+ near_edge = zone_bytes[i] > edge_threshold
125
+
126
+ # Mock is darker than render near an edge = missing shadow
127
+ darkness_diff = render_val - mock_val # positive = mock is darker
128
+ if near_edge and darkness_diff > darkness_threshold:
129
+ # Intensity proportional to how much shadow is missing
130
+ intensity = min(255, darkness_diff * 3)
131
+ shadow_pixels.append((0, intensity // 3, intensity)) # blue tint
132
+ missing_count += 1
133
+ else:
134
+ shadow_pixels.append((0, 0, 0))
135
+
136
+ # Build the shadow diff visualization
137
+ shadow_img = Image.new("RGB", render_rgb.size)
138
+ shadow_img.putdata(shadow_pixels)
139
+
140
+ # Overlay faintly on the render so you can see WHERE shadows are missing
141
+ render_dim = ImageEnhance.Brightness(render_rgb).enhance(0.4)
142
+ overlay = ImageChops.add(render_dim, shadow_img)
143
+
144
+ total_pixels = len(mock_blur_bytes)
145
+ shadow_pct = round(100 * missing_count / total_pixels, 1) if total_pixels > 0 else 0
146
+
147
+ return overlay, missing_count, shadow_pct
148
+
149
+
150
+ def _resolve_macos_path(path: str) -> str:
151
+ """Handle macOS screenshot filenames with Unicode narrow no-break space (U+202F)."""
152
+ if os.path.exists(path):
153
+ return path
154
+ # macOS uses U+202F (narrow no-break space) between time and AM/PM in screenshot filenames
155
+ for marker in (' AM', ' PM'):
156
+ fixed = path.replace(marker, '\u202f' + marker[1:])
157
+ if os.path.exists(fixed):
158
+ return fixed
159
+ return path
160
+
161
+
162
+ def _auto_detect_masks(img: Image.Image) -> list[tuple[int, int, int, int]]:
163
+ """
164
+ Auto-detect thumbnail/avatar regions in the left column of a resized image.
165
+ Scans for rectangular non-white blocks. Returns list of (x, y, w, h).
166
+ """
167
+ w, h = img.size
168
+ img_rgb = img.convert("RGB")
169
+ # Scan at ~11% from left (typical thumbnail center column)
170
+ scan_x = int(w * 0.11)
171
+ threshold = 230
172
+
173
+ # Find vertical segments of non-white pixels
174
+ segments = []
175
+ in_thumb = False
176
+ start_y = 0
177
+ for y in range(h):
178
+ r, g, b = img_rgb.getpixel((scan_x, y))
179
+ is_content = r < threshold or g < threshold or b < threshold
180
+ if is_content and not in_thumb:
181
+ start_y = y
182
+ in_thumb = True
183
+ elif not is_content and in_thumb:
184
+ seg_h = y - start_y
185
+ if seg_h > 10: # minimum thumbnail height in resized image
186
+ segments.append((start_y, y))
187
+ in_thumb = False
188
+ if in_thumb and (h - start_y) > 10:
189
+ segments.append((start_y, h))
190
+
191
+ # Find horizontal extent for each segment
192
+ results = []
193
+ for y_start, y_end in segments:
194
+ mid_y = (y_start + y_end) // 2
195
+ left = None
196
+ right = None
197
+ for x in range(0, w // 3):
198
+ r, g, b = img_rgb.getpixel((x, mid_y))
199
+ if r < threshold or g < threshold or b < threshold:
200
+ if left is None:
201
+ left = x
202
+ right = x
203
+ if left is not None and right is not None:
204
+ thumb_w = right - left + 1
205
+ thumb_h = y_end - y_start
206
+ # Small padding around the detected region
207
+ pad = 2
208
+ results.append((max(0, left - pad), max(0, y_start - pad),
209
+ thumb_w + pad * 2, thumb_h + pad * 2))
210
+
211
+ return results
212
+
213
+
214
+ def _apply_masks(img: Image.Image, mask_regions: list[tuple[int, int, int, int]], fill=(128, 128, 128)) -> Image.Image:
215
+ """Black out specified rectangular regions. Coordinates are in the final (resized) image space."""
216
+ masked = img.copy()
217
+ for x, y, w, h in mask_regions:
218
+ for py in range(max(0, y), min(y + h, masked.height)):
219
+ for px in range(max(0, x), min(x + w, masked.width)):
220
+ masked.putpixel((px, py), fill)
221
+ return masked
222
+
223
+
224
+ def _segment_match(diff: Image.Image, num_segments: int = 4, threshold: int = 30) -> list[tuple[str, float]]:
225
+ """
226
+ Segment the diff image into horizontal bands and compute per-segment match %.
227
+ Returns list of (label, match_pct) for each segment.
228
+ """
229
+ h = diff.height
230
+ seg_h = h // num_segments
231
+ results = []
232
+
233
+ for i in range(num_segments):
234
+ y_start = i * seg_h
235
+ y_end = (i + 1) * seg_h if i < num_segments - 1 else h
236
+ region = diff.crop((0, y_start, diff.width, y_end))
237
+ region_bytes = list(region.convert("RGB").tobytes())
238
+ pixels = [(region_bytes[j], region_bytes[j+1], region_bytes[j+2])
239
+ for j in range(0, len(region_bytes), 3)]
240
+ matching = sum(1 for r, g, b in pixels if r < threshold and g < threshold and b < threshold)
241
+ pct = round(100 * matching / len(pixels), 1) if pixels else 0
242
+ # Label by vertical position
243
+ frac_start = round(100 * y_start / h)
244
+ frac_end = round(100 * y_end / h)
245
+ label = f"rows {frac_start}-{frac_end}%"
246
+ results.append((label, pct))
247
+
248
+ return results
249
+
250
+
251
+ def generate_diff(mock_path: str, render_path: str, output_path: str, width: int = 400,
252
+ mask_regions: list[tuple[int, int, int, int]] | None = None,
253
+ auto_mask: bool = False,
254
+ num_segments: int = 0):
255
+ mock = Image.open(_resolve_macos_path(mock_path))
256
+ render = Image.open(_resolve_macos_path(render_path))
257
+
258
+ # Crop mock: remove phone status bar and bottom border/nav.
259
+ # 7% top and 5% bottom crops the phone chrome more aggressively,
260
+ # producing better aspect ratio alignment with pure-content renders.
261
+ status_bar = int(mock.height * 0.07)
262
+ bottom_nav = int(mock.height * 0.05)
263
+ mock_cropped = mock.crop((0, status_bar, mock.width, mock.height - bottom_nav))
264
+
265
+ # Crop render to the phone frame column. The PreviewRoot uses a 390px-wide
266
+ # phone frame centered in the window. Extract just that strip so the aspect
267
+ # ratios match the phone mock instead of the desktop window.
268
+ render_cropped = _crop_to_phone_frame(render)
269
+
270
+ # Use the mock's aspect ratio as ground truth
271
+ target_h = int(width * mock_cropped.height / mock_cropped.width)
272
+ mock_resized = mock_cropped.resize((width, target_h), Image.LANCZOS).convert("RGB")
273
+ render_resized = render_cropped.resize((width, target_h), Image.LANCZOS).convert("RGB")
274
+
275
+ mock_rgb = mock_resized.copy()
276
+ render_rgb = render_resized.copy()
277
+
278
+ # Auto-detect thumbnail masks from the resized mock if requested
279
+ if auto_mask:
280
+ detected = _auto_detect_masks(mock_resized)
281
+ if detected:
282
+ if mask_regions is None:
283
+ mask_regions = []
284
+ mask_regions.extend(detected)
285
+ print(f"Auto-detected {len(detected)} mask region(s): {detected}")
286
+
287
+ # Apply masks to exclude known-image regions (e.g., photo thumbnails)
288
+ mock_for_diff = mock_rgb
289
+ render_for_diff = render_rgb
290
+ if mask_regions:
291
+ mock_for_diff = _apply_masks(mock_rgb, mask_regions)
292
+ render_for_diff = _apply_masks(render_rgb, mask_regions)
293
+
294
+ # Pixel diff, amplified 4x for visibility
295
+ diff = ImageChops.difference(mock_for_diff, render_for_diff)
296
+ diff_bright = ImageEnhance.Brightness(diff).enhance(4.0)
297
+
298
+ # Shadow detection (on unmasked images — shadows matter everywhere)
299
+ shadow_overlay, shadow_count, shadow_pct = detect_missing_shadows(mock_rgb, render_rgb)
300
+
301
+ # Draw mask overlays on all panels so it's clear what's excluded
302
+ if mask_regions:
303
+ for panel_img in [mock_resized, render_resized, diff_bright]:
304
+ for mx, my, mw, mh in mask_regions:
305
+ for py in range(max(0, my), min(my + mh, panel_img.height)):
306
+ for px in range(max(0, mx), min(mx + mw, panel_img.width)):
307
+ # Semi-transparent red tint to mark masked areas
308
+ orig = panel_img.getpixel((px, py))
309
+ blended = (
310
+ min(255, orig[0] // 2 + 100),
311
+ orig[1] // 3,
312
+ orig[2] // 3,
313
+ )
314
+ panel_img.putpixel((px, py), blended)
315
+ # Draw border around masked region
316
+ for px in range(max(0, mx), min(mx + mw, panel_img.width)):
317
+ for edge_y in [my, my + mh - 1]:
318
+ if 0 <= edge_y < panel_img.height:
319
+ panel_img.putpixel((px, edge_y), (255, 0, 0))
320
+ for py in range(max(0, my), min(my + mh, panel_img.height)):
321
+ for edge_x in [mx, mx + mw - 1]:
322
+ if 0 <= edge_x < panel_img.width:
323
+ panel_img.putpixel((edge_x, py), (255, 0, 0))
324
+
325
+ # Side-by-side: mock | render | amplified diff | shadow diff
326
+ gap = 6
327
+ total_w = width * 4 + gap * 3
328
+ canvas = Image.new("RGB", (total_w, target_h), (50, 50, 50))
329
+ canvas.paste(mock_resized, (0, 0))
330
+ canvas.paste(render_resized, (width + gap, 0))
331
+ canvas.paste(diff_bright, (width * 2 + gap * 2, 0))
332
+ canvas.paste(shadow_overlay, (width * 3 + gap * 3, 0))
333
+ canvas.save(output_path)
334
+
335
+ # Match percentage (% of pixels with diff < threshold)
336
+ diff_bytes = list(diff.convert("RGB").tobytes())
337
+ diff_pixels = [(diff_bytes[i], diff_bytes[i+1], diff_bytes[i+2]) for i in range(0, len(diff_bytes), 3)]
338
+ threshold = 30 # per-channel tolerance
339
+ matching = sum(1 for r, g, b in diff_pixels if r < threshold and g < threshold and b < threshold)
340
+ total = len(diff_pixels)
341
+ match_pct = round(100 * matching / total, 1)
342
+
343
+ print(f"Diff saved: {output_path}")
344
+ print(f"Match: {match_pct}% pixels within threshold ({threshold}/255 per channel)")
345
+ if mask_regions:
346
+ # Also compute unmasked match for reference
347
+ raw_diff = ImageChops.difference(mock_rgb, render_rgb)
348
+ raw_bytes = list(raw_diff.convert("RGB").tobytes())
349
+ raw_pixels = [(raw_bytes[j], raw_bytes[j+1], raw_bytes[j+2]) for j in range(0, len(raw_bytes), 3)]
350
+ raw_matching = sum(1 for r, g, b in raw_pixels if r < threshold and g < threshold and b < threshold)
351
+ raw_pct = round(100 * raw_matching / len(raw_pixels), 1)
352
+ print(f"Match (unmasked): {raw_pct}% — masked {len(mask_regions)} region(s)")
353
+ print(f"Shadows: {shadow_pct}% of pixels have missing shadows ({shadow_count} pixels)")
354
+
355
+ # Per-region segmented diff
356
+ if num_segments > 0:
357
+ segments = _segment_match(diff, num_segments, threshold)
358
+ print(f"\nPer-region breakdown ({num_segments} segments):")
359
+ for label, pct in segments:
360
+ bar = '█' * int(pct / 5) + '░' * (20 - int(pct / 5))
361
+ print(f" {label:15s} {bar} {pct}%")
362
+
363
+ print(f"Mock: {mock.size} -> {mock_resized.size}, Render: {render.size} -> {render_resized.size}")
364
+ return match_pct
365
+
366
+
367
+ def _parse_mask_region(spec: str) -> tuple[int, int, int, int]:
368
+ """Parse 'x,y,w,h' into a tuple."""
369
+ parts = spec.split(',')
370
+ if len(parts) != 4:
371
+ raise ValueError(f"Mask region must be x,y,w,h — got: {spec}")
372
+ return tuple(int(p) for p in parts)
373
+
374
+
375
+ if __name__ == "__main__":
376
+ parser = argparse.ArgumentParser(description="Pixel diff: mock vs Valdi render")
377
+ parser.add_argument("mock", help="Path to the design mock image")
378
+ parser.add_argument("render", help="Path to the rendered snapshot")
379
+ parser.add_argument("--output", "-o", default="/tmp/mock-vs-render-diff.png", help="Output diff image path")
380
+ parser.add_argument("--width", "-w", type=int, default=400, help="Target comparison width in pixels")
381
+ parser.add_argument("--mask", nargs="*", default=[],
382
+ help='Regions to exclude from diff: "x,y,w,h" (in resized image coords)')
383
+ parser.add_argument("--auto-mask", action="store_true",
384
+ help="Auto-detect thumbnail/avatar regions in the mock and mask them")
385
+ parser.add_argument("--segments", "-s", type=int, default=0,
386
+ help="Number of horizontal segments for per-region breakdown (0=disabled)")
387
+ args = parser.parse_args()
388
+
389
+ masks = [_parse_mask_region(m) for m in args.mask] if args.mask else None
390
+
391
+ generate_diff(args.mock, args.render, args.output, args.width,
392
+ mask_regions=masks, auto_mask=args.auto_mask, num_segments=args.segments)
@@ -0,0 +1,277 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ Extract dominant colors from regions of a mock image using k-means clustering.
4
+
5
+ Usage:
6
+ # Auto-detect thumbnail regions in a list UI
7
+ python3 extract_colors.py <mock_path> --auto-thumbnails
8
+
9
+ # Extract from specific bounding boxes (x,y,w,h)
10
+ python3 extract_colors.py <mock_path> --regions "dodgers:45,50,70,70" "larams:45,145,70,70"
11
+
12
+ # Extract UI element colors by clicking coordinates
13
+ python3 extract_colors.py <mock_path> --sample "live_badge:230,135" "green_dot:90,360"
14
+ """
15
+
16
+ import argparse
17
+ import os
18
+ import sys
19
+
20
+ try:
21
+ from PIL import Image
22
+ except ImportError:
23
+ print("Pillow not installed. Run: pip3 install Pillow", file=sys.stderr)
24
+ sys.exit(1)
25
+
26
+
27
+ def _resolve_macos_path(path: str) -> str:
28
+ """Handle macOS screenshot filenames with Unicode narrow no-break space (U+202F)."""
29
+ if os.path.exists(path):
30
+ return path
31
+ for marker in (' AM', ' PM'):
32
+ fixed = path.replace(marker, '\u202f' + marker[1:])
33
+ if os.path.exists(fixed):
34
+ return fixed
35
+ return path
36
+
37
+
38
+ def dominant_color_kmeans(pixels: list[tuple[int, int, int]], k: int = 3) -> str:
39
+ """
40
+ Find the dominant color using a simple k-means implementation.
41
+ Returns the hex color of the largest cluster, preferring saturated colors.
42
+ No numpy/scipy dependency.
43
+ """
44
+ if not pixels:
45
+ return '#000000'
46
+
47
+ if len(pixels) < k:
48
+ r = sum(p[0] for p in pixels) // len(pixels)
49
+ g = sum(p[1] for p in pixels) // len(pixels)
50
+ b = sum(p[2] for p in pixels) // len(pixels)
51
+ return f'#{r:02X}{g:02X}{b:02X}'
52
+
53
+ # Initialize centroids by spreading across the pixel range
54
+ import random
55
+ random.seed(42)
56
+ centroids = random.sample(pixels, k)
57
+
58
+ for _ in range(20): # iterations
59
+ clusters: list[list[tuple[int, int, int]]] = [[] for _ in range(k)]
60
+
61
+ for p in pixels:
62
+ dists = [sum((p[c] - centroids[i][c]) ** 2 for c in range(3)) for i in range(k)]
63
+ clusters[dists.index(min(dists))].append(p)
64
+
65
+ new_centroids = []
66
+ for cluster in clusters:
67
+ if cluster:
68
+ r = sum(p[0] for p in cluster) // len(cluster)
69
+ g = sum(p[1] for p in cluster) // len(cluster)
70
+ b = sum(p[2] for p in cluster) // len(cluster)
71
+ new_centroids.append((r, g, b))
72
+ else:
73
+ new_centroids.append(random.choice(pixels))
74
+
75
+ if new_centroids == centroids:
76
+ break
77
+ centroids = new_centroids
78
+
79
+ # Score each cluster: prefer larger + more saturated
80
+ best = None
81
+ best_score = -1
82
+ for i, cluster in enumerate(clusters):
83
+ if not cluster:
84
+ continue
85
+ r, g, b = centroids[i]
86
+ # Saturation = how far from gray
87
+ mean_val = (r + g + b) / 3
88
+ saturation = (abs(r - mean_val) + abs(g - mean_val) + abs(b - mean_val)) / 3
89
+ # Score = size * (1 + saturation bonus)
90
+ score = len(cluster) * (1 + saturation / 128)
91
+ # Penalty for near-white and near-black (these are usually background)
92
+ if mean_val > 240 or mean_val < 15:
93
+ score *= 0.1
94
+ if score > best_score:
95
+ best_score = score
96
+ best = centroids[i]
97
+
98
+ if best is None:
99
+ best = centroids[0]
100
+ return f'#{best[0]:02X}{best[1]:02X}{best[2]:02X}'
101
+
102
+
103
+ def sample_point(img: Image.Image, x: int, y: int, radius: int = 3) -> str:
104
+ """Sample a small area around a point and return the median color."""
105
+ colors = []
106
+ w, h = img.size
107
+ for dy in range(-radius, radius + 1):
108
+ for dx in range(-radius, radius + 1):
109
+ px = max(0, min(x + dx, w - 1))
110
+ py = max(0, min(y + dy, h - 1))
111
+ colors.append(img.getpixel((px, py)))
112
+ colors.sort(key=lambda c: c[0] + c[1] + c[2])
113
+ mid = colors[len(colors) // 2]
114
+ return f'#{mid[0]:02X}{mid[1]:02X}{mid[2]:02X}'
115
+
116
+
117
+ def extract_region(img: Image.Image, x: int, y: int, w: int, h: int) -> str:
118
+ """Extract dominant color from a rectangular region."""
119
+ pixels = []
120
+ img_w, img_h = img.size
121
+ for py in range(max(0, y), min(y + h, img_h)):
122
+ for px in range(max(0, x), min(x + w, img_w)):
123
+ pixels.append(img.getpixel((px, py)))
124
+ return dominant_color_kmeans(pixels)
125
+
126
+
127
+ def auto_detect_thumbnails(img: Image.Image) -> list[tuple[str, int, int, int, int]]:
128
+ """
129
+ Auto-detect thumbnail regions in a list UI.
130
+ Scans for rectangular non-white blocks in the left column.
131
+ Returns list of (name, x, y, w, h).
132
+ """
133
+ w, h = img.size
134
+ # Scan vertical center of typical thumbnail column (x=50-90 range)
135
+ scan_x = int(w * 0.11) # ~11% from left
136
+
137
+ # Find vertical segments of non-white pixels
138
+ segments = []
139
+ in_thumb = False
140
+ start_y = 0
141
+ threshold = 230
142
+
143
+ for y in range(0, h):
144
+ r, g, b = img.getpixel((scan_x, y))
145
+ is_content = r < threshold or g < threshold or b < threshold
146
+
147
+ if is_content and not in_thumb:
148
+ start_y = y
149
+ in_thumb = True
150
+ elif not is_content and in_thumb:
151
+ seg_h = y - start_y
152
+ if seg_h > 20: # minimum thumbnail height
153
+ segments.append((start_y, y))
154
+ in_thumb = False
155
+
156
+ if in_thumb:
157
+ segments.append((start_y, h))
158
+
159
+ # Now find horizontal extent for each segment
160
+ results = []
161
+ for idx, (y_start, y_end) in enumerate(segments):
162
+ mid_y = (y_start + y_end) // 2
163
+ # Scan horizontally to find left and right edges
164
+ left = None
165
+ right = None
166
+ for x in range(0, w // 3):
167
+ r, g, b = img.getpixel((x, mid_y))
168
+ if r < threshold or g < threshold or b < threshold:
169
+ if left is None:
170
+ left = x
171
+ right = x
172
+
173
+ if left is not None and right is not None:
174
+ thumb_w = right - left + 1
175
+ thumb_h = y_end - y_start
176
+ results.append((f'thumb_{idx}', left, y_start, thumb_w, thumb_h))
177
+
178
+ return results
179
+
180
+
181
+ def auto_detect_colored_regions(img: Image.Image) -> list[tuple[str, int, int, int, int]]:
182
+ """
183
+ Auto-detect ALL saturated/colored regions in the image (buttons, badges, icons).
184
+ Scans the entire image for clusters of non-white, non-black, saturated pixels.
185
+ Returns list of (name, x, y, w, h).
186
+ """
187
+ w, h = img.size
188
+ threshold_sat = 25 # minimum saturation to be "colored"
189
+ step = 3
190
+
191
+ # Find all saturated pixels
192
+ colored_pixels = []
193
+ for y in range(0, h, step):
194
+ for x in range(0, w, step):
195
+ r, g, b = img.getpixel((x, y))
196
+ mean = (r + g + b) / 3
197
+ sat = max(abs(r - mean), abs(g - mean), abs(b - mean))
198
+ if sat > threshold_sat and 20 < mean < 245:
199
+ colored_pixels.append((x, y))
200
+
201
+ if not colored_pixels:
202
+ return []
203
+
204
+ # Simple flood-fill clustering: group nearby pixels
205
+ clusters: list[list[tuple[int, int]]] = []
206
+ used = set()
207
+ for px, py in colored_pixels:
208
+ if (px, py) in used:
209
+ continue
210
+ # BFS to find connected colored pixels
211
+ cluster = [(px, py)]
212
+ queue = [(px, py)]
213
+ used.add((px, py))
214
+ while queue:
215
+ cx, cy = queue.pop(0)
216
+ for nx, ny in colored_pixels:
217
+ if (nx, ny) not in used and abs(nx - cx) <= step * 2 and abs(ny - cy) <= step * 2:
218
+ used.add((nx, ny))
219
+ cluster.append((nx, ny))
220
+ queue.append((nx, ny))
221
+ if len(cluster) >= 3: # minimum cluster size
222
+ clusters.append(cluster)
223
+
224
+ results = []
225
+ for idx, cluster in enumerate(clusters):
226
+ xs = [p[0] for p in cluster]
227
+ ys = [p[1] for p in cluster]
228
+ x_min, x_max = min(xs), max(xs)
229
+ y_min, y_max = min(ys), max(ys)
230
+ cw = x_max - x_min + step
231
+ ch = y_max - y_min + step
232
+ results.append((f'region_{idx}', x_min, y_min, cw, ch))
233
+
234
+ return results
235
+
236
+
237
+ if __name__ == '__main__':
238
+ parser = argparse.ArgumentParser(description='Extract colors from a mock image')
239
+ parser.add_argument('mock', help='Path to mock image')
240
+ parser.add_argument('--auto-thumbnails', action='store_true',
241
+ help='Auto-detect thumbnail regions')
242
+ parser.add_argument('--auto-colors', action='store_true',
243
+ help='Auto-detect ALL colored regions (buttons, badges, icons)')
244
+ parser.add_argument('--regions', nargs='*', default=[],
245
+ help='Named regions: "name:x,y,w,h"')
246
+ parser.add_argument('--sample', nargs='*', default=[],
247
+ help='Sample points: "name:x,y"')
248
+ args = parser.parse_args()
249
+
250
+ img = Image.open(_resolve_macos_path(args.mock)).convert('RGB')
251
+ print(f'Image: {img.size[0]}x{img.size[1]}')
252
+
253
+ if args.auto_thumbnails:
254
+ print('\n--- Auto-detected thumbnails ---')
255
+ thumbs = auto_detect_thumbnails(img)
256
+ for name, x, y, tw, th in thumbs:
257
+ color = extract_region(img, x, y, tw, th)
258
+ print(f" {name:25s} {color} ({x},{y},{tw}x{th})")
259
+
260
+ if args.auto_colors:
261
+ print('\n--- Auto-detected colored regions ---')
262
+ regions = auto_detect_colored_regions(img)
263
+ for name, x, y, rw, rh in regions:
264
+ color = extract_region(img, x, y, rw, rh)
265
+ print(f" {name:25s} {color} ({x},{y},{rw}x{rh})")
266
+
267
+ for region_spec in args.regions:
268
+ name, coords = region_spec.split(':')
269
+ x, y, rw, rh = map(int, coords.split(','))
270
+ color = extract_region(img, x, y, rw, rh)
271
+ print(f" {name:25s} {color} ({x},{y},{rw}x{rh})")
272
+
273
+ for sample_spec in args.sample:
274
+ name, coords = sample_spec.split(':')
275
+ x, y = map(int, coords.split(','))
276
+ color = sample_point(img, x, y)
277
+ print(f" {name:25s} {color} ({x},{y})")