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