@lark-apaas/coding-steering 0.1.68-alpha.20261016070747 → 0.1.68

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 (143) hide show
  1. package/README.md +19 -21
  2. package/package.json +6 -6
  3. package/steering/design-html/skills/animated-video/SKILL.md +2 -2
  4. package/steering/design-html/skills/charts/SKILL.md +60 -8
  5. package/steering/design-html/skills/{data-report → data-viz}/SKILL.md +65 -9
  6. package/steering/design-html/skills/frontend-design/SKILL.md +2 -2
  7. package/steering/design-html/skills/hi-fi-design/SKILL.md +1 -1
  8. package/steering/design-html/skills/interactive-prototype/SKILL.md +19 -2
  9. package/steering/design-html/skills/mini-game/SKILL.md +71 -0
  10. package/steering/design-html/skills/mini-game/references/three-js.md +54 -0
  11. package/steering/design-html/skills/pptx-style-extract/SKILL.md +157 -0
  12. package/steering/design-html/skills/pptx-style-extract/font-fallback.yaml +129 -0
  13. package/steering/design-html/skills/pptx-style-extract/scripts/census.py +967 -0
  14. package/steering/design-html/skills/pptx-style-extract/scripts/check_v2.py +1052 -0
  15. package/steering/design-html/skills/pptx-style-extract/scripts/draft.py +3483 -0
  16. package/steering/design-html/skills/pptx-style-extract/scripts/export_consumer_md.py +75 -0
  17. package/steering/design-html/skills/pptx-style-extract/scripts/export_consumer_zip.py +175 -0
  18. package/steering/design-html/skills/pptx-style-extract/scripts/extract.py +1287 -0
  19. package/steering/design-html/skills/pptx-style-extract/scripts/ooxml.py +716 -0
  20. package/steering/design-html/skills/pptx-style-extract/scripts/package.py +1946 -0
  21. package/steering/design-html/skills/pptx-style-extract/scripts/parts.py +480 -0
  22. package/steering/design-html/skills/pptx-style-extract/scripts/query.py +557 -0
  23. package/steering/design-html/skills/pptx-style-extract/scripts/render_pages.py +687 -0
  24. package/steering/design-html/skills/pptx-style-extract/scripts/test_asset_judgment_package.py +556 -0
  25. package/steering/design-html/skills/pptx-style-extract/scripts/test_background_composite.py +364 -0
  26. package/steering/design-html/skills/pptx-style-extract/scripts/test_color_contract.py +60 -0
  27. package/steering/design-html/skills/pptx-style-extract/scripts/test_design_consumer_contract.py +76 -0
  28. package/steering/design-html/skills/pptx-style-extract/scripts/test_flow_layout_contract.py +528 -0
  29. package/steering/design-html/skills/pptx-style-extract/scripts/test_layout_css.py +1814 -0
  30. package/steering/design-html/skills/pptx-style-extract/scripts/test_logo_scope.py +600 -0
  31. package/steering/design-html/skills/pptx-style-extract/scripts/test_rounded_contract.py +112 -0
  32. package/steering/design-html/skills/pptx-style-extract/scripts/test_text_role_contract.py +315 -0
  33. package/steering/design-html/skills/pptx-style-extract/scripts/verify_font.py +68 -0
  34. package/steering/design-html/skills/pptx-style-extract/scripts/verify_layout_assets.py +421 -0
  35. package/steering/design-html/skills/pptx-style-extract/scripts/verify_logo_scope.py +12 -0
  36. package/steering/design-html/skills/pptx-style-extract/v2-format-spec.md +205 -0
  37. package/steering/design-html/skills/{make-a-deck → slide-deck}/SKILL.md +35 -11
  38. package/steering/design-html/skills/social-card/SKILL.md +263 -0
  39. package/steering/design-html/skills/{visual-exposure → visual-report}/SKILL.md +24 -2
  40. package/steering/nestjs-react-fullstack/skills/app-init-feasibility-guide/SKILL.md +5 -0
  41. package/steering/nestjs-react-fullstack/skills/authn-guide/SKILL.md +7 -0
  42. package/steering/nestjs-react-fullstack/skills/authz-guide/SKILL.md +43 -10
  43. package/steering/nestjs-react-fullstack/skills/authz-guide/references/dynamic-permission-guide.md +1 -1
  44. package/steering/nestjs-react-fullstack/skills/authz-guide/references/runtime-role-controller-spec.md +6 -8
  45. package/steering/nestjs-react-fullstack/skills/authz-guide/references/sdk-examples.md +6 -1
  46. package/steering/nestjs-react-fullstack/skills/authz-guide/references/sdk-types.md +8 -5
  47. package/steering/nestjs-react-fullstack/skills/client-builtins-file-storage-service/SKILL.md +45 -116
  48. package/steering/nestjs-react-fullstack/skills/client-builtins-user-service/SKILL.md +15 -2
  49. package/steering/nestjs-react-fullstack/skills/code-fix/SKILL.md +15 -9
  50. package/steering/nestjs-react-fullstack/skills/coding-guide/SKILL.md +360 -102
  51. package/steering/nestjs-react-fullstack/skills/connections-sdk/SKILL.md +202 -0
  52. package/steering/nestjs-react-fullstack/skills/contacts-service/SKILL.md +88 -11
  53. package/steering/nestjs-react-fullstack/skills/design-guide/SKILL.md +190 -0
  54. package/steering/nestjs-react-fullstack/skills/design-guide/references/broadsheet.md +313 -0
  55. package/steering/nestjs-react-fullstack/skills/design-guide/references/claude-editorial-research.md +375 -0
  56. package/steering/nestjs-react-fullstack/skills/design-guide/references/crimson-frosted-glass.md +221 -0
  57. package/steering/nestjs-react-fullstack/skills/design-guide/references/cybernetic-vault-terminal.md +74 -0
  58. package/steering/nestjs-react-fullstack/skills/design-guide/references/dashboard.md +234 -0
  59. package/steering/nestjs-react-fullstack/skills/design-guide/references/digital-e-guide.md +349 -0
  60. package/steering/nestjs-react-fullstack/skills/design-guide/references/finance-report.md +169 -0
  61. package/steering/nestjs-react-fullstack/skills/design-guide/references/flowbite.md +179 -0
  62. package/steering/{design-html/skills_local/creative-design → nestjs-react-fullstack/skills/design-guide}/references/frontend-design.md +21 -26
  63. package/steering/nestjs-react-fullstack/skills/design-guide/references/handwritten-sketch.md +215 -0
  64. package/steering/nestjs-react-fullstack/skills/design-guide/references/industry.md +348 -0
  65. package/steering/nestjs-react-fullstack/skills/design-guide/references/metabase.md +226 -0
  66. package/steering/nestjs-react-fullstack/skills/design-guide/references/minimal-jade.md +205 -0
  67. package/steering/nestjs-react-fullstack/skills/design-guide/references/nebula-crimson.md +306 -0
  68. package/steering/nestjs-react-fullstack/skills/design-guide/references/nexuscore-analytics.md +74 -0
  69. package/steering/nestjs-react-fullstack/skills/design-guide/references/organic-minimalism.md +253 -0
  70. package/steering/nestjs-react-fullstack/skills/design-guide/references/pm-spec.md +234 -0
  71. package/steering/nestjs-react-fullstack/skills/design-guide/references/pop-art.md +272 -0
  72. package/steering/nestjs-react-fullstack/skills/design-guide/references/sap-fiori-horizon.md +154 -0
  73. package/steering/nestjs-react-fullstack/skills/design-guide/references/token-mapping.md +68 -0
  74. package/steering/nestjs-react-fullstack/skills/design-guide/references/warm-elegance.md +217 -0
  75. package/steering/nestjs-react-fullstack/skills/design-guide/references/wild-orange.md +203 -0
  76. package/steering/nestjs-react-fullstack/skills/nestjs-cache/SKILL.md +254 -0
  77. package/steering/nestjs-react-fullstack/skills/openapi-guide/SKILL.md +44 -0
  78. package/steering/nestjs-react-fullstack/skills/plugin-guide/SKILL.md +179 -541
  79. package/steering/nestjs-react-fullstack/skills/plugin-guide/references/plugin-coding-guide.md +199 -17
  80. package/steering/nestjs-react-fullstack/skills/plugin-guide/references/table.md +30 -14
  81. package/steering/nestjs-react-fullstack/skills/raw-sql-boundary-audit/SKILL.md +63 -0
  82. package/steering/nestjs-react-fullstack/skills/server-builtins-file-storage-service/SKILL.md +210 -177
  83. package/steering/nestjs-react-fullstack/skills_common/mcp-guide/SKILL.md +78 -0
  84. package/steering/nestjs-react-fullstack/skills_common/mcp-guide/assets/eslint.mcp-ui.config.cjs +19 -0
  85. package/steering/nestjs-react-fullstack/skills_common/mcp-guide/assets/ui-tsconfig.json +19 -0
  86. package/steering/nestjs-react-fullstack/skills_common/mcp-guide/references/client-onboarding.md +82 -0
  87. package/steering/nestjs-react-fullstack/skills_common/mcp-guide/references/debugging.md +81 -0
  88. package/steering/nestjs-react-fullstack/skills_common/mcp-guide/references/mcp-apps.md +197 -0
  89. package/steering/nestjs-react-fullstack/skills_common/mcp-guide/references/tool-authoring.md +249 -0
  90. package/steering/nestjs-react-fullstack/skills_common/server-contacts-contract/SKILL.md +19 -0
  91. package/steering/nestjs-react-fullstack/{skills → skills_common}/trigger-guide/SKILL.md +38 -5
  92. package/steering/nestjs-react-fullstack/skills_common/user-identity/SKILL.md +33 -40
  93. package/steering/nestjs-react-fullstack/skills_local/authz-guide/SKILL.md +39 -6
  94. package/steering/nestjs-react-fullstack/skills_local/authz-guide/references/runtime-role-controller-spec.md +6 -8
  95. package/steering/nestjs-react-fullstack/skills_local/authz-guide/references/sdk-examples.md +6 -1
  96. package/steering/nestjs-react-fullstack/skills_local/authz-guide/references/sdk-types.md +8 -5
  97. package/steering/nestjs-react-fullstack/skills_local/client-builtins-user-service/SKILL.md +2 -0
  98. package/steering/nestjs-react-fullstack/skills_local/code-fix/SKILL.md +8 -2
  99. package/steering/nestjs-react-fullstack/skills_local/coding-guide/SKILL.md +145 -81
  100. package/steering/nestjs-react-fullstack/skills_local/plugin-guide/SKILL.md +14 -3
  101. package/steering/nestjs-react-fullstack/skills_local/plugin-guide/references/plugin-coding-guide.md +150 -16
  102. package/steering/vite-react/skills/plugin-guide/SKILL.md +8 -6
  103. package/steering/vite-react/skills/react-three-fiber/SKILL.md +5 -0
  104. package/steering/vite-react/tech.md +3 -0
  105. package/steering/design-html/skills_local/creative-design/agents/assets/vision-probe.png +0 -0
  106. package/steering/design-html/skills_local/creative-design/agents/fork-verifier-agent.md +0 -71
  107. package/steering/design-html/skills_local/creative-design/agents/vision-probe-agent.md +0 -41
  108. package/steering/design-html/skills_local/creative-design/assets/index.html +0 -27
  109. package/steering/design-html/skills_local/creative-design/references/aily.md +0 -39
  110. package/steering/design-html/skills_local/creative-design/references/animated-video.md +0 -35
  111. package/steering/design-html/skills_local/creative-design/references/charts.md +0 -165
  112. package/steering/design-html/skills_local/creative-design/references/claude.md +0 -36
  113. package/steering/design-html/skills_local/creative-design/references/codex.md +0 -32
  114. package/steering/design-html/skills_local/creative-design/references/data-report.md +0 -108
  115. package/steering/design-html/skills_local/creative-design/references/hi-fi-design.md +0 -32
  116. package/steering/design-html/skills_local/creative-design/references/interactive-prototype.md +0 -24
  117. package/steering/design-html/skills_local/creative-design/references/make-a-deck.md +0 -133
  118. package/steering/design-html/skills_local/creative-design/references/visual-exposure.md +0 -82
  119. package/steering/design-html/skills_local/creative-design/references/wireframe.md +0 -14
  120. package/steering/design-html/skills_local/creative-design/skill.md +0 -273
  121. package/steering/design-html/skills_local/creative-design/starter-components/android-frame.jsx +0 -188
  122. package/steering/design-html/skills_local/creative-design/starter-components/animations.jsx +0 -773
  123. package/steering/design-html/skills_local/creative-design/starter-components/browser-window.jsx +0 -122
  124. package/steering/design-html/skills_local/creative-design/starter-components/deck-stage.js +0 -2483
  125. package/steering/design-html/skills_local/creative-design/starter-components/design-canvas.jsx +0 -1432
  126. package/steering/design-html/skills_local/creative-design/starter-components/ios-frame.jsx +0 -270
  127. package/steering/design-html/skills_local/creative-design/starter-components/macos-window.jsx +0 -197
  128. package/steering/design-html/skills_local/creative-design/starter-components/tweaks-panel.jsx +0 -752
  129. package/steering/nestjs-react-fullstack/skills/client-add-aily-web-chat/SKILL.md +0 -139
  130. package/steering/nestjs-react-fullstack/skills/feishu/SKILL.md +0 -269
  131. package/steering/nestjs-react-fullstack/skills/feishu/references/approval.md +0 -214
  132. package/steering/nestjs-react-fullstack/skills/feishu/references/attendance.md +0 -163
  133. package/steering/nestjs-react-fullstack/skills/feishu/references/bitable.md +0 -311
  134. package/steering/nestjs-react-fullstack/skills/feishu/references/calendar.md +0 -190
  135. package/steering/nestjs-react-fullstack/skills/feishu/references/contacts.md +0 -160
  136. package/steering/nestjs-react-fullstack/skills/feishu/references/doc.md +0 -257
  137. package/steering/nestjs-react-fullstack/skills/feishu/references/drive.md +0 -104
  138. package/steering/nestjs-react-fullstack/skills/feishu/references/events.md +0 -199
  139. package/steering/nestjs-react-fullstack/skills/feishu/references/id-convert.md +0 -128
  140. package/steering/nestjs-react-fullstack/skills/feishu/references/messaging.md +0 -207
  141. package/steering/nestjs-react-fullstack/skills/feishu/references/oauth.md +0 -165
  142. package/steering/nestjs-react-fullstack/skills/feishu/references/perm.md +0 -91
  143. package/steering/nestjs-react-fullstack/skills/feishu/references/wiki.md +0 -165
@@ -0,0 +1,967 @@
1
+ #!/usr/bin/env python3
2
+ """S5 image census / S6 colour+font frequency / S7 layout inventory / S8 guides /
3
+ S13 theme topology, plus the derived text-scale, spacing, radii and effects censuses."""
4
+ import re
5
+ from collections import Counter, OrderedDict, defaultdict
6
+
7
+ from ooxml import (NS, alias_group, family_of, local, luminance, raw_token, read_color,
8
+ resolve_color)
9
+
10
+ # --- S5 epsilon split (方案 v0.2 §1 S5): position/repeat matching uses ±0.5% of the
11
+ # 1920px canvas; fullscreen detection has its own independent threshold.
12
+ EPS_PX = 0.005 * 1920 # 9.6 px
13
+ FULLSCREEN_MIN_PCT = 95.0 # 上不封顶(尺寸维度,兼容旧口径)
14
+ FULLSCREEN_COVERAGE = 0.95 # 画布覆盖率判据:溢出/略未贴边都算背景,偏移出画布的大图不算
15
+ REPEAT_MIN = 2 # 出现 <2 次谈不上「重复位」
16
+
17
+ # 下面三个跨模块共用,import 处不要再抄一份字面量
18
+ SMALL_IMG_W_PCT = 25.0 # 占画布宽小于此值算小图(图标/角标/logo),不是内容配图
19
+ LUM_MID = 0.5 # 深/浅分界,Rec.709 相对亮度
20
+ ASSET_WARN_SINGLE = 500 * 1024 # 单张压缩后体积的 WARN 线,对齐 v2-format-spec §5 V2-6
21
+
22
+
23
+ def canvas_coverage(box, cw, ch):
24
+ """图片与画布交集面积 / 画布面积。溢出(bleed)交集封顶于画布,天然 ≤1。"""
25
+ if not box:
26
+ return 0.0
27
+ x, y, w, h = box.get('x', 0), box.get('y', 0), box.get('w', 0), box.get('h', 0)
28
+ iw = max(0.0, min(x + w, cw) - max(x, 0.0))
29
+ ih = max(0.0, min(y + h, ch) - max(y, 0.0))
30
+ return (iw * ih) / (cw * ch)
31
+
32
+
33
+ # ------------------------------------------------------------- S5 image census
34
+ def _key(box):
35
+ return (box['x'], box['y'], box['w'], box['h'])
36
+
37
+
38
+ def _close(a, b, eps=EPS_PX):
39
+ return all(abs(a[i] - b[i]) <= eps for i in range(4))
40
+
41
+
42
+ def _cluster(occs, eps=EPS_PX):
43
+ """Greedy epsilon clustering over occurrence boxes."""
44
+ clusters = []
45
+ for o in occs:
46
+ k = _key(o['box'])
47
+ for c in clusters:
48
+ if _close(k, c['rep']):
49
+ c['occs'].append(o)
50
+ break
51
+ else:
52
+ clusters.append({'rep': k, 'occs': [o]})
53
+ return clusters
54
+
55
+
56
+ def image_census(shape_recs, bg_images, units):
57
+ """Per-image (media, box, crop) occurrence inventory with the three logo signals."""
58
+ occ = defaultdict(list)
59
+ for r in shape_recs:
60
+ media = r.get('media')
61
+ if not media or not r.get('box'):
62
+ continue
63
+ occ[media].append({
64
+ 'part': r['part'], 'layer': r['layer'], 'via': 'pic',
65
+ 'box': r['box'], 'box_emu': r.get('box_emu'),
66
+ 'crop': r.get('crop'), 'placement': r.get('placement'),
67
+ 'w_pct': r.get('w_pct'), 'h_pct': r.get('h_pct'),
68
+ 'in_group': bool(r.get('group_path')), 'svg': r.get('media_svg'),
69
+ 'visible_instance_blocked': r.get('visible_instance_blocked'),
70
+ })
71
+ for r in shape_recs:
72
+ f = r.get('fill') or {}
73
+ if f.get('type') == 'image' and f.get('media') and r.get('box'):
74
+ occ[f['media']].append({
75
+ 'part': r['part'], 'layer': r['layer'], 'via': 'shape-fill',
76
+ 'box': r['box'], 'box_emu': r.get('box_emu'), 'crop': f.get('crop'),
77
+ 'placement': r.get('placement'), 'w_pct': r.get('w_pct'),
78
+ 'h_pct': r.get('h_pct'), 'in_group': bool(r.get('group_path')),
79
+ })
80
+ for b in bg_images:
81
+ occ[b['media']].append(b)
82
+
83
+ images = []
84
+ for media, occs in occ.items():
85
+ exact = Counter()
86
+ for o in occs:
87
+ exact[_key(o['box'])] += 1
88
+ clusters = []
89
+ for c in _cluster(occs):
90
+ boxes = [_key(o['box']) for o in c['occs']]
91
+ rep = Counter(boxes).most_common(1)[0][0]
92
+ rep_occ = next(o for o in c['occs'] if _key(o['box']) == rep)
93
+ clusters.append({
94
+ 'box': {'x': rep[0], 'y': rep[1], 'w': rep[2], 'h': rep[3]},
95
+ 'box_emu': rep_occ.get('box_emu'),
96
+ 'count': len(c['occs']),
97
+ 'exact_count': exact[rep],
98
+ 'exact_variants': len(set(boxes)),
99
+ 'parts': sorted({o['part'] for o in c['occs']}),
100
+ 'layers': sorted({o['layer'] for o in c['occs']}),
101
+ 'crops': sorted({_crop_sig(o.get('crop')) for o in c['occs']}),
102
+ 'w_pct': rep_occ.get('w_pct'), 'h_pct': rep_occ.get('h_pct'),
103
+ 'placement': rep_occ.get('placement'),
104
+ 'bleed': rep_occ.get('placement') == 'bleed',
105
+ 'in_group': any(o.get('in_group') for o in c['occs']),
106
+ })
107
+ clusters.sort(key=lambda c: -c['count'])
108
+ cw, ch = float(units.w), float(units.h)
109
+ fs = [o for o in occs if canvas_coverage(o.get('box'), cw, ch) >= FULLSCREEN_COVERAGE]
110
+ fs_clusters = [c for c in clusters
111
+ if canvas_coverage(c.get('box'), cw, ch) >= FULLSCREEN_COVERAGE]
112
+ crop_sigs = {_crop_sig(o.get('crop')) for o in occs} - {''}
113
+ images.append({
114
+ 'media': media,
115
+ 'n': len(occs),
116
+ 'boxes': clusters,
117
+ 'exact_boxes': [{'box': {'x': k[0], 'y': k[1], 'w': k[2], 'h': k[3]}, 'count': n}
118
+ for k, n in exact.most_common()],
119
+ 'fullscreen': bool(fs),
120
+ 'fullscreen_n': len(fs),
121
+ 'fullscreen_top_cluster_n': max((c['exact_count'] for c in fs_clusters), default=0),
122
+ 'repeat_fixed': [c['box'] for c in clusters if c['count'] >= REPEAT_MIN],
123
+ 'max_w_pct': max((o.get('w_pct') or 0) for o in occs),
124
+ 'bleed': any(o.get('placement') == 'bleed' for o in occs),
125
+ 'crop_variants': sorted(crop_sigs),
126
+ 'stitch_candidate': len(crop_sigs) > 1,
127
+ 'svg_companion': next((o.get('svg') for o in occs if o.get('svg')), None),
128
+ 'visible_instance_blocked': any(
129
+ o.get('visible_instance_blocked') for o in occs),
130
+ })
131
+ images.sort(key=lambda i: (-i['n'], i['media']))
132
+
133
+ # variant_group: different media occupying the same position (many-to-many).
134
+ pos = []
135
+ for img in images:
136
+ for c in img['boxes']:
137
+ k = _key(c['box'])
138
+ for p in pos:
139
+ if _close(k, p['rep']):
140
+ p['members'].append({'media': img['media'], 'count': c['count']})
141
+ break
142
+ else:
143
+ pos.append({'rep': k, 'box': dict(c['box']),
144
+ 'members': [{'media': img['media'], 'count': c['count']}]})
145
+ groups = []
146
+ for i, p in enumerate(pos):
147
+ if len({m['media'] for m in p['members']}) < 2:
148
+ continue
149
+ gid = 'vg%d' % (len(groups) + 1)
150
+ groups.append({'id': gid, 'box': p['box'],
151
+ 'members': sorted(p['members'], key=lambda m: -m['count'])})
152
+ by_media = defaultdict(list)
153
+ for g in groups:
154
+ for m in g['members']:
155
+ by_media[m['media']].append(g['id'])
156
+ for img in images:
157
+ img['variant_group'] = by_media.get(img['media'], [])
158
+ return images, groups
159
+
160
+
161
+ def _crop_sig(crop):
162
+ if not crop:
163
+ return ''
164
+ return ','.join('%s=%s' % (k, crop[k]) for k in sorted(crop))
165
+
166
+
167
+ # ------------------------------------------ S5b media content clustering (素材聚类)
168
+ # Two levels: sha256 byte identity, then perceptual identity. The perceptual level
169
+ # is a dHash *prefilter* followed by a pixel confirmation, because dHash alone does
170
+ # not separate them on its own: distinct images can land at hamming distance 0
171
+ # while identical ones land several bits apart, so no single hamming threshold
172
+ # splits the two populations. The hash therefore only narrows the candidate set
173
+ # and the thumbnail pixel difference makes the call.
174
+ DHASH_PREFILTER_MAX = 10 # hamming distance over the 64-bit dHash
175
+ PIXDIFF_MAX = 5.0 # mean per-channel |Δ| over the 64x64 thumbnail
176
+ THUMB_PX = 64
177
+
178
+
179
+ def _composite_on_white(im):
180
+ """Flatten alpha the way a slide renders it, so transparent padding cannot
181
+ masquerade as image content."""
182
+ from PIL import Image
183
+ if im.mode in ('RGBA', 'LA', 'P'):
184
+ im = im.convert('RGBA')
185
+ return Image.alpha_composite(Image.new('RGBA', im.size, (255, 255, 255, 255)),
186
+ im).convert('RGB')
187
+ return im.convert('RGB')
188
+
189
+
190
+ def _dhash(rgb):
191
+ """9x8 grayscale row-wise gradient hash -> 64 bits."""
192
+ from PIL import Image
193
+ g = rgb.convert('L').resize((9, 8), Image.LANCZOS)
194
+ px = list(g.getdata())
195
+ bits = 0
196
+ for r in range(8):
197
+ for c in range(8):
198
+ bits = (bits << 1) | (1 if px[r * 9 + c] > px[r * 9 + c + 1] else 0)
199
+ return bits
200
+
201
+
202
+ def media_fingerprints(pkg, medias, pillow_ok):
203
+ """sha256 (always) + dHash and thumbnails (Pillow only), per media part."""
204
+ import hashlib
205
+ out = {}
206
+ for m in sorted(set(medias)):
207
+ if not m or m not in pkg.names:
208
+ continue
209
+ raw = pkg.zip.read(m)
210
+ rec = {'sha256': hashlib.sha256(raw).hexdigest(), 'bytes': len(raw)}
211
+ if pillow_ok and not m.lower().endswith('.svg'):
212
+ try:
213
+ import io
214
+
215
+ from PIL import Image
216
+ im = Image.open(io.BytesIO(raw))
217
+ im.load()
218
+ rec['px'] = list(im.size)
219
+ rgb = _composite_on_white(im)
220
+ rec['phash'] = '%016x' % _dhash(rgb)
221
+ rec['_thumb_rgb'] = rgb.resize((THUMB_PX, THUMB_PX), Image.LANCZOS)
222
+ rec['_thumb_rgba'] = im.convert('RGBA').resize(
223
+ (THUMB_PX, THUMB_PX), Image.LANCZOS)
224
+ except Exception as exc:
225
+ rec['fingerprint_error'] = '%s: %s' % (exc.__class__.__name__, exc)
226
+ out[m] = rec
227
+ return out
228
+
229
+
230
+ def _pixdiff(a, b):
231
+ from PIL import ImageChops, ImageStat
232
+ st = ImageStat.Stat(ImageChops.difference(a, b))
233
+ return sum(st.mean) / 3.0
234
+
235
+
236
+ def content_clusters(images, fps):
237
+ """Assign every image row a `content_id`, and merge same-content media.
238
+
239
+ Returns the `media_clusters` table. Rows are mutated in place with
240
+ `content_id` / `phash` only — every pre-existing field is left untouched,
241
+ because verify_gates reads them.
242
+ """
243
+ medias = [i['media'] for i in images]
244
+ parent = {m: m for m in medias}
245
+
246
+ def find(x):
247
+ while parent[x] != x:
248
+ parent[x] = parent[parent[x]]
249
+ x = parent[x]
250
+ return x
251
+
252
+ def union(a, b):
253
+ ra, rb = find(a), find(b)
254
+ if ra != rb:
255
+ parent[max(ra, rb)] = min(ra, rb)
256
+
257
+ evidence = []
258
+ for i, a in enumerate(medias):
259
+ fa = fps.get(a) or {}
260
+ for b in medias[i + 1:]:
261
+ fb = fps.get(b) or {}
262
+ if fa.get('sha256') and fa['sha256'] == fb.get('sha256'):
263
+ union(a, b)
264
+ evidence.append({'a': a, 'b': b, 'level': 'sha256', 'dhash_distance': 0,
265
+ 'pixel_diff': 0.0})
266
+ continue
267
+ if not fa.get('phash') or not fb.get('phash'):
268
+ continue
269
+ d = bin(int(fa['phash'], 16) ^ int(fb['phash'], 16)).count('1')
270
+ if d > DHASH_PREFILTER_MAX:
271
+ continue
272
+ try:
273
+ pd = _pixdiff(fa['_thumb_rgb'], fb['_thumb_rgb'])
274
+ except Exception:
275
+ continue
276
+ if pd <= PIXDIFF_MAX:
277
+ union(a, b)
278
+ evidence.append({'a': a, 'b': b, 'level': 'perceptual',
279
+ 'dhash_distance': d, 'pixel_diff': round(pd, 2)})
280
+ else:
281
+ evidence.append({'a': a, 'b': b, 'level': 'rejected',
282
+ 'dhash_distance': d, 'pixel_diff': round(pd, 2)})
283
+
284
+ by_root = defaultdict(list)
285
+ for m in medias:
286
+ by_root[find(m)].append(m)
287
+ ids, clusters = {}, []
288
+ by_media = {i['media']: i for i in images}
289
+ for root in sorted(by_root, key=lambda r: (-len(by_root[r]), r)):
290
+ members = sorted(by_root[root])
291
+ cid = 'c%d' % (len(clusters) + 1)
292
+ for m in members:
293
+ ids[m] = cid
294
+ # Cluster-level repeat detection: the whole point of the clustering is
295
+ # that N pasted copies of one asset must count as N occurrences of one
296
+ # asset, so the epsilon merge runs across member media, not within one.
297
+ merged = []
298
+ for m in members:
299
+ for c in by_media[m]['boxes']:
300
+ k = _key(c['box'])
301
+ for mc in merged:
302
+ if _close(k, mc['rep']):
303
+ mc['count'] += c['count']
304
+ mc['media'].add(m)
305
+ break
306
+ else:
307
+ merged.append({'rep': k, 'box': dict(c['box']), 'count': c['count'],
308
+ 'media': {m}})
309
+ merged.sort(key=lambda c: -c['count'])
310
+ clusters.append({
311
+ 'content_id': cid,
312
+ 'members': members,
313
+ 'member_n': len(members),
314
+ 'sha256_identical': len({(fps.get(m) or {}).get('sha256') for m in members}) == 1,
315
+ 'phash': (fps.get(members[0]) or {}).get('phash'),
316
+ 'n': sum(by_media[m]['n'] for m in members),
317
+ 'boxes': [{'box': c['box'], 'count': c['count'],
318
+ 'media': sorted(c['media']), 'cross_media': len(c['media']) > 1}
319
+ for c in merged],
320
+ 'repeat_fixed': [c['box'] for c in merged if c['count'] >= REPEAT_MIN],
321
+ 'repeat_fixed_cross_media': [c['box'] for c in merged
322
+ if c['count'] >= REPEAT_MIN and len(c['media']) > 1],
323
+ 'fullscreen': any(by_media[m]['fullscreen'] for m in members),
324
+ })
325
+ for img in images:
326
+ img['content_id'] = ids.get(img['media'])
327
+ img['phash'] = (fps.get(img['media']) or {}).get('phash')
328
+ return clusters, evidence
329
+
330
+
331
+ # ------------------------------------------------------------ S14 image palette
332
+ PALETTE_TOP_N = 5
333
+ PALETTE_BUCKET_SHIFT = 4 # 16 levels per channel
334
+ PALETTE_ALPHA_MIN = 128
335
+
336
+
337
+ def image_palette(images, fps, exported):
338
+ """Pixel-level dominant colours + whole-image luminance for exported assets.
339
+
340
+ Sampled from the *original* bytes in the package, not the webp the transcoder
341
+ writes, so the palette does not inherit quality-ladder artefacts. Pixels below
342
+ PALETTE_ALPHA_MIN are dropped: a logo on a transparent bed would otherwise
343
+ report its padding as the dominant colour.
344
+ """
345
+ from ooxml import _lin
346
+ lut = [_lin(i) for i in range(256)]
347
+ for img in images:
348
+ if img['media'] not in exported:
349
+ continue
350
+ f = fps.get(img['media']) or {}
351
+ thumb = f.get('_thumb_rgba')
352
+ if thumb is None:
353
+ continue
354
+ buckets, lum, n = defaultdict(lambda: [0, 0, 0, 0]), 0.0, 0
355
+ for r, g, b, a in thumb.getdata():
356
+ if a < PALETTE_ALPHA_MIN:
357
+ continue
358
+ n += 1
359
+ lum += 0.2126 * lut[r] + 0.7152 * lut[g] + 0.0722 * lut[b]
360
+ k = (r >> PALETTE_BUCKET_SHIFT, g >> PALETTE_BUCKET_SHIFT,
361
+ b >> PALETTE_BUCKET_SHIFT)
362
+ acc = buckets[k]
363
+ acc[0] += 1
364
+ acc[1] += r
365
+ acc[2] += g
366
+ acc[3] += b
367
+ if not n:
368
+ img['dominant_colors'] = []
369
+ img['luminance'] = None
370
+ img['palette_note'] = 'fully transparent above alpha %d' % PALETTE_ALPHA_MIN
371
+ continue
372
+ top = sorted(buckets.values(), key=lambda v: -v[0])[:PALETTE_TOP_N]
373
+ img['dominant_colors'] = [
374
+ {'hex': '#%02X%02X%02X' % (round(c[1] / c[0]), round(c[2] / c[0]),
375
+ round(c[3] / c[0])),
376
+ 'pct': round(c[0] * 100.0 / n, 2)} for c in top]
377
+ img['luminance'] = round(lum / n, 4)
378
+ img['opaque_sample_px'] = n
379
+
380
+
381
+ # ------------------------------------------------- S6 colour frequency (resolved)
382
+ # Declared XPath range: colours counted only when reachable through one of these
383
+ # containers. `p15:clr` -> editor, `a:buClr` / styleRef -> aux, everything else design.
384
+ DESIGN_VIA = ('solidFill', 'gs', 'bgRef')
385
+ EDITOR_VIA = ('clr',) # p15:clr (guides)
386
+ AUX_VIA = ('buClr', 'fillRef', 'lnRef', 'effectRef', 'fontRef')
387
+ COLOR_TAGS = {'srgbClr', 'schemeClr', 'sysClr', 'prstClr', 'scrgbClr', 'hslClr'}
388
+
389
+
390
+ def _scan_colors(el, ctx_stack, sink):
391
+ tag = local(el.tag)
392
+ if tag in COLOR_TAGS:
393
+ cls = None
394
+ for anc in reversed(ctx_stack):
395
+ if anc in EDITOR_VIA:
396
+ cls = 'editor'
397
+ break
398
+ if anc in AUX_VIA:
399
+ cls = 'aux'
400
+ break
401
+ if anc in DESIGN_VIA:
402
+ cls = 'design'
403
+ break
404
+ if cls:
405
+ sink.append((el, cls))
406
+ return
407
+ ctx_stack.append(tag)
408
+ for ch in el:
409
+ _scan_colors(ch, ctx_stack, sink)
410
+ ctx_stack.pop()
411
+
412
+
413
+ def color_census(pkg, part_ctxs):
414
+ """Counts keyed on the *resolved* hex/rgba (schemeClr -> clrMap -> clrScheme)."""
415
+ agg = OrderedDict()
416
+ raw_rows = []
417
+ for ctx in part_ctxs:
418
+ sink = []
419
+ _scan_colors(pkg.xml(ctx.part), [], sink)
420
+ for el, cls in sink:
421
+ raw = read_color(el)
422
+ res = resolve_color(raw, ctx.clrmap, ctx.clrscheme)
423
+ if not res:
424
+ continue
425
+ key = res.get('resolved') or ('UNRESOLVED:' + str(res.get('unresolved')))
426
+ e = agg.setdefault(key, {'resolved': key, 'hex': res.get('hex'),
427
+ 'alpha': res.get('alpha'), 'n': 0,
428
+ 'class': cls, 'layers': Counter(), 'raw': Counter()})
429
+ e['n'] += 1
430
+ e['layers'][ctx.layer] += 1
431
+ e['raw'][res['raw']] += 1
432
+ # design evidence wins over aux/editor if a colour appears in both roles
433
+ if cls == 'design':
434
+ e['class'] = 'design'
435
+ raw_rows.append({'part': ctx.part, 'layer': ctx.layer, 'class': cls,
436
+ 'raw': res['raw'], 'resolved': key})
437
+ out = []
438
+ for e in agg.values():
439
+ out.append({'resolved': e['resolved'], 'hex': e['hex'], 'alpha': e['alpha'],
440
+ 'n': e['n'], 'class': e['class'],
441
+ 'layers': dict(e['layers']),
442
+ 'raw': [r for r, _ in e['raw'].most_common()],
443
+ 'raw_counts': dict(e['raw'])})
444
+ out.sort(key=lambda e: (-e['n'], e['resolved']))
445
+ return out, raw_rows
446
+
447
+
448
+ # ------------------------------------------------------------ S6 font clustering
449
+ FONT_REF_RE = re.compile(r'^\+(mj|mn)-(lt|ea|cs)$')
450
+ FONT_REF_KIND = {'mj': 'majorFont', 'mn': 'minorFont'}
451
+ FONT_REF_SLOT = {'lt': 'latin', 'ea': 'ea', 'cs': 'cs'}
452
+
453
+
454
+ def font_scheme_by_part(pkg, graph, theme_of_master):
455
+ """part -> 该 part 所在母版链绑定 theme 的 fontScheme。
456
+
457
+ `+mj-lt` 之类占位符要解析成实名就得知道「这个形状属于哪条母版链」,
458
+ 与 schemeClr 走 clrMap→clrScheme 是同一条依赖。
459
+ """
460
+ of_master = {mp: (theme_of_master.get(mp) or {}).get('fontScheme') or {}
461
+ for mp in graph['master_order']}
462
+ out = dict(of_master)
463
+ for lp in pkg.layouts:
464
+ out[lp] = of_master.get(graph['master_of_layout'].get(lp), {})
465
+ for sp in pkg.slides:
466
+ layout = graph['layout_of_slide'].get(sp)
467
+ out[sp] = of_master.get(graph['master_of_layout'].get(layout), {})
468
+ return out
469
+
470
+
471
+ def resolve_font_ref(raw, scheme):
472
+ """`+mj-lt` → fontScheme 实名。返回 (face, ref, status)。
473
+
474
+ 与颜色一致:以解析后的实名计数。三种结局要分开,否则第三种会把非字体塞进字体表:
475
+ plain —— 不是占位符
476
+ resolved —— 解析到实名
477
+ empty —— 主题里该槽位显式为空串(`<a:cs typeface=""/>`,合法的「不指定」)
478
+ unresolved —— 压根没有可用 fontScheme / 无该槽位,才保留占位符并标注
479
+ """
480
+ m = FONT_REF_RE.match(raw or '')
481
+ if not m:
482
+ return raw, None, 'plain'
483
+ kind = (scheme or {}).get(FONT_REF_KIND[m.group(1)])
484
+ slot = FONT_REF_SLOT[m.group(2)]
485
+ if not isinstance(kind, dict) or slot not in kind:
486
+ return None, raw, 'unresolved'
487
+ face = kind[slot]
488
+ return (face, raw, 'resolved') if face else (None, raw, 'empty')
489
+
490
+
491
+ def font_census(shape_recs, txstyles_by_master, themes, scheme_by_part=None):
492
+ fams = {}
493
+ theme_faces = set()
494
+ for t in themes:
495
+ for kind in ('majorFont', 'minorFont'):
496
+ for face in (t.get('fontScheme', {}).get(kind) or {}).values():
497
+ if face:
498
+ theme_faces.add(face)
499
+
500
+ def add(raw, layer, slot, source, scheme, bold=False):
501
+ if not raw:
502
+ return
503
+ face, ref, status = resolve_font_ref(raw, scheme)
504
+ if status == 'empty':
505
+ return # 主题显式不指定该槽位,等同于没有声明过
506
+ if status == 'unresolved':
507
+ # Keep the placeholder as its own family rather than dropping it, so
508
+ # a broken theme binding is visible instead of silent.
509
+ face = ref
510
+ family, weight, italic = family_of(face)
511
+ e = fams.setdefault(family, {'family': family, 'n': 0, 'rendered': 0,
512
+ 'variants': OrderedDict(), 'positions': Counter(),
513
+ 'slots': Counter(), 'sources': Counter(),
514
+ 'theme_refs': Counter(), 'unresolved_ref': False,
515
+ 'italic': False, 'bold_runs': 0})
516
+ e['n'] += 1
517
+ if source != 'pPr_empty':
518
+ e['rendered'] += 1
519
+ e['positions'][layer] += 1
520
+ e['slots'][slot] += 1
521
+ e['sources'][source] += 1
522
+ e['italic'] = e['italic'] or italic
523
+ if ref:
524
+ e['theme_refs'][ref] += 1
525
+ if face == ref:
526
+ e['unresolved_ref'] = True
527
+ if bold:
528
+ e['bold_runs'] += 1
529
+ # weight comes from the font *name* only — it is the sole 字重 source; a b="1"
530
+ # flag is a separate signal and is counted apart so L4 can tell them apart.
531
+ v = e['variants'].setdefault(face, {'raw': face, 'weight': weight, 'n': 0,
532
+ 'bold_runs': 0, 'truncated': len(face) == 31})
533
+ v['n'] += 1
534
+ if bold:
535
+ v['bold_runs'] += 1
536
+
537
+ def visit_rpr(d, layer, source, scheme, skip=()):
538
+ bold = bool(d.get('bold'))
539
+ for slot in ('latin', 'ea', 'cs'):
540
+ if d.get(slot) and slot not in skip:
541
+ add(d[slot], layer, slot, source, scheme, bold)
542
+
543
+ for r in shape_recs:
544
+ layer = r['layer']
545
+ scheme = (scheme_by_part or {}).get(r['part'], {})
546
+ text = r.get('text') or {}
547
+ for lvl in (text.get('lstStyle') or {}).values():
548
+ visit_rpr(lvl, layer, 'lstStyle', scheme)
549
+ for p in text.get('paragraphs', []):
550
+ runs = [run for run in p.get('runs', []) if not run.get('empty_para')]
551
+ for run in p.get('runs', []):
552
+ visit_rpr(run, layer, 'run', scheme)
553
+ # a:p/a:pPr/a:defRPr supplies this paragraph's run defaults, per slot:
554
+ # a run declaring `latin` does not suppress the paragraph's `ea`.
555
+ # A paragraph with no runs at all (only <a:endParaRPr/>) declares a
556
+ # default that renders no glyph, so it is counted under its own source
557
+ # and kept out of `rendered_n` — otherwise a face backing zero visible
558
+ # text can outrank the deck's actual typeface.
559
+ dr = p.get('defRPr') or {}
560
+ if dr:
561
+ covered = {slot for slot in ('latin', 'ea', 'cs')
562
+ if any(run.get(slot) for run in runs)}
563
+ visit_rpr(dr, layer, 'pPr' if runs else 'pPr_empty', scheme, skip=covered)
564
+ for master, ts in (txstyles_by_master or {}).items():
565
+ scheme = (scheme_by_part or {}).get(master, {})
566
+ for lvls in (ts or {}).values():
567
+ for lvl in lvls.values():
568
+ visit_rpr(lvl, 'master', 'txStyles', scheme)
569
+
570
+ out = []
571
+ for e in fams.values():
572
+ variants = sorted(e['variants'].values(), key=lambda v: -v['n'])
573
+ weights = sorted({v['weight'] for v in variants if v['weight']})
574
+ row = {'family': e['family'], 'n': e['n'], 'rendered_n': e['rendered'],
575
+ 'variants': variants, 'weights': weights,
576
+ 'bold_runs': e['bold_runs'],
577
+ 'positions': dict(e['positions']), 'slots': dict(e['slots']),
578
+ 'sources': dict(e['sources']), 'italic': e['italic'],
579
+ 'alias_group': alias_group(e['family']),
580
+ 'in_theme': any(v['raw'] in theme_faces for v in variants)}
581
+ if e['theme_refs']:
582
+ row['theme_refs'] = dict(e['theme_refs'])
583
+ if e['unresolved_ref']:
584
+ row['unresolved_theme_ref'] = True
585
+ if not e['rendered']:
586
+ row['renders_no_text'] = True
587
+ out.append(row)
588
+ # rendered_n leads the sort so a face declared only on empty paragraphs cannot
589
+ # outrank one that actually sets type. For families without such declarations
590
+ # rendered_n == n, so the existing order is unchanged.
591
+ out.sort(key=lambda e: (-e['rendered_n'], -e['n'], e['family']))
592
+ return out
593
+
594
+
595
+ # --------------------------------------------------------- S7 layout inventory
596
+ def _ph_signature(shapes, part):
597
+ sig = []
598
+ for r in shapes:
599
+ if r['part'] != part or not r.get('ph'):
600
+ continue
601
+ b = r.get('box')
602
+ sig.append((r['ph']['type'],
603
+ tuple(round((b or {}).get(k, -1) / 5.0) for k in ('x', 'y', 'w', 'h'))))
604
+ return tuple(sorted(sig))
605
+
606
+
607
+ def layout_inventory(pkg, graph, shapes, bg_by_part):
608
+ rows = []
609
+ for lp in pkg.layouts:
610
+ root = pkg.xml(lp)
611
+ cSld = root.find('p:cSld', NS)
612
+ master = graph['master_of_layout'].get(lp)
613
+ background = bg_by_part.get(lp) or bg_by_part.get(master)
614
+ phs = Counter()
615
+ for r in shapes:
616
+ if r['part'] == lp and r.get('ph'):
617
+ phs[r['ph']['type']] += 1
618
+ rows.append({
619
+ 'part': lp,
620
+ 'name': cSld.get('name') if cSld is not None else None,
621
+ 'type_attr': root.get('type', 'cust'),
622
+ 'master': master,
623
+ 'used_by_slides': graph['slides_per_layout'].get(lp, 0),
624
+ 'placeholders': dict(phs),
625
+ 'shape_n': sum(1 for r in shapes if r['part'] == lp),
626
+ 'background': background,
627
+ 'background_source': lp if bg_by_part.get(lp) else master,
628
+ 'ph_signature': _ph_signature(shapes, lp),
629
+ 'guides': [],
630
+ })
631
+ return rows
632
+
633
+
634
+ def detect_twins(rows):
635
+ """跨母版孪生检测 (S7, runs before master triage): name match first, geometry fallback."""
636
+ pairs, by_name = [], defaultdict(list)
637
+ for r in rows:
638
+ by_name[(r['name'] or '').strip()].append(r)
639
+ for name, group in by_name.items():
640
+ if not name or len(group) < 2:
641
+ continue
642
+ masters = {r['master'] for r in group}
643
+ if len(masters) < 2:
644
+ continue
645
+ base = group[0]
646
+ for other in group[1:]:
647
+ if other['master'] == base['master']:
648
+ continue
649
+ pairs.append({'a': base['part'], 'b': other['part'], 'name': name,
650
+ 'match': 'name',
651
+ 'geometry_match': base['ph_signature'] == other['ph_signature']})
652
+ if not pairs:
653
+ by_sig = defaultdict(list)
654
+ for r in rows:
655
+ if r['ph_signature']:
656
+ by_sig[r['ph_signature']].append(r)
657
+ for sig, group in by_sig.items():
658
+ masters = {r['master'] for r in group}
659
+ if len(group) < 2 or len(masters) < 2:
660
+ continue
661
+ base = group[0]
662
+ for other in group[1:]:
663
+ if other['master'] != base['master']:
664
+ pairs.append({'a': base['part'], 'b': other['part'],
665
+ 'name': base['name'], 'match': 'geometry',
666
+ 'geometry_match': True})
667
+ paired = {p['a'] for p in pairs} | {p['b'] for p in pairs}
668
+ return pairs, sorted(r['part'] for r in rows if r['part'] not in paired)
669
+
670
+
671
+ # ------------------------------------------------------------------- S8 guides
672
+ def read_guides(pkg, units, parts):
673
+ """p:extLst/p15:sldGuideLst on presentation.xml and each slideLayout.
674
+ pos is 1/8 pt. Master level is checked too, purely to evidence that it is empty."""
675
+ out = []
676
+ for part in parts:
677
+ if part not in pkg.names:
678
+ continue
679
+ root = pkg.xml(part)
680
+ for g in root.iter('{%s}guide' % NS['p15']):
681
+ rec = {'part': part, 'orient': g.get('orient', 'vert'),
682
+ 'pos_eighth_pt': int(g.get('pos', 0)),
683
+ 'px': units.eighth_pt(g.get('pos', 0))}
684
+ clr = g.find('p15:clr', NS)
685
+ if clr is not None:
686
+ for ch in clr:
687
+ c = resolve_color(read_color(ch))
688
+ if c:
689
+ rec['color'] = c.get('hex')
690
+ break
691
+ out.append(rec)
692
+ return out
693
+
694
+
695
+ # --------------------------------------------------------- S13 theme topology
696
+ def theme_topology(graph, triage, themes_by_part, clrmap_by_master, bg_by_part, twin_pairs):
697
+ masters = [m['part'] for m in triage['masters'] if m['picked']]
698
+ labels, detail = OrderedDict(), []
699
+ for mp in masters:
700
+ cm = clrmap_by_master.get(mp, {})
701
+ theme = themes_by_part.get(graph['theme_of_master'].get(mp), {})
702
+ scheme = theme.get('clrScheme', {})
703
+ bg = bg_by_part.get(mp) or {}
704
+ bg_hex = ((bg.get('color') or {}).get('hex')
705
+ or scheme.get(cm.get('bg1', 'lt1')))
706
+ lum = luminance(bg_hex) if bg_hex else None
707
+ label = ('dark' if lum is not None and lum < 0.5 else 'light') if bg_hex else None
708
+ detail.append({'master': mp, 'clrMap': cm, 'bg_hex': bg_hex,
709
+ 'bg_luminance': round(lum, 4) if lum is not None else None,
710
+ 'theme_label': label,
711
+ 'bg1_slot': cm.get('bg1'), 'tx1_slot': cm.get('tx1')})
712
+ if label:
713
+ labels.setdefault(label, mp)
714
+
715
+ inversion = []
716
+ for i, a in enumerate(detail):
717
+ for b in detail[i + 1:]:
718
+ ca, cb = a['clrMap'], b['clrMap']
719
+ if not ca or not cb:
720
+ continue
721
+ swapped = [k for k in ('bg1', 'tx1', 'bg2', 'tx2')
722
+ if ca.get(k) and cb.get(k) and ca.get(k) != cb.get(k)]
723
+ pairwise = (ca.get('bg1') == cb.get('tx1') and ca.get('tx1') == cb.get('bg1'))
724
+ if swapped and pairwise:
725
+ inversion.append({'a': a['master'], 'b': b['master'], 'swapped_slots': swapped})
726
+
727
+ if inversion:
728
+ mechanism = 'clrmap-inversion'
729
+ elif twin_pairs and len(labels) > 1:
730
+ mechanism = 'twin-layouts'
731
+ else:
732
+ mechanism = 'single'
733
+ theme_list = list(labels.keys()) if len(labels) > 1 else ['single']
734
+ if mechanism == 'single':
735
+ theme_list = ['single']
736
+ return {
737
+ 'themes': theme_list,
738
+ 'mechanism': mechanism,
739
+ 'default': (list(labels.items())[0][0] if len(labels) > 1 else 'single'),
740
+ 'clrmap_by_master': {m: clrmap_by_master.get(m, {}) for m in masters},
741
+ 'per_master': detail,
742
+ 'inversion_pairs': inversion,
743
+ 'twin_pair_n': len(twin_pairs),
744
+ }
745
+
746
+
747
+ # ------------------------------------- derived censuses (text/spacing/radii/fx)
748
+ def text_scale(shape_recs, txstyles_by_master):
749
+ agg = {}
750
+
751
+ def add(sz, layer, source, d):
752
+ if not sz:
753
+ return
754
+ e = agg.setdefault(sz, {'sz_px': sz, 'n': 0, 'layers': Counter(),
755
+ 'sources': Counter(), 'weights': Counter(),
756
+ 'bold': 0, 'lnSpc': Counter()})
757
+ e['n'] += 1
758
+ e['layers'][layer] += 1
759
+ e['sources'][source] += 1
760
+ if d.get('weight'):
761
+ e['weights'][d['weight']] += 1
762
+ if d.get('bold'):
763
+ e['bold'] += 1
764
+
765
+ for r in shape_recs:
766
+ layer = r['layer']
767
+ text = r.get('text') or {}
768
+ for lvl in (text.get('lstStyle') or {}).values():
769
+ add(lvl.get('sz_px'), layer, 'lstStyle', lvl)
770
+ if lvl.get('sz_px') and lvl.get('lnSpc', {}).get('mult'):
771
+ agg[lvl['sz_px']]['lnSpc'][lvl['lnSpc']['mult']] += 1
772
+ for p in text.get('paragraphs', []):
773
+ mult = (p.get('lnSpc') or {}).get('mult')
774
+ runs = [r for r in p.get('runs', []) if not r.get('empty_para')]
775
+ sized = 0
776
+ for run in runs:
777
+ add(run.get('sz_px'), layer, 'run', run)
778
+ if run.get('sz_px'):
779
+ sized += 1
780
+ if mult:
781
+ agg[run['sz_px']]['lnSpc'][mult] += 1
782
+ # a:p/a:pPr/a:defRPr is the default for this paragraph's runs, so it
783
+ # only takes effect where no run overrides it. Counting it alongside
784
+ # an explicit run size would double-count one piece of text.
785
+ dr = p.get('defRPr') or {}
786
+ if runs and not sized and dr.get('sz_px'):
787
+ add(dr['sz_px'], layer, 'pPr', dr)
788
+ if mult:
789
+ agg[dr['sz_px']]['lnSpc'][mult] += 1
790
+ for ts in (txstyles_by_master or {}).values():
791
+ for lvls in (ts or {}).values():
792
+ for lvl in lvls.values():
793
+ add(lvl.get('sz_px'), 'master', 'txStyles', lvl)
794
+
795
+ out = [{'sz_px': e['sz_px'], 'n': e['n'], 'layers': dict(e['layers']),
796
+ 'sources': dict(e['sources']), 'weights': dict(e['weights']),
797
+ 'bold_runs': e['bold'],
798
+ 'line_height_mult': dict(e['lnSpc'].most_common())}
799
+ for e in agg.values()]
800
+ out.sort(key=lambda e: -e['sz_px'])
801
+ return out
802
+
803
+
804
+ def spacing_candidates(shape_recs, units, top=40):
805
+ W, H = units.w, units.h
806
+ pads = Counter()
807
+ gaps = Counter()
808
+ by_part = defaultdict(list)
809
+ for r in shape_recs:
810
+ b = r.get('box')
811
+ if not b or r.get('placement') not in ('inside', 'bleed'):
812
+ continue
813
+ if (r.get('w_pct') or 0) >= FULLSCREEN_MIN_PCT and (r.get('h_pct') or 0) >= FULLSCREEN_MIN_PCT:
814
+ continue
815
+ if r.get('depth'):
816
+ continue
817
+ by_part[r['part']].append(b)
818
+ for name, v, span in (('left', b['x'], W), ('top', b['y'], H),
819
+ ('right', W - (b['x'] + b['w']), W),
820
+ ('bottom', H - (b['y'] + b['h']), H)):
821
+ if 0 <= v <= span * 0.4:
822
+ pads[(name, int(round(v)))] += 1
823
+ for boxes in by_part.values():
824
+ for axis, pos, size, cross, cross_size in (('v', 'y', 'h', 'x', 'w'),
825
+ ('h', 'x', 'w', 'y', 'h')):
826
+ ordered = sorted(boxes, key=lambda b: b[pos])
827
+ for a, b2 in zip(ordered, ordered[1:]):
828
+ if a[cross] + a[cross_size] <= b2[cross] or b2[cross] + b2[cross_size] <= a[cross]:
829
+ continue
830
+ g = b2[pos] - (a[pos] + a[size])
831
+ if 0 < g <= 400:
832
+ gaps[(axis, int(round(g)))] += 1
833
+ return {
834
+ 'paddings': [{'edge': k[0], 'px': k[1], 'n': n}
835
+ for k, n in pads.most_common() if n >= 2][:top],
836
+ 'gaps': [{'axis': k[0], 'px': k[1], 'n': n}
837
+ for k, n in gaps.most_common() if n >= 2][:top],
838
+ 'grids': fit_grids(shape_recs),
839
+ }
840
+
841
+
842
+ # ------------------------------------------------------- 重复网格拟合(栅格)
843
+ GRID_MIN_CELLS = 3 # 少于 3 格谈不上"栅格"
844
+ GRID_TOL_PX = 6.0 # 中心归并容差:同列的元素中心允许这点抖动
845
+ GRID_PITCH_STDEV_MAX = 2.0 # 步距标准差超过它就不算规整
846
+
847
+
848
+ def _cluster_1d(vals, tol=GRID_TOL_PX):
849
+ """一维贪心聚类,返回按值排序的簇。"""
850
+ out = []
851
+ for v in sorted(vals):
852
+ if out and v - out[-1][-1] <= tol:
853
+ out[-1].append(v)
854
+ else:
855
+ out.append([v])
856
+ return out
857
+
858
+
859
+ def _axis_fit(centers, edges):
860
+ """一轴的列/行拟合。centers 决定分档,edges 给出该档的起始边(供 slot 用)。"""
861
+ groups = _cluster_1d(centers)
862
+ if len(groups) < 2:
863
+ return None
864
+ idx, cur = {}, 0
865
+ for g in groups:
866
+ for v in g:
867
+ idx[v] = cur
868
+ cur += 1
869
+ means = [sum(g) / len(g) for g in groups]
870
+ diffs = [b - a for a, b in zip(means, means[1:])]
871
+ pitch = sum(diffs) / len(diffs)
872
+ var = sum((d - pitch) ** 2 for d in diffs) / len(diffs)
873
+ sd = var ** 0.5
874
+ starts = [None] * len(groups)
875
+ for c, e in zip(centers, edges):
876
+ i = idx[c]
877
+ starts[i] = e if starts[i] is None else min(starts[i], e)
878
+ # 只有 2 档时全轴只有 1 个步距,方差恒为 0——这种"规整"是算法产物不是事实,
879
+ # 至少 3 档(2 个步距)才谈得上验证步距一致性。
880
+ return {'n': len(groups), 'centers': [round(m, 1) for m in means],
881
+ 'starts': [round(s, 1) for s in starts],
882
+ 'pitch': round(pitch, 1), 'pitch_stdev': round(sd, 2),
883
+ 'regular': sd <= GRID_PITCH_STDEV_MAX and len(groups) >= 3}
884
+
885
+
886
+ def fit_grids(shape_recs):
887
+ """逐页把同类形状拟合成栅格:列数/列起点/列步距 + 行数/行步距。
888
+
889
+ 按**中心**分档而不是按左上角——一排 logo 尺寸各不相同却居中对齐于等宽格,
890
+ 用左上角看不出列。
891
+ 因此这里也不要求同尺寸,只要求同页同 kind 同层级。
892
+ """
893
+ buckets = defaultdict(list)
894
+ for r in shape_recs:
895
+ b = r.get('box')
896
+ if not b or r.get('placement') not in ('inside', 'bleed'):
897
+ continue
898
+ if not b.get('w') or not b.get('h'):
899
+ continue
900
+ # 满屏底图不参与栅格(与 spacing_candidates 同口径):它和页面上的小图标
901
+ # 同属 pic、同页,会被凑成一个「2 列」的假栅格。
902
+ if ((r.get('w_pct') or 0) >= FULLSCREEN_MIN_PCT
903
+ and (r.get('h_pct') or 0) >= FULLSCREEN_MIN_PCT):
904
+ continue
905
+ buckets[(r['part'], r['kind'], r.get('depth', 0))].append(b)
906
+ out = []
907
+ for (part, kind, depth), boxes in buckets.items():
908
+ if len(boxes) < GRID_MIN_CELLS:
909
+ continue
910
+ cx = [b['x'] + b['w'] / 2.0 for b in boxes]
911
+ cy = [b['y'] + b['h'] / 2.0 for b in boxes]
912
+ cols = _axis_fit(cx, [b['x'] for b in boxes])
913
+ rows = _axis_fit(cy, [b['y'] for b in boxes])
914
+ keep = [a for a in (cols, rows) if a and a['regular']]
915
+ if not keep:
916
+ continue
917
+ # 至少一轴规整,且格子数够,才算拟合成功
918
+ if (cols['n'] if cols else 1) * (rows['n'] if rows else 1) < GRID_MIN_CELLS:
919
+ continue
920
+ e = {'part': part, 'kind': kind, 'depth': depth, 'n': len(boxes)}
921
+ if cols:
922
+ e['cols'] = cols
923
+ if rows:
924
+ e['rows'] = rows
925
+ if cols and rows:
926
+ e['cells'] = cols['n'] * rows['n']
927
+ e['filled'] = len(boxes)
928
+ w = [b['w'] for b in boxes]
929
+ h = [b['h'] for b in boxes]
930
+ e['item_w'] = [round(min(w), 1), round(max(w), 1)]
931
+ e['item_h'] = [round(min(h), 1), round(max(h), 1)]
932
+ out.append(e)
933
+ out.sort(key=lambda e: (-e['n'], e['part']))
934
+ return out
935
+
936
+
937
+ NEGATIVE_EVIDENCE_EFFECTS = ('outerShdw', 'innerShdw', 'glow', 'reflection', 'softEdge', 'blur')
938
+
939
+
940
+ def radii_effects_census(shape_recs):
941
+ radii = Counter()
942
+ prst = Counter()
943
+ fx = Counter()
944
+ grads = 0
945
+ alphas = Counter()
946
+ for r in shape_recs:
947
+ if r.get('radius_px') is not None:
948
+ radii[r['radius_px']] += 1
949
+ if r.get('geom'):
950
+ prst[r['geom']['prst']] += 1
951
+ for e in (r.get('effects') or []):
952
+ fx[e['type']] += 1
953
+ f = r.get('fill') or {}
954
+ if f.get('type') == 'gradient':
955
+ grads += 1
956
+ col = f.get('color') or {}
957
+ if col.get('alpha') is not None and col['alpha'] < 100:
958
+ alphas[col['alpha']] += 1
959
+ effects = {k: fx.get(k, 0) for k in NEGATIVE_EVIDENCE_EFFECTS}
960
+ for k, v in fx.items():
961
+ effects.setdefault(k, v)
962
+ return (
963
+ [{'px': px, 'n': n} for px, n in sorted(radii.items(), key=lambda kv: -kv[1])],
964
+ {'prst_geom': dict(prst.most_common()), 'gradient_fills': grads,
965
+ 'translucent_fills': {str(k): v for k, v in alphas.most_common()}},
966
+ effects,
967
+ )