@sokeai/cli 1.0.116 → 1.0.117
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/package.json +1 -1
- package/skills/multi/demo-init/CHANGELOG.md +1241 -0
- package/skills/multi/demo-init/README.md +137 -0
- package/skills/multi/demo-init/SKILL.legacy.md +307 -0
- package/skills/multi/demo-init/assets/placeholder.pptx +0 -0
- package/skills/multi/demo-init/references/anti-patterns.md +83 -0
- package/skills/multi/demo-init/references/asset-design.md +230 -0
- package/skills/multi/demo-init/references/asset-spec.md +94 -0
- package/skills/multi/demo-init/references/blueprint-schema.md +174 -0
- package/skills/multi/demo-init/references/cli-onboarding.md +207 -0
- package/skills/multi/demo-init/references/cli-shared.md +183 -0
- package/skills/multi/demo-init/references/contracts.md +34 -0
- package/skills/multi/demo-init/references/course-setup.md +265 -0
- package/skills/multi/demo-init/references/demo-defaults.md +132 -0
- package/skills/multi/demo-init/references/demo-verify.md +355 -0
- package/skills/multi/demo-init/references/exam-setup.md +245 -0
- package/skills/multi/demo-init/references/gates-matrix.md +38 -0
- package/skills/multi/demo-init/references/map-setup.md +283 -0
- package/skills/multi/demo-init/references/plan-parse.md +185 -0
- package/skills/multi/demo-init/references/platform-access.md +55 -0
- package/skills/multi/demo-init/references/platform-commands.md +510 -0
- package/skills/multi/demo-init/references/point-setup.md +308 -0
- package/skills/multi/demo-init/references/portal-modules.md +130 -0
- package/skills/multi/demo-init/references/portal-setup.md +342 -0
- package/skills/multi/demo-init/references/project-setup.md +173 -0
- package/skills/multi/demo-init/references/run-protocol.md +208 -0
- package/skills/multi/demo-init/references/taxonomy-setup.md +101 -0
- package/skills/multi/demo-init/scripts/assign_backfill.py +281 -0
- package/skills/multi/demo-init/scripts/blueprint_lint.py +693 -0
- package/skills/multi/demo-init/scripts/blueprint_write.py +390 -0
- package/skills/multi/demo-init/scripts/category_bind.py +303 -0
- package/skills/multi/demo-init/scripts/category_create.py +748 -0
- package/skills/multi/demo-init/scripts/category_reassign.py +405 -0
- package/skills/multi/demo-init/scripts/category_verify.py +373 -0
- package/skills/multi/demo-init/scripts/cli_kit.py +597 -0
- package/skills/multi/demo-init/scripts/cli_probe.py +205 -0
- package/skills/multi/demo-init/scripts/course_build.py +857 -0
- package/skills/multi/demo-init/scripts/course_cover_repair.py +243 -0
- package/skills/multi/demo-init/scripts/doc_lint.py +619 -0
- package/skills/multi/demo-init/scripts/dup_cleanup.py +299 -0
- package/skills/multi/demo-init/scripts/dup_scan.py +368 -0
- package/skills/multi/demo-init/scripts/exam_build.py +551 -0
- package/skills/multi/demo-init/scripts/extract_docx.py +370 -0
- package/skills/multi/demo-init/scripts/gen_assets.py +1366 -0
- package/skills/multi/demo-init/scripts/guard.py +1272 -0
- package/skills/multi/demo-init/scripts/map_rebuild.py +391 -0
- package/skills/multi/demo-init/scripts/oss_image_upload.py +367 -0
- package/skills/multi/demo-init/scripts/portal_build.py +450 -0
- package/skills/multi/demo-init/scripts/portal_home_apply.py +255 -0
- package/skills/multi/demo-init/scripts/portal_home_layout.py +398 -0
- package/skills/multi/demo-init/scripts/project_build.py +309 -0
- package/skills/multi/demo-init/scripts/rebuild_taxonomy_map.py +100 -0
- package/skills/multi/demo-init/scripts/scope_plan.py +387 -0
- package/skills/multi/demo-init/scripts/selftest_all.py +211 -0
- package/skills/multi/demo-init/scripts/stock_probe.py +452 -0
- package/skills/multi/demo-init/scripts/taxonomy_build.py +512 -0
- package/skills/multi/demo-init-4.1.0.zip +0 -0
- package/skills/multi/demo-init-4.1.1.zip +0 -0
- package/skills/multi/demo-init-4.1.2.zip +0 -0
- package/skills/multi/demo-init-4.1.3.zip +0 -0
- package/skills/multi/ziQIJJpL +0 -0
- package/skills/multi/ziRsINis +0 -0
- package/skills/multi/ziUjKWRm +0 -0
- package/skills/multi/zipFWfuj +0 -0
|
@@ -0,0 +1,1366 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""DEMO 图片生成器(v3.22.0:ImageGen 底图 + 确定性文字层)
|
|
3
|
+
|
|
4
|
+
管线(唯一正路,2026-10-21 定版):
|
|
5
|
+
① --emit-prompts → 产出 backdrop-prompts.json(仅缺失的类型底图作业,已缓存另列 reused)
|
|
6
|
+
② Agent 按 Banner / 课程 / 地图各生成至多一张 **无文字底图**,存到 backdrop/<slot>.png
|
|
7
|
+
③ --backdrop-dir → 底图 cover 裁切到平台规格 + 叠字(文案严格取 BLUEPRINT)+ 对比度/缩略图自检
|
|
8
|
+
④ 落盘 <outdir>/<key>.png + asset-render-report.json
|
|
9
|
+
|
|
10
|
+
为什么文字不交给生图模型:模型直出中文必错字/乱码,且不可复现。文字层永远由 Pillow 绘制。
|
|
11
|
+
`--offline-fallback` 才允许纯本地绘制底图(离线/生图不可用时显式降级,台账须标 engine)。
|
|
12
|
+
|
|
13
|
+
用法:
|
|
14
|
+
gen_assets.py --blueprint <DEMO-BLUEPRINT.json> --emit-prompts # 只出作业单
|
|
15
|
+
gen_assets.py --blueprint <...> --backdrop-dir ./backdrop # 底图合成 + 叠字
|
|
16
|
+
gen_assets.py --blueprint <...> --offline-fallback # 生图不可用时显式降级为本地绘制
|
|
17
|
+
gen_assets.py --blueprint <...> --only logo.main,banner.main.a
|
|
18
|
+
gen_assets.py --blueprint <...> --list # 只打印清单不落盘
|
|
19
|
+
gen_assets.py --blueprint <...> --force # 忽略 status=ready 重出
|
|
20
|
+
|
|
21
|
+
规格(与 references/asset-spec.md 一致):
|
|
22
|
+
banner_pc 3840x1336 PNG
|
|
23
|
+
cover_course 960x540 PNG
|
|
24
|
+
cover_map 960x540 PNG
|
|
25
|
+
logo 240x56 PNG
|
|
26
|
+
超出体积上限时自动「量化 → 降采样」,文件名恒为 <用途键>.png(命名契约不破)。
|
|
27
|
+
|
|
28
|
+
产物:
|
|
29
|
+
<outdir>/<key>.png 成品图
|
|
30
|
+
<outdir>/asset-render-report.json 渲染报告(尺寸/体积/主题/引擎/文字层级自检),供台账引用
|
|
31
|
+
<outdir>/backdrop-prompts.json 生图作业单(--emit-prompts)
|
|
32
|
+
"""
|
|
33
|
+
from __future__ import annotations
|
|
34
|
+
|
|
35
|
+
import argparse
|
|
36
|
+
import hashlib
|
|
37
|
+
import json
|
|
38
|
+
import math
|
|
39
|
+
import os
|
|
40
|
+
import random
|
|
41
|
+
import re
|
|
42
|
+
import sys
|
|
43
|
+
from pathlib import Path
|
|
44
|
+
|
|
45
|
+
try:
|
|
46
|
+
from PIL import Image, ImageDraw, ImageFilter, ImageFont
|
|
47
|
+
except ImportError:
|
|
48
|
+
print("ERR: 缺少 Pillow,请先安装(python3 -m pip install Pillow)", file=sys.stderr)
|
|
49
|
+
sys.exit(2)
|
|
50
|
+
|
|
51
|
+
# ---------------------------------------------------------------- 规格
|
|
52
|
+
|
|
53
|
+
SPEC = {
|
|
54
|
+
"banner_pc": (3840, 1336, 3200),
|
|
55
|
+
"banner_mobile": (750, 360, 500),
|
|
56
|
+
"cover_course": (960, 540, 500),
|
|
57
|
+
"cover_map": (960, 540, 500),
|
|
58
|
+
"logo": (240, 56, 500),
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
# 文字安全边距(占画布宽/高比例)——所有文案必须落在该区域内,越界即判不合格
|
|
62
|
+
SAFE_X = 0.055
|
|
63
|
+
SAFE_Y = 0.06
|
|
64
|
+
|
|
65
|
+
# 文字层级硬口径(v3.21.0 借鉴通用封面技能的可执行量化部分)
|
|
66
|
+
# 主标题字高 ≥ 画布高 13%(过小 → 手机缩略图不可读);副标题 = 主标题 55%–65%;
|
|
67
|
+
# 对比度目标:主标题 ≥ 4.5:1,副标题 ≥ 3:1;不足时自动加深色压板(scrim)而不是改文案。
|
|
68
|
+
TITLE_MIN_RATIO = 0.13
|
|
69
|
+
TITLE_MAX_RATIO = 0.20
|
|
70
|
+
SUB_RATIO_OF_TITLE = 0.58
|
|
71
|
+
CONTRAST_TITLE = 4.5
|
|
72
|
+
CONTRAST_SUB = 3.0
|
|
73
|
+
THUMB_SCALE = 0.25 # 手机端缩略比例
|
|
74
|
+
THUMB_MIN_TITLE_PX = 11 # 缩略后主标题字高下限(<11px 肉眼看不清)
|
|
75
|
+
|
|
76
|
+
FONT_CANDIDATES = [
|
|
77
|
+
# 显式指定优先(跨平台逃生口:DEMO_FONT=/path/to/font.ttf)
|
|
78
|
+
(os.environ.get("DEMO_FONT") or ""),
|
|
79
|
+
# macOS
|
|
80
|
+
"/System/Library/Fonts/PingFang.ttc",
|
|
81
|
+
"/System/Library/Fonts/Hiragino Sans GB.ttc",
|
|
82
|
+
"/System/Library/Fonts/STHeiti Medium.ttc",
|
|
83
|
+
"/System/Library/Fonts/STHeiti Light.ttc",
|
|
84
|
+
"/Library/Fonts/Arial Unicode.ttf",
|
|
85
|
+
# Linux
|
|
86
|
+
"/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc",
|
|
87
|
+
"/usr/share/fonts/truetype/noto/NotoSansCJK-Regular.ttc",
|
|
88
|
+
"/usr/share/fonts/truetype/wqy/wqy-microhei.ttc",
|
|
89
|
+
"/usr/share/fonts/wqy-microhei/wqy-microhei.ttc",
|
|
90
|
+
# Windows
|
|
91
|
+
"C:/Windows/Fonts/msyh.ttc",
|
|
92
|
+
"C:/Windows/Fonts/msyhbd.ttc",
|
|
93
|
+
"C:/Windows/Fonts/simhei.ttf",
|
|
94
|
+
"C:/Windows/Fonts/simsun.ttc",
|
|
95
|
+
]
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
# ---------------------------------------------------------------- 颜色工具
|
|
99
|
+
|
|
100
|
+
def hex2rgb(h: str) -> tuple[int, int, int]:
|
|
101
|
+
h = h.strip().lstrip("#")
|
|
102
|
+
if len(h) == 3:
|
|
103
|
+
h = "".join(c * 2 for c in h)
|
|
104
|
+
try:
|
|
105
|
+
return tuple(int(h[i:i + 2], 16) for i in (0, 2, 4)) # type: ignore[return-value]
|
|
106
|
+
except Exception:
|
|
107
|
+
return (31, 58, 104)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def mix(c1, c2, t: float):
|
|
111
|
+
return tuple(round(a + (b - a) * t) for a, b in zip(c1, c2))
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def shade(c, t: float):
|
|
115
|
+
"""t>0 变亮(向白),t<0 变暗(向黑)。"""
|
|
116
|
+
return mix(c, (255, 255, 255) if t > 0 else (0, 0, 0), abs(t))
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def ramp(c, stops: list[tuple[float, float]]):
|
|
120
|
+
"""按 [(t, delta)] 生成明暗阶梯,返回颜色列表。"""
|
|
121
|
+
return [shade(c, d) for _, d in stops]
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def hsv_shift(c, dh: float = 0.0, ds: float = 0.0, dv: float = 0.0):
|
|
125
|
+
import colorsys
|
|
126
|
+
r, g, b = [x / 255 for x in c]
|
|
127
|
+
h, s, v = colorsys.rgb_to_hsv(r, g, b)
|
|
128
|
+
h = (h + dh) % 1.0
|
|
129
|
+
s = min(1.0, max(0.0, s * (1 + ds)))
|
|
130
|
+
v = min(1.0, max(0.0, v * (1 + dv)))
|
|
131
|
+
return tuple(round(x * 255) for x in colorsys.hsv_to_rgb(h, s, v))
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
# ---------------------------------------------------------------- 字体
|
|
135
|
+
|
|
136
|
+
_FONT_CACHE: dict[int, ImageFont.FreeTypeFont] = {}
|
|
137
|
+
_FONT_PATH = next((p for p in FONT_CANDIDATES if p and Path(p).exists()), None)
|
|
138
|
+
_FONT_WARNED = False
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def font_status() -> dict:
|
|
142
|
+
"""出图所用字体状态,随汇总 JSON 回报——缺中文字体时中文会渲染成方块,必须显式暴露。"""
|
|
143
|
+
return {"path": _FONT_PATH, "cjk": bool(_FONT_PATH),
|
|
144
|
+
"hint": "" if _FONT_PATH else
|
|
145
|
+
"未找到中文字体:中文文字层将渲染为方块。装 Noto Sans CJK / 苹方,"
|
|
146
|
+
"或设 DEMO_FONT=/path/to/font.ttf 后重跑"}
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def font(size: int):
|
|
150
|
+
global _FONT_WARNED
|
|
151
|
+
size = max(8, int(size))
|
|
152
|
+
if size in _FONT_CACHE:
|
|
153
|
+
return _FONT_CACHE[size]
|
|
154
|
+
if _FONT_PATH:
|
|
155
|
+
try:
|
|
156
|
+
f = ImageFont.truetype(_FONT_PATH, size, index=0)
|
|
157
|
+
except Exception:
|
|
158
|
+
try:
|
|
159
|
+
f = ImageFont.truetype(_FONT_PATH, size)
|
|
160
|
+
except Exception:
|
|
161
|
+
f = ImageFont.load_default()
|
|
162
|
+
else:
|
|
163
|
+
if not _FONT_WARNED:
|
|
164
|
+
print("[warn] " + font_status()["hint"], file=sys.stderr)
|
|
165
|
+
_FONT_WARNED = True
|
|
166
|
+
f = ImageFont.load_default()
|
|
167
|
+
_FONT_CACHE[size] = f
|
|
168
|
+
return f
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def text_w(draw, s: str, f) -> float:
|
|
172
|
+
if not s:
|
|
173
|
+
return 0.0
|
|
174
|
+
try:
|
|
175
|
+
return draw.textlength(s, font=f)
|
|
176
|
+
except Exception:
|
|
177
|
+
return len(s) * f.size * 0.6
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def wrap(draw, s: str, f, max_w: float, max_lines: int = 2) -> list[str]:
|
|
181
|
+
lines, cur = [], ""
|
|
182
|
+
for ch in s:
|
|
183
|
+
if text_w(draw, cur + ch, f) <= max_w:
|
|
184
|
+
cur += ch
|
|
185
|
+
else:
|
|
186
|
+
if cur:
|
|
187
|
+
lines.append(cur)
|
|
188
|
+
cur = ch
|
|
189
|
+
if len(lines) == max_lines:
|
|
190
|
+
break
|
|
191
|
+
if cur and len(lines) < max_lines:
|
|
192
|
+
lines.append(cur)
|
|
193
|
+
if len(lines) == max_lines:
|
|
194
|
+
joined = "".join(lines)
|
|
195
|
+
if len(joined) < len(s): # 截断补省略号
|
|
196
|
+
last = lines[-1]
|
|
197
|
+
while last and text_w(draw, last + "…", f) > max_w:
|
|
198
|
+
last = last[:-1]
|
|
199
|
+
lines[-1] = last + "…"
|
|
200
|
+
return lines
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
# ---------------------------------------------------------------- 主题识别
|
|
204
|
+
|
|
205
|
+
TOPIC_RULES = [
|
|
206
|
+
# 顺序即优先级:先具体场景,后泛化气质。
|
|
207
|
+
# v4.2.0:补餐饮/零售/服务行业词(原表只覆盖金融信贷与通用培训,
|
|
208
|
+
# 导致「洗手消毒/开店清单/鸡汤出品/亲切服务/投诉处理/门店排班」全部落 abstract,
|
|
209
|
+
# 2026-10-22 老乡鸡 DEMO 因此出现 9 张课封共用同一句 Subject 的同质事故)。
|
|
210
|
+
("shield", ["合规", "安全", "风控", "风险", "权益", "红线", "制度", "隐私", "保护",
|
|
211
|
+
"审计", "食安", "卫生", "消毒", "污染", "责任"]),
|
|
212
|
+
("service", ["服务", "投诉", "客诉", "顾客", "接待", "礼貌", "沟通", "话术"]),
|
|
213
|
+
("food", ["鸡汤", "菜品", "出品", "后厨", "厨房", "熬汤", "老母鸡", "食材", "餐饮"]),
|
|
214
|
+
("store", ["门店", "开店", "开业", "闭店", "店铺", "收银", "外卖", "加盟", "陈列"]),
|
|
215
|
+
("culture", ["文化", "历程", "理念", "精神", "价值", "发展", "历史", "愿景", "品牌",
|
|
216
|
+
"农场", "养鸡"]),
|
|
217
|
+
("people", ["员工", "入职", "团队", "队伍", "干部", "管理者", "主管", "店员", "店长",
|
|
218
|
+
"排班", "人效", "带教"]),
|
|
219
|
+
("device", ["pad", "平台", "工具", "数字化", "系统", "移动", "线上", "智能"]),
|
|
220
|
+
("network", ["营销", "客户", "社区", "网格", "拓展", "获客", "走访"]),
|
|
221
|
+
("flow", ["信贷", "调查", "决策", "流程", "审查", "贷前", "贷中", "贷后", "三品", "三表", "三三制"]),
|
|
222
|
+
("stair", ["内训", "萃取", "授课", "讲师", "课程开发", "培训", "路径", "成长", "进阶", "通关"]),
|
|
223
|
+
("data", ["数据", "分析", "指标", "报表", "统计", "考核"]),
|
|
224
|
+
]
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def topic_of(text: str) -> str:
|
|
228
|
+
low = text.lower()
|
|
229
|
+
for name, keys in TOPIC_RULES:
|
|
230
|
+
if any(k in low for k in keys):
|
|
231
|
+
return name
|
|
232
|
+
return "abstract"
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
# ---------------------------------------------------------------- 底图绘制
|
|
236
|
+
|
|
237
|
+
def gradient(size, c1, c2, angle: float = 12.0):
|
|
238
|
+
"""线性渐变(渐变方向按 angle 倾斜),用 draw 逐行近似,速度快。"""
|
|
239
|
+
w, h = size
|
|
240
|
+
img = Image.new("RGB", (w, h), c1)
|
|
241
|
+
dr = ImageDraw.Draw(img)
|
|
242
|
+
rad = math.radians(angle)
|
|
243
|
+
span = abs(h * math.cos(rad)) + abs(w * math.sin(rad))
|
|
244
|
+
step = 2
|
|
245
|
+
for i in range(0, int(span) + step, step):
|
|
246
|
+
t = i / max(span, 1)
|
|
247
|
+
col = mix(c1, c2, t)
|
|
248
|
+
off = i
|
|
249
|
+
dr.line([(-w, off), (w * 2, off - w * 2 * math.tan(rad))], fill=col, width=step + 1)
|
|
250
|
+
return img
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def radial_glow(img, center, radius, color, alpha=60):
|
|
254
|
+
"""在既有底图上叠加柔光斑(保留原背景,不覆盖)。"""
|
|
255
|
+
w, h = img.size
|
|
256
|
+
glow = Image.new("L", (w, h), 0)
|
|
257
|
+
gd = ImageDraw.Draw(glow)
|
|
258
|
+
cx, cy = center
|
|
259
|
+
gd.ellipse([cx - radius, cy - radius, cx + radius, cy + radius], fill=alpha)
|
|
260
|
+
glow = glow.filter(ImageFilter.GaussianBlur(radius * 0.55))
|
|
261
|
+
layer = Image.new("RGB", (w, h), color)
|
|
262
|
+
img.paste(layer, (0, 0), glow)
|
|
263
|
+
return img
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def img_paste_alpha(base, layer, mask):
|
|
267
|
+
if base is None:
|
|
268
|
+
base = Image.new("RGB", layer.size, (0, 0, 0))
|
|
269
|
+
base.paste(layer, (0, 0), mask)
|
|
270
|
+
return base
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def add_texture(img, alpha=10, gap=26):
|
|
274
|
+
"""细网格 + 斜纹,提升"设计感",避免纯渐变的廉价感。"""
|
|
275
|
+
w, h = img.size
|
|
276
|
+
ov = Image.new("RGBA", (w, h), (0, 0, 0, 0))
|
|
277
|
+
d = ImageDraw.Draw(ov)
|
|
278
|
+
for x in range(0, w, gap):
|
|
279
|
+
d.line([(x, 0), (x, h)], fill=(255, 255, 255, alpha))
|
|
280
|
+
for y in range(0, h, gap):
|
|
281
|
+
d.line([(0, y), (w, y)], fill=(255, 255, 255, alpha // 2))
|
|
282
|
+
return Image.alpha_composite(img.convert("RGBA"), ov).convert("RGB")
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def add_vignette(img, strength=0.35):
|
|
286
|
+
w, h = img.size
|
|
287
|
+
mask = Image.new("L", (w, h), 0)
|
|
288
|
+
d = ImageDraw.Draw(mask)
|
|
289
|
+
d.ellipse([-w * 0.15, -h * 0.35, w * 1.15, h * 1.35], fill=255)
|
|
290
|
+
mask = mask.filter(ImageFilter.GaussianBlur(int(min(w, h) * 0.12)))
|
|
291
|
+
dark = Image.new("RGB", (w, h), (0, 0, 0))
|
|
292
|
+
return Image.composite(img, Image.blend(img, dark, strength), mask)
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def draw_motif(img, kind, brand, accent, rnd: random.Random):
|
|
296
|
+
"""右侧主题视觉:低透明度几何图形,作为"封面记忆点"。"""
|
|
297
|
+
w, h = img.size
|
|
298
|
+
ov = Image.new("RGBA", (w, h), (0, 0, 0, 0))
|
|
299
|
+
d = ImageDraw.Draw(ov)
|
|
300
|
+
cx, cy = w * 0.76, h * 0.52
|
|
301
|
+
s = min(w, h) * 0.42
|
|
302
|
+
line = shade(accent, 0.25)
|
|
303
|
+
a_line = 150
|
|
304
|
+
a_fill = 34
|
|
305
|
+
|
|
306
|
+
def poly(pts, fill=None, outline=None, width=6):
|
|
307
|
+
d.polygon(pts, fill=fill, outline=outline)
|
|
308
|
+
if outline:
|
|
309
|
+
d.line(pts + [pts[0]], fill=outline, width=width, joint="curve")
|
|
310
|
+
|
|
311
|
+
if kind == "shield":
|
|
312
|
+
pts = [(cx, cy - s * 0.62), (cx + s * 0.46, cy - s * 0.34),
|
|
313
|
+
(cx + s * 0.40, cy + s * 0.30), (cx, cy + s * 0.66),
|
|
314
|
+
(cx - s * 0.40, cy + s * 0.30), (cx - s * 0.46, cy - s * 0.34)]
|
|
315
|
+
poly(pts, (*line, a_fill), (*line, a_line))
|
|
316
|
+
d.line([(cx - s * 0.16, cy + s * 0.02), (cx - s * 0.02, cy + s * 0.16),
|
|
317
|
+
(cx + s * 0.20, cy - s * 0.16)], fill=(*line, 220), width=max(4, int(s * 0.05)), joint="curve")
|
|
318
|
+
elif kind == "device":
|
|
319
|
+
d.rounded_rectangle([cx - s * 0.36, cy - s * 0.58, cx + s * 0.36, cy + s * 0.58],
|
|
320
|
+
radius=int(s * 0.10), fill=(*line, a_fill), outline=(*line, a_line), width=5)
|
|
321
|
+
for i in range(3):
|
|
322
|
+
yy = cy - s * 0.30 + i * s * 0.26
|
|
323
|
+
d.rounded_rectangle([cx - s * 0.24, yy, cx + s * 0.24, yy + s * 0.12],
|
|
324
|
+
radius=int(s * 0.04), fill=(*line, 90))
|
|
325
|
+
elif kind == "culture":
|
|
326
|
+
for i in range(3):
|
|
327
|
+
r = s * (0.62 - i * 0.16)
|
|
328
|
+
d.arc([cx - r, cy - r, cx + r, cy + r], start=200 + i * 18, end=340 + i * 18,
|
|
329
|
+
fill=(*line, a_line - i * 25), width=max(5, int(s * 0.035)))
|
|
330
|
+
d.ellipse([cx - s * 0.10, cy - s * 0.10, cx + s * 0.10, cy + s * 0.10], fill=(*line, 120))
|
|
331
|
+
elif kind == "network":
|
|
332
|
+
pts = []
|
|
333
|
+
for i in range(6):
|
|
334
|
+
ang = math.radians(60 * i - 90)
|
|
335
|
+
r = s * (0.62 if i % 2 == 0 else 0.44)
|
|
336
|
+
pts.append((cx + r * math.cos(ang), cy + r * math.sin(ang)))
|
|
337
|
+
for p in pts:
|
|
338
|
+
d.line([(cx, cy), p], fill=(*line, 110), width=4)
|
|
339
|
+
for i, p in enumerate(pts):
|
|
340
|
+
d.line([p, pts[(i + 2) % 6]], fill=(*line, 70), width=3)
|
|
341
|
+
for i, p in enumerate(pts):
|
|
342
|
+
r = s * (0.07 if i % 2 == 0 else 0.05)
|
|
343
|
+
d.ellipse([p[0] - r, p[1] - r, p[0] + r, p[1] + r],
|
|
344
|
+
fill=(*line, 170) if i % 2 == 0 else (*line, 90))
|
|
345
|
+
elif kind == "flow":
|
|
346
|
+
pts = [(cx - s * 0.60, cy + s * 0.30), (cx - s * 0.20, cy + s * 0.30),
|
|
347
|
+
(cx - s * 0.20, cy - s * 0.10), (cx + s * 0.24, cy - s * 0.10),
|
|
348
|
+
(cx + s * 0.24, cy - s * 0.46), (cx + s * 0.62, cy - s * 0.46)]
|
|
349
|
+
d.line(pts, fill=(*line, a_line), width=max(6, int(s * 0.05)), joint="curve")
|
|
350
|
+
for i, (x, y) in enumerate(pts):
|
|
351
|
+
r = s * (0.09 if i % 2 == 0 else 0.06)
|
|
352
|
+
d.ellipse([x - r, y - r, x + r, y + r], fill=(*line, 120), outline=(*line, 210), width=4)
|
|
353
|
+
elif kind == "stair":
|
|
354
|
+
for i in range(4):
|
|
355
|
+
x0 = cx - s * 0.5 + i * s * 0.28
|
|
356
|
+
y0 = cy + s * 0.40 - i * s * 0.26
|
|
357
|
+
d.rounded_rectangle([x0, y0 - s * 0.20, x0 + s * 0.22, y0], radius=int(s * 0.03),
|
|
358
|
+
fill=(*line, 60 + i * 18), outline=(*line, 140), width=3)
|
|
359
|
+
elif kind == "data":
|
|
360
|
+
for i in range(4):
|
|
361
|
+
x0 = cx - s * 0.5 + i * s * 0.28
|
|
362
|
+
hh = s * (0.22 + 0.12 * ((i * 7) % 3))
|
|
363
|
+
d.rounded_rectangle([x0, cy + s * 0.40 - hh, x0 + s * 0.18, cy + s * 0.40],
|
|
364
|
+
radius=int(s * 0.03), fill=(*line, 70 + i * 12))
|
|
365
|
+
d.line([(cx - s * 0.55, cy + s * 0.12), (cx + s * 0.55, cy - s * 0.30)],
|
|
366
|
+
fill=(*line, 190), width=max(4, int(s * 0.03)))
|
|
367
|
+
elif kind == "people":
|
|
368
|
+
for i, (dx, r) in enumerate([(-0.34, 0.13), (0.0, 0.17), (0.34, 0.13)]):
|
|
369
|
+
d.ellipse([cx + s * dx - s * r, cy - s * 0.30 - s * r,
|
|
370
|
+
cx + s * dx + s * r, cy - s * 0.30 + s * r], fill=(*line, 80 + i * 15))
|
|
371
|
+
d.pieslice([cx + s * dx - s * r * 1.5, cy - s * 0.10, cx + s * dx + s * r * 1.5, cy + s * 0.52],
|
|
372
|
+
start=180, end=360, fill=(*line, 90 + i * 12))
|
|
373
|
+
else: # abstract
|
|
374
|
+
for i in range(3):
|
|
375
|
+
r = s * (0.66 - i * 0.19)
|
|
376
|
+
d.ellipse([cx - r, cy - r, cx + r, cy + r], outline=(*line, max(30, a_line - i * 40)),
|
|
377
|
+
width=max(4, int(s * 0.028)))
|
|
378
|
+
d.line([(cx - s * 0.55, cy + s * 0.45), (cx + s * 0.55, cy - s * 0.45)],
|
|
379
|
+
fill=(*brand, 60), width=max(3, int(s * 0.02)))
|
|
380
|
+
|
|
381
|
+
return Image.alpha_composite(img.convert("RGBA"), ov).convert("RGB")
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
def draw_banner_deco(img, brand, accent, rnd: random.Random):
|
|
385
|
+
w, h = img.size
|
|
386
|
+
ov = Image.new("RGBA", (w, h), (0, 0, 0, 0))
|
|
387
|
+
d = ImageDraw.Draw(ov)
|
|
388
|
+
accent_l = shade(accent, 0.15)
|
|
389
|
+
for i in range(3):
|
|
390
|
+
r = w * (0.20 + i * 0.10)
|
|
391
|
+
cx, cy = w * 0.86, h * 0.46
|
|
392
|
+
d.arc([cx - r, cy - r, cx + r, cy + r], start=140, end=400,
|
|
393
|
+
fill=(*accent_l, 70 - i * 15), width=max(6, int(w * 0.0035)))
|
|
394
|
+
# 右下斜切色块
|
|
395
|
+
d.polygon([(w * 0.62, h), (w, h), (w, h * 0.52)], fill=(*shade(brand, -0.25), 70))
|
|
396
|
+
# 点阵
|
|
397
|
+
step = max(28, w // 96)
|
|
398
|
+
for x in range(int(w * 0.60), w, step):
|
|
399
|
+
for y in range(0, h, step):
|
|
400
|
+
if (x // step + y // step) % 3 == 0:
|
|
401
|
+
d.ellipse([x, y, x + step * 0.18, y + step * 0.18], fill=(255, 255, 255, 34))
|
|
402
|
+
return Image.alpha_composite(img.convert("RGBA"), ov).convert("RGB")
|
|
403
|
+
|
|
404
|
+
|
|
405
|
+
def draw_roadmap(img, brand, accent, nodes=4):
|
|
406
|
+
w, h = img.size
|
|
407
|
+
ov = Image.new("RGBA", (w, h), (0, 0, 0, 0))
|
|
408
|
+
d = ImageDraw.Draw(ov)
|
|
409
|
+
accent_l = shade(accent, 0.2)
|
|
410
|
+
x0, x1 = w * 0.34, w * 0.95
|
|
411
|
+
base_y = h * 0.66
|
|
412
|
+
pts = []
|
|
413
|
+
for i in range(nodes):
|
|
414
|
+
t = i / max(nodes - 1, 1)
|
|
415
|
+
pts.append((x0 + (x1 - x0) * t, base_y - h * 0.26 * math.sin(t * math.pi * 0.9)))
|
|
416
|
+
d.line(pts, fill=(*accent_l, 120), width=max(6, int(h * 0.012)), joint="curve")
|
|
417
|
+
for i, (x, y) in enumerate(pts):
|
|
418
|
+
r = h * (0.075 if i == nodes - 1 else 0.055)
|
|
419
|
+
d.ellipse([x - r, y - r, x + r, y + r], fill=(*accent_l, 55), outline=(*accent_l, 210),
|
|
420
|
+
width=max(3, int(h * 0.006)))
|
|
421
|
+
d.ellipse([x - r * 0.34, y - r * 0.34, x + r * 0.34, y + r * 0.34], fill=(*accent_l, 230))
|
|
422
|
+
d.line([(x, y + r * 1.3), (x, h * 0.90)], fill=(*accent_l, 60), width=2)
|
|
423
|
+
return Image.alpha_composite(img.convert("RGBA"), ov).convert("RGB")
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
def draw_logo_mark(img, brand, accent):
|
|
427
|
+
w, h = img.size
|
|
428
|
+
d = ImageDraw.Draw(img)
|
|
429
|
+
s = h * 0.62
|
|
430
|
+
x0, y0 = h * 0.16, (h - s) / 2
|
|
431
|
+
d.rounded_rectangle([x0, y0, x0 + s, y0 + s], radius=int(s * 0.22), fill=brand)
|
|
432
|
+
d.polygon([(x0 + s * 0.28, y0 + s * 0.66), (x0 + s * 0.50, y0 + s * 0.30),
|
|
433
|
+
(x0 + s * 0.72, y0 + s * 0.66)], fill=shade(accent, 0.35))
|
|
434
|
+
d.line([(x0 + s * 0.28, y0 + s * 0.44), (x0 + s * 0.72, y0 + s * 0.44)], fill=(255, 255, 255), width=max(2, int(s * 0.07)))
|
|
435
|
+
|
|
436
|
+
|
|
437
|
+
def _rel_lum(rgb) -> float:
|
|
438
|
+
"""WCAG 相对亮度(sRGB 线性化)。"""
|
|
439
|
+
def f(c):
|
|
440
|
+
c = c / 255.0
|
|
441
|
+
return c / 12.92 if c <= 0.03928 else ((c + 0.055) / 1.055) ** 2.4
|
|
442
|
+
r, g, b = rgb[:3]
|
|
443
|
+
return 0.2126 * f(r) + 0.7152 * f(g) + 0.0722 * f(b)
|
|
444
|
+
|
|
445
|
+
|
|
446
|
+
def _contrast(l1: float, l2: float) -> float:
|
|
447
|
+
a, b = max(l1, l2), min(l1, l2)
|
|
448
|
+
return (a + 0.05) / (b + 0.05)
|
|
449
|
+
|
|
450
|
+
|
|
451
|
+
def _region_lum(img, box) -> float:
|
|
452
|
+
"""文字将要落位的区域的平均相对亮度(先缩到 1x1 再算,抗噪且快)。"""
|
|
453
|
+
x0, y0, x1, y1 = [int(round(v)) for v in box]
|
|
454
|
+
x0, y0 = max(0, x0), max(0, y0)
|
|
455
|
+
x1, y1 = min(img.size[0], max(x1, x0 + 1)), min(img.size[1], max(y1, y0 + 1))
|
|
456
|
+
crop = img.crop((x0, y0, x1, y1)).convert("RGB").resize((1, 1), Image.BOX)
|
|
457
|
+
return _rel_lum(crop.getpixel((0, 0)))
|
|
458
|
+
|
|
459
|
+
|
|
460
|
+
def ensure_contrast(img, box, color_hex: str, target: float, max_rounds: int = 3):
|
|
461
|
+
"""对比度不足时在文字区加深色压板(scrim),返回 (contrast, scrim_alpha)。
|
|
462
|
+
|
|
463
|
+
⛔ 不改文案、不换字体、不靠描边了事——压板是对底图的局部处理,最稳。
|
|
464
|
+
压板浓度按下式一次算足:需把区域亮度压到 Lb_target,混合比例 a = 1 - Lb_target/Lb0。
|
|
465
|
+
"""
|
|
466
|
+
l_text = _rel_lum(hex2rgb(color_hex))
|
|
467
|
+
l0 = _region_lum(img, box)
|
|
468
|
+
contrast = _contrast(l_text, l0)
|
|
469
|
+
if contrast >= target:
|
|
470
|
+
return round(contrast, 2), 0
|
|
471
|
+
|
|
472
|
+
# 亮字 → 需要更暗的底;暗字 → 需要更亮的底(用白色压板)
|
|
473
|
+
light_text = l_text >= 0.5
|
|
474
|
+
lb_target = (max(l_text, 0.0) + 0.05) / target - 0.05
|
|
475
|
+
if light_text:
|
|
476
|
+
a_req = 1.0 - max(lb_target, 0.02) / max(l0, 0.02)
|
|
477
|
+
else:
|
|
478
|
+
a_req = 1.0 - max(1.0 - lb_target, 0.02) / max(1.0 - l0, 0.02)
|
|
479
|
+
alpha = int(min(210, max(20, a_req * 130)))
|
|
480
|
+
|
|
481
|
+
w, h = img.size
|
|
482
|
+
pad_x = (box[2] - box[0]) * 0.06
|
|
483
|
+
pad_y = (box[3] - box[1]) * 0.22
|
|
484
|
+
radius = int(max(4, (box[3] - box[1]) * 0.16))
|
|
485
|
+
for i in range(max_rounds):
|
|
486
|
+
ov = Image.new("RGBA", (w, h), (0, 0, 0, 0))
|
|
487
|
+
dd = ImageDraw.Draw(ov)
|
|
488
|
+
fill = (0, 0, 0, alpha) if light_text else (255, 255, 255, alpha)
|
|
489
|
+
dd.rounded_rectangle([box[0] - pad_x, box[1] - pad_y, box[2] + pad_x, box[3] + pad_y],
|
|
490
|
+
radius=radius, fill=fill)
|
|
491
|
+
merged = Image.alpha_composite(img.convert("RGBA"), ov).convert("RGB")
|
|
492
|
+
img.paste(merged, (0, 0))
|
|
493
|
+
contrast = _contrast(l_text, _region_lum(img, box))
|
|
494
|
+
if contrast >= target:
|
|
495
|
+
break
|
|
496
|
+
alpha = min(225, alpha + 25)
|
|
497
|
+
return round(contrast, 2), alpha
|
|
498
|
+
|
|
499
|
+
|
|
500
|
+
def text_block(img, texts, max_w_ratio=0.52):
|
|
501
|
+
"""文字叠加:字号层级 + 安全边距 + 对比度 + 缩略图可读性,全部程序化判定。
|
|
502
|
+
|
|
503
|
+
v3.21.0 起按「通用封面技能」里可量化的三条硬口径收口:
|
|
504
|
+
① 主标题字高 ≥ 画布高 13%(原 8.8% 在手机缩略图上偏小);
|
|
505
|
+
② 副标题 = 主标题 55%–65%(原来 45%,层级压不住);
|
|
506
|
+
③ 文字与背景对比度 主标题 ≥4.5:1 / 副标题 ≥3:1,不足自动加暗色压板。
|
|
507
|
+
|
|
508
|
+
返回 (img, fits):fits 逐条记录 {role, size, lines, avail_w, widest, truncated,
|
|
509
|
+
overflow, contrast, scrim, thumb_ok, ratio},写入 asset-render-report.json 供程序化自检。
|
|
510
|
+
"""
|
|
511
|
+
w, h = img.size
|
|
512
|
+
d = ImageDraw.Draw(img)
|
|
513
|
+
safe_x = w * SAFE_X
|
|
514
|
+
safe_y = h * SAFE_Y
|
|
515
|
+
min_size = max(14, round(h * 0.026))
|
|
516
|
+
fits = []
|
|
517
|
+
title_px = 0
|
|
518
|
+
|
|
519
|
+
for t in texts:
|
|
520
|
+
content = (t.get("content") or "").strip()
|
|
521
|
+
if not content:
|
|
522
|
+
continue
|
|
523
|
+
role = t.get("role", "title")
|
|
524
|
+
x = w * float(t.get("x", 0.5))
|
|
525
|
+
align = t.get("align", "left")
|
|
526
|
+
max_w = w * (t.get("max_w") or max_w_ratio)
|
|
527
|
+
max_lines = int(t.get("max_lines", 2))
|
|
528
|
+
color = t.get("color", "#FFFFFF")
|
|
529
|
+
|
|
530
|
+
# ---- 字号:按角色定基准,主标题夹在 [13%, 20%] 画布高,副标题跟随主标题
|
|
531
|
+
if role == "title":
|
|
532
|
+
lo = max(min_size, round(h * TITLE_MIN_RATIO))
|
|
533
|
+
hi = round(h * TITLE_MAX_RATIO)
|
|
534
|
+
size = min(max(round(h * float(t.get("size_ratio") or 0.13)), lo), hi)
|
|
535
|
+
elif role == "subtitle" and title_px:
|
|
536
|
+
size = max(min_size, round(title_px * SUB_RATIO_OF_TITLE))
|
|
537
|
+
else:
|
|
538
|
+
size = max(min_size, round(h * float(t.get("size_ratio") or 0.032)))
|
|
539
|
+
|
|
540
|
+
# 可用宽度:max_w 与「到安全边距的实际距离」取小
|
|
541
|
+
if align == "center":
|
|
542
|
+
avail = min(max_w, w - 2 * safe_x)
|
|
543
|
+
elif align == "right":
|
|
544
|
+
avail = min(max_w, x - safe_x)
|
|
545
|
+
else:
|
|
546
|
+
avail = min(max_w, w - safe_x - x)
|
|
547
|
+
avail = max(avail, w * 0.20)
|
|
548
|
+
|
|
549
|
+
y = h * float(t.get("y", 0.4))
|
|
550
|
+
while True:
|
|
551
|
+
f = font(size)
|
|
552
|
+
lines = wrap(d, content, f, avail, max_lines=max_lines)
|
|
553
|
+
widest = max((text_w(d, ln, f) for ln in lines), default=0.0)
|
|
554
|
+
truncated = any(ln.endswith("…") for ln in lines)
|
|
555
|
+
block_h = (len(lines) - 1) * size * 1.24 + size * 0.92
|
|
556
|
+
fits_vert = (y - block_h / 2 >= safe_y - 1) and (y + block_h / 2 <= h - safe_y + 1)
|
|
557
|
+
if (widest <= avail + 0.5 and not truncated and fits_vert) or size <= min_size:
|
|
558
|
+
break
|
|
559
|
+
size = max(min_size, int(size * 0.94))
|
|
560
|
+
|
|
561
|
+
# 垂直越界 → 平移回安全区(不改变字号)
|
|
562
|
+
block_h = (len(lines) - 1) * size * 1.24 + size * 0.92
|
|
563
|
+
y = min(max(y, safe_y + block_h / 2), h - safe_y - block_h / 2)
|
|
564
|
+
lh = size * 1.24
|
|
565
|
+
top = y - block_h / 2
|
|
566
|
+
|
|
567
|
+
# 文本框(用于对比度采样与压板)
|
|
568
|
+
if align == "center":
|
|
569
|
+
box = (x - widest / 2, top, x + widest / 2, top + block_h)
|
|
570
|
+
elif align == "right":
|
|
571
|
+
box = (x - widest, top, x, top + block_h)
|
|
572
|
+
else:
|
|
573
|
+
box = (x, top, x + widest, top + block_h)
|
|
574
|
+
target = CONTRAST_TITLE if role == "title" else CONTRAST_SUB
|
|
575
|
+
contrast, scrim = ensure_contrast(img, box, color, target)
|
|
576
|
+
d = ImageDraw.Draw(img)
|
|
577
|
+
|
|
578
|
+
for i, ln in enumerate(lines):
|
|
579
|
+
yy = y + i * lh
|
|
580
|
+
if align == "center":
|
|
581
|
+
anchor, px = "mm", x
|
|
582
|
+
elif align == "right":
|
|
583
|
+
anchor, px = "rm", x
|
|
584
|
+
else:
|
|
585
|
+
anchor, px = "lm", x
|
|
586
|
+
# 柔阴影兜底(压板之外再加一层,保证边缘清晰)
|
|
587
|
+
d.text((px + max(1, size // 26), yy + max(1, size // 26)), ln, font=f,
|
|
588
|
+
fill=(0, 0, 0, 120), anchor=anchor)
|
|
589
|
+
if role == "title":
|
|
590
|
+
d.text((px, yy), ln, font=f, fill=color, anchor=anchor,
|
|
591
|
+
stroke_width=max(1, size // 42), stroke_fill=mix(hex2rgb(color), (0, 0, 0), 0.35))
|
|
592
|
+
else:
|
|
593
|
+
d.text((px, yy), ln, font=f, fill=color, anchor=anchor)
|
|
594
|
+
|
|
595
|
+
if role == "title":
|
|
596
|
+
title_px = size
|
|
597
|
+
fits.append({"role": role, "size": int(size), "lines": len(lines),
|
|
598
|
+
"avail_w": round(avail, 1), "widest": round(widest, 1),
|
|
599
|
+
"truncated": truncated,
|
|
600
|
+
"ratio": round(size / h, 3),
|
|
601
|
+
"contrast": contrast, "scrim": scrim,
|
|
602
|
+
"contrast_ok": contrast >= target,
|
|
603
|
+
"thumb_ok": (role != "title") or h < 400 or (size * THUMB_SCALE >= THUMB_MIN_TITLE_PX),
|
|
604
|
+
"overflow": bool(widest > avail + 0.5 or truncated)})
|
|
605
|
+
return img, fits
|
|
606
|
+
|
|
607
|
+
|
|
608
|
+
def bottom_shade(img, from_ratio=0.40, alpha=200):
|
|
609
|
+
w, h = img.size
|
|
610
|
+
ov = Image.new("RGBA", (w, h), (0, 0, 0, 0))
|
|
611
|
+
d = ImageDraw.Draw(ov)
|
|
612
|
+
top = int(h * from_ratio)
|
|
613
|
+
for y in range(top, h):
|
|
614
|
+
t = (y - top) / max(h - top, 1)
|
|
615
|
+
d.line([(0, y), (w, y)], fill=(0, 0, 0, int(alpha * t ** 1.25)))
|
|
616
|
+
return Image.alpha_composite(img.convert("RGBA"), ov).convert("RGB")
|
|
617
|
+
|
|
618
|
+
|
|
619
|
+
def accent_bar(img, x, y, w_ratio=0.06, h_px=6):
|
|
620
|
+
w, h = img.size
|
|
621
|
+
d = ImageDraw.Draw(img)
|
|
622
|
+
x0 = w * x
|
|
623
|
+
d.rounded_rectangle([x0, h * y - h_px, x0 + w * w_ratio, h * y], radius=h_px // 2, fill=ACCENT)
|
|
624
|
+
|
|
625
|
+
|
|
626
|
+
# ---------------------------------------------------------------- 主流程
|
|
627
|
+
|
|
628
|
+
ACCENT = (201, 162, 82)
|
|
629
|
+
|
|
630
|
+
|
|
631
|
+
def pick_accent(prompt_hint: str, brand) -> tuple[int, int, int]:
|
|
632
|
+
hexes = re.findall(r"#[0-9A-Fa-f]{6}", prompt_hint or "")
|
|
633
|
+
for hx in hexes:
|
|
634
|
+
c = hex2rgb(hx)
|
|
635
|
+
if sum(abs(a - b) for a, b in zip(c, brand)) > 90: # 与主色拉开距离才当辅色
|
|
636
|
+
return c
|
|
637
|
+
# 默认辅色 = 品牌金(蓝金/绿金/墨金都是商务安全组合);品牌本身近金时改用深调
|
|
638
|
+
if sum(abs(a - b) for a, b in zip(ACCENT, brand)) > 90:
|
|
639
|
+
return ACCENT
|
|
640
|
+
return shade(hsv_shift(brand, dh=0.5, ds=0.05, dv=0.15), 0.20)
|
|
641
|
+
|
|
642
|
+
|
|
643
|
+
# ---------------------------------------------------------------- ImageGen 底图作业单
|
|
644
|
+
|
|
645
|
+
BACKDROP_STYLE = (
|
|
646
|
+
"premium corporate learning and development key visual, cinematic soft lighting, "
|
|
647
|
+
"subtle depth of field, clean geometric composition, high-end brand campaign quality"
|
|
648
|
+
)
|
|
649
|
+
|
|
650
|
+
BACKDROP_SUBJECT = {
|
|
651
|
+
"shield": "abstract protective shield form, fine engraved lines, security and compliance mood",
|
|
652
|
+
"device": "sleek modern digital device / tablet interface floating in space, subtle screen glow",
|
|
653
|
+
"culture": "abstract circular emblem and layered horizon, heritage and growth metaphor",
|
|
654
|
+
"network": "connected node network with light trails, customer network metaphor",
|
|
655
|
+
"flow": "abstract flowing pipeline of layered translucent panels, process and decision metaphor",
|
|
656
|
+
"stair": "ascending architectural steps with warm light rims, coaching and growth metaphor",
|
|
657
|
+
"data": "floating translucent data charts and grid lines, analytics mood",
|
|
658
|
+
"people": "silhouettes of a small professional team in soft backlight, teamwork mood",
|
|
659
|
+
"service": "two people in warm attentive conversation across a service counter, shallow depth of field, hospitality mood",
|
|
660
|
+
"food": "macro close-up of steaming traditional broth with fresh ingredients on a warm stone surface, rising steam, culinary craft mood",
|
|
661
|
+
"store": "warm-lit modern restaurant interior with receding seating rows and soft window light, retail space mood",
|
|
662
|
+
"abstract": "abstract architectural geometry with soft light gradients and depth",
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
# 构图硬约束:文字永远叠在左下,底图必须让出该区域
|
|
666
|
+
BACKDROP_COMPOSE = (
|
|
667
|
+
"Composition: main subject anchored in the RIGHT third of the frame; "
|
|
668
|
+
"the LOWER-LEFT 45% of the frame kept intentionally empty, darker and low-contrast "
|
|
669
|
+
"(clean negative space reserved for a title overlay added later); gentle vignette, "
|
|
670
|
+
"no busy detail in the bottom band."
|
|
671
|
+
)
|
|
672
|
+
|
|
673
|
+
BACKDROP_NEGATIVE = (
|
|
674
|
+
"STRICT: absolutely NO text, NO letters, NO words, NO numbers, NO watermark, NO logo, "
|
|
675
|
+
"NO signature, NO UI labels anywhere in the image. No collage, no frame border, no mockup grid."
|
|
676
|
+
)
|
|
677
|
+
|
|
678
|
+
|
|
679
|
+
def _theme_cues(hint: str) -> list:
|
|
680
|
+
"""从 Chinese prompt_hint 里抽出「画面语义」,剥掉文案/字号/坐标/hex 这类排版指令。
|
|
681
|
+
|
|
682
|
+
生图模型看到「文案「xxx」」会尝试把字画进图里 —— 这正是错字乱码的来源,必须剥掉。
|
|
683
|
+
|
|
684
|
+
v4.2.0:改成**先按分隔符切段、再整段判定**。旧实现是先把 `#247A3F` 替换成空格,
|
|
685
|
+
于是「老乡鸡绿#247A3F底」被削成「老乡鸡绿底」留了下来——每张图的第一条 cue 都是
|
|
686
|
+
同一句品牌色描述,消歧直接失效(2026-10-22 十张图 Subject 仍然完全相同的原因)。
|
|
687
|
+
"""
|
|
688
|
+
raw_bits = re.split(r"[,,。;;/|+]+", hint or "")
|
|
689
|
+
bits = []
|
|
690
|
+
for b in raw_bits:
|
|
691
|
+
t = b.strip(" ·、,.")
|
|
692
|
+
if not t:
|
|
693
|
+
continue
|
|
694
|
+
if re.search(r"#[0-9A-Fa-f]{6}", t):
|
|
695
|
+
continue # 品牌色描述段(含 hex)
|
|
696
|
+
if re.search(r"(绿底|蓝底|红底|黑底|白底|底色|主题色|主色|辅色|配色|"
|
|
697
|
+
r"文案|字号|字重|字体|占比|居中|居左|居右|居上|居下|"
|
|
698
|
+
r"左上|右上|左下|右下|留白|叠加|底图)", t):
|
|
699
|
+
continue # 排版/配色指令段
|
|
700
|
+
if t[0] in "「\"'“":
|
|
701
|
+
continue # 纯文案段
|
|
702
|
+
t = re.sub(r"[「」\"'“”]", "", t)
|
|
703
|
+
t = re.sub(r"\s+", " ", t).strip(" ·、,.")
|
|
704
|
+
if len(t) >= 2:
|
|
705
|
+
bits.append(t)
|
|
706
|
+
return bits[:3]
|
|
707
|
+
|
|
708
|
+
|
|
709
|
+
def build_backdrop_prompt(asset: dict, ctx: dict, disambiguate: bool = False) -> dict:
|
|
710
|
+
"""产出单张图的生图指令(Agent 可直接用,可英译润色但不得删硬约束)。
|
|
711
|
+
|
|
712
|
+
disambiguate=True:同类主题多于一张时,把该图的场景词嵌进 Subject,
|
|
713
|
+
避免「4 张盾牌长一样」(--group-mode none 只拆槽位、不拆提示词)。
|
|
714
|
+
"""
|
|
715
|
+
typ = asset.get("type", "cover_course")
|
|
716
|
+
key = asset["key"]
|
|
717
|
+
hint = (asset.get("prompt_hint") or "").strip()
|
|
718
|
+
w, h, _ = SPEC.get(typ, SPEC["cover_course"])
|
|
719
|
+
kind = topic_of(f"{key} {hint}")
|
|
720
|
+
brand_hex = "#%02X%02X%02X" % ctx["brand"]
|
|
721
|
+
accent_hex = "#%02X%02X%02X" % pick_accent(hint, ctx["brand"])
|
|
722
|
+
|
|
723
|
+
subject = BACKDROP_SUBJECT.get(kind, BACKDROP_SUBJECT["abstract"])
|
|
724
|
+
cues = _theme_cues(hint)
|
|
725
|
+
subject_source = "topic:" + kind
|
|
726
|
+
if cues and (kind == "abstract" or disambiguate):
|
|
727
|
+
# 落 abstract、或同类主题不止一张时,用场景词打头给出方向。
|
|
728
|
+
# --group-mode none 只拆"槽位",不拆"提示词"——2026-10-22 九张课封同质的根因就在这里。
|
|
729
|
+
subject = ("editorial scene built around「%s」, %s" % (cues[0], subject))
|
|
730
|
+
subject_source = "hint:" + cues[0]
|
|
731
|
+
cue_line = ("Scene cues (Chinese, render as visual mood only, never as glyphs): "
|
|
732
|
+
+ " / ".join(cues) + ".") if cues else ""
|
|
733
|
+
|
|
734
|
+
prompt = " ".join(x for x in [
|
|
735
|
+
BACKDROP_STYLE + ".",
|
|
736
|
+
f"Subject: {subject}.",
|
|
737
|
+
f"Dominant brand color {brand_hex} with {accent_hex} accent light.",
|
|
738
|
+
cue_line,
|
|
739
|
+
BACKDROP_COMPOSE,
|
|
740
|
+
BACKDROP_NEGATIVE,
|
|
741
|
+
] if x)
|
|
742
|
+
|
|
743
|
+
if typ == "logo":
|
|
744
|
+
prompt = "" # LOGO 是白底文字标,不生成底图
|
|
745
|
+
return {
|
|
746
|
+
"key": key, "type": typ, "size": f"{w}x{h}",
|
|
747
|
+
"gen_size": ("" if typ == "logo" else ("1536x1024" if typ == "banner_pc" else "1024x1024")),
|
|
748
|
+
"aspect": f"{w}:{h}",
|
|
749
|
+
"out_path": f"backdrop/{key}.png", # 相对 blueprint 目录
|
|
750
|
+
"prompt": prompt,
|
|
751
|
+
"negative": BACKDROP_NEGATIVE,
|
|
752
|
+
"needs_backdrop": bool(prompt),
|
|
753
|
+
"subject_kind": kind,
|
|
754
|
+
"subject_source": subject_source,
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
|
|
758
|
+
def fit_cover(src: Image.Image, w: int, h: int):
|
|
759
|
+
"""等比放大铺满 + 居中裁切到目标尺寸(任意输入比例 → 平台规格)。返回 (图, 放大倍数)。"""
|
|
760
|
+
src = src.convert("RGB")
|
|
761
|
+
sw, sh = src.size
|
|
762
|
+
scale = max(w / sw, h / sh)
|
|
763
|
+
nw, nh = max(w, int(round(sw * scale))), max(h, int(round(sh * scale)))
|
|
764
|
+
img = src.resize((nw, nh), Image.LANCZOS)
|
|
765
|
+
left, top = (nw - w) // 2, (nh - h) // 2
|
|
766
|
+
return img.crop((left, top, left + w, top + h)), scale
|
|
767
|
+
|
|
768
|
+
|
|
769
|
+
def find_backdrop(backdrop_dir: Path, key: str):
|
|
770
|
+
"""只复用完整可解码图片;损坏文件不算命中缓存。"""
|
|
771
|
+
for ext in (".png", ".jpg", ".jpeg", ".webp"):
|
|
772
|
+
p = backdrop_dir / f"{key}{ext}"
|
|
773
|
+
if p.is_file():
|
|
774
|
+
try:
|
|
775
|
+
with Image.open(p) as img:
|
|
776
|
+
img.load()
|
|
777
|
+
return p
|
|
778
|
+
except (OSError, ValueError):
|
|
779
|
+
continue
|
|
780
|
+
return None
|
|
781
|
+
|
|
782
|
+
|
|
783
|
+
# ---------------------------------------------------------------- 底图复用(v3.23.0)
|
|
784
|
+
#
|
|
785
|
+
# 背景:同一 DEMO 里 19 张图(2 Banner + 10 课封 + 6 图封 + 1 LOGO)若各生一张 AI 底图,
|
|
786
|
+
# 既烧积分又烧时间;但客户演示真正在意的是「文字信息对不对」,底图只是氛围。
|
|
787
|
+
# 于是引入 **底图槽位(slot)**:多张图可共用同一张底图,只换文字层。
|
|
788
|
+
#
|
|
789
|
+
# 默认按业务类型固定三个槽位,不按尺寸、课程主题或遗留 backdrop_slot 拆分。
|
|
790
|
+
# 仅用户明确要求独立底图时传 --group-mode none,才采用 backdrop_slot / key。
|
|
791
|
+
# 文字重渲和 --force 永远不使可解码底图失效。
|
|
792
|
+
|
|
793
|
+
def slot_of(asset: dict, group_mode: str = "by-type") -> str:
|
|
794
|
+
"""该资产的稳定底图槽位;PC/移动 Banner 共用一个业务类型。"""
|
|
795
|
+
if asset.get("type") == "logo":
|
|
796
|
+
return ""
|
|
797
|
+
if group_mode == "all":
|
|
798
|
+
return "brand-shared"
|
|
799
|
+
if group_mode == "by-type":
|
|
800
|
+
typ = asset.get("type", "cover_course")
|
|
801
|
+
return "brand-banner" if typ.startswith("banner") else "brand-" + typ
|
|
802
|
+
return (asset.get("backdrop_slot") or "").strip() or asset["key"]
|
|
803
|
+
|
|
804
|
+
|
|
805
|
+
def slot_file(backdrop_dir: Path, slot: str):
|
|
806
|
+
return find_backdrop(backdrop_dir, slot) if slot else None
|
|
807
|
+
|
|
808
|
+
|
|
809
|
+
def slots_of(assets: list, group_mode: str = "by-type") -> dict:
|
|
810
|
+
"""{槽位名: [资产 key, ...]},LOGO 无底图槽。"""
|
|
811
|
+
out = {}
|
|
812
|
+
for a in assets:
|
|
813
|
+
slot = slot_of(a, group_mode)
|
|
814
|
+
if slot:
|
|
815
|
+
out.setdefault(slot, []).append(a["key"])
|
|
816
|
+
return out
|
|
817
|
+
|
|
818
|
+
|
|
819
|
+
def cached_backdrop(backdrop_dir: Path, slot: str, assets: list, group_mode: str):
|
|
820
|
+
"""槽位缓存优先;兼容旧文件并固化为稳定槽位,跨 --only 波次复用。"""
|
|
821
|
+
cached = slot_file(backdrop_dir, slot)
|
|
822
|
+
if cached is not None:
|
|
823
|
+
return cached
|
|
824
|
+
for asset in assets:
|
|
825
|
+
if slot_of(asset, group_mode) != slot:
|
|
826
|
+
continue
|
|
827
|
+
old_slots = [(asset.get("backdrop_slot") or "").strip(), asset["key"]]
|
|
828
|
+
if group_mode == "by-type" and asset.get("type", "").startswith("banner"):
|
|
829
|
+
old_slots.insert(0, "brand-" + asset["type"])
|
|
830
|
+
for old_slot in old_slots:
|
|
831
|
+
legacy = slot_file(backdrop_dir, old_slot)
|
|
832
|
+
if legacy is not None:
|
|
833
|
+
backdrop_dir.mkdir(parents=True, exist_ok=True)
|
|
834
|
+
target = backdrop_dir / f"{slot}.png"
|
|
835
|
+
with Image.open(legacy) as img:
|
|
836
|
+
img.convert("RGB").save(target, format="PNG")
|
|
837
|
+
return target
|
|
838
|
+
return None
|
|
839
|
+
|
|
840
|
+
|
|
841
|
+
|
|
842
|
+
def render(asset: dict, ctx: dict, outdir: Path, backdrop: Path = None,
|
|
843
|
+
brand_template: bool = False) -> dict:
|
|
844
|
+
key = asset["key"]
|
|
845
|
+
typ = asset.get("type", "cover_course")
|
|
846
|
+
w, h, max_kb = SPEC.get(typ, SPEC["cover_course"])
|
|
847
|
+
hint = asset.get("prompt_hint", "")
|
|
848
|
+
brand = ctx["brand"]
|
|
849
|
+
accent = pick_accent(hint, brand)
|
|
850
|
+
rnd = random.Random(int(hashlib.md5(f"{key}|{hint}".encode()).hexdigest()[:8], 16))
|
|
851
|
+
|
|
852
|
+
topic_src = f"{key} {hint}"
|
|
853
|
+
kind = topic_of(topic_src)
|
|
854
|
+
|
|
855
|
+
# 1) 底图:ImageGen 底图优先(cover 裁切到平台规格);无底图才本地绘制(显式降级)
|
|
856
|
+
# --brand-template:所有图共用一张本地品牌底图,engine=brand-template(零 ImageGen)
|
|
857
|
+
engine = "local-pil"
|
|
858
|
+
upscale = None
|
|
859
|
+
backdrop_used = None
|
|
860
|
+
if brand_template and backdrop is not None:
|
|
861
|
+
# 品牌模板底图:同样要裁切到平台规格 + 叠字,只是底图来源是本地模板而非 ImageGen
|
|
862
|
+
with Image.open(backdrop) as src:
|
|
863
|
+
img, upscale = fit_cover(src, w, h)
|
|
864
|
+
engine = "brand-template"
|
|
865
|
+
img = add_vignette(img, 0.18)
|
|
866
|
+
backdrop_used = backdrop
|
|
867
|
+
elif backdrop is not None and typ != "logo":
|
|
868
|
+
with Image.open(backdrop) as src:
|
|
869
|
+
img, upscale = fit_cover(src, w, h)
|
|
870
|
+
engine = "imagegen-text-overlay"
|
|
871
|
+
# AI 图质感已足够,只补轻微暗角,让文字层更稳
|
|
872
|
+
img = add_vignette(img, 0.18)
|
|
873
|
+
backdrop_used = backdrop
|
|
874
|
+
else:
|
|
875
|
+
c_deep = shade(hsv_shift(brand, dh=rnd.uniform(-0.02, 0.02), dv=-0.16), -0.18)
|
|
876
|
+
c_light = shade(hsv_shift(brand, dh=rnd.uniform(-0.03, 0.03), dv=0.10), 0.30)
|
|
877
|
+
img = gradient((w, h), c_deep, c_light, angle=rnd.choice([8, 12, 16, -10]))
|
|
878
|
+
img = radial_glow(img, (w * rnd.uniform(0.60, 0.80), h * 0.30), min(w, h) * 0.60, accent, 55)
|
|
879
|
+
img = radial_glow(img, (w * 0.08, h * 0.92), min(w, h) * 0.45, shade(brand, 0.45), 48)
|
|
880
|
+
|
|
881
|
+
if typ == "banner_pc":
|
|
882
|
+
img = draw_banner_deco(img, brand, accent, rnd)
|
|
883
|
+
img = add_texture(img, alpha=8, gap=max(24, w // 120))
|
|
884
|
+
elif typ == "cover_map":
|
|
885
|
+
img = draw_roadmap(img, brand, accent, nodes=4)
|
|
886
|
+
img = add_texture(img, alpha=7, gap=30)
|
|
887
|
+
elif typ == "cover_course":
|
|
888
|
+
img = draw_motif(img, kind, brand, accent, rnd)
|
|
889
|
+
img = add_texture(img, alpha=7, gap=22)
|
|
890
|
+
elif typ == "logo":
|
|
891
|
+
img = Image.new("RGB", (w, h), (255, 255, 255))
|
|
892
|
+
img = add_vignette(img, 0.20 if typ != "logo" else 0.0)
|
|
893
|
+
|
|
894
|
+
|
|
895
|
+
# 2) 文字叠加(文案严格取 BLUEPRINT,绝不交给生成模型)
|
|
896
|
+
texts = []
|
|
897
|
+
if typ.startswith("banner") and key.endswith(".a"):
|
|
898
|
+
img = bottom_shade(img, 0.34, 190)
|
|
899
|
+
texts = [
|
|
900
|
+
{"content": ctx["academy"], "role": "title", "x": 0.5, "y": 0.40, "align": "center",
|
|
901
|
+
"size_ratio": 0.105, "max_w": 0.78, "color": "#FFFFFF"},
|
|
902
|
+
{"content": ctx["slogan"], "role": "subtitle", "x": 0.5, "y": 0.56, "align": "center",
|
|
903
|
+
"size_ratio": 0.040, "max_w": 0.72, "color": "#F3E7CE"},
|
|
904
|
+
{"content": ctx["customer"], "role": "footnote", "x": 0.5, "y": 0.68, "align": "center",
|
|
905
|
+
"size_ratio": 0.026, "max_w": 0.7, "color": "#EADFD0"},
|
|
906
|
+
]
|
|
907
|
+
elif typ.startswith("banner"):
|
|
908
|
+
img = bottom_shade(img, 0.30, 200)
|
|
909
|
+
texts = [
|
|
910
|
+
{"content": ctx["banner_b_title"], "role": "title", "x": 0.08, "y": 0.38, "align": "left",
|
|
911
|
+
"size_ratio": 0.088, "max_w": 0.56, "color": "#FFFFFF"},
|
|
912
|
+
{"content": ctx["customer"], "role": "subtitle", "x": 0.08, "y": 0.62, "align": "left",
|
|
913
|
+
"size_ratio": 0.036, "max_w": 0.52, "color": "#F3E7CE"},
|
|
914
|
+
]
|
|
915
|
+
elif typ == "cover_course":
|
|
916
|
+
img = bottom_shade(img, 0.34, 205)
|
|
917
|
+
accent_bar(img, 0.075, 0.545, 0.055, max(4, h // 90))
|
|
918
|
+
texts = [
|
|
919
|
+
{"content": ctx["course_title"], "role": "title", "x": 0.075, "y": 0.62, "align": "left",
|
|
920
|
+
"size_ratio": 0.088, "max_w": 0.66, "color": "#FFFFFF", "max_lines": 2},
|
|
921
|
+
{"content": ctx["course_sub"], "role": "subtitle", "x": 0.075, "y": 0.855, "align": "left",
|
|
922
|
+
"size_ratio": 0.040, "max_w": 0.55, "color": "#F0E3CB"},
|
|
923
|
+
]
|
|
924
|
+
elif typ == "cover_map":
|
|
925
|
+
img = bottom_shade(img, 0.42, 150)
|
|
926
|
+
accent_bar(img, 0.065, 0.53, 0.05, max(4, h // 80))
|
|
927
|
+
texts = [
|
|
928
|
+
{"content": ctx["map_title"], "role": "title", "x": 0.065, "y": 0.56, "align": "left",
|
|
929
|
+
"size_ratio": 0.095, "max_w": 0.42, "color": "#FFFFFF"},
|
|
930
|
+
{"content": ctx["map_sub"], "role": "subtitle", "x": 0.065, "y": 0.87, "align": "left",
|
|
931
|
+
"size_ratio": 0.042, "max_w": 0.40, "color": "#F0E3CB"},
|
|
932
|
+
]
|
|
933
|
+
elif typ == "logo":
|
|
934
|
+
draw_logo_mark(img, brand, accent)
|
|
935
|
+
texts = [
|
|
936
|
+
{"content": ctx["academy"], "role": "title", "x": 0.30, "y": 0.52, "align": "left",
|
|
937
|
+
"size_ratio": 0.44, "max_w": 0.66, "color": "#%02X%02X%02X" % brand, "max_lines": 1},
|
|
938
|
+
]
|
|
939
|
+
|
|
940
|
+
explicit_texts = asset.get("texts") or {}
|
|
941
|
+
if isinstance(explicit_texts, list):
|
|
942
|
+
explicit_texts = {t.get("role", "title"): t.get("content", "") for t in explicit_texts}
|
|
943
|
+
for text in texts:
|
|
944
|
+
if text["role"] in explicit_texts:
|
|
945
|
+
text["content"] = str(explicit_texts[text["role"]] or "")
|
|
946
|
+
img, fits = text_block(img, texts)
|
|
947
|
+
|
|
948
|
+
# 3) 落盘 + 体积兜底(PNG 优先,超限量化→降采样,命名恒为 <key>.png)
|
|
949
|
+
out = outdir / f"{key}.png"
|
|
950
|
+
note = ""
|
|
951
|
+
img.save(out, format="PNG", optimize=True, compress_level=7)
|
|
952
|
+
kb = out.stat().st_size / 1024
|
|
953
|
+
if kb > max_kb:
|
|
954
|
+
q = img.convert("P", palette=Image.ADAPTIVE, colors=192)
|
|
955
|
+
q.save(out, format="PNG", optimize=True, compress_level=9)
|
|
956
|
+
kb = out.stat().st_size / 1024
|
|
957
|
+
note = "quantized"
|
|
958
|
+
if kb > max_kb:
|
|
959
|
+
scale = (max_kb / kb) ** 0.5
|
|
960
|
+
small = img.resize((max(1, int(w * scale)), max(1, int(h * scale))), Image.LANCZOS)
|
|
961
|
+
small.save(out, format="PNG", optimize=True, compress_level=9)
|
|
962
|
+
kb = out.stat().st_size / 1024
|
|
963
|
+
note = f"quantized+downscaled×{scale:.2f}"
|
|
964
|
+
|
|
965
|
+
return {"key": key, "type": typ, "size": f"{w}x{h}", "path": str(out),
|
|
966
|
+
"kb": round(kb, 1), "theme": kind, "note": note,
|
|
967
|
+
"engine": engine,
|
|
968
|
+
"backdrop": str(backdrop) if backdrop is not None else None,
|
|
969
|
+
"backdrop_used": str(backdrop_used) if backdrop_used is not None else None,
|
|
970
|
+
"upscale": round(upscale, 2) if upscale else None,
|
|
971
|
+
"upscale_warn": bool(upscale and upscale > 2.6),
|
|
972
|
+
"text_fit": fits,
|
|
973
|
+
"title_ratio": next((f["ratio"] for f in fits if f["role"] == "title"), None),
|
|
974
|
+
"contrast": {f["role"]: f["contrast"] for f in fits},
|
|
975
|
+
"text_ok": all(not f["overflow"] and f.get("contrast_ok", True) and f.get("thumb_ok", True)
|
|
976
|
+
for f in fits) if fits else True}
|
|
977
|
+
|
|
978
|
+
|
|
979
|
+
# ---------------------------------------------------------------- 上下文
|
|
980
|
+
|
|
981
|
+
def build_ctx(bp: dict, asset: dict) -> dict:
|
|
982
|
+
cust = bp.get("customer", {}) or {}
|
|
983
|
+
brand = hex2rgb(cust.get("theme_color") or "#1F3A68")
|
|
984
|
+
academy = cust.get("academy_name") or cust.get("name") or ""
|
|
985
|
+
hint = asset.get("prompt_hint") or ""
|
|
986
|
+
slogan = cust.get("slogan") or ""
|
|
987
|
+
m = re.search(r"【(.+?)】|「(.+?)」", hint)
|
|
988
|
+
if m and asset["key"].endswith(".a"):
|
|
989
|
+
slogan = (m.group(1) or m.group(2) or slogan).split("·")[-1].strip() or slogan
|
|
990
|
+
banner_b_title = asset.get("title") or academy
|
|
991
|
+
mb = re.search(r"文案[「\"](.+?)[」\"]", hint)
|
|
992
|
+
if mb:
|
|
993
|
+
banner_b_title = mb.group(1)
|
|
994
|
+
|
|
995
|
+
ctx = {"brand": brand, "academy": academy, "customer": cust.get("name", ""),
|
|
996
|
+
"slogan": slogan, "banner_b_title": banner_b_title}
|
|
997
|
+
|
|
998
|
+
key = asset["key"]
|
|
999
|
+
if key.startswith("cover.course."):
|
|
1000
|
+
idx = int(re.sub(r"\D", "", key.split(".")[-1]) or 0)
|
|
1001
|
+
c = (bp.get("courses") or [])
|
|
1002
|
+
# 资产 key 是 1 基(c1..c10),列表是 0 基——原实现直接用 c[idx] 会整体错位:
|
|
1003
|
+
# c1 拿到第二门课的标题、c10 越界拿空。这里统一换成 0 基位置。
|
|
1004
|
+
pos = idx - 1 if idx >= 1 else idx
|
|
1005
|
+
c = c[pos] if 0 <= pos < len(c) else {}
|
|
1006
|
+
ctx["course_title"] = c.get("title") or ""
|
|
1007
|
+
# category_path 在蓝图里是数组([L1, L2]),旧实现按字符串 split("/") 会直接抛异常
|
|
1008
|
+
cp = c.get("category_path")
|
|
1009
|
+
if isinstance(cp, (list, tuple)):
|
|
1010
|
+
ctx["course_sub"] = str(cp[-1]) if cp else ""
|
|
1011
|
+
elif isinstance(cp, dict):
|
|
1012
|
+
ctx["course_sub"] = str(cp.get("l2") or cp.get("l1") or "")
|
|
1013
|
+
else:
|
|
1014
|
+
ctx["course_sub"] = str(cp or "").split("/")[-1] or ""
|
|
1015
|
+
elif key.startswith("cover.map."):
|
|
1016
|
+
idx = int(re.sub(r"\D", "", key.split(".")[-1]) or 0)
|
|
1017
|
+
ms = bp.get("maps") or []
|
|
1018
|
+
pos = idx - 1 if idx >= 1 else idx
|
|
1019
|
+
mp = ms[pos] if 0 <= pos < len(ms) else {}
|
|
1020
|
+
ctx["map_title"] = mp.get("name") or ""
|
|
1021
|
+
n = len(mp.get("stages") or [])
|
|
1022
|
+
ctx["map_sub"] = f"{n} 阶段成长路径" if n else ""
|
|
1023
|
+
return ctx
|
|
1024
|
+
|
|
1025
|
+
|
|
1026
|
+
def _self_test() -> int:
|
|
1027
|
+
"""自检文字、类型分槽、缓存与 CLI(不连网、不写平台,仅使用临时目录)。"""
|
|
1028
|
+
fails = []
|
|
1029
|
+
assertions = 0
|
|
1030
|
+
|
|
1031
|
+
def ck(cond, msg):
|
|
1032
|
+
nonlocal assertions
|
|
1033
|
+
assertions += 1
|
|
1034
|
+
if not cond:
|
|
1035
|
+
fails.append(msg)
|
|
1036
|
+
|
|
1037
|
+
# ① 深底 + 常规长度标题:字高比、副标题比、对比度、缩略图
|
|
1038
|
+
img = Image.new("RGB", (960, 540), (24, 52, 96))
|
|
1039
|
+
_, fits = text_block(img, [
|
|
1040
|
+
{"content": "客舱失压与氧气处置", "role": "title", "x": 0.075, "y": 0.62, "max_w": 0.66},
|
|
1041
|
+
{"content": "客舱安全", "role": "subtitle", "x": 0.075, "y": 0.86, "max_w": 0.55},
|
|
1042
|
+
])
|
|
1043
|
+
t = next(f for f in fits if f["role"] == "title")
|
|
1044
|
+
s = next(f for f in fits if f["role"] == "subtitle")
|
|
1045
|
+
ck(t["ratio"] >= TITLE_MIN_RATIO - 0.005, f"主标题字高比 {t['ratio']} < {TITLE_MIN_RATIO}")
|
|
1046
|
+
ck(0.55 <= (s["size"] / t["size"]) <= 0.65, f"副标题/主标题字号比 {s['size'] / t['size']:.2f} 不在 55–65%")
|
|
1047
|
+
ck(t["contrast_ok"] and s["contrast_ok"], f"对比度未达标 title={t['contrast']} sub={s['contrast']}")
|
|
1048
|
+
ck(t["thumb_ok"], f"缩略图不可读 title 缩略后 {t['size'] * THUMB_SCALE:.0f}px")
|
|
1049
|
+
ck(not t["overflow"], "主标题溢出")
|
|
1050
|
+
|
|
1051
|
+
# ② 白底白字:必须自动加压板并把对比度拉回达标
|
|
1052
|
+
light = Image.new("RGB", (960, 540), (250, 250, 250))
|
|
1053
|
+
_, fits2 = text_block(light, [
|
|
1054
|
+
{"content": "白底压板测试", "role": "title", "x": 0.075, "y": 0.55, "max_w": 0.7, "color": "#FFFFFF"},
|
|
1055
|
+
])
|
|
1056
|
+
t2 = fits2[0]
|
|
1057
|
+
ck(t2["scrim"] > 0, "白底白字未加压板")
|
|
1058
|
+
ck(t2["contrast_ok"], f"压板后对比度仍不足 {t2['contrast']}")
|
|
1059
|
+
|
|
1060
|
+
# ③ 超长标题必须 wrap 或缩到下限,且不溢出
|
|
1061
|
+
long_img = Image.new("RGB", (960, 540), (24, 52, 96))
|
|
1062
|
+
_, fits3 = text_block(long_img, [
|
|
1063
|
+
{"content": "这是一条非常非常长的课程标题用来验证换行与安全边距不会顶边", "role": "title",
|
|
1064
|
+
"x": 0.075, "y": 0.6, "max_w": 0.66},
|
|
1065
|
+
])
|
|
1066
|
+
ck(not fits3[0]["overflow"], "超长标题溢出")
|
|
1067
|
+
|
|
1068
|
+
# ④ 底图裁切:任意比例输入 → 精确目标尺寸、无白边、放大倍数可记录
|
|
1069
|
+
src = Image.new("RGB", (1536, 1024), (40, 60, 90))
|
|
1070
|
+
img4, s4 = fit_cover(src, 960, 540)
|
|
1071
|
+
ck(img4.size == (960, 540), f"fit_cover 尺寸 {img4.size} != (960,540)")
|
|
1072
|
+
ck(0.2 <= s4 <= 6, f"fit_cover 缩放倍数异常 {s4}")
|
|
1073
|
+
ck(img4.getpixel((2, 2))[2] > 40, "fit_cover 边缘非底图内容(可能有白边)")
|
|
1074
|
+
img5, _ = fit_cover(Image.new("RGB", (4096, 512), (10, 20, 30)), 960, 540) # 超宽输入
|
|
1075
|
+
ck(img5.size == (960, 540), "fit_cover 超宽输入未裁到目标尺寸")
|
|
1076
|
+
|
|
1077
|
+
# ⑤ 生图作业单:prompt 必带「禁文字 / 品牌色 / 左下留白」三条硬约束
|
|
1078
|
+
bp_t = {"customer": {"name": "长龙航空", "theme_color": "#1F3A68"}, "courses": []}
|
|
1079
|
+
a_t = {"key": "cover.course.c1", "type": "cover_course",
|
|
1080
|
+
"prompt_hint": "客舱安全 合规 商务感 #C9A252"}
|
|
1081
|
+
p1 = build_backdrop_prompt(a_t, build_ctx(bp_t, a_t))
|
|
1082
|
+
ck("NO text" in p1["prompt"], "prompt 缺禁文字约束")
|
|
1083
|
+
ck("#1F3A68" in p1["prompt"].upper(), "prompt 缺品牌色")
|
|
1084
|
+
ck("LOWER-LEFT" in p1["prompt"], "prompt 缺左下留白构图约束")
|
|
1085
|
+
ck(p1["needs_backdrop"] and p1["out_path"] == "backdrop/cover.course.c1.png", "作业单落盘路径错")
|
|
1086
|
+
ck(p1["gen_size"] in ("1024x1024", "1536x1024"), "作业单缺推荐生图尺寸")
|
|
1087
|
+
p_logo = build_backdrop_prompt({"key": "logo.main", "type": "logo", "prompt_hint": ""}, build_ctx(bp_t, a_t))
|
|
1088
|
+
ck(not p_logo["needs_backdrop"], "logo 不应要求生图底图")
|
|
1089
|
+
|
|
1090
|
+
# ⑥ 底图合成链路:engine 标记 + 规格 + 文字自检同时成立
|
|
1091
|
+
import tempfile
|
|
1092
|
+
temp_dir = tempfile.TemporaryDirectory()
|
|
1093
|
+
tmp = Path(temp_dir.name)
|
|
1094
|
+
bd = tmp / "cover.course.c9.png"
|
|
1095
|
+
Image.new("RGB", (1536, 1024), (28, 44, 72)).save(bd)
|
|
1096
|
+
a6 = {"key": "cover.course.c9", "type": "cover_course", "prompt_hint": "安全 合规"}
|
|
1097
|
+
r6 = render(a6, build_ctx(bp_t, a6), tmp, backdrop=bd)
|
|
1098
|
+
ck(r6["engine"] == "imagegen-text-overlay", f"底图合成未标 imagegen 引擎:{r6['engine']}")
|
|
1099
|
+
ck(r6["size"] == "960x540", f"底图合成尺寸 {r6['size']}")
|
|
1100
|
+
ck(r6["text_ok"], "底图合成后文字自检未过")
|
|
1101
|
+
ck(Path(r6["path"]).exists(), "底图合成未落盘")
|
|
1102
|
+
|
|
1103
|
+
# ⑦ PC/移动端尺寸和遗留独立槽均不增加默认生图数;LOGO 不占槽。
|
|
1104
|
+
assets = [
|
|
1105
|
+
{"key": "banner.main.a", "type": "banner_pc", "backdrop_slot": "pc-a"},
|
|
1106
|
+
{"key": "banner.main.b", "type": "banner_pc", "backdrop_slot": "pc-b"},
|
|
1107
|
+
{"key": "banner.mobile.a", "type": "banner_mobile"},
|
|
1108
|
+
{"key": "cover.course.c1", "type": "cover_course", "backdrop_slot": "course-one"},
|
|
1109
|
+
{"key": "cover.course.c2", "type": "cover_course", "backdrop_slot": "course-two"},
|
|
1110
|
+
{"key": "cover.map.m1", "type": "cover_map"},
|
|
1111
|
+
{"key": "logo.main", "type": "logo"},
|
|
1112
|
+
]
|
|
1113
|
+
grouped_bp = {"assets": assets, "customer": {"name": "示例客户", "academy_name": "示例学堂"},
|
|
1114
|
+
"courses": [{"title": "真实课程一"}, {"title": "真实课程二"}]}
|
|
1115
|
+
ck(len(slots_of(assets)) == 3, "默认槽位不等于三类")
|
|
1116
|
+
ck(len(slots_of(assets, "none")) == 6, "显式独立底图模式失效")
|
|
1117
|
+
ck(len(slots_of(assets, "all")) == 1, "all 模式多于一张底图")
|
|
1118
|
+
import contextlib
|
|
1119
|
+
import io
|
|
1120
|
+
|
|
1121
|
+
def plan_for(selected, mode="by-type", bdir=None):
|
|
1122
|
+
with contextlib.redirect_stdout(io.StringIO()):
|
|
1123
|
+
emit_prompts(grouped_bp, selected, tmp, mode, bdir)
|
|
1124
|
+
return json.loads((tmp / "backdrop-prompts.json").read_text(encoding="utf-8"))
|
|
1125
|
+
|
|
1126
|
+
plan = plan_for(assets)
|
|
1127
|
+
ck(plan["need_image"] == 3 and len(plan["items"]) == 3, "完整作业单不是三张底图")
|
|
1128
|
+
ck(all(i["type"] != "logo" for i in plan["items"]), "LOGO 进入生图作业单")
|
|
1129
|
+
wave = plan_for(assets[:1])
|
|
1130
|
+
ck(wave["need_image"] == 1, "wave1 生成了未用类型")
|
|
1131
|
+
cache = tmp / "backdrop"
|
|
1132
|
+
cache.mkdir()
|
|
1133
|
+
Image.new("RGB", (80, 40), (22, 44, 66)).save(cache / "brand-banner.png")
|
|
1134
|
+
wave2 = plan_for(assets[1:3])
|
|
1135
|
+
ck(wave2["need_image"] == 0 and len(wave2["reused"]) == 1, "跨波次未复用 Banner 底图")
|
|
1136
|
+
(cache / "brand-cover_course.png").write_bytes(b"broken-image")
|
|
1137
|
+
ck(plan_for(assets[3:5])["need_image"] == 1, "损坏缓存被当作可复用底图")
|
|
1138
|
+
# 旧版按 key 保存的底图也可成为整类底图,即使旧 key 不在本波 todo 中。
|
|
1139
|
+
Image.new("RGB", (80, 40), (33, 55, 77)).save(cache / "cover.course.c1.png")
|
|
1140
|
+
legacy_plan = plan_for([assets[4]])
|
|
1141
|
+
ck(legacy_plan["need_image"] == 0, "旧 key 底图未跨 --only 波次复用")
|
|
1142
|
+
ck(slot_file(cache, "brand-cover_course") is not None, "旧底图未固化为类型槽")
|
|
1143
|
+
empty = plan_for([])
|
|
1144
|
+
ck(empty["items"] == [] and empty["need_image"] == 0, "空作业单遗留了待生图任务")
|
|
1145
|
+
ck(plan_for([assets[-1]])["need_image"] == 0, "仅 LOGO 仍请求生图")
|
|
1146
|
+
# 文案缺失不虚构开班/报名/默认四阶段;已有课程名严格取蓝图。
|
|
1147
|
+
plain_ctx = build_ctx(grouped_bp, assets[1])
|
|
1148
|
+
ck("报名" not in plain_ctx["banner_b_title"] and not plain_ctx["slogan"], "缺失文案虚构业务")
|
|
1149
|
+
ck(build_ctx(grouped_bp, assets[4])["course_title"] == "真实课程二", "课程索引/文案错位")
|
|
1150
|
+
ck(build_ctx(grouped_bp, assets[5])["map_sub"] == "", "缺失地图阶段时虚构四阶段")
|
|
1151
|
+
|
|
1152
|
+
# ⑧ CLI --force 只重渲成品,不触发缓存失效;自定义目录与空清单均重写作业单。
|
|
1153
|
+
import subprocess
|
|
1154
|
+
cli_bp = tmp / "blueprint.json"
|
|
1155
|
+
for asset in assets:
|
|
1156
|
+
asset["status"] = "ready"
|
|
1157
|
+
cli_bp.write_text(json.dumps(grouped_bp, ensure_ascii=False), encoding="utf-8")
|
|
1158
|
+
command = [sys.executable, str(Path(__file__).resolve()), "--blueprint", str(cli_bp),
|
|
1159
|
+
"--only", "banner.main.b", "--force", "--emit-prompts"]
|
|
1160
|
+
run = subprocess.run(command, capture_output=True, text=True)
|
|
1161
|
+
forced = json.loads((tmp / "backdrop-prompts.json").read_text(encoding="utf-8"))
|
|
1162
|
+
ck(run.returncode == 0 and forced["need_image"] == 0 and len(forced["reused"]) == 1,
|
|
1163
|
+
"--force 使缓存失效或CLI失败")
|
|
1164
|
+
custom = tmp / "custom"
|
|
1165
|
+
custom.mkdir()
|
|
1166
|
+
Image.new("RGB", (80, 40), (11, 33, 55)).save(custom / "brand-banner.jpg")
|
|
1167
|
+
run = subprocess.run(command + ["--backdrop-dir", str(custom)], capture_output=True, text=True)
|
|
1168
|
+
custom_plan = json.loads((tmp / "backdrop-prompts.json").read_text(encoding="utf-8"))
|
|
1169
|
+
ck(run.returncode == 0 and custom_plan["need_image"] == 0 and Path(custom_plan["backdrop_dir"]).resolve() == custom.resolve(),
|
|
1170
|
+
"自定义底图目录未生效")
|
|
1171
|
+
run = subprocess.run([c for c in command if c != "--force"], capture_output=True, text=True)
|
|
1172
|
+
cleared = json.loads((tmp / "backdrop-prompts.json").read_text(encoding="utf-8"))
|
|
1173
|
+
ck(run.returncode == 0 and cleared["items"] == [], "全部ready时未清除旧生图作业单")
|
|
1174
|
+
before_cache = (cache / "brand-cover_course.png").read_bytes()
|
|
1175
|
+
run = subprocess.run([sys.executable, str(Path(__file__).resolve()), "--blueprint", str(cli_bp),
|
|
1176
|
+
"--only", "cover.course.c2", "--force"], capture_output=True, text=True)
|
|
1177
|
+
rendered = json.loads((tmp / "asset-render-report.json").read_text(encoding="utf-8"))["items"][0]
|
|
1178
|
+
ck(run.returncode == 0 and rendered.get("engine") == "imagegen-text-overlay",
|
|
1179
|
+
"--force 成品合成未使用缓存底图")
|
|
1180
|
+
ck(before_cache == (cache / "brand-cover_course.png").read_bytes(), "--force 合成改写了已有底图")
|
|
1181
|
+
ck(rendered.get("backdrop_used") == str((cache / "brand-cover_course.png").resolve()),
|
|
1182
|
+
"课程成品未使用固定类型槽")
|
|
1183
|
+
first = render(assets[3], build_ctx(grouped_bp, assets[3]), tmp, cache / "brand-cover_course.png")
|
|
1184
|
+
ck(Path(first["path"]).read_bytes() != (tmp / "cover.course.c2.png").read_bytes(),
|
|
1185
|
+
"同底图不同课程标题未生成不同成品")
|
|
1186
|
+
explicit = dict(assets[3], texts={"title": "蓝图明确标题", "subtitle": "蓝图明确副标题"})
|
|
1187
|
+
explicit_result = render(explicit, build_ctx(grouped_bp, explicit), tmp, cache / "brand-cover_course.png")
|
|
1188
|
+
ck({f["role"] for f in explicit_result["text_fit"]} == {"title", "subtitle"},
|
|
1189
|
+
"蓝图显式文字未覆盖缺失副标题")
|
|
1190
|
+
temp_dir.cleanup()
|
|
1191
|
+
if fails:
|
|
1192
|
+
print(json.dumps({"ok": False, "assertions": assertions, "fails": fails}, ensure_ascii=False, indent=2))
|
|
1193
|
+
return 1
|
|
1194
|
+
print(json.dumps({"ok": True, "assertions": assertions}, ensure_ascii=False))
|
|
1195
|
+
return 0
|
|
1196
|
+
|
|
1197
|
+
|
|
1198
|
+
def emit_prompts(bp: dict, todo: list, outdir: Path,
|
|
1199
|
+
group_mode: str = "by-type", backdrop_dir: Path = None) -> int:
|
|
1200
|
+
"""仅为缺失的槽位出作业;缓存命中另列 reused,不受 --force 影响。"""
|
|
1201
|
+
bdir = backdrop_dir if backdrop_dir is not None else outdir / "backdrop"
|
|
1202
|
+
all_assets = bp.get("assets") or todo
|
|
1203
|
+
slot_map = {}
|
|
1204
|
+
for asset in todo:
|
|
1205
|
+
slot = slot_of(asset, group_mode)
|
|
1206
|
+
if slot:
|
|
1207
|
+
slot_map.setdefault(slot, []).append(asset)
|
|
1208
|
+
|
|
1209
|
+
items, reused = [], []
|
|
1210
|
+
for slot, assets in slot_map.items():
|
|
1211
|
+
cached = cached_backdrop(bdir, slot, all_assets, group_mode)
|
|
1212
|
+
if cached is not None:
|
|
1213
|
+
reused.append({"backdrop_slot": slot, "keys": [a["key"] for a in assets],
|
|
1214
|
+
"path": str(cached), "needs_backdrop": False})
|
|
1215
|
+
continue
|
|
1216
|
+
# 按完整蓝图选择代表,避免 --only 波次顺序影响同类底图主题。
|
|
1217
|
+
representative = next((a for a in all_assets if slot_of(a, group_mode) == slot), assets[0])
|
|
1218
|
+
rep = build_backdrop_prompt(representative, build_ctx(bp, representative),
|
|
1219
|
+
disambiguate=group_mode == "none")
|
|
1220
|
+
rep.update({"keys": [a["key"] for a in assets], "backdrop_slot": slot,
|
|
1221
|
+
"out_path": str(bdir / f"{slot}.png")})
|
|
1222
|
+
items.append(rep)
|
|
1223
|
+
|
|
1224
|
+
plan = {
|
|
1225
|
+
"blueprint_id": bp.get("blueprint_id") or outdir.name,
|
|
1226
|
+
"backdrop_dir": str(bdir),
|
|
1227
|
+
"engine": "imagegen", "group_mode": group_mode,
|
|
1228
|
+
"slots": len(slot_map), "total": len(todo), "need_image": len(items),
|
|
1229
|
+
"est_credits": [5 * len(items), 10 * len(items)],
|
|
1230
|
+
"retry_limit": 1, "items": items, "reused": reused,
|
|
1231
|
+
}
|
|
1232
|
+
out = outdir / "backdrop-prompts.json"
|
|
1233
|
+
out.write_text(json.dumps(plan, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
1234
|
+
print(json.dumps({"ok": True, "prompts": str(out), "total": plan["total"],
|
|
1235
|
+
"slots": plan["slots"], "need_image": plan["need_image"],
|
|
1236
|
+
"reused": len(reused), "group_mode": group_mode,
|
|
1237
|
+
"hint": "仅对 items 中缺失槽位调用 ImageGen;reused 禁止重新生图。"
|
|
1238
|
+
"每槽位失败最多重试一次;--force 只重绘文字成品。"},
|
|
1239
|
+
ensure_ascii=False, indent=2))
|
|
1240
|
+
return 0
|
|
1241
|
+
|
|
1242
|
+
|
|
1243
|
+
def main():
|
|
1244
|
+
ap = argparse.ArgumentParser()
|
|
1245
|
+
ap.add_argument("--blueprint", help="DEMO-BLUEPRINT.json 路径(--self-test 时可省)")
|
|
1246
|
+
ap.add_argument("--outdir")
|
|
1247
|
+
ap.add_argument("--only", help="逗号分隔的用途键")
|
|
1248
|
+
ap.add_argument("--force", action="store_true")
|
|
1249
|
+
ap.add_argument("--list", action="store_true")
|
|
1250
|
+
ap.add_argument("--emit-prompts", action="store_true", help="只产生 ImageGen 作业单,不出图")
|
|
1251
|
+
ap.add_argument("--backdrop-dir", help="ImageGen 底图目录(缺省 <outdir>/backdrop)")
|
|
1252
|
+
ap.add_argument("--offline-fallback", action="store_true",
|
|
1253
|
+
help="缺底图时允许本地绘制(显式降级,report 标 engine=local-pil)")
|
|
1254
|
+
ap.add_argument("--brand-template", action="store_true",
|
|
1255
|
+
help="品牌底图模板模式:不依赖 ImageGen,所有图片基于同一品牌模板底图 + 文字层;"
|
|
1256
|
+
"engine 标 brand-template(适合快速 DEMO / 无生图额度)")
|
|
1257
|
+
ap.add_argument("--group-mode", choices=["none", "by-type", "all"], default="by-type",
|
|
1258
|
+
help="默认 by-type:Banner(含PC/移动)、课程、地图各至多一张底图;"
|
|
1259
|
+
"忽略遗留分槽字段。all=全部共用;none=用户明确指定独立底图时才使用")
|
|
1260
|
+
ap.add_argument("--self-test", action="store_true", help="自检文字层级/对比度/缩略图/底图合成")
|
|
1261
|
+
args = ap.parse_args()
|
|
1262
|
+
|
|
1263
|
+
if args.self_test:
|
|
1264
|
+
return _self_test()
|
|
1265
|
+
|
|
1266
|
+
bpath = Path(args.blueprint).expanduser().resolve()
|
|
1267
|
+
bp = json.loads(bpath.read_text(encoding="utf-8"))
|
|
1268
|
+
outdir = Path(args.outdir).expanduser().resolve() if args.outdir else bpath.parent
|
|
1269
|
+
outdir.mkdir(parents=True, exist_ok=True)
|
|
1270
|
+
|
|
1271
|
+
only = {s.strip() for s in args.only.split(",")} if args.only else None
|
|
1272
|
+
todo = [a for a in bp.get("assets", [])
|
|
1273
|
+
if (only is None or a["key"] in only)
|
|
1274
|
+
and (args.force or a.get("status") != "ready")]
|
|
1275
|
+
if not todo and not args.emit_prompts:
|
|
1276
|
+
print(json.dumps({"ok": True, "generated": 0, "msg": "无待生成资产"}, ensure_ascii=False))
|
|
1277
|
+
return 0
|
|
1278
|
+
|
|
1279
|
+
if args.list:
|
|
1280
|
+
print(json.dumps([{"key": a["key"], "type": a.get("type"), "size": a.get("size")} for a in todo],
|
|
1281
|
+
ensure_ascii=False, indent=2))
|
|
1282
|
+
return 0
|
|
1283
|
+
|
|
1284
|
+
bdir = Path(args.backdrop_dir).expanduser().resolve() if args.backdrop_dir else outdir / "backdrop"
|
|
1285
|
+
if args.emit_prompts:
|
|
1286
|
+
return emit_prompts(bp, todo, outdir, args.group_mode, bdir)
|
|
1287
|
+
|
|
1288
|
+
# 品牌模板模式:所有图共用一张本地生成的品牌底图(无 ImageGen 依赖)
|
|
1289
|
+
brand_backdrop = None
|
|
1290
|
+
if args.brand_template:
|
|
1291
|
+
brand_backdrop = bdir / "brand-template.png"
|
|
1292
|
+
if not brand_backdrop.exists():
|
|
1293
|
+
# 用 render() 的本地绘制分支生成一张"底图"(无文字),作为品牌模板
|
|
1294
|
+
# 用 banner_pc 尺寸作为模板基准(最大尺寸,fit_cover 时会被裁切)
|
|
1295
|
+
import PIL.Image as _PI
|
|
1296
|
+
_brand_img = None
|
|
1297
|
+
# 复用 render 的本地绘制路径:构造一个 logo 类型 asset 强制 local-pil
|
|
1298
|
+
# 简单起见:用 draw_motif + gradient 生成一张 1920x1080 品牌底图
|
|
1299
|
+
w, h = 1920, 1080
|
|
1300
|
+
brand = hex2rgb((bp.get("customer") or {}).get("theme_color") or "#1F3A68")
|
|
1301
|
+
accent = pick_accent("", brand)
|
|
1302
|
+
rnd = random.Random(42)
|
|
1303
|
+
c_deep = shade(hsv_shift(brand, dh=rnd.uniform(-0.02, 0.02), dv=-0.16), -0.18)
|
|
1304
|
+
c_light = shade(hsv_shift(brand, dh=rnd.uniform(-0.03, 0.03), dv=0.10), 0.30)
|
|
1305
|
+
_brand_img = gradient((w, h), c_deep, c_light, angle=rnd.choice([8, 12, 16, -10]))
|
|
1306
|
+
_brand_img = radial_glow(_brand_img, (w * rnd.uniform(0.60, 0.80), h * 0.30), min(w, h) * 0.60, accent, 55)
|
|
1307
|
+
_brand_img = radial_glow(_brand_img, (w * 0.08, h * 0.92), min(w, h) * 0.45, shade(brand, 0.45), 48)
|
|
1308
|
+
_brand_img = draw_banner_deco(_brand_img, brand, accent, rnd)
|
|
1309
|
+
_brand_img = add_vignette(_brand_img, 0.20)
|
|
1310
|
+
bdir.mkdir(parents=True, exist_ok=True)
|
|
1311
|
+
_brand_img.save(brand_backdrop, format="PNG", optimize=True)
|
|
1312
|
+
print(json.dumps({"ok": True, "brand_template": str(brand_backdrop)}, ensure_ascii=False))
|
|
1313
|
+
|
|
1314
|
+
reports, missing = [], []
|
|
1315
|
+
for a in todo:
|
|
1316
|
+
typ = a.get("type", "cover_course")
|
|
1317
|
+
slot = slot_of(a, args.group_mode)
|
|
1318
|
+
# 全蓝图内发现旧底图即固化为类型槽,后续资产和波次始终复用同一张。
|
|
1319
|
+
bd = None
|
|
1320
|
+
if typ != "logo":
|
|
1321
|
+
bd = cached_backdrop(bdir, slot, bp.get("assets") or todo, args.group_mode)
|
|
1322
|
+
if bd is None and typ != "logo" and args.brand_template and brand_backdrop is not None:
|
|
1323
|
+
bd = brand_backdrop
|
|
1324
|
+
if bd is None and typ != "logo" and not args.offline_fallback and not args.brand_template:
|
|
1325
|
+
missing.append(a["key"])
|
|
1326
|
+
a["status"] = "failed"
|
|
1327
|
+
reports.append({"key": a["key"], "error": f"missing_backdrop: {bdir}/{slot}.png"})
|
|
1328
|
+
continue
|
|
1329
|
+
try:
|
|
1330
|
+
r = render(a, build_ctx(bp, a), outdir, backdrop=bd, brand_template=args.brand_template)
|
|
1331
|
+
a["status"] = "ready"
|
|
1332
|
+
a["local_path"] = r["path"]
|
|
1333
|
+
a["render"] = {"engine": r["engine"], "theme": r["theme"], "kb": r["kb"],
|
|
1334
|
+
"backdrop": r.get("backdrop_used") or r.get("backdrop"),
|
|
1335
|
+
"upscale": r.get("upscale"),
|
|
1336
|
+
"backdrop_slot": slot}
|
|
1337
|
+
reports.append(r)
|
|
1338
|
+
except Exception as e: # 失败隔离:单张失败不影响整批
|
|
1339
|
+
a["status"] = "failed"
|
|
1340
|
+
reports.append({"key": a["key"], "error": f"{type(e).__name__}: {e}"})
|
|
1341
|
+
|
|
1342
|
+
bpath.write_text(json.dumps(bp, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
1343
|
+
|
|
1344
|
+
ok = [r for r in reports if "error" not in r]
|
|
1345
|
+
engines = sorted({r.get("engine") for r in ok})
|
|
1346
|
+
manifest = outdir / "asset-render-report.json"
|
|
1347
|
+
manifest.write_text(json.dumps({"engine": "+".join(engines) if engines else "none",
|
|
1348
|
+
"items": reports}, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
1349
|
+
|
|
1350
|
+
bad_text = [r["key"] for r in ok if not r.get("text_ok", True)]
|
|
1351
|
+
print(json.dumps({"ok": len(ok) == len(reports), "generated": len(ok), "failed": len(reports) - len(ok),
|
|
1352
|
+
"engines": engines,
|
|
1353
|
+
"font": font_status(),
|
|
1354
|
+
"missing_backdrop": missing,
|
|
1355
|
+
"text_overflow": bad_text,
|
|
1356
|
+
"upscale_warn": [r["key"] for r in ok if r.get("upscale_warn")],
|
|
1357
|
+
"outdir": str(outdir),
|
|
1358
|
+
"items": [{"key": r.get("key"), "kb": r.get("kb"), "engine": r.get("engine"),
|
|
1359
|
+
"theme": r.get("theme"), "text_ok": r.get("text_ok")} for r in ok]},
|
|
1360
|
+
ensure_ascii=False, indent=2))
|
|
1361
|
+
return 0 if not missing and len(ok) == len(reports) else 1
|
|
1362
|
+
|
|
1363
|
+
|
|
1364
|
+
|
|
1365
|
+
if __name__ == "__main__":
|
|
1366
|
+
sys.exit(main())
|