@snap/valdi 1.0.11 → 1.1.7
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.
- package/.metadata/.bazelrc.template +7 -6
- package/.metadata/MODULE.bazel.template +154 -0
- package/bundled-skills/registry.json +13 -2
- package/bundled-skills/skills/valdi-animations/skill.md +197 -0
- package/bundled-skills/skills/valdi-async/tests/src/reference.tsx +1 -1
- package/bundled-skills/skills/valdi-compiler/skill.md +4 -4
- package/bundled-skills/skills/valdi-component-dedup/skill.md +263 -0
- package/bundled-skills/skills/valdi-component-tests/tests/test/ProfileCardTest.spec.tsx +1 -1
- package/bundled-skills/skills/valdi-custom-view/skill.md +43 -1
- package/bundled-skills/skills/valdi-error-handling/skill.md +238 -0
- package/bundled-skills/skills/valdi-gestures/skill.md +198 -0
- package/bundled-skills/skills/valdi-inspect/skill.md +19 -1
- package/bundled-skills/skills/valdi-localization/skill.md +142 -0
- package/bundled-skills/skills/valdi-mock-breakdown/skill.md +327 -0
- package/bundled-skills/skills/valdi-mock-iterate/skill.md +216 -0
- package/bundled-skills/skills/valdi-mock-to-module/scripts/diff.py +392 -0
- package/bundled-skills/skills/valdi-mock-to-module/scripts/extract_colors.py +277 -0
- package/bundled-skills/skills/valdi-mock-to-module/scripts/find_icon.py +303 -0
- package/bundled-skills/skills/valdi-mock-to-module/scripts/snapshot-and-diff.sh +53 -0
- package/bundled-skills/skills/valdi-mock-to-module/scripts/test_diff.py +207 -0
- package/bundled-skills/skills/valdi-mock-to-module/scripts/test_extract_colors.py +167 -0
- package/bundled-skills/skills/valdi-mock-to-module/scripts/test_find_icon.py +188 -0
- package/bundled-skills/skills/valdi-mock-to-module/scripts/watch-and-diff.sh +181 -0
- package/bundled-skills/skills/valdi-mock-to-module/skill.md +451 -0
- package/bundled-skills/skills/valdi-navigation/skill.md +187 -0
- package/bundled-skills/skills/valdi-overview/skill.md +7 -4
- package/bundled-skills/skills/valdi-perf/skill.md +223 -0
- package/bundled-skills/skills/valdi-polyglot-module/skill.md +80 -0
- package/bundled-skills/skills/valdi-preview/skill.md +303 -0
- package/bundled-skills/skills/valdi-setup/skill.md +55 -5
- package/bundled-skills/skills/valdi-testing/skill.md +23 -7
- package/bundled-skills/skills/valdi-tsx/skill.md +69 -5
- package/bundled-skills/skills/valdi-tsx/tests/src/reference.tsx +29 -5
- package/dist/commands/agentCheck.js +184 -0
- package/dist/commands/analyze.js +16 -0
- package/dist/commands/analyze_commands/duplicates.js +134 -0
- package/dist/commands/bootstrap.js +57 -73
- package/dist/commands/build.js +6 -0
- package/dist/commands/doctor.js +42 -266
- package/dist/commands/hotreload.js +15 -0
- package/dist/commands/inspect_commands/snapshot.js +71 -6
- package/dist/commands/inspect_commands/snapshot.spec.js +105 -0
- package/dist/commands/install.js +6 -0
- package/dist/commands/preview.js +81 -0
- package/dist/commands/projectsync.js +9 -7
- package/dist/commands/skills_commands/install.js +6 -1
- package/dist/commands/skills_commands/update.js +2 -1
- package/dist/core/analyze/clusterer.js +150 -0
- package/dist/core/analyze/fingerprint.js +2 -0
- package/dist/core/analyze/knownPatterns.js +76 -0
- package/dist/core/analyze/parser.js +177 -0
- package/dist/core/analyze/reporter.js +83 -0
- package/dist/core/analyze/scanner.js +172 -0
- package/dist/core/analyze/similarity.js +56 -0
- package/dist/core/constants.js +6 -3
- package/dist/core/packageFiles.spec.js +1 -1
- package/dist/preview/previewGenerator.js +240 -0
- package/dist/preview/previewGenerator.spec.js +203 -0
- package/dist/preview/viewModelParser.js +86 -0
- package/dist/preview/viewModelParser.spec.js +171 -0
- package/dist/setup/DevSetupHelper.js +0 -54
- package/dist/setup/linuxSetup.js +0 -16
- package/dist/setup/macOSSetup.js +1 -5
- package/dist/utils/BazelClient.js +15 -0
- package/dist/utils/applicationUtils.js +15 -0
- package/dist/utils/daemonClient.js +3 -1
- package/dist/utils/linuxDistro.js +0 -21
- package/dist/utils/linuxDistro.spec.js +0 -48
- package/dist/utils/skillsAdapters.js +126 -19
- package/dist/utils/skillsAdapters.spec.js +141 -0
- package/dist/utils/skillsRegistry.js +8 -0
- package/package.json +16 -8
- package/.metadata/WORKSPACE.template +0 -57
- package/dist/setup/versions.js +0 -8
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
# valdi-mock-iterate
|
|
2
|
+
|
|
3
|
+
Compare a design mock against a rendered Valdi screenshot and produce specific, actionable code fixes. This is the "critic" in the mock-to-module pipeline — it only looks at pixels, never at code.
|
|
4
|
+
|
|
5
|
+
## When to use
|
|
6
|
+
|
|
7
|
+
- You have both a design mock/screenshot AND a rendered Valdi screenshot
|
|
8
|
+
- You need to evaluate visual fidelity between a target design and generated output
|
|
9
|
+
- You're the "critic" agent in a generator+critic iteration loop
|
|
10
|
+
- User asks "does this match?" or "what's different?"
|
|
11
|
+
|
|
12
|
+
## Overview
|
|
13
|
+
|
|
14
|
+
1. Compare the two images side by side
|
|
15
|
+
2. List every visual difference — be specific and quantitative
|
|
16
|
+
3. Prioritize fixes by visual impact
|
|
17
|
+
4. Output structured feedback the generator can act on
|
|
18
|
+
|
|
19
|
+
---
|
|
20
|
+
|
|
21
|
+
## Step 1: Compare the images
|
|
22
|
+
|
|
23
|
+
You will receive two images:
|
|
24
|
+
|
|
25
|
+
- **Mock** — the target design (screenshot, Figma export, or photo)
|
|
26
|
+
- **Rendered** — the Valdi app screenshot (from `valdi inspect snapshot`)
|
|
27
|
+
|
|
28
|
+
Compare them systematically by scanning these dimensions:
|
|
29
|
+
|
|
30
|
+
### Layout and structure
|
|
31
|
+
- Are all elements present? Any missing or extra elements?
|
|
32
|
+
- Is the overall structure correct? (vertical vs horizontal, scroll vs fixed)
|
|
33
|
+
- Is the element ordering correct?
|
|
34
|
+
|
|
35
|
+
### Spacing and sizing
|
|
36
|
+
- Are margins and padding correct? Compare gaps between elements.
|
|
37
|
+
- Are element sizes correct? (width, height, aspect ratios)
|
|
38
|
+
- Is the overall content centered/aligned as expected?
|
|
39
|
+
|
|
40
|
+
### Typography
|
|
41
|
+
- Are font sizes correct? (compare relative sizes: title vs body vs caption)
|
|
42
|
+
- Are font weights correct? (bold vs regular)
|
|
43
|
+
- Is text color correct?
|
|
44
|
+
- Is text alignment correct? (left, center, right)
|
|
45
|
+
|
|
46
|
+
### Colors and backgrounds
|
|
47
|
+
- Is the background color correct?
|
|
48
|
+
- Are element background colors correct?
|
|
49
|
+
- Are accent/highlight colors correct?
|
|
50
|
+
- Are borders and dividers the right color and thickness?
|
|
51
|
+
|
|
52
|
+
### Components
|
|
53
|
+
- Do interactive components look correct? (buttons, toggles, checkboxes)
|
|
54
|
+
- Are icons/images the right size and position?
|
|
55
|
+
- Are rounded corners the right radius?
|
|
56
|
+
|
|
57
|
+
---
|
|
58
|
+
|
|
59
|
+
## Step 2: Produce structured feedback
|
|
60
|
+
|
|
61
|
+
For each difference found, output a structured entry:
|
|
62
|
+
|
|
63
|
+
```
|
|
64
|
+
ISSUE: <what's wrong>
|
|
65
|
+
ELEMENT: <which element in the layout — be specific>
|
|
66
|
+
EXPECTED: <what the mock shows>
|
|
67
|
+
ACTUAL: <what the rendered output shows>
|
|
68
|
+
FIX: <specific code change to make>
|
|
69
|
+
SEVERITY: critical | major | minor
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
### Severity levels
|
|
73
|
+
|
|
74
|
+
- **critical** — Missing elements, wrong structure, completely wrong layout
|
|
75
|
+
- **major** — Wrong colors, wrong font sizes, significantly wrong spacing
|
|
76
|
+
- **minor** — Slightly off spacing (2-4px), minor color shade differences, minor radius differences
|
|
77
|
+
|
|
78
|
+
### Example output
|
|
79
|
+
|
|
80
|
+
```
|
|
81
|
+
ISSUE: Title font too small
|
|
82
|
+
ELEMENT: Header title label ("Settings")
|
|
83
|
+
EXPECTED: Bold, approximately 24px
|
|
84
|
+
ACTUAL: Regular weight, approximately 16px
|
|
85
|
+
FIX: Change font from 'system 16' to 'system-bold 24'
|
|
86
|
+
SEVERITY: major
|
|
87
|
+
|
|
88
|
+
ISSUE: Missing divider between rows
|
|
89
|
+
ELEMENT: Between row 2 ("Dark Mode") and row 3 ("Notifications")
|
|
90
|
+
EXPECTED: Thin gray horizontal line
|
|
91
|
+
ACTUAL: No divider present
|
|
92
|
+
FIX: Add <view height={1} backgroundColor="#E0E0E0" margin="0 16" /> between rows
|
|
93
|
+
SEVERITY: major
|
|
94
|
+
|
|
95
|
+
ISSUE: Bottom button slightly too narrow
|
|
96
|
+
ELEMENT: "Save Changes" button at bottom
|
|
97
|
+
EXPECTED: Full width with 16px side margins
|
|
98
|
+
ACTUAL: Appears to have 24px side margins
|
|
99
|
+
FIX: Change button container padding from '0 24' to '0 16'
|
|
100
|
+
SEVERITY: minor
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
---
|
|
104
|
+
|
|
105
|
+
## Step 3: Summarize and prioritize
|
|
106
|
+
|
|
107
|
+
After listing all issues, provide:
|
|
108
|
+
|
|
109
|
+
1. **Match score** — rough percentage (e.g., "~70% match")
|
|
110
|
+
2. **Top 3 fixes** — the changes that will have the biggest visual impact
|
|
111
|
+
3. **Verdict** — one of:
|
|
112
|
+
- `MATCH` — close enough, no more iteration needed (>95% match)
|
|
113
|
+
- `ITERATE` — specific fixes needed, list them
|
|
114
|
+
- `RESTRUCTURE` — fundamental layout is wrong, generator should start over with different structure
|
|
115
|
+
|
|
116
|
+
---
|
|
117
|
+
|
|
118
|
+
## Guidelines for the critic
|
|
119
|
+
|
|
120
|
+
### Be specific, not vague
|
|
121
|
+
```
|
|
122
|
+
// BAD: "The text looks different"
|
|
123
|
+
// GOOD: "The title label is regular weight ~16px but should be bold ~24px"
|
|
124
|
+
|
|
125
|
+
// BAD: "Spacing is off"
|
|
126
|
+
// GOOD: "Gap between the header and first row is ~8px but should be ~24px"
|
|
127
|
+
|
|
128
|
+
// BAD: "Colors are wrong"
|
|
129
|
+
// GOOD: "Button background is #007AFF but should be #FFFC00 (yellow)"
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
### Estimate in points, not pixels
|
|
133
|
+
Valdi uses point-based sizing. Screenshots from `valdi inspect snapshot` are in points (1pt = 1 unit in the output). When estimating dimensions:
|
|
134
|
+
- Standard spacing increments: 4, 8, 12, 16, 24, 32, 48
|
|
135
|
+
- Expanded font size reference:
|
|
136
|
+
|
|
137
|
+
| Visual role | Typical range |
|
|
138
|
+
|------------|---------------|
|
|
139
|
+
| Hero / display numbers | 64–80pt bold |
|
|
140
|
+
| Section headings | 20–24pt bold |
|
|
141
|
+
| Primary body text | 20–22pt |
|
|
142
|
+
| Secondary labels | 17–19pt |
|
|
143
|
+
| Captions / axis labels | 15–17pt |
|
|
144
|
+
| Small metadata | 12–14pt |
|
|
145
|
+
|
|
146
|
+
- Round to the nearest standard value
|
|
147
|
+
|
|
148
|
+
### Common first-pass mistakes to watch for
|
|
149
|
+
|
|
150
|
+
These are the most frequent issues on the **first iteration** — catch them early for the biggest visual improvement:
|
|
151
|
+
|
|
152
|
+
1. **Font sizes 30-50% too small** — the #1 error. If all text looks "a size too small" compared to the mock, recommend bumping every font size up by 2-6pt.
|
|
153
|
+
2. **Vertical spacing too tight** — sections feel cramped compared to the mock. Gaps between major sections should typically be 24-44pt, not 8-16pt.
|
|
154
|
+
3. **Text colors too dark** — body text using `#000000` when it should be `#444444-#555555`. Secondary labels using `#666666` when they should be `#999999-#BBBBBB`.
|
|
155
|
+
4. **Card padding too small** — cards typically need 28-36pt padding, not 12-16pt.
|
|
156
|
+
5. **Card border radius too sharp** — modern designs use 16-20pt radius.
|
|
157
|
+
6. **Chart elements too thin/small** — data lines should be 4-5pt width, dots 10-12pt diameter.
|
|
158
|
+
|
|
159
|
+
When these issues appear together (they usually do), recommend **all of them at once** rather than fixing one at a time. This dramatically reduces iteration count.
|
|
160
|
+
|
|
161
|
+
7. **Gradient/area fills look like bar charts** — when using overlapping `<view>` columns to simulate area fill under a curve, you need 60-80+ columns with slight width overlap (`width: ${100/STEPS + 2}%`) and uniform low opacity (~0.10-0.20) for a smooth continuous appearance.
|
|
162
|
+
8. **Selected state not visible enough** — highlight backgrounds need sufficient contrast from the card background. Use at least `#F5E6D0` level warmth for beige/tan selection pills on white backgrounds, not `#F0EAE0` which is barely visible.
|
|
163
|
+
9. **Emoji instead of real icons** — emoji characters look wrong at any size. Recommend replacing with icon assets from the project's icon library if one exists.
|
|
164
|
+
10. **Raw primitives instead of widget components** — hand-built list rows using `<view>` + `<label>` miss standard spacing and styling. Check the workspace for a shared widget library and use those components instead.
|
|
165
|
+
|
|
166
|
+
### Don't nitpick platform differences
|
|
167
|
+
Some things will always look slightly different:
|
|
168
|
+
- System font rendering varies by platform
|
|
169
|
+
- Shadow rendering is approximate
|
|
170
|
+
- Scroll indicator visibility
|
|
171
|
+
- Status bar / window chrome
|
|
172
|
+
|
|
173
|
+
These are NOT issues to report.
|
|
174
|
+
|
|
175
|
+
### Focus on what the generator can fix
|
|
176
|
+
Only report issues that can be fixed by editing the .tsx file:
|
|
177
|
+
- Layout, spacing, sizing, colors, fonts, element ordering, missing elements
|
|
178
|
+
- Do NOT report: animation timing, gesture behavior, dynamic data differences, system UI differences
|
|
179
|
+
|
|
180
|
+
---
|
|
181
|
+
|
|
182
|
+
## Pixel diff (preferred over eyeballing)
|
|
183
|
+
|
|
184
|
+
When available, use the bundled pixel diff scripts for objective comparison:
|
|
185
|
+
|
|
186
|
+
```bash
|
|
187
|
+
# ALWAYS use --auto-mask to exclude avatar/thumbnail regions from the match score
|
|
188
|
+
python3 <skill_dir>/scripts/diff.py /path/to/mock.png /path/to/render.png --auto-mask
|
|
189
|
+
|
|
190
|
+
# For iOS simulator screenshots, also mask the status bar:
|
|
191
|
+
python3 <skill_dir>/scripts/diff.py /path/to/mock.png /path/to/render.png --auto-mask --mask "0,0,400,30"
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
**ALWAYS use `--auto-mask`** on every diff. This auto-detects avatar/thumbnail/Bitmoji regions and excludes them from the match score — these render as colored placeholder circles that unfairly penalize the score.
|
|
195
|
+
|
|
196
|
+
Output: `/tmp/mock-vs-render-diff.png` — side-by-side: mock | render | amplified diff. Bright spots in the third panel = mismatches. Also prints a match percentage.
|
|
197
|
+
|
|
198
|
+
**Always open the diff image** so humans can see it: `open /tmp/mock-vs-render-diff.png`
|
|
199
|
+
|
|
200
|
+
This catches subtle differences that eyeballing misses: background color mismatches (#F2F2F2 vs #FFFFFF), missing drop shadows, and small spacing differences.
|
|
201
|
+
|
|
202
|
+
---
|
|
203
|
+
|
|
204
|
+
## Integration with the pipeline
|
|
205
|
+
|
|
206
|
+
When used as part of `/valdi-mock-to-module`:
|
|
207
|
+
|
|
208
|
+
1. Receive mock image, rendered screenshot, and pixel diff image
|
|
209
|
+
2. Produce the structured feedback above
|
|
210
|
+
3. The diff coordinator applies fixes one at a time via hot-reload
|
|
211
|
+
4. After a batch of fixes, re-diff and compare again
|
|
212
|
+
5. Repeat until `MATCH` or max iterations reached
|
|
213
|
+
|
|
214
|
+
In the two-phase pipeline, this critic role is distributed across three specialist agents (Text, Icons, Widgets) that run in parallel. Each focuses on its domain and reports structured fix recommendations.
|
|
215
|
+
|
|
216
|
+
**Key principle**: You never see code. You only see images. This keeps your feedback honest — you can't be biased by "the code looks right". You evaluate purely on visual output.
|
|
@@ -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)
|