# -*- coding: utf-8 -*-
"""AI 交互式排版服务。
- LLM:OpenAI 兼容 chat/completions(环境变量 PL_AI_BASE_URL / PL_AI_API_KEY / PL_AI_MODEL,
默认智谱开放平台 glm-4-flash;未配置 key 时接口返回 503,前端提示)
- 用量:users.ai_quota / ai_used(后台可改额度),每次成功调用扣 1 并记录 ai_calls
- 交互:前端把上一轮生成的 elements 作为 context 传入即可多轮调整("文字再大一点")
- 输出严格校验(元素数、坐标、颜色格式),异常数据自动剔除,保证画布不炸
"""
import json
import os
import re
import time
import urllib.request
import cache
from db import db, get_setting, set_setting
ENV_BASE_URL = os.environ.get("PL_AI_BASE_URL", "https://open.bigmodel.cn/api/paas/v4")
ENV_API_KEY = os.environ.get("PL_AI_API_KEY", "")
ENV_MODEL = os.environ.get("PL_AI_MODEL", "glm-4-flash")
MAX_ELEMENTS = 12
HEX_RE = re.compile(r"^#[0-9a-fA-F]{6}$")
CONFIG_KEYS = ("ai_base_url", "ai_api_key", "ai_model")
def get_config() -> dict:
"""AI 配置:后台设置(settings 表,Redis 缓存)优先,环境变量兜底。"""
cached = cache.get_json("pl:ai-config")
if cached is not None:
return cached
cfg = {
"baseUrl": get_setting("ai_base_url") or ENV_BASE_URL,
"apiKey": get_setting("ai_api_key") or ENV_API_KEY,
"model": get_setting("ai_model") or ENV_MODEL,
"source": {
"baseUrl": "db" if get_setting("ai_base_url") else ("env" if ENV_API_KEY or True else "default"),
},
}
cache.set_json("pl:ai-config", cfg, 60)
return cfg
def save_config(base_url: str = None, api_key: str = None, model: str = None):
"""后台保存配置;api_key 传空串/None 表示不修改。保存后立即失效缓存。"""
if base_url is not None and base_url.strip():
set_setting("ai_base_url", base_url.strip()[:300])
if api_key: # 空串 = 保持不变(避免误清空)
set_setting("ai_api_key", api_key.strip()[:300])
if model is not None and model.strip():
set_setting("ai_model", model.strip()[:100])
cache.delete("pl:ai-config")
STICKERS = ["leaf", "coffeeBean", "cup", "star", "sparkle", "heart", "wave",
"sun", "flower", "paw", "arrow", "mountain", "wheat", "bolt"]
# ---------- logo / 背景装饰(盒面矢量模板,输出 asset 项) ----------
def _svg_dataurl(svg):
import base64
return "data:image/svg+xml;base64," + base64.b64encode(svg.encode()).decode()
def build_logo_svg(template, text, color):
"""按模板生成 logo SVG(viewBox 200x200,居中)。"""
t = str(text or "")[:6]
c = _hex(color, "#2b2620")
tpl = template if template in LOGO_TEMPLATES else "monogram"
return LOGO_TEMPLATES[tpl](t, c)
def _esc_xml(s):
return (str(s or "").replace("&", "&").replace("<", "<").replace(">", ">"))
LOGO_TEMPLATES = {
"monogram": lambda t, c: (
'' % (c, c, c, _esc_xml(t))),
"candle": lambda t, c: (
'' % (c, c, c, c, _esc_xml(t))),
"leaf": lambda t, c: (
'' % (c, c, c, _esc_xml(t))),
"spark": lambda t, c: (
'' % (c, c, _esc_xml(t))),
"mountain": lambda t, c: (
'' % (c, c, c, _esc_xml(t))),
"banner": lambda t, c: (
'' % (c, c, c, _esc_xml(t))),
}
BG_DECO_TEMPLATES = {
# 全幅装饰框(细线双框)
"border-frame": lambda c: (
'' % (c, c)),
# 顶部色带
"top-band": lambda c: (
'' % (c, c)),
# 底部色带
"bottom-band": lambda c: (
'' % (c, c)),
# 上下呼应带
"both-band": lambda c: (
'' % (c, c)),
# 四角刻线
"corner-marks": lambda c: (
'' % c),
}
def configured() -> bool:
return bool(get_config()["apiKey"])
# ---------- 用量 ----------
def quota_of(user_id: int) -> dict:
with db() as cur:
cur.execute("SELECT ai_quota, ai_used FROM users WHERE id = %s", (user_id,))
r = cur.fetchone()
return {"quota": r["ai_quota"], "used": r["ai_used"]} if r else {"quota": 0, "used": 0}
def consume(user_id: int, ok: bool, kind: str, brief: str, detail: str = ""):
with db() as cur:
if ok:
cur.execute("UPDATE users SET ai_used = ai_used + 1 WHERE id = %s", (user_id,))
cur.execute(
"INSERT INTO ai_calls (user_id, kind, brief, ok, detail, created_at) VALUES (%s,%s,%s,%s,%s,%s)",
(user_id, kind, brief[:500], 1 if ok else 0, detail[:200], int(time.time())),
)
# ---------- LLM ----------
def chat(messages: list, timeout: int = 180, max_tokens: int = 3000) -> str:
cfg = get_config()
body = json.dumps({
"model": cfg["model"],
"messages": messages,
"temperature": 0.7,
"max_tokens": max_tokens,
}).encode()
req = urllib.request.Request(
cfg["baseUrl"].rstrip("/") + "/chat/completions",
data=body,
headers={"Content-Type": "application/json", "Authorization": "Bearer " + cfg["apiKey"]},
method="POST",
)
with urllib.request.urlopen(req, timeout=timeout) as resp:
data = json.loads(resp.read())
return data["choices"][0]["message"]["content"]
def _salvage_truncated_json(text: str):
"""LLM 输出被 max_tokens 截断时,截到最后一个完整值并补全闭合容器。"""
stack = []
in_str = False
esc = False
last_safe = -1 # 最后一个"完整值结束"位置(元素 } 或 ] 或字符串结束后的 , 之前)
i = 0
n = len(text)
while i < n:
ch = text[i]
if in_str:
if esc:
esc = False
elif ch == '\\':
esc = True
elif ch == '"':
in_str = False
else:
if ch == '"':
in_str = True
elif ch in '[{':
stack.append(ch)
elif ch in ']}':
if stack:
stack.pop()
last_safe = i # 完整闭合的容器末尾
elif ch == ',' and not stack:
pass
i += 1
if last_safe < 0:
raise ValueError("no complete value in truncated output")
# 另一种截断:数组里最后一个完整对象后没有逗号——回退到该对象的 }
cut = text.rfind('}', 0, last_safe + 1)
if cut < 0:
cut = last_safe
candidate = text[:cut + 1].rstrip().rstrip(',').rstrip()
# 重新计数未闭合栈(含 pop),逆序补全
stack = []
in_str = False
esc = False
for ch in candidate:
if in_str:
if esc:
esc = False
elif ch == '\\':
esc = True
elif ch == '"':
in_str = False
else:
if ch == '"':
in_str = True
elif ch in '[{':
stack.append(ch)
elif ch in ']}':
if stack:
stack.pop()
closer = {'[': ']', '{': '}'}
return json.loads(candidate + ''.join(closer[c] for c in reversed(stack)))
def parse_json_content(content: str) -> dict:
"""剥掉 ```json 围栏后解析;截断输出自动补全修复。"""
content = content.strip()
m = re.search(r"```(?:json)?\s*([\s\S]*?)```", content)
if m:
content = m.group(1).strip()
start = content.find("{")
if start >= 0:
content = content[start:]
try:
end = content.rfind("}")
if end > 0:
return json.loads(content[:end + 1])
return json.loads(content)
except ValueError:
return _salvage_truncated_json(content)
# ---------- 校验 ----------
def _hex(v, fallback="#1a1a1a"):
v = str(v or "")
return v if HEX_RE.match(v) else fallback
def _num(v, lo, hi, default):
try:
return max(lo, min(hi, float(v)))
except (TypeError, ValueError):
return default
def sanitize_bag(result: dict, w: float, h: float) -> dict:
"""袋画布:坐标 mm(0..w/0..h),与 studio.js 元素结构一致。"""
out_elements = []
for el in (result.get("elements") or [])[:MAX_ELEMENTS]:
t = el.get("type")
base = {
"x": _num(el.get("x"), 0, w, w / 2),
"y": _num(el.get("y"), 0, h, h / 2),
"color": _hex(el.get("color")),
"rotation": _num(el.get("rotation"), -180, 180, 0),
}
if t == "text":
text = str(el.get("text") or "").strip()[:60]
if not text:
continue
out_elements.append(dict(base, type="text", id=None, text=text,
w=_num(el.get("w"), 10, w, w * 0.7),
size=_num(el.get("size"), 4, min(w, h) * 0.35, 12),
weight=700 if el.get("weight") in (700, "700", "bold") else 400,
align=el.get("align") if el.get("align") in ("left", "center", "right") else "center",
font=el.get("font") if el.get("font") in ("sans", "serif", "round", "mono", "hand") else "sans",
spacing=_num(el.get("spacing"), -5, 40, 0),
lineHeight=_num(el.get("lineHeight"), 1.0, 2.2, 1.35)))
elif t == "shape":
shape = el.get("shape") if el.get("shape") in ("rect", "circle", "line") else "rect"
out_elements.append(dict(base, type="shape", id=None, shape=shape,
w=_num(el.get("w"), 2, w, w * 0.4),
h=_num(el.get("h"), 2, h, h * 0.2),
fill=_hex(el.get("fill"), "#00000000"[:7]),
strokeWidth=_num(el.get("strokeWidth"), 0.2, 4, 0.6)))
elif t == "sticker":
sticker = el.get("sticker") if el.get("sticker") in STICKERS else "leaf"
out_elements.append(dict(base, type="sticker", id=None, sticker=sticker,
w=_num(el.get("w"), 5, w * 0.6, w * 0.2),
h=_num(el.get("h"), 5, h * 0.6, w * 0.2)))
bg = result.get("bg")
return {"bg": _hex(bg) if bg else None, "elements": out_elements}
def _spread_texts(items: list) -> list:
"""多条文字垂直疏散:按 y 排序后保证相邻两条中心距 ≥ 行高,防 LLM 堆叠。"""
texts = [i for i in items if i.get("type") == "text"]
if len(texts) < 2:
return items
# 中心距需求:字号 mm / 参考面高 150mm → 百分比,乘行高系数
def gap_of(t):
return max(4.0, (t.get("size") or 12) / 150.0 * 100.0 * 1.35 + 1.5)
texts.sort(key=lambda t: t["y"])
for idx in range(1, len(texts)):
prev, cur = texts[idx - 1], texts[idx]
need = max(gap_of(prev), gap_of(cur))
min_y = prev["y"] + need
if cur["y"] < min_y:
cur["y"] = min_y # 先如实下推
if texts[-1]["y"] > 98.0:
# 溢出:整组在 6~98 均匀重排,间距不足时按比例压缩字号
n = len(texts)
step = 92.0 / n
for i, t in enumerate(texts):
t["y"] = round(6.0 + step * (i + 0.5), 1)
need = gap_of(t)
if step < need:
t["size"] = max(3.0, round(t["size"] * step / need, 1))
else:
# 未溢出但个别超界:钳回
for t in texts:
t["y"] = min(t["y"], 98.0)
return items
def sanitize_box(result: dict) -> dict:
"""盒面:坐标为面板百分比(0..100);logo/背景装饰转矢量 asset。"""
bg_assets = []
out_items = []
for el in (result.get("items") or [])[:MAX_ELEMENTS]:
t = el.get("type")
base = {
"x": _num(el.get("x"), 2, 98, 50),
"y": _num(el.get("y"), 2, 98, 50),
}
if t == "text":
text = str(el.get("text") or "").strip()[:60]
if not text:
continue
out_items.append(dict(base, type="text", text=text,
size=_num(el.get("size"), 3, 40, 14),
weight=700 if el.get("weight") in (700, "700", "bold") else 400,
color=_hex(el.get("color")),
align=el.get("align") if el.get("align") in ("left", "center", "right") else "center"))
elif t == "logo":
template = el.get("template") if el.get("template") in LOGO_TEMPLATES else "monogram"
color = _hex(el.get("color"), _hex(result.get("color") and _darken_hex(result["color"]) or "#2b2620"))
svg = build_logo_svg(template, str(el.get("text") or "B"), color)
out_items.append(dict(base, type="asset", name="logo",
src=_svg_dataurl(svg), w=_num(el.get("w"), 8, 40, 18)))
elif t == "bgdeco":
style = el.get("style") if el.get("style") in BG_DECO_TEMPLATES else None
if not style:
continue
color = _hex(el.get("color"), _darken_hex(result.get("color") or "#f6f2ea"))
bg_assets.append(dict(type="asset", name="bg-" + style,
src=_svg_dataurl(BG_DECO_TEMPLATES[style](color)),
x=50, y=50, w=100)) # 全幅:渲染时按面宽等比
# 背景装饰垫底(items 顺序即图层,先画在下);非法底色回空串(前端保持原底色)
color = result.get("color")
valid_color = color if (color and HEX_RE.match(str(color))) else ""
out_items = _spread_texts(out_items)
return {"color": valid_color, "items": bg_assets + out_items}
def _darken_hex(hex_color: str, amount: float = 0.45) -> str:
"""从底色推导一个深色(背景装饰/logo 默认用色)。"""
h = str(hex_color or "").lstrip("#")
if len(h) != 6 or not all(ch in "0123456789abcdefABCDEF" for ch in h):
return "#2b2620"
rgb = [int(h[i:i + 2], 16) for i in (0, 2, 4)]
dark = [int(v * (1 - amount)) for v in rgb]
return "#%02x%02x%02x" % tuple(dark)
# ---------- 提示词 ----------
def bag_messages(brief: str, w: float, h: float, product: str, context: dict) -> list:
sys_prompt = (
"你是资深包装平面设计师。在 %s x %s mm 的%s印刷面上排版。只输出 JSON,不要解释。"
'格式:{"bg":"#RRGGBB 或 null","elements":[...]},坐标系左上原点,单位 mm。'
"元素类型:text(text,x,y,w,size,weight,align,font[sans|serif|round|mono|hand],color,spacing,lineHeight)、"
"shape(shape[rect|circle|line],x,y,w,h,fill)、"
"sticker(sticker[%s],x,y,w,h,color)。"
"用户可能输入排版指令,也可能输入产品/商业需求描述(如产品类型、卖点、风格、预算、数量)——后者请自行创作适合该产品的整面设计:品牌名可自拟、写品名/卖点/规格/一句 slogan,风格按描述(premium=简约高端留白多,eco=牛皮色系+环保字样)。面上文字语言与用户输入语言一致。禁止拒答、禁止输出解释。"
"每个设计应形成完整品牌感:bg 底色 + 大 sticker 作 logo 图形(叠加小文字可组合成徽标) + 主标题 + 副文案。设计要求:留足出血与安全区(四周 6mm 不放重要内容)、层级清晰、最多 %d 个元素、颜色协调。直接输出紧凑 JSON,不要换行缩进。"
% (w, h, product, "|".join(STICKERS), MAX_ELEMENTS)
)
user_msg = "需求:" + brief
if context and context.get("elements"):
user_msg += "\n\n当前设计 JSON(在此基础上调整,保持未提及内容不变):\n" + json.dumps(
{"bg": context.get("bg"), "elements": context.get("elements")}, ensure_ascii=False)
return [
{"role": "system", "content": sys_prompt},
{"role": "user", "content": user_msg},
]
def box_messages(brief: str, face: str, context: dict) -> list:
sys_prompt = (
"你是资深包装平面设计师。在纸盒「%s」面排版。只输出 JSON,不要解释。"
'格式:{"color":"#RRGGBB 或 \\"\\"","items":[...]},坐标为面板百分比 0-100(x 向右 y 向下)。'
"元素类型:text(text,x,y,size,weight,align,color)——size 单位 mm(主标题 20-45、副文 8-14、说明 5-8);"
"logo(template[text 首字母缩写],x,y,w,color)——品牌标志,template ∈ monogram|candle|leaf|spark|mountain|banner,w 约 14-24;"
"bgdeco(style,color)——背景装饰(每面至多 1 个),style ∈ border-frame|top-band|bottom-band|both-band|corner-marks,颜色取比底色深的同色系。"
"每个设计应包含:bgdeco 背景装饰 + logo + 主标题 + 副文案,形成完整品牌感版面。"
"用户可能输入排版指令,也可能输入产品/商业需求描述(产品、卖点、风格、预算)——后者请自行创作适合该产品的面设计(品牌名可自拟、写品名/卖点/规格),文字语言与用户输入一致,禁止拒答、禁止输出解释。"
"排版要求:对齐网格、留边距(重要内容距边缘 ≥8%%)、最多 %d 条文字。"
% (face, MAX_ELEMENTS)
)
user_msg = "需求:" + brief
if context and context.get("items"):
user_msg += "\n\n当前设计 JSON(在此基础上调整):\n" + json.dumps(
{"color": context.get("color"), "items": context.get("items")}, ensure_ascii=False)
return [
{"role": "system", "content": sys_prompt},
{"role": "user", "content": user_msg},
]
BOX_FACES = ["front", "back", "left", "right", "top", "bottom"]
def box_set_messages(brief: str, context: dict) -> list:
sys_prompt = (
"你是资深包装平面设计师。为纸盒外侧 6 面做成套设计。只输出 JSON,不要解释。"
'格式:{"faces":{"front":{"color":"#RRGGBB","items":[...]},"back":{...},"left":{...},"right":{...},"top":{...},"bottom":{...}}}'
"items 元素:text(text,x,y,size,weight,align,color),size 单位 mm;"
"logo(template,x,y,w,color)——template ∈ monogram|candle|leaf|spark|mountain|banner;"
"bgdeco(style,color)——style ∈ border-frame|top-band|bottom-band|both-band|corner-marks,每面至多 1 个。"
"成套规范:整套风格统一(同色系底色 + 同装饰语言 + 同 logo);"
"front=主品牌+品名+主 slogan(最丰富);back=品牌故事/卖点/使用说明;"
"left=logo+净含量/规格;right=简洁装饰或条码位留白说明;top=小 logo 居中;bottom=回收/警示小字。"
"用户可能输入产品/商业需求描述(产品、卖点、风格、预算)——自行创作适合该产品的成套设计,"
"品牌名可自拟,文字语言与用户输入一致,禁止拒答。每面 items ≤ 6。"
)
user_msg = "需求:" + brief
if context and context.get("faces"):
slim = {}
for k, v in (context.get("faces") or {}).items():
slim[k] = {"color": v.get("color"),
"items": [i for i in (v.get("items") or []) if i.get("type") == "text"]}
user_msg += "\n\n当前各面文字设计(在此基础上调整,保持未提及内容不变):\n" + json.dumps(slim, ensure_ascii=False)
return [
{"role": "system", "content": sys_prompt},
{"role": "user", "content": user_msg},
]
def sanitize_box_set(result: dict) -> dict:
"""整套 6 面:逐面复用单面校验逻辑。"""
faces_out = {}
raw_faces = result.get("faces") or {}
for face in BOX_FACES:
f = raw_faces.get(face) or {}
faces_out[face] = sanitize_box({"color": f.get("color"), "items": f.get("items")})
return {"faces": faces_out}
def generate_layout(kind: str, brief: str, context: dict, meta: dict) -> dict:
"""调用 LLM 生成/调整排版,返回已校验的结果 dict;结果为空视为失败。"""
if kind == "box" and meta.get("full"):
messages = box_set_messages(brief, context or {})
result = sanitize_box_set(parse_json_content(chat(messages, max_tokens=2500)))
key = "faces"
elif kind == "box":
messages = box_messages(brief, meta.get("face", "front"), context or {})
result = sanitize_box(parse_json_content(chat(messages)))
key = "items"
else:
messages = bag_messages(brief, float(meta.get("w", 140)), float(meta.get("h", 210)),
meta.get("product", "包装袋"), context or {})
result = sanitize_bag(parse_json_content(chat(messages)),
float(meta.get("w", 140)), float(meta.get("h", 210)))
key = "elements"
if key == "faces":
filled = [f for f in result["faces"].values() if (f.get("items") or [])]
if len(filled) < 2:
raise ValueError("AI 返回的成套设计不完整,请换个说法重试")
elif not (result.get(key) or []):
raise ValueError("AI 返回了空排版(模型输出未通过校验),请换个说法重试")
return result