@lark-apaas/coding-steering 0.1.66 → 0.1.68-alpha.20261016070747
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 +21 -19
- package/package.json +6 -6
- package/steering/design-html/skills/animated-video/SKILL.md +2 -2
- package/steering/design-html/skills/charts/SKILL.md +8 -60
- package/steering/design-html/skills/{data-viz → data-report}/SKILL.md +9 -65
- package/steering/design-html/skills/frontend-design/SKILL.md +2 -2
- package/steering/design-html/skills/hi-fi-design/SKILL.md +1 -1
- package/steering/design-html/skills/interactive-prototype/SKILL.md +2 -19
- package/steering/design-html/skills/{slide-deck → make-a-deck}/SKILL.md +11 -35
- package/steering/design-html/skills/{visual-report → visual-exposure}/SKILL.md +2 -24
- package/steering/design-html/skills_local/creative-design/agents/assets/vision-probe.png +0 -0
- package/steering/design-html/skills_local/creative-design/agents/fork-verifier-agent.md +71 -0
- package/steering/design-html/skills_local/creative-design/agents/vision-probe-agent.md +41 -0
- package/steering/design-html/skills_local/creative-design/assets/index.html +27 -0
- package/steering/design-html/skills_local/creative-design/references/aily.md +39 -0
- package/steering/design-html/skills_local/creative-design/references/animated-video.md +35 -0
- package/steering/design-html/skills_local/creative-design/references/charts.md +165 -0
- package/steering/design-html/skills_local/creative-design/references/claude.md +36 -0
- package/steering/design-html/skills_local/creative-design/references/codex.md +32 -0
- package/steering/design-html/skills_local/creative-design/references/data-report.md +108 -0
- package/steering/{nestjs-react-fullstack/skills/design-guide → design-html/skills_local/creative-design}/references/frontend-design.md +26 -21
- package/steering/design-html/skills_local/creative-design/references/hi-fi-design.md +32 -0
- package/steering/design-html/skills_local/creative-design/references/interactive-prototype.md +24 -0
- package/steering/design-html/skills_local/creative-design/references/make-a-deck.md +133 -0
- package/steering/design-html/skills_local/creative-design/references/visual-exposure.md +82 -0
- package/steering/design-html/skills_local/creative-design/references/wireframe.md +14 -0
- package/steering/design-html/skills_local/creative-design/skill.md +273 -0
- package/steering/design-html/skills_local/creative-design/starter-components/android-frame.jsx +188 -0
- package/steering/design-html/skills_local/creative-design/starter-components/animations.jsx +773 -0
- package/steering/design-html/skills_local/creative-design/starter-components/browser-window.jsx +122 -0
- package/steering/design-html/skills_local/creative-design/starter-components/deck-stage.js +2483 -0
- package/steering/design-html/skills_local/creative-design/starter-components/design-canvas.jsx +1432 -0
- package/steering/design-html/skills_local/creative-design/starter-components/ios-frame.jsx +270 -0
- package/steering/design-html/skills_local/creative-design/starter-components/macos-window.jsx +197 -0
- package/steering/design-html/skills_local/creative-design/starter-components/tweaks-panel.jsx +752 -0
- package/steering/nestjs-react-fullstack/skills/app-init-feasibility-guide/SKILL.md +0 -5
- package/steering/nestjs-react-fullstack/skills/authn-guide/SKILL.md +0 -6
- package/steering/nestjs-react-fullstack/skills/authz-guide/SKILL.md +10 -43
- package/steering/nestjs-react-fullstack/skills/authz-guide/references/dynamic-permission-guide.md +1 -1
- package/steering/nestjs-react-fullstack/skills/authz-guide/references/runtime-role-controller-spec.md +8 -6
- package/steering/nestjs-react-fullstack/skills/authz-guide/references/sdk-examples.md +1 -6
- package/steering/nestjs-react-fullstack/skills/authz-guide/references/sdk-types.md +5 -8
- package/steering/nestjs-react-fullstack/skills/client-add-aily-web-chat/SKILL.md +139 -0
- package/steering/nestjs-react-fullstack/skills/client-builtins-file-storage-service/SKILL.md +116 -45
- package/steering/nestjs-react-fullstack/skills/client-builtins-user-service/SKILL.md +2 -15
- package/steering/nestjs-react-fullstack/skills/code-fix/SKILL.md +9 -15
- package/steering/nestjs-react-fullstack/skills/coding-guide/SKILL.md +102 -353
- package/steering/nestjs-react-fullstack/skills/contacts-service/SKILL.md +11 -88
- package/steering/nestjs-react-fullstack/skills/feishu/SKILL.md +269 -0
- package/steering/nestjs-react-fullstack/skills/feishu/references/approval.md +214 -0
- package/steering/nestjs-react-fullstack/skills/feishu/references/attendance.md +163 -0
- package/steering/nestjs-react-fullstack/skills/feishu/references/bitable.md +311 -0
- package/steering/nestjs-react-fullstack/skills/feishu/references/calendar.md +190 -0
- package/steering/nestjs-react-fullstack/skills/feishu/references/contacts.md +160 -0
- package/steering/nestjs-react-fullstack/skills/feishu/references/doc.md +257 -0
- package/steering/nestjs-react-fullstack/skills/feishu/references/drive.md +104 -0
- package/steering/nestjs-react-fullstack/skills/feishu/references/events.md +199 -0
- package/steering/nestjs-react-fullstack/skills/feishu/references/id-convert.md +128 -0
- package/steering/nestjs-react-fullstack/skills/feishu/references/messaging.md +207 -0
- package/steering/nestjs-react-fullstack/skills/feishu/references/oauth.md +165 -0
- package/steering/nestjs-react-fullstack/skills/feishu/references/perm.md +91 -0
- package/steering/nestjs-react-fullstack/skills/feishu/references/wiki.md +165 -0
- package/steering/nestjs-react-fullstack/skills/openapi-guide/SKILL.md +0 -44
- package/steering/nestjs-react-fullstack/skills/plugin-guide/SKILL.md +541 -179
- package/steering/nestjs-react-fullstack/skills/plugin-guide/references/plugin-coding-guide.md +17 -199
- package/steering/nestjs-react-fullstack/skills/plugin-guide/references/table.md +14 -30
- package/steering/nestjs-react-fullstack/skills/server-builtins-file-storage-service/SKILL.md +177 -210
- package/steering/nestjs-react-fullstack/{skills_common → skills}/trigger-guide/SKILL.md +1 -5
- package/steering/nestjs-react-fullstack/skills_common/user-identity/SKILL.md +40 -33
- package/steering/nestjs-react-fullstack/skills_local/authz-guide/SKILL.md +5 -38
- package/steering/nestjs-react-fullstack/skills_local/authz-guide/references/runtime-role-controller-spec.md +8 -6
- package/steering/nestjs-react-fullstack/skills_local/authz-guide/references/sdk-examples.md +1 -6
- package/steering/nestjs-react-fullstack/skills_local/authz-guide/references/sdk-types.md +5 -8
- package/steering/nestjs-react-fullstack/skills_local/client-builtins-user-service/SKILL.md +0 -2
- package/steering/nestjs-react-fullstack/skills_local/code-fix/SKILL.md +2 -8
- package/steering/nestjs-react-fullstack/skills_local/coding-guide/SKILL.md +81 -145
- package/steering/nestjs-react-fullstack/skills_local/plugin-guide/SKILL.md +3 -14
- package/steering/nestjs-react-fullstack/skills_local/plugin-guide/references/plugin-coding-guide.md +16 -150
- package/steering/vite-react/skills/plugin-guide/SKILL.md +6 -8
- package/steering/vite-react/skills/react-three-fiber/SKILL.md +0 -5
- package/steering/vite-react/tech.md +0 -3
- package/steering/design-html/skills/mini-game/SKILL.md +0 -71
- package/steering/design-html/skills/mini-game/references/three-js.md +0 -54
- package/steering/design-html/skills/pptx-style-extract/SKILL.md +0 -157
- package/steering/design-html/skills/pptx-style-extract/font-fallback.yaml +0 -129
- package/steering/design-html/skills/pptx-style-extract/scripts/census.py +0 -967
- package/steering/design-html/skills/pptx-style-extract/scripts/check_v2.py +0 -1052
- package/steering/design-html/skills/pptx-style-extract/scripts/draft.py +0 -3483
- package/steering/design-html/skills/pptx-style-extract/scripts/export_consumer_md.py +0 -75
- package/steering/design-html/skills/pptx-style-extract/scripts/export_consumer_zip.py +0 -175
- package/steering/design-html/skills/pptx-style-extract/scripts/extract.py +0 -1287
- package/steering/design-html/skills/pptx-style-extract/scripts/ooxml.py +0 -716
- package/steering/design-html/skills/pptx-style-extract/scripts/package.py +0 -1946
- package/steering/design-html/skills/pptx-style-extract/scripts/parts.py +0 -480
- package/steering/design-html/skills/pptx-style-extract/scripts/query.py +0 -557
- package/steering/design-html/skills/pptx-style-extract/scripts/render_pages.py +0 -687
- package/steering/design-html/skills/pptx-style-extract/scripts/test_asset_judgment_package.py +0 -556
- package/steering/design-html/skills/pptx-style-extract/scripts/test_background_composite.py +0 -364
- package/steering/design-html/skills/pptx-style-extract/scripts/test_color_contract.py +0 -60
- package/steering/design-html/skills/pptx-style-extract/scripts/test_design_consumer_contract.py +0 -76
- package/steering/design-html/skills/pptx-style-extract/scripts/test_flow_layout_contract.py +0 -528
- package/steering/design-html/skills/pptx-style-extract/scripts/test_layout_css.py +0 -1814
- package/steering/design-html/skills/pptx-style-extract/scripts/test_logo_scope.py +0 -600
- package/steering/design-html/skills/pptx-style-extract/scripts/test_rounded_contract.py +0 -112
- package/steering/design-html/skills/pptx-style-extract/scripts/test_text_role_contract.py +0 -315
- package/steering/design-html/skills/pptx-style-extract/scripts/verify_font.py +0 -68
- package/steering/design-html/skills/pptx-style-extract/scripts/verify_layout_assets.py +0 -421
- package/steering/design-html/skills/pptx-style-extract/scripts/verify_logo_scope.py +0 -12
- package/steering/design-html/skills/pptx-style-extract/v2-format-spec.md +0 -205
- package/steering/design-html/skills/social-card/SKILL.md +0 -263
- package/steering/nestjs-react-fullstack/skills/connections-sdk/SKILL.md +0 -202
- package/steering/nestjs-react-fullstack/skills/design-guide/SKILL.md +0 -190
- package/steering/nestjs-react-fullstack/skills/design-guide/references/broadsheet.md +0 -313
- package/steering/nestjs-react-fullstack/skills/design-guide/references/claude-editorial-research.md +0 -375
- package/steering/nestjs-react-fullstack/skills/design-guide/references/crimson-frosted-glass.md +0 -221
- package/steering/nestjs-react-fullstack/skills/design-guide/references/cybernetic-vault-terminal.md +0 -74
- package/steering/nestjs-react-fullstack/skills/design-guide/references/dashboard.md +0 -234
- package/steering/nestjs-react-fullstack/skills/design-guide/references/digital-e-guide.md +0 -349
- package/steering/nestjs-react-fullstack/skills/design-guide/references/finance-report.md +0 -169
- package/steering/nestjs-react-fullstack/skills/design-guide/references/flowbite.md +0 -179
- package/steering/nestjs-react-fullstack/skills/design-guide/references/handwritten-sketch.md +0 -215
- package/steering/nestjs-react-fullstack/skills/design-guide/references/industry.md +0 -348
- package/steering/nestjs-react-fullstack/skills/design-guide/references/metabase.md +0 -226
- package/steering/nestjs-react-fullstack/skills/design-guide/references/minimal-jade.md +0 -205
- package/steering/nestjs-react-fullstack/skills/design-guide/references/nebula-crimson.md +0 -306
- package/steering/nestjs-react-fullstack/skills/design-guide/references/nexuscore-analytics.md +0 -74
- package/steering/nestjs-react-fullstack/skills/design-guide/references/organic-minimalism.md +0 -253
- package/steering/nestjs-react-fullstack/skills/design-guide/references/pm-spec.md +0 -234
- package/steering/nestjs-react-fullstack/skills/design-guide/references/pop-art.md +0 -272
- package/steering/nestjs-react-fullstack/skills/design-guide/references/sap-fiori-horizon.md +0 -154
- package/steering/nestjs-react-fullstack/skills/design-guide/references/token-mapping.md +0 -68
- package/steering/nestjs-react-fullstack/skills/design-guide/references/warm-elegance.md +0 -217
- package/steering/nestjs-react-fullstack/skills/design-guide/references/wild-orange.md +0 -203
- package/steering/nestjs-react-fullstack/skills/nestjs-cache/SKILL.md +0 -254
- package/steering/nestjs-react-fullstack/skills/raw-sql-boundary-audit/SKILL.md +0 -63
- package/steering/nestjs-react-fullstack/skills_common/mcp-guide/SKILL.md +0 -78
- package/steering/nestjs-react-fullstack/skills_common/mcp-guide/assets/eslint.mcp-ui.config.cjs +0 -19
- package/steering/nestjs-react-fullstack/skills_common/mcp-guide/assets/ui-tsconfig.json +0 -19
- package/steering/nestjs-react-fullstack/skills_common/mcp-guide/references/client-onboarding.md +0 -82
- package/steering/nestjs-react-fullstack/skills_common/mcp-guide/references/debugging.md +0 -81
- package/steering/nestjs-react-fullstack/skills_common/mcp-guide/references/mcp-apps.md +0 -197
- package/steering/nestjs-react-fullstack/skills_common/mcp-guide/references/tool-authoring.md +0 -249
- package/steering/nestjs-react-fullstack/skills_common/server-contacts-contract/SKILL.md +0 -19
|
@@ -1,1946 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env python3
|
|
2
|
-
"""S11 打包器:把「阶段一抽取产物 + L 层判断单」机械组装成风格包 v2。
|
|
3
|
-
|
|
4
|
-
python3 package.py <stage1-outdir> <l-out-dir> <pack-out-dir> [选项]
|
|
5
|
-
|
|
6
|
-
--check-v1 <path> 顺带跑 v1 门禁(需要外部 check_v1.py 路径)
|
|
7
|
-
--style-name <name> 覆盖 manifest 里的 name(包目录名仍取 pack-out-dir)
|
|
8
|
-
--force pack-out-dir 已存在且非空时照样写
|
|
9
|
-
|
|
10
|
-
本脚本零判断:所有语义来自 <l-out-dir>,所有数值来自 <stage1-outdir>/extract.json。
|
|
11
|
-
它只做四件机械事——排键序、拷资产、算审计数据、跑门禁。
|
|
12
|
-
|
|
13
|
-
================================================================================
|
|
14
|
-
L 层判断单 schema(<l-out-dir> 四个文件,这段就是填写说明书)
|
|
15
|
-
================================================================================
|
|
16
|
-
|
|
17
|
-
本脚本自带极简 YAML 读取器,只认下面这些写法,**不要用锚点/别名/复杂嵌套流**:
|
|
18
|
-
key: 标量 标量可加引号(会原样保留到产物里)
|
|
19
|
-
key: [a, b, c] 流式列表
|
|
20
|
-
key: | 或 key: > 块标量(`|` 保留换行,`>` 折成一行)
|
|
21
|
-
key: 后跟缩进块 —— 对 frontmatter.yaml / layouts.yaml
|
|
22
|
-
... 这类「原样透传」的键,块内文本**逐字节照搬**进产物,
|
|
23
|
-
所以缩进/引号/注释请按最终想要的样子写
|
|
24
|
-
|
|
25
|
-
--------------------------------------------------------------------------------
|
|
26
|
-
1) manifest.yaml —— 包身份 + 资产映射(唯一需要本脚本解析结构的文件)
|
|
27
|
-
--------------------------------------------------------------------------------
|
|
28
|
-
|
|
29
|
-
version: alpha # 可选,默认 alpha
|
|
30
|
-
name: azure-mist-deck # 必填,包名(英文 kebab)
|
|
31
|
-
name_zh: 碧空雾面 # 可选
|
|
32
|
-
description: > # 可选,一段话,会折成单行进 frontmatter
|
|
33
|
-
整幅铺满带颗粒感的淡蓝雾面底图……
|
|
34
|
-
themes: [dark, light] # 可选;单主题包不写
|
|
35
|
-
default-theme: dark # themes 长度 >1 时必填(V2-13)
|
|
36
|
-
theme-mechanism: "……" # 可选,进 ref/audit.yaml(不进 design.md)
|
|
37
|
-
color-confidence: {level: medium, note: "……"} # 可选,进 ref/audit.yaml
|
|
38
|
-
assets: # 可选;无资产包可整段省略
|
|
39
|
-
- id: bg-cover # 必填。命名规则 <kind 前缀>-<语义名>,
|
|
40
|
-
# logo- / slogan- / bg- / texture- / icon-
|
|
41
|
-
source_media: <原图文件名> # media-out/ 里的**原图**文件名(不是压缩版)
|
|
42
|
-
kind: background # logo|slogan|background|texture|icon
|
|
43
|
-
role: cover # background/icon 用;封闭枚举见规范 §2
|
|
44
|
-
theme: dark # 双主题包按需
|
|
45
|
-
on-bg: light # logo/slogan 用
|
|
46
|
-
mark: lockup # logo/slogan 用;**自动进 audit.yaml**
|
|
47
|
-
use_full: true # true = 同时落原图为 <name>@full.<ext>
|
|
48
|
-
recipe: "linear-gradient(…)" # 可选,CSS 重绘配方
|
|
49
|
-
confidence: high # 可选,默认 high;**自动进 audit.yaml**
|
|
50
|
-
- id: bg-surface # 纯色背景:不给 source_media,给 color
|
|
51
|
-
kind: background
|
|
52
|
-
role: content
|
|
53
|
-
color: "{colors.surface}"
|
|
54
|
-
|
|
55
|
-
asset_vision_groups: # 抽取草案专用,打包后不进入消费包
|
|
56
|
-
- id: vision-1
|
|
57
|
-
source_media: [mark.png, ornament.png]
|
|
58
|
-
visual_kind: decorative # FaaS 枚举;同组默认,可被 asset_decisions 覆盖
|
|
59
|
-
|
|
60
|
-
asset_decisions: # 可选:单图覆盖;旧版 decision 仍兼容
|
|
61
|
-
- source_media: chart.png
|
|
62
|
-
visual_kind: chart
|
|
63
|
-
|
|
64
|
-
说明:`boxes` / `aspect` / `canvas-source` **不要填**——脚本按 source_media 从
|
|
65
|
-
extract.json 的 images[] 直接取,写进 ref/audit.yaml。
|
|
66
|
-
|
|
67
|
-
derived: # 可选:推导值豁免声明(数值可追溯机检用)
|
|
68
|
-
- value: "1.05" # 按字面值豁免:产物里出现的该值放行
|
|
69
|
-
reason: "CJK 行高转译"
|
|
70
|
-
- value: "#5A5A5A"
|
|
71
|
-
reason: "白字 70% 不透明度的等效实色"
|
|
72
|
-
- token: light-surface # 按键名豁免:该 token(或其祖先键)下所有值放行
|
|
73
|
-
reason: "材质推导,gaps 已注明"
|
|
74
|
-
rebase_factor: 1.6 # 可选:字号等比上抬倍率;命中「普查值 × 它 ±1px」即放行
|
|
75
|
-
|
|
76
|
-
打包最后一步会校验产物里每个 hex / fontSize / slots.box 是否可追溯:
|
|
77
|
-
hex 命中 color_freq ∪ 形状与背景的填充/描边/渐变 stop 色 ∪ images[].dominant_colors
|
|
78
|
-
(每通道 ±8,采样色有量化误差);fontSize 命中 text_scale;box 命中 ref/shapes.json
|
|
79
|
-
某形状框 ±2px。命不中又没在 derived 里声明 → FAIL 并给出最近候选。
|
|
80
|
-
|
|
81
|
-
--------------------------------------------------------------------------------
|
|
82
|
-
2) frontmatter.yaml —— L 层判断产物,原样进 design.md frontmatter
|
|
83
|
-
--------------------------------------------------------------------------------
|
|
84
|
-
|
|
85
|
-
顶层键只允许这些(缺哪个就不写哪个,脚本按规范 §1 键序重排):
|
|
86
|
-
colors / typography / spacing / rounded / components / omitted
|
|
87
|
-
anchors / gaps / exceptions / safe-area
|
|
88
|
-
写法就是最终 frontmatter 的样子,例如:
|
|
89
|
-
|
|
90
|
-
colors:
|
|
91
|
-
surface: "#FFFFFF"
|
|
92
|
-
primary: "#RRGGBB"
|
|
93
|
-
safe-area:
|
|
94
|
-
content: {top: <px>, right: <px>, bottom: <px>, left: <px>, applies-to: [content]}
|
|
95
|
-
confidence: medium
|
|
96
|
-
|
|
97
|
-
--------------------------------------------------------------------------------
|
|
98
|
-
3) layouts.yaml —— archetype 数据,渲染成 layouts.md
|
|
99
|
-
--------------------------------------------------------------------------------
|
|
100
|
-
|
|
101
|
-
只需一个顶层键 `layouts:`,内容原样透传。**不要写 canvas**——脚本从
|
|
102
|
-
extract.json 取并放成 layouts.md frontmatter 首键(V2-10 / V2-R6)。
|
|
103
|
-
|
|
104
|
-
layouts:
|
|
105
|
-
cover:
|
|
106
|
-
name: "封面"
|
|
107
|
-
role: cover
|
|
108
|
-
background: bg-cover
|
|
109
|
-
slots:
|
|
110
|
-
- {role: title, box: [<x>, <y>, <w>, <h>], type: title,
|
|
111
|
-
css: "<由源模板转译出的 CSS 声明串>"}
|
|
112
|
-
confidence: high
|
|
113
|
-
|
|
114
|
-
可选 `body:` 块标量 —— 追加到 layouts.md frontmatter 之后作为说明正文。
|
|
115
|
-
|
|
116
|
-
--------------------------------------------------------------------------------
|
|
117
|
-
4) body.md —— design.md 正文全文
|
|
118
|
-
--------------------------------------------------------------------------------
|
|
119
|
-
|
|
120
|
-
从 `## Overview` 开始的全部正文(Usage / Colors / Typography / Hard Rules /
|
|
121
|
-
Exceptions……)。脚本原样拼在 frontmatter 之后,不改一个字。
|
|
122
|
-
"""
|
|
123
|
-
import argparse
|
|
124
|
-
from collections import Counter, defaultdict
|
|
125
|
-
import hashlib
|
|
126
|
-
import json
|
|
127
|
-
import os
|
|
128
|
-
import re
|
|
129
|
-
import shutil
|
|
130
|
-
import subprocess
|
|
131
|
-
import sys
|
|
132
|
-
|
|
133
|
-
HERE = os.path.dirname(os.path.abspath(__file__))
|
|
134
|
-
|
|
135
|
-
# 规范 §1 键序:官方白名单 → v1 自造 → v2 自造。审计键(canvas-source /
|
|
136
|
-
# theme-mechanism / color-confidence)按 V2-R6 不进 design.md,故不在此列。
|
|
137
|
-
FRONTMATTER_ORDER = [
|
|
138
|
-
'version', 'name', 'name_zh', 'description',
|
|
139
|
-
'colors', 'typography', 'spacing', 'rounded', 'components', 'omitted',
|
|
140
|
-
'anchors', 'gaps', 'exceptions',
|
|
141
|
-
'themes', 'default-theme', 'assets', 'layouts', 'safe-area',
|
|
142
|
-
]
|
|
143
|
-
# frontmatter.yaml 允许 L 层提供的键(其余由 manifest / 脚本产出)
|
|
144
|
-
L_FRONTMATTER_KEYS = {'colors', 'typography', 'spacing', 'rounded', 'components',
|
|
145
|
-
'omitted', 'anchors', 'gaps', 'exceptions', 'safe-area'}
|
|
146
|
-
# design.md 资产条目只留消费字段,顺序固定(check_v2 V2-R6 把其余判成审计字段)
|
|
147
|
-
ASSET_CONSUMER_FIELDS = ['path', 'url', 'color', 'full', 'kind', 'role',
|
|
148
|
-
'theme', 'on-bg', 'recipe']
|
|
149
|
-
ASSET_AUDIT_FIELDS = ['boxes', 'aspect', 'mark', 'confidence']
|
|
150
|
-
KIND_PREFIX = {'background': 'bg', 'logo': 'logo', 'slogan': 'slogan',
|
|
151
|
-
'texture': 'texture', 'icon': 'icon'}
|
|
152
|
-
# 与 studio_server_faas 的 assetVisualKinds 对齐。它是抽取期视觉分类,不是 v2
|
|
153
|
-
# 消费包的 kind:后者仍只允许 KIND_PREFIX 中的五种资产类型。
|
|
154
|
-
ASSET_VISUAL_KINDS = {
|
|
155
|
-
'logo', 'slogan', 'background', 'texture', 'icon',
|
|
156
|
-
'decorative', 'illustration', 'photo', 'chart', 'screenshot',
|
|
157
|
-
'footer-copyright', 'page-number', 'watermark', 'content-image', 'unknown',
|
|
158
|
-
}
|
|
159
|
-
VISUAL_KIND_TO_DECISION = {
|
|
160
|
-
'logo': 'logo',
|
|
161
|
-
'slogan': 'slogan',
|
|
162
|
-
'background': 'background',
|
|
163
|
-
'texture': 'texture',
|
|
164
|
-
'icon': 'icon',
|
|
165
|
-
'decorative': 'texture',
|
|
166
|
-
'illustration': 'texture',
|
|
167
|
-
'photo': 'content',
|
|
168
|
-
'chart': 'content',
|
|
169
|
-
'screenshot': 'content',
|
|
170
|
-
'content-image': 'content',
|
|
171
|
-
'footer-copyright': 'omit',
|
|
172
|
-
'page-number': 'omit',
|
|
173
|
-
'watermark': 'omit',
|
|
174
|
-
# FaaS 也会把非内容的 unknown 局部图保留为 texture,避免丢掉未能命名的装饰。
|
|
175
|
-
'unknown': 'texture',
|
|
176
|
-
}
|
|
177
|
-
LEGACY_ASSET_DECISIONS = {'content', 'texture', 'logo', 'icon', 'slogan'}
|
|
178
|
-
# 交付包的 ref/ 只留 audit.yaml(人复核数值出处用,几 KB)。
|
|
179
|
-
# 频次原表、聚类原始数据、extract.json、重建图、logo 候选图全部留在 stage1 抽取目录,
|
|
180
|
-
# 不拷进包——规范原本指望「下发时链路剥离」,但链路上没有环节真的剥离,结果
|
|
181
|
-
# 审计材料带着「别读我」一起进消费上下文,还占掉包体的大头。
|
|
182
|
-
REF_CARRY = ()
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
class Fail(SystemExit):
|
|
186
|
-
def __init__(self, msg):
|
|
187
|
-
super().__init__('package.py: %s' % msg)
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
class AssetDecisions(dict):
|
|
191
|
-
"""按素材的默认决定,以及只在对应 slot 生效的实例覆盖。"""
|
|
192
|
-
|
|
193
|
-
def __init__(self, defaults=None, overrides=None, roles=None,
|
|
194
|
-
default_overrides=None, explicit_overrides=None):
|
|
195
|
-
super().__init__(defaults or {})
|
|
196
|
-
self.overrides = overrides or {}
|
|
197
|
-
self.roles = roles or {}
|
|
198
|
-
self.default_overrides = default_overrides or set()
|
|
199
|
-
self.explicit_overrides = explicit_overrides or set()
|
|
200
|
-
|
|
201
|
-
def for_slot(self, source, line, layout_name=None):
|
|
202
|
-
box = source_box(line) or slot_box(line)
|
|
203
|
-
return self.for_scope(source, layout_name, box)
|
|
204
|
-
|
|
205
|
-
def for_scope(self, source, layout_name, box):
|
|
206
|
-
if box is not None:
|
|
207
|
-
for key in ((source, layout_name, box), (source, None, box)):
|
|
208
|
-
if key in self.explicit_overrides:
|
|
209
|
-
return self.overrides[key]
|
|
210
|
-
if source in self.default_overrides:
|
|
211
|
-
return self.get(source)
|
|
212
|
-
if box is not None:
|
|
213
|
-
for key in ((source, layout_name, box), (source, None, box)):
|
|
214
|
-
if key in self.overrides:
|
|
215
|
-
return self.overrides[key]
|
|
216
|
-
return self.get(source)
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
class AssetIds(dict):
|
|
220
|
-
"""同一原图因实例用途不同而落成多个资产时,按最终用途取对应 id。"""
|
|
221
|
-
|
|
222
|
-
def __init__(self, defaults=None, by_decision=None):
|
|
223
|
-
super().__init__(defaults or {})
|
|
224
|
-
self.by_decision = by_decision or {}
|
|
225
|
-
|
|
226
|
-
def for_decision(self, source, decision):
|
|
227
|
-
return self.by_decision.get((source, decision)) or self.get(source)
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
# ------------------------------------------------------------ 极简 YAML 读取
|
|
231
|
-
def split_top_blocks(text):
|
|
232
|
-
"""顶层 `key:` 切块。返回 [(key, inline_value, block_lines)],块内逐字节保留。"""
|
|
233
|
-
out, cur = [], None
|
|
234
|
-
for raw in text.splitlines():
|
|
235
|
-
if not raw.strip() or raw.lstrip().startswith('#'):
|
|
236
|
-
if cur:
|
|
237
|
-
cur[2].append(raw)
|
|
238
|
-
continue
|
|
239
|
-
m = re.match(r'([A-Za-z_][\w-]*):(.*)$', raw)
|
|
240
|
-
if m and not raw[0].isspace():
|
|
241
|
-
cur = [m.group(1), m.group(2).strip(), []]
|
|
242
|
-
out.append(cur)
|
|
243
|
-
elif cur:
|
|
244
|
-
cur[2].append(raw)
|
|
245
|
-
else:
|
|
246
|
-
raise Fail('顶层出现无键行: %r' % raw[:60])
|
|
247
|
-
# 去掉每块尾部空行,避免透传时带出多余空白
|
|
248
|
-
for entry in out:
|
|
249
|
-
while entry[2] and not entry[2][-1].strip():
|
|
250
|
-
entry[2].pop()
|
|
251
|
-
return out
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
LAYOUT_CONTROL_KEYS = {
|
|
255
|
-
'names', 'roles', 'text_roles', 'layout_modes', 'bg_rules',
|
|
256
|
-
}
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
def control_entry_keys(lines):
|
|
260
|
-
"""读取扁平判断段的一级条目,防止整段覆盖时漏掉旧结论。"""
|
|
261
|
-
return {
|
|
262
|
-
match.group(1)
|
|
263
|
-
for line in lines
|
|
264
|
-
for match in [re.match(r'^\s{2}([\w-]+):', line)]
|
|
265
|
-
if match
|
|
266
|
-
}
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
def load_layout_blocks(lout):
|
|
270
|
-
"""读取版式坐标事实;新草案把可编辑判断区放在独立的小文件里。"""
|
|
271
|
-
lay_path = os.path.join(lout, 'layouts.yaml')
|
|
272
|
-
if not os.path.exists(lay_path):
|
|
273
|
-
return None
|
|
274
|
-
with open(lay_path, encoding='utf-8') as stream:
|
|
275
|
-
layouts = split_top_blocks(stream.read())
|
|
276
|
-
controls_path = os.path.join(lout, 'layout-controls.yaml')
|
|
277
|
-
if not os.path.exists(controls_path):
|
|
278
|
-
return layouts
|
|
279
|
-
with open(controls_path, encoding='utf-8') as stream:
|
|
280
|
-
controls = split_top_blocks(stream.read())
|
|
281
|
-
invalid = {key for key, _, _ in controls} - LAYOUT_CONTROL_KEYS
|
|
282
|
-
if invalid:
|
|
283
|
-
raise Fail('layout-controls.yaml 只能包含 %s,不能包含:%s'
|
|
284
|
-
% ('|'.join(sorted(LAYOUT_CONTROL_KEYS)), ', '.join(sorted(invalid))))
|
|
285
|
-
legacy_keys = {key for key, _, _ in layouts if key in LAYOUT_CONTROL_KEYS}
|
|
286
|
-
control_keys = {key for key, _, _ in controls}
|
|
287
|
-
missing = legacy_keys - control_keys
|
|
288
|
-
if missing:
|
|
289
|
-
raise Fail('layout-controls.yaml 必须覆盖 layouts.yaml 的全部判断段,缺:%s'
|
|
290
|
-
% ', '.join(sorted(missing)))
|
|
291
|
-
legacy_blocks = {key: lines for key, _, lines in layouts}
|
|
292
|
-
control_blocks = {key: lines for key, _, lines in controls}
|
|
293
|
-
for key in sorted(legacy_keys):
|
|
294
|
-
missing_entries = (control_entry_keys(legacy_blocks[key])
|
|
295
|
-
- control_entry_keys(control_blocks[key]))
|
|
296
|
-
if missing_entries:
|
|
297
|
-
raise Fail('layout-controls.yaml 的 %s 段缺少旧判断条目:%s'
|
|
298
|
-
% (key, ', '.join(sorted(missing_entries))))
|
|
299
|
-
base = [block for block in layouts if block[0] not in LAYOUT_CONTROL_KEYS]
|
|
300
|
-
return controls + base
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
def unquote(s):
|
|
304
|
-
s = s.strip()
|
|
305
|
-
if len(s) >= 2 and s[0] == s[-1] and s[0] in '"\'':
|
|
306
|
-
return s[1:-1]
|
|
307
|
-
# 未加引号的标量后面跟行内注释:按 YAML 规矩剥掉(前面必须有空白)
|
|
308
|
-
s = re.split(r'\s+#', s, maxsplit=1)[0].strip()
|
|
309
|
-
return s
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
def scalar_of(inline, lines):
|
|
313
|
-
"""标量取值:支持 `key: v`、`key: |`、`key: >`。
|
|
314
|
-
|
|
315
|
-
`|` 按公共缩进整体 dedent,**不逐行 strip** —— 正文里的嵌套列表/缩进代码块
|
|
316
|
-
靠相对缩进表意,逐行 strip 会把它们拍平。
|
|
317
|
-
"""
|
|
318
|
-
if inline in ('|', '>', '|-', '>-'):
|
|
319
|
-
if inline.startswith('>'):
|
|
320
|
-
return ' '.join(ln.strip() for ln in lines if ln.strip()).strip()
|
|
321
|
-
indents = [len(ln) - len(ln.lstrip()) for ln in lines if ln.strip()]
|
|
322
|
-
pad = min(indents) if indents else 0
|
|
323
|
-
return '\n'.join(ln[pad:] if len(ln) >= pad else ln.lstrip()
|
|
324
|
-
for ln in lines).strip('\n')
|
|
325
|
-
return unquote(inline)
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
def parse_flow_list(s):
|
|
329
|
-
s = s.strip()
|
|
330
|
-
if not (s.startswith('[') and s.endswith(']')):
|
|
331
|
-
return None
|
|
332
|
-
inner = s[1:-1].strip()
|
|
333
|
-
return [unquote(x) for x in inner.split(',') if x.strip()] if inner else []
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
def parse_item_list(lines):
|
|
337
|
-
"""`- key: v` 形式的对象列表。"""
|
|
338
|
-
items, cur = [], None
|
|
339
|
-
for raw in lines:
|
|
340
|
-
if not raw.strip() or raw.lstrip().startswith('#'):
|
|
341
|
-
continue
|
|
342
|
-
stripped = raw.strip()
|
|
343
|
-
if stripped.startswith('- '):
|
|
344
|
-
cur = {}
|
|
345
|
-
items.append(cur)
|
|
346
|
-
stripped = stripped[2:].strip()
|
|
347
|
-
if not stripped:
|
|
348
|
-
continue
|
|
349
|
-
if cur is None:
|
|
350
|
-
raise Fail('资产列表里出现不属于任何 `- ` 项的行: %r' % raw[:60])
|
|
351
|
-
m = re.match(r'([A-Za-z_][\w-]*):(.*)$', stripped)
|
|
352
|
-
if not m:
|
|
353
|
-
raise Fail('资产列表行无法解析: %r' % raw[:60])
|
|
354
|
-
# 值原样保留(含作者的引号):recipe / color / url 这些是直接透传进
|
|
355
|
-
# design.md 的文本,重新决定要不要加引号会改掉作者的写法。
|
|
356
|
-
cur[m.group(1)] = m.group(2).strip()
|
|
357
|
-
return items
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
def read_manifest(path):
|
|
361
|
-
blocks = split_top_blocks(open(path, encoding='utf-8').read())
|
|
362
|
-
man, assets, asset_vision_groups, asset_decisions, raw = {}, [], [], [], {}
|
|
363
|
-
derived = []
|
|
364
|
-
for key, inline, lines in blocks:
|
|
365
|
-
if key == 'assets':
|
|
366
|
-
assets = parse_item_list(lines)
|
|
367
|
-
elif key == 'asset_vision_groups':
|
|
368
|
-
asset_vision_groups = parse_item_list(lines)
|
|
369
|
-
elif key == 'asset_decisions':
|
|
370
|
-
asset_decisions = parse_item_list(lines)
|
|
371
|
-
elif key == 'derived':
|
|
372
|
-
derived = parse_item_list(lines)
|
|
373
|
-
elif inline.startswith('['):
|
|
374
|
-
man[key] = parse_flow_list(inline)
|
|
375
|
-
elif inline.startswith('{'):
|
|
376
|
-
man[key] = inline # 流映射原样透传
|
|
377
|
-
else:
|
|
378
|
-
man[key] = scalar_of(inline, lines)
|
|
379
|
-
if lines:
|
|
380
|
-
# 记住原始块形态(如 `description: >` 多行),回写时逐字节照搬,
|
|
381
|
-
# 不把作者的折行改成一条长行。
|
|
382
|
-
raw[key] = (inline, lines)
|
|
383
|
-
man['assets'] = assets
|
|
384
|
-
man['asset_vision_groups'] = asset_vision_groups
|
|
385
|
-
man['asset_decisions'] = asset_decisions
|
|
386
|
-
man['derived'] = derived
|
|
387
|
-
man['_raw'] = raw
|
|
388
|
-
return man
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
def validate_asset_vision_groups(lout, manifest):
|
|
392
|
-
"""新草案的候选索引存在时,视觉判断必须逐项覆盖且不改写实例事实。"""
|
|
393
|
-
index_path = os.path.join(lout, 'asset-vision-groups.json')
|
|
394
|
-
if not os.path.exists(index_path):
|
|
395
|
-
return {}
|
|
396
|
-
try:
|
|
397
|
-
with open(index_path, encoding='utf-8') as stream:
|
|
398
|
-
index = json.load(stream)
|
|
399
|
-
except (OSError, ValueError) as exc:
|
|
400
|
-
raise Fail('asset-vision-groups.json 无法读取:%s' % exc)
|
|
401
|
-
if 'selected' not in index:
|
|
402
|
-
raise Fail('asset-vision-groups.json 缺少 selected 候选列表')
|
|
403
|
-
|
|
404
|
-
expected = {}
|
|
405
|
-
for group in index.get('selected') or []:
|
|
406
|
-
for candidate in group.get('candidates') or []:
|
|
407
|
-
candidate_id = unquote(str(candidate.get('id') or ''))
|
|
408
|
-
source = unquote(str(candidate.get('source_media') or candidate.get('file') or ''))
|
|
409
|
-
placements = candidate.get('placements') or []
|
|
410
|
-
placement = placements[0] if placements else {}
|
|
411
|
-
raw_box = placement.get('box')
|
|
412
|
-
box = tuple(raw_box) if isinstance(raw_box, list) and len(raw_box) == 4 else None
|
|
413
|
-
layout = unquote(str(candidate.get('layout') or placement.get('archetype') or ''))
|
|
414
|
-
if not candidate_id or not source or box is None:
|
|
415
|
-
raise Fail('asset-vision-groups.json 的候选缺少 id、source_media 或 box')
|
|
416
|
-
if candidate_id in expected:
|
|
417
|
-
raise Fail('asset-vision-groups.json 的候选 id 重复:%s' % candidate_id)
|
|
418
|
-
expected[candidate_id] = (source, layout or None, box)
|
|
419
|
-
|
|
420
|
-
actual = {}
|
|
421
|
-
for item in manifest.get('asset_vision_groups') or []:
|
|
422
|
-
candidate_id = unquote(item.get('id') or '')
|
|
423
|
-
sources = source_media_list(item.get('source_media') or '')
|
|
424
|
-
layout, box = decision_scope(item, 'asset_vision_groups.%s' % candidate_id)
|
|
425
|
-
if not candidate_id:
|
|
426
|
-
raise Fail('asset_vision_groups 必须逐项填写 id')
|
|
427
|
-
if candidate_id in actual:
|
|
428
|
-
raise Fail('asset_vision_groups 的候选 id 重复:%s' % candidate_id)
|
|
429
|
-
actual[candidate_id] = (sources, layout, box)
|
|
430
|
-
|
|
431
|
-
expected_ids = set(expected)
|
|
432
|
-
actual_ids = set(actual)
|
|
433
|
-
instance_format = index.get('version', 1) >= 2
|
|
434
|
-
if instance_format:
|
|
435
|
-
missing = sorted(expected_ids - actual_ids)
|
|
436
|
-
extra = sorted(actual_ids - expected_ids)
|
|
437
|
-
if missing or extra:
|
|
438
|
-
problems = []
|
|
439
|
-
if missing:
|
|
440
|
-
problems.append('缺少:%s' % ', '.join(missing))
|
|
441
|
-
if extra:
|
|
442
|
-
problems.append('出现未知项:%s' % ', '.join(extra))
|
|
443
|
-
raise Fail('asset_vision_groups 必须逐项保留抽取候选,%s'
|
|
444
|
-
% ';'.join(problems))
|
|
445
|
-
for candidate_id, expected_scope in expected.items():
|
|
446
|
-
sources, layout, box = actual[candidate_id]
|
|
447
|
-
expected_source, expected_layout, expected_box = expected_scope
|
|
448
|
-
if sources != [expected_source] or box != expected_box:
|
|
449
|
-
raise Fail('asset_vision_groups.%s 改写了抽取候选的图片或位置'
|
|
450
|
-
% candidate_id)
|
|
451
|
-
if layout and expected_layout and layout != expected_layout:
|
|
452
|
-
raise Fail('asset_vision_groups.%s 改写了抽取候选的页型'
|
|
453
|
-
% candidate_id)
|
|
454
|
-
return expected
|
|
455
|
-
|
|
456
|
-
# 旧草案用视觉组 id 和 source_media 列表表达默认判断,无法逐实例比对。
|
|
457
|
-
# 保留这种兼容输入,但仍要求每个选中的候选来源至少被一个组覆盖。
|
|
458
|
-
actual_sources = {
|
|
459
|
-
source for sources, _, _ in actual.values() for source in sources
|
|
460
|
-
}
|
|
461
|
-
missing_sources = sorted({
|
|
462
|
-
source for source, _, _ in expected.values()
|
|
463
|
-
} - actual_sources)
|
|
464
|
-
if missing_sources:
|
|
465
|
-
raise Fail('asset_vision_groups 必须覆盖抽取候选来源,缺少:%s'
|
|
466
|
-
% ', '.join(missing_sources))
|
|
467
|
-
return {}
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
def bind_asset_vision_group_scopes(lout, manifest):
|
|
471
|
-
"""用 v2 候选 id 恢复实例页型,模型无需重复填写 layout。"""
|
|
472
|
-
expected = validate_asset_vision_groups(lout, manifest)
|
|
473
|
-
for item in manifest.get('asset_vision_groups') or []:
|
|
474
|
-
candidate_id = unquote(item.get('id') or '')
|
|
475
|
-
scope = expected.get(candidate_id)
|
|
476
|
-
if scope and scope[1]:
|
|
477
|
-
item['_resolved_layout'] = scope[1]
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
# ------------------------------------------------------------------- 组装
|
|
481
|
-
def yaml_scalar(v):
|
|
482
|
-
"""标量回写。已带引号 / 流式结构原样;含 YAML 危险序列才补引号。"""
|
|
483
|
-
s = str(v)
|
|
484
|
-
if not s:
|
|
485
|
-
return "''"
|
|
486
|
-
if s[0] in '"\'[{' or s[-1] in '"\']}':
|
|
487
|
-
return s
|
|
488
|
-
if re.search(r':\s|\s#|^[-?*&!|>%@`]', s) or s.strip() != s:
|
|
489
|
-
return '"%s"' % s.replace('"', '\\"')
|
|
490
|
-
return s
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
def truthy(v):
|
|
494
|
-
return str(v).strip().lower() in ('1', 'true', 'yes', 'on')
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
# 浏览器能解码的图片格式。落进包的资产必须在此列,否则消费端引用到就是一张空白图。
|
|
498
|
-
WEB_SAFE_EXT = {'png', 'jpg', 'jpeg', 'webp', 'gif', 'svg', 'avif'}
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
def asset_ext(name):
|
|
502
|
-
return name.rsplit('.', 1)[-1].lower() if '.' in name else ''
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
def strip_kind_prefix(aid, kind):
|
|
506
|
-
"""`bg-cover` + background -> `cover`;前缀对不上就整名照用。"""
|
|
507
|
-
for pref in (KIND_PREFIX.get(kind), kind):
|
|
508
|
-
if pref and aid.startswith(pref + '-'):
|
|
509
|
-
return aid[len(pref) + 1:]
|
|
510
|
-
return aid
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
def source_media_list(value):
|
|
514
|
-
"""`source_media: one.png` 与视觉组的 `[a.png, b.png]` 两种写法都接受。"""
|
|
515
|
-
raw = value.strip()
|
|
516
|
-
parsed = parse_flow_list(raw)
|
|
517
|
-
return parsed if parsed is not None else [unquote(raw)] if raw else []
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
def visual_kind_decision(value, label):
|
|
521
|
-
visual_kind = unquote(value or '')
|
|
522
|
-
if visual_kind not in ASSET_VISUAL_KINDS:
|
|
523
|
-
raise Fail('%s 的 visual_kind 只能是 %s'
|
|
524
|
-
% (label, '|'.join(sorted(ASSET_VISUAL_KINDS))))
|
|
525
|
-
return VISUAL_KIND_TO_DECISION[visual_kind]
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
def slot_box(line):
|
|
529
|
-
match = re.search(r'\bbox:\s*\[([^\]]+)\]', line)
|
|
530
|
-
return parse_box_match(match)
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
def source_box(line):
|
|
534
|
-
match = re.search(r'\bsource_box:\s*\[([^\]]+)\]', line)
|
|
535
|
-
return parse_box_match(match)
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
def parse_box_match(match):
|
|
539
|
-
if not match:
|
|
540
|
-
return None
|
|
541
|
-
try:
|
|
542
|
-
values = tuple(int(float(part.strip())) for part in match.group(1).split(','))
|
|
543
|
-
except ValueError:
|
|
544
|
-
return None
|
|
545
|
-
return values if len(values) == 4 else None
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
def decision_scope(item, label):
|
|
549
|
-
raw_box = item.get('box')
|
|
550
|
-
box = slot_box('box: %s' % raw_box) if raw_box else None
|
|
551
|
-
if raw_box and box is None:
|
|
552
|
-
raise Fail('%s 的 box 必须是四个数的 [x, y, w, h]' % label)
|
|
553
|
-
layout = unquote(item.get('_resolved_layout') or item.get('layout') or '')
|
|
554
|
-
if layout and box is None:
|
|
555
|
-
raise Fail('%s 的 layout 必须与 box 一起填写' % label)
|
|
556
|
-
return layout or None, box
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
def register_asset_decision(decisions, visual_kinds, key, decision, visual_kind):
|
|
560
|
-
"""合并相同实例的重复判断;显式 visual_kind 必须逐字一致。"""
|
|
561
|
-
if key not in decisions:
|
|
562
|
-
decisions[key] = decision
|
|
563
|
-
visual_kinds[key] = visual_kind
|
|
564
|
-
return
|
|
565
|
-
previous_kind = visual_kinds[key]
|
|
566
|
-
if ((previous_kind and visual_kind and previous_kind != visual_kind)
|
|
567
|
-
or (not previous_kind or not visual_kind)
|
|
568
|
-
and decisions[key] != decision):
|
|
569
|
-
label = 'source_media' if key[2] is None else '实例'
|
|
570
|
-
raise Fail('图片判断的 %s判断冲突: %s' % (label, key[0]))
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
def register_asset_role(roles, background_roles, source, layout, box, decision, role):
|
|
574
|
-
if not role:
|
|
575
|
-
return
|
|
576
|
-
if source in roles and roles[source] != role:
|
|
577
|
-
raise Fail('图片判断的 source_media role 冲突: %s' % source)
|
|
578
|
-
roles[source] = role
|
|
579
|
-
if decision != 'background' or box is None:
|
|
580
|
-
return
|
|
581
|
-
for (known_layout, known_box), (known_source, known_role) in background_roles.items():
|
|
582
|
-
if (known_box == box
|
|
583
|
-
and (known_layout == layout
|
|
584
|
-
or known_layout is None
|
|
585
|
-
or layout is None)
|
|
586
|
-
and known_role != role):
|
|
587
|
-
raise Fail('图片判断的背景实例 role 冲突: %s、%s'
|
|
588
|
-
% (known_source, source))
|
|
589
|
-
background_roles[(layout, box)] = (source, role)
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
def decision_overrides(manifest):
|
|
593
|
-
"""把视觉组默认值与单图/单页型实例覆盖展开为按 source_media 的内部决定。"""
|
|
594
|
-
scoped, visual_kinds, roles, background_roles = {}, {}, {}, {}
|
|
595
|
-
for group in manifest.get('asset_vision_groups') or []:
|
|
596
|
-
group_id = unquote(group.get('id') or '')
|
|
597
|
-
sources = source_media_list(group.get('source_media') or '')
|
|
598
|
-
if not group_id or not sources:
|
|
599
|
-
raise Fail('asset_vision_groups 必须逐项填写 id 与 source_media')
|
|
600
|
-
visual_kind = unquote(group.get('visual_kind') or '')
|
|
601
|
-
decision = visual_kind_decision(visual_kind,
|
|
602
|
-
'asset_vision_groups.%s' % group_id)
|
|
603
|
-
layout, box = decision_scope(
|
|
604
|
-
group, 'asset_vision_groups.%s' % group_id)
|
|
605
|
-
if box is not None and len(sources) != 1:
|
|
606
|
-
raise Fail('asset_vision_groups.%s 的实例判断只能填写一个 source_media'
|
|
607
|
-
% group_id)
|
|
608
|
-
role = unquote(group.get('role') or '')
|
|
609
|
-
for source in sources:
|
|
610
|
-
key = (source, layout, box)
|
|
611
|
-
register_asset_decision(scoped, visual_kinds, key, decision, visual_kind)
|
|
612
|
-
register_asset_role(
|
|
613
|
-
roles, background_roles, source, layout, box, decision, role)
|
|
614
|
-
|
|
615
|
-
explicit_defaults, explicit_default_kinds = {}, {}
|
|
616
|
-
explicit_overrides, explicit_override_kinds = {}, {}
|
|
617
|
-
explicit_roles = {}
|
|
618
|
-
for item in manifest.get('asset_decisions') or []:
|
|
619
|
-
source = unquote(item.get('source_media') or '')
|
|
620
|
-
visual_kind = item.get('visual_kind')
|
|
621
|
-
legacy = item.get('decision')
|
|
622
|
-
if not source or (visual_kind and legacy):
|
|
623
|
-
raise Fail('asset_decisions 每项只填 source_media 和 visual_kind(或旧 decision)')
|
|
624
|
-
if visual_kind:
|
|
625
|
-
decision = visual_kind_decision(visual_kind, 'asset_decisions.%s' % source)
|
|
626
|
-
else:
|
|
627
|
-
decision = unquote(legacy or '')
|
|
628
|
-
if decision not in LEGACY_ASSET_DECISIONS:
|
|
629
|
-
raise Fail('asset_decisions 的旧 decision 只能是 %s'
|
|
630
|
-
% '|'.join(sorted(LEGACY_ASSET_DECISIONS)))
|
|
631
|
-
layout, box = decision_scope(item, 'asset_decisions.%s' % source)
|
|
632
|
-
target = (explicit_defaults, explicit_default_kinds) if box is None else (
|
|
633
|
-
explicit_overrides, explicit_override_kinds)
|
|
634
|
-
register_asset_decision(
|
|
635
|
-
target[0], target[1], (source, layout, box), decision,
|
|
636
|
-
unquote(visual_kind) if visual_kind else None)
|
|
637
|
-
role = unquote(item.get('role') or '')
|
|
638
|
-
register_asset_role(
|
|
639
|
-
explicit_roles, background_roles, source, layout, box, decision, role)
|
|
640
|
-
|
|
641
|
-
scoped.update(explicit_defaults)
|
|
642
|
-
scoped.update(explicit_overrides)
|
|
643
|
-
for source, role in explicit_roles.items():
|
|
644
|
-
if source in roles and roles[source] != role:
|
|
645
|
-
raise Fail('图片判断的 source_media role 冲突: %s' % source)
|
|
646
|
-
roles[source] = role
|
|
647
|
-
|
|
648
|
-
defaults = {
|
|
649
|
-
source: decision
|
|
650
|
-
for (source, _, box), decision in scoped.items()
|
|
651
|
-
if box is None
|
|
652
|
-
}
|
|
653
|
-
overrides = {
|
|
654
|
-
(source, layout, box): decision
|
|
655
|
-
for (source, layout, box), decision in scoped.items()
|
|
656
|
-
if box is not None
|
|
657
|
-
}
|
|
658
|
-
return AssetDecisions(
|
|
659
|
-
defaults, overrides, roles,
|
|
660
|
-
{source for source, _, _ in explicit_defaults},
|
|
661
|
-
set(explicit_overrides),
|
|
662
|
-
)
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
def reusable_decisions_for_source(source, decisions):
|
|
666
|
-
"""无布局槽位时,收集该源图所有可能落盘的可复用用途。"""
|
|
667
|
-
reusable = {'background', 'texture', 'logo', 'icon', 'slogan'}
|
|
668
|
-
default = decisions.get(source)
|
|
669
|
-
overrides = {
|
|
670
|
-
decision for (override_source, layout, box), decision in decisions.overrides.items()
|
|
671
|
-
if override_source == source
|
|
672
|
-
and decision in reusable
|
|
673
|
-
and (source not in decisions.default_overrides
|
|
674
|
-
or (override_source, layout, box) in decisions.explicit_overrides)
|
|
675
|
-
}
|
|
676
|
-
return overrides | ({default} if default in reusable else set())
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
def reusable_decisions_for_slots(source, decisions, source_slots=None):
|
|
680
|
-
"""按实际图片槽的最终决定保留资产,可让同图在不同实例按用途绑定。"""
|
|
681
|
-
reusable = {'background', 'texture', 'logo', 'icon', 'slogan'}
|
|
682
|
-
slots = (source_slots or {}).get(source)
|
|
683
|
-
if slots is None:
|
|
684
|
-
return reusable_decisions_for_source(source, decisions)
|
|
685
|
-
return {
|
|
686
|
-
decisions.for_scope(source, layout_name, box)
|
|
687
|
-
for layout_name, box in slots
|
|
688
|
-
} & reusable
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
def validate_instance_decisions(decisions, bound_slots):
|
|
692
|
-
"""实例判断必须指向已有图片槽,避免 layout 拼错后静默退化为通用图片。"""
|
|
693
|
-
if bound_slots is None:
|
|
694
|
-
return
|
|
695
|
-
for source, layout_name, box in decisions.overrides:
|
|
696
|
-
slots = bound_slots.get(source) or set()
|
|
697
|
-
matches = ((layout_name, box) in slots if layout_name is not None
|
|
698
|
-
else any(slot_box == box for _, slot_box in slots))
|
|
699
|
-
if not matches:
|
|
700
|
-
raise Fail('图片判断的实例没有对应图片槽: %s' % source)
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
def apply_asset_decisions(manifest, bound_sources=None, bound_slots=None):
|
|
704
|
-
"""把抽取期图片判断并入正式 assets;内容图与噪声不进入消费产物。"""
|
|
705
|
-
decisions = decision_overrides(manifest)
|
|
706
|
-
if bound_sources is not None:
|
|
707
|
-
declared = set(decisions)
|
|
708
|
-
declared |= {source for source, _, _ in decisions.overrides}
|
|
709
|
-
unbound = sorted(declared - set(bound_sources))
|
|
710
|
-
if unbound:
|
|
711
|
-
raise Fail('图片判断中这些图片没有对应图片槽:%s'
|
|
712
|
-
% '、'.join(unbound))
|
|
713
|
-
validate_instance_decisions(decisions, bound_slots)
|
|
714
|
-
|
|
715
|
-
assets = []
|
|
716
|
-
by_source_kind = {}
|
|
717
|
-
serial = Counter()
|
|
718
|
-
used_ids = {unquote(item.get('id') or '')
|
|
719
|
-
for item in manifest.get('assets') or [] if item.get('id')}
|
|
720
|
-
decision_sources = list(decisions)
|
|
721
|
-
for source, _, _ in decisions.overrides:
|
|
722
|
-
if source not in decision_sources:
|
|
723
|
-
decision_sources.append(source)
|
|
724
|
-
desired_kinds = {
|
|
725
|
-
source: reusable_decisions_for_slots(source, decisions, bound_slots)
|
|
726
|
-
for source in decision_sources
|
|
727
|
-
}
|
|
728
|
-
emitted = set()
|
|
729
|
-
|
|
730
|
-
def next_asset_id(kind):
|
|
731
|
-
serial[kind] += 1
|
|
732
|
-
aid = '%s-%d' % (KIND_PREFIX[kind], serial[kind])
|
|
733
|
-
while aid in used_ids:
|
|
734
|
-
serial[kind] += 1
|
|
735
|
-
aid = '%s-%d' % (KIND_PREFIX[kind], serial[kind])
|
|
736
|
-
used_ids.add(aid)
|
|
737
|
-
return aid
|
|
738
|
-
|
|
739
|
-
def append_asset(item, source, decision):
|
|
740
|
-
old_kind = unquote(item.get('kind') or '')
|
|
741
|
-
pair = (source, decision if source in decision_sources else old_kind)
|
|
742
|
-
if source and pair in emitted:
|
|
743
|
-
return
|
|
744
|
-
row = dict(item)
|
|
745
|
-
if decision and decision != old_kind:
|
|
746
|
-
row['kind'] = decision
|
|
747
|
-
row['id'] = next_asset_id(decision)
|
|
748
|
-
for field in ('role', 'theme', 'on-bg', 'mark'):
|
|
749
|
-
row.pop(field, None)
|
|
750
|
-
if decision == 'background':
|
|
751
|
-
row['role'] = decisions.roles.get(source) or 'content'
|
|
752
|
-
if source:
|
|
753
|
-
emitted.add(pair)
|
|
754
|
-
by_source_kind[(source, row['kind'])] = row
|
|
755
|
-
used_ids.add(unquote(row.get('id') or ''))
|
|
756
|
-
assets.append(row)
|
|
757
|
-
|
|
758
|
-
for item in manifest.get('assets') or []:
|
|
759
|
-
source = unquote(item.get('source_media') or '')
|
|
760
|
-
if source in decision_sources:
|
|
761
|
-
for decision in sorted(desired_kinds[source]):
|
|
762
|
-
append_asset(item, source, decision)
|
|
763
|
-
else:
|
|
764
|
-
append_asset(item, source, None)
|
|
765
|
-
|
|
766
|
-
for source in decision_sources:
|
|
767
|
-
for decision in sorted(desired_kinds[source]):
|
|
768
|
-
if (source, decision) in emitted:
|
|
769
|
-
continue
|
|
770
|
-
append_asset({
|
|
771
|
-
'id': next_asset_id(decision),
|
|
772
|
-
'source_media': source,
|
|
773
|
-
'kind': decision,
|
|
774
|
-
}, source, decision)
|
|
775
|
-
manifest['assets'] = assets
|
|
776
|
-
source_kinds = defaultdict(set)
|
|
777
|
-
for source, kind in by_source_kind:
|
|
778
|
-
source_kinds[source].add(kind)
|
|
779
|
-
defaults = {
|
|
780
|
-
source: unquote(by_source_kind[(source, next(iter(kinds)))]['id'])
|
|
781
|
-
for source, kinds in source_kinds.items()
|
|
782
|
-
if len(kinds) == 1
|
|
783
|
-
}
|
|
784
|
-
scoped = {
|
|
785
|
-
(source, kind): unquote(item['id'])
|
|
786
|
-
for (source, kind), item in by_source_kind.items()
|
|
787
|
-
}
|
|
788
|
-
return decisions, AssetIds(defaults, scoped)
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
def media_row_of(extract, source_media):
|
|
792
|
-
for m in extract.get('media') or []:
|
|
793
|
-
if m.get('out') and os.path.basename(m['out']) == source_media:
|
|
794
|
-
return m
|
|
795
|
-
for m in extract.get('media') or []:
|
|
796
|
-
if os.path.basename(m['media']) == source_media:
|
|
797
|
-
return m
|
|
798
|
-
return None
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
def image_row_of(extract, source_media):
|
|
802
|
-
for i in extract.get('images') or []:
|
|
803
|
-
if os.path.basename(i['media']) == source_media:
|
|
804
|
-
return i
|
|
805
|
-
# An svg that ships as a raster's vector companion has no images[] row of its
|
|
806
|
-
# own — the placement is recorded on the raster (a:blip embeds the png, the svg
|
|
807
|
-
# rides in a:extLst/svgBlip). Its boxes therefore come from the companion.
|
|
808
|
-
for i in extract.get('images') or []:
|
|
809
|
-
comp = i.get('svg_companion')
|
|
810
|
-
if comp and os.path.basename(comp) == source_media:
|
|
811
|
-
return i
|
|
812
|
-
return None
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
def place_assets(manifest, extract, stage1, pack):
|
|
816
|
-
"""拷贝资产 + 生成 design.md 的 assets 段 + audit.yaml 的 assets 段。"""
|
|
817
|
-
consumer, audit, copied = {}, {}, []
|
|
818
|
-
for a in manifest['assets']:
|
|
819
|
-
a = dict(a)
|
|
820
|
-
for f in ('id', 'kind', 'source_media', 'use_full', 'mark', 'confidence'):
|
|
821
|
-
if f in a:
|
|
822
|
-
a[f] = unquote(a[f])
|
|
823
|
-
aid = a.get('id')
|
|
824
|
-
if not aid:
|
|
825
|
-
raise Fail('assets 里有条目缺 id')
|
|
826
|
-
kind = a.get('kind')
|
|
827
|
-
if kind not in KIND_PREFIX:
|
|
828
|
-
raise Fail('%s: kind=%r 不在 %s 内' % (aid, kind, sorted(KIND_PREFIX)))
|
|
829
|
-
entry = {'kind': kind}
|
|
830
|
-
for f in ('role', 'theme', 'on-bg', 'recipe'):
|
|
831
|
-
if a.get(f):
|
|
832
|
-
entry[f] = a[f]
|
|
833
|
-
|
|
834
|
-
if a.get('color'):
|
|
835
|
-
entry['color'] = a['color'] # 纯色背景,不落文件
|
|
836
|
-
elif a.get('url'):
|
|
837
|
-
entry['url'] = a['url']
|
|
838
|
-
elif a.get('source_media'):
|
|
839
|
-
src = a['source_media']
|
|
840
|
-
row = media_row_of(extract, src)
|
|
841
|
-
if row is None or not row.get('out'):
|
|
842
|
-
raise Fail('%s: media-out 里找不到 %s(extract.json media 无该导出行;'
|
|
843
|
-
'非候选图需先用 extract.py --export-all-media 补导)' % (aid, src))
|
|
844
|
-
base = strip_kind_prefix(aid, kind)
|
|
845
|
-
sub = os.path.join(pack, 'assets', kind + 's')
|
|
846
|
-
os.makedirs(sub, exist_ok=True)
|
|
847
|
-
comp = row.get('compressed_out')
|
|
848
|
-
orig_path = os.path.join(stage1, row['out'])
|
|
849
|
-
if comp:
|
|
850
|
-
comp_path = os.path.join(stage1, comp)
|
|
851
|
-
cext = asset_ext(comp)
|
|
852
|
-
dst = os.path.join(sub, '%s.%s' % (base, cext))
|
|
853
|
-
shutil.copy2(comp_path, dst)
|
|
854
|
-
copied.append(dst)
|
|
855
|
-
entry['path'] = 'assets/%ss/%s.%s' % (kind, base, cext)
|
|
856
|
-
if truthy(a.get('use_full')):
|
|
857
|
-
oext = asset_ext(row['out'])
|
|
858
|
-
if oext.lower() in WEB_SAFE_EXT:
|
|
859
|
-
fdst = os.path.join(sub, '%s@full.%s' % (base, oext))
|
|
860
|
-
shutil.copy2(orig_path, fdst)
|
|
861
|
-
copied.append(fdst)
|
|
862
|
-
entry['full'] = 'assets/%ss/%s@full.%s' % (kind, base, oext)
|
|
863
|
-
else:
|
|
864
|
-
# 原图是浏览器不解码的格式(tiff/bmp 之类)。落进包并在 design.md
|
|
865
|
-
# 里声明成可用资源,消费端引用它就是一张空白图——实测踩过一次,
|
|
866
|
-
# 封面与结束页因此空白。压缩版已经带着全部像素,full 不给。
|
|
867
|
-
print(' ⚠ %s 的原图是 .%s,浏览器不解码,只给压缩版' % (aid, oext))
|
|
868
|
-
else:
|
|
869
|
-
oext = asset_ext(row['out'])
|
|
870
|
-
if oext.lower() not in WEB_SAFE_EXT:
|
|
871
|
-
# 转码两条路(Pillow / sips)都没成,原图又是浏览器不解码的格式。
|
|
872
|
-
# 照落进去就是把一张永远显示不出来的图当资产下发——实测封面因此空白。
|
|
873
|
-
raise Fail('%s: 原图是 .%s,浏览器不解码,而转码没有产物'
|
|
874
|
-
'(extract.json 里看 transcode_blocked 的原因)。'
|
|
875
|
-
'装上 Pillow 重跑抽取,或把这条资产从 manifest 删掉'
|
|
876
|
-
'并在 gaps 写明。' % (aid, oext))
|
|
877
|
-
dst = os.path.join(sub, '%s.%s' % (base, oext))
|
|
878
|
-
shutil.copy2(orig_path, dst)
|
|
879
|
-
copied.append(dst)
|
|
880
|
-
entry['path'] = 'assets/%ss/%s.%s' % (kind, base, oext)
|
|
881
|
-
if truthy(a.get('use_full')):
|
|
882
|
-
raise Fail('%s: use_full=true 但 %s 没有压缩版产物,'
|
|
883
|
-
'path/full 会指向同一文件' % (aid, src))
|
|
884
|
-
else:
|
|
885
|
-
raise Fail('%s: 必须给 source_media / color / url 之一' % aid)
|
|
886
|
-
|
|
887
|
-
consumer[aid] = entry
|
|
888
|
-
# ---- 审计数据全部机器算,L 层不碰
|
|
889
|
-
au = {}
|
|
890
|
-
if a.get('source_media'):
|
|
891
|
-
img = image_row_of(extract, a['source_media'])
|
|
892
|
-
if img:
|
|
893
|
-
# 首项为主位 = 出现次数最多者;次数打平时按阅读顺序(上→下、左→右)
|
|
894
|
-
# 定序,避免同频簇的先后取决于字典插入顺序。
|
|
895
|
-
clusters = sorted(img.get('boxes') or [],
|
|
896
|
-
key=lambda c: (-c['count'], c['box']['y'], c['box']['x']))
|
|
897
|
-
boxes = [[int(round(c['box'][k])) for k in ('x', 'y', 'w', 'h')]
|
|
898
|
-
for c in clusters]
|
|
899
|
-
if boxes:
|
|
900
|
-
au['boxes'] = boxes
|
|
901
|
-
# aspect 取**未取整**的 box —— 从取整后的整数反算会明显偏
|
|
902
|
-
# 先取整再相除,误差会落到小数点后两位,logo 这种细长框尤其明显。
|
|
903
|
-
raw = clusters[0]['box']
|
|
904
|
-
if raw.get('h'):
|
|
905
|
-
au['aspect'] = round(raw['w'] / float(raw['h']), 3)
|
|
906
|
-
if a.get('mark'):
|
|
907
|
-
au['mark'] = a['mark']
|
|
908
|
-
au['confidence'] = a.get('confidence') or 'high'
|
|
909
|
-
audit[aid] = au
|
|
910
|
-
return consumer, audit, copied
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
def _pages_of(extract, source_media):
|
|
914
|
-
img = image_row_of(extract, source_media) if source_media else None
|
|
915
|
-
if not img:
|
|
916
|
-
return []
|
|
917
|
-
pages = set()
|
|
918
|
-
for c in img.get('boxes') or []:
|
|
919
|
-
for p in c.get('parts') or []:
|
|
920
|
-
m = re.search(r'slide(\d+)\.xml$', p)
|
|
921
|
-
if m and '/slides/' in p:
|
|
922
|
-
pages.add(int(m.group(1)))
|
|
923
|
-
return sorted(pages)
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
def _archetypes_using(layouts_text, aid, key='asset'):
|
|
927
|
-
"""layouts.yaml 里哪些 archetype 引用了这个资产。
|
|
928
|
-
|
|
929
|
-
key='asset' 查 slots 里的图片槽;key='background' 查页型底图。
|
|
930
|
-
"""
|
|
931
|
-
out, cur, sect = [], None, None
|
|
932
|
-
for line in (layouts_text or '').split('\n'):
|
|
933
|
-
if re.match(r'^\w[\w-]*:\s*$', line):
|
|
934
|
-
sect = line.split(':')[0]
|
|
935
|
-
continue
|
|
936
|
-
if sect != 'layouts':
|
|
937
|
-
continue
|
|
938
|
-
m = re.match(r'^ ([\w-]+):\s*$', line)
|
|
939
|
-
if m:
|
|
940
|
-
cur = m.group(1)
|
|
941
|
-
continue
|
|
942
|
-
if cur and re.search(r'%s:\s*%s\b' % (key, re.escape(aid)), line) and cur not in out:
|
|
943
|
-
out.append(cur)
|
|
944
|
-
return out
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
def expand_placeholders(body, manifest, consumer, audit, extract, layouts_text):
|
|
948
|
-
"""body.md 里的 `{{ASSET_TABLE}}` / `{{LAYOUT_LIST}}` 由本脚本按落盘真值渲染——
|
|
949
|
-
路径与页型清单是打包期才确定的事实,不该由 L 层手抄(抄错就是死链)。"""
|
|
950
|
-
if '{{ASSET_TABLE}}' in body:
|
|
951
|
-
rows = ['| 资产 | 文件 | 什么时候用 |', '|---|---|---|']
|
|
952
|
-
src_of = {unquote(a.get('id', '')): a.get('source_media') for a in manifest['assets']}
|
|
953
|
-
for aid, e in consumer.items():
|
|
954
|
-
pages = _pages_of(extract, src_of.get(aid))
|
|
955
|
-
box = (audit.get(aid) or {}).get('boxes') or []
|
|
956
|
-
# 单元格保持短句:哪个页型用哪张由 `background` 字段决定,
|
|
957
|
-
# 那句说明放在表格前一次即可,逐行重复只是把同一句抄 N 遍。
|
|
958
|
-
if e['kind'] == 'background':
|
|
959
|
-
users = _archetypes_using(layouts_text, aid, key='background')
|
|
960
|
-
when = ('%s 用它' % '/'.join('`%s`' % o for o in users[:6])
|
|
961
|
-
if users else '未被任何页型引用')
|
|
962
|
-
else:
|
|
963
|
-
# 位置逐页型不同(同一 logo 常在封面左上、内容页右上,尺寸也不同),
|
|
964
|
-
# 所以这里只给归属,坐标一律交给 layouts.md 的 slots。
|
|
965
|
-
owners = _archetypes_using(layouts_text, aid)
|
|
966
|
-
when = ('%s 这 %d 个页型带它' % ('/'.join('`%s`' % o for o in owners[:6]),
|
|
967
|
-
len(owners))
|
|
968
|
-
if owners else '⚠ 没有页型声明它的位置,本包不使用它')
|
|
969
|
-
f = '`%s`' % e['path'] if e.get('path') else (
|
|
970
|
-
'`%s`' % e['url'] if e.get('url') else '纯色 `%s`' % e.get('color'))
|
|
971
|
-
if e.get('full'):
|
|
972
|
-
f += '(原图 `%s`)' % e['full']
|
|
973
|
-
rows.append('| `%s` | %s | %s |' % (aid, f, when))
|
|
974
|
-
body = body.replace('{{ASSET_TABLE}}', '\n'.join(rows))
|
|
975
|
-
if '{{LOGO_RULES}}' in body:
|
|
976
|
-
rows = []
|
|
977
|
-
for aid, entry in consumer.items():
|
|
978
|
-
if entry.get('kind') != 'logo':
|
|
979
|
-
continue
|
|
980
|
-
owners = _archetypes_using(layouts_text, aid)
|
|
981
|
-
rows.append('- `%s` 只出现在这些页型上:%s;其余页型不放。位置取该页型 '
|
|
982
|
-
'`slots` 里 `role: logo` 那一项的 `box`,原样使用该文件、保持原比例。'
|
|
983
|
-
% (aid, '、'.join('`%s`' % owner for owner in owners) or '(无)'))
|
|
984
|
-
body = body.replace('{{LOGO_RULES}}', '\n'.join(rows))
|
|
985
|
-
if '{{LAYOUT_LIST}}' in body:
|
|
986
|
-
rows, sect, names = [], None, {}
|
|
987
|
-
for line in (layouts_text or '').split('\n'):
|
|
988
|
-
if re.match(r'^\w[\w-]*:\s*$', line):
|
|
989
|
-
sect = line.split(':')[0]
|
|
990
|
-
continue
|
|
991
|
-
m = re.match(r'^ ([\w-]+):\s*(.*)$', line)
|
|
992
|
-
if not m:
|
|
993
|
-
m2 = re.match(r'^ name:\s*(.+?)\s*$', line)
|
|
994
|
-
if m2 and rows and rows[-1][1] is None:
|
|
995
|
-
rows[-1][1] = unquote(m2.group(1))
|
|
996
|
-
continue
|
|
997
|
-
if sect == 'names' and m.group(2).strip():
|
|
998
|
-
names[m.group(1)] = unquote(m.group(2))
|
|
999
|
-
elif sect == 'layouts' and not m.group(2).strip():
|
|
1000
|
-
rows.append(['- `%s`' % m.group(1), names.get(m.group(1))])
|
|
1001
|
-
rows = ['%s —— %s' % (k, n) if n else k for k, n in rows]
|
|
1002
|
-
body = body.replace('{{LAYOUT_LIST}}', '\n'.join(rows) or '(无 archetype)')
|
|
1003
|
-
return body
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
def render_assets_block(consumer):
|
|
1007
|
-
out = ['assets:']
|
|
1008
|
-
for aid, entry in consumer.items():
|
|
1009
|
-
out.append(' %s:' % aid)
|
|
1010
|
-
for f in ASSET_CONSUMER_FIELDS:
|
|
1011
|
-
if f in entry:
|
|
1012
|
-
out.append(' %s: %s' % (f, yaml_scalar(entry[f])))
|
|
1013
|
-
return out
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
# ------------------------------------------------- 数值可追溯机检(抄错即 FAIL)
|
|
1017
|
-
HEX_RE = re.compile(r'#([0-9A-Fa-f]{6})\b')
|
|
1018
|
-
FONTSIZE_RE = re.compile(r'\b(?:fontSize|font-size):\s*([\d.]+)px')
|
|
1019
|
-
BOX_RE = re.compile(r'\bbox:\s*\[\s*(-?[\d.]+)\s*,\s*(-?[\d.]+)\s*,'
|
|
1020
|
-
r'\s*(-?[\d.]+)\s*,\s*(-?[\d.]+)\s*\]')
|
|
1021
|
-
KEYLINE_RE = re.compile(r'^(\s*)-?\s*([A-Za-z_][\w-]*):\s*(.*)$')
|
|
1022
|
-
DOMINANT_TOL = 8 # 采样主色的每通道容差(量化误差天然存在)
|
|
1023
|
-
BOX_TOL = 2.0 # slot 坐标逐维容差
|
|
1024
|
-
SIZE_TOL = 0.51 # 字号容差(px 取整误差)
|
|
1025
|
-
REBASE_TOL = 1.0 # 等比上抬后的字号容差
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
def _hex2rgb(h):
|
|
1029
|
-
h = h.lstrip('#')
|
|
1030
|
-
return int(h[0:2], 16), int(h[2:4], 16), int(h[4:6], 16)
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
def frontmatter_of(path):
|
|
1034
|
-
if not os.path.exists(path):
|
|
1035
|
-
return ''
|
|
1036
|
-
t = open(path, encoding='utf-8').read()
|
|
1037
|
-
parts = t.split('---\n')
|
|
1038
|
-
return parts[1] if len(parts) >= 3 else ''
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
def _scan_keyed(text):
|
|
1042
|
-
"""逐行产出 (行号, 该行祖先键路径, 行内容),供 token 级豁免定位。"""
|
|
1043
|
-
stack = []
|
|
1044
|
-
for i, raw in enumerate(text.splitlines(), 1):
|
|
1045
|
-
m = KEYLINE_RE.match(raw)
|
|
1046
|
-
if m:
|
|
1047
|
-
indent = len(m.group(1))
|
|
1048
|
-
while stack and stack[-1][0] >= indent:
|
|
1049
|
-
stack.pop()
|
|
1050
|
-
path = [k for _, k in stack] + [m.group(2)]
|
|
1051
|
-
stack.append((indent, m.group(2)))
|
|
1052
|
-
yield i, path, raw
|
|
1053
|
-
else:
|
|
1054
|
-
yield i, [k for _, k in stack], raw
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
def build_trace_index(extract, shapes):
|
|
1058
|
-
"""可命中集合:色 / 字号 / 形状框。"""
|
|
1059
|
-
hexes, dominant = set(), []
|
|
1060
|
-
for c in extract.get('color_freq') or []:
|
|
1061
|
-
for k in ('resolved', 'hex'):
|
|
1062
|
-
v = c.get(k)
|
|
1063
|
-
if isinstance(v, str) and v.startswith('#') and len(v) == 7:
|
|
1064
|
-
hexes.add(v.upper())
|
|
1065
|
-
# 主题 clrScheme 也是普查值:出厂色常被「排除色」条款正面引用(页面频次为 0
|
|
1066
|
-
# 恰恰是它要论证的事),不收进来会把这类正确引用误判成抄错。
|
|
1067
|
-
for t in extract.get('themes') or []:
|
|
1068
|
-
for v in (t.get('clrScheme') or {}).values():
|
|
1069
|
-
if isinstance(v, str) and v.startswith('#') and len(v) == 7:
|
|
1070
|
-
hexes.add(v.upper())
|
|
1071
|
-
|
|
1072
|
-
def eat_fill(f):
|
|
1073
|
-
if not isinstance(f, dict):
|
|
1074
|
-
return
|
|
1075
|
-
col = f.get('color') or {}
|
|
1076
|
-
for k in ('resolved', 'hex'):
|
|
1077
|
-
v = col.get(k) if isinstance(col, dict) else None
|
|
1078
|
-
if isinstance(v, str) and v.startswith('#') and len(v) == 7:
|
|
1079
|
-
hexes.add(v.upper())
|
|
1080
|
-
for st in f.get('stops') or []: # 渐变 stop 色
|
|
1081
|
-
eat_fill(st if 'color' in st else {'color': st})
|
|
1082
|
-
|
|
1083
|
-
for grp in ('slides', 'layouts'):
|
|
1084
|
-
for row in extract.get(grp) or []:
|
|
1085
|
-
eat_fill(row.get('background'))
|
|
1086
|
-
for s in shapes:
|
|
1087
|
-
eat_fill(s.get('fill'))
|
|
1088
|
-
ln = s.get('line') or {}
|
|
1089
|
-
eat_fill(ln)
|
|
1090
|
-
eat_fill(ln.get('gradient'))
|
|
1091
|
-
for i in extract.get('images') or []:
|
|
1092
|
-
for dc in i.get('dominant_colors') or []:
|
|
1093
|
-
if dc.get('hex'):
|
|
1094
|
-
dominant.append((_hex2rgb(dc['hex']), dc['hex'].upper()))
|
|
1095
|
-
|
|
1096
|
-
sizes = sorted({e['sz_px'] for e in extract.get('text_scale') or []
|
|
1097
|
-
if e.get('sz_px')})
|
|
1098
|
-
boxes = []
|
|
1099
|
-
for s in shapes:
|
|
1100
|
-
b = s.get('box')
|
|
1101
|
-
if b and b.get('w') is not None:
|
|
1102
|
-
boxes.append((b['x'], b['y'], b['w'], b['h'],
|
|
1103
|
-
'%s %s' % (os.path.basename(s['part']), s.get('name') or s['kind'])))
|
|
1104
|
-
return {'hexes': hexes, 'dominant': dominant, 'sizes': sizes, 'boxes': boxes}
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
def _hex_hit(value, idx):
|
|
1108
|
-
v = value.upper()
|
|
1109
|
-
if v in idx['hexes']:
|
|
1110
|
-
return True, None
|
|
1111
|
-
rgb = _hex2rgb(v)
|
|
1112
|
-
best, bestd = None, None
|
|
1113
|
-
for drgb, dhex in idx['dominant']:
|
|
1114
|
-
d = max(abs(a - b) for a, b in zip(rgb, drgb))
|
|
1115
|
-
if d <= DOMINANT_TOL:
|
|
1116
|
-
return True, None
|
|
1117
|
-
if bestd is None or d < bestd:
|
|
1118
|
-
best, bestd = dhex, d
|
|
1119
|
-
for h in idx['hexes']:
|
|
1120
|
-
d = max(abs(a - b) for a, b in zip(rgb, _hex2rgb(h)))
|
|
1121
|
-
if bestd is None or d < bestd:
|
|
1122
|
-
best, bestd = h, d
|
|
1123
|
-
return False, ('最近 %s(每通道差 %d)' % (best, bestd) if best else '普查里无任何色值')
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
def _size_hit(v, idx, factor):
|
|
1127
|
-
for s in idx['sizes']:
|
|
1128
|
-
if abs(s - v) <= SIZE_TOL:
|
|
1129
|
-
return True, None
|
|
1130
|
-
if factor and abs(s * factor - v) <= REBASE_TOL:
|
|
1131
|
-
return True, None
|
|
1132
|
-
if not idx['sizes']:
|
|
1133
|
-
return False, '普查里无字号'
|
|
1134
|
-
near = min(idx['sizes'], key=lambda s: abs(s - v))
|
|
1135
|
-
tip = '最近 %gpx' % near
|
|
1136
|
-
if factor:
|
|
1137
|
-
nf = min(idx['sizes'], key=lambda s: abs(s * factor - v))
|
|
1138
|
-
tip += ';×%g 后最近 %gpx→%.1f' % (factor, nf, nf * factor)
|
|
1139
|
-
return False, tip
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
def _box_hit(box, idx):
|
|
1143
|
-
best, bestd = None, None
|
|
1144
|
-
for x, y, w, h, tag in idx['boxes']:
|
|
1145
|
-
d = max(abs(box[0] - x), abs(box[1] - y), abs(box[2] - w), abs(box[3] - h))
|
|
1146
|
-
if d <= BOX_TOL:
|
|
1147
|
-
return True, None
|
|
1148
|
-
if bestd is None or d < bestd:
|
|
1149
|
-
best, bestd = (x, y, w, h, tag), d
|
|
1150
|
-
if best is None:
|
|
1151
|
-
return False, 'shapes.json 无形状'
|
|
1152
|
-
return False, ('最近 [%g, %g, %g, %g](%s,最大维差 %.1fpx)'
|
|
1153
|
-
% (best[0], best[1], best[2], best[3], best[4], bestd))
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
# 判断产物:L 层看着背景图划出来的区域,本就不该命中普查值——整键豁免,
|
|
1157
|
-
# 不要求写 derived。逼它们走 derived 只会把整段豁免掉,机检反而更弱。
|
|
1158
|
-
JUDGEMENT_KEYS = frozenset(('avoid', 'text_safe', 'pairing_rule'))
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
def media_integrity(stage1, extract):
|
|
1162
|
-
"""extract.json 记录的尺寸,必须和磁盘上那个文件真实的尺寸一致。
|
|
1163
|
-
|
|
1164
|
-
这条挡的是「记录全对、文件被顶替」——两个 media 的输出名撞车时,后写的覆盖先写的,
|
|
1165
|
-
extract.json 里各自的记录都还是对的,任何只读记录的检查都发现不了;只有把记录和
|
|
1166
|
-
文件本身对一遍才抓得到。实测某模板因此把一张 109x109 的图当成了整页背景。
|
|
1167
|
-
"""
|
|
1168
|
-
try:
|
|
1169
|
-
from PIL import Image
|
|
1170
|
-
except Exception:
|
|
1171
|
-
return [] # 没有 Pillow 就量不了,跳过而不是假装通过
|
|
1172
|
-
bad, seen = [], {}
|
|
1173
|
-
for m in extract.get('media') or []:
|
|
1174
|
-
for key, rel in (('source_px', m.get('out')),
|
|
1175
|
-
('compressed_px', m.get('compressed_out'))):
|
|
1176
|
-
rec = m.get(key)
|
|
1177
|
-
if not rel or not rec:
|
|
1178
|
-
continue
|
|
1179
|
-
path = os.path.join(stage1, rel)
|
|
1180
|
-
if not os.path.exists(path):
|
|
1181
|
-
bad.append('%s 的 %s 指向 %s,文件不存在' % (m['media'], key, rel))
|
|
1182
|
-
continue
|
|
1183
|
-
try:
|
|
1184
|
-
with Image.open(path) as im:
|
|
1185
|
-
real = list(im.size)
|
|
1186
|
-
except Exception:
|
|
1187
|
-
continue
|
|
1188
|
-
if real != list(rec):
|
|
1189
|
-
bad.append('%s 的 %s 记录 %s,但 %s 实际是 %s'
|
|
1190
|
-
% (m['media'], key, rec, rel, real))
|
|
1191
|
-
if rel in seen and seen[rel] != m['media']:
|
|
1192
|
-
bad.append('%s 与 %s 都写到 %s' % (seen[rel], m['media'], rel))
|
|
1193
|
-
seen[rel] = m['media']
|
|
1194
|
-
return bad
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
def trace_check(pack, extract, shapes, derived_values, derived_tokens, factor):
|
|
1198
|
-
"""产物里每个 hex / 字号 / slot 坐标都必须可追溯到普查值或 derived 声明。"""
|
|
1199
|
-
idx = build_trace_index(extract, shapes)
|
|
1200
|
-
problems, checked = [], Counter()
|
|
1201
|
-
targets = [('design.md', frontmatter_of(os.path.join(pack, 'design.md'))),
|
|
1202
|
-
('layouts.md', frontmatter_of(os.path.join(pack, 'layouts.md')))]
|
|
1203
|
-
for fname, text in targets:
|
|
1204
|
-
if not text:
|
|
1205
|
-
continue
|
|
1206
|
-
for lineno, path, raw in _scan_keyed(text):
|
|
1207
|
-
if JUDGEMENT_KEYS & set(path):
|
|
1208
|
-
checked['judgement'] += 1
|
|
1209
|
-
continue
|
|
1210
|
-
exempt_token = any(k in derived_tokens for k in path)
|
|
1211
|
-
for m in HEX_RE.finditer(raw):
|
|
1212
|
-
val = '#' + m.group(1).upper()
|
|
1213
|
-
checked['hex'] += 1
|
|
1214
|
-
if exempt_token or val in derived_values:
|
|
1215
|
-
checked['exempt'] += 1
|
|
1216
|
-
continue
|
|
1217
|
-
ok, tip = _hex_hit(val, idx)
|
|
1218
|
-
if not ok:
|
|
1219
|
-
problems.append(('hex', fname, lineno, val, tip, '.'.join(path)))
|
|
1220
|
-
for m in FONTSIZE_RE.finditer(raw):
|
|
1221
|
-
val = float(m.group(1))
|
|
1222
|
-
checked['size'] += 1
|
|
1223
|
-
if exempt_token or m.group(1) in derived_values:
|
|
1224
|
-
checked['exempt'] += 1
|
|
1225
|
-
continue
|
|
1226
|
-
ok, tip = _size_hit(val, idx, factor)
|
|
1227
|
-
if not ok:
|
|
1228
|
-
problems.append(('fontSize', fname, lineno, '%gpx' % val, tip,
|
|
1229
|
-
'.'.join(path)))
|
|
1230
|
-
for m in BOX_RE.finditer(raw):
|
|
1231
|
-
box = [float(x) for x in m.groups()]
|
|
1232
|
-
checked['box'] += 1
|
|
1233
|
-
key = '[%s]' % ', '.join(m.groups())
|
|
1234
|
-
if exempt_token or key in derived_values:
|
|
1235
|
-
checked['exempt'] += 1
|
|
1236
|
-
continue
|
|
1237
|
-
ok, tip = _box_hit(box, idx)
|
|
1238
|
-
if not ok:
|
|
1239
|
-
problems.append(('slot box', fname, lineno,
|
|
1240
|
-
'[%g, %g, %g, %g]' % tuple(box), tip, '.'.join(path)))
|
|
1241
|
-
return problems, checked
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
def render_audit(manifest, extract, audit):
|
|
1245
|
-
L = ['# 审计元数据(从 design.md 剥离,消费模型不需要;机检与人工复核用)']
|
|
1246
|
-
src = extract['canvas']['source']
|
|
1247
|
-
L.append('canvas-source: {cx: %d, cy: %d, unit: %s}'
|
|
1248
|
-
% (src['cx'], src['cy'], src.get('unit', 'EMU')))
|
|
1249
|
-
for k in ('theme-mechanism', 'color-confidence'):
|
|
1250
|
-
if manifest.get(k):
|
|
1251
|
-
L.append('%s: %s' % (k, yaml_scalar(manifest[k])))
|
|
1252
|
-
if audit:
|
|
1253
|
-
L.append('assets:')
|
|
1254
|
-
for aid, au in audit.items():
|
|
1255
|
-
L.append(' %s:' % aid)
|
|
1256
|
-
if au.get('boxes'):
|
|
1257
|
-
L.append(' boxes:')
|
|
1258
|
-
for b in au['boxes']:
|
|
1259
|
-
L.append(' - [%d, %d, %d, %d]' % tuple(b))
|
|
1260
|
-
for f in ('aspect', 'mark', 'confidence'):
|
|
1261
|
-
if f in au:
|
|
1262
|
-
L.append(' %s: %s' % (f, yaml_scalar(au[f])))
|
|
1263
|
-
return '\n'.join(L) + '\n'
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
def _sha256(path):
|
|
1267
|
-
h = hashlib.sha256()
|
|
1268
|
-
with open(path, 'rb') as f:
|
|
1269
|
-
for chunk in iter(lambda: f.read(1024 * 1024), b''):
|
|
1270
|
-
h.update(chunk)
|
|
1271
|
-
return h.hexdigest()
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
def _rel_files(root):
|
|
1275
|
-
files = []
|
|
1276
|
-
for dirpath, dirnames, filenames in os.walk(root):
|
|
1277
|
-
dirnames.sort()
|
|
1278
|
-
for name in sorted(filenames):
|
|
1279
|
-
path = os.path.join(dirpath, name)
|
|
1280
|
-
files.append(os.path.relpath(path, root))
|
|
1281
|
-
return files
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
def build_package_manifest(manifest, consumer, audit, extract, pack):
|
|
1285
|
-
"""Machine index for the style package.
|
|
1286
|
-
|
|
1287
|
-
design.md remains the consumer entry. manifest.json is for storage/control
|
|
1288
|
-
planes: stable identity plus file and asset checksums.
|
|
1289
|
-
"""
|
|
1290
|
-
files = []
|
|
1291
|
-
for rel in _rel_files(pack):
|
|
1292
|
-
if rel == 'manifest.json':
|
|
1293
|
-
continue
|
|
1294
|
-
path = os.path.join(pack, rel)
|
|
1295
|
-
files.append({
|
|
1296
|
-
'path': rel,
|
|
1297
|
-
'bytes': os.path.getsize(path),
|
|
1298
|
-
'sha256': _sha256(path),
|
|
1299
|
-
})
|
|
1300
|
-
|
|
1301
|
-
assets = []
|
|
1302
|
-
for aid, entry in consumer.items():
|
|
1303
|
-
item = {'id': aid, 'kind': entry.get('kind')}
|
|
1304
|
-
for key in ('role', 'theme', 'on-bg', 'path', 'full', 'url', 'color'):
|
|
1305
|
-
if entry.get(key):
|
|
1306
|
-
item[key] = entry[key]
|
|
1307
|
-
for key in ('path', 'full'):
|
|
1308
|
-
rel = entry.get(key)
|
|
1309
|
-
if rel:
|
|
1310
|
-
path = os.path.join(pack, rel)
|
|
1311
|
-
if os.path.exists(path):
|
|
1312
|
-
item[key + '_bytes'] = os.path.getsize(path)
|
|
1313
|
-
item[key + '_sha256'] = _sha256(path)
|
|
1314
|
-
au = audit.get(aid) or {}
|
|
1315
|
-
if au.get('confidence'):
|
|
1316
|
-
item['confidence'] = au['confidence']
|
|
1317
|
-
assets.append(item)
|
|
1318
|
-
|
|
1319
|
-
files_digest = hashlib.sha256()
|
|
1320
|
-
for item in files:
|
|
1321
|
-
files_digest.update(item['path'].encode('utf-8'))
|
|
1322
|
-
files_digest.update(b'\0')
|
|
1323
|
-
files_digest.update(item['sha256'].encode('ascii'))
|
|
1324
|
-
files_digest.update(b'\0')
|
|
1325
|
-
files_digest.update(str(item['bytes']).encode('ascii'))
|
|
1326
|
-
files_digest.update(b'\n')
|
|
1327
|
-
|
|
1328
|
-
pkg = {
|
|
1329
|
-
'schemaVersion': 'pptx-style-package/v2',
|
|
1330
|
-
'id': manifest.get('name'),
|
|
1331
|
-
'name': manifest.get('name'),
|
|
1332
|
-
'name_zh': manifest.get('name_zh'),
|
|
1333
|
-
'version': manifest.get('version') or 'alpha',
|
|
1334
|
-
'description': manifest.get('description'),
|
|
1335
|
-
'entry': 'design.md',
|
|
1336
|
-
'layouts': 'layouts.md' if os.path.exists(os.path.join(pack, 'layouts.md')) else None,
|
|
1337
|
-
'canvas': '%dx%d' % tuple(extract['canvas']['px']),
|
|
1338
|
-
'source': {
|
|
1339
|
-
'filename': (extract.get('source') or {}).get('filename'),
|
|
1340
|
-
'content_type_kind': (extract.get('source') or {}).get('content_type_kind'),
|
|
1341
|
-
'is_template': (extract.get('source') or {}).get('is_template'),
|
|
1342
|
-
'bytes': (extract.get('source') or {}).get('bytes'),
|
|
1343
|
-
},
|
|
1344
|
-
'themes': manifest.get('themes') or ['single'],
|
|
1345
|
-
'default_theme': manifest.get('default-theme'),
|
|
1346
|
-
'files': files,
|
|
1347
|
-
'assets': assets,
|
|
1348
|
-
'totals': {
|
|
1349
|
-
'file_count': len(files),
|
|
1350
|
-
'bytes': sum(f['bytes'] for f in files),
|
|
1351
|
-
'sha256': files_digest.hexdigest(),
|
|
1352
|
-
'asset_count': len(assets),
|
|
1353
|
-
},
|
|
1354
|
-
}
|
|
1355
|
-
return {k: v for k, v in pkg.items() if v is not None}
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
def strip_agent_fast_path(body):
|
|
1359
|
-
if '## Agent Fast Path' not in body:
|
|
1360
|
-
return body
|
|
1361
|
-
return re.sub(r'\n?## Agent Fast Path\n.*?(?=\n## |\Z)', '\n', body,
|
|
1362
|
-
count=1, flags=re.S).lstrip('\n')
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
def build_design(manifest, l_frontmatter, consumer, body, has_sidecar, canvas):
|
|
1366
|
-
blocks = {k: (inline, lines) for k, inline, lines in l_frontmatter}
|
|
1367
|
-
bad = set(blocks) - L_FRONTMATTER_KEYS
|
|
1368
|
-
if bad:
|
|
1369
|
-
raise Fail('frontmatter.yaml 出现不该由 L 层提供的顶层键: %s'
|
|
1370
|
-
'(身份键写 manifest.yaml,assets/layouts 由脚本生成)'
|
|
1371
|
-
% ', '.join(sorted(bad)))
|
|
1372
|
-
out = ['---']
|
|
1373
|
-
for key in FRONTMATTER_ORDER:
|
|
1374
|
-
if key in ('version', 'name', 'name_zh', 'description'):
|
|
1375
|
-
block = (manifest.get('_raw') or {}).get(key)
|
|
1376
|
-
if block:
|
|
1377
|
-
out.append('%s:%s' % (key, (' ' + block[0]) if block[0] else ''))
|
|
1378
|
-
out += block[1]
|
|
1379
|
-
continue
|
|
1380
|
-
v = manifest.get(key) or ('alpha' if key == 'version' else None)
|
|
1381
|
-
if v:
|
|
1382
|
-
out.append('%s: %s' % (key, yaml_scalar(v)))
|
|
1383
|
-
elif key in ('themes', 'default-theme'):
|
|
1384
|
-
v = manifest.get(key)
|
|
1385
|
-
if isinstance(v, list):
|
|
1386
|
-
out.append('%s: [%s]' % (key, ', '.join(v)))
|
|
1387
|
-
elif v:
|
|
1388
|
-
out.append('%s: %s' % (key, yaml_scalar(v)))
|
|
1389
|
-
elif key == 'assets':
|
|
1390
|
-
if consumer:
|
|
1391
|
-
out += render_assets_block(consumer)
|
|
1392
|
-
elif key == 'layouts':
|
|
1393
|
-
if has_sidecar:
|
|
1394
|
-
out.append('layouts: layouts.md')
|
|
1395
|
-
elif key in blocks:
|
|
1396
|
-
inline, lines = blocks[key]
|
|
1397
|
-
out.append('%s:%s' % (key, (' ' + inline) if inline else ''))
|
|
1398
|
-
out += lines
|
|
1399
|
-
if key == 'exceptions' and not has_sidecar and canvas:
|
|
1400
|
-
out.append('canvas: %dx%d' % tuple(canvas))
|
|
1401
|
-
out.append('---')
|
|
1402
|
-
text = '\n'.join(out) + '\n'
|
|
1403
|
-
# Fast Path 已废弃:它是 Usage / Hard Rules / 资产表 / 页型清单的第二份副本。
|
|
1404
|
-
# 规则的唯一出处是正文各段,这里只负责把历史产物里的残留剥掉。
|
|
1405
|
-
body = strip_agent_fast_path(body)
|
|
1406
|
-
if body:
|
|
1407
|
-
text += body if body.startswith('\n') else '\n' + body
|
|
1408
|
-
if not text.endswith('\n'):
|
|
1409
|
-
text += '\n'
|
|
1410
|
-
return text
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
def layout_forms(lines):
|
|
1414
|
-
"""每个页型草案里实际给了哪几种形态(flow / slots)。"""
|
|
1415
|
-
out, cur = {}, None
|
|
1416
|
-
for line in lines:
|
|
1417
|
-
m = re.match(r'^ ([\w-]+):\s*$', line)
|
|
1418
|
-
if m:
|
|
1419
|
-
cur = m.group(1)
|
|
1420
|
-
out[cur] = set()
|
|
1421
|
-
continue
|
|
1422
|
-
m = re.match(r'^ (flow|slots):\s*$', line)
|
|
1423
|
-
if m and cur:
|
|
1424
|
-
out[cur].add(m.group(1))
|
|
1425
|
-
return out
|
|
1426
|
-
|
|
1427
|
-
|
|
1428
|
-
def layout_modes(lines):
|
|
1429
|
-
"""读取扁平 `layout_modes:` 判断区。"""
|
|
1430
|
-
out = {}
|
|
1431
|
-
for line in lines:
|
|
1432
|
-
m = re.match(r'^\s{2}([\w-]+):\s*([^\s#]+)', line)
|
|
1433
|
-
if m:
|
|
1434
|
-
out[m.group(1)] = m.group(2).strip()
|
|
1435
|
-
return out
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
def text_role_boxes(lines):
|
|
1439
|
-
"""从 slots 里的同名标记取回文本槽坐标,供 flow 固定锚点复用。"""
|
|
1440
|
-
out, pending = {}, None
|
|
1441
|
-
for line in lines:
|
|
1442
|
-
marker = re.match(r'^\s*#\s*text-role:\s*([\w-]+)\s*$', line)
|
|
1443
|
-
if marker:
|
|
1444
|
-
pending = marker.group(1)
|
|
1445
|
-
continue
|
|
1446
|
-
if pending:
|
|
1447
|
-
box = re.search(r'\bbox:\s*(\[[^\]]+\])', line)
|
|
1448
|
-
if box:
|
|
1449
|
-
out[pending] = box.group(1)
|
|
1450
|
-
pending = None
|
|
1451
|
-
return out
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
def select_layout_forms(lines, modes):
|
|
1455
|
-
"""按 `layout_modes` 只保留每个页型选中的 flow 或 slots。"""
|
|
1456
|
-
forms = layout_forms(lines)
|
|
1457
|
-
out, layout, drop = [], None, False
|
|
1458
|
-
for line in lines:
|
|
1459
|
-
layout_match = re.match(r'^ ([\w-]+):\s*$', line)
|
|
1460
|
-
form_match = re.match(r'^ (flow|slots):\s*$', line)
|
|
1461
|
-
if layout_match:
|
|
1462
|
-
layout, drop = layout_match.group(1), False
|
|
1463
|
-
elif form_match:
|
|
1464
|
-
selected = modes.get(layout)
|
|
1465
|
-
if selected is None and len(forms.get(layout) or ()) >= 2:
|
|
1466
|
-
selected = 'slots'
|
|
1467
|
-
drop = selected is not None and selected != form_match.group(1)
|
|
1468
|
-
elif drop and re.match(r'^ \S', line):
|
|
1469
|
-
drop = False
|
|
1470
|
-
if not drop:
|
|
1471
|
-
out.append(line)
|
|
1472
|
-
return out
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
def shrink_safe_area(lines):
|
|
1476
|
-
"""text_safe 与 avoid 相交时把安全区收掉重叠的那部分。
|
|
1477
|
-
|
|
1478
|
-
text_safe 是脚本按「该背景各页型的槽位并集」算的,而模板里的槽位本身可能就压在
|
|
1479
|
-
主视觉上;avoid 是看图的人填的。两者从不同来源来,会直接打架——实测一张背景的
|
|
1480
|
-
text_safe 有 34% 落在 avoid 里,消费端按 text_safe 把标题放进了禁放区,正好压在
|
|
1481
|
-
背景的山峰主体上。这里以 avoid 为准收缩:能不能放字是看图的人说了算。
|
|
1482
|
-
"""
|
|
1483
|
-
def parse_box(s):
|
|
1484
|
-
m = re.findall(r'-?\d+', s)
|
|
1485
|
-
return [int(x) for x in m[:4]] if len(m) >= 4 else None
|
|
1486
|
-
|
|
1487
|
-
ts_i = ts = None
|
|
1488
|
-
avoids = []
|
|
1489
|
-
for i, ln in enumerate(lines):
|
|
1490
|
-
st = ln.strip()
|
|
1491
|
-
if st.startswith('text_safe:'):
|
|
1492
|
-
ts_i, ts = i, parse_box(st.split(':', 1)[1].split('#')[0])
|
|
1493
|
-
elif st.startswith('avoid:'):
|
|
1494
|
-
for chunk in re.findall(r'box:\s*\[[^\]]*\]', st):
|
|
1495
|
-
b = parse_box(chunk)
|
|
1496
|
-
if b:
|
|
1497
|
-
avoids.append(b)
|
|
1498
|
-
if ts is None or not avoids:
|
|
1499
|
-
return lines, None
|
|
1500
|
-
x0, y0, x1, y1 = ts[0], ts[1], ts[0] + ts[2], ts[1] + ts[3]
|
|
1501
|
-
for a in avoids:
|
|
1502
|
-
ax0, ay0, ax1, ay1 = a[0], a[1], a[0] + a[2], a[1] + a[3]
|
|
1503
|
-
if ax1 <= x0 or ax0 >= x1 or ay1 <= y0 or ay0 >= y1:
|
|
1504
|
-
continue # 不相交
|
|
1505
|
-
# 从被侵占得最少的一边切:优先保留面积最大的剩余矩形
|
|
1506
|
-
cands = []
|
|
1507
|
-
if ax0 > x0:
|
|
1508
|
-
cands.append((x0, y0, ax0, y1))
|
|
1509
|
-
if ax1 < x1:
|
|
1510
|
-
cands.append((ax1, y0, x1, y1))
|
|
1511
|
-
if ay0 > y0:
|
|
1512
|
-
cands.append((x0, y0, x1, ay0))
|
|
1513
|
-
if ay1 < y1:
|
|
1514
|
-
cands.append((x0, ay1, x1, y1))
|
|
1515
|
-
if not cands:
|
|
1516
|
-
return lines, 'text_safe 被 avoid 完全覆盖,这张背景没有可放文字的区域'
|
|
1517
|
-
x0, y0, x1, y1 = max(cands, key=lambda c: (c[2] - c[0]) * (c[3] - c[1]))
|
|
1518
|
-
new = [x0, y0, x1 - x0, y1 - y0]
|
|
1519
|
-
if new == ts:
|
|
1520
|
-
return lines, None
|
|
1521
|
-
lines = list(lines)
|
|
1522
|
-
lines[ts_i] = ' text_safe: [%d, %d, %d, %d] # 已按 avoid 收缩(原 %s)' % (
|
|
1523
|
-
new[0], new[1], new[2], new[3], ts)
|
|
1524
|
-
return lines, None
|
|
1525
|
-
|
|
1526
|
-
|
|
1527
|
-
def resolve_asset_candidate_lines(lines, decisions, asset_ids):
|
|
1528
|
-
"""把 source_media 临时字段转成资产引用;内容图保留通用 pic 槽。"""
|
|
1529
|
-
out = []
|
|
1530
|
-
content_slots = set()
|
|
1531
|
-
layout_name, layout_form = None, None
|
|
1532
|
-
for line in lines:
|
|
1533
|
-
layout_match = re.match(r'^ ([\w-]+):\s*$', line)
|
|
1534
|
-
form_match = re.match(r'^ (flow|slots):\s*$', line)
|
|
1535
|
-
if layout_match:
|
|
1536
|
-
layout_name, layout_form = layout_match.group(1), None
|
|
1537
|
-
elif form_match:
|
|
1538
|
-
layout_form = form_match.group(1)
|
|
1539
|
-
match = re.search(r'\bsource_media:\s*([^,}]+)', line)
|
|
1540
|
-
if not match:
|
|
1541
|
-
out.append(line)
|
|
1542
|
-
continue
|
|
1543
|
-
source = unquote(match.group(1).strip())
|
|
1544
|
-
candidate_box = source_box(line) or slot_box(line)
|
|
1545
|
-
decision = (decisions.for_slot(source, line, layout_name)
|
|
1546
|
-
if isinstance(decisions, AssetDecisions)
|
|
1547
|
-
else decisions.get(source))
|
|
1548
|
-
line = re.sub(r'\s*,?\s*source_media:\s*[^,}]+', '', line, count=1)
|
|
1549
|
-
line = re.sub(r'\s*,?\s*source_box:\s*\[[^\]]+\]', '', line, count=1)
|
|
1550
|
-
# 预算裁掉、没有进入视觉组的素材不凭空判成风格资产;保留原位置通用图片槽,
|
|
1551
|
-
# 让生成侧可放这一页的内容图。`omit` 是页码/水印等纯噪声,直接去掉槽。
|
|
1552
|
-
if decision == 'omit':
|
|
1553
|
-
continue
|
|
1554
|
-
if decision in (None, 'content'):
|
|
1555
|
-
line = re.sub(r'\s*,?\s*asset:\s*[^,}]+', '', line, count=1)
|
|
1556
|
-
line = re.sub(r'(\brole:\s*)[\w-]+', r'\g<1>pic', line, count=1)
|
|
1557
|
-
# 内容图不进风格资产,但同一位置只能留一个通用图片槽。不同图片源在同一
|
|
1558
|
-
# box 的叠加是原 PPT 的内容选择,不应被转换成两个生成时必然重叠的 pic 槽。
|
|
1559
|
-
content_key = (layout_name, layout_form, candidate_box or line.strip())
|
|
1560
|
-
if content_key in content_slots:
|
|
1561
|
-
continue
|
|
1562
|
-
content_slots.add(content_key)
|
|
1563
|
-
out.append(line)
|
|
1564
|
-
continue
|
|
1565
|
-
aid = (asset_ids.for_decision(source, decision)
|
|
1566
|
-
if isinstance(asset_ids, AssetIds) else asset_ids.get(source))
|
|
1567
|
-
if not aid:
|
|
1568
|
-
raise Fail('layouts.yaml 引用了未完成资产判断的 source_media: %s' % source)
|
|
1569
|
-
if re.search(r'\basset:\s*[^,}]+', line):
|
|
1570
|
-
line = re.sub(r'(\basset:\s*)[^,}]+', r'\g<1>%s' % aid, line, count=1)
|
|
1571
|
-
else:
|
|
1572
|
-
line = line.replace('}', ', asset: %s}' % aid, 1)
|
|
1573
|
-
line = re.sub(r'(\brole:\s*)[\w-]+', r'\g<1>%s' % decision, line, count=1)
|
|
1574
|
-
out.append(line)
|
|
1575
|
-
return out
|
|
1576
|
-
|
|
1577
|
-
|
|
1578
|
-
def build_layouts_md(layouts_blocks, canvas, asset_decisions=None, asset_ids=None):
|
|
1579
|
-
blocks = {k: (inline, lines) for k, inline, lines in layouts_blocks}
|
|
1580
|
-
if 'canvas' in blocks:
|
|
1581
|
-
raise Fail('layouts.yaml 不要写 canvas —— 脚本从 extract.json 取')
|
|
1582
|
-
if 'layouts' not in blocks:
|
|
1583
|
-
raise Fail('layouts.yaml 缺顶层键 `layouts:`')
|
|
1584
|
-
# `names:` / `roles:` / `text_roles:` / `layout_modes:` / `bg_rules:` 是给 L 层集中填判断的
|
|
1585
|
-
# 扁平区——在这里并回各 archetype,本身不进产物。让 L 层只改扁平键值,别去动 layouts 里的
|
|
1586
|
-
# slots/confidence 结构(嵌套结构手改极易破坏缩进,进而静默改变语义)。
|
|
1587
|
-
names, roles = {}, {}
|
|
1588
|
-
for key, sink in (('names', names), ('roles', roles)):
|
|
1589
|
-
for line in blocks.get(key, ('', []))[1]:
|
|
1590
|
-
m = re.match(r'^\s{2}([\w-]+):\s*(.+?)\s*$', line)
|
|
1591
|
-
if m:
|
|
1592
|
-
sink[m.group(1)] = unquote(m.group(2))
|
|
1593
|
-
text_roles = {}
|
|
1594
|
-
allowed_text_roles = {'title', 'subtitle', 'header', 'footer', 'body'}
|
|
1595
|
-
for line in blocks.get('text_roles', ('', []))[1]:
|
|
1596
|
-
m = re.match(r'^\s{2}([\w-]+):\s*([A-Za-z-]+)(?:\s+#.*)?$', line)
|
|
1597
|
-
if not m:
|
|
1598
|
-
continue
|
|
1599
|
-
role_id, role = m.groups()
|
|
1600
|
-
if role not in allowed_text_roles:
|
|
1601
|
-
raise Fail('text_roles.%s 取值 %s 非法;应为 %s'
|
|
1602
|
-
% (role_id, role, '|'.join(sorted(allowed_text_roles))))
|
|
1603
|
-
text_roles[role_id] = role
|
|
1604
|
-
bg_rules, cur = {}, None
|
|
1605
|
-
for line in blocks.get('bg_rules', ('', []))[1]:
|
|
1606
|
-
# 键后面允许行内注释(草案会标「用它的页型:…」)
|
|
1607
|
-
m = re.match(r'^\s{2}([\w-]+):\s*(?:#.*)?$', line)
|
|
1608
|
-
if m:
|
|
1609
|
-
cur = m.group(1)
|
|
1610
|
-
bg_rules[cur] = []
|
|
1611
|
-
continue
|
|
1612
|
-
if cur and line.strip():
|
|
1613
|
-
bg_rules[cur].append(' ' + line.strip())
|
|
1614
|
-
out = ['---', 'canvas: %dx%d' % tuple(canvas)]
|
|
1615
|
-
# 禁放区是背景的属性,按背景写一次;页型只留 `background:` 指针。
|
|
1616
|
-
# 合并进每个页型会把同一句话按页型数复制 N 遍。
|
|
1617
|
-
if bg_rules:
|
|
1618
|
-
out.append('backgrounds:')
|
|
1619
|
-
for bg, lines in bg_rules.items():
|
|
1620
|
-
lines, err = shrink_safe_area(lines)
|
|
1621
|
-
if err:
|
|
1622
|
-
raise Fail('%s: %s' % (bg, err))
|
|
1623
|
-
out.append(' %s:' % bg)
|
|
1624
|
-
out += lines
|
|
1625
|
-
modes = layout_modes(blocks.get('layout_modes', ('', []))[1])
|
|
1626
|
-
decided_layout_roles = set(roles)
|
|
1627
|
-
out.append('layouts:')
|
|
1628
|
-
pending_text_role = None
|
|
1629
|
-
used_text_roles = set()
|
|
1630
|
-
decisions = asset_decisions if asset_decisions is not None else {}
|
|
1631
|
-
resolved_asset_ids = asset_ids if asset_ids is not None else {}
|
|
1632
|
-
source_layout_lines = resolve_asset_candidate_lines(
|
|
1633
|
-
blocks['layouts'][1], decisions, resolved_asset_ids)
|
|
1634
|
-
role_boxes = text_role_boxes(source_layout_lines)
|
|
1635
|
-
layout_lines = select_layout_forms(source_layout_lines, modes)
|
|
1636
|
-
cur, fixed_items = None, []
|
|
1637
|
-
emitted_roles = set()
|
|
1638
|
-
|
|
1639
|
-
def flush_fixed_items():
|
|
1640
|
-
if not fixed_items:
|
|
1641
|
-
return
|
|
1642
|
-
out.append(' - kind: free')
|
|
1643
|
-
out.append(' items:')
|
|
1644
|
-
out.extend(fixed_items)
|
|
1645
|
-
fixed_items.clear()
|
|
1646
|
-
|
|
1647
|
-
for line in layout_lines:
|
|
1648
|
-
m = re.match(r'^ ([\w-]+):\s*$', line)
|
|
1649
|
-
if m:
|
|
1650
|
-
flush_fixed_items()
|
|
1651
|
-
cur = m.group(1)
|
|
1652
|
-
elif fixed_items and re.match(r'^ \S', line):
|
|
1653
|
-
flush_fixed_items()
|
|
1654
|
-
if cur in decided_layout_roles and re.match(r'^ role:\s*', line):
|
|
1655
|
-
# 页型草案中的 role 只是初始值;最终语义只由扁平 roles 判断单决定。
|
|
1656
|
-
# 否则两者同时写入会产生重复 YAML 键,并让后面的草案默认值覆盖模型判断。
|
|
1657
|
-
continue
|
|
1658
|
-
# 判断单里的结构事实(栅格、间距序列、样张字数、命中配方)是给 L 层判断用的,
|
|
1659
|
-
# 不进产物——消费端要的是结论,不是推导过程。layout_mode 同理,它是判断的载体。
|
|
1660
|
-
if line.lstrip().startswith('#'):
|
|
1661
|
-
marker = re.match(r'^\s*#\s*text-role:\s*([\w-]+)\s*$', line)
|
|
1662
|
-
if marker:
|
|
1663
|
-
pending_text_role = marker.group(1)
|
|
1664
|
-
continue
|
|
1665
|
-
if pending_text_role:
|
|
1666
|
-
role = text_roles.get(pending_text_role)
|
|
1667
|
-
if role:
|
|
1668
|
-
# header 是语义角色,V2 没有同名的渲染 slot type;保留 role 供消费端
|
|
1669
|
-
# 识别固定页眉,同时用 body 通过 V2 的类型枚举。
|
|
1670
|
-
slot_type = role if role in ('title', 'subtitle', 'footer') else 'body'
|
|
1671
|
-
line, role_n = re.subn(r'(\{\s*role:\s*)[\w-]+',
|
|
1672
|
-
r'\g<1>%s' % role, line, count=1)
|
|
1673
|
-
line, type_n = re.subn(r'(\btype:\s*)[\w-]+',
|
|
1674
|
-
r'\g<1>%s' % slot_type, line, count=1)
|
|
1675
|
-
if role_n != 1 or type_n != 1:
|
|
1676
|
-
raise Fail('text_roles.%s 没有命中一个文本槽' % pending_text_role)
|
|
1677
|
-
if (modes.get(cur) == 'flow' and role in ('header', 'footer')
|
|
1678
|
-
and re.match(r'^\s{12}-\s*\{', line) and 'box:' not in line):
|
|
1679
|
-
box = role_boxes.get(pending_text_role)
|
|
1680
|
-
if not box:
|
|
1681
|
-
raise Fail('text_roles.%s 识别为 %s,但 slots 中没有坐标'
|
|
1682
|
-
% (pending_text_role, role))
|
|
1683
|
-
line = re.sub(r',\s*type:', ', box: %s, type:' % box, line, count=1)
|
|
1684
|
-
fixed_items.append(line)
|
|
1685
|
-
used_text_roles.add(pending_text_role)
|
|
1686
|
-
pending_text_role = None
|
|
1687
|
-
continue
|
|
1688
|
-
used_text_roles.add(pending_text_role)
|
|
1689
|
-
pending_text_role = None
|
|
1690
|
-
out.append(line)
|
|
1691
|
-
if cur and re.match(r'^ role:\s*', line):
|
|
1692
|
-
emitted_roles.add(cur)
|
|
1693
|
-
if m and m.group(1) in names:
|
|
1694
|
-
out.append(' name: "%s"' % names.pop(m.group(1)))
|
|
1695
|
-
if m and m.group(1) in roles:
|
|
1696
|
-
out.append(' role: %s' % roles.pop(m.group(1)))
|
|
1697
|
-
emitted_roles.add(m.group(1))
|
|
1698
|
-
flush_fixed_items()
|
|
1699
|
-
if names:
|
|
1700
|
-
raise Fail('names 里这些页型在 layouts 下找不到:%s' % ', '.join(sorted(names)))
|
|
1701
|
-
if roles:
|
|
1702
|
-
raise Fail('roles 里这些页型在 layouts 下找不到:%s' % ', '.join(sorted(roles)))
|
|
1703
|
-
unused_text_roles = set(text_roles) - used_text_roles
|
|
1704
|
-
if unused_text_roles:
|
|
1705
|
-
raise Fail('text_roles 里这些判断没有命中文本槽:%s'
|
|
1706
|
-
% ', '.join(sorted(unused_text_roles)))
|
|
1707
|
-
missing_role = [
|
|
1708
|
-
k for k in re.findall(r'^ ([\w-]+):\s*$', '\n'.join(blocks['layouts'][1]), re.M)
|
|
1709
|
-
if k not in emitted_roles
|
|
1710
|
-
]
|
|
1711
|
-
if missing_role:
|
|
1712
|
-
raise Fail('这些页型没有 role(在 layouts.yaml 的 roles 段填):%s' % ', '.join(missing_role))
|
|
1713
|
-
# 未声明 layout_modes 时默认 slots:固定坐标是从原 PPT 直接普查的安全交付形态。
|
|
1714
|
-
# 模型只在看样张确认内容需要随高度重排时显式改为 flow。
|
|
1715
|
-
forms = layout_forms(blocks['layouts'][1])
|
|
1716
|
-
bad = []
|
|
1717
|
-
for k, v in sorted(modes.items()):
|
|
1718
|
-
if len(forms.get(k) or ()) < 2:
|
|
1719
|
-
continue # 只有一份形态,无从选择
|
|
1720
|
-
if v not in ('flow', 'slots'):
|
|
1721
|
-
bad.append('%s 的 layout_modes 判断是 %r' % (k, v))
|
|
1722
|
-
elif v not in forms[k]:
|
|
1723
|
-
bad.append('%s 选了 %s 但该页型没有这一份' % (k, v))
|
|
1724
|
-
if bad:
|
|
1725
|
-
raise Fail('layout_modes 只能填 flow 或 slots,一个页型一个词:%s' % ';'.join(bad))
|
|
1726
|
-
declared = set(re.findall(r'^ background:\s*(\S+)\s*$',
|
|
1727
|
-
'\n'.join(blocks['layouts'][1]), re.M))
|
|
1728
|
-
stray = set(bg_rules) - declared
|
|
1729
|
-
if stray:
|
|
1730
|
-
raise Fail('backgrounds 段里这些背景没有任何页型在用:%s' % ', '.join(sorted(stray)))
|
|
1731
|
-
out.append('---')
|
|
1732
|
-
text = '\n'.join(out) + '\n'
|
|
1733
|
-
if 'body' in blocks:
|
|
1734
|
-
body = scalar_of(blocks['body'][0], blocks['body'][1])
|
|
1735
|
-
if body:
|
|
1736
|
-
text += '\n' + body.rstrip('\n') + '\n'
|
|
1737
|
-
return text
|
|
1738
|
-
|
|
1739
|
-
|
|
1740
|
-
# --------------------------------------------------------------------- 主流程
|
|
1741
|
-
|
|
1742
|
-
def _autodetect_check_v1():
|
|
1743
|
-
skill_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
1744
|
-
for cand in (os.environ.get('DSM_V1_DIR'),
|
|
1745
|
-
os.path.join(os.path.dirname(skill_root), 'miaoda-design-system-extract'),
|
|
1746
|
-
os.path.expanduser('~/dev/gitlab/miaoda_workspace/.agents/skills/miaoda-design-system-extract')):
|
|
1747
|
-
if cand and os.path.isfile(os.path.join(cand, 'scripts', 'check_v1.py')):
|
|
1748
|
-
return os.path.join(cand, 'scripts', 'check_v1.py')
|
|
1749
|
-
return None
|
|
1750
|
-
|
|
1751
|
-
|
|
1752
|
-
def main(argv=None):
|
|
1753
|
-
ap = argparse.ArgumentParser(add_help=True)
|
|
1754
|
-
ap.add_argument('stage1')
|
|
1755
|
-
ap.add_argument('lout')
|
|
1756
|
-
ap.add_argument('pack')
|
|
1757
|
-
ap.add_argument('--check-v1', default=None, help='check_v1.py 路径;缺省自动探测($DSM_V1_DIR → 同级 skill → 开发机路径)')
|
|
1758
|
-
ap.add_argument('--style-name', default=None)
|
|
1759
|
-
ap.add_argument('--force', action='store_true')
|
|
1760
|
-
args = ap.parse_args(argv)
|
|
1761
|
-
|
|
1762
|
-
stage1, lout, pack = (os.path.abspath(p) for p in (args.stage1, args.lout, args.pack))
|
|
1763
|
-
ex_path = os.path.join(stage1, 'extract.json')
|
|
1764
|
-
if not os.path.exists(ex_path):
|
|
1765
|
-
raise Fail('找不到 %s' % ex_path)
|
|
1766
|
-
extract = json.load(open(ex_path, encoding='utf-8'))
|
|
1767
|
-
|
|
1768
|
-
need = ['manifest.yaml', 'frontmatter.yaml', 'body.md']
|
|
1769
|
-
for f in need:
|
|
1770
|
-
if not os.path.exists(os.path.join(lout, f)):
|
|
1771
|
-
raise Fail('判断单缺 %s(schema 见本脚本 docstring)' % f)
|
|
1772
|
-
if os.path.isdir(pack) and os.listdir(pack) and not args.force:
|
|
1773
|
-
raise Fail('%s 非空;加 --force 覆盖' % pack)
|
|
1774
|
-
|
|
1775
|
-
left = []
|
|
1776
|
-
control_path = os.path.join(lout, 'layout-controls.yaml')
|
|
1777
|
-
draft_files = ['manifest.yaml', 'frontmatter.yaml', 'body.md']
|
|
1778
|
-
# 新草案的可编辑判断已移到小型控制文件;layouts.yaml 中保留的旧控制区只是
|
|
1779
|
-
# 兼容坐标事实,仍含 TODO 也不会进入最终 layouts.md。
|
|
1780
|
-
draft_files.append('layout-controls.yaml' if os.path.exists(control_path)
|
|
1781
|
-
else 'layouts.yaml')
|
|
1782
|
-
for f in draft_files:
|
|
1783
|
-
p = os.path.join(lout, f)
|
|
1784
|
-
if not os.path.exists(p):
|
|
1785
|
-
continue
|
|
1786
|
-
for i, line in enumerate(open(p, encoding='utf-8'), 1):
|
|
1787
|
-
if 'TODO' in line:
|
|
1788
|
-
left.append('%s:%d %s' % (f, i, line.strip()[:90]))
|
|
1789
|
-
if left:
|
|
1790
|
-
raise Fail('判断单还有 %d 处草案占位没改(TODO 是 draft.py 留给 L 层的判断点):\n %s'
|
|
1791
|
-
% (len(left), '\n '.join(left)))
|
|
1792
|
-
mdesc = re.search(r'^description:\s*[|>]?\s*\n((?:\s+\S.*\n?)+)',
|
|
1793
|
-
open(os.path.join(lout, 'manifest.yaml'), encoding='utf-8').read(), re.M)
|
|
1794
|
-
if mdesc and len(re.sub(r'\s+', '', mdesc.group(1))) < 20:
|
|
1795
|
-
raise Fail('manifest 的 description 只有 %d 个字符——它是消费模型定调的唯一入口,'
|
|
1796
|
-
'写清底色/主色/字形/版面骨架,不要留占位'
|
|
1797
|
-
% len(re.sub(r'\s+', '', mdesc.group(1))))
|
|
1798
|
-
|
|
1799
|
-
manifest = read_manifest(os.path.join(lout, 'manifest.yaml'))
|
|
1800
|
-
bind_asset_vision_group_scopes(lout, manifest)
|
|
1801
|
-
if args.style_name:
|
|
1802
|
-
manifest['name'] = args.style_name
|
|
1803
|
-
if not manifest.get('name'):
|
|
1804
|
-
raise Fail('manifest.yaml 缺 name')
|
|
1805
|
-
themes = manifest.get('themes')
|
|
1806
|
-
if isinstance(themes, list) and len(themes) > 1 and not manifest.get('default-theme'):
|
|
1807
|
-
raise Fail('themes 有 %d 个主题,必须给 default-theme(V2-13)' % len(themes))
|
|
1808
|
-
|
|
1809
|
-
l_fm = split_top_blocks(open(os.path.join(lout, 'frontmatter.yaml'),
|
|
1810
|
-
encoding='utf-8').read())
|
|
1811
|
-
body = open(os.path.join(lout, 'body.md'), encoding='utf-8').read()
|
|
1812
|
-
layouts_blocks = load_layout_blocks(lout)
|
|
1813
|
-
bound_sources, bound_slots = set(), defaultdict(set)
|
|
1814
|
-
if layouts_blocks is not None:
|
|
1815
|
-
for key, _, lines in layouts_blocks:
|
|
1816
|
-
layout_name = None
|
|
1817
|
-
for line in lines:
|
|
1818
|
-
layout_match = re.match(r'^ ([\w-]+):\s*$', line)
|
|
1819
|
-
if layout_match:
|
|
1820
|
-
layout_name = layout_match.group(1)
|
|
1821
|
-
match = re.search(r'\bsource_media:\s*([^,}]+)', line)
|
|
1822
|
-
if match:
|
|
1823
|
-
source = unquote(match.group(1).strip())
|
|
1824
|
-
bound_sources.add(source)
|
|
1825
|
-
box = source_box(line) or slot_box(line)
|
|
1826
|
-
if key == 'layouts' and box is not None:
|
|
1827
|
-
bound_slots[source].add((layout_name, box))
|
|
1828
|
-
has_asset_judgments = bool(
|
|
1829
|
-
manifest.get('asset_vision_groups') or manifest.get('asset_decisions'))
|
|
1830
|
-
asset_decisions, asset_ids = apply_asset_decisions(
|
|
1831
|
-
manifest,
|
|
1832
|
-
bound_sources=bound_sources if has_asset_judgments else None,
|
|
1833
|
-
bound_slots=bound_slots if has_asset_judgments else None)
|
|
1834
|
-
canvas = extract['canvas']['px']
|
|
1835
|
-
final_layouts = (build_layouts_md(
|
|
1836
|
-
layouts_blocks, canvas, asset_decisions=asset_decisions, asset_ids=asset_ids)
|
|
1837
|
-
if layouts_blocks is not None else None)
|
|
1838
|
-
|
|
1839
|
-
os.makedirs(pack, exist_ok=True)
|
|
1840
|
-
consumer, audit, copied = place_assets(manifest, extract, stage1, pack)
|
|
1841
|
-
|
|
1842
|
-
lay_text = final_layouts or ''
|
|
1843
|
-
body = expand_placeholders(body, manifest, consumer, audit, extract, lay_text)
|
|
1844
|
-
design = build_design(manifest, l_fm, consumer, body,
|
|
1845
|
-
has_sidecar=layouts_blocks is not None, canvas=canvas)
|
|
1846
|
-
with open(os.path.join(pack, 'design.md'), 'w', encoding='utf-8') as f:
|
|
1847
|
-
f.write(design)
|
|
1848
|
-
if layouts_blocks is not None:
|
|
1849
|
-
with open(os.path.join(pack, 'layouts.md'), 'w', encoding='utf-8') as f:
|
|
1850
|
-
f.write(final_layouts)
|
|
1851
|
-
|
|
1852
|
-
# 审计记录写回**抽取工作目录**,不进交付包:包是消费产物,`ref/` 里的东西
|
|
1853
|
-
# 没有任何门禁读、消费模型也用不上,放进去只会让「别读我」和「几 MB 材料」同时下发。
|
|
1854
|
-
ref = os.path.join(stage1, 'ref')
|
|
1855
|
-
os.makedirs(ref, exist_ok=True)
|
|
1856
|
-
audit_path = os.path.join(ref, 'audit.yaml')
|
|
1857
|
-
with open(audit_path, 'w', encoding='utf-8') as f:
|
|
1858
|
-
f.write(render_audit(manifest, extract, audit))
|
|
1859
|
-
carried = []
|
|
1860
|
-
# L 层自备的 ref 补充件(判断理由、版式溯源等)也归到抽取目录
|
|
1861
|
-
l_ref = os.path.join(lout, 'ref')
|
|
1862
|
-
if os.path.isdir(l_ref):
|
|
1863
|
-
shutil.copytree(l_ref, ref, dirs_exist_ok=True)
|
|
1864
|
-
carried.append('(L 层 ref/)')
|
|
1865
|
-
|
|
1866
|
-
with open(os.path.join(pack, 'manifest.json'), 'w', encoding='utf-8') as f:
|
|
1867
|
-
json.dump(build_package_manifest(manifest, consumer, audit, extract, pack),
|
|
1868
|
-
f, ensure_ascii=False, indent=2, sort_keys=True)
|
|
1869
|
-
f.write('\n')
|
|
1870
|
-
|
|
1871
|
-
print('pack → %s' % pack)
|
|
1872
|
-
print(' design.md %d 行 / %.1f KB%s'
|
|
1873
|
-
% (len(design.splitlines()), len(design.encode()) / 1024.0,
|
|
1874
|
-
' layouts.md sidecar' if layouts_blocks is not None else ' (layouts 内联/缺省)'))
|
|
1875
|
-
print(' assets %d 条目 / %d 文件落盘' % (len(consumer), len(copied)))
|
|
1876
|
-
for d in copied:
|
|
1877
|
-
print(' %-52s %8d B' % (os.path.relpath(d, pack), os.path.getsize(d)))
|
|
1878
|
-
print(' 审计记录 -> %s%s(不进交付包)'
|
|
1879
|
-
% (os.path.relpath(audit_path, os.path.dirname(stage1)),
|
|
1880
|
-
' ' + ', '.join(carried) if carried else ''))
|
|
1881
|
-
|
|
1882
|
-
# ---- 数值可追溯机检:产物里每个色值/字号/坐标都得能指回普查值
|
|
1883
|
-
derived_values, derived_tokens = set(), set()
|
|
1884
|
-
for d in manifest.get('derived') or []:
|
|
1885
|
-
if d.get('value'):
|
|
1886
|
-
v = unquote(d['value'])
|
|
1887
|
-
derived_values.add(v.upper() if v.startswith('#') else v)
|
|
1888
|
-
if d.get('token'):
|
|
1889
|
-
derived_tokens.add(unquote(d['token']))
|
|
1890
|
-
try:
|
|
1891
|
-
factor = float(manifest.get('rebase_factor') or 0) or None
|
|
1892
|
-
except ValueError:
|
|
1893
|
-
raise Fail('rebase_factor 不是数字: %r' % manifest.get('rebase_factor'))
|
|
1894
|
-
sp = os.path.join(stage1, 'ref', 'shapes.json')
|
|
1895
|
-
shapes = json.load(open(sp, encoding='utf-8'))['shapes'] if os.path.exists(sp) else []
|
|
1896
|
-
problems, checked = trace_check(pack, extract, shapes,
|
|
1897
|
-
derived_values, derived_tokens, factor)
|
|
1898
|
-
integrity = media_integrity(stage1, extract)
|
|
1899
|
-
if integrity:
|
|
1900
|
-
print('\n--- 媒体产物完整性 ---')
|
|
1901
|
-
for b in integrity:
|
|
1902
|
-
print(' FAIL ' + b)
|
|
1903
|
-
raise Fail('media-out 里的文件和 extract.json 的记录对不上(%d 处)' % len(integrity))
|
|
1904
|
-
print('\n--- 数值可追溯机检 ---')
|
|
1905
|
-
print(' 受检 hex %d / fontSize %d / slot box %d;derived 豁免 %d%s%s'
|
|
1906
|
-
% (checked['hex'], checked['size'], checked['box'], checked['exempt'],
|
|
1907
|
-
';判断键跳过 %d 行(avoid/text_safe/pairing_rule)' % checked['judgement']
|
|
1908
|
-
if checked['judgement'] else '',
|
|
1909
|
-
';rebase_factor=%g' % factor if factor else ''))
|
|
1910
|
-
if not shapes:
|
|
1911
|
-
print(' ⚠ 未找到 %s,slot 坐标一项无法校验' % sp)
|
|
1912
|
-
trace_rc = 0
|
|
1913
|
-
if problems:
|
|
1914
|
-
trace_rc = 1
|
|
1915
|
-
print(' FAIL %d 处数值无法追溯(既不命中普查值,也没在 manifest 的 derived 里声明):'
|
|
1916
|
-
% len(problems))
|
|
1917
|
-
for kind, fname, lineno, val, tip, path in problems:
|
|
1918
|
-
print(' %s:%d %s %s ← %s' % (fname, lineno, kind, val, path))
|
|
1919
|
-
print(' %s' % (tip or ''))
|
|
1920
|
-
print(' 修法二选一:改成命中的值,或在 manifest.yaml 的 derived: 段声明推导理由。')
|
|
1921
|
-
else:
|
|
1922
|
-
print(' PASS 全部可追溯')
|
|
1923
|
-
|
|
1924
|
-
rc = trace_rc
|
|
1925
|
-
print('\n--- check_v2 ---')
|
|
1926
|
-
sys.stdout.flush() # 子进程直写 fd,不 flush 会让本脚本的输出排在其后
|
|
1927
|
-
r = subprocess.run([sys.executable, os.path.join(HERE, 'check_v2.py'), pack])
|
|
1928
|
-
rc = rc or r.returncode
|
|
1929
|
-
if not args.check_v1:
|
|
1930
|
-
args.check_v1 = _autodetect_check_v1()
|
|
1931
|
-
if not args.check_v1:
|
|
1932
|
-
print('check_v1: 未探测到($DSM_V1_DIR / 同级 skill / 开发机路径均无)—— v1 门禁未跑,交付前必须补跑')
|
|
1933
|
-
if args.check_v1:
|
|
1934
|
-
print('\n--- check_v1 ---')
|
|
1935
|
-
sys.stdout.flush()
|
|
1936
|
-
r1 = subprocess.run([sys.executable, args.check_v1,
|
|
1937
|
-
os.path.join(pack, 'design.md'), 'slide'])
|
|
1938
|
-
rc = rc or r1.returncode
|
|
1939
|
-
if rc:
|
|
1940
|
-
print('\n门禁未过(exit %d)。回修属 L 层的事:改判断单后重跑本脚本。' % rc)
|
|
1941
|
-
return rc
|
|
1942
|
-
return rc
|
|
1943
|
-
|
|
1944
|
-
|
|
1945
|
-
if __name__ == '__main__':
|
|
1946
|
-
sys.exit(main())
|