@lark-apaas/coding-steering 0.1.18-dev.21ea0ba → 0.1.18-dev.22911a7

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.
@@ -19,12 +19,39 @@ import shutil
19
19
  import sys
20
20
  from collections import Counter, defaultdict
21
21
 
22
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
23
+ from ooxml import OFFICE_DEFAULT_FONTS # noqa: E402
24
+ from census import (ASSET_WARN_SINGLE, FULLSCREEN_COVERAGE, LUM_MID, # noqa: E402
25
+ REPEAT_MIN, SMALL_IMG_W_PCT, canvas_coverage)
26
+
27
+ OPAQUE_ENOUGH = 128 # 能当背景的最低不透明度:低于半透明就遮不住底下的东西,
28
+ # 那是叠加装饰不是背景
29
+ FILL_MANY = 5 # 「被大量当填充铺开」的次数下限,用于区分卡片底与偶发用色
30
+ BG_CONTENT_CAP = 5 # 内容页背景收几张:再多消费端也挑不过来,超出的写进 TODO 交人取舍
31
+ SHEET_CAP = 12 # 联系表展示上限;进包的资产不受它约束,一张都不截
32
+
22
33
  HERE = os.path.dirname(os.path.abspath(__file__))
23
34
  SKILL_ROOT = os.path.dirname(HERE)
24
35
  SYS_FALLBACK = '"PingFang SC", "Microsoft YaHei", sans-serif'
25
36
 
26
37
 
27
38
  # ---------------------------------------------------------------- 小工具
39
+ # 被名额截掉的东西统一记在这里,最后并进 gaps。截断本身是必要的(色板 40 个 token
40
+ # 消费端挑不过来),但**不说**就成了「悄悄少了东西而产物看起来正常」——消费端会以为
41
+ # 它拿到的就是全部。
42
+ _TRUNCATED = []
43
+
44
+
45
+ def note_truncation(kind, kept, total, advice='', where=''):
46
+ """记一条「这里按名额截断了」。kept >= total 时什么都不记。
47
+
48
+ 按 kind 归并成一条 gap:同一类截断逐处各写一行会淹掉别的 gaps。
49
+ """
50
+ if total > kept:
51
+ _TRUNCATED.append((kind, kept, total, advice, where))
52
+ return kept
53
+
54
+
28
55
  def hex2rgb(h):
29
56
  h = h.lstrip('#')
30
57
  return tuple(int(h[i:i + 2], 16) for i in (0, 2, 4))
@@ -82,7 +109,64 @@ def q(v):
82
109
 
83
110
 
84
111
  # ---------------------------------------------------------------- 颜色
85
- def draft_colors(d):
112
+ def bg_colors(d):
113
+ """页面/版式/母版的 `background` 声明里出现的底色,按声明次数排序。
114
+
115
+ 「哪个色是底色」是直读事实(bgPr / bgRef),不用靠亮度猜:渐变里出现的浅色,
116
+ 亮度可能比真底色更像底色。
117
+ """
118
+ cnt = Counter()
119
+ rows = (d.get('slides') or []) + (d.get('layouts') or []) \
120
+ + ((d.get('masters') or {}).get('masters') or [])
121
+ for row in rows:
122
+ bg = row.get('background')
123
+ if not isinstance(bg, dict):
124
+ continue
125
+ cols = []
126
+ if isinstance(bg.get('color'), dict):
127
+ cols.append(bg['color'])
128
+ for st in (bg.get('stops') or []):
129
+ if isinstance(st.get('color'), dict):
130
+ cols.append(st['color'])
131
+ for c in cols:
132
+ h = (c.get('hex') or '').upper()
133
+ if h:
134
+ cnt[h] += 1
135
+ return [h for h, _ in cnt.most_common()]
136
+
137
+
138
+ def _gap_cut(vals, lo, hi):
139
+ """在排序后的值里找最大间隙,切点取间隙中点。
140
+
141
+ 不用中位数:中位数会正好落在某个样本自己身上,它归哪边就只取决于写 >= 还是 >,
142
+ 纯属任意。真正的分界在两族之间的空档里。夹在 [lo, hi] 内,避免整套同色的模板
143
+ 把界推到极端。
144
+ """
145
+ v = sorted(vals)
146
+ if len(v) < 2:
147
+ return (lo + hi) / 2.0
148
+ _, mid = max((v[i + 1] - v[i], (v[i + 1] + v[i]) / 2.0) for i in range(len(v) - 1))
149
+ return min(max(mid, lo), hi)
150
+
151
+
152
+ def palette_cuts(rows):
153
+ """「有彩 vs 中性」「深 vs 浅」的分界,按本模板自己的色分布切。
154
+
155
+ 固定分界必然错一边:低饱和的莫兰迪配色整套都在低位,高饱和的品牌配色整套都在高位。
156
+ """
157
+ sat_cut = _gap_cut([r['sat'] for r in rows], 0.12, 0.45)
158
+ lums = sorted(r['lum'] for r in rows) or [0.0]
159
+ return sat_cut, lums[len(lums) // 2]
160
+
161
+
162
+ def draft_colors(d, cusage=None):
163
+ """色板 token:名字按**实际用法**定,不只看亮度饱和度。
164
+
165
+ 只看 lum/sat 会把「主要用来填色的纯黑」命名成 ink(文字色)、把「只出现在渐变里的
166
+ 浅蓝」命名成 surface-alt。这里先看它在形状上主要干什么,再结合
167
+ 亮度定名;用量太少的直接不进色板。
168
+ """
169
+ cusage = cusage or {}
86
170
  pool = [c for c in d['color_freq']
87
171
  if c.get('class') == 'design' and abs((c.get('alpha') or 100) - 100) < 0.1]
88
172
  seen, rows = set(), []
@@ -92,29 +176,63 @@ def draft_colors(d):
92
176
  continue
93
177
  seen.add(h)
94
178
  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'])
179
+ u = cusage.get(h) or Counter()
180
+ tot = sum(u.values())
181
+ main = u.most_common(1)[0][0] if tot else None
182
+ rows.append({'hex': h, 'n': c['n'], 'lum': lum(rgb), 'sat': satu(rgb),
183
+ 'use': u, 'use_n': tot, 'main': main})
184
+ # 用量只用来**命名**,不作准入门槛——color_usage 只数形状级的填充/描边/文字,
185
+ # 背景 p:bg 与主题色不在其中,拿它筛会把色板砍到只剩极少数几个。
186
+ strong = sorted(rows, key=lambda r: -r['n'])
187
+
188
+ SAT_CUT, LUM_CUT = palette_cuts(rows)
97
189
 
98
190
  tokens, used = [], set()
99
191
 
100
192
  def take(pred, names):
101
193
  for name in names:
102
- for r in rows:
194
+ for r in strong:
103
195
  if r['hex'] in used or not pred(r):
104
196
  continue
105
197
  used.add(r['hex'])
106
198
  tokens.append((name, r))
107
199
  break
108
200
 
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]
201
+ def kind(r):
202
+ if r['main'] == '文字':
203
+ return 'text'
204
+ if r['main'] in ('填充', '渐变', '描边'):
205
+ return 'paint'
206
+ return 'unknown' # 形状层看不到用法,退回亮度/饱和度判断
207
+
208
+ # 墨色:主要用来写字(或看不出用法但本身是深中性色),且不是彩色
209
+ take(lambda r: r['sat'] < SAT_CUT and r['lum'] < min(LUM_CUT, LUM_MID)
210
+ and (kind(r) == 'text' or kind(r) == 'unknown'), ['ink', 'ink-muted'])
211
+ # 底色:直接取页面 background 声明里的色,按声明次数排
212
+ grounds = bg_colors(d)
213
+ for name in ('surface', 'surface-alt'):
214
+ for h in grounds:
215
+ r = next((x for x in strong if x['hex'] == h and x['hex'] not in used), None)
216
+ if r:
217
+ used.add(r['hex'])
218
+ tokens.append((name, r))
219
+ break
220
+
221
+ # 卡片/面板底:页面底色之外,真被大量当填充铺开的浅色(≥5 处才算)
222
+ take(lambda r: r['lum'] > max(LUM_CUT, 0.85) and r['sat'] < SAT_CUT
223
+ and (r['use'].get('填充') or 0) >= FILL_MANY, ['surface-raised'])
224
+ # 表达色:有彩度的按频次排
225
+ take(lambda r: r['sat'] >= SAT_CUT, ['primary', 'accent', 'accent-2', 'accent-3'])
226
+ # 其余低饱和色一律 neutral-N——它到底是卡片底、分隔线还是描边,数据分不出来,
227
+ # 就不要用名字去替消费方下结论;真实用法写在 Colors 表的用途列里。
228
+ take(lambda r: r['sat'] < SAT_CUT, ['neutral', 'neutral-2', 'neutral-3'])
229
+ spare = [r for r in rows if r['hex'] not in used]
230
+ note_truncation('设计色', 6, len(spare), '色板只收主要色,其余在联系表里看')
231
+ rest = spare[:6]
115
232
  return tokens, rest, rows
116
233
 
117
234
 
235
+
118
236
  # ---------------------------------------------------------------- 字体
119
237
  def parse_fallback_table():
120
238
  path = os.path.join(SKILL_ROOT, 'font-fallback.yaml')
@@ -142,6 +260,48 @@ def norm(s):
142
260
  return re.sub(r'[\s\-_]', '', s or '').lower()
143
261
 
144
262
 
263
+ OFFICE_DEFAULT_FONTS_NORM = {norm(x) for x in OFFICE_DEFAULT_FONTS}
264
+
265
+
266
+ def cover_slot_colors(tokens, archetypes, rows, cusage):
267
+ """slot 里出现的每个色值都必须在色板里有名字。
268
+
269
+ Hard Rules 写「颜色只用 colors 里的 token」,而 slot 的 color 是从模板直读的,
270
+ 两者不对齐就等于产物自己违反自己的规则——slot 的色值直读自模板,未必都已进
271
+ 色板。这里把缺的补进色板,按用法归族命名。
272
+ """
273
+ have = {r['hex'].upper() for _, r in tokens}
274
+ by_hex = {r['hex'].upper(): r for r in rows}
275
+ sat_cut, lum_cut = palette_cuts(rows) # 与 draft_colors 同一套切点,别各切各的
276
+ used = [n for n, _ in tokens]
277
+
278
+ def nxt(fam):
279
+ if fam not in used:
280
+ return fam
281
+ i = 2
282
+ while '%s-%d' % (fam, i) in used:
283
+ i += 1
284
+ return '%s-%d' % (fam, i)
285
+
286
+ added = []
287
+ for a in archetypes:
288
+ for s in a['slots']:
289
+ h = (s.get('color') or '').upper()
290
+ if not h.startswith('#') or h in have:
291
+ continue
292
+ have.add(h)
293
+ r = by_hex.get(h)
294
+ if r is None: # 普查里没有这个色(理论上不该发生),跳过不编造
295
+ continue
296
+ fam = ('ink' if r['sat'] < sat_cut and r['lum'] < min(lum_cut, LUM_MID)
297
+ else 'accent' if r['sat'] >= sat_cut else 'neutral')
298
+ name = nxt(fam)
299
+ used.append(name)
300
+ tokens.append((name, r))
301
+ added.append((name, h))
302
+ return added
303
+
304
+
145
305
  def draft_fonts(d):
146
306
  table = parse_fallback_table()
147
307
  groups = defaultdict(lambda: {'rendered': 0, 'weights': set(), 'names': set(), 'bold': 0})
@@ -167,6 +327,7 @@ def draft_fonts(d):
167
327
  return None
168
328
 
169
329
  out = []
330
+ note_truncation('字族', 4, len(ranked), '只报渲染量最大的几族')
170
331
  for key, g in ranked[:4]:
171
332
  fam = resolve(sorted(g['names'], key=len))
172
333
  stack = [sorted(g['names'], key=len)[0]]
@@ -201,35 +362,192 @@ def import_line(fonts):
201
362
  return "@import url('%s?%s&display=swap');" % (MIRROR, fam), webs
202
363
 
203
364
 
365
+ def quant(hit, total):
366
+ """覆盖率决定量词——不到一半就不许说「一律/每页」。"""
367
+ if not total:
368
+ return None
369
+ r = hit / float(total)
370
+ if r >= 0.9:
371
+ return '一律'
372
+ if r >= 0.5:
373
+ return '多数'
374
+ return None
375
+
376
+
377
+ def color_usage(shapes, d=None):
378
+ """每个色值在形状上的真实用法计数:填充 / 渐变 / 描边 / 文字。
379
+
380
+ 用途列不能靠预设字典猜——同一个色在不同模板里的主用途完全不同。这里从 shapes
381
+ 直接数,数不到就如实说数不到。
382
+ """
383
+ def hx(c):
384
+ return (c.get('hex') or '').upper() if isinstance(c, dict) else ''
385
+
386
+ def walk_text_colors(node, out):
387
+ """文本样式可能嵌在 lstStyle.lvlNpPr / defRPr / rPr 任一层——通用遍历,
388
+ 别逐层枚举(枚举漏过 lvl2pPr,导致主色被写成「用途待确认」)。"""
389
+ if isinstance(node, dict):
390
+ if isinstance(node.get('color'), dict) and hx(node['color']):
391
+ out.append(hx(node['color']))
392
+ for v in node.values():
393
+ walk_text_colors(v, out)
394
+ elif isinstance(node, list):
395
+ for v in node:
396
+ walk_text_colors(v, out)
397
+
398
+ use = defaultdict(Counter)
399
+ for s in shapes:
400
+ f = s.get('fill') or {}
401
+ if f.get('type') == 'solid' and hx(f.get('color')):
402
+ use[hx(f['color'])]['填充'] += 1
403
+ for st in (f.get('stops') or []):
404
+ if hx(st.get('color')):
405
+ use[hx(st['color'])]['渐变'] += 1
406
+ ln = s.get('line') or {}
407
+ if hx(ln.get('color')):
408
+ use[hx(ln['color'])]['描边'] += 1
409
+ cols = []
410
+ walk_text_colors(s.get('text') or {}, cols)
411
+ for h in cols:
412
+ use[h]['文字'] += 1
413
+ for h in bg_colors(d or {}):
414
+ use[h]['页面背景'] += 1
415
+ # 主题 clrScheme:这类色常常只在主题里声明、页面上由 schemeClr 间接引用,
416
+ # 不记上就会在用途列写「未落在形状上」,看着像没人用。
417
+ for th in ((d or {}).get('themes') or []):
418
+ if not th.get('picked'):
419
+ continue
420
+ for slot, hexv in (th.get('clrScheme') or {}).items():
421
+ if isinstance(hexv, str) and hexv.startswith('#'):
422
+ use[hexv.upper()]['主题 ' + slot] += 1
423
+ return use
424
+
425
+
426
+ def usage_phrase(counter):
427
+ """把用法计数写成一句话;主用法占六成以上就直接点名,否则并列前三。"""
428
+ if not counter:
429
+ return '普查里有声明,但未落在形状/背景/主题色上——用途待确认'
430
+ items = counter.most_common()
431
+ tot = sum(counter.values())
432
+ if items[0][1] >= tot * 0.6:
433
+ return '主要作%s(%d/%d 处)' % (items[0][0], items[0][1], tot)
434
+ return '、'.join('%s %d 处' % (k, v) for k, v in items[:3])
435
+
436
+
204
437
  def draft_anchors(d, tokens, fonts, roles, assets, archetypes):
205
- names = [t[0] for t in tokens]
438
+ """anchors 只报测到的数,不下「这套风格是什么」的结论。
439
+
440
+ 这一段在 design.md 里读起来像「设计总纲」,消费端会照它建全局样式。脚本写进去的
441
+ 每一句解读都会被当成规则执行——实测把 1/8 覆盖率的 logo 描述成「跨页不动」,
442
+ 消费端就建了全局 CSS 类,12 页全铺了 logo。所以这里只给覆盖率和计数,
443
+ 「这是不是这套风格的特征」由看得到图的人判断。
444
+ """
445
+ A = []
446
+ n_arch = len(archetypes) or 1
447
+
448
+ # 1. 表达色:未取用的高频彩色要如实带上,不能说「其余全是中性」
449
+ names = [x[0] for x in tokens]
206
450
  chroma = [n for n in names if n.startswith(('primary', 'accent'))]
451
+ if chroma:
452
+ A.append((chroma[0] + '-led-palette', 'token',
453
+ '有彩色 token 共 %d 个,用量最大的是 %s'
454
+ % (len(chroma), '、'.join(chroma[:3]))))
455
+
456
+ # 2. 圆角:按普查占比
207
457
  radii = d.get('radii_census') or []
208
458
  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 {}
459
+ tot_r = sum(r['n'] for r in radii) or 1
460
+ if zero:
461
+ q0 = quant(zero['n'], tot_r)
462
+ if q0:
463
+ A.append(('zero-radius', 'token',
464
+ '圆角量为零的形状占 %d%%(普查 %d 个带圆角声明的形状)'
465
+ % (round(100.0 * zero['n'] / tot_r), tot_r)))
466
+
467
+ # 3. 满屏底图:按有背景的页型占比
468
+ with_bg = sum(1 for a in archetypes if a.get('bg'))
469
+ qb = quant(with_bg, n_arch)
470
+ if qb:
471
+ A.append(('full-bleed-ground', 'pattern',
472
+ '%d/%d 个页型声明了整幅铺满的底图' % (with_bg, n_arch)))
473
+
474
+ # 4. 标识:位置是不是真的固定,看有几个不同的 box
475
+ logo_slots = [s for a in archetypes for s in a['slots']
476
+ if str(s.get('asset') or '').startswith(('logo', 'slogan'))]
477
+ logo_arch = sum(1 for a in archetypes
478
+ if any(str(s.get('asset') or '').startswith(('logo', 'slogan'))
479
+ for s in a['slots']))
480
+ boxes = {tuple(s['box']) for s in logo_slots}
481
+ # anchors 是「这套风格的定义性特征」,消费端读它来建全局样式。只在少数页型出现的
482
+ # 东西写进来,等于宣布它是全局元素——实测某模板 logo 只在 1/8 个页型上,anchor 仍
483
+ # 写成「跨页不动」,消费端据此建了个全局 CSS 类,12 页全铺了 logo。
484
+ # 所以这里和其他 anchor 用同一把尺:覆盖率不过半就不进 anchors。
485
+ ql = quant(logo_arch, n_arch)
486
+ if logo_arch and len(boxes) == 1 and ql:
487
+ A.append(('corner-locked-logo', 'component',
488
+ '品牌标识出现在 %d/%d 个页型上,这些页型里它的 box 完全一致'
489
+ % (logo_arch, n_arch)))
490
+ elif len(boxes) > 1:
491
+ A.append(('logo-moves-by-archetype', 'component',
492
+ '品牌标识按页型换位换尺寸(共 %d 种摆法),必须按 layouts 里该页型的 box 放,'
493
+ '不能沿用上一页' % len(boxes)))
494
+
495
+ # 5. 渐变:按普查计数
496
+ if (d.get('geom_census') or {}).get('gradient_fills'):
497
+ A.append(('gradient-accent', 'pattern',
498
+ '全档共 %d 处渐变填充' % (d['geom_census']['gradient_fills'])))
499
+
500
+ # 6. 层级:字号跨度 + 字重是否单一(字重真单一才敢说「不靠字重」)
501
+ disp, body = roles.get('display'), roles.get('body')
502
+ if disp and body and disp['sz_px'] > body['sz_px']:
503
+ ws = {s.get('weight') for a in archetypes for s in a['slots'] if s.get('weight')}
504
+ tail = (',字重只用 %s 一档' % list(ws)[0]) if len(ws) == 1 else ''
505
+ A.append(('size-driven-hierarchy', 'pattern',
506
+ '最大字号档与正文档相差 %.1f 倍(见 typography)%s'
507
+ % (disp['sz_px'] / body['sz_px'], tail)))
508
+
509
+ # 7. 阴影:只在描边极少时才敢说「不用描边分隔」
211
510
  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
511
  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', '正文一律落在统一安全区内,不贴画布边'))
512
+ A.append(('soft-shadow-card', 'component',
513
+ '全档 %d outerShdw 外阴影' % eff['outerShdw']))
514
+
515
+ # 8. 双字族:只陈述分工存在,不断言「同一行混排」(普查没采集混排)
516
+ tot_r_font = sum(f['rendered'] for f in fonts) or 1
517
+ if len(fonts) >= 2 and fonts[1]['rendered']:
518
+ A.append(('dual-family-typesetting', 'token',
519
+ '用了两套字族:%s 渲染 %d 处、%s 渲染 %d 处'
520
+ % (fonts[0]['names'][0], fonts[0]['rendered'],
521
+ fonts[1]['names'][0], fonts[1]['rendered'])))
522
+
523
+ # 9. 安全区:只在各页型正文左边界真的收敛时才写
524
+ # 「多宽算正文槽」按本包自己的槽宽分布定:固定 px 门槛在窄版心模板上会一个都不剩
525
+ widths = sorted(s['box'][2] for a in archetypes for s in a['slots'] if not s.get('asset'))
526
+ w_cut = widths[len(widths) // 2] if widths else 0
527
+ lefts = [s['box'][0] for a in archetypes for s in a['slots']
528
+ if not s.get('asset') and s['box'][2] >= w_cut]
529
+ if len(lefts) >= 4:
530
+ common = Counter(lefts).most_common(1)[0]
531
+ qs = quant(common[1], len(lefts))
532
+ if qs:
533
+ A.append(('shared-left-margin', 'token',
534
+ '%d/%d 个正文槽的左边界落在同一个 x 上(坐标见 layouts)'
535
+ % (common[1], len(lefts))))
536
+
537
+ # 10. 双主题:直读事实
538
+ themes = (d.get('theme_topology') or {}).get('themes') or []
539
+ if len(themes) > 1:
540
+ A.append(('dual-theme-masters', 'token',
541
+ '模板声明了 %s 两套主题母版' % ' / '.join(themes)))
542
+
543
+ # 11. 画布:直读事实(兜底凑数也只用真事实)
544
+ cv = d['canvas']['px']
545
+ A.append(('fixed-canvas', 'token',
546
+ '画布 %d×%d,layouts 里的坐标都是这张画布上的绝对像素' % (cv[0], cv[1])))
547
+ if len(archetypes) >= 3:
548
+ A.append(('archetype-catalog', 'pattern',
549
+ '归纳出 %d 种页型' % len(archetypes)))
550
+
233
551
  seen, out = set(), []
234
552
  for a in A:
235
553
  if a[0] in seen:
@@ -238,8 +556,6 @@ def draft_anchors(d, tokens, fonts, roles, assets, archetypes):
238
556
  out.append(a)
239
557
  return out[:8]
240
558
 
241
-
242
- # ---------------------------------------------------------------- 字号轴
243
559
  def draft_scale(d, archetypes=()):
244
560
  ts = [t for t in d['text_scale'] if t['sz_px'] >= 10]
245
561
  ts.sort(key=lambda t: -t['sz_px'])
@@ -251,8 +567,9 @@ def draft_scale(d, archetypes=()):
251
567
  display = by_px.get(max(title_sz)) if title_sz else None
252
568
  big = [t for t in ts if t['n'] >= 2] or ts
253
569
  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]
570
+ # 正文档 = 渲染次数最多的那一档。不设「多大算正文」的上限:大字号排版的模板
571
+ # 正文本来就可能比别的模板的标题还大,预设上限会把它整档判错。
572
+ body = max([t for t in ts if t is not display] or ts, key=lambda t: t['n'])
256
573
  heading_pool = [t for t in ts if body['sz_px'] * 1.3 <= t['sz_px'] < display['sz_px']]
257
574
  heading = max(heading_pool, key=lambda t: t['n']) if heading_pool else None
258
575
  small_pool = [t for t in ts if t['sz_px'] < body['sz_px']]
@@ -296,6 +613,53 @@ def probe_image(path):
296
613
  return info
297
614
 
298
615
 
616
+ def bg_busy_map(path, canvas, cells=12):
617
+ """把背景图切成网格,报每格的**局部对比度**(该格内亮度极差)。
618
+
619
+ 「哪里不能压文字」的本质是「哪里花」。整幅渐变的底图各格对比度都低,说明没有
620
+ 视觉主体;有山峰、人物、产品图的底图会在主体处出现明显更高的对比度。这里只出
621
+ 客观数值和一个据此推出的草案,最终由看得到图的人定。
622
+ """
623
+ try:
624
+ from PIL import Image
625
+ except Exception:
626
+ return None
627
+ try:
628
+ im = Image.open(path).convert('L').resize((cells * 8, cells * 8))
629
+ except Exception:
630
+ return None
631
+ px = im.load()
632
+ grid = []
633
+ for gy in range(cells):
634
+ row = []
635
+ for gx in range(cells):
636
+ vals = [px[gx * 8 + x, gy * 8 + y] for y in range(8) for x in range(8)]
637
+ row.append(max(vals) - min(vals))
638
+ grid.append(row)
639
+ flat = sorted(v for row in grid for v in row)
640
+ if not flat:
641
+ return None
642
+ med = flat[len(flat) // 2]
643
+ hi = flat[int(len(flat) * 0.9)]
644
+ # 主体 = 对比度显著高于全图中位数的连片格子。阈值取「中位数与九分位的中点」,
645
+ # 由本图自己的分布定,不用固定值。
646
+ cut = (med + hi) / 2.0
647
+ cW, cH = canvas
648
+ hot = [(gx, gy) for gy in range(cells) for gx in range(cells) if grid[gy][gx] > cut]
649
+ if not hot:
650
+ return {'busy': None, 'median': med, 'p90': hi, 'why': '各处对比度一致,没有更花的区域'}
651
+ xs = [g[0] for g in hot]
652
+ ys = [g[1] for g in hot]
653
+ span = ((max(xs) - min(xs) + 1) * (max(ys) - min(ys) + 1)) / float(cells * cells)
654
+ if span > 0.5:
655
+ # 热格散落全图,外接矩形几乎覆盖整幅——圈出来等于没圈
656
+ return {'busy': None, 'median': med, 'p90': hi, 'why': '较花的格子散布全图,圈不出单一主体'}
657
+ box = [round(min(xs) * cW / cells), round(min(ys) * cH / cells),
658
+ round((max(xs) - min(xs) + 1) * cW / cells),
659
+ round((max(ys) - min(ys) + 1) * cH / cells)]
660
+ return {'busy': box, 'median': med, 'p90': hi, 'span': round(span, 2)}
661
+
662
+
299
663
  def copy_logo_candidates(outdir, logo_pool):
300
664
  if not logo_pool:
301
665
  return []
@@ -347,6 +711,7 @@ def draft_assets(d, outdir, bg_needed=(), cover_media=None, bg_under=None):
347
711
  cands.append({
348
712
  'media': m['media'], 'file': os.path.basename(out_rel), 'out': out_rel,
349
713
  'bytes': m.get('bytes'), 'n': img.get('n', m.get('used_n', 0)),
714
+ 'has_compressed': bool(m.get('compressed_out')),
350
715
  'fullscreen': bool(img.get('fullscreen')), 'w_pct': img.get('max_w_pct', 0),
351
716
  'box': top.get('box') or {}, 'slides': slides,
352
717
  'layer_only': bool(parts) and not slides,
@@ -362,35 +727,58 @@ def draft_assets(d, outdir, bg_needed=(), cover_media=None, bg_under=None):
362
727
  if k not in best_of or c['n'] > best_of[k]['n']:
363
728
  best_of[k] = c
364
729
  kept = sorted(best_of.values(), key=lambda c: (-c['n'], -(c['bytes'] or 0)))
730
+ # 被同簇兄弟淘汰的 media 仍要能指到胜出者——封面底图常常是簇里 n 最小的那张
731
+ alias = {}
732
+ for c in cands:
733
+ w = best_of.get(c['cluster'] or c['media'])
734
+ if w and w['media'] != c['media']:
735
+ alias[c['media']] = w['media']
736
+ cover_media = alias.get(cover_media, cover_media)
737
+ bg_needed = {alias.get(m, m) for m in (bg_needed or ())}
365
738
 
366
739
  assets, rejected, todos = [], [], []
740
+ over_cap_bgs = []
367
741
  logo_pool = []
368
742
  bg_under = bg_under or {}
369
743
  bg_i = 0
370
- canvas_w = d['canvas']['px'][0]
744
+ canvas_w, canvas_h = d['canvas']['px']
371
745
  for c in kept:
372
746
  if c['probe'].get('near_blank'):
373
747
  rejected.append((c, '近全透明(alpha 均值 %.0f/255),PPT 里看不见' % c['probe']['alpha_mean']))
374
748
  continue
749
+ # 铺满 ≠ 能当背景。背景的定义性属性是**遮盖**:它得挡住底下的东西。一张大半透明
750
+ # 的图铺满整页也遮不住任何像素,它在 PPT 里是叠在幻灯片底色上的一层装饰(顶部
751
+ # 光晕之类),底色才是真背景。实测某模板一张 alpha 均值 30/255、72% 完全透明的
752
+ # 顶部光晕被当成满屏背景收进包,消费端每页铺它,顶部就多出一条原稿没有的浓色带。
753
+ am = c['probe'].get('alpha_mean')
754
+ if c['fullscreen'] and am is not None and am < OPAQUE_ENOUGH:
755
+ rejected.append((c, 'alpha 均值只有 %.0f/255,遮不住底下的东西——'
756
+ '它是叠在底色上的装饰层,不是背景' % am))
757
+ continue
375
758
  if c['fullscreen']:
376
759
  if c['media'] == cover_media:
377
760
  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:
761
+ 'src': c,
762
+ # 只有真出了压缩版才能带原图;否则 path/full 指向同一
763
+ # 文件,package.py 必 FAIL(封面不需要转码时就会踩到)
764
+ 'use_full': c['has_compressed']})
765
+ elif c['media'] in bg_needed and bg_i < BG_CONTENT_CAP:
380
766
  bg_i += 1
381
767
  assets.append({'id': 'bg-content-%d' % bg_i, 'kind': 'background',
382
768
  'role': 'content', 'src': c, 'use_full': False})
769
+ elif c['media'] in bg_needed:
770
+ over_cap_bgs.append(c)
771
+ rejected.append((c, '有页型以它为主底,但内容页背景已收满 %d 张' % BG_CONTENT_CAP))
383
772
  else:
384
773
  rejected.append((c, '满屏图但没有页面以它为主底(只在版式层备用)'))
385
- elif c['w_pct'] < 30 and c['n'] >= 2:
774
+ elif c['w_pct'] < SMALL_IMG_W_PCT and c['n'] >= REPEAT_MIN:
775
+ # 品牌标识的共性是「小、重复出现、贴角」。这里只按贴角程度排序给出首选,
776
+ # 不设及格线——「多少分算 logo」没有客观依据,判断交 L 层,分项证据随 TODO 给出。
386
777
  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))
778
+ edge_x = min(b.get('x', 0), max(canvas_w - (b.get('x', 0) + (b.get('w') or 0)), 0))
779
+ edge_y = min(b.get('y', 0), max(canvas_h - (b.get('y', 0) + (b.get('h') or 0)), 0))
780
+ corner = (edge_x / canvas_w) + (edge_y / canvas_h) # 越小越贴角
781
+ logo_pool.append((corner, c))
394
782
  else:
395
783
  rejected.append((c, '内容区图片(占宽 %.0f%%,出现 %d 次)' % (c['w_pct'], c['n'])))
396
784
 
@@ -404,42 +792,402 @@ def draft_assets(d, outdir, bg_needed=(), cover_media=None, bg_under=None):
404
792
  from PIL import Image
405
793
  im = Image.open(os.path.join(outdir, row['out'])).convert('RGB')
406
794
  b = c['box']
407
- sx, sy = im.width / float(canvas_w), im.height / float(d['canvas']['px'][1])
795
+ sx, sy = im.width / float(canvas_w), im.height / float(canvas_h)
408
796
  crop = im.crop((int(b.get('x', 0) * sx), int(b.get('y', 0) * sy),
409
797
  max(int((b.get('x', 0) + b.get('w', 1)) * sx), 1),
410
798
  max(int((b.get('y', 0) + b.get('h', 1)) * sy), 1))).resize((16, 16))
411
799
  raw = crop.tobytes()
412
800
  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'
801
+ return 'light' if sum(lum(p) for p in px) / len(px) > LUM_MID else 'dark'
414
802
  except Exception:
415
803
  return None
416
804
 
417
- logo_pool.sort(key=lambda kv: (-kv[0], -kv[1]['n']))
418
- for i, (score, c) in enumerate(logo_pool):
805
+ # 贴角是品牌标识的定义性特征:离两边都超过画布 1/4 的重复小图,更可能是页内装饰。
806
+ # 这不是「多少分算 logo」那种凑出来的分数线——它直接来自「贴角」这个判据本身。
807
+ LOGO_CORNER_MAX = 0.5 # edge_x/W + edge_y/H,两边各 25% 即到上限
808
+ logo_pool.sort(key=lambda kv: (kv[0], -kv[1]['n']))
809
+ if logo_pool and logo_pool[0][0] > LOGO_CORNER_MAX:
810
+ todos.append('没有贴角的重复小图(最接近的一张离画布边 %.0f%%),本模板可能没有 logo;'
811
+ '确认后要么从联系表挑一张补进 manifest,要么在 gaps 写明模板无品牌标识'
812
+ % (logo_pool[0][0] * 50))
813
+ logo_pool = []
814
+ for i, (corner, c) in enumerate(logo_pool):
419
815
  b = c['box']
420
- if i == 0 and score >= 5:
816
+ if i == 0:
421
817
  assets.append({'id': 'logo-primary', 'kind': 'logo', 'role': None, 'src': c,
422
818
  'use_full': False, 'on_bg': on_bg_of(c)})
423
- todos.append('看联系表确认 `%s`(%.0fx%.0f @ %.0f,%.0f,出现 %d 次)真是品牌 logo;'
819
+ todos.append('看联系表确认 `%s` 真是品牌 logo(%.0fx%.0f @ %.0f,%.0f,出现 %d 次,'
820
+ '离画布边 %.0f%%,是所有小图里最贴角的一张);'
424
821
  '不是就把 manifest 的 logo-primary 换成别的候选或整条删掉'
425
- % (c['file'], b.get('w', 0), b.get('h', 0), b.get('x', 0), b.get('y', 0), c['n']))
822
+ % (c['file'], b.get('w', 0), b.get('h', 0), b.get('x', 0), b.get('y', 0),
823
+ c['n'], corner * 50))
824
+ else:
825
+ rejected.append((c, '重复小图(%.0fx%.0f @ %.0f,%.0f),贴角程度 %.0f%% 不如首选'
826
+ % (b.get('w', 0), b.get('h', 0), b.get('x', 0), b.get('y', 0),
827
+ corner * 50)))
828
+
829
+ # 体量预算:包内资产总量超 20MB 直接 FAIL(V2-6)。`use_full` 的原图是唯一可能
830
+ # 单张爆预算的东西(未压缩的封面级大图可以单张达到数十 MB),所以在草案期就先丢 full,
831
+ # 不要留给 L 层去撞门禁再回修。
832
+ PACK_BUDGET = 20 * 1024 * 1024
833
+ est = sum(min(a['src'].get('bytes') or 0, ASSET_WARN_SINGLE) for a in assets)
834
+ for a in sorted([x for x in assets if x['use_full']],
835
+ key=lambda x: -(x['src'].get('bytes') or 0)):
836
+ orig = a['src'].get('bytes') or 0
837
+ if est + orig > PACK_BUDGET * 0.9:
838
+ a['use_full'] = False
839
+ todos.append('`%s` 的原图 %.1fMB 会把包撑过 20MB 上限,草案已只保留压缩版;'
840
+ '确实需要原图就改走 url 承载' % (a['id'], orig / 1024.0 / 1024))
426
841
  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))))
842
+ est += orig
429
843
 
844
+ if over_cap_bgs:
845
+ todos.append('模板有 %d 张内容页背景超出 %d 张上限(%s);用到它们的页型在 layouts.md 里'
846
+ '不会有 background,需要就手工补进 manifest 并删掉不重要的那几张'
847
+ % (len(over_cap_bgs), BG_CONTENT_CAP,
848
+ '、'.join(c['file'] for c in over_cap_bgs[:5])))
430
849
  if not any(a['role'] == 'cover' for a in assets):
431
850
  todos.append('没定出封面底图——从联系表挑一张补进 manifest(role: cover),或在 gaps 写明模板无封面主视觉')
432
851
  copy_logo_candidates(outdir, logo_pool)
433
- return assets, rejected, todos
852
+ return assets, rejected, todos, alias, {c['media']: c for c in kept}
434
853
 
435
854
 
436
855
  # ---------------------------------------------------------------- 版式聚类
437
856
  DECOR_MIN = 40.0
438
857
 
858
+ # 版式名 → role(模板自己按页型命名时直接用它,别再猜)。
859
+ # 英文词按整词匹配:裸子串会让短词吃掉长词——`end` 一度把 `agenda`、`Appendix`、
860
+ # `Trends Section` 全判成 closing,表里 `agenda -> section` 那条永远轮不到。
861
+ ROLE_BY_WORD = [('封面', 'cover'), ('cover', 'cover'), ('首页', 'cover'),
862
+ ('title slide', 'cover'), ('标题幻灯片', 'cover'),
863
+ ('封底', 'closing'), ('尾页', 'closing'), ('结束', 'closing'),
864
+ ('致谢', 'closing'), ('谢谢', 'closing'), ('end', 'closing'),
865
+ ('thank you', 'closing'), ('closing', 'closing'),
866
+ ('章节', 'section'), ('目录', 'section'), ('过渡', 'section'),
867
+ ('section', 'section'), ('agenda', 'section'),
868
+ ('section header', 'section'), ('节标题', 'section'),
869
+ ('金句', 'quote'), ('问句', 'quote'), ('引言', 'quote'), ('quote', 'quote'),
870
+ ('空白', 'blank'), ('blank', 'blank')]
871
+ PH_TO_TYPE = {'title': 'title', 'ctrTitle': 'title', 'subTitle': 'subtitle',
872
+ 'body': 'body', 'pic': 'pic', 'clipArt': 'pic', 'tbl': 'table',
873
+ 'chart': 'chart', 'media': 'media', 'dgm': 'pic',
874
+ 'sldNum': 'slide-number', 'ftr': 'footer', 'dt': 'footer'}
875
+
876
+
877
+ def role_of_name(name):
878
+ """版式名 → role。认不出返回 None,由调用方降置信度并留 TODO——不要静默当 content。
879
+
880
+ 词表只覆盖中英文;换一种语言命名的模板会整份认不出。那时全落 content 且机检照过,
881
+ 消费端拿到的是「每一页都是内容页」,封面/章节/结束页的语义整个丢掉且无处可查。
882
+ """
883
+ low = (name or '').lower()
884
+ for word, role in ROLE_BY_WORD:
885
+ if word.isascii():
886
+ if re.search(r'(?<![a-z])%s(?![a-z])' % re.escape(word), low):
887
+ return role
888
+ elif word in low:
889
+ return role
890
+ return None
891
+
892
+
893
+ def clean_layout_name(name):
894
+ """`1_内容-左右排版(无副标题)` → `内容-左右排版(无副标题)`。"""
895
+ return re.sub(r'^\d+[_\-\s]*', '', (name or '').strip()) or '未命名版式'
896
+
897
+
898
+ def is_bleed(s):
899
+ return (s.get('kind') == 'pic' and (s.get('w_pct') or 0) >= 95
900
+ and (s.get('h_pct') or 0) >= 95)
901
+
902
+
903
+ def top_bleed_media(shapes):
904
+ """一串形状里最上层的满屏图。
905
+
906
+ OOXML 的 spTree 是绘制序,靠后的画在上面。一个版式常叠两张满屏图——通用底纹在
907
+ 下、这一页的主视觉在上——所以看得见的是最后那张。取第一张会拿到底纹,实测让
908
+ 章节页的深蓝主视觉被换成了另一张鲜蓝底纹,成品与原稿完全不是一个颜色。
909
+ """
910
+ out = None
911
+ for s in shapes:
912
+ if is_bleed(s) and s.get('media'):
913
+ out = s['media']
914
+ return out
915
+
916
+
917
+ def slot_overlaps(slots):
918
+ """同一页型里坐标互相重叠的槽对。只报事实,不改坐标——坐标是从模板量的。"""
919
+ out = []
920
+ for i in range(len(slots)):
921
+ for j in range(i + 1, len(slots)):
922
+ a, b = slots[i].get('box'), slots[j].get('box')
923
+ if not (a and b):
924
+ continue
925
+ ox = min(a[0] + a[2], b[0] + b[2]) - max(a[0], b[0])
926
+ oy = min(a[1] + a[3], b[1] + b[3]) - max(a[1], b[1])
927
+ if ox > 0 and oy > 0:
928
+ out.append('%s×%s 叠 %dx%d' % (slots[i].get('role'), slots[j].get('role'),
929
+ round(ox), round(oy)))
930
+ return out
931
+
932
+
933
+ def slot_style(s):
934
+ """占位符自带的排版样式——字号/色值/对齐/字重都是直读,不给消费端留编的空间。
935
+
936
+ 样式可能在三层:lstStyle.lvl1pPr(版式占位符常用)、段落 defRPr(Mac Office
937
+ 导出把大量属性写在这一层)、段落 pPr(对齐)。逐层兜底,缺一层就往下取。
938
+ """
939
+ txt = s.get('text') or {}
940
+ ls = dict((txt.get('lstStyle') or {}).get('lvl1pPr') or {})
941
+ # 四层逐级兜底,按 OOXML 的就近原则:run rPr → 段落 defRPr → 段落 pPr → lstStyle。
942
+ # 只枚举前几层会整份漏掉——有的导出器把字号全写在 run rPr 上,lstStyle 一个都没有。
943
+ for para in (txt.get('paragraphs') or []):
944
+ srcs = [r.get('rPr') or {} for r in (para.get('runs') or [])]
945
+ srcs.append(para.get('defRPr') or {})
946
+ srcs.append({k: v for k, v in para.items() if k not in ('runs', 'defRPr')})
947
+ for src in srcs:
948
+ for k, v in (src or {}).items():
949
+ if v is not None:
950
+ ls.setdefault(k, v)
951
+ if ls.get('sz_px'):
952
+ break
953
+ if not ls.get('sz_px'):
954
+ # 仍无声明:退到整形状里出现过的最大字号(generic walk),仍是文件里的值
955
+ anysz = shape_sz(s)
956
+ if anysz:
957
+ ls['sz_px'] = anysz
958
+ out = {}
959
+ if ls.get('sz_px'):
960
+ out['size'] = round(ls['sz_px'])
961
+ col = (ls.get('color') or {}).get('resolved')
962
+ if col:
963
+ out['color'] = col
964
+ else:
965
+ # 占位符的字色也可以是 gradFill(章节页的大号序号常这么做)。解析层已经把
966
+ # stops 和角度记全了,这里只取单色就会整条丢掉,消费端只能自己编一个平色。
967
+ # 与 decor 同一约定:css 是可直接写进 style 的声明串。
968
+ f = ls.get('fill') or {}
969
+ if f.get('type') == 'gradient':
970
+ g = _load_query()._css_gradient(f)
971
+ if g:
972
+ out['css'] = ('background-image: %s; -webkit-background-clip: text; '
973
+ 'background-clip: text; color: transparent' % g)
974
+ if ls.get('weight'):
975
+ out['weight'] = ls['weight']
976
+ elif ls.get('bold'):
977
+ out['weight'] = 700
978
+ if ls.get('algn') and ls['algn'] not in ('l', 'just'):
979
+ out['align'] = {'ctr': 'center', 'r': 'right'}.get(ls['algn'], ls['algn'])
980
+ anchor = ((s.get('text') or {}).get('bodyPr') or {}).get('anchor')
981
+ if anchor in ('ctr', 'b'):
982
+ out['valign'] = {'ctr': 'middle', 'b': 'bottom'}[anchor]
983
+ return out
984
+
985
+
986
+ def instance_override(shapes, slide_part, slots, bgm, cW, cH, composites=None):
987
+ """实例页覆盖版式:版式是骨架,实例页才是设计师最终摆定的样子。
988
+
989
+ 版式底图常是多个版式共用的通用底纹,实例页可能另铺主视觉大图;标题占位符的框高
990
+ 也常被实例页放大以容纳多行。只读版式的包会让消费端拿到错的底图和装不下字的框,
991
+ 只能自己缩字号。
992
+ """
993
+ ins = [s for s in shapes if s.get('part') == slide_part]
994
+ if not ins:
995
+ return slots, bgm
996
+ bgm = (composites or {}).get(slide_part) or top_bleed_media(ins) or bgm
997
+ texts = []
998
+ for s in ins:
999
+ b = s.get('box') or {}
1000
+ if not (b.get('w') and b.get('h')) or not shape_text(s):
1001
+ continue
1002
+ texts.append({'sz': shape_sz(s), 'box': b, 'style': slot_style(s)})
1003
+ texts.sort(key=lambda x: -x['sz'])
1004
+ # 按字号大小依次顶替版式的文字槽(版式槽已按 y 排过,字号序更贴合语义层级)
1005
+ tslots = [s for s in slots if s['type'] != 'pic']
1006
+ for slot, ins_t in zip(sorted(tslots, key=lambda s: -(s.get('sz') or 0)), texts):
1007
+ b = ins_t['box']
1008
+ slot['box'] = [round(b.get('x', 0)), round(b.get('y', 0)),
1009
+ round(b.get('w', 0)), round(b.get('h', 0))]
1010
+ slot['sz'] = ins_t['sz']
1011
+ slot.update(ins_t['style'] or {})
1012
+ return slots, bgm
1013
+
1014
+
1015
+ def layouts_from_template(d, shapes, cW, cH):
1016
+ """form=3:模板自己用 slideLayout 声明了页型,直接读版式层。
1017
+
1018
+ 拿样张聚类只能得到「样张数」个 archetype——模板往往只放 1-2 张样张,
1019
+ 真正的页型全在版式里。模板常见只放个位数样张却声明几十个语义版式,按样张聚类
1020
+ 只能得到「样张数」个 archetype,消费端搭页时大半无版式可抄,只能自己编。
1021
+ """
1022
+ by_part = defaultdict(list)
1023
+ for s in shapes:
1024
+ if s.get('layer') == 'layout' and s.get('ph'):
1025
+ by_part[s['part']].append(s)
1026
+ bg_of_layout = {}
1027
+ composites = d.get('background_composites') or {}
1028
+ for s in shapes:
1029
+ if s.get('layer') == 'layout' and is_bleed(s) and s.get('media'):
1030
+ bg_of_layout[s['part']] = s['media'] # 靠后者在上层,最后一张才是看得见的
1031
+ topo = d.get('theme_topology') or {}
1032
+ theme_of_master = {m['master']: m.get('theme_label')
1033
+ for m in (topo.get('per_master') or [])}
1034
+ master_of = (d.get('reference_graph') or {}).get('master_of_layout') or {}
1035
+ # 只在版式恰好被 1 张实例页使用时才拿实例覆盖:多张实例共用一个版式时,
1036
+ # 谁都不代表版式本身,硬挑一张会把别页的构图当成页型
1037
+ lay_of_slide = (d.get('reference_graph') or {}).get('layout_of_slide') or {}
1038
+ used_n = Counter(lay_of_slide.values())
1039
+ slide_of_layout = {lp: sp for sp, lp in lay_of_slide.items() if used_n[lp] == 1}
1040
+ default_theme = topo.get('default')
1041
+ multi = len(topo.get('themes') or []) > 1
1042
+
1043
+ rows = []
1044
+ for l in d.get('layouts') or []:
1045
+ phs = [s for s in by_part.get(l['part'], []) if (s.get('box') or {}).get('w')]
1046
+ if not phs:
1047
+ continue
1048
+ theme = theme_of_master.get(master_of.get(l['part']))
1049
+ phs.sort(key=lambda s: ((s['box'].get('y') or 0), (s['box'].get('x') or 0)))
1050
+ slots, seen_kind = [], set()
1051
+ for s in phs:
1052
+ t = PH_TO_TYPE.get((s['ph'] or {}).get('type'), 'body')
1053
+ if t in ('slide-number', 'footer'):
1054
+ continue # 页码/页脚属 chrome,不是内容槽
1055
+ b = s['box']
1056
+ role = t if t in ('title', 'subtitle') else 'body'
1057
+ if t == 'title' and 'title' in seen_kind:
1058
+ role, t = 'subtitle', 'subtitle'
1059
+ seen_kind.add(t)
1060
+ row = {'role': role, 'type': t, 'sz': shape_sz(s),
1061
+ 'box': [round(b.get('x', 0)), round(b.get('y', 0)),
1062
+ round(b.get('w', 0)), round(b.get('h', 0))],
1063
+ 'txt': shape_text(s) or (s.get('name') or '')[:24]}
1064
+ row.update(slot_style(s))
1065
+ slots.append(row)
1066
+ # 非满屏的图片元素(logo / 联名标 / 装饰)——它们逐版式换位置换尺寸,
1067
+ # 必须按版式落进 slots,压成一条全局「固定位」规则就会撞标题。
1068
+ bgm = composites.get(l['part']) or bg_of_layout.get(l['part'])
1069
+ for s in shapes:
1070
+ if s['part'] != l['part'] or s.get('kind') != 'pic' or not s.get('media'):
1071
+ continue
1072
+ if s['media'] == bgm or (s.get('w_pct', 0) >= 95 and s.get('h_pct', 0) >= 95):
1073
+ continue
1074
+ b = s.get('box') or {}
1075
+ if not b.get('w'):
1076
+ continue
1077
+ slots.append({'role': 'logo', 'type': 'pic', 'sz': 0, 'txt': '',
1078
+ 'media': s['media'],
1079
+ 'box': [round(b.get('x', 0)), round(b.get('y', 0)),
1080
+ round(b.get('w', 0)), round(b.get('h', 0))]})
1081
+ if not slots:
1082
+ continue
1083
+ inst = slide_of_layout.get(l['part'])
1084
+ if inst:
1085
+ slots, bgm = instance_override(
1086
+ shapes, inst, slots, bgm, cW, cH, composites)
1087
+ taken = {tuple(s['box']) for s in slots}
1088
+ decor = collect_decor(shapes, inst or l['part'], taken, (cW, cH))
1089
+ named_role = role_of_name(l.get('name'))
1090
+ rows.append({'zh': clean_layout_name(l.get('name')),
1091
+ 'role': named_role or 'content', 'role_guessed': named_role is None,
1092
+ 'slots': slots, 'decor': decor, 'bg_raw': bgm,
1093
+ 'theme': theme, 'part': l['part'],
1094
+ 'used': l.get('used_by_slides') or 0})
1095
+
1096
+ # 同名版式在 dark/light 两套 master 下各有一份——按名字归一,优先默认主题那份
1097
+ best = {}
1098
+ for r in rows:
1099
+ k = r['zh']
1100
+ cur = best.get(k)
1101
+ if cur is None or (r['theme'] == default_theme and cur['theme'] != default_theme) \
1102
+ or (r['used'] > cur['used']):
1103
+ best[k] = r
1104
+ picked = sorted(best.values(), key=lambda r: (
1105
+ ['cover', 'section', 'quote', 'content', 'closing', 'blank'].index(r['role'])
1106
+ if r['role'] in ('cover', 'section', 'quote', 'content', 'closing', 'blank') else 9,
1107
+ -r['used'], r['part']))
1108
+
1109
+ used_key = Counter()
1110
+ arch = []
1111
+ for r in picked:
1112
+ used_key[r['role']] += 1
1113
+ n = used_key[r['role']]
1114
+ key = r['role'] if n == 1 else '%s-%d' % (r['role'], n)
1115
+ m_no = re.search(r'slideLayout(\d+)\.xml$', r['part'])
1116
+ arch.append({'name': key, 'zh': r['zh'], 'role': r['role'], 'bg': None,
1117
+ 'role_guessed': r.get('role_guessed'),
1118
+ 'bg_raw': r['bg_raw'], 'slots': r['slots'],
1119
+ 'decor': r.get('decor') or [], 'pages': [],
1120
+ 'rep': None, 'rep_layout': int(m_no.group(1)) if m_no else None,
1121
+ # 版式名认不出 role 时不装作有把握:置信度降到 low,让 L 层看图定
1122
+ 'pic_n': 0, 'confidence': 'low' if r.get('role_guessed') else 'high',
1123
+ 'theme': r['theme'] if multi else None,
1124
+ 'source': 'layout:' + r['part'].split('/')[-1]})
1125
+ return arch
1126
+
1127
+
1128
+ _QUERY = []
1129
+
1130
+
1131
+ def _load_query():
1132
+ """复用 query.py 的 OOXML→CSS 渲染,不再写第二份。"""
1133
+ if not _QUERY:
1134
+ import importlib.util
1135
+ spec = importlib.util.spec_from_file_location('_q', os.path.join(HERE, 'query.py'))
1136
+ mod = importlib.util.module_from_spec(spec)
1137
+ spec.loader.exec_module(mod)
1138
+ _QUERY.append(mod)
1139
+ return _QUERY[0]
1140
+
1141
+
1142
+ def collect_decor(shapes, part, taken_boxes, canvas, limit=10):
1143
+ """页面上撑起版式骨架、但不含文字的形状(圆形图标托、卡片、分隔线)。
1144
+
1145
+ 只给文字框的坐标,消费端看到的是「一段说明悬在半空、上方一片空白」,只能自己编
1146
+ 容器,编出来的形状与模板无关。这些形状必须进包。
1147
+ """
1148
+ q = _load_query()
1149
+ cW, cH = canvas
1150
+ out = []
1151
+ for s in shapes:
1152
+ if s.get('part') != part or s.get('kind') != 'sp':
1153
+ continue
1154
+ if any(r.get('text', '').strip()
1155
+ for para in ((s.get('text') or {}).get('paragraphs') or [])
1156
+ for r in (para.get('runs') or [])):
1157
+ continue # 有文字的已经作为 slot 出过
1158
+ b = s.get('box') or {}
1159
+ w, h = b.get('w') or 0, b.get('h') or 0
1160
+ if not (w or h):
1161
+ continue # 零尺寸形状渲染不出任何东西
1162
+ if canvas_coverage(b, cW, cH) >= FULLSCREEN_COVERAGE:
1163
+ continue # 满屏底,属 background
1164
+ box = [round(b.get('x', 0)), round(b.get('y', 0)), round(w), round(h)]
1165
+ if tuple(box) in taken_boxes:
1166
+ continue
1167
+ css = q._recipe_css(s.get('fill'), s.get('line'),
1168
+ [s.get('radius_px')] if s.get('radius_px') else [], s.get('effects'))
1169
+ # 声明要落成单行:含换行的声明会被下游的行式解析器从换行处截断,
1170
+ # 且只记 PARSE-WARN 不 FAIL,整包照常出厂——带着半条渲染不出来的 CSS
1171
+ css = [re.sub(r'\s*\n\s*', ' ', c.split('\x00')[0]).strip() for c in css if c]
1172
+ if not css:
1173
+ continue # 无填充无描边无阴影 = 看不见,不占篇幅
1174
+ out.append({'box': box, 'geom': (s.get('geom') or {}).get('prst') or 'rect',
1175
+ 'css': '; '.join(css), 'area': max(w * h, w, h)})
1176
+ # 按面积降序取前 limit 条:撑起版式的结构性形状总在最前,零星噪点自然落在截断线外,
1177
+ # 不需要再设一个「多小算噪点」的尺寸门槛(那种门槛会误杀 1px 分隔线)。
1178
+ out.sort(key=lambda d: -d['area'])
1179
+ note_truncation('装饰形状', limit, len(out), '按面积降序保留,剩下的多是零星小件',
1180
+ part.split('/')[-1])
1181
+ return out[:limit] # 同款不同位置都要留,位置本身是版式信息
1182
+
439
1183
 
440
1184
  def draft_layouts(d, outdir):
441
1185
  shapes = json.load(open(os.path.join(outdir, 'ref', 'shapes.json'), encoding='utf-8'))['shapes']
442
1186
  cW, cH = d['canvas']['px']
1187
+ if (d.get('form_hint') or {}).get('form') == 3:
1188
+ arch = layouts_from_template(d, shapes, cW, cH)
1189
+ if len(arch) >= 3:
1190
+ return arch, [], []
443
1191
  by_slide = defaultdict(list)
444
1192
  for s in shapes:
445
1193
  if s.get('layer') == 'slide':
@@ -451,21 +1199,20 @@ def draft_layouts(d, outdir):
451
1199
  bg_of_slide[s['part']] = json.dumps(bg, sort_keys=True) if isinstance(bg, dict) else bg
452
1200
  layout_of_slide[s['part']] = s.get('layout')
453
1201
  # 版式层的满屏底图(form=2 常态:底图挂在 layout 上)
1202
+ composites = d.get('background_composites') or {}
454
1203
  bg_of_layout = {}
455
1204
  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'))
1205
+ if s.get('layer') == 'layout' and is_bleed(s) and s.get('media'):
1206
+ bg_of_layout[s['part']] = s['media']
459
1207
 
460
1208
  pages = []
461
1209
  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
1210
+ bg_media = top_bleed_media(sh)
467
1211
  if bg_media is None:
468
1212
  bg_media = bg_of_layout.get(layout_of_slide.get(part))
1213
+ rendered_bg = (composites.get(part)
1214
+ or composites.get(layout_of_slide.get(part))
1215
+ or bg_media)
469
1216
  texts = []
470
1217
  for s in sh:
471
1218
  if s.get('kind') != 'sp':
@@ -476,30 +1223,41 @@ def draft_layouts(d, outdir):
476
1223
  b = s.get('box') or {}
477
1224
  if b.get('w', 0) < DECOR_MIN or b.get('h', 0) < 16:
478
1225
  continue
479
- texts.append({'sz': shape_sz(s), 'box': b, 'txt': txt})
1226
+ texts.append({'sz': shape_sz(s), 'box': b, 'txt': txt, 'style': slot_style(s)})
480
1227
  texts.sort(key=lambda t: (-t['sz'], t['box'].get('y', 0)))
481
1228
  pics = [s for s in sh if s.get('kind') == 'pic' and s.get('w_pct', 0) < 95]
1229
+ # 小图元素(logo / 角标 / 装饰)逐页记位置,供 archetype 落 slots
1230
+ marks = [{'media': s['media'], 'box': s['box']} for s in pics
1231
+ if s.get('media') and (s.get('box') or {}).get('w') and s.get('w_pct', 0) < 30]
482
1232
  pages.append({'part': part, 'no': slide_no(part), 'bg_media': bg_media,
1233
+ 'rendered_bg': rendered_bg,
483
1234
  'bg_color': bg_of_slide.get(part), 'texts': texts, 'pic_n': len(pics),
484
- 'shape_n': len(sh)})
1235
+ 'marks': marks, 'shape_n': len(sh)})
1236
+
1237
+ # 页型的**角色**(封面 / 章节页 / 内容页……)不在这里判:那是看图才能下的结论,
1238
+ # 交给读得到重建图的模型。脚本只做客观归并——同一张底图 + 文字块数量相近的页
1239
+ # 归成一组,档位按本 deck 自己的分布切,不用「字号 ≥60 就是章节页」这类固定数。
1240
+ ns = sorted(len(p['texts']) for p in pages) or [0]
1241
+ q1, q2 = ns[len(ns) // 3], ns[len(ns) * 2 // 3]
485
1242
 
486
- def kind_of(p):
1243
+ def density_band(p):
487
1244
  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'
1245
+ return 0 if n <= q1 else (1 if n <= q2 else 2)
496
1246
 
497
1247
  groups = defaultdict(list)
498
1248
  for p in pages:
499
- groups[(p['bg_media'] or p['bg_color'] or 'none', kind_of(p))].append(p)
1249
+ if p['no'] == 1:
1250
+ # 首页单独成组:它是 deck 唯一的入口页,版面通常和后面任何一页都不同,
1251
+ # 并进别的组就会被代表页顶掉、坐标全丢。这只是不合并,不代表它是封面。
1252
+ groups[('__first__', -1)] = [p]
1253
+ continue
1254
+ groups[(p['bg_media'] or p['bg_color'] or 'none', density_band(p))].append(p)
500
1255
 
501
1256
  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]
1257
+ # 首页所在的组一定收——deck 的第一页是模板的门面,孤例也不能被名额挤掉。
1258
+ # 这只保证它进包,它是不是封面由看图的人定。
1259
+ first = [g for g in ranked if g[0][0] == '__first__']
1260
+ kept = first + [g for g in ranked if g not in first and len(g[1]) >= 2][:8 - len(first)]
503
1261
  for g in ranked: # 名额没用满就把最大的孤例页也收进来
504
1262
  if len(kept) >= 8:
505
1263
  break
@@ -508,35 +1266,63 @@ def draft_layouts(d, outdir):
508
1266
  leftover = sorted(p['no'] for g in ranked if g not in kept for p in g[1])
509
1267
 
510
1268
  archetypes = []
511
- used = Counter()
512
- for (bg_raw, kind), ps in kept:
1269
+ for gi, ((bg_raw, _band), ps) in enumerate(kept, 1):
513
1270
  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 (
1271
+ if bg_raw == '__first__':
1272
+ bg_raw = rep['bg_media'] or rep['bg_color'] or 'none'
1273
+ rendered_bg = rep.get('rendered_bg')
1274
+ if rendered_bg:
1275
+ bg_raw = rendered_bg
1276
+ name = 'layout-%d' % gi
1277
+ # 标题按「位置 + 跨度」认,不按字号——big-number 类的巨号数值常比标题还大
1278
+ # 标题 = 该页最靠上的那批文本里最宽的一块。不按「画布前 28%」这类固定比例切:
1279
+ # 版心靠下的模板会整页认不出标题。以该页自身的文本框分布定「靠上」。
1280
+ ys = sorted(t['box'].get('y', 0) for t in rep['texts'])
1281
+ y_cut = ys[max(len(ys) // 4, 0)] if ys else 0
1282
+ band = [t for t in rep['texts'] if t['box'].get('y', 1e9) <= y_cut]
1283
+ title = max(band, key=lambda t: (t['box'].get('w', 0), t['sz'])) if band else (
520
1284
  max(rep['texts'], key=lambda t: t['sz']) if rep['texts'] else None)
521
1285
  rest = [t for t in rep['texts'] if t is not title]
522
1286
  rest.sort(key=lambda t: (t['box'].get('y', 0), t['box'].get('x', 0)))
523
1287
  ordered = ([title] if title else []) + rest
524
1288
  slots = []
1289
+ note_truncation('文字槽', 6, len(ordered),
1290
+ '需要更多同类槽时,按已有同类槽的间距等距延续,不要另起一套网格'
1291
+ '——包里的坐标是模板量出来的,自创网格等于放弃这套版式', name)
525
1292
  for i, t in enumerate(ordered[:6]):
526
1293
  b = t['box']
527
1294
  if t is title:
528
1295
  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
1296
+ elif (title and i == 1
1297
+ # 副标题 = 紧跟在标题下方、与标题左对齐的那一块。三个量都相对标题
1298
+ # 自身:绝对 px 门槛在大字号排版的模板上会整片认不出来。
1299
+ and abs(b.get('x', 0) - title['box'].get('x', 0)) <= title['box'].get('h', 0)
531
1300
  and 0 <= b.get('y', 0) - (title['box'].get('y', 0)
532
- + title['box'].get('h', 0)) < 220):
1301
+ + title['box'].get('h', 0))
1302
+ <= title['box'].get('h', 0) * 2):
533
1303
  role = typ = 'subtitle'
534
1304
  else:
535
1305
  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']})
1306
+ row = {'role': role, 'box': [round(b.get('x', 0)), round(b.get('y', 0)),
1307
+ round(b.get('w', 0)), round(b.get('h', 0))],
1308
+ 'type': typ, 'sz': t['sz'], 'txt': t['txt']}
1309
+ row.update(t.get('style') or {})
1310
+ slots.append(row)
1311
+ # 代表页上的小图元素按位置去重后落 slots(同一 logo 在不同页型位置不同)
1312
+ seen_mark = set()
1313
+ for mk in rep.get('marks') or []:
1314
+ b = mk['box']
1315
+ key = (mk['media'], round(b.get('x', 0)), round(b.get('y', 0)))
1316
+ if key in seen_mark:
1317
+ continue
1318
+ seen_mark.add(key)
1319
+ slots.append({'role': 'logo', 'type': 'pic', 'sz': 0, 'txt': '',
1320
+ 'media': mk['media'],
1321
+ 'box': [round(b.get('x', 0)), round(b.get('y', 0)),
1322
+ round(b.get('w', 0)), round(b.get('h', 0))]})
1323
+ decor = collect_decor(shapes, rep['part'], {tuple(s['box']) for s in slots}, (cW, cH))
539
1324
  archetypes.append({'name': name, 'bg': None, 'bg_raw': bg_raw, 'slots': slots,
1325
+ 'decor': decor,
540
1326
  'pages': sorted(p['no'] for p in ps), 'rep': rep['no'],
541
1327
  'pic_n': rep['pic_n'],
542
1328
  'confidence': 'high' if len(ps) >= 3 else
@@ -547,12 +1333,15 @@ def draft_layouts(d, outdir):
547
1333
  # ---------------------------------------------------------------- 联系表
548
1334
  def layout_sheet(outdir, archetypes, path):
549
1335
  """把各 archetype 的代表页光栅出来拼成一张——版式命名得看得见页面。"""
550
- reps = [a['rep'] for a in archetypes]
1336
+ use_layout = all(a.get('rep') is None for a in archetypes)
1337
+ reps = [a.get('rep_layout') if use_layout else a.get('rep') for a in archetypes]
1338
+ reps = [x for x in reps if x is not None]
551
1339
  if not reps:
552
1340
  return None
553
1341
  import subprocess
554
1342
  r = subprocess.run([sys.executable, os.path.join(HERE, 'render_pages.py'), outdir,
555
- '--pages', 'slides', '--only', ','.join(map(str, reps)), '--no-html'],
1343
+ '--pages', 'layouts' if use_layout else 'slides',
1344
+ '--only', ','.join(map(str, reps)), '--no-html'],
556
1345
  capture_output=True, text=True)
557
1346
  png_dir = os.path.join(outdir, 'ref', 'rebuild', 'png')
558
1347
  if r.returncode or not os.path.isdir(png_dir):
@@ -570,14 +1359,19 @@ def layout_sheet(outdir, archetypes, path):
570
1359
  for i, a in enumerate(archetypes):
571
1360
  x = pad + (i % cols) * (cw + pad)
572
1361
  y = pad + (i // cols) * (ch + pad + lab)
573
- f = os.path.join(png_dir, 'slide-%d.png' % a['rep'])
1362
+ no = a.get('rep_layout') if use_layout else a.get('rep')
1363
+ f = os.path.join(png_dir, '%s-%s.png' % ('layout' if use_layout else 'slide', no))
574
1364
  if os.path.exists(f):
575
1365
  im = Image.open(f).convert('RGB')
576
1366
  im.thumbnail((cw, ch))
577
1367
  sheet.paste(im, (x, y))
578
1368
  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 '-'),
1369
+ # 标注只写 ASCII——Pillow 默认字体没有 CJK 字形,中文会渲染成方框
1370
+ dr.text((x + 2, y + ch + 5), '[%s] %s bg=%s'
1371
+ % (a['name'],
1372
+ ('layout %s' % a.get('rep_layout')) if use_layout
1373
+ else ('slide %s x%d pages' % (a.get('rep'), len(a['pages']))),
1374
+ a.get('bg') or '-'),
581
1375
  fill=(20, 20, 24))
582
1376
  sheet.save(path, optimize=True)
583
1377
  return path
@@ -589,7 +1383,7 @@ def contact_sheet(outdir, cands, path):
589
1383
  except Exception:
590
1384
  return None
591
1385
  cell, pad, cols = 220, 20, 4
592
- items = cands[:12]
1386
+ items = cands # 上限由调用方定,编号与 BRIEF 表格一一对应
593
1387
  if not items:
594
1388
  return None
595
1389
  rows = (len(items) + cols - 1) // cols
@@ -669,20 +1463,31 @@ def emit_frontmatter(d, tokens, fonts, roles, anchors, gaps, ldir):
669
1463
  edge = {}
670
1464
  for p in pads:
671
1465
  edge.setdefault(p['edge'], p['px'])
672
- if edge:
1466
+ # 四边都测出来才写 spacing / safe-area。缺一边就整段不写,并在 gaps 说明——
1467
+ # 拿另一套模板的边距当默认值,会让消费端按一个从没在本模板出现过的网格排版。
1468
+ edges_full = all(edge.get(k) is not None for k in ('top', 'right', 'bottom', 'left'))
1469
+ if edges_full:
673
1470
  L.append('spacing:')
674
1471
  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]
1472
+ % (edge['top'], edge['right'], edge['bottom'], edge['left']))
1473
+ # 只排除「圆角量为零」(那是直角不是圆角),不再设「出现几次才算数」的门槛
1474
+ radii = [r for r in (d.get('radii_census') or []) if r['px'] >= 1]
678
1475
  if radii:
679
1476
  top = max(radii, key=lambda r: r['n'])
680
1477
  L.append('rounded:')
681
1478
  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')
1479
+ if edges_full:
1480
+ L.append('safe-area:')
1481
+ L.append(' content: {top: %s, right: %s, bottom: %s, left: %s, applies-to: [content]}'
1482
+ % (edge['top'], edge['right'], edge['bottom'], edge['left']))
1483
+ L.append(' confidence: medium')
1484
+ else:
1485
+ gaps = list(gaps) + ['本模板没测出四边都稳定的页边距(普查到 %s),'
1486
+ '因此不给 spacing / safe-area:按各页型 slot 的实际坐标排版,'
1487
+ '不要自造统一边距。'
1488
+ % ('、'.join('%s=%s' % (k, edge[k]) for k in
1489
+ ('top', 'right', 'bottom', 'left') if edge.get(k) is not None)
1490
+ or '一边都没有')]
686
1491
  L.append('anchors:')
687
1492
  for aid, typ, desc in anchors:
688
1493
  L.append(' - {id: %s, type: %s, desc: "%s"}' % (aid, typ, desc))
@@ -692,131 +1497,396 @@ def emit_frontmatter(d, tokens, fonts, roles, anchors, gaps, ldir):
692
1497
  write(os.path.join(ldir, 'frontmatter.yaml'), '\n'.join(L) + '\n')
693
1498
 
694
1499
 
695
- def emit_layouts(archetypes, ldir):
696
- L = ['# 只改 names 这一段:给每个页型起表意的中文名(看 layout-sheet.png)。下面 layouts 段不要动。',
697
- 'names:']
1500
+ def draft_flow(a, facts, canvas):
1501
+ """从结构事实推出「区带」草案:一页 = 若干竖直区带,高度由内容决定。
1502
+
1503
+ 绝对坐标只能表达「模板样张那份内容摆在哪」。真实内容长度不同,上面的区带一变高,
1504
+ 下面的就该整体下移——这件事在一张坐标表里表达不出来,只能靠消费端自己算,而它
1505
+ 算错的方向有两个:估小了压穿下一块,估大了留一片空。
1506
+
1507
+ 这里只出草案,最终用绝对还是流式由看得到重建图的人定。
1508
+ """
1509
+ cW, cH = canvas
1510
+ # 装饰件也算进来:很多模板的版式层只有几个占位符,真正撑起版面的是卡片容器
1511
+ # (在 decor 里)。只看 slots 会把一页的主体结构整个漏掉。
1512
+ items = [s for s in a['slots'] if s.get('box')]
1513
+ items += [{'role': 'container', 'type': 'decor', 'box': dcr['box'], 'css': dcr.get('css')}
1514
+ for dcr in (a.get('decor') or [])]
1515
+ if len(items) < 2:
1516
+ return None
1517
+ items.sort(key=lambda s: (s['box'][1], s['box'][0]))
1518
+ gaps = [items[i + 1]['box'][1] - (items[i]['box'][1] + items[i]['box'][3])
1519
+ for i in range(len(items) - 1)]
1520
+ pos = [g for g in gaps if g > 0]
1521
+ if not pos:
1522
+ return None
1523
+ # 区带边界 = 间距分布里的最大空档。同一区带内部的间距(网格行距之类)总是明显
1524
+ # 小于区带之间的间距,用本页自己的分布切,不设固定阈值。
1525
+ cut = _gap_cut(pos, min(pos), max(pos)) if len(pos) > 1 else max(pos) + 1
1526
+ regions, cur = [], [items[0]]
1527
+ for i, g in enumerate(gaps):
1528
+ if g >= cut:
1529
+ regions.append(cur)
1530
+ cur = []
1531
+ cur.append(items[i + 1])
1532
+ regions.append(cur)
1533
+
1534
+ out = []
1535
+ for reg in regions:
1536
+ if not reg:
1537
+ continue
1538
+ # 同一区带里 y 接近的算一行;每行元素数一致且 >1 就是网格
1539
+ rows, cr = [], [reg[0]]
1540
+ for s in reg[1:]:
1541
+ if abs(s['box'][1] - cr[-1]['box'][1]) <= max(s['box'][3], 1) * 0.5:
1542
+ cr.append(s)
1543
+ else:
1544
+ rows.append(cr)
1545
+ cr = [s]
1546
+ rows.append(cr)
1547
+ widths = {len(r) for r in rows}
1548
+ if len(rows) >= 1 and widths == {len(rows[0])} and len(rows[0]) > 1:
1549
+ cols = len(rows[0])
1550
+ xs = sorted(s['box'][0] for s in rows[0])
1551
+ col_gap = round((xs[1] - xs[0]) - rows[0][0]['box'][2]) if cols > 1 else 0
1552
+ row_gap = 0
1553
+ if len(rows) > 1:
1554
+ row_gap = round(rows[1][0]['box'][1]
1555
+ - (rows[0][0]['box'][1] + rows[0][0]['box'][3]))
1556
+ out.append({'kind': 'grid', 'cols': cols, 'gap': [max(col_gap, 0), max(row_gap, 0)],
1557
+ 'items': rows[0]})
1558
+ elif len(rows) == len(reg):
1559
+ # 每行一个元素 = 真的竖着排
1560
+ inner = 0
1561
+ if len(reg) > 1:
1562
+ inner = round(reg[1]['box'][1] - (reg[0]['box'][1] + reg[0]['box'][3]))
1563
+ out.append({'kind': 'stack', 'gap': max(inner, 0), 'items': reg})
1564
+ else:
1565
+ # 每行元素数不一致(比如左列两张、右列一张跨两行)。硬说成 stack 会让消费端
1566
+ # 以为它们是竖排的,比不给还糟。如实说这块推不出规整结构,按坐标摆。
1567
+ out.append({'kind': 'free', 'items': reg})
1568
+ if len(out) < 2:
1569
+ return None
1570
+ lefts = [s['box'][0] for s in items]
1571
+ rights = [s['box'][0] + s['box'][2] for s in items]
1572
+ return {'top': items[0]['box'][1], 'margin': [min(lefts), cW - max(rights)],
1573
+ 'gap': round(cut), 'regions': out}
1574
+
1575
+
1576
+ def structure_facts(archetypes, d, shapes):
1577
+ """每个页型的**结构事实**:栅格、垂直间距序列、容器样式配方、样张里的实际字数。
1578
+
1579
+ 这些是判「该用绝对坐标还是流式」的依据,脚本只测不判:
1580
+ - 栅格拟合好不好,决定这页是不是一个规整的多列区带
1581
+ - 垂直间距序列里的突变点,就是区带的边界(网格内部 24、区带之间 110)
1582
+ - 样张字数说明这个框是按几行内容设计的——框高本身看不出这件事
1583
+ """
1584
+ q = _load_query()
1585
+ by_part = defaultdict(list)
1586
+ for s in shapes:
1587
+ by_part[s.get('part')].append(s)
1588
+
1589
+ # 容器样式配方:跨全档聚类一次,记出现次数与跨页数,供判断「哪些是共性风格」
1590
+ groups = {}
1591
+ for s in shapes:
1592
+ fill, line, fx = s.get('fill'), s.get('line'), s.get('effects')
1593
+ if not fill and not line and not fx:
1594
+ continue
1595
+ if isinstance(fill, dict) and fill.get('type') == 'image':
1596
+ continue
1597
+ k = q._sig(fill, line, fx)
1598
+ if k[0] == 'none' and k[1] == 'none' and not k[2]:
1599
+ continue
1600
+ g = groups.setdefault(k, {'n': 0, 'parts': set(), 'radii': [],
1601
+ 'fill': fill, 'line': line, 'fx': fx, 'shapes': set()})
1602
+ g['n'] += 1
1603
+ g['parts'].add(s.get('part'))
1604
+ if s.get('radius_px'):
1605
+ g['radii'].append(s['radius_px'])
1606
+ g['shapes'].add(id(s))
1607
+ ranked = sorted(groups.values(), key=lambda g: -g['n'])
1608
+ recipe_id = {}
1609
+ recipes = []
1610
+ for i, g in enumerate(ranked, 1):
1611
+ rid = 'r%d' % i
1612
+ css = [re.sub(r'\s*\n\s*', ' ', c.split('\x00')[0]).strip()
1613
+ for c in q._recipe_css(g['fill'], g['line'], g['radii'], g['fx']) if c]
1614
+ recipes.append({'id': rid, 'n': g['n'], 'pages': len(g['parts']),
1615
+ 'css': '; '.join(css)})
1616
+ for sid in g['shapes']:
1617
+ recipe_id[sid] = rid
1618
+
1619
+ grids = (d.get('spacing_candidates') or {}).get('grids') or []
1620
+ grid_by_part = defaultdict(list)
1621
+ for gd in grids:
1622
+ grid_by_part[gd.get('part')].append(gd)
1623
+
1624
+ out = {}
1625
+ for a in archetypes:
1626
+ part = None
1627
+ if a.get('source', '').startswith('layout:'):
1628
+ part = 'ppt/slideLayouts/' + a['source'].split(':', 1)[1]
1629
+ elif a.get('rep'):
1630
+ part = 'ppt/slides/slide%d.xml' % a['rep']
1631
+ boxes = [s['box'] for s in a['slots']] + [x['box'] for x in (a.get('decor') or [])]
1632
+ boxes.sort(key=lambda b: b[1])
1633
+ gaps = [boxes[i + 1][1] - (boxes[i][1] + boxes[i][3]) for i in range(len(boxes) - 1)]
1634
+ chars = [(s['box'], len(s.get('txt') or '')) for s in a['slots'] if s.get('txt')]
1635
+ used = []
1636
+ for s in by_part.get(part, []):
1637
+ rid = recipe_id.get(id(s))
1638
+ if rid and rid not in used:
1639
+ used.append(rid)
1640
+ out[a['name']] = {'grids': grid_by_part.get(part) or [], 'gaps': gaps,
1641
+ 'chars': chars, 'recipes': used}
1642
+ return out, recipes
1643
+
1644
+
1645
+ def emit_layouts(archetypes, ldir, busy_hints=None, facts=None, recipes=None):
1646
+ prefilled = sum(1 for a in archetypes if a.get('zh'))
1647
+ L = ['# 判断单草案 —— package.py 读它产出 layouts.md,deck 的版式坐标从 layouts.md 读。',
1648
+ '# 只改 names / roles / bg_rules 三段(都是扁平键值,改完 package.py 自动并回各页型)。',
1649
+ '# 下面 layouts 段是普查数值,一个字都不要动——改它容易连带删掉 slots/confidence。']
1650
+ if prefilled:
1651
+ L.append('# names 已按模板自带的版式名填好 %d 条,读一遍确认表意即可,通常不用改。' % prefilled)
1652
+ if recipes:
1653
+ L.append('# 容器样式配方(按出现次数排;跨页数多 = 共性风格,只在一处出现的多半不是):')
1654
+ for r in recipes[:8]:
1655
+ L.append('# %s 出现 %d 次 / 跨 %d 处 %s' % (r['id'], r['n'], r['pages'], r['css']))
1656
+ L.append('names:')
1657
+ for a in archetypes:
1658
+ if a.get('zh'):
1659
+ # 模板自己给版式起了名(form=3),直接用——比看图起名准,也省掉一轮判断
1660
+ L.append(' %s: %s' % (a['name'], q(a['zh'])))
1661
+ else:
1662
+ L.append(' %s: TODO中文名(代表页 %s,共 %d 页)'
1663
+ % (a['name'], a['rep'], len(a['pages'])))
1664
+ # 角色(封面 / 章节页 / 内容页……)是看图才能下的结论,脚本不猜。模板自己按页型
1665
+ # 命名时用它的标注,否则连同客观事实一起摆出来,由看得到重建图的你来定。
1666
+ need_role = [a for a in archetypes if not a.get('role')]
1667
+ if need_role:
1668
+ L.append('roles: # 取值 cover|section|content|quote|closing|blank|custom')
1669
+ for a in need_role:
1670
+ szs = sorted({round(s['sz']) for s in a['slots'] if s.get('sz')}, reverse=True)
1671
+ L.append(' %s: TODO角色 # 代表页 %s,共 %d 页;文字块 %d 个,字号 %s;'
1672
+ '图片 %d 张%s'
1673
+ % (a['name'], a['rep'], len(a['pages']),
1674
+ len([s for s in a['slots'] if not s.get('asset')]),
1675
+ '/'.join(str(x) for x in szs[:5]) or '未声明',
1676
+ a.get('pic_n') or 0, ';有满屏底图' if a.get('bg_raw') else ''))
1677
+ # 禁放区是**背景图**的属性,不是页型的属性——按背景资产分组,页型再多也不涨
1678
+ bgs = []
698
1679
  for a in archetypes:
699
- L.append(' %s: TODO中文名(代表页 %s,共 %d 页)' % (a['name'], a['rep'], len(a['pages'])))
1680
+ if a['bg'] and a['bg'] not in bgs:
1681
+ bgs.append(a['bg'])
1682
+ if bgs:
1683
+ L.append('bg_rules:')
1684
+ for bg in bgs:
1685
+ users = [a['name'] for a in archetypes if a['bg'] == bg]
1686
+ L.append(' %s: # 用它的页型:%s' % (bg, ', '.join(users)))
1687
+ hint = (busy_hints or {}).get(bg)
1688
+ if hint:
1689
+ L.append(' # 图像局部对比度:中位 %s、九分位 %s;%s'
1690
+ % (hint['median'], hint['p90'],
1691
+ ('更花的一片在 %s' % hint['busy']) if hint.get('busy')
1692
+ else hint.get('why', '')))
1693
+ # text_safe 不是判断题:模板自己已经把文字放在哪儿写死了。取用这张背景的
1694
+ # 所有页型的槽与装饰件的外接并集即可——让人看图猜只会猜得更松,把模板从不
1695
+ # 放字的区域也划进安全区,这个字段就白设了。
1696
+ boxes = [s['box'] for a in archetypes if a['bg'] == bg for s in a['slots']] + \
1697
+ [dcr['box'] for a in archetypes if a['bg'] == bg for dcr in (a.get('decor') or [])]
1698
+ if boxes:
1699
+ x0 = min(b[0] for b in boxes)
1700
+ y0 = min(b[1] for b in boxes)
1701
+ x1 = max(b[0] + b[2] for b in boxes)
1702
+ y1 = max(b[1] + b[3] for b in boxes)
1703
+ L.append(' text_safe: [%d, %d, %d, %d] # 由该背景各页型的槽位并集算出'
1704
+ % (x0, y0, x1 - x0, y1 - y0))
1705
+ else:
1706
+ L.append(' text_safe: TODO安全文字区[x,y,w,h](该背景下没有任何槽位可依据)')
1707
+ L.append(' avoid: TODO禁放区列表;无禁放区写 [],有则写 [{box: [x,y,w,h], reason: "..."}]')
1708
+ L.append(' pairing_rule: "TODO这张背景上标题/正文/图表要避让哪些区域"')
700
1709
  L.append('layouts:')
701
1710
  for a in archetypes:
1711
+ fx = (facts or {}).get(a['name']) or {}
1712
+ if fx:
1713
+ # 结构事实:判「这页该用绝对坐标还是流式」的依据。脚本只测不判。
1714
+ for gd in (fx.get('grids') or [])[:2]:
1715
+ c, r = gd.get('cols') or {}, gd.get('rows') or {}
1716
+ L.append(' # 栅格:%s 列%s%s' % (
1717
+ c.get('n'), ' @%gpx 步距方差 %.2f' % (c.get('pitch') or 0, c.get('sd') or 0)
1718
+ if c.get('regular') else '(列不规整)',
1719
+ ',行 %s' % (('%d @%gpx' % (r.get('n') or 0, r.get('pitch') or 0))
1720
+ if r.get('regular') else '不规整')))
1721
+ if fx.get('gaps'):
1722
+ L.append(' # 垂直间距:%s(突变处即区带边界)'
1723
+ % '、'.join(str(int(g)) for g in fx['gaps'][:10]))
1724
+ if fx.get('chars'):
1725
+ L.append(' # 样张字数:%s'
1726
+ % '、'.join('%s=%d字' % (b, n) for b, n in fx['chars'][:6]))
1727
+ if fx.get('recipes'):
1728
+ L.append(' # 命中配方:%s' % '、'.join(fx['recipes'][:4]))
1729
+ # 槽与槽在坐标上重叠:PPT 里占位符互相压是常态(文字 valign 居中、样张只有一行,
1730
+ # 看不出来),照抄坐标做成 HTML 后内容一变长就撞。实测封面 title 框比 subtitle
1731
+ # 的顶还低 41px,两行标题直接压在副标题上。这里只报事实,怎么让开由你定。
1732
+ ov = slot_overlaps(a.get('slots') or [])
1733
+ if ov:
1734
+ L.append(' # 槽位重叠:%s(模板里靠文字居中不显形,内容变长会撞)'
1735
+ % '、'.join(ov[:3]))
702
1736
  L.append(' %s:' % a['name'])
703
- L.append(' role: %s' % a['name'].split('-')[0])
1737
+ if a.get('role'):
1738
+ L.append(' role: %s' % a['role'])
704
1739
  if a['bg']:
705
1740
  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说明该页型必须配这张背景时,标题/正文/图表需要避让哪些区域"')
1741
+ fl = a.get('flow')
1742
+ if fl:
1743
+ L.append(' # ↓ flow 与 slots 二选一:内容长度会变的页用 flow(区带依次排、'
1744
+ '高度由内容定、下面的自动被推下去),构图固定的页用 slots。删掉不要的那个。')
1745
+ L.append(' flow:')
1746
+ L.append(' top: %d' % fl['top'])
1747
+ L.append(' margin: [%d, %d]' % tuple(fl['margin']))
1748
+ L.append(' gap: %d' % fl['gap'])
1749
+ L.append(' regions:')
1750
+ for r in fl['regions']:
1751
+ if r['kind'] == 'grid':
1752
+ L.append(' - kind: grid')
1753
+ L.append(' cols: %d' % r['cols'])
1754
+ L.append(' gap: [%d, %d]' % tuple(r['gap']))
1755
+ elif r['kind'] == 'free':
1756
+ L.append(' - kind: free # 推不出规整结构,按 slots 的坐标摆')
1757
+ else:
1758
+ L.append(' - kind: stack')
1759
+ L.append(' gap: %d' % r['gap'])
1760
+ L.append(' items:')
1761
+ for s in r['items']:
1762
+ # free 区带按坐标摆,而 slots 会被删掉,所以坐标必须写在这里
1763
+ bx = ', box: %s' % s['box'] if r['kind'] == 'free' else ''
1764
+ if s.get('type') == 'decor':
1765
+ L.append(' - {role: container%s, css: "%s"}'
1766
+ % (bx, (s.get('css') or '').replace('"', "'")))
1767
+ continue
1768
+ extra = bx
1769
+ for k in ('size', 'weight', 'color', 'css', 'align', 'valign'):
1770
+ if s.get(k) is not None:
1771
+ # 色值与 css 串一律加引号:里面的逗号/冒号在 flow map 里是分隔符
1772
+ extra += ', %s: %s' % (
1773
+ k, '"%s"' % str(s[k]).replace('"', "'")
1774
+ if k in ('color', 'css') else s[k])
1775
+ if s.get('asset'):
1776
+ extra += ', asset: %s' % s['asset']
1777
+ L.append(' - {role: %s, type: %s%s}' % (s['role'], s['type'], extra))
709
1778
  L.append(' slots:')
710
1779
  for s in a['slots']:
711
- L.append(' - {role: %s, box: %s, type: %s}' % (s['role'], s['box'], s['type']))
1780
+ extra = ''
1781
+ if s.get('asset'):
1782
+ extra += ', asset: %s' % s['asset']
1783
+ for k in ('size', 'weight', 'color', 'css', 'align', 'valign'):
1784
+ if s.get(k) is not None:
1785
+ v = s[k]
1786
+ extra += ', %s: %s' % (
1787
+ k, '"%s"' % str(v).replace('"', "'") if k in ('color', 'css') else v)
1788
+ L.append(' - {role: %s, box: %s, type: %s%s}'
1789
+ % (s['role'], s['box'], s['type'], extra))
1790
+ if a.get('decor'):
1791
+ L.append(' decor:')
1792
+ for dcr in a['decor']:
1793
+ L.append(' - {box: %s, geom: %s, css: "%s"}'
1794
+ % (dcr['box'], dcr['geom'], dcr['css'].replace('"', "'")))
712
1795
  L.append(' confidence: %s' % a.get('confidence', 'medium'))
713
1796
  write(os.path.join(ldir, 'layouts.yaml'), '\n'.join(L) + '\n')
714
1797
 
715
1798
 
716
- def emit_body(d, tokens, fonts, roles, assets, archetypes, exceptions, ldir):
1799
+ def emit_body(d, tokens, fonts, roles, assets, archetypes, exceptions, cusage, ldir):
1800
+ """design.md 正文。
1801
+
1802
+ 每条规则只出现一次——同一条散在 Fast Path / Usage / Background Safety /
1803
+ Hard Rules 各写一遍时措辞必然漂移,消费端无法判断哪份权威。
1804
+ 坐标、字号、色值、资产位置的权威都在 layouts.md;本文件只给色板、字体栈与纪律。
1805
+ """
717
1806
  canvas = d['canvas']['px']
718
1807
  cover = next((a for a in assets if a['id'] == 'bg-cover'), None)
719
1808
  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` 取。', '']
1809
+ imp, webs = import_line(fonts)
1810
+ sidecar = '`layouts.md`'
1811
+
1812
+ L = ['## Overview', '',
1813
+ 'TODO: 两三句话讲清这套模板的性格与适用场景——看过联系表和页面重建图之后再写。', '']
1814
+ L.append(('模板自带 %d 种版式,页型、坐标、字号、色值都直读自版式层。'
1815
+ % len(archetypes)) if (d.get('form_hint') or {}).get('form') == 3 else
1816
+ ('%d 页样张归纳出 %d 种页型。' % (d['counts']['slides'], len(archetypes))))
1817
+ L += ['', '## Usage', '',
1818
+ '搭一页 PPT 六步,中间四步的数据都在 %s:' % sidecar, '']
1819
+ L += ['1. **定画布** —— 舞台按 `layouts.md` `canvas` 设成 %d×%d,'
1820
+ '别套用默认尺寸:源模板的长宽比不一定是 16:9,套错了整页坐标全偏。'
1821
+ '舞台尺寸改不了时,整体等比缩放 `min(舞台宽/%d, 舞台高/%d)` 后居中留白——'
1822
+ '逐轴拉伸会把圆压成椭圆、把字挤扁。' % (canvas[0], canvas[1], canvas[0], canvas[1]),
1823
+ '2. **挑页型** —— %s 里按用途选一个 archetype(清单见下面 Layouts 段)。'
1824
+ '页数多于页型时,挑最接近的一个原样套用它的 slot:用不到的槽删掉,'
1825
+ '内容比槽多就按同类槽的间距等距加,**坐标一律沿用该页型给的那套,不要自己另起网格**。'
1826
+ % sidecar,
1827
+ '3. **按页型给的形态落元素** —— 页型给 `flow` 就用流式,给 `slots` 就用绝对,'
1828
+ '两者只会出现一个。'
1829
+ '**flow**:整块用一个纵向 flex 容器,`top` 是它的起始 y,`margin` 是左右边距,'
1830
+ '`gap` 是区带之间的间距;`regions` 从上往下依次排,**每个区带的高度由它自己的'
1831
+ '内容决定,不要写死高度**——上面的区带内容变多时,下面的自然被推下去,这正是'
1832
+ '这套表达要解决的事。区带内部:`kind: grid` `grid-template-columns: repeat(cols, 1fr)` '
1833
+ '配 `gap: [行间距, 列间距]`;`kind: stack` 用纵向 flex 配 `gap`;`kind: free` '
1834
+ '按该页型 `slots` 里的坐标绝对定位。`role: container` 的项是容器,把它的 `css` '
1835
+ '原样写进 style,内容放进去。',
1836
+ '4. **按 slot 落元素(页型给的是 slots 时)** —— 每个 slot 渲染成一个绝对定位元素:`box` '
1837
+ '`[x, y, w, h]`(%dx%d 画布上的绝对像素),字号取 slot 的 `size`,'
1838
+ '字重取 `weight`,颜色取 `color`,对齐取 `align` / `valign`。'
1839
+ '带 `asset` slot 是图片元素(logo、角标),把该资产放在它自己的 `box` 里;'
1840
+ '这个页型没有 `asset` 槽,这一页就不出现该资产。' % (canvas[0], canvas[1]),
1841
+ '5. **铺装饰几何** —— 页型的 `decor` 是这一页的图形骨架(图标托底的圆、'
1842
+ '卡片、分隔线):每条渲染成一个绝对定位空元素,`box` 给位置,`css` 原样写进 style,'
1843
+ '`geom: ellipse` 另加 `border-radius: 50%`。它们压在背景之上、slot 之下,'
1844
+ '落在 slot 上的图标正是靠它们托住。',
1845
+ '6. **配色与字体** —— 色板见下面 Colors 段,字体栈与 `@import` 见 Typography 段。']
774
1846
  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), '',
1847
+ L += ['', '资产文件(背景由页型的 `background` 字段指定,'
1848
+ '图片资产的位置由该页型 `slots` 里带 `asset` 的槽给出):', '',
1849
+ '{{ASSET_TABLE}}']
1850
+ L += ['', '文字与容器的外接矩形落在该页型 `background` 对应的 `text_safe` 内,'
1851
+ '避开 `avoid` 列出的区域(两者都在 %s `backgrounds` 段)。内容装不下时换页型或拆页。'
1852
+ % sidecar, '',
780
1853
  '## Colors', '', '| token | 值 | 用途 |', '|---|---|---|']
781
- USE = {'surface': '页面与卡片主底色', 'surface-alt': '次级底色,分区/强调区块的浅底',
782
- 'ink': '正文与标题文字色', 'ink-muted': '次级文字色,说明与标签',
783
- 'primary': '主强调色:图表主序列、关键数字、行动点',
784
- 'accent': '副强调色,多与 primary 组成渐变',
785
- 'accent-2': '渐变与图表的第二落点色', 'accent-3': '渐变收尾色,用量最少',
786
- 'neutral': '中性弱化色:分隔线、次要标签'}
787
1854
  for name, r in tokens:
788
- L.append('| `%s` | `%s` | %s |' % (name, r['hex'], USE.get(name, '按 token 名对应的角色使用')))
789
- imp, webs = import_line(fonts)
1855
+ L.append('| `%s` | `%s` | %s |'
1856
+ % (name, r['hex'], usage_phrase(cusage.get(r['hex'].upper()))))
790
1857
  L += ['', '## Typography', '']
791
1858
  for f in fonts[:2]:
792
1859
  L.append('- **%s** —— 栈 `%s`%s' % (
793
1860
  f['names'][0], font_css(f['stack']),
794
1861
  ',源为商业/内部字体无 web 分发源,按气质降级到 %s' % f['stack'][1]
795
1862
  if len(f['stack']) > 1 else ''))
796
- L += ['', '字号轴:' + '、'.join('%s %dpx' % (k, round(v['sz_px'])) for k, v in roles.items()), '',
1863
+ L += ['', '字号轴:' + '、'.join('%s %dpx' % (k, round(v['sz_px'])) for k, v in roles.items())
1864
+ + '。slot 自带 `size` 时以 slot 为准;层级在轴上没有的,复用最接近的一档。', '',
797
1865
  '字体加载(**HARD REQUIREMENT:下面这行 @import 原样写入全局样式首行,禁止替换为 '
798
1866
  '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', '']
1867
+ '镜像只保证 wght 400 一档,更粗的字重由浏览器合成,字重不能作为唯一区分手段;'
1868
+ '系统字体 PingFang SC / Microsoft YaHei 置于栈末保底,中文场景负字距清零。', '',
1869
+ '## Layouts', '', '页型清单如下,每个页型的 slots、background、'
1870
+ '禁放区都在 %s:' % sidecar, '', '{{LAYOUT_LIST}}',
1871
+ '', '## Hard Rules', '']
805
1872
  if cover:
806
- L.append('- 封面页背景必须铺 `bg-cover`(文件见 Usage 表),整幅铺满 %dx%d,不要自造渐变或换图。'
807
- % (canvas[0], canvas[1]))
1873
+ L.append('- 封面页铺满 `bg-cover`,整幅覆盖 %dx%d 画布。' % (canvas[0], canvas[1]))
808
1874
  if any(a['role'] == 'content' for a in assets):
809
- L.append('- 内容页背景整幅铺满,用哪一张按 `layouts.md` 里该 archetype 的 `background` 字段取,不要混用。')
1875
+ L.append('- 内容页的背景由该页型的 `background` 字段指定,整幅铺满。')
810
1876
  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 条这套模板特有的硬规则(看过联系表之后写,例如主色只许用在哪类元素)。',
1877
+ # 点名哪几个页型带 logo。只说「位置去 slots 里查」的话,读起来像是每个页型都有
1878
+ # 这个槽、去查就行——而「不放」是靠该页型 slots 里缺这一项来表达的,要消费端
1879
+ # 自己做否定式推理才能得出。正面点名比让它去发现缺席可靠。
1880
+ with_logo = [a['name'] for a in archetypes
1881
+ if any(str(s.get('asset') or '') == logo['id'] for s in a['slots'])]
1882
+ L.append('- `%s` 只出现在这些页型上:%s;其余页型不放。位置取该页型 `slots` '
1883
+ '`role: logo` 那一项的 `box`,原样使用该文件、保持原比例。'
1884
+ % (logo['id'], '、'.join('`%s`' % x for x in with_logo) or '(无)'))
1885
+ L += ['- 坐标、字号、色值、资产位置以 %s 为准;本文件的 Colors / Typography 是可用值的清单。'
1886
+ % sidecar,
1887
+ '- 色板里没有绿/红这类语义色时,正负用同族颜色的深浅或透明度区分——先看 Colors 段确认。',
1888
+ '- 本包里的数值就是普查结果,照用即可,无需重新统计颜色、字体或版式。',
1889
+ '- 风格包以文本形式(zip 摘要等)到手时,直接用摘要里 design.md / layouts.md 的文本。',
820
1890
  '', '## Exceptions', '']
821
1891
  if exceptions:
822
1892
  L += ['- ' + e for e in exceptions]
@@ -828,31 +1898,57 @@ def emit_body(d, tokens, fonts, roles, assets, archetypes, exceptions, ldir):
828
1898
 
829
1899
  def emit_brief(d, ctx, ldir):
830
1900
  (tokens, rest, fonts, roles, assets, rejected, todos, archetypes, cands, sheet,
831
- leftover, lsheet) = ctx
1901
+ leftover, lsheet, sheet_n) = ctx
832
1902
  canvas = d['canvas']['px']
833
- L = ['# 抽取简报(草案已生成,读完这一页就能改)', '',
1903
+ L = ['# 抽取简报(第 1/3 步产物;改完草案跑 package.py 出包)', '',
834
1904
  '源:`%s` 画布 %dx%d %d 页 / %d 版式 主题 %s form=%s'
835
1905
  % (d['source']['filename'], canvas[0], canvas[1], d['counts']['slides'],
836
1906
  d['counts']['layouts'], d['theme_topology']['themes'],
837
1907
  d['form_hint']['form']), '',
838
1908
  '## 待判断(草案里已标 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:
1909
+ # 待判断清单从草案实时扫 TODO 生成,不写死:写死的清单会和草案对不上——
1910
+ # 既漏掉后加的段(模型读到一半才发现还有活),又在草案已预填时还催人去填。
1911
+ HINT = {'manifest.yaml': '看两张图定气质',
1912
+ 'layouts.yaml': '看 layout-sheet.png;layouts 段本身不要动',
1913
+ 'body.md': 'Colors 用途列草案已填好,觉得不对再改'}
1914
+ for fn in ('manifest.yaml', 'body.md', 'layouts.yaml', 'frontmatter.yaml'):
1915
+ path = os.path.join(ldir, fn)
1916
+ if not os.path.exists(path):
1917
+ continue
1918
+ keys = []
1919
+ for line in open(path, encoding='utf-8'):
1920
+ if 'TODO' not in line:
1921
+ continue
1922
+ m = re.match(r'\s*[-#]?\s*([\w-]+):', line)
1923
+ keys.append(m.group(1) if m else line.strip()[:24])
1924
+ if not keys:
1925
+ continue
1926
+ seen, uniq = set(), []
1927
+ for k in keys:
1928
+ if k not in seen:
1929
+ seen.add(k)
1930
+ uniq.append(k)
1931
+ hint = HINT.get(fn)
1932
+ L.append('- `%s` %d 处:%s%s'
1933
+ % (fn, len(keys), '、'.join(uniq[:6]) + ('…' if len(uniq) > 6 else ''),
1934
+ '(%s)' % hint if hint else ''))
1935
+ for t in todos:
844
1936
  L.append('- ' + t)
845
1937
  L += ['', '## 联系表(一次看完所有候选图)', '',
846
- '`l-out/contact-sheet.png` —— 编号对应下表;看完再决定 logo / 封面归属。' if sheet
1938
+ '`l-out/contact-sheet.png` —— 图格编号对应下表前几行;看完再决定 logo / 封面归属。' if sheet
847
1939
  else '(Pillow 不可用,未生成联系表;逐张看 `media-out/`)', '',
848
1940
  '| # | 文件 | 尺寸 | 出现 | 满屏 | 页 | 草案判定 |', '|---|---|---|---|---|---|---|']
849
1941
  decided = {a['src']['file']: a['id'] for a in assets}
850
1942
  why = {c['file']: r for c, r in rejected}
851
- for i, c in enumerate(cands[:12], 1):
1943
+ for i, c in enumerate(cands, 1):
852
1944
  L.append('| %d | `%s` | %sx%s | %d | %s | %s | %s |' % (
853
1945
  i, c['file'], c['probe'].get('w') or '?', c['probe'].get('h') or '?', c['n'],
854
1946
  'Y' if c['fullscreen'] else '', ','.join(map(str, c['slides'][:6])) or 'layout',
855
1947
  decided.get(c['file']) or ('✗ ' + why.get(c['file'], '未采纳'))))
1948
+ if len(cands) > sheet_n:
1949
+ L.append('')
1950
+ L.append('拼版图只含前 %d 张(第 %d 行之后的没有图格)。要看后面某张,'
1951
+ '按文件名直接看 `media-out/`。' % (sheet_n, sheet_n))
856
1952
  L += ['', '## 颜色(草案 token 已写进 frontmatter.yaml)', '',
857
1953
  '| token | hex | 出现 |', '|---|---|---|']
858
1954
  for name, r in tokens:
@@ -898,20 +1994,94 @@ def main(argv=None):
898
1994
  ldir = os.path.join(outdir, 'l-out')
899
1995
  os.makedirs(ldir, exist_ok=True)
900
1996
 
901
- tokens, rest, _ = draft_colors(d)
1997
+ all_shapes = json.load(open(os.path.join(outdir, 'ref', 'shapes.json'),
1998
+ encoding='utf-8'))['shapes']
1999
+ cusage = color_usage(all_shapes, d)
2000
+ tokens, rest, rows = draft_colors(d, cusage)
902
2001
  fonts = draft_fonts(d)
903
2002
  archetypes, pages, leftover = draft_layouts(d, outdir)
2003
+ # 封面底图:form=3 的页型键就是角色名(cover/section/...),直接按名字取。
2004
+ # form=2 按样张聚类,键是 layout-1..N,永远匹配不上 'cover'——实测 vo-lite 因此
2005
+ # 一张 role: cover 都没有,封面主视觉被标成 bg-content-1,消费端拿不到封面资产,
2006
+ # design.md 的「封面底图必用 cover 资产」这条硬规则无从满足。回退到覆盖第 1 页的
2007
+ # 那个页型:deck 的第 1 页就是封面,这是版式无关的事实。
904
2008
  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)
2009
+ if not cover_media:
2010
+ cover_media = next((a['bg_raw'] for a in archetypes
2011
+ if 1 in (a.get('pages') or ())), None)
2012
+ exported_media = {m['media'] for m in d.get('media', []) if m.get('exported')}
2013
+ bg_needed = {a['bg_raw'] for a in archetypes if a['bg_raw'] in exported_media}
2014
+ bg_under = {p['no']: p.get('rendered_bg') or p['bg_media'] for p in pages}
2015
+ assets, rejected, todos, alias, pool = draft_assets(d, outdir, bg_needed, cover_media, bg_under)
908
2016
  media_to_asset = {a['src']['media']: a['id'] for a in assets}
2017
+ for m, w in (alias or {}).items():
2018
+ if w in media_to_asset:
2019
+ media_to_asset.setdefault(m, media_to_asset[w])
2020
+
2021
+ # 版式里那些贴在装饰容器上的小图(图标托底圆里的图标之类):不进包的话,消费端只看到
2022
+ # 一个空圆,只能自己编图形。它们是版式的一部分,按 icon 收进来。
2023
+ ICON_CAP = 12
2024
+ ICON_BUDGET = 3 * 1024 * 1024 # 图标是小件,占包体不该超过背景
2025
+ cW, cH = d['canvas']['px']
2026
+ icon_i, icon_bytes = 0, 0
2027
+ for a in archetypes:
2028
+ for s in a['slots']:
2029
+ m = s.get('media')
2030
+ if not m or media_to_asset.get(m) or media_to_asset.get(alias.get(m, m)):
2031
+ continue
2032
+ c = pool.get(alias.get(m, m)) or pool.get(m)
2033
+ if not c or not c.get('out') or icon_i >= ICON_CAP:
2034
+ continue
2035
+ if icon_bytes + (c.get('bytes') or 0) > ICON_BUDGET:
2036
+ continue
2037
+ if s['box'][2] > cW * 0.25 or s['box'][3] > cH * 0.25:
2038
+ continue # 不是图标,是内容配图,交给消费端自备
2039
+ icon_i += 1
2040
+ icon_bytes += c.get('bytes') or 0
2041
+ aid = 'icon-%d' % icon_i
2042
+ assets.append({'id': aid, 'kind': 'icon', 'role': None, 'src': c, 'use_full': False})
2043
+ media_to_asset[c['media']] = aid
2044
+ media_to_asset[m] = aid
2045
+ dropped_slots = []
909
2046
  for a in archetypes:
910
2047
  a['bg'] = media_to_asset.get(a['bg_raw'])
2048
+ # 版式自带的图片元素:映射到资产 id。映射不到时**保留槽位但不写 asset**——
2049
+ # 删掉整条槽,消费端看到的是一个没有图标的托底圆,和图标不进包是同一个失败模式,
2050
+ # 而且它连「这里本来有东西」都不知道。
2051
+ keep = []
2052
+ for s in a['slots']:
2053
+ if s.get('media'):
2054
+ aid = media_to_asset.get(s['media'])
2055
+ if not aid:
2056
+ s['role'] = 'icon'
2057
+ s.pop('media', None)
2058
+ dropped_slots.append((a['name'], s['box']))
2059
+ keep.append(s)
2060
+ continue
2061
+ s['asset'] = aid
2062
+ # role 跟着资产走:图标槽写成 logo 会让消费端把它当品牌标识,每页都摆一个
2063
+ s['role'] = next((x['kind'] for x in assets if x['id'] == aid), s['role'])
2064
+ keep.append(s)
2065
+ a['slots'] = keep
911
2066
  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'))
2067
+ slot_added = cover_slot_colors(tokens, archetypes, rows, cusage)
2068
+ # 进包的资产必须全部上联系表。BRIEF L 层「看联系表确认 logo / 封面归属」,
2069
+ # 表上没有的东西它只会从表里另挑一张顶上去。封面主视觉按定义只出现在封面那一页
2070
+ # (n=1),按出现次数排序时排在最末——实测被 cands[:12] 截掉,模型于是把 bg-cover
2071
+ # 换成了已经在用的内容页背景,封面与内容页字节相同,封面主视觉整个丢失。
2072
+ decided_c = sorted([a['src'] for a in assets], key=lambda c: (-c['n'], c['file']))
2073
+ other_c = sorted([c for c, _ in rejected], key=lambda c: (-c['n'], c['file']))
2074
+ cands, seen_file = [], set()
2075
+ for c in decided_c + other_c: # 同一张图可能有多条候选记录(不同位置各一条)
2076
+ if c['file'] not in seen_file:
2077
+ seen_file.add(c['file'])
2078
+ cands.append(c)
2079
+ # 表列全部候选,拼版图只拼前几张:两者成本差着数量级。表是文字,60 行也几乎不占
2080
+ # 上下文,却是模型唯一能知道「存在这张图」的地方——名额砍在这里,被误判成未采纳的
2081
+ # 图连翻案的机会都没有。拼版图是要「看」的,60 格就是 4 列×15 行、降采样后每格
2082
+ # 糊成一团,那个上限才有意义。
2083
+ sheet_items = cands[:max(SHEET_CAP, len(decided_c))]
2084
+ sheet = contact_sheet(outdir, sheet_items, os.path.join(ldir, 'contact-sheet.png'))
915
2085
  lsheet = layout_sheet(outdir, archetypes, os.path.join(ldir, 'layout-sheet.png'))
916
2086
 
917
2087
  anchors = draft_anchors(d, tokens, fonts, roles, assets, archetypes)
@@ -919,25 +2089,79 @@ def main(argv=None):
919
2089
  for c, why in rejected:
920
2090
  if '近全透明' in why:
921
2091
  gaps.append('母版/版式里的 %s 是%s,不是设计资产,任何情况下不要当背景用。' % (c['file'], why))
922
- for f in fonts[:2]:
923
- if len(f['stack']) > 1:
2092
+ elif '不是背景' in why:
2093
+ gaps.append('%s 在模板里铺满整页,但%s;那几页的真实背景是幻灯片自身的底色,'
2094
+ '需要时按 Colors 里的 surface 铺纯色。' % (c['file'], why))
2095
+ by_kind = {}
2096
+ for kind, kept, total, advice, where in _TRUNCATED:
2097
+ e = by_kind.setdefault(kind, {'kept': 0, 'total': 0, 'advice': advice, 'where': []})
2098
+ e['kept'] += kept
2099
+ e['total'] += total
2100
+ if where:
2101
+ e['where'].append(where)
2102
+ for kind, e in by_kind.items():
2103
+ at = ('(%s)' % '、'.join(e['where'][:6])) if e['where'] else ''
2104
+ gaps.append('%s%s按名额截断:普查到 %d 个,包内留了 %d 个%s。'
2105
+ % (kind, at, e['total'], e['kept'],
2106
+ ';' + e['advice'] if e['advice'] else ''))
2107
+ if dropped_slots:
2108
+ gaps.append('这些图标槽的源图没有随包分发(超出图标配额或不适合进包):%s。'
2109
+ '槽位保留了坐标,渲染时留空或用中性占位,不要自造图形去填。'
2110
+ % '、'.join('%s %s' % (n, b) for n, b in dropped_slots[:8]))
2111
+ # 「没命中映射表」不等于「装不上」:降级目标本身(Noto Sans SC 之类)和 Office 出厂体
2112
+ # 都不在 match 列里,但它们本来就可用。真正危险的是**既没命中、又不是已知可用字体**的
2113
+ # 那种——design.md 的字体栈里留着一个消费端装不上的商业字体名,且没有任何降级说明。
2114
+ web_ok = {norm(x) for fam in parse_fallback_table() for x in fam['fallback']}
2115
+ web_ok |= {norm(x.strip().strip('"')) for x in SYS_FALLBACK.split(',')}
2116
+ for f in fonts:
2117
+ if f.get('mapped'):
924
2118
  gaps.append('源字体 %s 无 web 授权源,已按 font-fallback 表降级到 %s;字形细节与原稿有差异。'
925
2119
  % (f['names'][0], f['stack'][1]))
2120
+ elif norm(f['names'][0]) in OFFICE_DEFAULT_FONTS_NORM:
2121
+ gaps.append('%s 是 Office 出厂字体,多半是模板里没清干净的残留而非设计选型;'
2122
+ '按正文/标题的实际气质挑替代体,不要照抄它。' % f['names'][0])
2123
+ elif norm(f['names'][0]) not in web_ok:
2124
+ gaps.append('源字体 %s 不在 font-fallback 表里,字体栈只有原名,消费端很可能装不上;'
2125
+ '按气质挑一个有 web 分发源的近似体补进栈,不要照抄原名。' % f['names'][0])
2126
+ nosize = [(a['name'], s['box']) for a in archetypes for s in a['slots']
2127
+ if not s.get('asset') and not s.get('size')]
2128
+ if nosize:
2129
+ gaps.append('这些文字槽在源文件任何层级都没有字号声明(都不是占位符,是普通文本框,'
2130
+ '继承源是 presentation.xml 的 defaultTextStyle,本抽取按约定不解继承链):'
2131
+ '%s。用 typography 里最接近的档位,不要自造新档。'
2132
+ % '、'.join('%s %s' % (n, b) for n, b in nosize[:6]))
2133
+
926
2134
  if leftover:
927
2135
  exceptions.append('源 deck 第 %s 页是单页孤例,没有归纳成 archetype;需要类似构图时按最接近的页型改。'
928
2136
  % '、'.join(map(str, leftover)))
929
2137
 
930
2138
  emit_manifest(d, assets, ldir)
931
2139
  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)
2140
+ # 每张背景量一次局部对比度,作为「哪里不能压文字」的客观依据摆进判断单。
2141
+ # 只报测到的数,不替人填 avoid——哪块算主体、要不要避让,是看图才能定的。
2142
+ busy_hints = {}
2143
+ for a in assets:
2144
+ if a['kind'] != 'background' or not a['src'].get('out'):
2145
+ continue
2146
+ r = bg_busy_map(os.path.join(outdir, a['src']['out']), (cW, cH))
2147
+ if r:
2148
+ busy_hints[a['id']] = r
2149
+ facts, recipes = structure_facts(archetypes, d, all_shapes)
2150
+ for a in archetypes:
2151
+ a['flow'] = draft_flow(a, facts.get(a['name']) or {}, (cW, cH))
2152
+ emit_layouts(archetypes, ldir, busy_hints, facts, recipes)
2153
+ emit_body(d, tokens, fonts, roles, assets, archetypes, exceptions, cusage, ldir)
934
2154
  emit_brief(d, (tokens, rest, fonts, roles, assets, rejected, todos, archetypes, cands, sheet,
935
- leftover, lsheet), ldir)
2155
+ leftover, lsheet, len(sheet_items)), ldir)
936
2156
 
937
- print('草案就绪 -> %s' % ldir)
938
- print(' 资产 %d(%s) 版式 %d 色 %d 字体 %d'
2157
+ # 这几行落在模型判断「skill 是不是做完了」的那一刻。只报数就会被读成「包已生成」,
2158
+ # 于是判断和打包整段被跳过,deck 拿不到任何版式坐标。所以这里报进度与下一条命令。
2159
+ print('第 1/3 步完成,判断单草案 -> %s' % ldir)
2160
+ print(' 待你确认:资产 %d(%s) 版式 %d 色 %d 字体 %d'
939
2161
  % (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')
2162
+ print(' 2 步 读 l-out/BRIEF.md contact-sheet.png,改掉草案里的 TODO')
2163
+ print(' 第 3 步 package.py 产出 design.md + layouts.md —— deck 的版式坐标只从这两份读')
2164
+ sys.stdout.flush()
941
2165
  return 0
942
2166
 
943
2167