ai_service.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. # -*- coding: utf-8 -*-
  2. """AI 交互式排版服务。
  3. - LLM:OpenAI 兼容 chat/completions(环境变量 PL_AI_BASE_URL / PL_AI_API_KEY / PL_AI_MODEL,
  4. 默认智谱开放平台 glm-4-flash;未配置 key 时接口返回 503,前端提示)
  5. - 用量:users.ai_quota / ai_used(后台可改额度),每次成功调用扣 1 并记录 ai_calls
  6. - 交互:前端把上一轮生成的 elements 作为 context 传入即可多轮调整("文字再大一点")
  7. - 输出严格校验(元素数、坐标、颜色格式),异常数据自动剔除,保证画布不炸
  8. """
  9. import json
  10. import os
  11. import re
  12. import time
  13. import urllib.request
  14. import cache
  15. from db import db, get_setting, set_setting
  16. ENV_BASE_URL = os.environ.get("PL_AI_BASE_URL", "https://open.bigmodel.cn/api/paas/v4")
  17. ENV_API_KEY = os.environ.get("PL_AI_API_KEY", "")
  18. ENV_MODEL = os.environ.get("PL_AI_MODEL", "glm-4-flash")
  19. MAX_ELEMENTS = 12
  20. HEX_RE = re.compile(r"^#[0-9a-fA-F]{6}$")
  21. CONFIG_KEYS = ("ai_base_url", "ai_api_key", "ai_model")
  22. def get_config() -> dict:
  23. """AI 配置:后台设置(settings 表,Redis 缓存)优先,环境变量兜底。"""
  24. cached = cache.get_json("pl:ai-config")
  25. if cached is not None:
  26. return cached
  27. cfg = {
  28. "baseUrl": get_setting("ai_base_url") or ENV_BASE_URL,
  29. "apiKey": get_setting("ai_api_key") or ENV_API_KEY,
  30. "model": get_setting("ai_model") or ENV_MODEL,
  31. "source": {
  32. "baseUrl": "db" if get_setting("ai_base_url") else ("env" if ENV_API_KEY or True else "default"),
  33. },
  34. }
  35. cache.set_json("pl:ai-config", cfg, 60)
  36. return cfg
  37. def save_config(base_url: str = None, api_key: str = None, model: str = None):
  38. """后台保存配置;api_key 传空串/None 表示不修改。保存后立即失效缓存。"""
  39. if base_url is not None and base_url.strip():
  40. set_setting("ai_base_url", base_url.strip()[:300])
  41. if api_key: # 空串 = 保持不变(避免误清空)
  42. set_setting("ai_api_key", api_key.strip()[:300])
  43. if model is not None and model.strip():
  44. set_setting("ai_model", model.strip()[:100])
  45. cache.delete("pl:ai-config")
  46. STICKERS = ["leaf", "coffeeBean", "cup", "star", "sparkle", "heart", "wave",
  47. "sun", "flower", "paw", "arrow", "mountain", "wheat", "bolt"]
  48. # ---------- logo / 背景装饰(盒面矢量模板,输出 asset 项) ----------
  49. def _svg_dataurl(svg):
  50. import base64
  51. return "data:image/svg+xml;base64," + base64.b64encode(svg.encode()).decode()
  52. def build_logo_svg(template, text, color):
  53. """按模板生成 logo SVG(viewBox 200x200,居中)。"""
  54. t = str(text or "")[:6]
  55. c = _hex(color, "#2b2620")
  56. tpl = template if template in LOGO_TEMPLATES else "monogram"
  57. return LOGO_TEMPLATES[tpl](t, c)
  58. def _esc_xml(s):
  59. return (str(s or "").replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;"))
  60. LOGO_TEMPLATES = {
  61. "monogram": lambda t, c: (
  62. '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200">'
  63. '<circle cx="100" cy="100" r="86" fill="none" stroke="%s" stroke-width="3"/>'
  64. '<circle cx="100" cy="100" r="76" fill="none" stroke="%s" stroke-width="1"/>'
  65. '<text x="100" y="112" text-anchor="middle" font-family="Georgia,serif" '
  66. 'font-size="34" letter-spacing="1" fill="%s">%s</text></svg>' % (c, c, c, _esc_xml(t))),
  67. "candle": lambda t, c: (
  68. '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200">'
  69. '<rect x="86" y="86" width="28" height="76" rx="3" fill="none" stroke="%s" stroke-width="3"/>'
  70. '<line x1="100" y1="86" x2="100" y2="58" stroke="%s" stroke-width="3"/>'
  71. '<ellipse cx="100" cy="48" rx="7" ry="12" fill="%s"/>'
  72. '<text x="100" y="40" text-anchor="middle" font-family="Georgia,serif" font-size="15" '
  73. 'letter-spacing="2" fill="%s">%s</text></svg>' % (c, c, c, c, _esc_xml(t))),
  74. "leaf": lambda t, c: (
  75. '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200">'
  76. '<path d="M100 26 C150 60 158 120 100 174 C42 120 50 60 100 26 Z" fill="none" stroke="%s" stroke-width="3"/>'
  77. '<line x1="100" y1="40" x2="100" y2="166" stroke="%s" stroke-width="1.4"/>'
  78. '<text x="100" y="196" text-anchor="middle" font-family="Georgia,serif" font-size="14" '
  79. 'letter-spacing="2" fill="%s">%s</text></svg>' % (c, c, c, _esc_xml(t))),
  80. "spark": lambda t, c: (
  81. '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200">'
  82. '<path d="M100 20 L112 78 L170 90 L112 102 L100 160 L88 102 L30 90 L88 78 Z" '
  83. 'fill="none" stroke="%s" stroke-width="3" stroke-linejoin="round"/>'
  84. '<text x="100" y="192" text-anchor="middle" font-family="Georgia,serif" font-size="15" '
  85. 'letter-spacing="2" fill="%s">%s</text></svg>' % (c, c, _esc_xml(t))),
  86. "mountain": lambda t, c: (
  87. '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200">'
  88. '<path d="M26 150 L74 74 L104 118 L126 88 L174 150 Z" fill="none" stroke="%s" '
  89. 'stroke-width="3" stroke-linejoin="round"/>'
  90. '<circle cx="148" cy="54" r="12" fill="none" stroke="%s" stroke-width="2.4"/>'
  91. '<text x="100" y="180" text-anchor="middle" font-family="Georgia,serif" font-size="14" '
  92. 'letter-spacing="2" fill="%s">%s</text></svg>' % (c, c, c, _esc_xml(t))),
  93. "banner": lambda t, c: (
  94. '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200">'
  95. '<rect x="30" y="66" width="140" height="66" fill="none" stroke="%s" stroke-width="2.6"/>'
  96. '<path d="M30 132 L50 148 L50 118 M170 132 L150 148 L150 118" fill="none" stroke="%s" stroke-width="2.6"/>'
  97. '<text x="100" y="106" text-anchor="middle" font-family="Georgia,serif" font-size="22" '
  98. 'letter-spacing="1.6" fill="%s">%s</text></svg>' % (c, c, c, _esc_xml(t))),
  99. }
  100. BG_DECO_TEMPLATES = {
  101. # 全幅装饰框(细线双框)
  102. "border-frame": lambda c: (
  103. '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 300" preserveAspectRatio="none">'
  104. '<rect x="6" y="6" width="188" height="288" fill="none" stroke="%s" stroke-width="1.6"/>'
  105. '<rect x="12" y="12" width="176" height="276" fill="none" stroke="%s" stroke-width="0.8"/>'
  106. '</svg>' % (c, c)),
  107. # 顶部色带
  108. "top-band": lambda c: (
  109. '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 300" preserveAspectRatio="none">'
  110. '<rect x="0" y="0" width="200" height="34" fill="%s"/>'
  111. '<rect x="0" y="38" width="200" height="2.4" fill="%s"/>'
  112. '</svg>' % (c, c)),
  113. # 底部色带
  114. "bottom-band": lambda c: (
  115. '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 300" preserveAspectRatio="none">'
  116. '<rect x="0" y="264" width="200" height="36" fill="%s"/>'
  117. '<rect x="0" y="258" width="200" height="2.4" fill="%s"/>'
  118. '</svg>' % (c, c)),
  119. # 上下呼应带
  120. "both-band": lambda c: (
  121. '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 300" preserveAspectRatio="none">'
  122. '<rect x="0" y="0" width="200" height="26" fill="%s"/>'
  123. '<rect x="0" y="274" width="200" height="26" fill="%s"/>'
  124. '</svg>' % (c, c)),
  125. # 四角刻线
  126. "corner-marks": lambda c: (
  127. '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 300" preserveAspectRatio="none">'
  128. '<path d="M8 28 V8 H28 M172 8 H192 V28 M192 272 V292 H172 M28 292 H8 V272" '
  129. 'fill="none" stroke="%s" stroke-width="2.4"/></svg>' % c),
  130. }
  131. def configured() -> bool:
  132. return bool(get_config()["apiKey"])
  133. # ---------- 用量 ----------
  134. def quota_of(user_id: int) -> dict:
  135. with db() as cur:
  136. cur.execute("SELECT ai_quota, ai_used FROM users WHERE id = %s", (user_id,))
  137. r = cur.fetchone()
  138. return {"quota": r["ai_quota"], "used": r["ai_used"]} if r else {"quota": 0, "used": 0}
  139. def consume(user_id: int, ok: bool, kind: str, brief: str, detail: str = ""):
  140. with db() as cur:
  141. if ok:
  142. cur.execute("UPDATE users SET ai_used = ai_used + 1 WHERE id = %s", (user_id,))
  143. cur.execute(
  144. "INSERT INTO ai_calls (user_id, kind, brief, ok, detail, created_at) VALUES (%s,%s,%s,%s,%s,%s)",
  145. (user_id, kind, brief[:500], 1 if ok else 0, detail[:200], int(time.time())),
  146. )
  147. # ---------- LLM ----------
  148. def chat(messages: list, timeout: int = 180, max_tokens: int = 3000) -> str:
  149. cfg = get_config()
  150. body = json.dumps({
  151. "model": cfg["model"],
  152. "messages": messages,
  153. "temperature": 0.7,
  154. "max_tokens": max_tokens,
  155. }).encode()
  156. req = urllib.request.Request(
  157. cfg["baseUrl"].rstrip("/") + "/chat/completions",
  158. data=body,
  159. headers={"Content-Type": "application/json", "Authorization": "Bearer " + cfg["apiKey"]},
  160. method="POST",
  161. )
  162. with urllib.request.urlopen(req, timeout=timeout) as resp:
  163. data = json.loads(resp.read())
  164. return data["choices"][0]["message"]["content"]
  165. def _salvage_truncated_json(text: str):
  166. """LLM 输出被 max_tokens 截断时,截到最后一个完整值并补全闭合容器。"""
  167. stack = []
  168. in_str = False
  169. esc = False
  170. last_safe = -1 # 最后一个"完整值结束"位置(元素 } 或 ] 或字符串结束后的 , 之前)
  171. i = 0
  172. n = len(text)
  173. while i < n:
  174. ch = text[i]
  175. if in_str:
  176. if esc:
  177. esc = False
  178. elif ch == '\\':
  179. esc = True
  180. elif ch == '"':
  181. in_str = False
  182. else:
  183. if ch == '"':
  184. in_str = True
  185. elif ch in '[{':
  186. stack.append(ch)
  187. elif ch in ']}':
  188. if stack:
  189. stack.pop()
  190. last_safe = i # 完整闭合的容器末尾
  191. elif ch == ',' and not stack:
  192. pass
  193. i += 1
  194. if last_safe < 0:
  195. raise ValueError("no complete value in truncated output")
  196. # 另一种截断:数组里最后一个完整对象后没有逗号——回退到该对象的 }
  197. cut = text.rfind('}', 0, last_safe + 1)
  198. if cut < 0:
  199. cut = last_safe
  200. candidate = text[:cut + 1].rstrip().rstrip(',').rstrip()
  201. # 重新计数未闭合栈(含 pop),逆序补全
  202. stack = []
  203. in_str = False
  204. esc = False
  205. for ch in candidate:
  206. if in_str:
  207. if esc:
  208. esc = False
  209. elif ch == '\\':
  210. esc = True
  211. elif ch == '"':
  212. in_str = False
  213. else:
  214. if ch == '"':
  215. in_str = True
  216. elif ch in '[{':
  217. stack.append(ch)
  218. elif ch in ']}':
  219. if stack:
  220. stack.pop()
  221. closer = {'[': ']', '{': '}'}
  222. return json.loads(candidate + ''.join(closer[c] for c in reversed(stack)))
  223. def parse_json_content(content: str) -> dict:
  224. """剥掉 ```json 围栏后解析;截断输出自动补全修复。"""
  225. content = content.strip()
  226. m = re.search(r"```(?:json)?\s*([\s\S]*?)```", content)
  227. if m:
  228. content = m.group(1).strip()
  229. start = content.find("{")
  230. if start >= 0:
  231. content = content[start:]
  232. try:
  233. end = content.rfind("}")
  234. if end > 0:
  235. return json.loads(content[:end + 1])
  236. return json.loads(content)
  237. except ValueError:
  238. return _salvage_truncated_json(content)
  239. # ---------- 校验 ----------
  240. def _hex(v, fallback="#1a1a1a"):
  241. v = str(v or "")
  242. return v if HEX_RE.match(v) else fallback
  243. def _num(v, lo, hi, default):
  244. try:
  245. return max(lo, min(hi, float(v)))
  246. except (TypeError, ValueError):
  247. return default
  248. def sanitize_bag(result: dict, w: float, h: float) -> dict:
  249. """袋画布:坐标 mm(0..w/0..h),与 studio.js 元素结构一致。"""
  250. out_elements = []
  251. for el in (result.get("elements") or [])[:MAX_ELEMENTS]:
  252. t = el.get("type")
  253. base = {
  254. "x": _num(el.get("x"), 0, w, w / 2),
  255. "y": _num(el.get("y"), 0, h, h / 2),
  256. "color": _hex(el.get("color")),
  257. "rotation": _num(el.get("rotation"), -180, 180, 0),
  258. }
  259. if t == "text":
  260. text = str(el.get("text") or "").strip()[:60]
  261. if not text:
  262. continue
  263. out_elements.append(dict(base, type="text", id=None, text=text,
  264. w=_num(el.get("w"), 10, w, w * 0.7),
  265. size=_num(el.get("size"), 4, min(w, h) * 0.35, 12),
  266. weight=700 if el.get("weight") in (700, "700", "bold") else 400,
  267. align=el.get("align") if el.get("align") in ("left", "center", "right") else "center",
  268. font=el.get("font") if el.get("font") in ("sans", "serif", "round", "mono", "hand") else "sans",
  269. spacing=_num(el.get("spacing"), -5, 40, 0),
  270. lineHeight=_num(el.get("lineHeight"), 1.0, 2.2, 1.35)))
  271. elif t == "shape":
  272. shape = el.get("shape") if el.get("shape") in ("rect", "circle", "line") else "rect"
  273. out_elements.append(dict(base, type="shape", id=None, shape=shape,
  274. w=_num(el.get("w"), 2, w, w * 0.4),
  275. h=_num(el.get("h"), 2, h, h * 0.2),
  276. fill=_hex(el.get("fill"), "#00000000"[:7]),
  277. strokeWidth=_num(el.get("strokeWidth"), 0.2, 4, 0.6)))
  278. elif t == "sticker":
  279. sticker = el.get("sticker") if el.get("sticker") in STICKERS else "leaf"
  280. out_elements.append(dict(base, type="sticker", id=None, sticker=sticker,
  281. w=_num(el.get("w"), 5, w * 0.6, w * 0.2),
  282. h=_num(el.get("h"), 5, h * 0.6, w * 0.2)))
  283. bg = result.get("bg")
  284. return {"bg": _hex(bg) if bg else None, "elements": out_elements}
  285. def _spread_texts(items: list) -> list:
  286. """多条文字垂直疏散:按 y 排序后保证相邻两条中心距 ≥ 行高,防 LLM 堆叠。"""
  287. texts = [i for i in items if i.get("type") == "text"]
  288. if len(texts) < 2:
  289. return items
  290. # 中心距需求:字号 mm / 参考面高 150mm → 百分比,乘行高系数
  291. def gap_of(t):
  292. return max(4.0, (t.get("size") or 12) / 150.0 * 100.0 * 1.35 + 1.5)
  293. texts.sort(key=lambda t: t["y"])
  294. for idx in range(1, len(texts)):
  295. prev, cur = texts[idx - 1], texts[idx]
  296. need = max(gap_of(prev), gap_of(cur))
  297. min_y = prev["y"] + need
  298. if cur["y"] < min_y:
  299. cur["y"] = min_y # 先如实下推
  300. if texts[-1]["y"] > 98.0:
  301. # 溢出:整组在 6~98 均匀重排,间距不足时按比例压缩字号
  302. n = len(texts)
  303. step = 92.0 / n
  304. for i, t in enumerate(texts):
  305. t["y"] = round(6.0 + step * (i + 0.5), 1)
  306. need = gap_of(t)
  307. if step < need:
  308. t["size"] = max(3.0, round(t["size"] * step / need, 1))
  309. else:
  310. # 未溢出但个别超界:钳回
  311. for t in texts:
  312. t["y"] = min(t["y"], 98.0)
  313. return items
  314. def sanitize_box(result: dict) -> dict:
  315. """盒面:坐标为面板百分比(0..100);logo/背景装饰转矢量 asset。"""
  316. bg_assets = []
  317. out_items = []
  318. for el in (result.get("items") or [])[:MAX_ELEMENTS]:
  319. t = el.get("type")
  320. base = {
  321. "x": _num(el.get("x"), 2, 98, 50),
  322. "y": _num(el.get("y"), 2, 98, 50),
  323. }
  324. if t == "text":
  325. text = str(el.get("text") or "").strip()[:60]
  326. if not text:
  327. continue
  328. out_items.append(dict(base, type="text", text=text,
  329. size=_num(el.get("size"), 3, 40, 14),
  330. weight=700 if el.get("weight") in (700, "700", "bold") else 400,
  331. color=_hex(el.get("color")),
  332. align=el.get("align") if el.get("align") in ("left", "center", "right") else "center"))
  333. elif t == "logo":
  334. template = el.get("template") if el.get("template") in LOGO_TEMPLATES else "monogram"
  335. color = _hex(el.get("color"), _hex(result.get("color") and _darken_hex(result["color"]) or "#2b2620"))
  336. svg = build_logo_svg(template, str(el.get("text") or "B"), color)
  337. out_items.append(dict(base, type="asset", name="logo",
  338. src=_svg_dataurl(svg), w=_num(el.get("w"), 8, 40, 18)))
  339. elif t == "bgdeco":
  340. style = el.get("style") if el.get("style") in BG_DECO_TEMPLATES else None
  341. if not style:
  342. continue
  343. color = _hex(el.get("color"), _darken_hex(result.get("color") or "#f6f2ea"))
  344. bg_assets.append(dict(type="asset", name="bg-" + style,
  345. src=_svg_dataurl(BG_DECO_TEMPLATES[style](color)),
  346. x=50, y=50, w=100)) # 全幅:渲染时按面宽等比
  347. # 背景装饰垫底(items 顺序即图层,先画在下);非法底色回空串(前端保持原底色)
  348. color = result.get("color")
  349. valid_color = color if (color and HEX_RE.match(str(color))) else ""
  350. out_items = _spread_texts(out_items)
  351. return {"color": valid_color, "items": bg_assets + out_items}
  352. def _darken_hex(hex_color: str, amount: float = 0.45) -> str:
  353. """从底色推导一个深色(背景装饰/logo 默认用色)。"""
  354. h = str(hex_color or "").lstrip("#")
  355. if len(h) != 6 or not all(ch in "0123456789abcdefABCDEF" for ch in h):
  356. return "#2b2620"
  357. rgb = [int(h[i:i + 2], 16) for i in (0, 2, 4)]
  358. dark = [int(v * (1 - amount)) for v in rgb]
  359. return "#%02x%02x%02x" % tuple(dark)
  360. # ---------- 提示词 ----------
  361. def bag_messages(brief: str, w: float, h: float, product: str, context: dict) -> list:
  362. sys_prompt = (
  363. "你是资深包装平面设计师。在 %s x %s mm 的%s印刷面上排版。只输出 JSON,不要解释。"
  364. '格式:{"bg":"#RRGGBB 或 null","elements":[...]},坐标系左上原点,单位 mm。'
  365. "元素类型:text(text,x,y,w,size,weight,align,font[sans|serif|round|mono|hand],color,spacing,lineHeight)、"
  366. "shape(shape[rect|circle|line],x,y,w,h,fill)、"
  367. "sticker(sticker[%s],x,y,w,h,color)。"
  368. "用户可能输入排版指令,也可能输入产品/商业需求描述(如产品类型、卖点、风格、预算、数量)——后者请自行创作适合该产品的整面设计:品牌名可自拟、写品名/卖点/规格/一句 slogan,风格按描述(premium=简约高端留白多,eco=牛皮色系+环保字样)。面上文字语言与用户输入语言一致。禁止拒答、禁止输出解释。"
  369. "每个设计应形成完整品牌感:bg 底色 + 大 sticker 作 logo 图形(叠加小文字可组合成徽标) + 主标题 + 副文案。设计要求:留足出血与安全区(四周 6mm 不放重要内容)、层级清晰、最多 %d 个元素、颜色协调。直接输出紧凑 JSON,不要换行缩进。"
  370. % (w, h, product, "|".join(STICKERS), MAX_ELEMENTS)
  371. )
  372. user_msg = "需求:" + brief
  373. if context and context.get("elements"):
  374. user_msg += "\n\n当前设计 JSON(在此基础上调整,保持未提及内容不变):\n" + json.dumps(
  375. {"bg": context.get("bg"), "elements": context.get("elements")}, ensure_ascii=False)
  376. return [
  377. {"role": "system", "content": sys_prompt},
  378. {"role": "user", "content": user_msg},
  379. ]
  380. def box_messages(brief: str, face: str, context: dict) -> list:
  381. sys_prompt = (
  382. "你是资深包装平面设计师。在纸盒「%s」面排版。只输出 JSON,不要解释。"
  383. '格式:{"color":"#RRGGBB 或 \\"\\"","items":[...]},坐标为面板百分比 0-100(x 向右 y 向下)。'
  384. "元素类型:text(text,x,y,size,weight,align,color)——size 单位 mm(主标题 20-45、副文 8-14、说明 5-8);"
  385. "logo(template[text 首字母缩写],x,y,w,color)——品牌标志,template ∈ monogram|candle|leaf|spark|mountain|banner,w 约 14-24;"
  386. "bgdeco(style,color)——背景装饰(每面至多 1 个),style ∈ border-frame|top-band|bottom-band|both-band|corner-marks,颜色取比底色深的同色系。"
  387. "每个设计应包含:bgdeco 背景装饰 + logo + 主标题 + 副文案,形成完整品牌感版面。"
  388. "用户可能输入排版指令,也可能输入产品/商业需求描述(产品、卖点、风格、预算)——后者请自行创作适合该产品的面设计(品牌名可自拟、写品名/卖点/规格),文字语言与用户输入一致,禁止拒答、禁止输出解释。"
  389. "排版要求:对齐网格、留边距(重要内容距边缘 ≥8%%)、最多 %d 条文字。"
  390. % (face, MAX_ELEMENTS)
  391. )
  392. user_msg = "需求:" + brief
  393. if context and context.get("items"):
  394. user_msg += "\n\n当前设计 JSON(在此基础上调整):\n" + json.dumps(
  395. {"color": context.get("color"), "items": context.get("items")}, ensure_ascii=False)
  396. return [
  397. {"role": "system", "content": sys_prompt},
  398. {"role": "user", "content": user_msg},
  399. ]
  400. BOX_FACES = ["front", "back", "left", "right", "top", "bottom"]
  401. def box_set_messages(brief: str, context: dict) -> list:
  402. sys_prompt = (
  403. "你是资深包装平面设计师。为纸盒外侧 6 面做成套设计。只输出 JSON,不要解释。"
  404. '格式:{"faces":{"front":{"color":"#RRGGBB","items":[...]},"back":{...},"left":{...},"right":{...},"top":{...},"bottom":{...}}}'
  405. "items 元素:text(text,x,y,size,weight,align,color),size 单位 mm;"
  406. "logo(template,x,y,w,color)——template ∈ monogram|candle|leaf|spark|mountain|banner;"
  407. "bgdeco(style,color)——style ∈ border-frame|top-band|bottom-band|both-band|corner-marks,每面至多 1 个。"
  408. "成套规范:整套风格统一(同色系底色 + 同装饰语言 + 同 logo);"
  409. "front=主品牌+品名+主 slogan(最丰富);back=品牌故事/卖点/使用说明;"
  410. "left=logo+净含量/规格;right=简洁装饰或条码位留白说明;top=小 logo 居中;bottom=回收/警示小字。"
  411. "用户可能输入产品/商业需求描述(产品、卖点、风格、预算)——自行创作适合该产品的成套设计,"
  412. "品牌名可自拟,文字语言与用户输入一致,禁止拒答。每面 items ≤ 6。"
  413. )
  414. user_msg = "需求:" + brief
  415. if context and context.get("faces"):
  416. slim = {}
  417. for k, v in (context.get("faces") or {}).items():
  418. slim[k] = {"color": v.get("color"),
  419. "items": [i for i in (v.get("items") or []) if i.get("type") == "text"]}
  420. user_msg += "\n\n当前各面文字设计(在此基础上调整,保持未提及内容不变):\n" + json.dumps(slim, ensure_ascii=False)
  421. return [
  422. {"role": "system", "content": sys_prompt},
  423. {"role": "user", "content": user_msg},
  424. ]
  425. def sanitize_box_set(result: dict) -> dict:
  426. """整套 6 面:逐面复用单面校验逻辑。"""
  427. faces_out = {}
  428. raw_faces = result.get("faces") or {}
  429. for face in BOX_FACES:
  430. f = raw_faces.get(face) or {}
  431. faces_out[face] = sanitize_box({"color": f.get("color"), "items": f.get("items")})
  432. return {"faces": faces_out}
  433. def generate_layout(kind: str, brief: str, context: dict, meta: dict) -> dict:
  434. """调用 LLM 生成/调整排版,返回已校验的结果 dict;结果为空视为失败。"""
  435. if kind == "box" and meta.get("full"):
  436. messages = box_set_messages(brief, context or {})
  437. result = sanitize_box_set(parse_json_content(chat(messages, max_tokens=2500)))
  438. key = "faces"
  439. elif kind == "box":
  440. messages = box_messages(brief, meta.get("face", "front"), context or {})
  441. result = sanitize_box(parse_json_content(chat(messages)))
  442. key = "items"
  443. else:
  444. messages = bag_messages(brief, float(meta.get("w", 140)), float(meta.get("h", 210)),
  445. meta.get("product", "包装袋"), context or {})
  446. result = sanitize_bag(parse_json_content(chat(messages)),
  447. float(meta.get("w", 140)), float(meta.get("h", 210)))
  448. key = "elements"
  449. if key == "faces":
  450. filled = [f for f in result["faces"].values() if (f.get("items") or [])]
  451. if len(filled) < 2:
  452. raise ValueError("AI 返回的成套设计不完整,请换个说法重试")
  453. elif not (result.get(key) or []):
  454. raise ValueError("AI 返回了空排版(模型输出未通过校验),请换个说法重试")
  455. return result