@dickpy/dsh-oil-slide 0.0.0-stage → 0.2.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.
Files changed (97) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +89 -2
  3. package/bundled-assets/brand/empty-deck-cobalt.webp +0 -0
  4. package/bundled-assets/brand/oil-slide-mark-512.png +0 -0
  5. package/bundled-assets/skill/LICENSE +21 -0
  6. package/bundled-assets/skill/README.md +61 -0
  7. package/bundled-assets/skill/SKILL.md +185 -0
  8. package/bundled-assets/skill/references/art-directions.md +99 -0
  9. package/bundled-assets/skill/references/brand-and-canvas.md +72 -0
  10. package/bundled-assets/skill/references/design-baseline.txt +1 -0
  11. package/bundled-assets/skill/references/prompt-compiler.md +99 -0
  12. package/bundled-assets/skill/references/restore-and-pptx.md +178 -0
  13. package/bundled-assets/skill/references/staged-pptx.md +71 -0
  14. package/bundled-assets/skill/scripts/_runtime_utils.py +351 -0
  15. package/bundled-assets/skill/scripts/asset_sheet.py +528 -0
  16. package/bundled-assets/skill/scripts/brand_ref.py +776 -0
  17. package/bundled-assets/skill/scripts/crop_asset.py +1709 -0
  18. package/bundled-assets/skill/scripts/deck_shell.py +2322 -0
  19. package/bundled-assets/skill/scripts/export_images.py +280 -0
  20. package/bundled-assets/skill/scripts/extract_pptx.py +360 -0
  21. package/bundled-assets/skill/scripts/extract_slide_dom.js +1640 -0
  22. package/bundled-assets/skill/scripts/html_to_pptx.py +4042 -0
  23. package/bundled-assets/skill/scripts/measure_slide_layout.py +952 -0
  24. package/bundled-assets/skill/scripts/oiloil-connect.mjs +1493 -0
  25. package/bundled-assets/skill/scripts/oiloil-image.mjs +492 -0
  26. package/bundled-assets/skill/scripts/prepare_plate.py +412 -0
  27. package/bundled-assets/skill/scripts/render_gradient.py +258 -0
  28. package/bundled-assets/skill/scripts/slide_brand.py +111 -0
  29. package/bundled-assets/skill/scripts/slide_incremental.py +122 -0
  30. package/bundled-assets/skill/scripts/slide_workflow.py +711 -0
  31. package/bundled-assets/skill/scripts/verify_deck.py +3483 -0
  32. package/bundled-assets/skill/vendor/README.md +4 -0
  33. package/bundled-assets/skill/vendor/codex-ppt/LICENSE +21 -0
  34. package/bundled-assets/skill/vendor/codex-ppt/assemble_ppt.py +435 -0
  35. package/bundled-assets/skill/vendor/codex-ppt/codex_ppt_runtime.py +284 -0
  36. package/bundled-assets/skill/vendor/codex-ppt/image_gen.py +972 -0
  37. package/bundled-assets/skill/vendor/codex-ppt/image_providers/__init__.py +6 -0
  38. package/bundled-assets/skill/vendor/codex-ppt/image_providers/atlascloud.py +222 -0
  39. package/bundled-assets/skill/vendor/codex-ppt/image_providers/base.py +32 -0
  40. package/bundled-assets/skill/vendor/codex-ppt/image_providers/factory.py +21 -0
  41. package/bundled-assets/skill/vendor/codex-ppt/image_providers/openai_compatible.py +238 -0
  42. package/bundled-assets/skill/vendor/codex-ppt/requirements.txt +5 -0
  43. package/bundled-assets/skill/vendor/codex-ppt/styles//345/205/232/346/224/277/347/272/242/351/243/216/346/240/274.md +98 -0
  44. package/bundled-assets/skill/vendor/codex-ppt/styles//345/210/233/346/204/217/346/235/202/345/277/227/351/243/216.md +72 -0
  45. package/bundled-assets/skill/vendor/codex-ppt/styles//345/244/215/345/217/244/346/211/201/345/271/263/346/217/222/347/224/273/351/243/216.md +72 -0
  46. package/bundled-assets/skill/vendor/codex-ppt/styles//346/211/213/347/273/230/346/212/200/346/234/257/350/247/243/351/207/212/351/243/216.md +86 -0
  47. package/bundled-assets/skill/vendor/codex-ppt/styles//346/211/213/347/273/230/347/231/275/346/235/277/351/243/216.md +72 -0
  48. package/bundled-assets/skill/vendor/codex-ppt/styles//346/225/231/345/255/246/350/257/276/344/273/266/351/243/216.md +107 -0
  49. package/bundled-assets/skill/vendor/codex-ppt/styles//346/225/260/346/215/256/344/273/252/350/241/250/347/233/230/351/243/216.md +73 -0
  50. package/bundled-assets/skill/vendor/codex-ppt/styles//346/270/205/347/210/275/344/270/223/344/270/232/351/243/216.md +87 -0
  51. package/bundled-assets/skill/vendor/codex-ppt/styles//346/270/251/346/232/226/346/211/213/345/267/245/351/243/216.md +72 -0
  52. package/bundled-assets/skill/vendor/codex-ppt/styles//347/224/265/345/255/220/345/242/250/346/260/264/346/235/202/345/277/227/351/243/216.md +86 -0
  53. package/bundled-assets/skill/vendor/codex-ppt/styles//347/247/221/347/240/224/347/255/224/350/276/251/351/243/216.md +138 -0
  54. package/bundled-assets/skill/vendor/codex-ppt/styles//351/272/246/350/202/257/351/224/241/351/243/216/346/240/274.md +119 -0
  55. package/bundled-assets/skill/vendor/image-to-editable-ppt/LICENSE +21 -0
  56. package/bundled-assets/skill/vendor/image-to-editable-ppt/SKILL.md +171 -0
  57. package/bundled-assets/skill/vendor/image-to-editable-ppt/agents/openai.yaml +4 -0
  58. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/__init__.py +1 -0
  59. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/cli.py +25 -0
  60. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/__init__.py +1 -0
  61. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/_input_normalization.py +355 -0
  62. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/_page_artifacts.py +132 -0
  63. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/build_pptx_from_manifest.py +1029 -0
  64. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/configure_image_backend.py +52 -0
  65. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/deck_run_state.py +214 -0
  66. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/deck_text_hints.py +179 -0
  67. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/finalize_deck_run.py +96 -0
  68. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/formula_renderer.py +254 -0
  69. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/image_gen.py +206 -0
  70. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/main.py +795 -0
  71. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/make_page_contact_sheet.py +28 -0
  72. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/native_tables.py +140 -0
  73. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/paddle_text_hints.py +212 -0
  74. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/page_job_status.py +54 -0
  75. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/page_text_metrics.py +334 -0
  76. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/path_geometry.py +174 -0
  77. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/prepare_deck_run.py +209 -0
  78. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/process_asset_sheet.py +104 -0
  79. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/record_imagegen_result.py +118 -0
  80. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/record_page_dispatch.py +83 -0
  81. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/record_page_result.py +130 -0
  82. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/remove_chroma_key.py +441 -0
  83. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/reset_page_job.py +74 -0
  84. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/runtime_env.py +283 -0
  85. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/split_alpha_components.py +323 -0
  86. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/text_hints.py +309 -0
  87. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/validate_pptx.py +873 -0
  88. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/pyproject.toml +29 -0
  89. package/bundled-assets/skill/vendor/image-to-editable-ppt/prompts/page-worker.md +47 -0
  90. package/bundled-assets/skill/vendor/image-to-editable-ppt/references/cli-helper.md +282 -0
  91. package/bundled-assets/skill/vendor/image-to-editable-ppt/references/manifest-schema.md +423 -0
  92. package/bundled-assets/skill/vendor/image-to-editable-ppt/references/page-decision-tree.md +301 -0
  93. package/bundled-assets/skill/vendor/image-to-editable-ppt/scripts/build-page-worker-prompt.py +134 -0
  94. package/cordis.patch.yml +3 -0
  95. package/lib/client.js +11282 -0
  96. package/lib/index.js +2638 -0
  97. package/package.json +140 -4
@@ -0,0 +1,952 @@
1
+ #!/usr/bin/env python3
2
+ """Fast local Pixel Eyedropper & 1920x1080 Coordinate Layout Skeleton extractor.
3
+
4
+ Runs locally via Pillow in < 0.5s (0 LLM/image credits) on 16:9 reference slides
5
+ (e.g. assets/reference/s1..sN.png) and emits a compact `verify/layout-skeleton.json`
6
+ mapped directly to exact 1920x1080 pixel coordinates:
7
+ - exact background hex (edge-clustered, immune to right-edge photo bleed)
8
+ - subtle gradient detection (base_hex, glow_hex, focus_xy_pct)
9
+ - primary ink hex, accent hex, top palette colors, light/dark polarity
10
+ - header logo & page-number bounding boxes + deck-wide header_lock
11
+ - left vs right content bounding boxes + vertical split gutter + right visual bleed
12
+ - horizontal content bands + estimated headline height (px at 1920x1080) + hero KPI height
13
+
14
+ CLI:
15
+ python3 scripts/measure_slide_layout.py --ref-dir assets/reference --out verify/layout-skeleton.json --json
16
+ python3 scripts/measure_slide_layout.py s1.png s2.png --out verify/layout-skeleton.json --json
17
+ """
18
+ from __future__ import annotations
19
+
20
+ import argparse
21
+ import colorsys
22
+ import json
23
+ import math
24
+ import re
25
+ import statistics
26
+ import sys
27
+ import time
28
+ from collections import Counter
29
+ from pathlib import Path
30
+ from typing import Any
31
+
32
+ from PIL import Image, ImageChops, ImageFilter, ImageStat
33
+
34
+ CANVAS_W = 1920
35
+ CANVAS_H = 1080
36
+ # Exact 1:4 working resolution -> every 1px maps cleanly to 4px at canvas resolution
37
+ WORK_W = 480
38
+ WORK_H = 270
39
+ SCALE = 4
40
+
41
+ _CANVAS_BY_RATIO: dict[str, tuple[int, int, str]] = {
42
+ "16:9": (1920, 1080, "16:9"),
43
+ "3:4": (1080, 1440, "3:4"),
44
+ "9:16": (1080, 1920, "9:16"),
45
+ "1:1": (1440, 1440, "1:1"),
46
+ "1920x1080": (1920, 1080, "16:9"),
47
+ "1080x1440": (1080, 1440, "3:4"),
48
+ "1080x1920": (1080, 1920, "9:16"),
49
+ "1440x1440": (1440, 1440, "1:1"),
50
+ }
51
+
52
+
53
+ def resolve_measure_canvas(
54
+ src_w: int,
55
+ src_h: int,
56
+ *,
57
+ ratio: str | None = None,
58
+ canvas_width: int | None = None,
59
+ canvas_height: int | None = None,
60
+ ) -> tuple[int, int, str]:
61
+ """Resolve target (canvas_w, canvas_h, ratio_str) from explicit args or reference image aspect ratio."""
62
+ if canvas_width is not None and canvas_height is not None and int(canvas_width) > 0 and int(canvas_height) > 0:
63
+ cw, ch = int(canvas_width), int(canvas_height)
64
+ preset = _CANVAS_BY_RATIO.get(f"{cw}x{ch}")
65
+ return (cw, ch, preset[2] if preset else f"{cw}:{ch}")
66
+ if ratio:
67
+ tok = str(ratio).strip().lower().replace("×", "x").replace("/", ":")
68
+ if tok in _CANVAS_BY_RATIO:
69
+ return _CANVAS_BY_RATIO[tok]
70
+ m = re.fullmatch(r"(\d+)\s*x\s*(\d+)", tok)
71
+ if m and int(m.group(1)) > 0 and int(m.group(2)) > 0:
72
+ cw, ch = int(m.group(1)), int(m.group(2))
73
+ preset = _CANVAS_BY_RATIO.get(f"{cw}x{ch}")
74
+ return (cw, ch, preset[2] if preset else f"{cw}:{ch}")
75
+ raise ValueError(f"Unsupported ratio: {ratio!r} (expected '16:9', '3:4', '9:16', '1:1', or 'WxH')")
76
+ if (CANVAS_W, CANVAS_H) != (1920, 1080):
77
+ cw, ch = int(CANVAS_W), int(CANVAS_H)
78
+ preset = _CANVAS_BY_RATIO.get(f"{cw}x{ch}")
79
+ return (cw, ch, preset[2] if preset else f"{cw}:{ch}")
80
+ if src_w > 0 and src_h > 0:
81
+ aspect = float(src_w) / float(src_h)
82
+ if aspect >= 1.18:
83
+ return (1920, 1080, "16:9")
84
+ if aspect >= 0.88:
85
+ return (1440, 1440, "1:1")
86
+ if aspect >= 0.65:
87
+ return (1080, 1440, "3:4")
88
+ return (1080, 1920, "9:16")
89
+ return (1920, 1080, "16:9")
90
+
91
+
92
+ def _rgb_to_hex(rgb: tuple[int, int, int]) -> str:
93
+ return f"#{rgb[0]:02X}{rgb[1]:02X}{rgb[2]:02X}"
94
+
95
+
96
+ def _rgb_dist(a: tuple[int, int, int], b: tuple[int, int, int]) -> float:
97
+ return math.sqrt((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2 + (a[2] - b[2]) ** 2)
98
+
99
+
100
+ def _luminance(rgb: tuple[int, int, int]) -> float:
101
+ return (0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2]) / 255.0
102
+
103
+
104
+ def _bbox_to_dict(bbox: tuple[int, int, int, int] | None, ox: int = 0, oy: int = 0) -> dict[str, int] | None:
105
+ if not bbox:
106
+ return None
107
+ x0, y0, x1, y1 = bbox
108
+ return {
109
+ "x": (x0 + ox) * SCALE,
110
+ "y": (y0 + oy) * SCALE,
111
+ "w": max(0, (x1 - x0) * SCALE),
112
+ "h": max(0, (y1 - y0) * SCALE),
113
+ }
114
+
115
+
116
+ def _find_ref_images(ref_dir: Path) -> list[Path]:
117
+ if not ref_dir.is_dir():
118
+ return []
119
+ exts = {".png", ".jpg", ".jpeg", ".webp"}
120
+ candidates = [
121
+ p
122
+ for p in sorted(ref_dir.iterdir())
123
+ if p.is_file()
124
+ and p.suffix.lower() in exts
125
+ and not p.stem.lower().endswith("-ref")
126
+ and not p.name.lower().endswith((".preview.webp", ".full.webp"))
127
+ and not any(
128
+ skip in p.stem.lower()
129
+ for skip in ("overview", "2x2", "grid", "sheet", "compare", "brand", "swatch", "preview", "bg-plate")
130
+ )
131
+ ]
132
+
133
+ def _sort_key(p: Path) -> tuple[int, str]:
134
+ m = re.search(r"(?:^|[^0-9])(?:s|slide)?0?(\d+)(?:[^0-9]|$)", p.stem, re.IGNORECASE)
135
+ return (int(m.group(1)) if m else 9999, p.name.lower())
136
+
137
+ candidates.sort(key=_sort_key)
138
+ return candidates
139
+
140
+
141
+ def _sample_patch(im: Image.Image, x0: int, y0: int, w: int, h: int) -> dict[str, Any]:
142
+ cx0 = max(0, min(im.width - 1, int(x0)))
143
+ cy0 = max(0, min(im.height - 1, int(y0)))
144
+ cx1 = max(cx0 + 1, min(im.width, int(x0 + w)))
145
+ cy1 = max(cy0 + 1, min(im.height, int(y0 + h)))
146
+ crop = im.crop((cx0, cy0, cx1, cy1))
147
+ stat = ImageStat.Stat(crop)
148
+ med = tuple(int(round(v)) for v in stat.median[:3])
149
+ max_std = float(max(stat.stddev[:3]))
150
+ cx_pct = round(100.0 * (cx0 + (cx1 - cx0) / 2.0) / im.width, 1)
151
+ cy_pct = round(100.0 * (cy0 + (cy1 - cy0) / 2.0) / im.height, 1)
152
+ return {
153
+ "rgb": med,
154
+ "std": round(max_std, 2),
155
+ "cx_pct": cx_pct,
156
+ "cy_pct": cy_pct,
157
+ "rect_work": (cx0, cy0, cx1, cy1),
158
+ }
159
+
160
+
161
+ def _patch_texture_energy(
162
+ src_rgb: Image.Image,
163
+ rect_work: tuple[int, int, int, int],
164
+ work_size: tuple[int, int] | None = None,
165
+ ) -> float:
166
+ """High-pass residual std abs(patch - GaussianBlur(r=2)) on native-resolution background patch."""
167
+ x0, y0, x1, y1 = rect_work
168
+ ww, wh = work_size if work_size is not None else (WORK_W, WORK_H)
169
+ sx = src_rgb.width / float(max(1, ww))
170
+ sy = src_rgb.height / float(max(1, wh))
171
+ rx0 = max(0, int(round(x0 * sx)))
172
+ ry0 = max(0, int(round(y0 * sy)))
173
+ rx1 = min(src_rgb.width, max(rx0 + 4, int(round(x1 * sx))))
174
+ ry1 = min(src_rgb.height, max(ry0 + 4, int(round(y1 * sy))))
175
+
176
+ # Pad by 4px before GaussianBlur(r=2) so smooth linear ramps don't pick up edge clamping artifacts
177
+ pad = 4
178
+ px0 = max(0, rx0 - pad)
179
+ py0 = max(0, ry0 - pad)
180
+ px1 = min(src_rgb.width, rx1 + pad)
181
+ py1 = min(src_rgb.height, ry1 + pad)
182
+ padded = src_rgb.crop((px0, py0, px1, py1))
183
+ blurred = padded.filter(ImageFilter.GaussianBlur(radius=2))
184
+ diff = ImageChops.difference(padded, blurred)
185
+ inner = diff.crop((rx0 - px0, ry0 - py0, rx1 - px0, ry1 - py0))
186
+ if inner.width < 2 or inner.height < 2:
187
+ return 0.0
188
+ stat = ImageStat.Stat(inner)
189
+ # High-pass residual std (use max across RGB channels so colored grain isn't diluted)
190
+ return float(max(stat.stddev[:3]))
191
+
192
+
193
+ def _compute_bg_hue_spread(patches: list[dict[str, Any]]) -> float:
194
+ """Chroma-weighted pairwise circular hue spread detecting multi-hue aurora/nebula lighting."""
195
+ hsv_list: list[tuple[float, float, int]] = []
196
+ for p in patches:
197
+ r, g, b = p["rgb"]
198
+ chroma = max(r, g, b) - min(r, g, b)
199
+ h, s, _ = colorsys.rgb_to_hsv(r / 255.0, g / 255.0, b / 255.0)
200
+ if s >= 0.035 and chroma >= 9:
201
+ hsv_list.append((h, s, chroma))
202
+
203
+ max_spread = 0.0
204
+ for i in range(len(hsv_list)):
205
+ hi, si, _ = hsv_list[i]
206
+ for j in range(i + 1, len(hsv_list)):
207
+ hj, sj, _ = hsv_list[j]
208
+ dh = min(abs(hi - hj), 1.0 - abs(hi - hj))
209
+ weight = min(1.0, math.sqrt(si * sj) * 2.5)
210
+ spread = dh * weight
211
+ if spread > max_spread:
212
+ max_spread = spread
213
+ return round(max_spread, 4)
214
+
215
+
216
+ def _extract_background_and_gradient(im: Image.Image, raw_rgb: Image.Image | None = None) -> dict[str, Any]:
217
+ """Detect clean canvas background hex, tonal gradient, texture energy, hue spread, and backdrop advice."""
218
+ ww, wh = im.width, im.height
219
+
220
+ def _wx(v: int) -> int:
221
+ return round(v * ww / 480)
222
+
223
+ def _wy(v: int) -> int:
224
+ return round(v * wh / 270)
225
+
226
+ def _ww(v: int) -> int:
227
+ return max(4, round(v * ww / 480))
228
+
229
+ def _wh(v: int) -> int:
230
+ return max(4, round(v * wh / 270))
231
+
232
+ # Perimeter patches avoiding logo (top-left inner) and page number (top-right inner), proportional to (ww, wh)
233
+ edge_w = max(4, min(8, _ww(10)))
234
+ right_x = max(0, ww - edge_w - max(1, _wx(2)))
235
+ margin_specs = [
236
+ ("left_top", _wx(2), _wy(42), edge_w, _wh(26)),
237
+ ("left_mid", _wx(2), _wy(122), edge_w, _wh(26)),
238
+ ("left_bot", _wx(2), _wy(204), edge_w, _wh(26)),
239
+ ("top_left_corner", _wx(2), _wy(2), _ww(16), _wh(10)),
240
+ ("top_mid", _wx(220), _wy(2), _ww(40), _wh(10)),
241
+ ("bot_left", _wx(24), _wy(254), _ww(36), _wh(12)),
242
+ ("bot_mid", _wx(220), _wy(254), _ww(40), _wh(12)),
243
+ ("bot_right", _wx(420), _wy(254), _ww(36), _wh(12)),
244
+ ("right_top", right_x, _wy(42), edge_w, _wh(26)),
245
+ ("right_mid", right_x, _wy(122), edge_w, _wh(26)),
246
+ ("right_bot", right_x, _wy(204), edge_w, _wh(26)),
247
+ ]
248
+ edge_patches = []
249
+ for name, x0, y0, w, h in margin_specs:
250
+ p = _sample_patch(im, x0, y0, w, h)
251
+ p["name"] = name
252
+ p["is_left_or_margin"] = name.startswith(("left_", "top_", "bot_left", "bot_mid"))
253
+ edge_patches.append(p)
254
+
255
+ # Prefer smooth patches (excludes textured photo bleed along edges)
256
+ smooth_edges = [p for p in edge_patches if p["std"] <= 18.0]
257
+ if len(smooth_edges) < 3:
258
+ smooth_edges = sorted(edge_patches, key=lambda p: p["std"])[:5]
259
+
260
+ # Cluster smooth edge patches within Euclidean RGB <= 30
261
+ best_cluster: list[dict[str, Any]] = []
262
+ best_score = -1.0
263
+ for seed in smooth_edges:
264
+ cluster = [p for p in smooth_edges if _rgb_dist(seed["rgb"], p["rgb"]) <= 30.0]
265
+ # Slight tie-break preference for left/top/bottom margins (cover right bleed safety)
266
+ score = len(cluster) + 0.15 * sum(1 for p in cluster if p["is_left_or_margin"])
267
+ if score > best_score:
268
+ best_score = score
269
+ best_cluster = cluster
270
+
271
+ bg_rgb = (
272
+ int(round(statistics.median(p["rgb"][0] for p in best_cluster))),
273
+ int(round(statistics.median(p["rgb"][1] for p in best_cluster))),
274
+ int(round(statistics.median(p["rgb"][2] for p in best_cluster))),
275
+ )
276
+ bg_std = float(statistics.median(p["std"] for p in best_cluster)) if best_cluster else 6.0
277
+ polarity = "light" if _luminance(bg_rgb) >= 0.5 else "dark"
278
+
279
+ # Perimeter-only gradient delta (immune to interior shaded chart boxes/cards)
280
+ edge_grad_candidates = [p for p in smooth_edges if _rgb_dist(p["rgb"], bg_rgb) <= 58.0]
281
+ edge_delta = 0.0
282
+ for i in range(len(edge_grad_candidates)):
283
+ for j in range(i + 1, len(edge_grad_candidates)):
284
+ d = _rgb_dist(edge_grad_candidates[i]["rgb"], edge_grad_candidates[j]["rgb"])
285
+ if d > edge_delta:
286
+ edge_delta = d
287
+
288
+ # High-pass background texture energy on the cleanest background patches
289
+ # (sorting by patch std excludes perimeter strips that accidentally graze tight-margin text/hairlines)
290
+ tex_src = raw_rgb if raw_rgb is not None else im
291
+ tex_patches = best_cluster if best_cluster else smooth_edges
292
+ clean_tex_patches = sorted(tex_patches, key=lambda p: p["std"])[: max(2, (len(tex_patches) + 1) // 2)]
293
+ tex_energies = [_patch_texture_energy(tex_src, p["rect_work"], work_size=(ww, wh)) for p in clean_tex_patches]
294
+ bg_texture_energy = round(float(statistics.median(tex_energies)) if tex_energies else 0.0, 2)
295
+
296
+ # Also sample interior 3x3 smooth patches to detect radial/linear background gradients
297
+ # Skip interior tint sampling on flat uniform-edge light canvases so shaded chart boxes/cards
298
+ # on pure white slides are never mistaken for a full-bleed atmospheric gradient.
299
+ interior_patches: list[dict[str, Any]] = []
300
+ skip_light_interior_boxes = polarity == "light" and edge_delta < 10.0 and bg_texture_energy < 1.2
301
+ if not skip_light_interior_boxes:
302
+ for gy in (_wy(48), _wy(128), _wy(208)):
303
+ for gx in (_wx(84), _wx(224), _wx(364)):
304
+ p = _sample_patch(im, gx, gy, _ww(28), _wh(22))
305
+ if p["std"] <= max(14.0, bg_std + 6.0) and _rgb_dist(p["rgb"], bg_rgb) <= 58.0:
306
+ interior_patches.append(p)
307
+
308
+ grad_candidates = edge_grad_candidates + interior_patches
309
+ max_delta = 0.0
310
+ base_patch = best_cluster[0] if best_cluster else smooth_edges[0]
311
+ glow_patch = base_patch
312
+ for i in range(len(grad_candidates)):
313
+ for j in range(i + 1, len(grad_candidates)):
314
+ d = _rgb_dist(grad_candidates[i]["rgb"], grad_candidates[j]["rgb"])
315
+ if d > max_delta:
316
+ max_delta = d
317
+ a, b = grad_candidates[i], grad_candidates[j]
318
+ if _luminance(a["rgb"]) <= _luminance(b["rgb"]):
319
+ base_patch, glow_patch = a, b
320
+ else:
321
+ base_patch, glow_patch = b, a
322
+
323
+ # Multi-hue lighting spread across smooth background patches (including broader smooth edges for aurora)
324
+ hue_candidates = list(smooth_edges) + list(interior_patches)
325
+ bg_hue_spread = _compute_bg_hue_spread(hue_candidates)
326
+
327
+ has_gradient = max_delta >= 12.0
328
+ bg_gradient: dict[str, Any] | None = None
329
+ if has_gradient:
330
+ bg_gradient = {
331
+ "base_hex": _rgb_to_hex(base_patch["rgb"]),
332
+ "glow_hex": _rgb_to_hex(glow_patch["rgb"]),
333
+ "delta_rgb": round(max_delta, 1),
334
+ "focus_xy_pct": [glow_patch["cx_pct"], glow_patch["cy_pct"]],
335
+ }
336
+
337
+ if max_delta >= 24.0 or bg_texture_energy >= 1.8 or bg_hue_spread >= 0.08:
338
+ backdrop_recommendation = "clean_backdrop_plate"
339
+ elif has_gradient:
340
+ backdrop_recommendation = "css_micro_gradient"
341
+ else:
342
+ backdrop_recommendation = "flat_solid"
343
+
344
+ return {
345
+ "bg_rgb": bg_rgb,
346
+ "bg_hex": _rgb_to_hex(bg_rgb),
347
+ "bg_std": round(bg_std, 2),
348
+ "polarity": polarity,
349
+ "has_gradient": has_gradient,
350
+ "bg_gradient": bg_gradient,
351
+ "gradient_delta": round(max_delta, 1),
352
+ "bg_texture_energy": bg_texture_energy,
353
+ "bg_hue_spread": bg_hue_spread,
354
+ "backdrop_recommendation": backdrop_recommendation,
355
+ }
356
+
357
+
358
+ def _extract_ink_and_accent(
359
+ raw_im: Image.Image,
360
+ bg_rgb: tuple[int, int, int],
361
+ polarity: str,
362
+ work_size: tuple[int, int] | None = None,
363
+ ) -> dict[str, Any]:
364
+ """Sample native pixels (no bilinear blur) to extract primary ink, accent hex, and top palette."""
365
+ ww, wh = work_size if work_size is not None else (WORK_W, WORK_H)
366
+ # Subsample with NEAREST so thin dark text strokes & accent bars keep crisp true RGB values
367
+ small = raw_im.resize((max(60, ww // 2), max(60, wh // 2)), Image.Resampling.NEAREST)
368
+ buf = small.tobytes()
369
+ bg_lum = _luminance(bg_rgb)
370
+ bg_h, bg_s, _ = colorsys.rgb_to_hsv(bg_rgb[0] / 255.0, bg_rgb[1] / 255.0, bg_rgb[2] / 255.0)
371
+
372
+ # Quantize to 12-step bins for crisp dominant clusters
373
+ bin_counts: Counter[tuple[int, int, int]] = Counter()
374
+ bin_sums: dict[tuple[int, int, int], list[int]] = {}
375
+ ink_bins: Counter[tuple[int, int, int]] = Counter()
376
+ accent_bins: Counter[tuple[int, int, int]] = Counter()
377
+
378
+ total_px = len(buf) // 3
379
+ for idx in range(0, len(buf), 3):
380
+ r, g, b = buf[idx], buf[idx + 1], buf[idx + 2]
381
+ dist_bg = _rgb_dist((r, g, b), bg_rgb)
382
+ if dist_bg < 28.0:
383
+ continue
384
+ key = ((r // 12) * 12, (g // 12) * 12, (b // 12) * 12)
385
+ bin_counts[key] += 1
386
+ acc = bin_sums.get(key)
387
+ if acc is None:
388
+ bin_sums[key] = [r, g, b, 1]
389
+ else:
390
+ acc[0] += r
391
+ acc[1] += g
392
+ acc[2] += b
393
+ acc[3] += 1
394
+
395
+ lum = _luminance((r, g, b))
396
+ hue, sat, val = colorsys.rgb_to_hsv(r / 255.0, g / 255.0, b / 255.0)
397
+ contrast = (bg_lum - lum) if polarity == "light" else (lum - bg_lum)
398
+
399
+ # High-contrast ink (strong luminance contrast from background)
400
+ if contrast >= 0.45 and sat <= 0.65:
401
+ ink_bins[key] += 1
402
+
403
+ # Distinct brand accent: non-neutral chroma, visibly distinct from both paper tint & shadow
404
+ hue_diff = min(abs(hue - bg_h), 1.0 - abs(hue - bg_h))
405
+ if sat >= 0.28 and val >= 0.22 and dist_bg >= 48.0 and (hue_diff >= 0.05 or sat >= bg_s + 0.22):
406
+ accent_bins[key] += 1
407
+
408
+ def _mean_rgb(k: tuple[int, int, int]) -> tuple[int, int, int]:
409
+ s = bin_sums[k]
410
+ c = max(1, s[3])
411
+ return (round(s[0] / c), round(s[1] / c), round(s[2] / c))
412
+
413
+ # Primary ink: pick darkest (light mode) or brightest (dark mode) among top high-contrast ink clusters
414
+ if ink_bins:
415
+ top_inks = [_mean_rgb(k) for k, _ in ink_bins.most_common(5)]
416
+ if polarity == "light":
417
+ ink_rgb = min(top_inks, key=_luminance)
418
+ else:
419
+ ink_rgb = max(top_inks, key=_luminance)
420
+ else:
421
+ ink_rgb = (24, 30, 26) if polarity == "light" else (244, 247, 251)
422
+
423
+ # Primary accent: strongest saturated cluster separated from bg and primary ink
424
+ accent_rgb: tuple[int, int, int] | None = None
425
+ best_accent_score = -1.0
426
+ for k, cnt in accent_bins.most_common(16):
427
+ cand = _mean_rgb(k)
428
+ hue, sat, val = colorsys.rgb_to_hsv(cand[0] / 255.0, cand[1] / 255.0, cand[2] / 255.0)
429
+ ink_sep = 1.0 if _rgb_dist(cand, ink_rgb) >= 34.0 else 0.4
430
+ hue_bonus = 1.35 if min(abs(hue - bg_h), 1.0 - abs(hue - bg_h)) >= 0.08 else 0.75
431
+ score = math.sqrt(cnt) * (0.3 + sat * 1.6) * (0.4 + 0.6 * val) * ink_sep * hue_bonus
432
+ if score > best_accent_score:
433
+ best_accent_score = score
434
+ accent_rgb = cand
435
+
436
+ if accent_rgb is None:
437
+ accent_rgb = ink_rgb
438
+
439
+ # Top distinct non-background palette swatches (up to 4)
440
+ palette_top: list[dict[str, Any]] = []
441
+ chosen_rgbs: list[tuple[int, int, int]] = [bg_rgb]
442
+ for k, cnt in bin_counts.most_common(48):
443
+ cand = _mean_rgb(k)
444
+ if all(_rgb_dist(cand, prev) >= 36.0 for prev in chosen_rgbs):
445
+ chosen_rgbs.append(cand)
446
+ palette_top.append({"hex": _rgb_to_hex(cand), "pct": round(100.0 * cnt / total_px, 1)})
447
+ if len(palette_top) >= 4:
448
+ break
449
+
450
+ return {
451
+ "ink_hex": _rgb_to_hex(ink_rgb),
452
+ "accent_hex": _rgb_to_hex(accent_rgb),
453
+ "palette_top": palette_top,
454
+ }
455
+
456
+
457
+ def _build_masks(
458
+ im: Image.Image,
459
+ bg_rgb: tuple[int, int, int],
460
+ polarity: str,
461
+ bg_std: float,
462
+ gradient_delta: float,
463
+ ) -> tuple[Image.Image, Image.Image]:
464
+ """Return (fg_mask, ink_mask) as 1-channel 0/255 images at WORK_W x WORK_H."""
465
+ bg_im = Image.new("RGB", im.size, bg_rgb)
466
+ diff = ImageChops.difference(im, bg_im)
467
+ r_d, g_d, b_d = diff.split()
468
+ max_d = ImageChops.lighter(ImageChops.lighter(r_d, g_d), b_d)
469
+
470
+ # Adaptive foreground threshold clears paper grain & gentle gradients
471
+ fg_thresh = int(min(44, max(24, round(18 + bg_std * 1.4), round(gradient_delta + 8))))
472
+ fg_mask = max_d.point(lambda v: 255 if v > fg_thresh else 0)
473
+
474
+ # High-contrast ink mask for crisp text-line & headline-height measurement
475
+ gray = im.convert("L")
476
+ bg_l = int(round(_luminance(bg_rgb) * 255.0))
477
+ if polarity == "light":
478
+ ink_cut = max(20, bg_l - 62)
479
+ ink_mask = gray.point(lambda v: 255 if v < ink_cut else 0)
480
+ else:
481
+ ink_cut = min(235, bg_l + 62)
482
+ ink_mask = gray.point(lambda v: 255 if v > ink_cut else 0)
483
+
484
+ return fg_mask, ink_mask
485
+
486
+
487
+ def _row_and_col_counts(mask: Image.Image, x0: int, y0: int, x1: int, y1: int) -> tuple[list[int], list[int]]:
488
+ crop = mask.crop((x0, y0, x1, y1))
489
+ w, h = crop.size
490
+ data = crop.tobytes()
491
+ row_counts = [0] * h
492
+ col_counts = [0] * w
493
+ for y in range(h):
494
+ row_slice = data[y * w : (y + 1) * w]
495
+ cnt = 0
496
+ for x, val in enumerate(row_slice):
497
+ if val:
498
+ cnt += 1
499
+ col_counts[x] += 1
500
+ row_counts[y] = cnt
501
+ return row_counts, col_counts
502
+
503
+
504
+ def _extract_bands(counts: list[int], min_val: int, min_gap: int, min_span: int) -> list[tuple[int, int]]:
505
+ """Find contiguous [start, end) intervals where count >= min_val, merging tiny gaps < min_gap."""
506
+ raw: list[tuple[int, int]] = []
507
+ in_seg = False
508
+ start = 0
509
+ for i, c in enumerate(counts):
510
+ if c >= min_val and not in_seg:
511
+ in_seg = True
512
+ start = i
513
+ elif c < min_val and in_seg:
514
+ in_seg = False
515
+ raw.append((start, i))
516
+ if in_seg:
517
+ raw.append((start, len(counts)))
518
+
519
+ merged: list[tuple[int, int]] = []
520
+ for s, e in raw:
521
+ if merged and s - merged[-1][1] < min_gap:
522
+ merged[-1] = (merged[-1][0], e)
523
+ else:
524
+ merged.append((s, e))
525
+ return [(s, e) for s, e in merged if (e - s) >= min_span]
526
+
527
+
528
+ def _measure_headline_and_kpi(
529
+ ink_mask: Image.Image,
530
+ split_x_work: int,
531
+ has_two_col_split: bool,
532
+ has_right_bleed: bool,
533
+ ) -> dict[str, Any]:
534
+ """Measure primary headline line height (px at canvas resolution) and optional hero KPI height."""
535
+ ww, wh = ink_mask.size
536
+ canvas_w = ww * SCALE
537
+
538
+ def _wx(v: int) -> int:
539
+ return round(v * ww / 480)
540
+
541
+ def _wy(v: int) -> int:
542
+ return round(v * wh / 270)
543
+
544
+ # Check whether upper zone is split cleanly at split_x_work
545
+ search_x0 = _wx(16)
546
+ pad_r_16 = _wx(16)
547
+ pad_r_24 = _wx(24)
548
+ if has_right_bleed:
549
+ search_x1 = min(ww - pad_r_16, split_x_work)
550
+ elif has_two_col_split:
551
+ # Check if ink crosses the split gutter in the upper headline band
552
+ gutter_crop = ink_mask.crop(
553
+ (max(search_x0, split_x_work - 4), _wy(35), min(ww - pad_r_16, split_x_work + 4), _wy(105))
554
+ )
555
+ gutter_ink = ImageStat.Stat(gutter_crop).mean[0] / 255.0
556
+ search_x1 = (ww - pad_r_24) if gutter_ink >= 0.04 else min(ww - pad_r_16, split_x_work)
557
+ else:
558
+ search_x1 = ww - pad_r_24
559
+
560
+ # Upper-to-mid zone for headline: y in [35, 160] (scaled proportionally to wh)
561
+ y0, y1 = _wy(35), _wy(160)
562
+ upper_max_px = round(580 * wh / 270)
563
+
564
+ def _find_headline_in_window(
565
+ wx0: int, wx1: int, win_y0: int = y0, win_y1: int = y1
566
+ ) -> tuple[list[tuple[int, int, int]], int, int, int]:
567
+ w = max(1, wx1 - wx0)
568
+ rc, _ = _row_and_col_counts(ink_mask, wx0, win_y0, wx1, win_y1)
569
+ min_row_px = max(3, int(w * 0.018))
570
+ raw_bands = _extract_bands(rc, min_val=min_row_px, min_gap=2, min_span=3)
571
+ # Keep genuine text-line heights (up to 168px for bold display CJK covers)
572
+ t_lines = [(s, e, (e - s) * SCALE) for s, e in raw_bands if 12 <= (e - s) * SCALE <= 168]
573
+ if not t_lines:
574
+ return [], wx0, wx1, win_y0
575
+ upper = [ln for ln in t_lines if (win_y0 + ln[0]) * SCALE <= upper_max_px] or t_lines
576
+ max_h = max(ln[2] for ln in upper)
577
+ tall = [ln for ln in upper if ln[2] >= max(36, int(max_h * 0.72))]
578
+ if not tall:
579
+ return [], wx0, wx1, win_y0
580
+ cluster = [tall[0]]
581
+ for ln in tall[1:]:
582
+ prev_end = cluster[-1][1]
583
+ if (ln[0] - prev_end) * SCALE <= 72:
584
+ cluster.append(ln)
585
+ else:
586
+ break
587
+ return cluster, wx0, wx1, win_y0
588
+
589
+ # Check top-header left-to-center band for consulting/editorial Action Titles.
590
+ top_x0_w, top_x1_w = _wx(12), int(ww * 0.76)
591
+ top_lines, top_x0, top_x1, top_y0 = _find_headline_in_window(top_x0_w, top_x1_w, win_y0=_wy(6), win_y1=_wy(32))
592
+ top_action_title: tuple[list[tuple[int, int, int]], int, int, int, int] | None = None
593
+ if top_lines:
594
+ tl0 = top_lines[0]
595
+ tl_h = tl0[2]
596
+ _, col_cnts = _row_and_col_counts(ink_mask, top_x0, top_y0 + tl0[0], top_x1, top_y0 + tl0[1])
597
+ # Contiguous text span (allowing normal inter-word gaps up to 24px = 6 work px)
598
+ horiz_spans = _extract_bands(col_cnts, min_val=1, min_gap=6, min_span=8)
599
+ longest_span_px = max(((e - s) * SCALE for s, e in horiz_spans), default=0)
600
+ # A genuine top Action Title spans >= 32% canvas width contiguously and is 32..84px tall
601
+ if longest_span_px >= int(canvas_w * 0.32) and 32 <= tl_h <= 84:
602
+ top_action_title = ([tl0], top_x0, top_x1, top_y0, tl_h)
603
+
604
+ if top_action_title is not None:
605
+ headline_lines, best_x0, best_x1, best_y0, best_line_h = top_action_title
606
+ else:
607
+ headline_lines, best_x0, best_x1, best_y0 = _find_headline_in_window(search_x0, search_x1)
608
+ best_line_h = int(round(statistics.median(ln[2] for ln in headline_lines))) if headline_lines else 0
609
+
610
+ # If a side illustration vertically overlaps the headline (e.g., cover mascot on left/right),
611
+ # full-width row counts merge them into a >168px band leaving only a tiny kicker badge (<56px).
612
+ # Probe sub-windows excluding left/right illustration zones to recover the real display headline.
613
+ if best_line_h < 60:
614
+ sub_windows = [
615
+ (int(ww * 0.30), ww - pad_r_24),
616
+ (search_x0, int(ww * 0.70)),
617
+ (int(ww * 0.22), int(ww * 0.84)),
618
+ ]
619
+ for wx0, wx1 in sub_windows:
620
+ cand_lines, cx0, cx1, cy0 = _find_headline_in_window(wx0, wx1)
621
+ if not cand_lines:
622
+ continue
623
+ cand_h = int(round(statistics.median(ln[2] for ln in cand_lines)))
624
+ # Verify the candidate cluster spans a meaningful text width (>= 14% canvas width)
625
+ c_y0 = cy0 + cand_lines[0][0]
626
+ c_y1 = cy0 + cand_lines[-1][1]
627
+ c_bb = ink_mask.crop((cx0, c_y0, cx1, c_y1)).getbbox()
628
+ c_w_px = ((c_bb[2] - c_bb[0]) * SCALE) if c_bb else 0
629
+ if cand_h > best_line_h and c_w_px >= int(canvas_w * 0.14):
630
+ headline_lines, best_x0, best_x1, best_y0, best_line_h = cand_lines, cx0, cx1, cy0, cand_h
631
+
632
+ headline_bbox: dict[str, int] | None = None
633
+ headline_line_h: int | None = None
634
+ headline_est_font: int | None = None
635
+ if headline_lines:
636
+ hl_y0 = best_y0 + headline_lines[0][0]
637
+ hl_y1 = best_y0 + headline_lines[-1][1]
638
+ hl_crop = ink_mask.crop((best_x0, hl_y0, best_x1, hl_y1))
639
+ hl_bb = hl_crop.getbbox()
640
+ headline_bbox = _bbox_to_dict(hl_bb, ox=best_x0, oy=hl_y0)
641
+ headline_line_h = best_line_h
642
+ # Ink cap-height to CSS font-size factor (~1.12 for CJK heavy glyphs)
643
+ headline_est_font = int(min(152, max(32, round(headline_line_h * 1.12))))
644
+
645
+ # Check mid/lower zone for oversized hero KPI numerals
646
+ kpi_y0, kpi_y1 = _wy(85), _wy(230)
647
+ kpi_rows, _ = _row_and_col_counts(ink_mask, search_x0, kpi_y0, ww - search_x0, kpi_y1)
648
+ kpi_bands = _extract_bands(kpi_rows, min_val=6, min_gap=2, min_span=20) # >= 80px tall single line
649
+ hero_kpi_est_px: int | None = None
650
+ tall_kpis = [(e - s) * SCALE for s, e in kpi_bands if 84 <= (e - s) * SCALE <= 220]
651
+ if tall_kpis:
652
+ top_kpi_h = max(tall_kpis)
653
+ if not headline_line_h or top_kpi_h >= int(headline_line_h * 1.2):
654
+ hero_kpi_est_px = int(round(top_kpi_h * 1.15))
655
+
656
+ return {
657
+ "headline_bbox": headline_bbox,
658
+ "headline_lines": len(headline_lines),
659
+ "headline_line_height_px": headline_line_h,
660
+ "headline_est_font_px": headline_est_font,
661
+ "hero_kpi_est_px": hero_kpi_est_px,
662
+ }
663
+
664
+
665
+ def measure_single_slide(
666
+ img_path: Path,
667
+ slide_num: int = 1,
668
+ *,
669
+ ratio: str | None = None,
670
+ canvas_width: int | None = None,
671
+ canvas_height: int | None = None,
672
+ ) -> dict[str, Any]:
673
+ """Measure palette, polarity, and canvas-coordinate bounding boxes for one reference slide image."""
674
+ with Image.open(img_path) as raw:
675
+ src_w, src_h = raw.size
676
+ raw_rgb = raw.convert("RGB")
677
+ canvas_w, canvas_h, ratio_str = resolve_measure_canvas(
678
+ src_w, src_h, ratio=ratio, canvas_width=canvas_width, canvas_height=canvas_height
679
+ )
680
+ ww = max(16, canvas_w // SCALE)
681
+ wh = max(16, canvas_h // SCALE)
682
+ im = raw_rgb.resize((ww, wh), Image.Resampling.BILINEAR)
683
+
684
+ def _wx(v: int) -> int:
685
+ return round(v * ww / 480)
686
+
687
+ def _wy(v: int) -> int:
688
+ return round(v * wh / 270)
689
+
690
+ bg_info = _extract_background_and_gradient(im, raw_rgb=raw_rgb)
691
+ bg_rgb = bg_info["bg_rgb"]
692
+ polarity = bg_info["polarity"]
693
+ color_info = _extract_ink_and_accent(raw_rgb, bg_rgb, polarity, work_size=(ww, wh))
694
+ fg_mask, ink_mask = _build_masks(im, bg_rgb, polarity, bg_info["bg_std"], bg_info["gradient_delta"])
695
+
696
+ # 1. Header zone using high-contrast ink_mask so edge-bleeding photos don't pollute lockup
697
+ logo_x0, logo_y0, logo_x1, logo_y1 = _wx(12), _wy(8), _wx(185), _wy(33)
698
+ page_x0, page_y0, page_x1, page_y1 = _wx(415), _wy(10), _wx(472), _wy(32)
699
+ logo_bb = ink_mask.crop((logo_x0, logo_y0, logo_x1, logo_y1)).getbbox()
700
+ if not logo_bb:
701
+ logo_bb = fg_mask.crop((logo_x0, logo_y0, logo_x1, logo_y1)).getbbox()
702
+ page_bb = ink_mask.crop((page_x0, page_y0, page_x1, page_y1)).getbbox()
703
+ if not page_bb:
704
+ page_bb = fg_mask.crop((page_x0, page_y0, page_x1, page_y1)).getbbox()
705
+ header_logo_bbox = _bbox_to_dict(logo_bb, ox=logo_x0, oy=logo_y0)
706
+ page_num_bbox = _bbox_to_dict(page_bb, ox=page_x0, oy=page_y0)
707
+
708
+ # 2. Content zone
709
+ content_y0, content_y1 = _wy(35), _wy(259)
710
+ content_x0, content_x1 = _wx(10), _wx(470)
711
+ content_bb = fg_mask.crop((content_x0, content_y0, content_x1, content_y1)).getbbox()
712
+ content_bbox = _bbox_to_dict(content_bb, ox=content_x0, oy=content_y0)
713
+
714
+ # Detect right-edge visual bleed (e.g. cover photo or right-bleeding UI)
715
+ right_strip = fg_mask.crop((_wx(460), _wy(20), max(_wx(460) + 1, _wx(478)), _wy(250)))
716
+ right_bleed_ratio = ImageStat.Stat(right_strip).mean[0] / 255.0
717
+ has_right_visual_bleed = right_bleed_ratio >= 0.22
718
+
719
+ # Find cleanest vertical gutter in central 35%-65% band
720
+ row_counts, col_counts = _row_and_col_counts(fg_mask, content_x0, content_y0, content_x1, content_y1)
721
+ gutter_start = max(0, _wx(168) - content_x0)
722
+ gutter_end = min(len(col_counts), _wx(312) - content_x0)
723
+ window = max(2, _wx(6))
724
+ best_gx = _wx(240) - content_x0
725
+ best_gval = 1e9
726
+ for gx in range(gutter_start, max(gutter_start + 1, gutter_end - window)):
727
+ val = sum(col_counts[gx : gx + window]) / window
728
+ if val < best_gval:
729
+ best_gval = val
730
+ best_gx = gx + window // 2
731
+ split_x_work = content_x0 + best_gx
732
+ split_x = split_x_work * SCALE
733
+ # Detect whether there is a clean 2-column split (gutter density < 14% of content height)
734
+ has_two_col_split = best_gval < (content_y1 - content_y0) * 0.14
735
+
736
+ left_bb = fg_mask.crop((content_x0, content_y0, split_x_work, content_y1)).getbbox()
737
+ right_bb = fg_mask.crop((split_x_work, content_y0, content_x1, content_y1)).getbbox()
738
+ left_bbox = _bbox_to_dict(left_bb, ox=content_x0, oy=content_y0)
739
+ right_bbox = _bbox_to_dict(right_bb, ox=split_x_work, oy=content_y0)
740
+
741
+ left_cov = round(100.0 * ImageStat.Stat(fg_mask.crop((content_x0, content_y0, split_x_work, content_y1))).mean[0] / 255.0, 1)
742
+ right_cov = round(100.0 * ImageStat.Stat(fg_mask.crop((split_x_work, content_y0, content_x1, content_y1))).mean[0] / 255.0, 1)
743
+ content_cov = round(100.0 * ImageStat.Stat(fg_mask.crop((content_x0, content_y0, content_x1, content_y1))).mean[0] / 255.0, 1)
744
+
745
+ # Horizontal content bands (separated by >= 20px vertical whitespace)
746
+ h_bands_raw = _extract_bands(row_counts, min_val=max(4, _wx(8)), min_gap=5, min_span=4)
747
+ horizontal_bands: list[dict[str, int]] = []
748
+ for by0, by1 in h_bands_raw[:6]:
749
+ b_crop = fg_mask.crop((content_x0, content_y0 + by0, content_x1, content_y0 + by1))
750
+ bb = b_crop.getbbox()
751
+ bd = _bbox_to_dict(bb, ox=content_x0, oy=content_y0 + by0)
752
+ if bd:
753
+ horizontal_bands.append(bd)
754
+
755
+ # Headline & Hero KPI height estimation
756
+ typo = _measure_headline_and_kpi(
757
+ ink_mask,
758
+ split_x_work=split_x_work,
759
+ has_two_col_split=has_two_col_split,
760
+ has_right_bleed=has_right_visual_bleed,
761
+ )
762
+
763
+ return {
764
+ "slide": slide_num,
765
+ "file": img_path.name,
766
+ "source_size": [src_w, src_h],
767
+ "canvas": {"width": canvas_w, "height": canvas_h, "ratio": ratio_str},
768
+ "scale_to_canvas": round(canvas_w / max(1, src_w), 4),
769
+ "scale_to_1920": round(canvas_w / max(1, src_w), 4),
770
+ "polarity": polarity,
771
+ "bg_hex": bg_info["bg_hex"],
772
+ "has_gradient": bg_info["has_gradient"],
773
+ "bg_gradient": bg_info["bg_gradient"],
774
+ "gradient_delta": bg_info["gradient_delta"],
775
+ "bg_texture_energy": bg_info["bg_texture_energy"],
776
+ "bg_hue_spread": bg_info["bg_hue_spread"],
777
+ "backdrop_recommendation": bg_info["backdrop_recommendation"],
778
+ "ink_hex": color_info["ink_hex"],
779
+ "accent_hex": color_info["accent_hex"],
780
+ "palette_top": color_info["palette_top"],
781
+ "header": {
782
+ "logo_bbox": header_logo_bbox,
783
+ "page_num_bbox": page_num_bbox,
784
+ },
785
+ "layout": {
786
+ "content_bbox": content_bbox,
787
+ "split_x": split_x,
788
+ "has_two_col_split": has_two_col_split,
789
+ "has_right_visual_bleed": has_right_visual_bleed,
790
+ "left_bbox": left_bbox,
791
+ "right_bbox": right_bbox,
792
+ "left_coverage_pct": left_cov,
793
+ "right_coverage_pct": right_cov,
794
+ "content_coverage_pct": content_cov,
795
+ "horizontal_bands": horizontal_bands,
796
+ },
797
+ "typography": typo,
798
+ }
799
+
800
+
801
+ def measure_slides(
802
+ ref_dir: Path | None = None,
803
+ image_paths: list[Path] | None = None,
804
+ out_path: Path | None = None,
805
+ *,
806
+ ratio: str | None = None,
807
+ canvas_width: int | None = None,
808
+ canvas_height: int | None = None,
809
+ ) -> dict[str, Any]:
810
+ """Measure all reference slides and optionally persist verify/layout-skeleton.json."""
811
+ t0 = time.perf_counter()
812
+ paths: list[Path] = []
813
+ if image_paths:
814
+ paths = [Path(p) for p in image_paths if Path(p).is_file()]
815
+ elif ref_dir:
816
+ paths = _find_ref_images(Path(ref_dir))
817
+
818
+ if not paths:
819
+ return {"ok": False, "error": "No reference slide images found to measure."}
820
+
821
+ slide_results = [
822
+ measure_single_slide(
823
+ p, slide_num=idx, ratio=ratio, canvas_width=canvas_width, canvas_height=canvas_height
824
+ )
825
+ for idx, p in enumerate(paths, start=1)
826
+ ]
827
+ first_canvas = slide_results[0].get("canvas") or {"width": CANVAS_W, "height": CANVAS_H, "ratio": "16:9"}
828
+ rep_canvas_w = int(first_canvas.get("width") or CANVAS_W)
829
+ rep_canvas_h = int(first_canvas.get("height") or CANVAS_H)
830
+ rep_ratio = str(first_canvas.get("ratio") or "16:9")
831
+
832
+ # Deck-level summaries
833
+ pols = Counter(s["polarity"] for s in slide_results)
834
+ deck_polarity = pols.most_common(1)[0][0] if len(pols) == 1 else (
835
+ pols.most_common(1)[0][0] if pols.most_common(1)[0][1] >= len(slide_results) * 0.75 else "mixed"
836
+ )
837
+ dominant_bg = Counter(s["bg_hex"] for s in slide_results).most_common(1)[0][0]
838
+ dominant_ink = Counter(s["ink_hex"] for s in slide_results).most_common(1)[0][0]
839
+ dominant_accent = Counter(s["accent_hex"] for s in slide_results).most_common(1)[0][0]
840
+
841
+ rec_counts = Counter(s["backdrop_recommendation"] for s in slide_results)
842
+ rec_priority = {"clean_backdrop_plate": 3, "css_micro_gradient": 2, "flat_solid": 1}
843
+ deck_backdrop_rec = max(
844
+ rec_counts.keys(),
845
+ key=lambda k: (rec_counts[k], rec_priority.get(k, 0)),
846
+ )
847
+ clean_backdrop_slides = [
848
+ s["slide"] for s in slide_results if s["backdrop_recommendation"] == "clean_backdrop_plate"
849
+ ]
850
+
851
+ # Consensus header_lock across slides
852
+ logo_xs = [s["header"]["logo_bbox"]["x"] for s in slide_results if s["header"]["logo_bbox"]]
853
+ logo_ys = [s["header"]["logo_bbox"]["y"] for s in slide_results if s["header"]["logo_bbox"]]
854
+ logo_hs = [s["header"]["logo_bbox"]["h"] for s in slide_results if s["header"]["logo_bbox"]]
855
+ pnum_rs = [
856
+ s["header"]["page_num_bbox"]["x"] + s["header"]["page_num_bbox"]["w"]
857
+ for s in slide_results
858
+ if s["header"]["page_num_bbox"]
859
+ ]
860
+ pnum_ys = [s["header"]["page_num_bbox"]["y"] for s in slide_results if s["header"]["page_num_bbox"]]
861
+ default_side_inset = int(round(112 * rep_canvas_w / 1920))
862
+
863
+ header_lock = {
864
+ "top_px": int(round(statistics.median(logo_ys))) if logo_ys else 56,
865
+ "left_px": int(round(statistics.median(logo_xs))) if logo_xs else default_side_inset,
866
+ "right_inset_px": int(round(rep_canvas_w - statistics.median(pnum_rs))) if pnum_rs else default_side_inset,
867
+ "logo_height_px": int(round(statistics.median(logo_hs))) if logo_hs else 28,
868
+ "page_num_y_px": int(round(statistics.median(pnum_ys))) if pnum_ys else 56,
869
+ }
870
+
871
+ elapsed_ms = round((time.perf_counter() - t0) * 1000.0, 1)
872
+ report: dict[str, Any] = {
873
+ "ok": True,
874
+ "canvas": {"width": rep_canvas_w, "height": rep_canvas_h, "ratio": rep_ratio},
875
+ "slide_count": len(slide_results),
876
+ "elapsed_ms": elapsed_ms,
877
+ "deck_summary": {
878
+ "polarity": deck_polarity,
879
+ "dominant_bg_hex": dominant_bg,
880
+ "dominant_ink_hex": dominant_ink,
881
+ "dominant_accent_hex": dominant_accent,
882
+ "backdrop_recommendation": deck_backdrop_rec,
883
+ "clean_backdrop_slides": clean_backdrop_slides,
884
+ "header_lock": header_lock,
885
+ },
886
+ "slides": slide_results,
887
+ }
888
+
889
+ if out_path is not None:
890
+ out_abs = Path(out_path).resolve()
891
+ out_abs.parent.mkdir(parents=True, exist_ok=True)
892
+ out_abs.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
893
+ report["out"] = str(out_abs)
894
+
895
+ return report
896
+
897
+
898
+ def _configure_utf8_stdio() -> None:
899
+ for stream in (sys.stdout, sys.stderr):
900
+ if stream is not None:
901
+ try:
902
+ if not stream.isatty() and hasattr(stream, "reconfigure"):
903
+ stream.reconfigure(encoding="utf-8", errors="replace")
904
+ except Exception:
905
+ pass
906
+
907
+
908
+ def main() -> int:
909
+ _configure_utf8_stdio()
910
+ parser = argparse.ArgumentParser(
911
+ description="Fast local pixel eyedropper & layout skeleton extractor for reference slides (16:9, 3:4, 9:16, 1:1)."
912
+ )
913
+ parser.add_argument("images", nargs="*", type=Path, help="Optional explicit slide image paths (s1.png s2.png ...)")
914
+ parser.add_argument("--ref-dir", type=Path, default=None, help="Directory of reference slide images (e.g. assets/reference)")
915
+ parser.add_argument("--ratio", "--aspect-ratio", dest="ratio", type=str, default=None, help="Optional canvas aspect ratio (16:9, 3:4, 9:16, 1:1); auto-detected from images when omitted")
916
+ parser.add_argument("--width", type=int, default=None, help="Optional canvas width override (px)")
917
+ parser.add_argument("--height", type=int, default=None, help="Optional canvas height override (px)")
918
+ parser.add_argument("--out", type=Path, default=None, help="Output JSON path (e.g. verify/layout-skeleton.json)")
919
+ parser.add_argument("--json", action="store_true", help="Print JSON report to stdout")
920
+ args = parser.parse_args()
921
+
922
+ if not args.images and not args.ref_dir:
923
+ print("Error: provide --ref-dir or one or more image paths.", file=sys.stderr)
924
+ return 2
925
+
926
+ report = measure_slides(
927
+ ref_dir=args.ref_dir,
928
+ image_paths=args.images if args.images else None,
929
+ out_path=args.out,
930
+ ratio=args.ratio,
931
+ canvas_width=args.width,
932
+ canvas_height=args.height,
933
+ )
934
+ if not report.get("ok"):
935
+ print(f"Error: {report.get('error')}", file=sys.stderr)
936
+ return 1
937
+
938
+ if args.json:
939
+ print(json.dumps(report, ensure_ascii=False, indent=2))
940
+ else:
941
+ ds = report["deck_summary"]
942
+ print(
943
+ f"measure_slide_layout: ok=True slides={report['slide_count']} "
944
+ f"polarity={ds['polarity']} bg={ds['dominant_bg_hex']} "
945
+ f"ink={ds['dominant_ink_hex']} accent={ds['dominant_accent_hex']} "
946
+ f"elapsed={report['elapsed_ms']}ms"
947
+ )
948
+ return 0
949
+
950
+
951
+ if __name__ == "__main__":
952
+ raise SystemExit(main())