@lark-apaas/coding-steering 0.1.32-beta.0 → 0.1.32-dev.5abff3b

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 (58) hide show
  1. package/package.json +6 -6
  2. package/steering/design-html/skills/charts/SKILL.md +4 -0
  3. package/steering/design-html/skills/pptx-style-extract/SKILL.md +64 -26
  4. package/steering/design-html/skills/pptx-style-extract/font-fallback.yaml +3 -3
  5. package/steering/design-html/skills/pptx-style-extract/scripts/census.py +18 -12
  6. package/steering/design-html/skills/pptx-style-extract/scripts/check_v2.py +153 -8
  7. package/steering/design-html/skills/pptx-style-extract/scripts/draft.py +2735 -288
  8. package/steering/design-html/skills/pptx-style-extract/scripts/extract.py +325 -22
  9. package/steering/design-html/skills/pptx-style-extract/scripts/ooxml.py +19 -2
  10. package/steering/design-html/skills/pptx-style-extract/scripts/package.py +991 -165
  11. package/steering/design-html/skills/pptx-style-extract/scripts/parts.py +6 -3
  12. package/steering/design-html/skills/pptx-style-extract/scripts/query.py +4 -9
  13. package/steering/design-html/skills/pptx-style-extract/scripts/render_pages.py +16 -10
  14. package/steering/design-html/skills/pptx-style-extract/scripts/test_asset_judgment_package.py +443 -0
  15. package/steering/design-html/skills/pptx-style-extract/scripts/test_background_composite.py +57 -0
  16. package/steering/design-html/skills/pptx-style-extract/scripts/test_color_contract.py +60 -0
  17. package/steering/design-html/skills/pptx-style-extract/scripts/test_design_consumer_contract.py +63 -0
  18. package/steering/design-html/skills/pptx-style-extract/scripts/test_flow_layout_contract.py +528 -0
  19. package/steering/design-html/skills/pptx-style-extract/scripts/test_layout_css.py +1513 -0
  20. package/steering/design-html/skills/pptx-style-extract/scripts/test_rounded_contract.py +112 -0
  21. package/steering/design-html/skills/pptx-style-extract/scripts/test_text_role_contract.py +315 -0
  22. package/steering/design-html/skills/pptx-style-extract/v2-format-spec.md +27 -15
  23. package/steering/design-html/skills/preflight/scripts/probe.sh +0 -0
  24. package/steering/nestjs-react-fullstack/skills/app-init-feasibility-guide/SKILL.md +1 -0
  25. package/steering/nestjs-react-fullstack/skills/authn-guide/SKILL.md +6 -0
  26. package/steering/nestjs-react-fullstack/skills/authz-guide/SKILL.md +5 -5
  27. package/steering/nestjs-react-fullstack/skills/authz-guide/references/dynamic-permission-guide.md +1 -1
  28. package/steering/nestjs-react-fullstack/skills/client-builtins-file-storage-service/SKILL.md +37 -113
  29. package/steering/nestjs-react-fullstack/skills/client-builtins-user-service/SKILL.md +13 -2
  30. package/steering/nestjs-react-fullstack/skills/code-fix/SKILL.md +7 -7
  31. package/steering/nestjs-react-fullstack/skills/coding-guide/SKILL.md +149 -24
  32. package/steering/nestjs-react-fullstack/skills/connections-sdk/SKILL.md +202 -0
  33. package/steering/nestjs-react-fullstack/skills/nestjs-cache/SKILL.md +255 -0
  34. package/steering/nestjs-react-fullstack/skills/plugin-guide/SKILL.md +158 -543
  35. package/steering/nestjs-react-fullstack/skills/plugin-guide/references/plugin-coding-guide.md +15 -1
  36. package/steering/nestjs-react-fullstack/skills/plugin-guide/references/table.md +30 -14
  37. package/steering/nestjs-react-fullstack/skills/raw-sql-boundary-audit/SKILL.md +63 -0
  38. package/steering/nestjs-react-fullstack/skills/server-builtins-file-storage-service/SKILL.md +1 -1
  39. package/steering/nestjs-react-fullstack/skills_common/trigger-guide/SKILL.md +284 -12
  40. package/steering/nestjs-react-fullstack/skills_local/plugin-guide/SKILL.md +4 -0
  41. package/steering/vite-react/skills/plugin-guide/SKILL.md +3 -1
  42. package/steering/vite-react/skills/react-three-fiber/SKILL.md +4 -0
  43. package/steering/nestjs-react-fullstack/skills/client-add-aily-web-chat/SKILL.md +0 -139
  44. package/steering/nestjs-react-fullstack/skills/feishu/SKILL.md +0 -269
  45. package/steering/nestjs-react-fullstack/skills/feishu/references/approval.md +0 -214
  46. package/steering/nestjs-react-fullstack/skills/feishu/references/attendance.md +0 -163
  47. package/steering/nestjs-react-fullstack/skills/feishu/references/bitable.md +0 -311
  48. package/steering/nestjs-react-fullstack/skills/feishu/references/calendar.md +0 -190
  49. package/steering/nestjs-react-fullstack/skills/feishu/references/contacts.md +0 -160
  50. package/steering/nestjs-react-fullstack/skills/feishu/references/doc.md +0 -257
  51. package/steering/nestjs-react-fullstack/skills/feishu/references/drive.md +0 -104
  52. package/steering/nestjs-react-fullstack/skills/feishu/references/events.md +0 -199
  53. package/steering/nestjs-react-fullstack/skills/feishu/references/id-convert.md +0 -128
  54. package/steering/nestjs-react-fullstack/skills/feishu/references/messaging.md +0 -207
  55. package/steering/nestjs-react-fullstack/skills/feishu/references/oauth.md +0 -165
  56. package/steering/nestjs-react-fullstack/skills/feishu/references/perm.md +0 -91
  57. package/steering/nestjs-react-fullstack/skills/feishu/references/wiki.md +0 -165
  58. package/steering/nestjs-react-fullstack/skills_common/trigger-guide/references/trigger-lifecycle.md +0 -301
@@ -5,26 +5,69 @@
5
5
 
6
6
  产出 <stage1-outdir>/l-out/:
7
7
  BRIEF.md 唯一必读简报:事实 + 草案依据 + 待判断清单
8
- contact-sheet.png 候选图拼版(带编号,一次看完所有图)
9
- manifest.yaml / frontmatter.yaml / layouts.yaml / body.md 四件草案,可直接进 package.py
8
+ vision-group-*.jpg 候选图与所在页语境拼版
9
+ asset-vision-groups.json 候选来源、位置与预算索引
10
+ manifest.yaml / frontmatter.yaml / layout-controls.yaml / layouts.yaml / body.md
11
+ 判断单与坐标事实,可直接进 package.py
10
12
 
11
13
  草案里所有数值都来自 extract.json;凡是需要「像人一样看」才能定的,写成 `TODO:` 行
12
14
  (package.py 见 TODO 即 FAIL),由 L 层改掉。
13
15
  """
14
16
  import argparse
17
+ import copy
18
+ import glob
15
19
  import json
16
20
  import os
17
21
  import re
18
22
  import shutil
23
+ import subprocess
19
24
  import sys
20
25
  from collections import Counter, defaultdict
21
26
 
27
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
28
+ from ooxml import OFFICE_DEFAULT_FONTS # noqa: E402
29
+ from census import (ASSET_WARN_SINGLE, FULLSCREEN_COVERAGE, LUM_MID, # noqa: E402
30
+ REPEAT_MIN, SMALL_IMG_W_PCT, canvas_coverage)
31
+
32
+ OPAQUE_ENOUGH = 128 # 能当背景的最低不透明度:低于半透明就遮不住底下的东西,
33
+ # 那是叠加装饰不是背景
34
+ FILL_MANY = 5 # 「被大量当填充铺开」的次数下限,用于区分卡片底与偶发用色
35
+ BG_CONTENT_CAP = 5 # 内容页背景收几张:再多消费端也挑不过来,超出的写进 TODO 交人取舍
36
+ SHEET_BATCH = 12 # 每张联系表最多 12 个候选;候选不截断,超出就继续生成下一张
37
+ CONTEXT_BATCH = 8 # 每张整页语境表最多 8 页;同页只渲染一次
38
+ # 与 studio_server_faas 的批量 vision 图数预算保持一致。单页大组允许 1 张整页图 +
39
+ # 9 张候选;多个小页合组时,所有整页图和候选图合计最多 5 张。
40
+ SINGLE_PAGE_IMAGE_BUDGET = 10
41
+ MULTI_PAGE_IMAGE_BUDGET = 5
42
+ # Skill 侧的总输入上限:限制模型需要读取的拼版数量和总视觉图数,而不是偷偷截断
43
+ # 中间产物。首页、尾页优先;其余超限候选在 gaps 中显式说明。
44
+ VISUAL_PACK_CAP = 5
45
+ VISUAL_INPUT_CAP = 30
46
+ VISUAL_PREVIEW_MAX_EDGE = 1200
47
+ VISUAL_JPEG_QUALITY = 82
48
+
22
49
  HERE = os.path.dirname(os.path.abspath(__file__))
23
50
  SKILL_ROOT = os.path.dirname(HERE)
24
51
  SYS_FALLBACK = '"PingFang SC", "Microsoft YaHei", sans-serif'
25
52
 
26
53
 
27
54
  # ---------------------------------------------------------------- 小工具
55
+ # 被名额截掉的东西统一记在这里,最后并进 gaps。截断本身是必要的(色板 40 个 token
56
+ # 消费端挑不过来),但**不说**就成了「悄悄少了东西而产物看起来正常」——消费端会以为
57
+ # 它拿到的就是全部。
58
+ _TRUNCATED = []
59
+
60
+
61
+ def note_truncation(kind, kept, total, advice='', where=''):
62
+ """记一条「这里按名额截断了」。kept >= total 时什么都不记。
63
+
64
+ 按 kind 归并成一条 gap:同一类截断逐处各写一行会淹掉别的 gaps。
65
+ """
66
+ if total > kept:
67
+ _TRUNCATED.append((kind, kept, total, advice, where))
68
+ return kept
69
+
70
+
28
71
  def hex2rgb(h):
29
72
  h = h.lstrip('#')
30
73
  return tuple(int(h[i:i + 2], 16) for i in (0, 2, 4))
@@ -82,7 +125,64 @@ def q(v):
82
125
 
83
126
 
84
127
  # ---------------------------------------------------------------- 颜色
85
- def draft_colors(d):
128
+ def bg_colors(d):
129
+ """页面/版式/母版的 `background` 声明里出现的底色,按声明次数排序。
130
+
131
+ 「哪个色是底色」是直读事实(bgPr / bgRef),不用靠亮度猜:渐变里出现的浅色,
132
+ 亮度可能比真底色更像底色。
133
+ """
134
+ cnt = Counter()
135
+ rows = (d.get('slides') or []) + (d.get('layouts') or []) \
136
+ + ((d.get('masters') or {}).get('masters') or [])
137
+ for row in rows:
138
+ bg = row.get('background')
139
+ if not isinstance(bg, dict):
140
+ continue
141
+ cols = []
142
+ if isinstance(bg.get('color'), dict):
143
+ cols.append(bg['color'])
144
+ for st in (bg.get('stops') or []):
145
+ if isinstance(st.get('color'), dict):
146
+ cols.append(st['color'])
147
+ for c in cols:
148
+ h = (c.get('hex') or '').upper()
149
+ if h:
150
+ cnt[h] += 1
151
+ return [h for h, _ in cnt.most_common()]
152
+
153
+
154
+ def _gap_cut(vals, lo, hi):
155
+ """在排序后的值里找最大间隙,切点取间隙中点。
156
+
157
+ 不用中位数:中位数会正好落在某个样本自己身上,它归哪边就只取决于写 >= 还是 >,
158
+ 纯属任意。真正的分界在两族之间的空档里。夹在 [lo, hi] 内,避免整套同色的模板
159
+ 把界推到极端。
160
+ """
161
+ v = sorted(vals)
162
+ if len(v) < 2:
163
+ return (lo + hi) / 2.0
164
+ _, mid = max((v[i + 1] - v[i], (v[i + 1] + v[i]) / 2.0) for i in range(len(v) - 1))
165
+ return min(max(mid, lo), hi)
166
+
167
+
168
+ def palette_cuts(rows):
169
+ """「有彩 vs 中性」「深 vs 浅」的分界,按本模板自己的色分布切。
170
+
171
+ 固定分界必然错一边:低饱和的莫兰迪配色整套都在低位,高饱和的品牌配色整套都在高位。
172
+ """
173
+ sat_cut = _gap_cut([r['sat'] for r in rows], 0.12, 0.45)
174
+ lums = sorted(r['lum'] for r in rows) or [0.0]
175
+ return sat_cut, lums[len(lums) // 2]
176
+
177
+
178
+ def draft_colors(d, cusage=None):
179
+ """色板 token:名字按**实际用法**定,不只看亮度饱和度。
180
+
181
+ 只看 lum/sat 会把「主要用来填色的纯黑」命名成 ink(文字色)、把「只出现在渐变里的
182
+ 浅蓝」命名成 surface-alt。这里先看它在形状上主要干什么,再结合
183
+ 亮度定名;用量太少的直接不进色板。
184
+ """
185
+ cusage = cusage or {}
86
186
  pool = [c for c in d['color_freq']
87
187
  if c.get('class') == 'design' and abs((c.get('alpha') or 100) - 100) < 0.1]
88
188
  seen, rows = set(), []
@@ -92,29 +192,63 @@ def draft_colors(d):
92
192
  continue
93
193
  seen.add(h)
94
194
  rgb = hex2rgb(h)
95
- rows.append({'hex': h, 'n': c['n'], 'lum': lum(rgb), 'sat': satu(rgb)})
96
- rows.sort(key=lambda r: -r['n'])
195
+ u = cusage.get(h) or Counter()
196
+ tot = sum(u.values())
197
+ main = u.most_common(1)[0][0] if tot else None
198
+ rows.append({'hex': h, 'n': c['n'], 'lum': lum(rgb), 'sat': satu(rgb),
199
+ 'use': u, 'use_n': tot, 'main': main})
200
+ # 用量只用来**命名**,不作准入门槛——color_usage 只数形状级的填充/描边/文字,
201
+ # 背景 p:bg 与主题色不在其中,拿它筛会把色板砍到只剩极少数几个。
202
+ strong = sorted(rows, key=lambda r: -r['n'])
203
+
204
+ SAT_CUT, LUM_CUT = palette_cuts(rows)
97
205
 
98
206
  tokens, used = [], set()
99
207
 
100
208
  def take(pred, names):
101
209
  for name in names:
102
- for r in rows:
210
+ for r in strong:
103
211
  if r['hex'] in used or not pred(r):
104
212
  continue
105
213
  used.add(r['hex'])
106
214
  tokens.append((name, r))
107
215
  break
108
216
 
109
- take(lambda r: r['lum'] > 0.85 and r['sat'] < 0.15, ['surface', 'surface-alt'])
110
- take(lambda r: r['lum'] < 0.32 and r['sat'] < 0.25, ['ink', 'ink-muted'])
111
- take(lambda r: r['sat'] >= 0.35, ['primary', 'accent', 'accent-2', 'accent-3'])
112
- take(lambda r: r['sat'] < 0.35, ['neutral'])
113
- # 未取用但高频的留给 BRIEF 展示
114
- rest = [r for r in rows if r['hex'] not in used][:6]
217
+ def kind(r):
218
+ if r['main'] == '文字':
219
+ return 'text'
220
+ if r['main'] in ('填充', '渐变', '描边'):
221
+ return 'paint'
222
+ return 'unknown' # 形状层看不到用法,退回亮度/饱和度判断
223
+
224
+ # 墨色:主要用来写字(或看不出用法但本身是深中性色),且不是彩色
225
+ take(lambda r: r['sat'] < SAT_CUT and r['lum'] < min(LUM_CUT, LUM_MID)
226
+ and (kind(r) == 'text' or kind(r) == 'unknown'), ['ink', 'ink-muted'])
227
+ # 底色:直接取页面 background 声明里的色,按声明次数排
228
+ grounds = bg_colors(d)
229
+ for name in ('surface', 'surface-alt'):
230
+ for h in grounds:
231
+ r = next((x for x in strong if x['hex'] == h and x['hex'] not in used), None)
232
+ if r:
233
+ used.add(r['hex'])
234
+ tokens.append((name, r))
235
+ break
236
+
237
+ # 卡片/面板底:页面底色之外,真被大量当填充铺开的浅色(≥5 处才算)
238
+ take(lambda r: r['lum'] > max(LUM_CUT, 0.85) and r['sat'] < SAT_CUT
239
+ and (r['use'].get('填充') or 0) >= FILL_MANY, ['surface-raised'])
240
+ # 表达色:有彩度的按频次排
241
+ take(lambda r: r['sat'] >= SAT_CUT, ['primary', 'accent', 'accent-2', 'accent-3'])
242
+ # 其余低饱和色一律 neutral-N——它到底是卡片底、分隔线还是描边,数据分不出来,
243
+ # 就不要用名字去替消费方下结论;真实用法写在 Colors 表的用途列里。
244
+ take(lambda r: r['sat'] < SAT_CUT, ['neutral', 'neutral-2', 'neutral-3'])
245
+ spare = [r for r in rows if r['hex'] not in used]
246
+ note_truncation('设计色', 6, len(spare), '色板只收主要色,其余在联系表里看')
247
+ rest = spare[:6]
115
248
  return tokens, rest, rows
116
249
 
117
250
 
251
+
118
252
  # ---------------------------------------------------------------- 字体
119
253
  def parse_fallback_table():
120
254
  path = os.path.join(SKILL_ROOT, 'font-fallback.yaml')
@@ -142,6 +276,48 @@ def norm(s):
142
276
  return re.sub(r'[\s\-_]', '', s or '').lower()
143
277
 
144
278
 
279
+ OFFICE_DEFAULT_FONTS_NORM = {norm(x) for x in OFFICE_DEFAULT_FONTS}
280
+
281
+
282
+ def cover_slot_colors(tokens, archetypes, rows, cusage):
283
+ """slot CSS 里出现的每个色值都必须在色板里有名字。
284
+
285
+ Hard Rules 写「颜色只用 colors 里的 token」,而 slot CSS 的 color 是从模板直读的,
286
+ 两者不对齐就等于产物自己违反自己的规则——slot 的色值直读自模板,未必都已进
287
+ 色板。这里把缺的补进色板,按用法归族命名。
288
+ """
289
+ have = {r['hex'].upper() for _, r in tokens}
290
+ by_hex = {r['hex'].upper(): r for r in rows}
291
+ sat_cut, lum_cut = palette_cuts(rows) # 与 draft_colors 同一套切点,别各切各的
292
+ used = [n for n, _ in tokens]
293
+
294
+ def nxt(fam):
295
+ if fam not in used:
296
+ return fam
297
+ i = 2
298
+ while '%s-%d' % (fam, i) in used:
299
+ i += 1
300
+ return '%s-%d' % (fam, i)
301
+
302
+ added = []
303
+ for a in archetypes:
304
+ for s in a['slots']:
305
+ h = (s.get('_color') or '').upper()
306
+ if not h.startswith('#') or h in have:
307
+ continue
308
+ have.add(h)
309
+ r = by_hex.get(h)
310
+ if r is None: # 普查里没有这个色(理论上不该发生),跳过不编造
311
+ continue
312
+ fam = ('ink' if r['sat'] < sat_cut and r['lum'] < min(lum_cut, LUM_MID)
313
+ else 'accent' if r['sat'] >= sat_cut else 'neutral')
314
+ name = nxt(fam)
315
+ used.append(name)
316
+ tokens.append((name, r))
317
+ added.append((name, h))
318
+ return added
319
+
320
+
145
321
  def draft_fonts(d):
146
322
  table = parse_fallback_table()
147
323
  groups = defaultdict(lambda: {'rendered': 0, 'weights': set(), 'names': set(), 'bold': 0})
@@ -167,6 +343,7 @@ def draft_fonts(d):
167
343
  return None
168
344
 
169
345
  out = []
346
+ note_truncation('字族', 4, len(ranked), '只报渲染量最大的几族')
170
347
  for key, g in ranked[:4]:
171
348
  fam = resolve(sorted(g['names'], key=len))
172
349
  stack = [sorted(g['names'], key=len)[0]]
@@ -201,35 +378,193 @@ def import_line(fonts):
201
378
  return "@import url('%s?%s&display=swap');" % (MIRROR, fam), webs
202
379
 
203
380
 
381
+ def quant(hit, total):
382
+ """覆盖率决定量词——不到一半就不许说「一律/每页」。"""
383
+ if not total:
384
+ return None
385
+ r = hit / float(total)
386
+ if r >= 0.9:
387
+ return '一律'
388
+ if r >= 0.5:
389
+ return '多数'
390
+ return None
391
+
392
+
393
+ def color_usage(shapes, d=None):
394
+ """每个色值在形状上的真实用法计数:填充 / 渐变 / 描边 / 文字。
395
+
396
+ 用途列不能靠预设字典猜——同一个色在不同模板里的主用途完全不同。这里从 shapes
397
+ 直接数,数不到就如实说数不到。
398
+ """
399
+ def hx(c):
400
+ return (c.get('hex') or '').upper() if isinstance(c, dict) else ''
401
+
402
+ def walk_text_colors(node, out):
403
+ """文本样式可能嵌在 lstStyle.lvlNpPr / defRPr / rPr 任一层——通用遍历,
404
+ 别逐层枚举(枚举漏过 lvl2pPr,导致主色被写成「用途待确认」)。"""
405
+ if isinstance(node, dict):
406
+ if isinstance(node.get('color'), dict) and hx(node['color']):
407
+ out.append(hx(node['color']))
408
+ for v in node.values():
409
+ walk_text_colors(v, out)
410
+ elif isinstance(node, list):
411
+ for v in node:
412
+ walk_text_colors(v, out)
413
+
414
+ use = defaultdict(Counter)
415
+ for s in shapes:
416
+ f = s.get('fill') or {}
417
+ if f.get('type') == 'solid' and hx(f.get('color')):
418
+ use[hx(f['color'])]['填充'] += 1
419
+ for st in (f.get('stops') or []):
420
+ if hx(st.get('color')):
421
+ use[hx(st['color'])]['渐变'] += 1
422
+ ln = s.get('line') or {}
423
+ if hx(ln.get('color')):
424
+ use[hx(ln['color'])]['描边'] += 1
425
+ cols = []
426
+ walk_text_colors(s.get('text') or {}, cols)
427
+ for h in cols:
428
+ use[h]['文字'] += 1
429
+ for h in bg_colors(d or {}):
430
+ use[h]['页面背景'] += 1
431
+ # 主题 clrScheme:这类色常常只在主题里声明、页面上由 schemeClr 间接引用,
432
+ # 不记上就会在用途列写「未落在形状上」,看着像没人用。
433
+ for th in ((d or {}).get('themes') or []):
434
+ if not th.get('picked'):
435
+ continue
436
+ for slot, hexv in (th.get('clrScheme') or {}).items():
437
+ if isinstance(hexv, str) and hexv.startswith('#'):
438
+ use[hexv.upper()]['主题 ' + slot] += 1
439
+ return use
440
+
441
+
442
+ def usage_phrase(counter):
443
+ """把用法计数写成一句话;主用法占六成以上就直接点名,否则并列前三。"""
444
+ if not counter:
445
+ return '普查里有声明,但未落在形状/背景/主题色上——用途待确认'
446
+ items = counter.most_common()
447
+ tot = sum(counter.values())
448
+ if items[0][1] >= tot * 0.6:
449
+ return '主要作%s(%d/%d 处)' % (items[0][0], items[0][1], tot)
450
+ return '、'.join('%s %d 处' % (k, v) for k, v in items[:3])
451
+
452
+
204
453
  def draft_anchors(d, tokens, fonts, roles, assets, archetypes):
205
- names = [t[0] for t in tokens]
454
+ """anchors 只报测到的数,不下「这套风格是什么」的结论。
455
+
456
+ 这一段在 design.md 里读起来像「设计总纲」,消费端会照它建全局样式。脚本写进去的
457
+ 每一句解读都会被当成规则执行——实测把 1/8 覆盖率的 logo 描述成「跨页不动」,
458
+ 消费端就建了全局 CSS 类,12 页全铺了 logo。所以这里只给覆盖率和计数,
459
+ 「这是不是这套风格的特征」由看得到图的人判断。
460
+ """
461
+ A = []
462
+ n_arch = len(archetypes) or 1
463
+
464
+ # 1. 表达色:未取用的高频彩色要如实带上,不能说「其余全是中性」
465
+ names = [x[0] for x in tokens]
206
466
  chroma = [n for n in names if n.startswith(('primary', 'accent'))]
467
+ if chroma:
468
+ A.append((chroma[0] + '-led-palette', 'token',
469
+ '有彩色 token 共 %d 个,用量最大的是 %s'
470
+ % (len(chroma), '、'.join(chroma[:3]))))
471
+
472
+ # 2. 圆角:按普查占比
207
473
  radii = d.get('radii_census') or []
208
474
  zero = next((r for r in radii if r['px'] == 0), None)
209
- total_r = sum(r['n'] for r in radii) or 1
210
- geom = d.get('geom_census') or {}
475
+ tot_r = sum(r['n'] for r in radii) or 1
476
+ if zero:
477
+ q0 = quant(zero['n'], tot_r)
478
+ if q0:
479
+ A.append(('zero-radius', 'token',
480
+ '圆角量为零的形状占 %d%%(普查 %d 个带圆角声明的形状)'
481
+ % (round(100.0 * zero['n'] / tot_r), tot_r)))
482
+
483
+ # 3. 满屏底图:按有背景的页型占比
484
+ with_bg = sum(1 for a in archetypes if a.get('bg'))
485
+ qb = quant(with_bg, n_arch)
486
+ if qb:
487
+ A.append(('full-bleed-ground', 'pattern',
488
+ '%d/%d 个页型声明了整幅铺满的底图' % (with_bg, n_arch)))
489
+
490
+ # 4. 标识:位置是不是真的固定,看有几个不同的 box
491
+ logo_slots = [s for a in archetypes for s in a['slots']
492
+ if str(s.get('asset') or '').startswith(('logo', 'slogan'))]
493
+ logo_arch = sum(1 for a in archetypes
494
+ if any(str(s.get('asset') or '').startswith(('logo', 'slogan'))
495
+ for s in a['slots']))
496
+ boxes = {tuple(s['box']) for s in logo_slots}
497
+ # anchors 是「这套风格的定义性特征」,消费端读它来建全局样式。只在少数页型出现的
498
+ # 东西写进来,等于宣布它是全局元素——实测某模板 logo 只在 1/8 个页型上,anchor 仍
499
+ # 写成「跨页不动」,消费端据此建了个全局 CSS 类,12 页全铺了 logo。
500
+ # 所以这里和其他 anchor 用同一把尺:覆盖率不过半就不进 anchors。
501
+ ql = quant(logo_arch, n_arch)
502
+ if logo_arch and len(boxes) == 1 and ql:
503
+ A.append(('corner-locked-logo', 'component',
504
+ '品牌标识出现在 %d/%d 个页型上,这些页型里它的 box 完全一致'
505
+ % (logo_arch, n_arch)))
506
+ elif len(boxes) > 1:
507
+ A.append(('logo-moves-by-archetype', 'component',
508
+ '品牌标识按页型换位换尺寸(共 %d 种摆法),必须按 layouts 里该页型的 box 放,'
509
+ '不能沿用上一页' % len(boxes)))
510
+
511
+ # 5. 渐变:按普查计数
512
+ if (d.get('geom_census') or {}).get('gradient_fills'):
513
+ A.append(('gradient-accent', 'pattern',
514
+ '全档共 %d 处渐变填充' % (d['geom_census']['gradient_fills'])))
515
+
516
+ # 6. 层级:字号跨度 + 字重是否单一(字重真单一才敢说「不靠字重」)
517
+ disp, body = roles.get('display'), roles.get('body')
518
+ if disp and body and disp['sz_px'] > body['sz_px']:
519
+ ws = {s.get('_font_weight') for a in archetypes for s in a['slots']
520
+ if s.get('_font_weight')}
521
+ tail = (',字重只用 %s 一档' % list(ws)[0]) if len(ws) == 1 else ''
522
+ A.append(('size-driven-hierarchy', 'pattern',
523
+ '最大字号档与正文档相差 %.1f 倍(见 typography)%s'
524
+ % (disp['sz_px'] / body['sz_px'], tail)))
525
+
526
+ # 7. 阴影:只在描边极少时才敢说「不用描边分隔」
211
527
  eff = d.get('effects_census') or {}
212
- A = []
213
- if chroma:
214
- A.append((chroma[0] + '-led-palette', 'token',
215
- '表达色只有 %s 这一组,其余全是中性底与墨色,见 colors' % '、'.join(chroma[:3])))
216
- if zero and zero['n'] >= total_r * 0.7:
217
- A.append(('zero-radius', 'token', '卡片、按钮、面板一律直角,圆角量在全 deck 压倒性为零'))
218
- if any(a['kind'] == 'background' for a in assets):
219
- A.append(('full-bleed-ground', 'pattern', '每页由整幅铺满的底图打底,元素浮在图上而不是浮在纯色块上'))
220
- if any(a['kind'] == 'logo' for a in assets):
221
- A.append(('corner-locked-logo', 'component', '品牌标识固定在同一角位,跨页不移动、不缩放'))
222
- if geom.get('gradient_fills'):
223
- A.append(('gradient-accent', 'pattern', '强调元素靠线性渐变承载,而不是纯色块'))
224
- if len(fonts) >= 2:
225
- A.append(('dual-family-typesetting', 'token', '中文与拉丁数字分属两套字族,同一行里混排'))
226
528
  if eff.get('outerShdw'):
227
- A.append(('soft-shadow-card', 'component', '卡片靠极浅外阴影托起,不用描边分隔'))
228
- disp, body = roles.get('display'), roles.get('body')
229
- if disp and body and disp['sz_px'] >= body['sz_px'] * 3:
230
- A.append(('size-driven-hierarchy', 'pattern', '层级靠字号跨度拉开而不是字重,展示档与正文档差出数倍'))
231
- A.append(('archetype-reuse', 'pattern', '全 deck 只用 %d 种页型反复排列,版面骨架高度复用' % len(archetypes)))
232
- A.append(('safe-area-discipline', 'token', '正文一律落在统一安全区内,不贴画布边'))
529
+ A.append(('soft-shadow-card', 'component',
530
+ '全档 %d outerShdw 外阴影' % eff['outerShdw']))
531
+
532
+ # 8. 双字族:只陈述分工存在,不断言「同一行混排」(普查没采集混排)
533
+ tot_r_font = sum(f['rendered'] for f in fonts) or 1
534
+ if len(fonts) >= 2 and fonts[1]['rendered']:
535
+ A.append(('dual-family-typesetting', 'token',
536
+ '用了两套字族:%s 渲染 %d 处、%s 渲染 %d 处'
537
+ % (fonts[0]['names'][0], fonts[0]['rendered'],
538
+ fonts[1]['names'][0], fonts[1]['rendered'])))
539
+
540
+ # 9. 安全区:只在各页型正文左边界真的收敛时才写
541
+ # 「多宽算正文槽」按本包自己的槽宽分布定:固定 px 门槛在窄版心模板上会一个都不剩
542
+ widths = sorted(s['box'][2] for a in archetypes for s in a['slots'] if not s.get('asset'))
543
+ w_cut = widths[len(widths) // 2] if widths else 0
544
+ lefts = [s['box'][0] for a in archetypes for s in a['slots']
545
+ if not s.get('asset') and s['box'][2] >= w_cut]
546
+ if len(lefts) >= 4:
547
+ common = Counter(lefts).most_common(1)[0]
548
+ qs = quant(common[1], len(lefts))
549
+ if qs:
550
+ A.append(('shared-left-margin', 'token',
551
+ '%d/%d 个正文槽的左边界落在同一个 x 上(坐标见 layouts)'
552
+ % (common[1], len(lefts))))
553
+
554
+ # 10. 双主题:直读事实
555
+ themes = (d.get('theme_topology') or {}).get('themes') or []
556
+ if len(themes) > 1:
557
+ A.append(('dual-theme-masters', 'token',
558
+ '模板声明了 %s 两套主题母版' % ' / '.join(themes)))
559
+
560
+ # 11. 画布:直读事实(兜底凑数也只用真事实)
561
+ cv = d['canvas']['px']
562
+ A.append(('fixed-canvas', 'token',
563
+ '画布 %d×%d,layouts 里的坐标都是这张画布上的绝对像素' % (cv[0], cv[1])))
564
+ if len(archetypes) >= 3:
565
+ A.append(('archetype-catalog', 'pattern',
566
+ '归纳出 %d 种页型' % len(archetypes)))
567
+
233
568
  seen, out = set(), []
234
569
  for a in A:
235
570
  if a[0] in seen:
@@ -238,8 +573,6 @@ def draft_anchors(d, tokens, fonts, roles, assets, archetypes):
238
573
  out.append(a)
239
574
  return out[:8]
240
575
 
241
-
242
- # ---------------------------------------------------------------- 字号轴
243
576
  def draft_scale(d, archetypes=()):
244
577
  ts = [t for t in d['text_scale'] if t['sz_px'] >= 10]
245
578
  ts.sort(key=lambda t: -t['sz_px'])
@@ -251,8 +584,9 @@ def draft_scale(d, archetypes=()):
251
584
  display = by_px.get(max(title_sz)) if title_sz else None
252
585
  big = [t for t in ts if t['n'] >= 2] or ts
253
586
  display = display or big[0]
254
- body_pool = [t for t in ts if t['sz_px'] <= 48]
255
- body = max(body_pool, key=lambda t: t['n']) if body_pool else ts[-1]
587
+ # 正文档 = 渲染次数最多的那一档。不设「多大算正文」的上限:大字号排版的模板
588
+ # 正文本来就可能比别的模板的标题还大,预设上限会把它整档判错。
589
+ body = max([t for t in ts if t is not display] or ts, key=lambda t: t['n'])
256
590
  heading_pool = [t for t in ts if body['sz_px'] * 1.3 <= t['sz_px'] < display['sz_px']]
257
591
  heading = max(heading_pool, key=lambda t: t['n']) if heading_pool else None
258
592
  small_pool = [t for t in ts if t['sz_px'] < body['sz_px']]
@@ -279,7 +613,13 @@ def lh_of(t):
279
613
 
280
614
  # ---------------------------------------------------------------- 资产
281
615
  def probe_image(path):
282
- info = {'w': None, 'h': None, 'alpha_mean': None, 'near_blank': False}
616
+ info = {
617
+ 'w': None,
618
+ 'h': None,
619
+ 'alpha_mean': None,
620
+ 'near_blank': False,
621
+ 'near_white_ratio': None,
622
+ }
283
623
  try:
284
624
  from PIL import Image
285
625
  except Exception:
@@ -287,15 +627,119 @@ def probe_image(path):
287
627
  try:
288
628
  im = Image.open(path)
289
629
  info['w'], info['h'] = im.size
630
+ preview = im.convert('RGBA').resize((64, 64))
631
+ pixels = (preview.get_flattened_data()
632
+ if hasattr(preview, 'get_flattened_data') else preview.getdata())
633
+ px = list(pixels)
634
+ alpha = [item[3] for item in px]
290
635
  if im.mode in ('RGBA', 'LA') or 'transparency' in im.info:
291
- px = im.convert('RGBA').getchannel('A').resize((64, 64)).tobytes()
292
- info['alpha_mean'] = sum(px) / len(px)
636
+ info['alpha_mean'] = sum(alpha) / len(alpha)
293
637
  info['near_blank'] = info['alpha_mean'] < 13 # <5% 不透明度
638
+ visible = [item for item in px if item[3] >= 32]
639
+ if visible:
640
+ near_white = [item for item in visible
641
+ if item[0] >= 235 and item[1] >= 235 and item[2] >= 235]
642
+ info['near_white_ratio'] = round(len(near_white) / float(len(visible)), 3)
294
643
  except Exception:
295
644
  pass
296
645
  return info
297
646
 
298
647
 
648
+ def needs_asset_judgment(candidate):
649
+ """局部图和半透明满屏叠加层需要看图定性;不透明满屏图按背景处理。"""
650
+ effective_alpha = candidate.get('effective_alpha_mean')
651
+ if ((candidate.get('probe') or {}).get('near_blank')
652
+ or (effective_alpha is not None and effective_alpha < 13)):
653
+ return False
654
+ if not candidate.get('fullscreen'):
655
+ return True
656
+ alpha = (effective_alpha if effective_alpha is not None
657
+ else (candidate.get('probe') or {}).get('alpha_mean'))
658
+ return alpha is not None and alpha < OPAQUE_ENOUGH
659
+
660
+
661
+ def fullscreen_effective_alpha(data, outdir, shapes):
662
+ """满屏图片的实际平均 alpha,包含图片文件 alpha 与 OOXML 形状透明度。"""
663
+ media_out = {row.get('media'): row.get('out') for row in data.get('media') or []
664
+ if row.get('media') and row.get('out')}
665
+ probed = {}
666
+ effective = {}
667
+ for shape in shapes:
668
+ media = shape.get('media')
669
+ if (shape.get('kind') != 'pic' or not media
670
+ or shape.get('w_pct', 0) < 95 or shape.get('h_pct', 0) < 95):
671
+ continue
672
+ if media not in probed:
673
+ out = media_out.get(media)
674
+ probe = probe_image(os.path.join(outdir, out)) if out else {}
675
+ probed[media] = probe.get('alpha_mean')
676
+ source_alpha = probed[media]
677
+ if source_alpha is None:
678
+ source_alpha = 255.0
679
+ try:
680
+ opacity = float(shape.get('opacity', 1.0))
681
+ except (TypeError, ValueError):
682
+ opacity = 1.0
683
+ alpha = source_alpha * max(0.0, min(opacity, 1.0))
684
+ effective[media] = min(effective.get(media, 255.0), alpha)
685
+ return effective
686
+
687
+
688
+ def fullscreen_overlay_media(data, outdir, shapes):
689
+ """需要模型判断的满屏叠加层媒体。"""
690
+ return {
691
+ media for media, alpha in fullscreen_effective_alpha(data, outdir, shapes).items()
692
+ if 13 <= alpha < OPAQUE_ENOUGH
693
+ }
694
+
695
+
696
+ def bg_busy_map(path, canvas, cells=12):
697
+ """把背景图切成网格,报每格的**局部对比度**(该格内亮度极差)。
698
+
699
+ 「哪里不能压文字」的本质是「哪里花」。整幅渐变的底图各格对比度都低,说明没有
700
+ 视觉主体;有山峰、人物、产品图的底图会在主体处出现明显更高的对比度。这里只出
701
+ 客观数值和一个据此推出的草案,最终由看得到图的人定。
702
+ """
703
+ try:
704
+ from PIL import Image
705
+ except Exception:
706
+ return None
707
+ try:
708
+ im = Image.open(path).convert('L').resize((cells * 8, cells * 8))
709
+ except Exception:
710
+ return None
711
+ px = im.load()
712
+ grid = []
713
+ for gy in range(cells):
714
+ row = []
715
+ for gx in range(cells):
716
+ vals = [px[gx * 8 + x, gy * 8 + y] for y in range(8) for x in range(8)]
717
+ row.append(max(vals) - min(vals))
718
+ grid.append(row)
719
+ flat = sorted(v for row in grid for v in row)
720
+ if not flat:
721
+ return None
722
+ med = flat[len(flat) // 2]
723
+ hi = flat[int(len(flat) * 0.9)]
724
+ # 主体 = 对比度显著高于全图中位数的连片格子。阈值取「中位数与九分位的中点」,
725
+ # 由本图自己的分布定,不用固定值。
726
+ cut = (med + hi) / 2.0
727
+ cW, cH = canvas
728
+ hot = [(gx, gy) for gy in range(cells) for gx in range(cells) if grid[gy][gx] > cut]
729
+ if not hot:
730
+ return {'busy': None, 'median': med, 'p90': hi, 'why': '各处对比度一致,没有更花的区域'}
731
+ xs = [g[0] for g in hot]
732
+ ys = [g[1] for g in hot]
733
+ span = ((max(xs) - min(xs) + 1) * (max(ys) - min(ys) + 1)) / float(cells * cells)
734
+ if span > 0.5:
735
+ # 热格散落全图,外接矩形几乎覆盖整幅——圈出来等于没圈
736
+ return {'busy': None, 'median': med, 'p90': hi, 'why': '较花的格子散布全图,圈不出单一主体'}
737
+ box = [round(min(xs) * cW / cells), round(min(ys) * cH / cells),
738
+ round((max(xs) - min(xs) + 1) * cW / cells),
739
+ round((max(ys) - min(ys) + 1) * cH / cells)]
740
+ return {'busy': box, 'median': med, 'p90': hi, 'span': round(span, 2)}
741
+
742
+
299
743
  def copy_logo_candidates(outdir, logo_pool):
300
744
  if not logo_pool:
301
745
  return []
@@ -326,7 +770,8 @@ def copy_logo_candidates(outdir, logo_pool):
326
770
  return rows
327
771
 
328
772
 
329
- def draft_assets(d, outdir, bg_needed=(), cover_media=None, bg_under=None):
773
+ def draft_assets(d, outdir, bg_needed=(), cover_media=None, bg_under=None,
774
+ effective_alpha=None):
330
775
  imgs = {i['media']: i for i in d['images']}
331
776
  cluster_of = {}
332
777
  for c in d.get('media_clusters', []):
@@ -343,15 +788,35 @@ def draft_assets(d, outdir, bg_needed=(), cover_media=None, bg_under=None):
343
788
  boxes = img.get('boxes') or []
344
789
  top = max(boxes, key=lambda b: b.get('count', 0)) if boxes else {}
345
790
  parts = top.get('parts') or []
346
- slides = sorted({slide_no(p) for p in parts if '/slides/' in p})
791
+ placements, seen_placements = [], set()
792
+ for cluster in boxes:
793
+ box = cluster.get('box') or {}
794
+ rounded = [round(box.get(key, 0)) for key in ('x', 'y', 'w', 'h')]
795
+ for part in cluster.get('parts') or []:
796
+ if '/slides/' in part:
797
+ row = {'slide': slide_no(part), 'box': rounded}
798
+ elif '/slideLayouts/' in part:
799
+ row = {'layout': os.path.basename(part), 'box': rounded}
800
+ else:
801
+ continue
802
+ key = (row.get('slide'), row.get('layout'), tuple(rounded))
803
+ if key not in seen_placements:
804
+ seen_placements.add(key)
805
+ placements.append(row)
806
+ placements.sort(key=lambda row: (
807
+ row.get('slide', 9999), row.get('layout', ''), tuple(row['box'])))
808
+ slides = sorted({row['slide'] for row in placements if row.get('slide')})
347
809
  cands.append({
348
810
  'media': m['media'], 'file': os.path.basename(out_rel), 'out': out_rel,
349
811
  'bytes': m.get('bytes'), 'n': img.get('n', m.get('used_n', 0)),
812
+ 'has_compressed': bool(m.get('compressed_out')),
350
813
  'fullscreen': bool(img.get('fullscreen')), 'w_pct': img.get('max_w_pct', 0),
351
814
  'box': top.get('box') or {}, 'slides': slides,
815
+ 'placements': placements,
352
816
  'layer_only': bool(parts) and not slides,
353
817
  'repeat': bool(img.get('repeat_fixed')),
354
818
  'cluster': cluster_of.get(m['media']),
819
+ 'effective_alpha_mean': (effective_alpha or {}).get(m['media']),
355
820
  'probe': probe, 'reasons': m.get('reasons', []),
356
821
  })
357
822
 
@@ -362,35 +827,62 @@ def draft_assets(d, outdir, bg_needed=(), cover_media=None, bg_under=None):
362
827
  if k not in best_of or c['n'] > best_of[k]['n']:
363
828
  best_of[k] = c
364
829
  kept = sorted(best_of.values(), key=lambda c: (-c['n'], -(c['bytes'] or 0)))
830
+ # 被同簇兄弟淘汰的 media 仍要能指到胜出者——封面底图常常是簇里 n 最小的那张
831
+ alias = {}
832
+ for c in cands:
833
+ w = best_of.get(c['cluster'] or c['media'])
834
+ if w and w['media'] != c['media']:
835
+ alias[c['media']] = w['media']
836
+ cover_media = alias.get(cover_media, cover_media)
837
+ bg_needed = {alias.get(m, m) for m in (bg_needed or ())}
365
838
 
366
839
  assets, rejected, todos = [], [], []
840
+ over_cap_bgs = []
367
841
  logo_pool = []
368
842
  bg_under = bg_under or {}
369
843
  bg_i = 0
370
- canvas_w = d['canvas']['px'][0]
844
+ canvas_w, canvas_h = d['canvas']['px']
371
845
  for c in kept:
372
- if c['probe'].get('near_blank'):
373
- rejected.append((c, '近全透明(alpha 均值 %.0f/255),PPT 里看不见' % c['probe']['alpha_mean']))
846
+ effective_am = c.get('effective_alpha_mean')
847
+ if (c['probe'].get('near_blank')
848
+ or (effective_am is not None and effective_am < 13)):
849
+ rejected.append((c, '近全透明(alpha 均值 %.0f/255),PPT 里看不见'
850
+ % (effective_am if effective_am is not None
851
+ else c['probe']['alpha_mean'])))
852
+ continue
853
+ # 铺满 ≠ 能当背景。背景的定义性属性是**遮盖**:它得挡住底下的东西。一张大半透明
854
+ # 的图铺满整页也遮不住任何像素,它在 PPT 里是叠在幻灯片底色上的一层装饰(顶部
855
+ # 光晕之类),底色才是真背景。实测某模板一张 alpha 均值 30/255、72% 完全透明的
856
+ # 顶部光晕被当成满屏背景收进包,消费端每页铺它,顶部就多出一条原稿没有的浓色带。
857
+ am = effective_am if effective_am is not None else c['probe'].get('alpha_mean')
858
+ if c['fullscreen'] and am is not None and am < OPAQUE_ENOUGH:
859
+ rejected.append((c, 'alpha 均值只有 %.0f/255,遮不住底下的东西——'
860
+ '它是叠在底色上的装饰层,不是背景' % am))
374
861
  continue
375
862
  if c['fullscreen']:
376
863
  if c['media'] == cover_media:
377
864
  assets.append({'id': 'bg-cover', 'kind': 'background', 'role': 'cover',
378
- 'src': c, 'use_full': True})
379
- elif c['media'] in bg_needed and bg_i < 5:
865
+ 'src': c,
866
+ # 只有真出了压缩版才能带原图;否则 path/full 指向同一
867
+ # 文件,package.py 必 FAIL(封面不需要转码时就会踩到)
868
+ 'use_full': c['has_compressed']})
869
+ elif c['media'] in bg_needed and bg_i < BG_CONTENT_CAP:
380
870
  bg_i += 1
381
871
  assets.append({'id': 'bg-content-%d' % bg_i, 'kind': 'background',
382
872
  'role': 'content', 'src': c, 'use_full': False})
873
+ elif c['media'] in bg_needed:
874
+ over_cap_bgs.append(c)
875
+ rejected.append((c, '有页型以它为主底,但内容页背景已收满 %d 张' % BG_CONTENT_CAP))
383
876
  else:
384
877
  rejected.append((c, '满屏图但没有页面以它为主底(只在版式层备用)'))
385
- elif c['w_pct'] < 30 and c['n'] >= 2:
878
+ elif c['w_pct'] < SMALL_IMG_W_PCT and c['n'] >= REPEAT_MIN:
879
+ # 品牌标识的共性是「小、重复出现、贴角」。这里只按贴角程度排序给出首选,
880
+ # 不设及格线——「多少分算 logo」没有客观依据,判断交 L 层,分项证据随 TODO 给出。
386
881
  b = c['box']
387
- score = 0
388
- score += 3 if b.get('y', 999) < 160 else (1 if b.get('y', 0) > canvas_w * 0.5 else 0)
389
- score += 2 if b.get('x', 999) < 200 or b.get('x', 0) > canvas_w * 0.7 else 0
390
- ar = (b.get('w') or 1) / max(b.get('h') or 1, 1)
391
- score += 1 if 1.0 <= ar <= 8.0 else 0
392
- score += 1 if c['n'] >= 2 else 0
393
- logo_pool.append((score, c))
882
+ edge_x = min(b.get('x', 0), max(canvas_w - (b.get('x', 0) + (b.get('w') or 0)), 0))
883
+ edge_y = min(b.get('y', 0), max(canvas_h - (b.get('y', 0) + (b.get('h') or 0)), 0))
884
+ corner = (edge_x / canvas_w) + (edge_y / canvas_h) # 越小越贴角
885
+ logo_pool.append((corner, c))
394
886
  else:
395
887
  rejected.append((c, '内容区图片(占宽 %.0f%%,出现 %d 次)' % (c['w_pct'], c['n'])))
396
888
 
@@ -404,46 +896,618 @@ def draft_assets(d, outdir, bg_needed=(), cover_media=None, bg_under=None):
404
896
  from PIL import Image
405
897
  im = Image.open(os.path.join(outdir, row['out'])).convert('RGB')
406
898
  b = c['box']
407
- sx, sy = im.width / float(canvas_w), im.height / float(d['canvas']['px'][1])
899
+ sx, sy = im.width / float(canvas_w), im.height / float(canvas_h)
408
900
  crop = im.crop((int(b.get('x', 0) * sx), int(b.get('y', 0) * sy),
409
901
  max(int((b.get('x', 0) + b.get('w', 1)) * sx), 1),
410
902
  max(int((b.get('y', 0) + b.get('h', 1)) * sy), 1))).resize((16, 16))
411
903
  raw = crop.tobytes()
412
904
  px = [raw[i:i + 3] for i in range(0, len(raw), 3)]
413
- return 'light' if sum(lum(p) for p in px) / len(px) > 0.55 else 'dark'
905
+ return 'light' if sum(lum(p) for p in px) / len(px) > LUM_MID else 'dark'
414
906
  except Exception:
415
907
  return None
416
908
 
417
- logo_pool.sort(key=lambda kv: (-kv[0], -kv[1]['n']))
418
- for i, (score, c) in enumerate(logo_pool):
909
+ # 贴角是品牌标识的定义性特征:离两边都超过画布 1/4 的重复小图,更可能是页内装饰。
910
+ # 这不是「多少分算 logo」那种凑出来的分数线——它直接来自「贴角」这个判据本身。
911
+ LOGO_CORNER_MAX = 0.5 # edge_x/W + edge_y/H,两边各 25% 即到上限
912
+ logo_pool.sort(key=lambda kv: (kv[0], -kv[1]['n']))
913
+ if logo_pool and logo_pool[0][0] > LOGO_CORNER_MAX:
914
+ todos.append('没有贴角的重复小图(最接近的一张离画布边 %.0f%%),本模板可能没有 logo;'
915
+ '确认后要么从联系表挑一张补进 manifest,要么在 gaps 写明模板无品牌标识'
916
+ % (logo_pool[0][0] * 50))
917
+ logo_pool = []
918
+ for i, (corner, c) in enumerate(logo_pool):
419
919
  b = c['box']
420
- if i == 0 and score >= 5:
421
- assets.append({'id': 'logo-primary', 'kind': 'logo', 'role': None, 'src': c,
422
- 'use_full': False, 'on_bg': on_bg_of(c)})
423
- todos.append('看联系表确认 `%s`(%.0fx%.0f @ %.0f,%.0f,出现 %d 次)真是品牌 logo;'
424
- '不是就把 manifest logo-primary 换成别的候选或整条删掉'
425
- % (c['file'], b.get('w', 0), b.get('h', 0), b.get('x', 0), b.get('y', 0), c['n']))
920
+ if i == 0:
921
+ # 贴角、重复只能说明“像 logo”,不能替模型判定。比如一张产品功能角标也会
922
+ # 同时满足这些结构特征;先作为候选保留在联系表与图片槽中,由模型定为 logo
923
+ # content,避免把内容图直接带进风格包。
924
+ rejected.append((c, '贴角重复小图候选(%.0fx%.0f @ %.0f,%.0f,出现 %d 次,'
925
+ '离画布边 %.0f%%),结合样张判断 logo content'
926
+ % (b.get('w', 0), b.get('h', 0), b.get('x', 0), b.get('y', 0),
927
+ c['n'], corner * 50)))
426
928
  else:
427
- rejected.append((c, '重复小图(%.0fx%.0f @ %.0f,%.0f),logo 相似度低于首选'
428
- % (b.get('w', 0), b.get('h', 0), b.get('x', 0), b.get('y', 0))))
929
+ rejected.append((c, '重复小图(%.0fx%.0f @ %.0f,%.0f),贴角程度 %.0f%% 不如首选'
930
+ % (b.get('w', 0), b.get('h', 0), b.get('x', 0), b.get('y', 0),
931
+ corner * 50)))
932
+
933
+ # 体量预算:包内资产总量超 20MB 直接 FAIL(V2-6)。`use_full` 的原图是唯一可能
934
+ # 单张爆预算的东西(未压缩的封面级大图可以单张达到数十 MB),所以在草案期就先丢 full,
935
+ # 不要留给 L 层去撞门禁再回修。
936
+ PACK_BUDGET = 20 * 1024 * 1024
937
+ est = sum(min(a['src'].get('bytes') or 0, ASSET_WARN_SINGLE) for a in assets)
938
+ for a in sorted([x for x in assets if x['use_full']],
939
+ key=lambda x: -(x['src'].get('bytes') or 0)):
940
+ orig = a['src'].get('bytes') or 0
941
+ if est + orig > PACK_BUDGET * 0.9:
942
+ a['use_full'] = False
943
+ todos.append('`%s` 的原图 %.1fMB 会把包撑过 20MB 上限,草案已只保留压缩版;'
944
+ '确实需要原图就改走 url 承载' % (a['id'], orig / 1024.0 / 1024))
945
+ else:
946
+ est += orig
429
947
 
948
+ if over_cap_bgs:
949
+ todos.append('模板有 %d 张内容页背景超出 %d 张上限(%s);用到它们的页型在 layouts.md 里'
950
+ '不会有 background,需要就手工补进 manifest 并删掉不重要的那几张'
951
+ % (len(over_cap_bgs), BG_CONTENT_CAP,
952
+ '、'.join(c['file'] for c in over_cap_bgs[:5])))
430
953
  if not any(a['role'] == 'cover' for a in assets):
431
954
  todos.append('没定出封面底图——从联系表挑一张补进 manifest(role: cover),或在 gaps 写明模板无封面主视觉')
432
955
  copy_logo_candidates(outdir, logo_pool)
433
- return assets, rejected, todos
956
+ return assets, rejected, todos, alias, {c['media']: c for c in kept}
957
+
958
+
959
+ def cover_background_media(archetypes):
960
+ """只从模板明确命名的 cover 页型读取封面背景。"""
961
+ return next((archetype['bg_raw'] for archetype in archetypes
962
+ if archetype['name'] == 'cover'), None)
434
963
 
435
964
 
436
965
  # ---------------------------------------------------------------- 版式聚类
437
966
  DECOR_MIN = 40.0
438
967
 
968
+ # 版式名 → role(模板自己按页型命名时直接用它,别再猜)。
969
+ # 英文词按整词匹配:裸子串会让短词吃掉长词——`end` 一度把 `agenda`、`Appendix`、
970
+ # `Trends Section` 全判成 closing,表里 `agenda -> section` 那条永远轮不到。
971
+ ROLE_BY_WORD = [('封面', 'cover'), ('cover', 'cover'), ('首页', 'cover'),
972
+ ('title slide', 'cover'), ('标题幻灯片', 'cover'),
973
+ ('封底', 'closing'), ('尾页', 'closing'), ('结束', 'closing'),
974
+ ('致谢', 'closing'), ('谢谢', 'closing'), ('end', 'closing'),
975
+ ('thank you', 'closing'), ('closing', 'closing'),
976
+ ('章节', 'section'), ('目录', 'section'), ('过渡', 'section'),
977
+ ('section', 'section'), ('agenda', 'section'),
978
+ ('section header', 'section'), ('节标题', 'section'),
979
+ ('金句', 'quote'), ('问句', 'quote'), ('引言', 'quote'), ('quote', 'quote'),
980
+ ('空白', 'blank'), ('blank', 'blank')]
981
+ PH_TO_TYPE = {'title': 'title', 'ctrTitle': 'title', 'subTitle': 'subtitle',
982
+ 'body': 'body', 'pic': 'pic', 'clipArt': 'pic', 'tbl': 'table',
983
+ 'chart': 'chart', 'media': 'media', 'dgm': 'pic',
984
+ 'sldNum': 'slide-number', 'ftr': 'footer', 'dt': 'footer'}
985
+
986
+
987
+ def role_of_name(name):
988
+ """版式名 → role。认不出返回 None,由调用方降置信度并留 TODO——不要静默当 content。
989
+
990
+ 词表只覆盖中英文;换一种语言命名的模板会整份认不出。那时全落 content 且机检照过,
991
+ 消费端拿到的是「每一页都是内容页」,封面/章节/结束页的语义整个丢掉且无处可查。
992
+ """
993
+ low = (name or '').lower()
994
+ for word, role in ROLE_BY_WORD:
995
+ if word.isascii():
996
+ if re.search(r'(?<![a-z])%s(?![a-z])' % re.escape(word), low):
997
+ return role
998
+ elif word in low:
999
+ return role
1000
+ return None
1001
+
1002
+
1003
+ def clean_layout_name(name):
1004
+ """`1_内容-左右排版(无副标题)` → `内容-左右排版(无副标题)`。"""
1005
+ return re.sub(r'^\d+[_\-\s]*', '', (name or '').strip()) or '未命名版式'
1006
+
1007
+
1008
+ def is_bleed(s):
1009
+ return (s.get('kind') == 'pic' and (s.get('w_pct') or 0) >= 95
1010
+ and (s.get('h_pct') or 0) >= 95)
1011
+
1012
+
1013
+ def top_bleed_media(shapes):
1014
+ """一串形状里最上层的满屏图。
1015
+
1016
+ OOXML 的 spTree 是绘制序,靠后的画在上面。一个版式常叠两张满屏图——通用底纹在
1017
+ 下、这一页的主视觉在上——所以看得见的是最后那张。取第一张会拿到底纹,实测让
1018
+ 章节页的深蓝主视觉被换成了另一张鲜蓝底纹,成品与原稿完全不是一个颜色。
1019
+ """
1020
+ out = None
1021
+ for s in shapes:
1022
+ if is_bleed(s) and s.get('media'):
1023
+ out = s['media']
1024
+ return out
1025
+
1026
+
1027
+ def slot_overlaps(slots):
1028
+ """同一页型里坐标互相重叠的槽对。只报事实,不改坐标——坐标是从模板量的。"""
1029
+ out = []
1030
+ for i in range(len(slots)):
1031
+ for j in range(i + 1, len(slots)):
1032
+ a, b = slots[i].get('box'), slots[j].get('box')
1033
+ if not (a and b):
1034
+ continue
1035
+ ox = min(a[0] + a[2], b[0] + b[2]) - max(a[0], b[0])
1036
+ oy = min(a[1] + a[3], b[1] + b[3]) - max(a[1], b[1])
1037
+ if ox > 0 and oy > 0:
1038
+ out.append('%s×%s 叠 %dx%d' % (slots[i].get('role'), slots[j].get('role'),
1039
+ round(ox), round(oy)))
1040
+ return out
1041
+
1042
+
1043
+ def css_number(value, digits=3):
1044
+ """CSS 数值稳定格式:整数不带小数,其余去掉无意义尾零。"""
1045
+ number = round(float(value), digits)
1046
+ if number == int(number):
1047
+ return str(int(number))
1048
+ return ('%.*f' % (digits, number)).rstrip('0').rstrip('.')
1049
+
1050
+
1051
+ def slot_style(s):
1052
+ """占位符自带的排版样式,统一转成可直接写进 HTML style 的 CSS 声明串。
1053
+
1054
+ 样式可能在三层:lstStyle.lvl1pPr(版式占位符常用)、段落 defRPr(Mac Office
1055
+ 导出把大量属性写在这一层)、段落 pPr(对齐)。逐层兜底,缺一层就往下取。
1056
+
1057
+ `box` 是布局几何,继续由 slot 独立承载;其余渲染属性不再泄漏成 size / color /
1058
+ align / insets_px 等 PPTX 中间字段。下划线开头的键仅供 draft 内部统计,emit_layouts
1059
+ 不会写进消费者产物。
1060
+ """
1061
+ txt = s.get('text') or {}
1062
+ inherited = dict((txt.get('lstStyle') or {}).get('lvl1pPr') or {})
1063
+ ls = {}
1064
+ # 四层逐级兜底,按 OOXML 的就近原则:run rPr → 段落 defRPr → 段落 pPr → lstStyle。
1065
+ # 只枚举前几层会整份漏掉——有的导出器把字号全写在 run rPr 上,lstStyle 一个都没有。
1066
+ for para in (txt.get('paragraphs') or []):
1067
+ srcs = [r for r in (para.get('runs') or [])]
1068
+ srcs.append(para.get('defRPr') or {})
1069
+ srcs.append({k: v for k, v in para.items() if k not in ('runs', 'defRPr')})
1070
+ for src in srcs:
1071
+ for k, v in (src or {}).items():
1072
+ if v is not None:
1073
+ ls.setdefault(k, v)
1074
+ for k, v in inherited.items():
1075
+ if v is not None:
1076
+ ls.setdefault(k, v)
1077
+ if not ls.get('sz_px'):
1078
+ # 仍无声明:退到整形状里出现过的最大字号(generic walk),仍是文件里的值
1079
+ anysz = shape_sz(s)
1080
+ if anysz:
1081
+ ls['sz_px'] = anysz
1082
+ body = txt.get('bodyPr') or {}
1083
+ css = []
1084
+ out = {}
1085
+ insets = body.get('insets_px') or {}
1086
+ if insets:
1087
+ css.append('box-sizing: border-box')
1088
+ css.append('padding: %spx %spx %spx %spx' % (
1089
+ css_number(insets.get('tIns', 0) or 0),
1090
+ css_number(insets.get('rIns', 0) or 0),
1091
+ css_number(insets.get('bIns', 0) or 0),
1092
+ css_number(insets.get('lIns', 0) or 0),
1093
+ ))
1094
+ if ls.get('sz_px'):
1095
+ # normAutofit 的 fontScale 是模板让大字装进小框的手段——不乘它,消费端拿到的是
1096
+ # 未缩放字号,字比框高,渐变裁切会把溢出的底部切成透明。缺省 1.0(无 autofit / 无缩放)。
1097
+ scale = body.get('font_scale')
1098
+ raw = ls['sz_px'] * scale if scale else ls['sz_px']
1099
+ size = round(raw)
1100
+ css.append('font-size: %dpx' % size)
1101
+ out['_font_size'] = size
1102
+ typeface = ls.get('ea') or ls.get('latin') or ls.get('cs')
1103
+ if typeface:
1104
+ css.append('font-family: %s' % font_css([typeface]))
1105
+ weight = ls.get('weight') or (700 if ls.get('bold') else None)
1106
+ if weight:
1107
+ css.append('font-weight: %s' % weight)
1108
+ out['_font_weight'] = weight
1109
+ if ls.get('italic'):
1110
+ css.append('font-style: italic')
1111
+ decorations = []
1112
+ if ls.get('underline'):
1113
+ decorations.append('underline')
1114
+ if ls.get('strike'):
1115
+ decorations.append('line-through')
1116
+ if decorations:
1117
+ css.append('text-decoration: %s' % ' '.join(decorations))
1118
+ if ls.get('spc_px') is not None:
1119
+ css.append('letter-spacing: %spx' % css_number(ls['spc_px']))
1120
+ col = (ls.get('color') or {}).get('resolved')
1121
+ if col:
1122
+ css.append('color: %s' % col)
1123
+ out['_color'] = col
1124
+ else:
1125
+ # 占位符的字色也可以是 gradFill(章节页的大号序号常这么做)。解析层已经把
1126
+ # stops 和角度记全了,这里只取单色就会整条丢掉,消费端只能自己编一个平色。
1127
+ # 与 decor 同一约定:css 是可直接写进 style 的声明串。
1128
+ f = ls.get('fill') or {}
1129
+ if f.get('type') == 'gradient':
1130
+ g = _load_query()._css_gradient(f)
1131
+ if g:
1132
+ css += ['background-image: %s' % g, '-webkit-background-clip: text',
1133
+ 'background-clip: text', 'color: transparent']
1134
+ align = ls.get('algn')
1135
+ if align:
1136
+ css.append('text-align: %s' % {
1137
+ 'l': 'left', 'ctr': 'center', 'r': 'right', 'just': 'justify',
1138
+ }.get(align, align))
1139
+ line_spacing = ls.get('lnSpc') or {}
1140
+ # normAutofit 的 lnSpcReduction 与 fontScale 同时把行距压缩,一起缩才装得进原框。
1141
+ reduction = body.get('ln_spc_reduction') or 0
1142
+ if line_spacing.get('mult'):
1143
+ mult = line_spacing['mult'] * 1.2 * (1 - reduction)
1144
+ css.append('line-height: %s' % css_number(mult))
1145
+ elif line_spacing.get('px'):
1146
+ css.append('line-height: %spx' % css_number(line_spacing['px'] * (1 - reduction)))
1147
+ anchor = body.get('anchor')
1148
+ if anchor in ('ctr', 'b'):
1149
+ css += ['display: flex', 'flex-direction: column',
1150
+ 'justify-content: %s' % {'ctr': 'center', 'b': 'flex-end'}[anchor]]
1151
+ if body.get('rot'):
1152
+ try:
1153
+ degrees = float(body['rot']) / 60000.0
1154
+ css.append('rotate: %sdeg' % css_number(degrees))
1155
+ except (TypeError, ValueError):
1156
+ pass
1157
+ if css:
1158
+ out['css'] = '; '.join(css)
1159
+ return out
1160
+
1161
+
1162
+ def instance_override(shapes, slide_part, slots, bgm, cW, cH, composites=None):
1163
+ """实例页覆盖版式:版式是骨架,实例页才是设计师最终摆定的样子。
1164
+
1165
+ 版式底图常是多个版式共用的通用底纹,实例页可能另铺主视觉大图;标题占位符的框高
1166
+ 也常被实例页放大以容纳多行。只读版式的包会让消费端拿到错的底图和装不下字的框,
1167
+ 只能自己缩字号。
1168
+ """
1169
+ ins = [s for s in shapes if s.get('part') == slide_part]
1170
+ if not ins:
1171
+ return slots, bgm
1172
+ bgm = (composites or {}).get(slide_part) or top_bleed_media(ins) or bgm
1173
+ texts = []
1174
+ for s in ins:
1175
+ b = s.get('box') or {}
1176
+ if not (b.get('w') and b.get('h')) or not shape_text(s):
1177
+ continue
1178
+ texts.append({'sz': shape_sz(s), 'box': b, 'style': slot_style(s)})
1179
+ texts.sort(key=lambda x: -x['sz'])
1180
+ # 按字号大小依次顶替版式的文字槽(版式槽已按 y 排过,字号序更贴合语义层级)
1181
+ tslots = [s for s in slots if s['type'] != 'pic']
1182
+ for slot, ins_t in zip(sorted(tslots, key=lambda s: -(s.get('sz') or 0)), texts):
1183
+ b = ins_t['box']
1184
+ slot['box'] = [round(b.get('x', 0)), round(b.get('y', 0)),
1185
+ round(b.get('w', 0)), round(b.get('h', 0))]
1186
+ slot['sz'] = ins_t['sz']
1187
+ slot.update(ins_t['style'] or {})
1188
+ return slots, bgm
1189
+
1190
+
1191
+ def layouts_from_template(d, shapes, cW, cH):
1192
+ """form=3:模板自己用 slideLayout 声明了页型,直接读版式层。
1193
+
1194
+ 拿样张聚类只能得到「样张数」个 archetype——模板往往只放 1-2 张样张,
1195
+ 真正的页型全在版式里。模板常见只放个位数样张却声明几十个语义版式,按样张聚类
1196
+ 只能得到「样张数」个 archetype,消费端搭页时大半无版式可抄,只能自己编。
1197
+ """
1198
+ by_part = defaultdict(list)
1199
+ for s in shapes:
1200
+ if (s.get('layer') == 'layout' and s.get('kind') == 'sp'
1201
+ and (s.get('box') or {}).get('w') and (s.get('ph') or shape_text(s))):
1202
+ by_part[s['part']].append(s)
1203
+ bg_of_layout = {}
1204
+ composites = d.get('background_composites') or {}
1205
+ for s in shapes:
1206
+ if s.get('layer') == 'layout' and is_bleed(s) and s.get('media'):
1207
+ bg_of_layout[s['part']] = s['media'] # 靠后者在上层,最后一张才是看得见的
1208
+ topo = d.get('theme_topology') or {}
1209
+ theme_of_master = {m['master']: m.get('theme_label')
1210
+ for m in (topo.get('per_master') or [])}
1211
+ master_of = (d.get('reference_graph') or {}).get('master_of_layout') or {}
1212
+ # 只在版式恰好被 1 张实例页使用时才拿实例覆盖:多张实例共用一个版式时,
1213
+ # 谁都不代表版式本身,硬挑一张会把别页的构图当成页型
1214
+ lay_of_slide = (d.get('reference_graph') or {}).get('layout_of_slide') or {}
1215
+ used_n = Counter(lay_of_slide.values())
1216
+ slide_of_layout = {lp: sp for sp, lp in lay_of_slide.items() if used_n[lp] == 1}
1217
+ sample_pages_of_layout = defaultdict(list)
1218
+ for slide_part, layout_part in lay_of_slide.items():
1219
+ sample_pages_of_layout[layout_part].append(slide_no(slide_part))
1220
+ default_theme = topo.get('default')
1221
+ multi = len(topo.get('themes') or []) > 1
1222
+
1223
+ rows = []
1224
+ for l in d.get('layouts') or []:
1225
+ phs = [s for s in by_part.get(l['part'], []) if (s.get('box') or {}).get('w')]
1226
+ if not phs:
1227
+ continue
1228
+ theme = theme_of_master.get(master_of.get(l['part']))
1229
+ phs.sort(key=lambda s: ((s['box'].get('y') or 0), (s['box'].get('x') or 0)))
1230
+ slots, seen_kind = [], set()
1231
+ for s in phs:
1232
+ t = PH_TO_TYPE.get((s.get('ph') or {}).get('type'), 'body')
1233
+ if t in ('slide-number', 'footer') and not shape_text(s):
1234
+ continue # 空 chrome 占位符不是实际元素
1235
+ b = s['box']
1236
+ role = t if t in ('title', 'subtitle', 'footer', 'slide-number') else 'body'
1237
+ if t == 'title' and 'title' in seen_kind:
1238
+ role, t = 'subtitle', 'subtitle'
1239
+ seen_kind.add(t)
1240
+ row = {'role': role, 'type': t, 'sz': shape_sz(s),
1241
+ 'box': [round(b.get('x', 0)), round(b.get('y', 0)),
1242
+ round(b.get('w', 0)), round(b.get('h', 0))],
1243
+ 'txt': shape_text(s) or (s.get('name') or '')[:24]}
1244
+ row.update(slot_style(s))
1245
+ if t == 'body':
1246
+ ph = s.get('ph') or {}
1247
+ row.update({
1248
+ '_needs_role': True,
1249
+ '_source_layer': 'layout',
1250
+ '_placeholder': '%s/%s' % (
1251
+ ph.get('type') or '-', ph.get('idx') or '-'),
1252
+ })
1253
+ slots.append(row)
1254
+ # 非满屏的图片元素(logo / 联名标 / 装饰)——它们逐版式换位置换尺寸,
1255
+ # 必须按版式落进 slots,压成一条全局「固定位」规则就会撞标题。
1256
+ bgm = composites.get(l['part']) or bg_of_layout.get(l['part'])
1257
+ for s in shapes:
1258
+ if s['part'] != l['part'] or s.get('kind') != 'pic' or not s.get('media'):
1259
+ continue
1260
+ if s['media'] == bgm or (s.get('w_pct', 0) >= 95 and s.get('h_pct', 0) >= 95):
1261
+ continue
1262
+ b = s.get('box') or {}
1263
+ if not b.get('w'):
1264
+ continue
1265
+ slots.append({'role': 'logo', 'type': 'pic', 'sz': 0, 'txt': '',
1266
+ 'media': s['media'],
1267
+ 'box': [round(b.get('x', 0)), round(b.get('y', 0)),
1268
+ round(b.get('w', 0)), round(b.get('h', 0))]})
1269
+ if not slots:
1270
+ continue
1271
+ inst = slide_of_layout.get(l['part'])
1272
+ if inst:
1273
+ slots, bgm = instance_override(
1274
+ shapes, inst, slots, bgm, cW, cH, composites)
1275
+ taken = {tuple(s['box']) for s in slots}
1276
+ decor = collect_decor(shapes, inst or l['part'], taken, (cW, cH))
1277
+ named_role = role_of_name(l.get('name'))
1278
+ rows.append({'zh': clean_layout_name(l.get('name')),
1279
+ 'role': named_role or 'content', 'role_guessed': named_role is None,
1280
+ 'slots': slots, 'decor': decor, 'bg_raw': bgm,
1281
+ 'theme': theme, 'part': l['part'],
1282
+ 'used': l.get('used_by_slides') or 0})
1283
+
1284
+ # 同名版式在 dark/light 两套 master 下各有一份——按名字归一,优先默认主题那份
1285
+ best = {}
1286
+ for r in rows:
1287
+ k = r['zh']
1288
+ cur = best.get(k)
1289
+ if cur is None or (r['theme'] == default_theme and cur['theme'] != default_theme) \
1290
+ or (r['used'] > cur['used']):
1291
+ best[k] = r
1292
+ picked = sorted(best.values(), key=lambda r: (
1293
+ ['cover', 'section', 'quote', 'content', 'closing', 'blank'].index(r['role'])
1294
+ if r['role'] in ('cover', 'section', 'quote', 'content', 'closing', 'blank') else 9,
1295
+ -r['used'], r['part']))
1296
+
1297
+ used_key = Counter()
1298
+ arch = []
1299
+ for r in picked:
1300
+ used_key[r['role']] += 1
1301
+ n = used_key[r['role']]
1302
+ key = r['role'] if n == 1 else '%s-%d' % (r['role'], n)
1303
+ m_no = re.search(r'slideLayout(\d+)\.xml$', r['part'])
1304
+ arch.append({'name': key, 'zh': r['zh'], 'role': r['role'], 'bg': None,
1305
+ 'role_guessed': r.get('role_guessed'),
1306
+ 'bg_raw': r['bg_raw'], 'slots': r['slots'],
1307
+ 'decor': r.get('decor') or [], 'pages': [],
1308
+ 'rep': None, 'rep_layout': int(m_no.group(1)) if m_no else None,
1309
+ # 版式名认不出 role 时不装作有把握:置信度降到 low,让 L 层看图定
1310
+ 'pic_n': 0, 'confidence': 'low' if r.get('role_guessed') else 'high',
1311
+ 'theme': r['theme'] if multi else None,
1312
+ '_layout_part': r['part'],
1313
+ '_sample_pages': sorted(sample_pages_of_layout.get(r['part']) or []),
1314
+ 'source': 'layout:' + r['part'].split('/')[-1]})
1315
+ return arch
1316
+
1317
+
1318
+ _QUERY = []
1319
+
1320
+
1321
+ def _load_query():
1322
+ """复用 query.py 的 OOXML→CSS 渲染,不再写第二份。"""
1323
+ if not _QUERY:
1324
+ import importlib.util
1325
+ spec = importlib.util.spec_from_file_location('_q', os.path.join(HERE, 'query.py'))
1326
+ mod = importlib.util.module_from_spec(spec)
1327
+ spec.loader.exec_module(mod)
1328
+ _QUERY.append(mod)
1329
+ return _QUERY[0]
1330
+
1331
+
1332
+ def collect_decor(shapes, part, taken_boxes, canvas, limit=10):
1333
+ """页面上撑起版式骨架、但不含文字的形状(圆形图标托、卡片、分隔线)。
1334
+
1335
+ 只给文字框的坐标,消费端看到的是「一段说明悬在半空、上方一片空白」,只能自己编
1336
+ 容器,编出来的形状与模板无关。这些形状必须进包。
1337
+ """
1338
+ q = _load_query()
1339
+ cW, cH = canvas
1340
+ out = []
1341
+ for s in shapes:
1342
+ if s.get('part') != part or s.get('kind') != 'sp':
1343
+ continue
1344
+ if any(r.get('text', '').strip()
1345
+ for para in ((s.get('text') or {}).get('paragraphs') or [])
1346
+ for r in (para.get('runs') or [])):
1347
+ continue # 有文字的已经作为 slot 出过
1348
+ b = s.get('box') or {}
1349
+ w, h = b.get('w') or 0, b.get('h') or 0
1350
+ if not (w or h):
1351
+ continue # 零尺寸形状渲染不出任何东西
1352
+ if canvas_coverage(b, cW, cH) >= FULLSCREEN_COVERAGE:
1353
+ continue # 满屏底,属 background
1354
+ box = [round(b.get('x', 0)), round(b.get('y', 0)), round(w), round(h)]
1355
+ if tuple(box) in taken_boxes:
1356
+ continue
1357
+ css = q._recipe_css(s.get('fill'), s.get('line'),
1358
+ [s.get('radius_px')] if s.get('radius_px') else [], s.get('effects'))
1359
+ # 声明要落成单行:含换行的声明会被下游的行式解析器从换行处截断,
1360
+ # 且只记 PARSE-WARN 不 FAIL,整包照常出厂——带着半条渲染不出来的 CSS
1361
+ css = [re.sub(r'\s*\n\s*', ' ', c.split('\x00')[0]).strip() for c in css if c]
1362
+ if not css:
1363
+ continue # 无填充无描边无阴影 = 看不见,不占篇幅
1364
+ out.append({'box': box, 'geom': (s.get('geom') or {}).get('prst') or 'rect',
1365
+ 'css': '; '.join(css), 'area': max(w * h, w, h)})
1366
+ # 按面积降序取前 limit 条:撑起版式的结构性形状总在最前,零星噪点自然落在截断线外,
1367
+ # 不需要再设一个「多小算噪点」的尺寸门槛(那种门槛会误杀 1px 分隔线)。
1368
+ out.sort(key=lambda d: -d['area'])
1369
+ note_truncation('装饰形状', limit, len(out), '按面积降序保留,剩下的多是零星小件',
1370
+ part.split('/')[-1])
1371
+ return out[:limit] # 同款不同位置都要留,位置本身是版式信息
1372
+
1373
+
1374
+ def placeholder_key(shape):
1375
+ ph = shape.get('ph') or {}
1376
+ if not ph:
1377
+ return None
1378
+ return (ph.get('type') or 'body', str(ph.get('idx') or ''))
1379
+
1380
+
1381
+ def merge_dict(base, override):
1382
+ """把实例页的非空声明叠到版式声明上;空实例占位符继续继承版式事实。"""
1383
+ out = copy.deepcopy(base or {})
1384
+ for key, value in (override or {}).items():
1385
+ if value is None or value == []:
1386
+ continue
1387
+ if isinstance(value, dict) and isinstance(out.get(key), dict):
1388
+ out[key] = merge_dict(out[key], value)
1389
+ else:
1390
+ out[key] = copy.deepcopy(value)
1391
+ return out
1392
+
1393
+
1394
+ def inherited_text_shapes(layout_shapes, slide_shapes):
1395
+ """返回实例页可用的文字形状,并补齐其引用版式中的占位符几何与样式。"""
1396
+ layout_text = []
1397
+ for shape in layout_shapes:
1398
+ if shape.get('kind') != 'sp' or not (shape.get('box') or {}).get('w'):
1399
+ continue
1400
+ ph = shape.get('ph') or {}
1401
+ ph_type = ph.get('type')
1402
+ if shape_text(shape) or (ph and ph_type not in ('ftr', 'dt', 'sldNum')):
1403
+ layout_text.append(shape)
1404
+ by_placeholder = {placeholder_key(s): s for s in layout_text if placeholder_key(s)}
1405
+ used = set()
1406
+ out = []
1407
+ for shape in slide_shapes:
1408
+ if shape.get('kind') != 'sp':
1409
+ continue
1410
+ key = placeholder_key(shape)
1411
+ base = by_placeholder.get(key)
1412
+ if base:
1413
+ merged = merge_dict(base, shape)
1414
+ merged['text'] = merge_dict(base.get('text'), shape.get('text'))
1415
+ if not shape_text(shape):
1416
+ merged['text']['paragraphs'] = copy.deepcopy(
1417
+ (base.get('text') or {}).get('paragraphs') or [])
1418
+ used.add(key)
1419
+ out.append((merged, 'slide+layout'))
1420
+ elif (shape.get('box') or {}).get('w') and shape_text(shape):
1421
+ out.append((shape, 'slide'))
1422
+ for shape in layout_text:
1423
+ key = placeholder_key(shape)
1424
+ if key not in used:
1425
+ out.append((shape, 'layout'))
1426
+ return out
1427
+
1428
+
1429
+ def slide_image_marks(data, included_fullscreen=()):
1430
+ """从图片普查补齐形状图片填充;它们没有独立 pic 节点,但仍有媒体与坐标。"""
1431
+ allowed_fullscreen = set(included_fullscreen)
1432
+ out = defaultdict(list)
1433
+ for image in data.get('images') or []:
1434
+ media = image.get('media')
1435
+ if not media or (image.get('fullscreen') and media not in allowed_fullscreen):
1436
+ continue
1437
+ for cluster in image.get('boxes') or []:
1438
+ box = cluster.get('box')
1439
+ if not box or not box.get('w'):
1440
+ continue
1441
+ for part in cluster.get('parts') or []:
1442
+ if '/slides/' not in part and '/slideLayouts/' not in part:
1443
+ continue
1444
+ out[part].append({'media': media, 'box': box})
1445
+ return out
1446
+
439
1447
 
440
- def draft_layouts(d, outdir):
441
- shapes = json.load(open(os.path.join(outdir, 'ref', 'shapes.json'), encoding='utf-8'))['shapes']
1448
+ def add_template_image_marks(archetypes, data, included_fullscreen=()):
1449
+ """把版式和实例页的图片填充补进 form=3 页型。"""
1450
+ marks_by_part = slide_image_marks(data, included_fullscreen)
1451
+ layout_of_slide = (data.get('reference_graph') or {}).get('layout_of_slide') or {}
1452
+ by_layout = {archetype.get('_layout_part'): archetype for archetype in archetypes}
1453
+ for part, marks in marks_by_part.items():
1454
+ layout_part = layout_of_slide.get(part, part)
1455
+ archetype = by_layout.get(layout_part)
1456
+ if not archetype:
1457
+ continue
1458
+ seen = {
1459
+ (slot.get('media'), tuple(slot.get('box') or ()))
1460
+ for slot in archetype.get('slots') or []
1461
+ if slot.get('media')
1462
+ }
1463
+ for mark in marks:
1464
+ box = mark['box']
1465
+ rounded = [round(box.get(key, 0)) for key in ('x', 'y', 'w', 'h')]
1466
+ key = (mark['media'], tuple(rounded))
1467
+ if key in seen:
1468
+ continue
1469
+ seen.add(key)
1470
+ archetype['slots'].append({
1471
+ 'role': 'logo',
1472
+ 'type': 'pic',
1473
+ 'sz': 0,
1474
+ 'txt': '',
1475
+ 'media': mark['media'],
1476
+ 'box': rounded,
1477
+ })
1478
+
1479
+
1480
+ def preserve_image_bearing_groups(kept, ranked):
1481
+ """有图片实例的孤例保留自己的页型,避免把资产绑定到近似但错误的版式。"""
1482
+ return kept + [
1483
+ group for group in ranked
1484
+ if group not in kept and any(page.get('marks') for page in group[1])
1485
+ ]
1486
+
1487
+
1488
+ def draft_layouts(d, outdir, effective_alpha=None):
1489
+ with open(os.path.join(outdir, 'ref', 'shapes.json'), encoding='utf-8') as stream:
1490
+ shapes = json.load(stream)['shapes']
442
1491
  cW, cH = d['canvas']['px']
1492
+ if effective_alpha is None:
1493
+ effective_alpha = fullscreen_effective_alpha(d, outdir, shapes)
1494
+ overlay_media = {
1495
+ media for media, alpha in effective_alpha.items()
1496
+ if 13 <= alpha < OPAQUE_ENOUGH
1497
+ }
1498
+ if (d.get('form_hint') or {}).get('form') == 3:
1499
+ arch = layouts_from_template(d, shapes, cW, cH)
1500
+ if len(arch) >= 3:
1501
+ add_template_image_marks(arch, d, overlay_media)
1502
+ return arch, [], []
443
1503
  by_slide = defaultdict(list)
1504
+ by_layout = defaultdict(list)
444
1505
  for s in shapes:
445
1506
  if s.get('layer') == 'slide':
446
1507
  by_slide[s['part']].append(s)
1508
+ elif s.get('layer') == 'layout':
1509
+ by_layout[s['part']].append(s)
1510
+ image_marks = slide_image_marks(d, overlay_media)
447
1511
 
448
1512
  bg_of_slide, layout_of_slide = {}, {}
449
1513
  for s in d.get('slides', []):
@@ -451,94 +1515,200 @@ def draft_layouts(d, outdir):
451
1515
  bg_of_slide[s['part']] = json.dumps(bg, sort_keys=True) if isinstance(bg, dict) else bg
452
1516
  layout_of_slide[s['part']] = s.get('layout')
453
1517
  # 版式层的满屏底图(form=2 常态:底图挂在 layout 上)
1518
+ composites = d.get('background_composites') or {}
454
1519
  bg_of_layout = {}
455
1520
  for s in shapes:
456
- if (s.get('layer') == 'layout' and s.get('kind') == 'pic'
457
- and s.get('w_pct', 0) >= 95 and s.get('h_pct', 0) >= 95):
458
- bg_of_layout.setdefault(s['part'], s.get('media'))
1521
+ if s.get('layer') == 'layout' and is_bleed(s) and s.get('media'):
1522
+ bg_of_layout[s['part']] = s['media']
459
1523
 
460
1524
  pages = []
461
1525
  for part, sh in sorted(by_slide.items(), key=lambda kv: slide_no(kv[0])):
462
- bg_media = None
463
- for s in sh:
464
- if s.get('kind') == 'pic' and s.get('w_pct', 0) >= 95 and s.get('h_pct', 0) >= 95:
465
- bg_media = s.get('media')
466
- break
1526
+ layout_part = layout_of_slide.get(part)
1527
+ layout_shapes = by_layout.get(layout_part) or []
1528
+ bg_media = top_bleed_media(sh)
467
1529
  if bg_media is None:
468
- bg_media = bg_of_layout.get(layout_of_slide.get(part))
1530
+ bg_media = bg_of_layout.get(layout_part)
1531
+ rendered_bg = (composites.get(part)
1532
+ or composites.get(layout_part)
1533
+ or bg_media)
469
1534
  texts = []
470
- for s in sh:
471
- if s.get('kind') != 'sp':
472
- continue
473
- txt = shape_text(s)
474
- if not txt:
475
- continue
1535
+ for s, source_layer in inherited_text_shapes(layout_shapes, sh):
1536
+ txt = shape_text(s) or (s.get('name') or '')[:24]
476
1537
  b = s.get('box') or {}
477
1538
  if b.get('w', 0) < DECOR_MIN or b.get('h', 0) < 16:
478
1539
  continue
479
- texts.append({'sz': shape_sz(s), 'box': b, 'txt': txt})
1540
+ ph = s.get('ph') or {}
1541
+ ph_type = ph.get('type')
1542
+ direct_type = PH_TO_TYPE.get(ph_type, 'body')
1543
+ texts.append({
1544
+ 'sz': shape_sz(s),
1545
+ 'box': b,
1546
+ 'txt': txt,
1547
+ 'style': slot_style(s),
1548
+ 'direct_type': direct_type,
1549
+ 'needs_role': direct_type == 'body',
1550
+ 'source_layer': source_layer,
1551
+ 'placeholder': '%s/%s' % (ph_type or '-', ph.get('idx') or '-'),
1552
+ })
480
1553
  texts.sort(key=lambda t: (-t['sz'], t['box'].get('y', 0)))
481
- pics = [s for s in sh if s.get('kind') == 'pic' and s.get('w_pct', 0) < 95]
1554
+ visible_shapes = layout_shapes + sh
1555
+ pics = []
1556
+ for shape in visible_shapes:
1557
+ if shape.get('kind') != 'pic':
1558
+ continue
1559
+ if shape.get('w_pct', 0) < 95 or shape.get('media') in overlay_media:
1560
+ pics.append(shape)
1561
+ # 小图元素(logo / 角标 / 装饰)逐页记位置,供 archetype 落 slots
1562
+ marks = [{'media': s['media'], 'box': s['box']} for s in pics
1563
+ if s.get('media') and (s.get('box') or {}).get('w')]
1564
+ seen_marks = {
1565
+ (mark['media'], round(mark['box'].get('x', 0)), round(mark['box'].get('y', 0)))
1566
+ for mark in marks
1567
+ }
1568
+ for mark in image_marks.get(part) or []:
1569
+ key = (mark['media'], round(mark['box'].get('x', 0)),
1570
+ round(mark['box'].get('y', 0)))
1571
+ if key not in seen_marks:
1572
+ seen_marks.add(key)
1573
+ marks.append(mark)
482
1574
  pages.append({'part': part, 'no': slide_no(part), 'bg_media': bg_media,
1575
+ 'rendered_bg': rendered_bg,
483
1576
  'bg_color': bg_of_slide.get(part), 'texts': texts, 'pic_n': len(pics),
484
- 'shape_n': len(sh)})
1577
+ 'marks': marks, 'shape_n': len(visible_shapes), 'layout': layout_part})
485
1578
 
486
- def kind_of(p):
1579
+ # 页型的**角色**(封面 / 章节页 / 内容页……)不在这里判:那是看图才能下的结论,
1580
+ # 交给读得到重建图的模型。脚本只做客观归并——同一张底图 + 文字块数量相近的页
1581
+ # 归成一组,档位按本 deck 自己的分布切,不用「字号 ≥60 就是章节页」这类固定数。
1582
+ ns = sorted(len(p['texts']) for p in pages) or [0]
1583
+ q1, q2 = ns[len(ns) // 3], ns[len(ns) * 2 // 3]
1584
+
1585
+ def density_band(p):
487
1586
  n = len(p['texts'])
488
- top = p['texts'][0]['sz'] if p['texts'] else 0
489
- if p['no'] == 1:
490
- return 'cover'
491
- if n <= 3 and top >= 60:
492
- return 'section'
493
- if n >= 8 or p['pic_n'] >= 4:
494
- return 'content-dense'
495
- return 'content'
1587
+ return 0 if n <= q1 else (1 if n <= q2 else 2)
496
1588
 
1589
+ last_page_no = max((p['no'] for p in pages), default=None)
497
1590
  groups = defaultdict(list)
498
1591
  for p in pages:
499
- groups[(p['bg_media'] or p['bg_color'] or 'none', kind_of(p))].append(p)
1592
+ if p['no'] == 1:
1593
+ # 首页单独成组:它是 deck 唯一的入口页,版面通常和后面任何一页都不同,
1594
+ # 并进别的组就会被代表页顶掉、坐标全丢。这只是不合并,不代表它是封面。
1595
+ groups[('__first__', -1)] = [p]
1596
+ continue
1597
+ if p['no'] == last_page_no:
1598
+ # 末页也单独保留完整结构:它可能是封底,也可能只是最后一张内容页,脚本
1599
+ # 不替模型下结论。和首页一样,拆组只避免它被聚类代表页吞掉。
1600
+ groups[('__last__', -2)] = [p]
1601
+ continue
1602
+ groups[(p['bg_media'] or p['bg_color'] or 'none', density_band(p))].append(p)
500
1603
 
501
1604
  ranked = sorted(groups.items(), key=lambda kv: (-len(kv[1]), kv[1][0]['no']))
502
- kept = [g for g in ranked if len(g[1]) >= 2 or g[0][1] == 'cover'][:8]
1605
+ # 首页所在的组一定收——deck 的第一页是模板的门面,孤例也不能被名额挤掉。
1606
+ # 这只保证它进包,它是不是封面由看图的人定。
1607
+ first = [g for g in ranked if g[0][0] == '__first__']
1608
+ last = [g for g in ranked if g[0][0] == '__last__']
1609
+ kept = first + last + [
1610
+ g for g in ranked
1611
+ if g not in first and g not in last and len(g[1]) >= 2
1612
+ ][:max(0, 8 - len(first) - len(last))]
503
1613
  for g in ranked: # 名额没用满就把最大的孤例页也收进来
504
1614
  if len(kept) >= 8:
505
1615
  break
506
1616
  if g not in kept:
507
1617
  kept.append(g)
1618
+ # 图片用途必须与它实际所在的版式绑定。若把图片孤例并到“最接近”页型,装饰会被
1619
+ # 绑定到错误布局;是否为内容图、logo 墙或装饰由后续模型看图判断,不按图片数量猜。
1620
+ kept = preserve_image_bearing_groups(kept, ranked)
508
1621
  leftover = sorted(p['no'] for g in ranked if g not in kept for p in g[1])
509
1622
 
510
1623
  archetypes = []
511
- used = Counter()
512
- for (bg_raw, kind), ps in kept:
1624
+ for gi, ((bg_raw, _band), ps) in enumerate(kept, 1):
513
1625
  rep = max(ps, key=lambda p: len(p['texts']))
514
- used[kind] += 1
515
- name = kind if used[kind] == 1 else '%s-%d' % (kind, used[kind])
516
- # 标题按「位置 + 跨度」认,不按字号——巨号数值(21%、7,869)常比标题还大
517
- band = [t for t in rep['texts']
518
- if t['box'].get('y', 1e9) < cH * 0.28 and t['box'].get('w', 0) >= cW * 0.25]
519
- title = max(band, key=lambda t: t['sz']) if band else (
1626
+ if bg_raw == '__first__':
1627
+ bg_raw = rep['bg_media'] or rep['bg_color'] or 'none'
1628
+ elif bg_raw == '__last__':
1629
+ bg_raw = rep['bg_media'] or rep['bg_color'] or 'none'
1630
+ rendered_bg = rep.get('rendered_bg')
1631
+ if rendered_bg:
1632
+ bg_raw = rendered_bg
1633
+ name = 'layout-%d' % gi
1634
+ # 标题按「位置 + 跨度」认,不按字号——big-number 类的巨号数值常比标题还大
1635
+ # 标题 = 该页最靠上的那批文本里最宽的一块。不按「画布前 28%」这类固定比例切:
1636
+ # 版心靠下的模板会整页认不出标题。以该页自身的文本框分布定「靠上」。
1637
+ ys = sorted(t['box'].get('y', 0) for t in rep['texts'])
1638
+ y_cut = ys[max(len(ys) // 4, 0)] if ys else 0
1639
+ band = [t for t in rep['texts'] if t['box'].get('y', 1e9) <= y_cut]
1640
+ title = max(band, key=lambda t: (t['box'].get('w', 0), t['sz'])) if band else (
520
1641
  max(rep['texts'], key=lambda t: t['sz']) if rep['texts'] else None)
521
1642
  rest = [t for t in rep['texts'] if t is not title]
522
1643
  rest.sort(key=lambda t: (t['box'].get('y', 0), t['box'].get('x', 0)))
523
1644
  ordered = ([title] if title else []) + rest
524
1645
  slots = []
525
- for i, t in enumerate(ordered[:6]):
1646
+ for i, t in enumerate(ordered):
526
1647
  b = t['box']
527
- if t is title:
1648
+ if t.get('needs_role'):
1649
+ role = typ = 'body'
1650
+ elif t.get('direct_type') in ('title', 'subtitle', 'footer', 'slide-number'):
1651
+ role = typ = t['direct_type']
1652
+ elif t is title:
528
1653
  role = typ = 'title'
529
- elif (title and i == 1 and t['sz'] >= 28
530
- and abs(b.get('x', 0) - title['box'].get('x', 0)) < 120
1654
+ elif (title and i == 1
1655
+ # 副标题 = 紧跟在标题下方、与标题左对齐的那一块。三个量都相对标题
1656
+ # 自身:绝对 px 门槛在大字号排版的模板上会整片认不出来。
1657
+ and abs(b.get('x', 0) - title['box'].get('x', 0)) <= title['box'].get('h', 0)
531
1658
  and 0 <= b.get('y', 0) - (title['box'].get('y', 0)
532
- + title['box'].get('h', 0)) < 220):
1659
+ + title['box'].get('h', 0))
1660
+ <= title['box'].get('h', 0) * 2):
533
1661
  role = typ = 'subtitle'
534
1662
  else:
535
1663
  role = typ = 'body'
536
- slots.append({'role': role, 'box': [round(b.get('x', 0)), round(b.get('y', 0)),
537
- round(b.get('w', 0)), round(b.get('h', 0))],
538
- 'type': typ, 'sz': t['sz'], 'txt': t['txt']})
1664
+ row = {'role': role, 'box': [round(b.get('x', 0)), round(b.get('y', 0)),
1665
+ round(b.get('w', 0)), round(b.get('h', 0))],
1666
+ 'type': typ, 'sz': t['sz'], 'txt': t['txt']}
1667
+ row.update(t.get('style') or {})
1668
+ if t.get('needs_role'):
1669
+ row.update({
1670
+ '_needs_role': True,
1671
+ '_source_layer': t.get('source_layer'),
1672
+ '_placeholder': t.get('placeholder'),
1673
+ })
1674
+ slots.append(row)
1675
+ # 同组页面上的图片元素按素材+位置去重后落候选 slots。内容图去掉具体资产引用,
1676
+ # 保留通用图片槽;装饰图绑定资产,避免非代表页上的装饰没有进入 layouts。
1677
+ seen_mark = set()
1678
+ for page in ps:
1679
+ for mk in page.get('marks') or []:
1680
+ b = mk['box']
1681
+ key = (mk['media'], round(b.get('x', 0)), round(b.get('y', 0)))
1682
+ if key in seen_mark:
1683
+ continue
1684
+ seen_mark.add(key)
1685
+ slots.append({'role': 'logo', 'type': 'pic', 'sz': 0, 'txt': '',
1686
+ 'media': mk['media'],
1687
+ 'box': [round(b.get('x', 0)), round(b.get('y', 0)),
1688
+ round(b.get('w', 0)), round(b.get('h', 0))]})
1689
+ taken = {tuple(s['box']) for s in slots}
1690
+ decor = []
1691
+ seen_decor = set()
1692
+ for source_part in (rep.get('layout'), rep['part']):
1693
+ for item in collect_decor(shapes, source_part, taken, (cW, cH)):
1694
+ key = (tuple(item['box']), item['geom'], item['css'])
1695
+ if key not in seen_decor:
1696
+ seen_decor.add(key)
1697
+ decor.append(item)
539
1698
  archetypes.append({'name': name, 'bg': None, 'bg_raw': bg_raw, 'slots': slots,
1699
+ 'decor': decor,
540
1700
  'pages': sorted(p['no'] for p in ps), 'rep': rep['no'],
541
1701
  'pic_n': rep['pic_n'],
1702
+ '_source_layouts': sorted({
1703
+ p['layout'] for p in ps if p.get('layout')
1704
+ }),
1705
+ '_source_backgrounds': sorted({
1706
+ p.get('rendered_bg') or p.get('bg_media') or p.get('bg_color')
1707
+ for p in ps
1708
+ if p.get('rendered_bg') or p.get('bg_media') or p.get('bg_color')
1709
+ }),
1710
+ '_text_n': len(rep['texts']),
1711
+ '_last_page_candidate': rep['no'] == last_page_no,
542
1712
  'confidence': 'high' if len(ps) >= 3 else
543
1713
  ('medium' if len(ps) == 2 else 'low')})
544
1714
  return archetypes, pages, leftover
@@ -547,15 +1717,24 @@ def draft_layouts(d, outdir):
547
1717
  # ---------------------------------------------------------------- 联系表
548
1718
  def layout_sheet(outdir, archetypes, path):
549
1719
  """把各 archetype 的代表页光栅出来拼成一张——版式命名得看得见页面。"""
550
- reps = [a['rep'] for a in archetypes]
1720
+ use_layout = all(a.get('rep') is None for a in archetypes)
1721
+ reps = [a.get('rep_layout') if use_layout else a.get('rep') for a in archetypes]
1722
+ reps = [x for x in reps if x is not None]
551
1723
  if not reps:
552
1724
  return None
553
- import subprocess
554
- r = subprocess.run([sys.executable, os.path.join(HERE, 'render_pages.py'), outdir,
555
- '--pages', 'slides', '--only', ','.join(map(str, reps)), '--no-html'],
556
- capture_output=True, text=True)
557
1725
  png_dir = os.path.join(outdir, 'ref', 'rebuild', 'png')
558
- if r.returncode or not os.path.isdir(png_dir):
1726
+ kind = 'layout' if use_layout else 'slide'
1727
+ missing = [no for no in reps
1728
+ if not os.path.exists(os.path.join(png_dir, '%s-%s.png' % (kind, no)))]
1729
+ if missing:
1730
+ import subprocess
1731
+ r = subprocess.run([sys.executable, os.path.join(HERE, 'render_pages.py'), outdir,
1732
+ '--pages', 'layouts' if use_layout else 'slides',
1733
+ '--only', ','.join(map(str, missing)), '--no-html'],
1734
+ capture_output=True, text=True)
1735
+ if r.returncode:
1736
+ return None
1737
+ if not os.path.isdir(png_dir):
559
1738
  return None
560
1739
  try:
561
1740
  from PIL import Image, ImageDraw
@@ -570,26 +1749,31 @@ def layout_sheet(outdir, archetypes, path):
570
1749
  for i, a in enumerate(archetypes):
571
1750
  x = pad + (i % cols) * (cw + pad)
572
1751
  y = pad + (i // cols) * (ch + pad + lab)
573
- f = os.path.join(png_dir, 'slide-%d.png' % a['rep'])
1752
+ no = a.get('rep_layout') if use_layout else a.get('rep')
1753
+ f = os.path.join(png_dir, '%s-%s.png' % (kind, no))
574
1754
  if os.path.exists(f):
575
1755
  im = Image.open(f).convert('RGB')
576
1756
  im.thumbnail((cw, ch))
577
1757
  sheet.paste(im, (x, y))
578
1758
  dr.rectangle([x, y, x + cw, y + ch], outline=(120, 120, 128))
579
- dr.text((x + 2, y + ch + 5), '[%s] slide %d x%d pages bg=%s'
580
- % (a['name'], a['rep'], len(a['pages']), a.get('bg') or '-'),
1759
+ # 标注只写 ASCII——Pillow 默认字体没有 CJK 字形,中文会渲染成方框
1760
+ dr.text((x + 2, y + ch + 5), '[%s] %s bg=%s'
1761
+ % (a['name'],
1762
+ ('layout %s' % a.get('rep_layout')) if use_layout
1763
+ else ('slide %s x%d pages' % (a.get('rep'), len(a['pages']))),
1764
+ a.get('bg') or '-'),
581
1765
  fill=(20, 20, 24))
582
1766
  sheet.save(path, optimize=True)
583
1767
  return path
584
1768
 
585
1769
 
586
- def contact_sheet(outdir, cands, path):
1770
+ def contact_sheet(outdir, cands, path, start_index=1):
587
1771
  try:
588
1772
  from PIL import Image, ImageDraw
589
1773
  except Exception:
590
1774
  return None
591
1775
  cell, pad, cols = 220, 20, 4
592
- items = cands[:12]
1776
+ items = cands # 上限由调用方定,编号与 BRIEF 表格一一对应
593
1777
  if not items:
594
1778
  return None
595
1779
  rows = (len(items) + cols - 1) // cols
@@ -613,19 +1797,548 @@ def contact_sheet(outdir, cands, path):
613
1797
  dr.text((x + 8, y + 8), 'unreadable', fill=(200, 0, 0))
614
1798
  dr.rectangle([x, y, x + cell, y + cell], outline=(120, 120, 128))
615
1799
  dr.text((x + 2, y + cell + 4), '[%d] %s %dx%d used=%d'
616
- % (idx + 1, c['file'], c['probe'].get('w') or 0, c['probe'].get('h') or 0, c['n']),
1800
+ % (c.get('_candidate_index', start_index + idx), c['file'],
1801
+ c['probe'].get('w') or 0,
1802
+ c['probe'].get('h') or 0, c['n']),
617
1803
  fill=(20, 20, 24))
618
1804
  sheet.save(path, optimize=True)
619
1805
  return path
620
1806
 
621
1807
 
1808
+ def contact_sheets(outdir, cands, ldir):
1809
+ paths = []
1810
+ legacy = os.path.join(ldir, 'contact-sheet.png')
1811
+ if os.path.exists(legacy):
1812
+ os.remove(legacy)
1813
+ for start in range(0, len(cands), SHEET_BATCH):
1814
+ batch = cands[start:start + SHEET_BATCH]
1815
+ path = os.path.join(ldir, 'contact-sheet-%d.png' % (start // SHEET_BATCH + 1))
1816
+ if contact_sheet(outdir, batch, path, start + 1):
1817
+ paths.append(path)
1818
+ if paths:
1819
+ shutil.copy2(paths[0], legacy)
1820
+ return paths
1821
+
1822
+
1823
+ def asset_vision_contexts(candidates):
1824
+ """把同一素材的每个归纳页型实例放进对应语境,不只展示最早出现的页面。"""
1825
+ contexts = []
1826
+ for candidate in candidates:
1827
+ placements = candidate.get('placements') or []
1828
+ instance_placements = [row for row in placements if row.get('slide')]
1829
+ if not instance_placements:
1830
+ row = dict(candidate)
1831
+ row['source_placements'] = placements
1832
+ contexts.append(row)
1833
+ continue
1834
+ seen = set()
1835
+ id_counts = Counter()
1836
+ for placement in instance_placements:
1837
+ box = tuple(placement['box'])
1838
+ layout = placement.get('archetype')
1839
+ key = (layout, box) if layout else (placement['slide'], box)
1840
+ if key in seen:
1841
+ continue
1842
+ seen.add(key)
1843
+ row = dict(candidate)
1844
+ base_id = '%s-s%d' % (candidate['id'], placement['slide'])
1845
+ id_counts[base_id] += 1
1846
+ row['id'] = (base_id if id_counts[base_id] == 1
1847
+ else '%s-%d' % (base_id, id_counts[base_id]))
1848
+ row['placements'] = [placement]
1849
+ row['slides'] = [placement['slide']]
1850
+ row['layout'] = layout
1851
+ row['source_placements'] = placements
1852
+ contexts.append(row)
1853
+ return contexts
1854
+
1855
+
1856
+ def _group_input_count(group):
1857
+ # 与 FaaS 一致:每页桶预留一张页面语境图;无实例页的版式候选也占一个图位。
1858
+ page_count = len([page for page in group['pages'] if page > 0]) or 1
1859
+ return len(group['candidates']) + page_count
1860
+
1861
+
1862
+ def build_asset_vision_groups(candidates):
1863
+ """按 FaaS 的 10/5 图数预算,把候选按所在页组合成视觉判断批次。"""
1864
+ buckets = defaultdict(list)
1865
+ for candidate in asset_vision_contexts(candidates):
1866
+ page = next((row['slide'] for row in candidate.get('placements') or []
1867
+ if row.get('slide')), 0)
1868
+ buckets[page].append(candidate)
1869
+
1870
+ groups, queued = [], []
1871
+
1872
+ def flush_small_pages():
1873
+ if not queued:
1874
+ return
1875
+ current, current_pages, inputs = [], [], 0
1876
+ for page, page_candidates in queued:
1877
+ page_inputs = 1 + len(page_candidates)
1878
+ if current and inputs + page_inputs > MULTI_PAGE_IMAGE_BUDGET:
1879
+ groups.append({'pages': current_pages, 'candidates': current})
1880
+ current, current_pages, inputs = [], [], 0
1881
+ current.extend(page_candidates)
1882
+ current_pages.append(page)
1883
+ inputs += page_inputs
1884
+ if current:
1885
+ groups.append({'pages': current_pages, 'candidates': current})
1886
+ del queued[:]
1887
+
1888
+ for page in sorted(buckets):
1889
+ page_candidates = buckets[page]
1890
+ page_inputs = 1 + len(page_candidates)
1891
+ if page_inputs > MULTI_PAGE_IMAGE_BUDGET:
1892
+ flush_small_pages()
1893
+ per_group = SINGLE_PAGE_IMAGE_BUDGET - 1
1894
+ for start in range(0, len(page_candidates), per_group):
1895
+ groups.append({
1896
+ 'pages': [page],
1897
+ 'candidates': page_candidates[start:start + per_group],
1898
+ })
1899
+ continue
1900
+ queued.append((page, page_candidates))
1901
+ flush_small_pages()
1902
+
1903
+ for index, group in enumerate(groups, 1):
1904
+ group['id'] = 'vision-%d' % index
1905
+ group['input_count'] = _group_input_count(group)
1906
+ return groups
1907
+
1908
+
1909
+ def select_asset_vision_groups(groups, slide_count):
1910
+ """受总预算约束选择视觉批次:首页和尾页的所有可容纳分批优先于中间页。"""
1911
+ if not groups:
1912
+ return [], []
1913
+ first_page = 1
1914
+ last_page = slide_count or max(
1915
+ (page for group in groups for page in group['pages'] if page > 0), default=0)
1916
+ selected, selected_ids, inputs = [], set(), 0
1917
+
1918
+ def add(group):
1919
+ nonlocal inputs
1920
+ if (group['id'] in selected_ids or len(selected) >= VISUAL_PACK_CAP
1921
+ or inputs + group['input_count'] > VISUAL_INPUT_CAP):
1922
+ return False
1923
+ selected.append(group)
1924
+ selected_ids.add(group['id'])
1925
+ inputs += group['input_count']
1926
+ return True
1927
+
1928
+ # 首尾页先于中间页保留全部可容纳分批。交错加入避免首页多批先占满总预算,尾页
1929
+ # 连首批都进不去;单页 deck 不重复扫描。
1930
+ priority_batches = [
1931
+ [group for group in groups if page in group['pages']]
1932
+ for page in dict.fromkeys((first_page, last_page))
1933
+ ]
1934
+ for batch_index in range(max(map(len, priority_batches), default=0)):
1935
+ for batches in priority_batches:
1936
+ if batch_index < len(batches):
1937
+ add(batches[batch_index])
1938
+
1939
+ # 首尾的第一个批次已经保证;剩余按页码保留前段内容,优先丢弃尾页之前的后段。
1940
+ remainder = sorted(
1941
+ (group for group in groups if group['id'] not in selected_ids),
1942
+ key=lambda group: (
1943
+ min((page for page in group['pages'] if page > 0), default=999999),
1944
+ group['id'],
1945
+ ),
1946
+ )
1947
+ for group in remainder:
1948
+ add(group)
1949
+
1950
+ selected.sort(key=lambda group: (
1951
+ min((page for page in group['pages'] if page > 0), default=999999), group['id']))
1952
+ omitted = [group for group in groups if group['id'] not in selected_ids]
1953
+ return selected, omitted
1954
+
1955
+
1956
+ def _safe_remove(pattern):
1957
+ for path in glob.glob(pattern):
1958
+ try:
1959
+ os.remove(path)
1960
+ except OSError:
1961
+ pass
1962
+
1963
+
1964
+ def _fit_image(image, width, height):
1965
+ copy = image.copy()
1966
+ copy.thumbnail((width, height))
1967
+ return copy
1968
+
1969
+
1970
+ def _draw_checkerboard(draw, box, size=14):
1971
+ x, y, w, h = box
1972
+ for row in range(0, h, size):
1973
+ for col in range(0, w, size):
1974
+ if (row // size + col // size) % 2 == 0:
1975
+ draw.rectangle([x + col, y + row, x + col + size - 1, y + row + size - 1],
1976
+ fill=(214, 214, 218))
1977
+
1978
+
1979
+ def _candidate_is_visual_risk(candidate):
1980
+ probe = candidate.get('probe') or {}
1981
+ alpha = candidate.get('effective_alpha_mean')
1982
+ if alpha is None:
1983
+ alpha = probe.get('alpha_mean')
1984
+ return ((alpha is not None and alpha < 230)
1985
+ or (probe.get('near_white_ratio') or 0) >= 0.7)
1986
+
1987
+
1988
+ def _paste_candidate_preview(sheet, draw, image, box, dark=False):
1989
+ x, y, w, h = box
1990
+ if dark:
1991
+ draw.rectangle([x, y, x + w, y + h], fill=(54, 54, 58))
1992
+ else:
1993
+ _draw_checkerboard(draw, box)
1994
+ preview = _fit_image(image.convert('RGBA'), w - 8, h - 8)
1995
+ px = x + (w - preview.width) // 2
1996
+ py = y + (h - preview.height) // 2
1997
+ sheet.paste(preview, (px, py), preview)
1998
+
1999
+
2000
+ def _placement_text(candidate):
2001
+ rows = []
2002
+ for placement in candidate.get('placements') or []:
2003
+ box = placement['box']
2004
+ if placement.get('slide'):
2005
+ rows.append('s%d@%d,%d,%d,%d' % (
2006
+ placement['slide'], box[0], box[1], box[2], box[3]))
2007
+ else:
2008
+ rows.append('%s@%d,%d,%d,%d' % (
2009
+ placement.get('layout') or 'layout', box[0], box[1], box[2], box[3]))
2010
+ return ';'.join(rows)
2011
+
2012
+
2013
+ def _save_visual_sheet(sheet, path):
2014
+ if max(sheet.size) > VISUAL_PREVIEW_MAX_EDGE:
2015
+ ratio = VISUAL_PREVIEW_MAX_EDGE / float(max(sheet.size))
2016
+ sheet = sheet.resize((max(1, round(sheet.width * ratio)),
2017
+ max(1, round(sheet.height * ratio))))
2018
+ sheet.save(path, 'JPEG', quality=VISUAL_JPEG_QUALITY, optimize=True, progressive=True)
2019
+
2020
+
2021
+ def render_asset_vision_pages(outdir, pages):
2022
+ """视觉判断必须有页面语境;截图失败时中止草案而非让模型盲判。"""
2023
+ if not pages:
2024
+ return None
2025
+ result = subprocess.run(
2026
+ [sys.executable, os.path.join(HERE, 'render_pages.py'), outdir,
2027
+ '--pages', 'slides', '--only', ','.join(map(str, pages)), '--no-html'],
2028
+ capture_output=True, text=True,
2029
+ )
2030
+ png_dir = os.path.join(outdir, 'ref', 'rebuild', 'png')
2031
+ missing = [
2032
+ page for page in pages
2033
+ if not os.path.isfile(os.path.join(png_dir, 'slide-%d.png' % page))
2034
+ ]
2035
+ if result.returncode or missing:
2036
+ detail = (result.stderr or result.stdout or '').strip().splitlines()
2037
+ raise RuntimeError(
2038
+ '视觉判断所需页面截图生成失败%s%s' % (
2039
+ '(缺第%s页)' % '、'.join(map(str, missing)) if missing else '',
2040
+ ':' + detail[-1] if detail else '',
2041
+ )
2042
+ )
2043
+ return png_dir
2044
+
2045
+
2046
+ class VisionContextError(RuntimeError):
2047
+ pass
2048
+
2049
+
2050
+ def has_pillow():
2051
+ try:
2052
+ from PIL import Image # noqa: F401
2053
+ except Exception:
2054
+ return False
2055
+ return True
2056
+
2057
+
2058
+ def asset_vision_group_sheet(outdir, group, png_dir, path):
2059
+ """把一组整页语境和候选图做成可索引拼版;每张候选保持独立卡片。"""
2060
+ try:
2061
+ from PIL import Image, ImageDraw
2062
+ except Exception:
2063
+ return None
2064
+
2065
+ candidates = group['candidates']
2066
+ page_count = len([page for page in group['pages'] if page > 0])
2067
+ page_w, page_h = 440, 248
2068
+ cell, pad, label_h = 220, 16, 42
2069
+ asset_cols = 3
2070
+ asset_rows = max(1, (len(candidates) + asset_cols - 1) // asset_cols)
2071
+ page_rows = max(1, (page_count + 1) // 2) if page_count else 0
2072
+ page_cols = min(2, page_count) if page_count else 0
2073
+ width = max(2 * (page_w + pad) + pad if page_cols else 0,
2074
+ asset_cols * (cell + pad) + pad)
2075
+ header_h = 28
2076
+ page_area_h = (page_rows * (page_h + label_h + pad) + pad) if page_rows else 0
2077
+ asset_top = header_h + page_area_h
2078
+ height = asset_top + asset_rows * (cell + label_h + pad) + pad
2079
+ sheet = Image.new('RGB', (width, height), (245, 245, 247))
2080
+ draw = ImageDraw.Draw(sheet)
2081
+ draw.text((pad, 7), '%s inputs=%d pages=%s' % (
2082
+ group['id'], group['input_count'],
2083
+ ','.join(map(str, group['pages'])) or 'layout'), fill=(20, 20, 24))
2084
+
2085
+ for index, page in enumerate([page for page in group['pages'] if page > 0]):
2086
+ x = pad + (index % 2) * (page_w + pad)
2087
+ y = header_h + (index // 2) * (page_h + label_h + pad)
2088
+ source = (os.path.join(png_dir, 'slide-%d.png' % page)
2089
+ if png_dir else None)
2090
+ if source and os.path.exists(source):
2091
+ try:
2092
+ image = Image.open(source).convert('RGB')
2093
+ image = _fit_image(image, page_w, page_h)
2094
+ sheet.paste(image, (x + (page_w - image.width) // 2,
2095
+ y + (page_h - image.height) // 2))
2096
+ except Exception as exc:
2097
+ raise VisionContextError('视觉判断所需页面截图不可读取:第%d页' % page) from exc
2098
+ else:
2099
+ raise VisionContextError('视觉判断所需页面截图缺失:第%d页' % page)
2100
+ draw.rectangle([x, y, x + page_w, y + page_h], outline=(120, 120, 128))
2101
+ draw.text((x + 2, y + page_h + 5), '[page %d] context for candidates below' % page,
2102
+ fill=(20, 20, 24))
2103
+
2104
+ for index, candidate in enumerate(candidates):
2105
+ x = pad + (index % asset_cols) * (cell + pad)
2106
+ y = asset_top + (index // asset_cols) * (cell + label_h + pad)
2107
+ image_path = os.path.join(outdir, candidate['out'])
2108
+ try:
2109
+ image = Image.open(image_path)
2110
+ if _candidate_is_visual_risk(candidate):
2111
+ half = (cell - 3) // 2
2112
+ _paste_candidate_preview(sheet, draw, image, (x, y, half, cell))
2113
+ _paste_candidate_preview(sheet, draw, image, (x + half + 3, y, cell - half - 3, cell),
2114
+ dark=True)
2115
+ else:
2116
+ _paste_candidate_preview(sheet, draw, image, (x, y, cell, cell))
2117
+ except Exception:
2118
+ draw.text((x + 8, y + 8), 'unreadable', fill=(200, 0, 0))
2119
+ draw.rectangle([x, y, x + cell, y + cell], outline=(120, 120, 128))
2120
+ probe = candidate.get('probe') or {}
2121
+ alpha = candidate.get('effective_alpha_mean')
2122
+ if alpha is None:
2123
+ alpha = probe.get('alpha_mean')
2124
+ risk = (' a=%s w=%s' % (
2125
+ '?' if alpha is None else round(alpha),
2126
+ '?' if probe.get('near_white_ratio') is None
2127
+ else round(probe['near_white_ratio'] * 100),
2128
+ )) if _candidate_is_visual_risk(candidate) else ''
2129
+ draw.text((x + 2, y + cell + 3), '[%s] %s %dx%d%s' % (
2130
+ candidate['id'], candidate['file'], probe.get('w') or 0, probe.get('h') or 0, risk),
2131
+ fill=(20, 20, 24))
2132
+ first = (candidate.get('placements') or [{}])[0]
2133
+ total_placements = len(candidate.get('source_placements') or
2134
+ candidate.get('placements') or [])
2135
+ if first.get('slide'):
2136
+ box = first['box']
2137
+ draw.text((x + 2, y + cell + 18), 's%d @%d,%d %dx%d seen=%d' % (
2138
+ first['slide'], box[0], box[1], box[2], box[3],
2139
+ total_placements), fill=(20, 20, 24))
2140
+ else:
2141
+ draw.text((x + 2, y + cell + 18), 'layout x%d' % len(candidate.get('placements') or []),
2142
+ fill=(20, 20, 24))
2143
+ _save_visual_sheet(sheet, path)
2144
+ return path
2145
+
2146
+
2147
+ def emit_asset_vision_groups(outdir, candidates, slide_count, ldir):
2148
+ """生成受预算约束的拼版和结构化索引,返回已选/未选组。"""
2149
+ groups = build_asset_vision_groups(candidates)
2150
+ selected, omitted = select_asset_vision_groups(groups, slide_count)
2151
+ _safe_remove(os.path.join(ldir, 'vision-group-*.jpg'))
2152
+ _safe_remove(os.path.join(ldir, 'contact-sheet-*.png'))
2153
+ _safe_remove(os.path.join(ldir, 'contact-sheet.png'))
2154
+ _safe_remove(os.path.join(ldir, 'asset-context-sheet-*.png'))
2155
+
2156
+ paths = []
2157
+ if not has_pillow():
2158
+ omitted = groups
2159
+ selected = []
2160
+ else:
2161
+ pages = sorted({page for group in selected for page in group['pages'] if page > 0})
2162
+ png_dir = render_asset_vision_pages(outdir, pages)
2163
+ try:
2164
+ for index, group in enumerate(selected, 1):
2165
+ path = os.path.join(ldir, 'vision-group-%d.jpg' % index)
2166
+ if asset_vision_group_sheet(outdir, group, png_dir, path):
2167
+ paths.append(path)
2168
+ group['sheet'] = os.path.basename(path)
2169
+ if selected and len(paths) != len(selected):
2170
+ raise RuntimeError('视觉判断拼版生成失败')
2171
+ except VisionContextError:
2172
+ raise
2173
+ except Exception:
2174
+ _safe_remove(os.path.join(ldir, 'vision-group-*.jpg'))
2175
+ selected, omitted, paths = [], groups, []
2176
+ if paths:
2177
+ # 旧流程只认 contact-sheet.png;保留首个视觉组的 PNG 别名,新的 BRIEF 不再要求读它。
2178
+ try:
2179
+ from PIL import Image
2180
+ legacy = os.path.join(ldir, 'contact-sheet-1.png')
2181
+ Image.open(paths[0]).convert('RGB').save(legacy, 'PNG', optimize=True)
2182
+ shutil.copy2(legacy, os.path.join(ldir, 'contact-sheet.png'))
2183
+ except Exception:
2184
+ pass
2185
+
2186
+ def serialize(group):
2187
+ return {
2188
+ 'id': group['id'],
2189
+ 'sheet': group.get('sheet'),
2190
+ 'pages': group['pages'],
2191
+ 'input_count': group['input_count'],
2192
+ 'candidates': [{
2193
+ 'id': candidate['id'],
2194
+ 'source_media': candidate['file'],
2195
+ 'source_px': [candidate['probe'].get('w'), candidate['probe'].get('h')],
2196
+ 'bytes': candidate.get('bytes'),
2197
+ 'repeat_count': candidate.get('n'),
2198
+ 'fullscreen': candidate.get('fullscreen'),
2199
+ 'effective_alpha_mean': candidate.get('effective_alpha_mean'),
2200
+ 'near_white_ratio': candidate['probe'].get('near_white_ratio'),
2201
+ 'placements': candidate.get('placements') or [],
2202
+ 'source_placements': candidate.get('source_placements') or
2203
+ candidate.get('placements') or [],
2204
+ } for candidate in group['candidates']],
2205
+ }
2206
+
2207
+ index = {
2208
+ 'version': 2,
2209
+ 'limits': {
2210
+ 'single_page_image_budget': SINGLE_PAGE_IMAGE_BUDGET,
2211
+ 'multi_page_image_budget': MULTI_PAGE_IMAGE_BUDGET,
2212
+ 'pack_cap': VISUAL_PACK_CAP,
2213
+ 'input_cap': VISUAL_INPUT_CAP,
2214
+ },
2215
+ 'selected': [serialize(group) for group in selected],
2216
+ 'omitted': [serialize(group) for group in omitted],
2217
+ }
2218
+ with open(os.path.join(ldir, 'asset-vision-groups.json'), 'w', encoding='utf-8') as stream:
2219
+ json.dump(index, stream, ensure_ascii=False, indent=2)
2220
+ stream.write('\n')
2221
+ return selected, omitted, paths
2222
+
2223
+
2224
+ def asset_context_sheets(outdir, cands, ldir):
2225
+ """按候选主所在页去重拼整页语境,供模型识别 logo 墙和装饰用途。"""
2226
+ reviewed = [c for c in cands if needs_asset_judgment(c)]
2227
+ pages = []
2228
+ seen = set()
2229
+ for c in reviewed:
2230
+ page = next((no for no in c.get('slides') or [] if no and no != 9999), None)
2231
+ if page is not None and page not in seen:
2232
+ seen.add(page)
2233
+ pages.append(page)
2234
+ if not pages:
2235
+ return []
2236
+ import subprocess
2237
+ result = subprocess.run(
2238
+ [sys.executable, os.path.join(HERE, 'render_pages.py'), outdir,
2239
+ '--pages', 'slides', '--only', ','.join(map(str, pages)), '--no-html'],
2240
+ capture_output=True, text=True,
2241
+ )
2242
+ png_dir = os.path.join(outdir, 'ref', 'rebuild', 'png')
2243
+ if result.returncode or not os.path.isdir(png_dir):
2244
+ return []
2245
+ try:
2246
+ from PIL import Image, ImageDraw
2247
+ except Exception:
2248
+ return []
2249
+ paths = []
2250
+ candidate_ids = defaultdict(list)
2251
+ for index, c in enumerate(cands, 1):
2252
+ if not needs_asset_judgment(c):
2253
+ continue
2254
+ for page in c.get('slides') or []:
2255
+ if page in seen:
2256
+ candidate_ids[page].append(index)
2257
+ for start in range(0, len(pages), CONTEXT_BATCH):
2258
+ batch = pages[start:start + CONTEXT_BATCH]
2259
+ cols, cw, ch, pad, lab = 2, 480, 270, 16, 22
2260
+ rows = (len(batch) + cols - 1) // cols
2261
+ sheet = Image.new('RGB', (cols * (cw + pad) + pad,
2262
+ rows * (ch + pad + lab) + pad), (245, 245, 247))
2263
+ draw = ImageDraw.Draw(sheet)
2264
+ for offset, page in enumerate(batch):
2265
+ x = pad + (offset % cols) * (cw + pad)
2266
+ y = pad + (offset // cols) * (ch + pad + lab)
2267
+ source = os.path.join(png_dir, 'slide-%d.png' % page)
2268
+ if os.path.exists(source):
2269
+ image = Image.open(source).convert('RGB')
2270
+ image.thumbnail((cw, ch))
2271
+ sheet.paste(image, (x, y))
2272
+ draw.rectangle([x, y, x + cw, y + ch], outline=(120, 120, 128))
2273
+ draw.text((x + 2, y + ch + 5), 'slide %d candidates=%s'
2274
+ % (page, ','.join(map(str, candidate_ids[page]))),
2275
+ fill=(20, 20, 24))
2276
+ path = os.path.join(ldir, 'asset-context-sheet-%d.png'
2277
+ % (start // CONTEXT_BATCH + 1))
2278
+ sheet.save(path, optimize=True)
2279
+ paths.append(path)
2280
+ return paths
2281
+
2282
+
622
2283
  # ---------------------------------------------------------------- 落盘
623
2284
  def write(p, s):
624
2285
  with open(p, 'w', encoding='utf-8') as f:
625
2286
  f.write(s)
626
2287
 
627
2288
 
628
- def emit_manifest(d, assets, ldir):
2289
+ def bound_visual_candidates(candidates, archetypes):
2290
+ """只把最终有图片槽的候选交给判断单;其余仍留在联系表供视觉核对。"""
2291
+ bound_files = {
2292
+ s.get('source_media')
2293
+ for a in archetypes
2294
+ for s in a.get('slots') or []
2295
+ if s.get('source_media')
2296
+ }
2297
+ return [c for c in candidates if c.get('file') in bound_files]
2298
+
2299
+
2300
+ def visual_slot_candidates(candidates, archetypes):
2301
+ """把候选绑定到最终槽位;页面截图只作该槽位的视觉语境。"""
2302
+ source_candidates = {
2303
+ candidate.get('file'): candidate
2304
+ for candidate in bound_visual_candidates(candidates, archetypes)
2305
+ }
2306
+ rows, seen = [], set()
2307
+ for archetype in archetypes:
2308
+ pages = set(archetype.get('pages') or archetype.get('_sample_pages') or [])
2309
+ for slot in archetype.get('slots') or []:
2310
+ source = slot.get('source_media')
2311
+ raw_box = slot.get('box')
2312
+ candidate = source_candidates.get(source)
2313
+ if not pages or not candidate or not raw_box or not needs_asset_judgment(candidate):
2314
+ continue
2315
+ box = [round(value) for value in raw_box]
2316
+ key = (source, archetype['name'], tuple(box))
2317
+ if key in seen:
2318
+ continue
2319
+ seen.add(key)
2320
+ source_placements = candidate.get('placements') or []
2321
+ matching = [
2322
+ placement for placement in source_placements
2323
+ if tuple(placement.get('box') or ()) == tuple(box)
2324
+ and placement.get('slide') in pages
2325
+ ]
2326
+ if not matching:
2327
+ continue
2328
+ slide = matching[0]['slide']
2329
+ row = dict(candidate)
2330
+ row['placements'] = [{
2331
+ 'slide': slide,
2332
+ 'box': box,
2333
+ 'archetype': archetype['name'],
2334
+ }]
2335
+ row['slides'] = [slide] if slide else []
2336
+ row['source_placements'] = source_placements
2337
+ rows.append(row)
2338
+ return rows
2339
+
2340
+
2341
+ def emit_manifest(d, assets, vision_groups, ldir):
629
2342
  L = ['version: alpha',
630
2343
  'name: TODO-style-name # 英文 kebab,体现气质,不要用文件名',
631
2344
  'name_zh: TODO中文名',
@@ -646,6 +2359,28 @@ def emit_manifest(d, assets, ldir):
646
2359
  L.append(' on-bg: %s' % (a.get('on_bg') or 'light'))
647
2360
  if a['use_full']:
648
2361
  L.append(' use_full: true')
2362
+ if vision_groups:
2363
+ L += [
2364
+ 'asset_vision_groups:',
2365
+ ' # 每项对应拼版中的一个候选实例;同源图在不同页型/位置可分别定性。',
2366
+ ' # 取值与 FaaS 对齐:logo|slogan|background|texture|icon|decorative|illustration|photo|chart|screenshot|footer-copyright|page-number|watermark|content-image|unknown。',
2367
+ ]
2368
+ for group in vision_groups:
2369
+ for candidate in group['candidates']:
2370
+ placement = (candidate.get('placements') or [{}])[0]
2371
+ L.append(' - id: %s' % candidate['id'])
2372
+ L.append(' source_media: %s' % q(candidate['file']))
2373
+ if placement.get('box'):
2374
+ L.append(' box: %s' % placement['box'])
2375
+ L.append(' visual_kind: TODO-visual-kind-%s # %s;视觉组 %s'
2376
+ % (candidate['id'], candidate['id'], group['id']))
2377
+ L += [
2378
+ 'asset_decisions:',
2379
+ ' # 仅在不在视觉预算内的图片、或需要覆盖已有判断时追加。',
2380
+ ' # 位置例外写 box;同图同坐标跨页型不同,再补 layout。',
2381
+ ' # - {source_media: example.png, visual_kind: chart}',
2382
+ ' # - {source_media: example.png, layout: layout-2, box: [0, 0, 100, 100], visual_kind: decorative}',
2383
+ ]
649
2384
  write(os.path.join(ldir, 'manifest.yaml'), '\n'.join(L) + '\n')
650
2385
 
651
2386
 
@@ -669,20 +2404,32 @@ def emit_frontmatter(d, tokens, fonts, roles, anchors, gaps, ldir):
669
2404
  edge = {}
670
2405
  for p in pads:
671
2406
  edge.setdefault(p['edge'], p['px'])
672
- if edge:
2407
+ # 四边都测出来才写 spacing / safe-area。缺一边就整段不写,并在 gaps 说明——
2408
+ # 拿另一套模板的边距当默认值,会让消费端按一个从没在本模板出现过的网格排版。
2409
+ edges_full = all(edge.get(k) is not None for k in ('top', 'right', 'bottom', 'left'))
2410
+ if edges_full:
673
2411
  L.append('spacing:')
674
2412
  L.append(' page-padding: {top: %s, right: %s, bottom: %s, left: %s}'
675
- % (edge.get('top', 73), edge.get('right', 90),
676
- edge.get('bottom', 95), edge.get('left', 90)))
677
- radii = [r for r in (d.get('radii_census') or []) if r['px'] >= 2 and r['n'] >= 6]
678
- if radii:
679
- top = max(radii, key=lambda r: r['n'])
2413
+ % (edge['top'], edge['right'], edge['bottom'], edge['left']))
2414
+ # rounded.card 是全局 token,只能表达全档共同的一档圆角。多个非零档位或零/非零
2415
+ # 混用时,圆角属于 layouts.md 里的局部形状事实,压成一个值会把直角容器也圆角化。
2416
+ radii = d.get('radii_census') or []
2417
+ if len(radii) == 1 and radii[0]['px'] >= 1:
2418
+ top = radii[0]
680
2419
  L.append('rounded:')
681
2420
  L.append(' card: %dpx' % round(top['px']))
682
- L.append('safe-area:')
683
- L.append(' content: {top: %s, right: %s, bottom: %s, left: %s, applies-to: [content]}'
684
- % (edge.get('top', 73), edge.get('right', 90), edge.get('bottom', 95), edge.get('left', 90)))
685
- L.append(' confidence: medium')
2421
+ if edges_full:
2422
+ L.append('safe-area:')
2423
+ L.append(' content: {top: %s, right: %s, bottom: %s, left: %s, applies-to: [content]}'
2424
+ % (edge['top'], edge['right'], edge['bottom'], edge['left']))
2425
+ L.append(' confidence: medium')
2426
+ else:
2427
+ gaps = list(gaps) + ['本模板没测出四边都稳定的页边距(普查到 %s),'
2428
+ '因此不给 spacing / safe-area:按各页型 slot 的实际坐标排版,'
2429
+ '不要自造统一边距。'
2430
+ % ('、'.join('%s=%s' % (k, edge[k]) for k in
2431
+ ('top', 'right', 'bottom', 'left') if edge.get(k) is not None)
2432
+ or '一边都没有')]
686
2433
  L.append('anchors:')
687
2434
  for aid, typ, desc in anchors:
688
2435
  L.append(' - {id: %s, type: %s, desc: "%s"}' % (aid, typ, desc))
@@ -692,131 +2439,638 @@ def emit_frontmatter(d, tokens, fonts, roles, anchors, gaps, ldir):
692
2439
  write(os.path.join(ldir, 'frontmatter.yaml'), '\n'.join(L) + '\n')
693
2440
 
694
2441
 
695
- def emit_layouts(archetypes, ldir):
696
- L = ['# 只改 names 这一段:给每个页型起表意的中文名(看 layout-sheet.png)。下面 layouts 段不要动。',
697
- 'names:']
2442
+ def draft_flow(a, facts, canvas):
2443
+ """从结构事实推出「区带」草案:一页 = 若干竖直区带,高度由内容决定。
2444
+
2445
+ 绝对坐标只能表达「模板样张那份内容摆在哪」。真实内容长度不同,上面的区带一变高,
2446
+ 下面的就该整体下移——这件事在一张坐标表里表达不出来,只能靠消费端自己算,而它
2447
+ 算错的方向有两个:估小了压穿下一块,估大了留一片空。
2448
+
2449
+ 这里只出草案,最终用绝对还是流式由看得到重建图的人定。
2450
+ """
2451
+ cW, cH = canvas
2452
+ # 装饰件也算进来:很多模板的版式层只有几个占位符,真正撑起版面的是卡片容器
2453
+ # (在 decor 里)。只看 slots 会把一页的主体结构整个漏掉。
2454
+ slots = [s for s in a['slots'] if s.get('box')]
2455
+ fixed_roles = {'logo', 'slide-number', 'page-number', 'header', 'footer'}
2456
+ fixed = [s for s in slots if s.get('role') in fixed_roles]
2457
+ content_slots = [s for s in slots if s.get('role') not in fixed_roles]
2458
+ containers = [{'role': 'container', 'type': 'decor', 'box': dcr['box'],
2459
+ 'css': dcr.get('css')} for dcr in (a.get('decor') or [])]
2460
+ items = group_flow_cards(content_slots, containers)
2461
+ if len(items) < 2:
2462
+ return None
2463
+ items.sort(key=lambda s: (s['box'][1], s['box'][0]))
2464
+ gaps = [items[i + 1]['box'][1] - (items[i]['box'][1] + items[i]['box'][3])
2465
+ for i in range(len(items) - 1)]
2466
+ pos = [g for g in gaps if g > 0]
2467
+ if not pos:
2468
+ return None
2469
+ # 区带边界 = 间距分布里的最大空档。同一区带内部的间距(网格行距之类)总是明显
2470
+ # 小于区带之间的间距,用本页自己的分布切,不设固定阈值。
2471
+ cut = _gap_cut(pos, min(pos), max(pos)) if len(pos) > 1 else pos[0]
2472
+ regions, cur = [], [items[0]]
2473
+ for i, g in enumerate(gaps):
2474
+ if g >= cut:
2475
+ regions.append(cur)
2476
+ cur = []
2477
+ cur.append(items[i + 1])
2478
+ regions.append(cur)
2479
+
2480
+ # 整页左右边距 = 所有内容的横向外包络,作为各区带的缺省。
2481
+ lefts = [s['box'][0] for s in items]
2482
+ rights = [s['box'][0] + s['box'][2] for s in items]
2483
+ page_margin = [min(lefts), cW - max(rights)]
2484
+
2485
+ out = []
2486
+ for reg in regions:
2487
+ if not reg:
2488
+ continue
2489
+ # 同一区带里 y 接近的算一行;每行元素数一致且 >1 就是网格
2490
+ rows, cr = [], [reg[0]]
2491
+ for s in reg[1:]:
2492
+ if abs(s['box'][1] - cr[-1]['box'][1]) <= max(s['box'][3], 1) * 0.5:
2493
+ cr.append(s)
2494
+ else:
2495
+ rows.append(cr)
2496
+ cr = [s]
2497
+ rows.append(cr)
2498
+ widths = {len(r) for r in rows}
2499
+ if len(rows) >= 1 and widths == {len(rows[0])} and len(rows[0]) > 1:
2500
+ cols = len(rows[0])
2501
+ xs = sorted(s['box'][0] for s in rows[0])
2502
+ col_gap = round((xs[1] - xs[0]) - rows[0][0]['box'][2]) if cols > 1 else 0
2503
+ row_gap = 0
2504
+ if len(rows) > 1:
2505
+ row_gap = round(rows[1][0]['box'][1]
2506
+ - (rows[0][0]['box'][1] + rows[0][0]['box'][3]))
2507
+ region = {'kind': 'grid', 'cols': cols, 'gap': [max(col_gap, 0), max(row_gap, 0)],
2508
+ 'items': rows[0]}
2509
+ # 卡片组的横向范围常和整页不同(标题贴左、卡片居中)。整页边距是所有元素的
2510
+ # 外包络,直接套给居中卡片组会把它拉偏成左对齐。区带范围和整页明显不一致时,
2511
+ # 落这个区带自己的左右边距,消费端把网格放进它再填 1fr。按落盘的整数比较,
2512
+ # 亚像素噪声不触发多余的区带边距。
2513
+ reg_margin = [min(s['box'][0] for s in rows[0]),
2514
+ cW - max(s['box'][0] + s['box'][2] for s in rows[0])]
2515
+ if [int(reg_margin[0]), int(reg_margin[1])] != [int(page_margin[0]), int(page_margin[1])]:
2516
+ region['margin'] = reg_margin
2517
+ out.append(region)
2518
+ elif len(rows) == len(reg):
2519
+ # 每行一个元素 = 真的竖着排
2520
+ inner = 0
2521
+ if len(reg) > 1:
2522
+ inner = round(reg[1]['box'][1] - (reg[0]['box'][1] + reg[0]['box'][3]))
2523
+ out.append({'kind': 'stack', 'gap': max(inner, 0), 'items': reg})
2524
+ else:
2525
+ # 每行元素数不一致(比如左列两张、右列一张跨两行)。硬说成 stack 会让消费端
2526
+ # 以为它们是竖排的,比不给还糟。如实说这块推不出规整结构,按坐标摆。
2527
+ out.append({'kind': 'free', 'items': reg})
2528
+ if fixed:
2529
+ out.append({'kind': 'free', 'items': fixed})
2530
+ if len(out) < 2:
2531
+ return None
2532
+ return {'top': items[0]['box'][1], 'margin': page_margin,
2533
+ 'gap': round(cut), 'regions': out}
2534
+
2535
+
2536
+ def box_contains(outer, inner):
2537
+ return (outer[0] <= inner[0] and outer[1] <= inner[1]
2538
+ and outer[0] + outer[2] >= inner[0] + inner[2]
2539
+ and outer[1] + outer[3] >= inner[1] + inner[3])
2540
+
2541
+
2542
+ def boxes_overlap(a, b):
2543
+ return (min(a[0] + a[2], b[0] + b[2]) > max(a[0], b[0])
2544
+ and min(a[1] + a[3], b[1] + b[3]) > max(a[1], b[1]))
2545
+
2546
+
2547
+ def overlap_ratio(outer, inner):
2548
+ width = min(outer[0] + outer[2], inner[0] + inner[2]) - max(outer[0], inner[0])
2549
+ height = min(outer[1] + outer[3], inner[1] + inner[3]) - max(outer[1], inner[1])
2550
+ if width <= 0 or height <= 0 or inner[2] <= 0 or inner[3] <= 0:
2551
+ return 0
2552
+ return width * height / (inner[2] * inner[3])
2553
+
2554
+
2555
+ def group_flow_cards(slots, containers):
2556
+ """把并列卡片容器及其文字组成一层 group,避免拍平成多列元素。"""
2557
+ candidates = []
2558
+ for container in containers:
2559
+ children = [slot for slot in slots if box_contains(container['box'], slot['box'])]
2560
+ if len(children) >= 2:
2561
+ candidates.append((container, children))
2562
+ selected = []
2563
+ for container, children in sorted(
2564
+ candidates, key=lambda pair: pair[0]['box'][2] * pair[0]['box'][3]):
2565
+ if not any(boxes_overlap(container['box'], other['box']) for other, _ in selected):
2566
+ selected.append((container, children))
2567
+ if len(selected) < 2:
2568
+ return slots + containers
2569
+
2570
+ grouped_slots = {id(slot) for _, children in selected for slot in children}
2571
+ nested_by_container = {}
2572
+ for container, _ in selected:
2573
+ nested_by_container[id(container)] = [
2574
+ other for other in containers
2575
+ if other is not container and overlap_ratio(container['box'], other['box']) >= 0.9
2576
+ ]
2577
+ grouped_containers = {
2578
+ id(container)
2579
+ for container, _ in selected
2580
+ for container in [container] + nested_by_container[id(container)]
2581
+ }
2582
+ out = [slot for slot in slots if id(slot) not in grouped_slots]
2583
+ out += [container for container in containers if id(container) not in grouped_containers]
2584
+ for container, children in selected:
2585
+ children = children + nested_by_container[id(container)]
2586
+ children = sorted(children, key=lambda slot: (slot['box'][1], slot['box'][0]))
2587
+ gaps = [children[i + 1]['box'][1]
2588
+ - (children[i]['box'][1] + children[i]['box'][3])
2589
+ for i in range(len(children) - 1)]
2590
+ outer = container['box']
2591
+ insets = [
2592
+ min(child['box'][1] - outer[1] for child in children),
2593
+ min(outer[0] + outer[2] - child['box'][0] - child['box'][2] for child in children),
2594
+ min(outer[1] + outer[3] - child['box'][1] - child['box'][3] for child in children),
2595
+ min(child['box'][0] - outer[0] for child in children),
2596
+ ]
2597
+ padding = max(0, round(min(insets)))
2598
+ css = container.get('css') or ''
2599
+ if padding:
2600
+ css = '; '.join(part for part in (
2601
+ css.rstrip('; '), 'box-sizing: border-box', 'padding: %dpx' % padding) if part)
2602
+ out.append({
2603
+ 'role': 'group',
2604
+ 'type': 'group',
2605
+ 'box': outer,
2606
+ 'css': css,
2607
+ 'gap': max(0, round(min(gaps))) if gaps else 0,
2608
+ 'items': children,
2609
+ })
2610
+ return out
2611
+
2612
+
2613
+ def structure_facts(archetypes, d, shapes):
2614
+ """每个页型的**结构事实**:栅格、垂直间距序列、容器样式配方、样张里的实际字数。
2615
+
2616
+ 这些是判「该用绝对坐标还是流式」的依据,脚本只测不判:
2617
+ - 栅格拟合好不好,决定这页是不是一个规整的多列区带
2618
+ - 垂直间距序列里的突变点,就是区带的边界(网格内部 24、区带之间 110)
2619
+ - 样张字数说明这个框是按几行内容设计的——框高本身看不出这件事
2620
+ """
2621
+ q = _load_query()
2622
+ by_part = defaultdict(list)
2623
+ for s in shapes:
2624
+ by_part[s.get('part')].append(s)
2625
+
2626
+ # 容器样式配方:跨全档聚类一次,记出现次数与跨页数,供判断「哪些是共性风格」
2627
+ groups = {}
2628
+ for s in shapes:
2629
+ fill, line, fx = s.get('fill'), s.get('line'), s.get('effects')
2630
+ if not fill and not line and not fx:
2631
+ continue
2632
+ if isinstance(fill, dict) and fill.get('type') == 'image':
2633
+ continue
2634
+ k = q._sig(fill, line, fx)
2635
+ if k[0] == 'none' and k[1] == 'none' and not k[2]:
2636
+ continue
2637
+ g = groups.setdefault(k, {'n': 0, 'parts': set(), 'radii': [],
2638
+ 'fill': fill, 'line': line, 'fx': fx, 'shapes': set()})
2639
+ g['n'] += 1
2640
+ g['parts'].add(s.get('part'))
2641
+ g['radii'].append(s.get('radius_px') or 0)
2642
+ g['shapes'].add(id(s))
2643
+ ranked = sorted(groups.values(), key=lambda g: -g['n'])
2644
+ recipe_id = {}
2645
+ recipes = []
2646
+ for i, g in enumerate(ranked, 1):
2647
+ rid = 'r%d' % i
2648
+ css = [re.sub(r'\s*\n\s*', ' ', c.split('\x00')[0]).strip()
2649
+ for c in q._recipe_css(g['fill'], g['line'], g['radii'], g['fx']) if c]
2650
+ recipes.append({'id': rid, 'n': g['n'], 'pages': len(g['parts']),
2651
+ 'css': '; '.join(css)})
2652
+ for sid in g['shapes']:
2653
+ recipe_id[sid] = rid
2654
+
2655
+ grids = (d.get('spacing_candidates') or {}).get('grids') or []
2656
+ grid_by_part = defaultdict(list)
2657
+ for gd in grids:
2658
+ grid_by_part[gd.get('part')].append(gd)
2659
+
2660
+ out = {}
2661
+ for a in archetypes:
2662
+ part = None
2663
+ if a.get('source', '').startswith('layout:'):
2664
+ part = 'ppt/slideLayouts/' + a['source'].split(':', 1)[1]
2665
+ elif a.get('rep'):
2666
+ part = 'ppt/slides/slide%d.xml' % a['rep']
2667
+ boxes = [s['box'] for s in a['slots']] + [x['box'] for x in (a.get('decor') or [])]
2668
+ boxes.sort(key=lambda b: b[1])
2669
+ gaps = [boxes[i + 1][1] - (boxes[i][1] + boxes[i][3]) for i in range(len(boxes) - 1)]
2670
+ chars = [(s['box'], len(s.get('txt') or '')) for s in a['slots'] if s.get('txt')]
2671
+ used = []
2672
+ for s in by_part.get(part, []):
2673
+ rid = recipe_id.get(id(s))
2674
+ if rid and rid not in used:
2675
+ used.append(rid)
2676
+ out[a['name']] = {'grids': grid_by_part.get(part) or [], 'gaps': gaps,
2677
+ 'chars': chars, 'recipes': used}
2678
+ return out, recipes
2679
+
2680
+
2681
+ LAYOUT_CONTROL_KEYS = {
2682
+ 'names', 'roles', 'text_roles', 'layout_modes', 'bg_rules',
2683
+ }
2684
+
2685
+
2686
+ def emit_layout_controls(layout_lines, ldir, text_role_candidates, flow_archetypes):
2687
+ """从兼容用的 layouts.yaml 分出模型只需编辑的判断区。
2688
+
2689
+ 旧判断单把控制项和每个 slot 的坐标正文混在一起。模型为补一个角色读取整份文件,
2690
+ 在版式很多的模板上会把时间耗在无须判断的数值上。仍保留旧文件给既有调用方;
2691
+ 新文件只承载最终可覆盖它的五个顶层判断区。
2692
+ """
2693
+ blocks, current = {}, None
2694
+ for line in layout_lines:
2695
+ match = re.match(r'^([A-Za-z_][\w-]*):', line)
2696
+ if match:
2697
+ current = match.group(1)
2698
+ if current in LAYOUT_CONTROL_KEYS:
2699
+ blocks[current] = [line]
2700
+ continue
2701
+ if current in blocks:
2702
+ blocks[current].append(line)
2703
+
2704
+ controls = [
2705
+ '# 版式判断控制区 —— 只读并编辑本文件;不要打开或修改 layouts.yaml。',
2706
+ '# package.py 会用本文件覆盖 layouts.yaml 的同名判断区,后者仅保留坐标事实与兼容输入。',
2707
+ '# 可编辑顶层键仅为 names / roles / text_roles / layout_modes / bg_rules。',
2708
+ ]
2709
+ for key in ('names', 'roles'):
2710
+ if key in blocks:
2711
+ controls.extend([''] + blocks[key])
2712
+ if text_role_candidates:
2713
+ controls += [
2714
+ '',
2715
+ 'text_roles:',
2716
+ '# 默认文字槽都是 body;仅把确认属于 title|subtitle|header|footer 的例外填为',
2717
+ '# <id>: title(不要给普通正文补 body)。候选对应的原始槽位在下列注释中。',
2718
+ ]
2719
+ for role_id, slot in text_role_candidates:
2720
+ controls.append('# %s:%s' % (
2721
+ role_id, (slot.get('txt') or '(无样本文字)')[:60]))
2722
+ if flow_archetypes:
2723
+ controls += [
2724
+ '',
2725
+ 'layout_modes:',
2726
+ '# 默认 slots。只有样张明确需要内容随高度重排时,取消注释并填 `<页型>: flow`。',
2727
+ ]
2728
+ controls.extend('# %s: flow' % archetype['name'] for archetype in flow_archetypes)
2729
+ if 'bg_rules' in blocks:
2730
+ controls.extend([''] + blocks['bg_rules'])
2731
+ write(os.path.join(ldir, 'layout-controls.yaml'), '\n'.join(controls) + '\n')
2732
+
2733
+
2734
+ def emit_layouts(archetypes, ldir, busy_hints=None, facts=None, recipes=None):
2735
+ sampled_archetypes = {
2736
+ id(archetype) for archetype in archetypes
2737
+ if (archetype.get('rep') is not None
2738
+ or archetype.get('pages')
2739
+ or archetype.get('_sample_pages'))
2740
+ }
2741
+ prefilled = sum(1 for a in archetypes if a.get('zh'))
2742
+ L = ['# 判断单草案 —— package.py 读它产出 layouts.md,deck 的版式坐标从 layouts.md 读。',
2743
+ '# 只改 names / roles / text_roles / layout_modes / bg_rules 五段(都是扁平键值,'
2744
+ '改完 package.py 自动并回各页型)。',
2745
+ '# 下面 layouts 段是普查数值,一个字都不要动——改它容易连带删掉 slots/confidence。']
2746
+ if prefilled:
2747
+ L.append('# names 已按模板自带的版式名填好 %d 条,读一遍确认表意即可,通常不用改。' % prefilled)
2748
+ if recipes:
2749
+ L.append('# 容器样式配方(按出现次数排;跨页数多 = 共性风格,只在一处出现的多半不是):')
2750
+ for r in recipes[:8]:
2751
+ L.append('# %s 出现 %d 次 / 跨 %d 处 %s' % (r['id'], r['n'], r['pages'], r['css']))
2752
+ L.append('names:')
2753
+ for a in archetypes:
2754
+ if a.get('zh'):
2755
+ # 模板自己给版式起了名(form=3),直接用——比看图起名准,也省掉一轮判断
2756
+ L.append(' %s: %s' % (a['name'], q(a['zh'])))
2757
+ else:
2758
+ L.append(' %s: TODO中文名(代表页 %s,共 %d 页)'
2759
+ % (a['name'], a['rep'], len(a['pages'])))
2760
+ # 角色(封面 / 章节页 / 内容页……)是看图才能下的结论,脚本不猜。模板自己按页型
2761
+ # 命名时用它的标注,否则连同客观事实一起摆出来,由看得到重建图的你来定。
2762
+ need_role = [a for a in archetypes if not a.get('role')]
2763
+ if need_role:
2764
+ L.append('roles: # 取值 cover|section|content|quote|closing|blank|custom')
2765
+ for a in need_role:
2766
+ szs = sorted({round(s['sz']) for s in a['slots'] if s.get('sz')}, reverse=True)
2767
+ L.append(' %s: TODO角色 # 代表页 %s,共 %d 页;文字块 %d 个,字号 %s;'
2768
+ '图片 %d 张%s%s'
2769
+ % (a['name'], a['rep'], len(a['pages']),
2770
+ len([s for s in a['slots'] if not s.get('asset')]),
2771
+ '/'.join(str(x) for x in szs[:5]) or '未声明',
2772
+ a.get('pic_n') or 0, ';有满屏底图' if a.get('bg_raw') else '',
2773
+ ';末页候选,结合样张判断 closing 或实际角色'
2774
+ if a.get('_last_page_candidate') else ''))
2775
+ # 普通正文先保持 body:它是安全且可消费的默认值。标题/页眉/页脚的少量例外依然
2776
+ # 要由模型看样张后写入 text_roles;把每一个正文槽都做成 TODO 会迫使模型逐行复述
2777
+ # 近百个显然的 body,挤占真正的视觉判断时间。
2778
+ text_role_ids = {}
2779
+ for a in archetypes:
2780
+ index = 0
2781
+ for slot in a.get('slots') or []:
2782
+ if not slot.get('_needs_role'):
2783
+ continue
2784
+ index += 1
2785
+ text_role_ids[id(slot)] = '%s-text-%d' % (a['name'], index)
2786
+ if text_role_ids:
2787
+ L.append('# 文字槽默认均为 body。看样张后,只把确实属于 title|subtitle|header|footer 的'
2788
+ '例外追加到 text_roles:;不要为普通正文逐条补 body。')
2789
+ flow_archetypes = [a for a in archetypes if a.get('flow')]
2790
+ if flow_archetypes:
2791
+ L.append('# 同时有 flow 与 slots 时默认保留 slots,保证固定构图可消费。'
2792
+ '只有样张明确需要内容随高度重排时,才在 layout_modes: 中写 <页型>: flow。')
2793
+ # 禁放区是**背景图**的属性,不是页型的属性——按背景资产分组,页型再多也不涨
2794
+ bgs = []
698
2795
  for a in archetypes:
699
- L.append(' %s: TODO中文名(代表页 %s,共 %d 页)' % (a['name'], a['rep'], len(a['pages'])))
2796
+ if a['bg'] and a['bg'] not in bgs:
2797
+ bgs.append(a['bg'])
2798
+ if bgs:
2799
+ L.append('bg_rules:')
2800
+ for bg in bgs:
2801
+ users = [a['name'] for a in archetypes if a['bg'] == bg]
2802
+ L.append(' %s: # 用它的页型:%s' % (bg, ', '.join(users)))
2803
+ hint = (busy_hints or {}).get(bg)
2804
+ if hint:
2805
+ L.append(' # 图像局部对比度:中位 %s、九分位 %s;%s'
2806
+ % (hint['median'], hint['p90'],
2807
+ ('更花的一片在 %s' % hint['busy']) if hint.get('busy')
2808
+ else hint.get('why', '')))
2809
+ # text_safe 不是判断题:模板自己已经把文字放在哪儿写死了。取用这张背景的
2810
+ # 所有页型的槽与装饰件的外接并集即可——让人看图猜只会猜得更松,把模板从不
2811
+ # 放字的区域也划进安全区,这个字段就白设了。
2812
+ boxes = [s['box'] for a in archetypes if a['bg'] == bg for s in a['slots']] + \
2813
+ [dcr['box'] for a in archetypes if a['bg'] == bg for dcr in (a.get('decor') or [])]
2814
+ if boxes:
2815
+ x0 = min(b[0] for b in boxes)
2816
+ y0 = min(b[1] for b in boxes)
2817
+ x1 = max(b[0] + b[2] for b in boxes)
2818
+ y1 = max(b[1] + b[3] for b in boxes)
2819
+ L.append(' text_safe: [%d, %d, %d, %d] # 由该背景各页型的槽位并集算出'
2820
+ % (x0, y0, x1 - x0, y1 - y0))
2821
+ elif any(id(archetype) in sampled_archetypes
2822
+ for archetype in archetypes if archetype['bg'] == bg):
2823
+ L.append(' text_safe: TODO安全文字区[x,y,w,h](该背景下没有任何槽位可依据)')
2824
+ else:
2825
+ L.append(' text_safe: [0, 0, 0, 0] # 未见对应样张,没有可依据的文字区')
2826
+ if any(id(archetype) in sampled_archetypes
2827
+ for archetype in archetypes if archetype['bg'] == bg):
2828
+ L.append(' avoid: TODO禁放区列表;无禁放区写 [],有则写 [{box: [x,y,w,h], reason: "..."}]')
2829
+ L.append(' pairing_rule: "TODO这张背景上标题/正文/图表要避让哪些区域"')
2830
+ else:
2831
+ L.append(' avoid: [] # 未见对应样张,不额外推断禁放区')
2832
+ L.append(' pairing_rule: "未见对应样张;沿用该页型已有槽位"')
700
2833
  L.append('layouts:')
701
2834
  for a in archetypes:
2835
+ fx = (facts or {}).get(a['name']) or {}
2836
+ if fx:
2837
+ # 结构事实:判「这页该用绝对坐标还是流式」的依据。脚本只测不判。
2838
+ for gd in (fx.get('grids') or [])[:2]:
2839
+ c, r = gd.get('cols') or {}, gd.get('rows') or {}
2840
+ L.append(' # 栅格:%s 列%s%s' % (
2841
+ c.get('n'), ' @%gpx 步距方差 %.2f' % (c.get('pitch') or 0, c.get('sd') or 0)
2842
+ if c.get('regular') else '(列不规整)',
2843
+ ',行 %s' % (('%d @%gpx' % (r.get('n') or 0, r.get('pitch') or 0))
2844
+ if r.get('regular') else '不规整')))
2845
+ if fx.get('gaps'):
2846
+ L.append(' # 垂直间距:%s(突变处即区带边界)'
2847
+ % '、'.join(str(int(g)) for g in fx['gaps'][:10]))
2848
+ if fx.get('chars'):
2849
+ L.append(' # 样张字数:%s'
2850
+ % '、'.join('%s=%d字' % (b, n) for b, n in fx['chars'][:6]))
2851
+ if fx.get('recipes'):
2852
+ L.append(' # 命中配方:%s' % '、'.join(fx['recipes'][:4]))
2853
+ # 槽与槽在坐标上重叠:PPT 里占位符互相压是常态(文字 valign 居中、样张只有一行,
2854
+ # 看不出来),照抄坐标做成 HTML 后内容一变长就撞。实测封面 title 框比 subtitle
2855
+ # 的顶还低 41px,两行标题直接压在副标题上。这里只报事实,怎么让开由你定。
2856
+ ov = slot_overlaps(a.get('slots') or [])
2857
+ if ov:
2858
+ L.append(' # 槽位重叠:%s(模板里靠文字居中不显形,内容变长会撞)'
2859
+ % '、'.join(ov[:3]))
702
2860
  L.append(' %s:' % a['name'])
703
- L.append(' role: %s' % a['name'].split('-')[0])
2861
+ if a.get('role'):
2862
+ L.append(' role: %s' % a['role'])
704
2863
  if a['bg']:
705
2864
  L.append(' background: %s' % a['bg'])
706
- L.append(' text_safe: TODO安全文字区[x,y,w,h],按背景主体避让后填写')
707
- L.append(' avoid: TODO禁放区列表;无禁放区写 [],有则写 [{box: [x,y,w,h], reason: "..."}]')
708
- L.append(' pairing_rule: "TODO说明该页型必须配这张背景时,标题/正文/图表需要避让哪些区域"')
2865
+ fl = a.get('flow')
2866
+ if fl:
2867
+ L.append(' flow:')
2868
+ L.append(' top: %d' % fl['top'])
2869
+ L.append(' margin: [%d, %d]' % tuple(fl['margin']))
2870
+ L.append(' gap: %d' % fl['gap'])
2871
+ L.append(' regions:')
2872
+ for r in fl['regions']:
2873
+ if r['kind'] == 'grid':
2874
+ L.append(' - kind: grid')
2875
+ L.append(' cols: %d' % r['cols'])
2876
+ L.append(' gap: [%d, %d]' % tuple(r['gap']))
2877
+ if r.get('margin'):
2878
+ L.append(' margin: [%d, %d] # 本区带自己的左右边距,'
2879
+ '和整页 margin 不同(居中卡片组不跟标题的左边距)'
2880
+ % tuple(r['margin']))
2881
+ elif r['kind'] == 'free':
2882
+ L.append(' - kind: free # 推不出规整结构,按 slots 的坐标摆')
2883
+ else:
2884
+ L.append(' - kind: stack')
2885
+ L.append(' gap: %d' % r['gap'])
2886
+ L.append(' items:')
2887
+ for s in r['items']:
2888
+ if s.get('type') == 'group':
2889
+ L.append(' - role: group')
2890
+ L.append(' gap: %d' % s['gap'])
2891
+ if s.get('css'):
2892
+ L.append(' css: "%s"'
2893
+ % str(s['css']).replace('"', "'"))
2894
+ L.append(' items:')
2895
+ for child in s['items']:
2896
+ role_id = text_role_ids.get(id(child))
2897
+ if role_id:
2898
+ L.append(' # text-role: %s' % role_id)
2899
+ if child.get('type') == 'decor':
2900
+ L.append(' - {role: container, css: "%s"}'
2901
+ % str(child.get('css') or '').replace('"', "'"))
2902
+ continue
2903
+ extra = ''
2904
+ if child.get('css') is not None:
2905
+ extra += ', css: "%s"' % str(child['css']).replace('"', "'")
2906
+ if child.get('asset'):
2907
+ extra += ', asset: %s' % child['asset']
2908
+ if child.get('source_media'):
2909
+ extra += ', source_media: %s' % child['source_media']
2910
+ extra += ', source_box: %s' % child['box']
2911
+ L.append(' - {role: %s, type: %s%s}'
2912
+ % (child['role'], child['type'], extra))
2913
+ continue
2914
+ role_id = text_role_ids.get(id(s))
2915
+ if role_id:
2916
+ L.append(' # text-role: %s' % role_id)
2917
+ # free 区带按坐标摆,而 slots 会被删掉,所以坐标必须写在这里
2918
+ bx = ', box: %s' % s['box'] if r['kind'] == 'free' else ''
2919
+ if s.get('type') == 'decor':
2920
+ L.append(' - {role: container%s, css: "%s"}'
2921
+ % (bx, (s.get('css') or '').replace('"', "'")))
2922
+ continue
2923
+ extra = bx
2924
+ if s.get('css') is not None:
2925
+ # CSS 串一律加引号:里面的逗号/冒号在 flow map 里是分隔符
2926
+ extra += ', css: "%s"' % str(s['css']).replace('"', "'")
2927
+ if s.get('asset'):
2928
+ extra += ', asset: %s' % s['asset']
2929
+ if s.get('source_media'):
2930
+ extra += ', source_media: %s' % s['source_media']
2931
+ if r['kind'] != 'free':
2932
+ extra += ', source_box: %s' % s['box']
2933
+ L.append(' - {role: %s, type: %s%s}' % (s['role'], s['type'], extra))
709
2934
  L.append(' slots:')
710
2935
  for s in a['slots']:
711
- L.append(' - {role: %s, box: %s, type: %s}' % (s['role'], s['box'], s['type']))
2936
+ role_id = text_role_ids.get(id(s))
2937
+ if role_id:
2938
+ L.append(' # text-role: %s' % role_id)
2939
+ extra = ''
2940
+ if s.get('asset'):
2941
+ extra += ', asset: %s' % s['asset']
2942
+ if s.get('source_media'):
2943
+ extra += ', source_media: %s' % s['source_media']
2944
+ if s.get('css') is not None:
2945
+ extra += ', css: "%s"' % str(s['css']).replace('"', "'")
2946
+ L.append(' - {role: %s, box: %s, type: %s%s}'
2947
+ % (s['role'], s['box'], s['type'], extra))
2948
+ if a.get('decor'):
2949
+ L.append(' decor:')
2950
+ for dcr in a['decor']:
2951
+ L.append(' - {box: %s, geom: %s, css: "%s"}'
2952
+ % (dcr['box'], dcr['geom'], dcr['css'].replace('"', "'")))
712
2953
  L.append(' confidence: %s' % a.get('confidence', 'medium'))
713
2954
  write(os.path.join(ldir, 'layouts.yaml'), '\n'.join(L) + '\n')
714
-
715
-
716
- def emit_body(d, tokens, fonts, roles, assets, archetypes, exceptions, ldir):
2955
+ emit_layout_controls(L, ldir, [
2956
+ (text_role_ids[id(slot)], slot)
2957
+ for archetype in archetypes
2958
+ for slot in archetype.get('slots') or []
2959
+ if id(archetype) in sampled_archetypes and id(slot) in text_role_ids
2960
+ ], [
2961
+ archetype for archetype in flow_archetypes
2962
+ if id(archetype) in sampled_archetypes
2963
+ ])
2964
+
2965
+
2966
+ def emit_body(d, tokens, fonts, roles, assets, archetypes, exceptions, cusage, ldir,
2967
+ has_asset_candidates=False):
2968
+ """design.md 正文。
2969
+
2970
+ 每条规则只出现一次——同一条散在 Fast Path / Usage / Background Safety /
2971
+ Hard Rules 各写一遍时措辞必然漂移,消费端无法判断哪份权威。
2972
+ 坐标、字号、色值、资产位置的权威都在 layouts.md;本文件只给色板、字体栈与纪律。
2973
+ """
717
2974
  canvas = d['canvas']['px']
718
2975
  cover = next((a for a in assets if a['id'] == 'bg-cover'), None)
719
- logo = next((a for a in assets if a['kind'] == 'logo'), None)
720
- content_bgs = [a['id'] for a in assets
721
- if a.get('kind') == 'background' and a.get('role') == 'content']
722
- key_assets = []
723
- for a in assets[:8]:
724
- role = a.get('role') or a.get('kind')
725
- key_assets.append('`%s` -> `%s` (%s)' % (a['id'], a.get('out_rel') or a['id'], role))
726
-
727
- L = ['## Agent Fast Path', '',
728
- '消费本风格时先读这一节;它是给生成 Agent 的短路径,目标是把风格理解控制在 1 分钟内,避免把审计材料重新理解一遍。',
729
- '',
730
- '- **时间预算**:风格导入最多做 1 次 `read_file design.md`;如需坐标,最多再读 1 次 `layouts.md`。完成这两步后必须直接开始生成,不要再探索风格包。',
731
- '- **只读入口**:常规生成只需要 `design.md`;需要坐标时再打开 `layouts.md`。',
732
- '- **附件/zip 兜底**:如果当前内容来自 zip 附件的文本摘要,直接使用摘要中 `design.md` / `layouts.md` 的文本;不要尝试修复 zip、解析二进制、搜索附件目录或重建压缩包。',
733
- '- **禁止动作**:不要读取 `ref/color-freq-raw.json`、`ref/font-clusters.json`、`ref/extract.json`、`ref/rebuild/`、`ref/rebuild/png/*`;不要 summarize / view 参考页;不要重新统计颜色、字体或版式。',
734
- '- **信息来源优先级**:本节 > `## Usage` > frontmatter `assets` / `colors` / `typography` > `layouts.md`。除此之外的文件只用于人工审计,不用于生成。',
735
- '- **缺信息时降级**:如果某个细节本节没有写,用 frontmatter token 和最接近的 `layouts.md` archetype 推断;不要打开审计文件补证。',
736
- '- **画布**:所有坐标按 `%dx%d` 绝对像素理解。' % (canvas[0], canvas[1])]
737
- if cover:
738
- L.append('- **封面背景**:优先使用 `%s`;整幅铺满画布,禁止自造渐变替代。' % cover['id'])
739
- if content_bgs:
740
- L.append('- **内容页背景**:按 `layouts.md` 中 archetype 的 `background` 字段取;常用内容背景为 %s。'
741
- % ''.join('`%s`' % x for x in content_bgs[:4]))
742
- if cover or content_bgs:
743
- L.append('- **背景安全区**:背景图和版式必须配对。按 archetype `background`、`text_safe`、`avoid` 一起放文字和卡片;标题、正文、关键数字、图表、卡片、时间线及其容器的外接矩形都不得压到背景视觉主体、强光斑、深色透明区上,透明容器也不能跨进禁放区。')
744
- if logo:
745
- L.append('- **标识资产**:只使用 `%s`;不得重画、不得改比例。' % logo['id'])
746
- L += ['- **配色与字体**:颜色只取 frontmatter `colors`;字体/字号只取 frontmatter `typography`;内容主题不得引入新色相。',
747
- '- **版式**:优先使用下面内联版式索引;需要更多 slot 时才读 `layouts.md`;不要用 `ref/rebuild/png` 反推坐标。']
748
- if archetypes:
749
- L += ['', '内联版式索引(先用这里,不要为了选页型再读文件):']
750
- for a in archetypes:
751
- parts = ['`%s`' % a['name']]
752
- if a.get('bg'):
753
- parts.append('背景 `%s`' % a['bg'])
754
- slots = []
755
- for s in a['slots'][:4]:
756
- slots.append('%s/%s %s' % (s['role'], s['type'], s['box']))
757
- L.append('- %s:%s' % (' / '.join(parts), ';'.join(slots) or '按最接近用途套用'))
758
- if key_assets:
759
- L += ['', '关键资产:'] + ['- ' + a for a in key_assets]
760
-
761
- L += ['', '## Overview', '',
762
- 'TODO: 两三句话讲清这套模板的性格与适用场景——看过联系表和页面事实之后再写,不要套话。', '',
763
- '画布 %dx%d px,%d 页样张归纳出 %d 种页型;版式坐标全部放在 `layouts.md`。'
764
- % (canvas[0], canvas[1], d['counts']['slides'], len(archetypes)), '',
765
- '## Usage', '',
766
- '搭一页 PPT 就三步:', '',
767
- '1. **挑版式** —— 打开 `layouts.md`,按用途选一个 archetype,`slots[].box` 的 `[x, y, w, h]` 是 %dx%d 画布上的绝对像素,直接照搬,不要自己排版;同时遵守该 archetype 的 `text_safe` 和 `avoid`。'
768
- % (canvas[0], canvas[1])]
769
- if assets:
770
- L.append('2. **铺资产** —— 背景和标识只用 `assets/` 里的文件,见下表;不要自造渐变或重画 logo。背景必须和版式配对,文字必须留在安全区内。')
771
- else:
772
- L.append('2. **铺背景** —— 本包无图片资产,背景用 `colors` 里的底色。')
773
- L += ['3. **填色与字** —— 颜色只从 frontmatter 的 `colors` 取,字号只从 `typography` 取。', '']
774
- if assets:
775
- L += ['{{ASSET_TABLE}}', '']
776
- L += ['## Background Safety', '',
777
- '真实背景不是纯装饰底。填写本包时必须根据 `contact-sheet.png` `layout-sheet.png` 补充每个 archetype 的 `text_safe`、`avoid`、`pairing_rule`;消费时文字、图表、卡片、表格、时间线、标题容器、正文容器和宽透明容器的外接矩形不得与 `avoid` 区域重叠。内容量超出安全区时换页型或拆页,不要扩大文字区域压住背景主体。', '']
778
- L += ['**色板纪律**:整套页面只用 `colors` 里的 %d token,内容主题(咖啡、医疗、金融……)不改变配色;'
779
- '需要强调时用 `primary`,不要引入模板外的色相。' % len(tokens), '',
2976
+ imp, webs = import_line(fonts)
2977
+ sidecar = '`layouts.md`'
2978
+
2979
+ L = ['## Overview', '',
2980
+ 'TODO: 两三句话讲清这套模板的性格与适用场景——看过联系表和页面重建图之后再写。', '']
2981
+ L.append(('模板自带 %d 种版式,页型、坐标和 CSS 样式都直读自版式层。'
2982
+ % len(archetypes)) if (d.get('form_hint') or {}).get('form') == 3 else
2983
+ ('%d 页样张归纳出 %d 种页型。' % (d['counts']['slides'], len(archetypes))))
2984
+ L += ['', '## Usage', '',
2985
+ '搭一页 PPT 六步,中间四步的数据都在 %s:' % sidecar, '']
2986
+ L += ['1. **定画布** —— 舞台按 `layouts.md` 的 `canvas` 设成 %d×%d,'
2987
+ '别套用默认尺寸:源模板的长宽比不一定是 16:9,套错了整页坐标全偏。'
2988
+ '舞台尺寸改不了时,整体等比缩放 `min(舞台宽/%d, 舞台高/%d)` 后居中留白——'
2989
+ '逐轴拉伸会把圆压成椭圆、把字挤扁。' % (canvas[0], canvas[1], canvas[0], canvas[1]),
2990
+ '2. **挑页型** —— %s 里按用途选一个 archetype(清单见下面 Layouts 段)。'
2991
+ '页数多于页型时,挑最接近的一个原样套用它的 slot:用不到的槽删掉,'
2992
+ '内容比槽多就按同类槽的间距等距加,**坐标一律沿用该页型给的那套,不要自己另起网格**。'
2993
+ % sidecar,
2994
+ '3. **按页型给的形态落元素** —— 页型给 `flow` 就用流式,给 `slots` 就用绝对,'
2995
+ '两者只会出现一个。'
2996
+ '**flow**:整块用一个纵向 flex 容器,`top` 是它的起始 y,`margin` 是整块的左右边距,'
2997
+ '`gap` 是区带之间的间距;`regions` 从上往下依次排,**每个区带的高度由它自己的'
2998
+ '内容决定,不要写死高度**——上面的区带内容变多时,下面的自然被推下去,这正是'
2999
+ '这套表达要解决的事。区带内部:`kind: grid` `grid-template-columns: repeat(cols, 1fr)` '
3000
+ ' `gap: [行间距, 列间距]`;`kind: stack` 用纵向 flex 配 `gap`;`kind: free` '
3001
+ '按 item 自带的 `box` 绝对定位。区带自带 `margin: [左, 右]` 时用它的、'
3002
+ '覆盖整块的 `margin`(模板里居中的卡片组和贴左的标题横向范围本就不同);'
3003
+ '没带就用整块的 `margin`。`grid` 在自己这份左右边距里再 `repeat(cols, 1fr)`。'
3004
+ '`grid` 里的 `role: group` 是一张卡片:'
3005
+ 'group 的 `css` 用于外层容器,内部 `items` 按顺序纵向排布并使用 group 的 `gap`。'
3006
+ '每个 `role: container` 的项是容器,把它的 `css` 逐项原样写进 style,内容放进去;'
3007
+ '其中没有 `border-radius` 就按 `0`,不得自行补圆角。',
3008
+ '4. **按 slot 落元素(页型给的是 slots 时)** —— 每个 slot 渲染成一个绝对定位元素:`box` '
3009
+ '`[x, y, w, h]`(%dx%d 画布上的绝对像素),机械展开成 `left/top/width/height`;'
3010
+ 'slot `css` 是模板排版属性已转译好的声明串,原样写进 style,不要另选字号、'
3011
+ '内边距、颜色或对齐。'
3012
+ '带 `asset` slot 是图片元素(logo、角标),把该资产放在它自己的 `box` 里;'
3013
+ '这个页型没有 `asset` 槽,这一页就不出现该资产。' % (canvas[0], canvas[1]),
3014
+ '5. **铺装饰几何** —— 页型的 `decor` 是这一页的图形骨架(图标托底的圆、'
3015
+ '卡片、分隔线):每条渲染成一个绝对定位空元素,`box` 给位置,`css` 逐项原样写进 '
3016
+ 'style;没有 `border-radius` 就按 `0`。只有 `geom: ellipse` 另加 '
3017
+ '`border-radius: 50%`。它们压在背景之上、slot 之下,'
3018
+ '落在 slot 上的图标正是靠它们托住。',
3019
+ '6. **落实全局设计** —— `design.md` frontmatter 的 `colors`、`typography`、'
3020
+ '`spacing`、`rounded`、`components` 是全局 token;用 CSS variables、类名或内联'
3021
+ '样式承载。局部 slot / decor `css` 优先,不能再解释成另一套视觉系统。'
3022
+ '字体使用 Typography 的完整栈与降级,不在运行时安装字体或依赖。',
3023
+ '7. **保持标题结构** —— 有合适页型可参考时,沿用该页型已有的标题层级与局部 '
3024
+ '`css`;只渲染该页型已有的文字槽,背景中已经可见的固定标题不再创建文本,'
3025
+ '页型没有 `subtitle` 槽就不新增副标题。没有合适参考时,按本包整体视觉组织标题。']
3026
+ if assets or has_asset_candidates:
3027
+ L += ['', '资产文件(背景由页型的 `background` 字段指定,'
3028
+ '图片资产的位置由该页型 `slots` 里带 `asset` 的槽给出):', '',
3029
+ '{{ASSET_TABLE}}', '',
3030
+ '将包内 `assets/` 复制到项目内相对目录,再引用复制后的路径;最终 HTML 不引用'
3031
+ '抽取工作目录或本机绝对路径。附件只提供 `assetRoot` / `assetPaths` 时,把'
3032
+ '`assetRoot` 当作不透明前缀,只拼接清单中声明的相对路径。']
3033
+ L += ['', '文字与容器的外接矩形落在该页型 `background` 对应的 `text_safe` 内,'
3034
+ '避开 `avoid` 列出的区域(两者都在 %s 的 `backgrounds` 段)。内容装不下时换页型或拆页。'
3035
+ % sidecar, '',
780
3036
  '## Colors', '', '| token | 值 | 用途 |', '|---|---|---|']
781
- USE = {'surface': '页面与卡片主底色', 'surface-alt': '次级底色,分区/强调区块的浅底',
782
- 'ink': '正文与标题文字色', 'ink-muted': '次级文字色,说明与标签',
783
- 'primary': '主强调色:图表主序列、关键数字、行动点',
784
- 'accent': '副强调色,多与 primary 组成渐变',
785
- 'accent-2': '渐变与图表的第二落点色', 'accent-3': '渐变收尾色,用量最少',
786
- 'neutral': '中性弱化色:分隔线、次要标签'}
787
3037
  for name, r in tokens:
788
- L.append('| `%s` | `%s` | %s |' % (name, r['hex'], USE.get(name, '按 token 名对应的角色使用')))
789
- imp, webs = import_line(fonts)
3038
+ L.append('| `%s` | `%s` | %s |'
3039
+ % (name, r['hex'], usage_phrase(cusage.get(r['hex'].upper()))))
790
3040
  L += ['', '## Typography', '']
791
3041
  for f in fonts[:2]:
792
3042
  L.append('- **%s** —— 栈 `%s`%s' % (
793
3043
  f['names'][0], font_css(f['stack']),
794
3044
  ',源为商业/内部字体无 web 分发源,按气质降级到 %s' % f['stack'][1]
795
3045
  if len(f['stack']) > 1 else ''))
796
- L += ['', '字号轴:' + '、'.join('%s %dpx' % (k, round(v['sz_px'])) for k, v in roles.items()), '',
3046
+ L += ['', '字号轴:' + '、'.join('%s %dpx' % (k, round(v['sz_px'])) for k, v in roles.items())
3047
+ + '。slot 自带 `css` 时以其中的 `font-size` 为准;没有 slot CSS 的新增层级,'
3048
+ '复用轴上最接近的一档。', '',
797
3049
  '字体加载(**HARD REQUIREMENT:下面这行 @import 原样写入全局样式首行,禁止替换为 '
798
3050
  'fonts.googleapis.com 或其他域**):', '', '```', imp, '```', '',
799
- '镜像只保证 wght 400 一档,更粗的字重由浏览器合成,不要把字重当唯一区分手段;'
800
- '系统字体 PingFang SC / Microsoft YaHei 置于栈末保底,中文场景负字距一律清零。', '',
801
- '## Layouts', '',
802
- '**搭页前先读 `layouts.md`**——%d archetype slot 坐标都在那里,本文件不重复。'
803
- % len(archetypes), '', '{{LAYOUT_LIST}}']
804
- L += ['', '## Hard Rules', '']
3051
+ '镜像只保证 wght 400 一档,更粗的字重由浏览器合成,字重不能作为唯一区分手段;'
3052
+ '系统字体 PingFang SC / Microsoft YaHei 置于栈末保底,中文场景负字距清零。', '',
3053
+ '## Layouts', '', '页型清单如下,每个页型的 slots、background、'
3054
+ '禁放区都在 %s:' % sidecar, '', '{{LAYOUT_LIST}}',
3055
+ '', '## Hard Rules', '']
805
3056
  if cover:
806
- L.append('- 封面页背景必须铺 `bg-cover`(文件见 Usage 表),整幅铺满 %dx%d,不要自造渐变或换图。'
807
- % (canvas[0], canvas[1]))
3057
+ L.append('- 封面页铺满 `bg-cover`,整幅覆盖 %dx%d 画布。' % (canvas[0], canvas[1]))
808
3058
  if any(a['role'] == 'content' for a in assets):
809
- L.append('- 内容页背景整幅铺满,用哪一张按 `layouts.md` 里该 archetype 的 `background` 字段取,不要混用。')
810
- if logo:
811
- b, pages = logo['src']['box'], logo['src']['slides']
812
- where = ('只出现在源第 %s 页' % '、'.join(map(str, pages))
813
- if pages and len(pages) <= 4 else '每页放一次')
814
- L.append('- `%s` 放在 (%d, %d),尺寸 %dx%d px,%s;不要重画、不要替换成文字、不要改比例。'
815
- % (logo['id'], b.get('x', 0), b.get('y', 0), b.get('w', 0), b.get('h', 0), where))
816
- L += ['- 版式坐标只从 `layouts.md` 的 `slots[].box` 取。',
817
- '- 颜色只用 `colors` 里的 token;字号只用 `typography` 里的档位。',
818
- '- `@import` 行原样写入,禁止替换域名。',
819
- '- TODO: 补 1-2 条这套模板特有的硬规则(看过联系表之后写,例如主色只许用在哪类元素)。',
3059
+ L.append('- 内容页的背景由该页型的 `background` 字段指定,整幅铺满。')
3060
+ L.append('{{LOGO_RULES}}')
3061
+ L += ['- 坐标、字号、色值、资产位置以 %s 为准;本文件的 Colors / Typography 是可用值的清单。'
3062
+ % sidecar,
3063
+ '- 强调色族以 Colors %s slot CSS 为主;必要时可以使用 Colors 之外的颜色,'
3064
+ '但不能形成与模板主色竞争的第二强调色。' % sidecar,
3065
+ '- 新增颜色应与模板整体的色相、明度和饱和度关系协调。允许新增中性色、低彩度辅助色'
3066
+ '或局部语义色表达正负、风险、警告、状态、图表序列,但保持辅助层级;'
3067
+ '只要新色通过高饱和、高对比、大面积或跨页重复获得主视觉权重,'
3068
+ '或被用于标题、关键数字、图表主序列、卡片底色或渐变,就属于新的强调色,改用模板'
3069
+ '强调色族的深浅、透明度,或改用线型、纹理、标签区分。',
3070
+ '- 交付前逐页检查:色板、字体、版式、背景、资产和本段规则均来自本风格包;'
3071
+ '页面无资源加载失败、内容溢出或画幅裁切。',
3072
+ '- 本包里的数值就是普查结果,照用即可,无需重新统计颜色、字体或版式。',
3073
+ '- 风格包以文本形式(zip 摘要等)到手时,直接用摘要里 design.md / layouts.md 的文本。',
820
3074
  '', '## Exceptions', '']
821
3075
  if exceptions:
822
3076
  L += ['- ' + e for e in exceptions]
@@ -827,32 +3081,82 @@ def emit_body(d, tokens, fonts, roles, assets, archetypes, exceptions, ldir):
827
3081
 
828
3082
 
829
3083
  def emit_brief(d, ctx, ldir):
830
- (tokens, rest, fonts, roles, assets, rejected, todos, archetypes, cands, sheet,
831
- leftover, lsheet) = ctx
3084
+ (tokens, rest, fonts, roles, assets, rejected, todos, archetypes, cands, sheets,
3085
+ selected_vision_groups, omitted_vision_groups, leftover, lsheet) = ctx
832
3086
  canvas = d['canvas']['px']
833
- L = ['# 抽取简报(草案已生成,读完这一页就能改)', '',
3087
+ def sample_pages(archetype):
3088
+ return archetype.get('pages') or archetype.get('_sample_pages') or []
3089
+
3090
+ sampled_archetypes = [
3091
+ archetype for archetype in archetypes
3092
+ if archetype.get('rep') is not None or sample_pages(archetype)
3093
+ ]
3094
+ template_only_archetypes = [
3095
+ archetype for archetype in archetypes
3096
+ if archetype not in sampled_archetypes
3097
+ ]
3098
+ L = ['# 抽取简报(第 1/3 步产物;改完草案跑 package.py 出包)', '',
834
3099
  '源:`%s` 画布 %dx%d %d 页 / %d 版式 主题 %s form=%s'
835
3100
  % (d['source']['filename'], canvas[0], canvas[1], d['counts']['slides'],
836
3101
  d['counts']['layouts'], d['theme_topology']['themes'],
837
3102
  d['form_hint']['form']), '',
838
3103
  '## 待判断(草案里已标 TODO,逐条改掉)', '']
839
- base_todos = ['给风格起名:`manifest.yaml` 的 name / name_zh / description(看两张图定气质)',
840
- '`layouts.yaml` 顶部 `names:` 一段填 %d 个中文页型名(看 layout-sheet.png,'
841
- '一次改完;下面 layouts 段不要动)' % len(archetypes),
842
- '`body.md` Overview 与 Hard Rules 末条(Colors 用途列草案已填好,觉得不对再改)']
843
- for t in base_todos + todos:
3104
+ # 待判断清单从草案实时扫 TODO 生成,不写死:写死的清单会和草案对不上——
3105
+ # 既漏掉后加的段(模型读到一半才发现还有活),又在草案已预填时还催人去填。
3106
+ HINT = {'manifest.yaml': '看两张图定气质',
3107
+ 'layout-controls.yaml': '看 layout-sheet.png;只改这个控制区',
3108
+ 'body.md': 'Colors 用途列草案已填好,觉得不对再改'}
3109
+ for fn in ('manifest.yaml', 'body.md', 'layout-controls.yaml', 'frontmatter.yaml'):
3110
+ path = os.path.join(ldir, fn)
3111
+ if not os.path.exists(path):
3112
+ continue
3113
+ keys = []
3114
+ for line in open(path, encoding='utf-8'):
3115
+ if 'TODO' not in line:
3116
+ continue
3117
+ m = re.match(r'\s*[-#]?\s*([\w-]+):', line)
3118
+ keys.append(m.group(1) if m else line.strip()[:24])
3119
+ if not keys:
3120
+ continue
3121
+ seen, uniq = set(), []
3122
+ for k in keys:
3123
+ if k not in seen:
3124
+ seen.add(k)
3125
+ uniq.append(k)
3126
+ hint = HINT.get(fn)
3127
+ L.append('- `%s` %d 处:%s%s'
3128
+ % (fn, len(keys), '、'.join(uniq[:6]) + ('…' if len(uniq) > 6 else ''),
3129
+ '(%s)' % hint if hint else ''))
3130
+ for t in todos:
844
3131
  L.append('- ' + t)
845
- L += ['', '## 联系表(一次看完所有候选图)', '',
846
- '`l-out/contact-sheet.png` —— 编号对应下表;看完再决定 logo / 封面归属。' if sheet
847
- else '(Pillow 不可用,未生成联系表;逐张看 `media-out/`)', '',
848
- '| # | 文件 | 尺寸 | 出现 | 满屏 | 页 | 草案判定 |', '|---|---|---|---|---|---|---|']
3132
+ L += ['', '## 资产判断(按视觉组一次看完)', '',
3133
+ ('视觉判断拼版:%s。每张都含候选独立卡与所在页截图;只读这些拼版,不逐张打开素材。'
3134
+ % '、'.join('`l-out/%s`' % os.path.basename(path) for path in sheets))
3135
+ if sheets else '(未生成视觉拼版;不要给图片候选定性,已按内容图保留位置并在 gaps 说明。)',
3136
+ '`l-out/asset-vision-groups.json` 记录每张候选的原图尺寸、所有页内位置和尺寸;'
3137
+ '透明/近白候选在拼版中同时给棋盘格和深灰底预览。',
3138
+ '按每个候选实例填 `asset_vision_groups.visual_kind`;同源图在不同页型/位置可不同。'
3139
+ '第三方 logo 墙属于 `content-image`,不是 deck 的 `logo`。',
3140
+ '',
3141
+ '| ID | 文件 | 原图 | 出现 | 页 | 所有位置 |', '|---|---|---|---|---|---|']
849
3142
  decided = {a['src']['file']: a['id'] for a in assets}
850
3143
  why = {c['file']: r for c, r in rejected}
851
- for i, c in enumerate(cands[:12], 1):
852
- L.append('| %d | `%s` | %sx%s | %d | %s | %s | %s |' % (
853
- i, c['file'], c['probe'].get('w') or '?', c['probe'].get('h') or '?', c['n'],
854
- 'Y' if c['fullscreen'] else '', ','.join(map(str, c['slides'][:6])) or 'layout',
855
- decided.get(c['file']) or ('✗ ' + why.get(c['file'], '未采纳'))))
3144
+ selected_candidates = {
3145
+ candidate['file']: candidate
3146
+ for group in selected_vision_groups
3147
+ for candidate in group['candidates']
3148
+ }
3149
+ for c in selected_candidates.values():
3150
+ L.append('| `%s` | `%s` | %sx%s | %d | %s | `%s` |' % (
3151
+ c['id'], c['file'], c['probe'].get('w') or '?', c['probe'].get('h') or '?',
3152
+ c['n'], ','.join(map(str, c['slides'])) or 'layout', _placement_text(c)))
3153
+ if omitted_vision_groups:
3154
+ omitted_pages = sorted({
3155
+ page for group in omitted_vision_groups for page in group['pages'] if page > 0
3156
+ })
3157
+ L.append('')
3158
+ L.append('未进视觉预算:%s;对应 slot 默认保留内容图片位置,不会自动升为风格资产。'
3159
+ % ('第%s页' % '、'.join(map(str, omitted_pages)) if omitted_pages else '版式候选'))
856
3160
  L += ['', '## 颜色(草案 token 已写进 frontmatter.yaml)', '',
857
3161
  '| token | hex | 出现 |', '|---|---|---|']
858
3162
  for name, r in tokens:
@@ -868,24 +3172,55 @@ def emit_brief(d, ctx, ldir):
868
3172
  L.append('')
869
3173
  L.append('字号轴:' + '、'.join('%s=%dpx(n=%d)' % (k, round(v['sz_px']), v['n'])
870
3174
  for k, v in roles.items()))
871
- L += ['', '## 版式聚类(草案已写进 layouts.yaml)', '',
872
- '`l-out/layout-sheet.png` 是各页型代表页的重建图——**看它给页型起名**,'
873
- '不用再逐页查 shapes。' if lsheet else '(未生成版式图,按下面的 slot 原文命名)', '',
3175
+ L += ['', '## 版式聚类(判断项在 layout-controls.yaml,坐标事实在 layouts.yaml)', '',
3176
+ ('`l-out/layout-sheet.png` 是各页型代表页的重建图——**看它给页型起名**,'
3177
+ '不用再逐页查 shapes。' if sampled_archetypes else
3178
+ '`l-out/layout-sheet.png` 是模板版式层的重建图;用它看整体视觉即可,'
3179
+ '没有对应样张的版式已按模板名称预填,不逐项改名或判角色。')
3180
+ if lsheet else '(未生成版式图,按下面的 slot 原文命名)', '',
874
3181
  '| archetype | 页数 | 代表页 | 背景 | slot 数 |', '|---|---|---|---|---|']
875
- for a in archetypes:
3182
+ for a in sampled_archetypes:
3183
+ pages = sample_pages(a)
3184
+ representative = a.get('rep') or (pages[0] if pages else None)
876
3185
  L.append('| `%s` | %d | %s | %s | %d |' % (
877
- a['name'], len(a['pages']), a['rep'], a['bg'] or '(无资产底图)', len(a['slots'])))
3186
+ a['name'], len(pages), representative, a['bg'] or '(无资产底图)', len(a['slots'])))
3187
+ if template_only_archetypes:
3188
+ L.append('')
3189
+ L.append('另有 %d 个模板声明版式没有对应样张:名称、角色和坐标已预填并会进入最终包;'
3190
+ '除非当前样张直接证明不对,不需要逐项判断。'
3191
+ % len(template_only_archetypes))
3192
+ sampled_pages = {
3193
+ page: archetype
3194
+ for archetype in sampled_archetypes
3195
+ for page in sample_pages(archetype)
3196
+ }
3197
+ first_page = 1
3198
+ last_page = d['counts']['slides']
3199
+ if first_page in sampled_pages:
3200
+ first_archetype = sampled_pages[first_page]
3201
+ L.append('')
3202
+ L.append('第 1 页实际使用页型:`%s`。若样张确为封面,只在 `roles.%s` 填 `cover`,'
3203
+ '不要按页型名称猜。'
3204
+ % (first_archetype['name'], first_archetype['name']))
3205
+ if last_page != first_page and last_page in sampled_pages:
3206
+ last_archetype = sampled_pages[last_page]
3207
+ L.append('第 %d 页实际使用页型:`%s`。若样张确为封底,只在 `roles.%s` 填 `closing`,'
3208
+ '不要按页型名称猜。'
3209
+ % (last_page, last_archetype['name'], last_archetype['name']))
878
3210
  if leftover:
879
3211
  L += ['', '未归入 archetype 的页:%s —— 都是单页孤例,需要就自己补一个 archetype。'
880
3212
  % ', '.join(map(str, leftover))]
881
- L += ['', ' archetype slot 原文(据此起中文页型名、改 role):', '']
882
- for a in archetypes:
883
- L.append('- `%s`(第 %s 页,覆盖 %s)' % (a['name'], a['rep'], a['pages']))
3213
+ L += ['', '有样张页型的 slot 原文(据此起中文页型名,并在 text_roles 判断文本角色):', '']
3214
+ for a in sampled_archetypes:
3215
+ pages = sample_pages(a)
3216
+ representative = a.get('rep') or (pages[0] if pages else None)
3217
+ L.append('- `%s`(第 %s 页,覆盖 %s)' % (a['name'], representative, pages))
884
3218
  for s in a['slots']:
885
3219
  L.append(' - %s %spx 「%s」' % (s['role'], round(s['sz']), s['txt']))
886
3220
  L += ['', '## 下一步', '',
887
- '1. `contact-sheet.png` 和 `layout-sheet.png`;'
888
- '2. 用一次批量编辑/patch 改掉四份草案里的 TODO;3. 跑 `package.py`。']
3221
+ '1. 并行看全部 `vision-group-*.jpg` 和 `layout-sheet.png`;'
3222
+ '2. 先填 asset_vision_groups,再用少量 asset_decisions 写例外,最后一次批量改完其它 TODO;'
3223
+ '3. 只改 `layout-controls.yaml` 的版式判断项,再跑 `package.py`。']
889
3224
  write(os.path.join(ldir, 'BRIEF.md'), '\n'.join(L) + '\n')
890
3225
 
891
3226
 
@@ -898,46 +3233,158 @@ def main(argv=None):
898
3233
  ldir = os.path.join(outdir, 'l-out')
899
3234
  os.makedirs(ldir, exist_ok=True)
900
3235
 
901
- tokens, rest, _ = draft_colors(d)
3236
+ all_shapes = json.load(open(os.path.join(outdir, 'ref', 'shapes.json'),
3237
+ encoding='utf-8'))['shapes']
3238
+ cusage = color_usage(all_shapes, d)
3239
+ tokens, rest, rows = draft_colors(d, cusage)
902
3240
  fonts = draft_fonts(d)
903
- archetypes, pages, leftover = draft_layouts(d, outdir)
904
- cover_media = next((a['bg_raw'] for a in archetypes if a['name'] == 'cover'), None)
905
- bg_needed = {a['bg_raw'] for a in archetypes if a['bg_raw'] and a['bg_raw'].startswith('ppt/media')}
906
- bg_under = {p['no']: p['bg_media'] for p in pages}
907
- assets, rejected, todos = draft_assets(d, outdir, bg_needed, cover_media, bg_under)
3241
+ effective_alpha = fullscreen_effective_alpha(d, outdir, all_shapes)
3242
+ archetypes, pages, leftover = draft_layouts(d, outdir, effective_alpha)
3243
+ # 只有模板已声明 cover 页型时才能直读它的封面背景。首页和末页会单独保留样张,
3244
+ # 但它们的角色仍由模型看图判断,不能因为页码就自动升格为 cover / closing。
3245
+ cover_media = cover_background_media(archetypes)
3246
+ exported_media = {m['media'] for m in d.get('media', []) if m.get('exported')}
3247
+ bg_needed = {a['bg_raw'] for a in archetypes if a['bg_raw'] in exported_media}
3248
+ bg_under = {p['no']: p.get('rendered_bg') or p['bg_media'] for p in pages}
3249
+ assets, rejected, todos, alias, pool = draft_assets(
3250
+ d, outdir, bg_needed, cover_media, bg_under, effective_alpha)
908
3251
  media_to_asset = {a['src']['media']: a['id'] for a in assets}
3252
+ for m, w in (alias or {}).items():
3253
+ if w in media_to_asset:
3254
+ media_to_asset.setdefault(m, media_to_asset[w])
3255
+
3256
+ cW, cH = d['canvas']['px']
909
3257
  for a in archetypes:
910
3258
  a['bg'] = media_to_asset.get(a['bg_raw'])
3259
+ # 版式自带的图片元素:映射到资产 id。映射不到时**保留槽位但不写 asset**——
3260
+ # 删掉整条槽,消费端看到的是一个没有图标的托底圆,和图标不进包是同一个失败模式,
3261
+ # 而且它连「这里本来有东西」都不知道。
3262
+ keep = []
3263
+ for s in a['slots']:
3264
+ if s.get('media'):
3265
+ aid = media_to_asset.get(s['media'])
3266
+ if not aid:
3267
+ c = pool.get(alias.get(s['media'], s['media'])) or pool.get(s['media'])
3268
+ s['role'] = 'asset-candidate'
3269
+ if c:
3270
+ s['source_media'] = c['file']
3271
+ s.pop('media', None)
3272
+ keep.append(s)
3273
+ continue
3274
+ s['asset'] = aid
3275
+ c = pool.get(alias.get(s['media'], s['media'])) or pool.get(s['media'])
3276
+ if c:
3277
+ s['source_media'] = c['file']
3278
+ # role 跟着资产走:图标槽写成 logo 会让消费端把它当品牌标识,每页都摆一个
3279
+ s['role'] = next((x['kind'] for x in assets if x['id'] == aid), s['role'])
3280
+ keep.append(s)
3281
+ a['slots'] = keep
911
3282
  roles = draft_scale(d, archetypes)
912
- cands = sorted([c for c in [a['src'] for a in assets]] +
913
- [c for c, _ in rejected], key=lambda c: (-c['n'], c['file']))
914
- sheet = contact_sheet(outdir, cands, os.path.join(ldir, 'contact-sheet.png'))
3283
+ slot_added = cover_slot_colors(tokens, archetypes, rows, cusage)
3284
+ # 局部图和半透明满屏叠加层必须结合页面语境定性。候选在本阶段按图片槽过滤:
3285
+ # 没有最终槽位的媒体无需让模型判断;有槽位但超出视觉预算的则保留通用 pic 槽。
3286
+ decided_c = sorted([a['src'] for a in assets], key=lambda c: (-c['n'], c['file']))
3287
+ other_c = sorted([c for c, _ in rejected], key=lambda c: (-c['n'], c['file']))
3288
+ cands, seen_file = [], set()
3289
+ for c in decided_c + other_c: # 同一张图可能有多条候选记录(不同位置各一条)
3290
+ if c['file'] not in seen_file:
3291
+ seen_file.add(c['file'])
3292
+ cands.append(c)
3293
+ review_candidates = []
3294
+ for candidate_index, candidate in enumerate(
3295
+ visual_slot_candidates(cands, archetypes), 1):
3296
+ row = dict(candidate)
3297
+ row['id'] = 'asset-%d' % candidate_index
3298
+ review_candidates.append(row)
3299
+ selected_vision_groups, omitted_vision_groups, sheets = emit_asset_vision_groups(
3300
+ outdir, review_candidates, d['counts']['slides'], ldir)
915
3301
  lsheet = layout_sheet(outdir, archetypes, os.path.join(ldir, 'layout-sheet.png'))
916
3302
 
917
3303
  anchors = draft_anchors(d, tokens, fonts, roles, assets, archetypes)
918
3304
  gaps, exceptions = [], []
3305
+ if omitted_vision_groups:
3306
+ omitted_pages = sorted({
3307
+ page for group in omitted_vision_groups for page in group['pages'] if page > 0
3308
+ })
3309
+ if omitted_pages:
3310
+ gaps.append('视觉略过:%s页' % '/'.join(map(str, omitted_pages)))
3311
+ else:
3312
+ gaps.append('视觉判断超预算,未覆盖版式候选')
3313
+ if review_candidates and not sheets:
3314
+ gaps.append('视觉拼版不可用,图片候选按内容图保留,未做风格定性。')
919
3315
  for c, why in rejected:
920
3316
  if '近全透明' in why:
921
3317
  gaps.append('母版/版式里的 %s 是%s,不是设计资产,任何情况下不要当背景用。' % (c['file'], why))
922
- for f in fonts[:2]:
923
- if len(f['stack']) > 1:
3318
+ elif '不是背景' in why:
3319
+ gaps.append('%s 在模板里铺满整页,但%s;那几页的真实背景是幻灯片自身的底色,'
3320
+ '需要时按 Colors 里的 surface 铺纯色。' % (c['file'], why))
3321
+ by_kind = {}
3322
+ for kind, kept, total, advice, where in _TRUNCATED:
3323
+ e = by_kind.setdefault(kind, {'kept': 0, 'total': 0, 'advice': advice, 'where': []})
3324
+ e['kept'] += kept
3325
+ e['total'] += total
3326
+ if where:
3327
+ e['where'].append(where)
3328
+ for kind, e in by_kind.items():
3329
+ at = ('(%s)' % '、'.join(e['where'][:6])) if e['where'] else ''
3330
+ gaps.append('%s%s按名额截断:普查到 %d 个,包内留了 %d 个%s。'
3331
+ % (kind, at, e['total'], e['kept'],
3332
+ ';' + e['advice'] if e['advice'] else ''))
3333
+ # 「没命中映射表」不等于「装不上」:降级目标本身(Noto Sans SC 之类)和 Office 出厂体
3334
+ # 都不在 match 列里,但它们本来就可用。真正危险的是**既没命中、又不是已知可用字体**的
3335
+ # 那种——design.md 的字体栈里留着一个消费端装不上的商业字体名,且没有任何降级说明。
3336
+ web_ok = {norm(x) for fam in parse_fallback_table() for x in fam['fallback']}
3337
+ web_ok |= {norm(x.strip().strip('"')) for x in SYS_FALLBACK.split(',')}
3338
+ for f in fonts:
3339
+ if f.get('mapped'):
924
3340
  gaps.append('源字体 %s 无 web 授权源,已按 font-fallback 表降级到 %s;字形细节与原稿有差异。'
925
3341
  % (f['names'][0], f['stack'][1]))
3342
+ elif norm(f['names'][0]) in OFFICE_DEFAULT_FONTS_NORM:
3343
+ gaps.append('%s 是 Office 出厂字体,多半是模板里没清干净的残留而非设计选型;'
3344
+ '按正文/标题的实际气质挑替代体,不要照抄它。' % f['names'][0])
3345
+ elif norm(f['names'][0]) not in web_ok:
3346
+ gaps.append('源字体 %s 不在 font-fallback 表里,字体栈只有原名,消费端很可能装不上;'
3347
+ '按气质挑一个有 web 分发源的近似体补进栈,不要照抄原名。' % f['names'][0])
3348
+ nosize = [(a['name'], s['box']) for a in archetypes for s in a['slots']
3349
+ if not s.get('asset') and not s.get('_font_size')]
3350
+ if nosize:
3351
+ gaps.append('这些文字槽在源文件任何层级都没有字号声明(都不是占位符,是普通文本框,'
3352
+ '继承源是 presentation.xml 的 defaultTextStyle,本抽取按约定不解继承链):'
3353
+ '%s。用 typography 里最接近的档位,不要自造新档。'
3354
+ % '、'.join('%s %s' % (n, b) for n, b in nosize[:6]))
3355
+
926
3356
  if leftover:
927
3357
  exceptions.append('源 deck 第 %s 页是单页孤例,没有归纳成 archetype;需要类似构图时按最接近的页型改。'
928
3358
  % '、'.join(map(str, leftover)))
929
3359
 
930
- emit_manifest(d, assets, ldir)
3360
+ emit_manifest(d, assets, selected_vision_groups, ldir)
931
3361
  emit_frontmatter(d, tokens, fonts, roles, anchors, gaps, ldir)
932
- emit_layouts(archetypes, ldir)
933
- emit_body(d, tokens, fonts, roles, assets, archetypes, exceptions, ldir)
934
- emit_brief(d, (tokens, rest, fonts, roles, assets, rejected, todos, archetypes, cands, sheet,
935
- leftover, lsheet), ldir)
936
-
937
- print('草案就绪 -> %s' % ldir)
938
- print(' 资产 %d(%s) 版式 %d 色 %d 字体 %d'
3362
+ # 每张背景量一次局部对比度,作为「哪里不能压文字」的客观依据摆进判断单。
3363
+ # 只报测到的数,不替人填 avoid——哪块算主体、要不要避让,是看图才能定的。
3364
+ busy_hints = {}
3365
+ for a in assets:
3366
+ if a['kind'] != 'background' or not a['src'].get('out'):
3367
+ continue
3368
+ r = bg_busy_map(os.path.join(outdir, a['src']['out']), (cW, cH))
3369
+ if r:
3370
+ busy_hints[a['id']] = r
3371
+ facts, recipes = structure_facts(archetypes, d, all_shapes)
3372
+ for a in archetypes:
3373
+ a['flow'] = draft_flow(a, facts.get(a['name']) or {}, (cW, cH))
3374
+ emit_layouts(archetypes, ldir, busy_hints, facts, recipes)
3375
+ emit_body(d, tokens, fonts, roles, assets, archetypes, exceptions, cusage, ldir,
3376
+ has_asset_candidates=any(needs_asset_judgment(c) for c in cands))
3377
+ emit_brief(d, (tokens, rest, fonts, roles, assets, rejected, todos, archetypes, cands, sheets,
3378
+ selected_vision_groups, omitted_vision_groups, leftover, lsheet), ldir)
3379
+
3380
+ # 这几行落在模型判断「skill 是不是做完了」的那一刻。只报数就会被读成「包已生成」,
3381
+ # 于是判断和打包整段被跳过,deck 拿不到任何版式坐标。所以这里报进度与下一条命令。
3382
+ print('第 1/3 步完成,判断单草案 -> %s' % ldir)
3383
+ print(' 待你确认:资产 %d(%s) 版式 %d 色 %d 字体 %d'
939
3384
  % (len(assets), ', '.join(x['id'] for x in assets), len(archetypes), len(tokens), len(fonts)))
940
- print(' 先读 l-out/BRIEF.md,再看 l-out/contact-sheet.png')
3385
+ print(' 2 步 读 l-out/BRIEF.md,并行看视觉组拼版与版式图;版式判断只改 layout-controls.yaml')
3386
+ print(' 第 3 步 package.py 产出 design.md + layouts.md —— deck 的版式坐标只从这两份读')
3387
+ sys.stdout.flush()
941
3388
  return 0
942
3389
 
943
3390