A8多套打包+M4归档+R5多图:存量功能备份
A8 多套交付包(packaging_task.py): - 修复交付包只打第1条混乱note的bug,按ImageCandidate.strategy分A/B/C组 - 每组生独立note_0N夹(6图+文案.txt),同seq留最新去重,老数据兼容 - task74端到端验:3套各6图,独立agent7项交叉验证全过 M4 归档(tasks.py/exports.py/前端): - list_tasks加date_from/date_to/product_id筛选+product_name批量填(防N+1) - 新增exports.py:产品JSON导出+标杆CSV导出(UTF-8 BOM) - 前端HistoryFilters日期/产品筛选+产品列+打回原因红banner - response.py加raise_param_error;独立agent验A1/A2/A9通过 R5 产品多图(product_images.py/020迁移/前端): - product_images表+5端点(上传/列/改场景/设主图/删图) - 生图按ROLE_SCENE_PREFERENCE选对应场景图,回落primary - 前端ProductImageManager多图画廊 R6 账号config拆页(settings/): - 配置页按角色拆/settings(运营+组长+admin)+/config(仅admin) - Key只显末4位不显余额(守红线) 核销表对齐真实代码状态:D1改稿框/M7裂变/E12评图分纠偏为已完成(曾漏回写) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -131,6 +131,38 @@ angle(本条角度标签)/ coverTitle(封面大字≤10字)/ imageBrief
|
||||
硬性格式:只输出JSON,不要markdown代码块,字符串内用中文引号「」。"""
|
||||
|
||||
|
||||
# ── 第2环标杆爆款配方 → 文案 prompt(借方法层结构,禁抄竞品原话)──────────────
|
||||
_BM_DIM_LABELS: list[tuple[str, str]] = [
|
||||
("title_formula", "标题公式"),
|
||||
("opening_hook", "开篇钩子"),
|
||||
("content_structure", "内容结构"),
|
||||
("selling_point_style", "卖点表达风格"),
|
||||
("emotion_tone", "情绪基调"),
|
||||
("topic_tags", "话题标签思路"),
|
||||
]
|
||||
|
||||
|
||||
def _build_benchmark_block(refs: list[dict]) -> str:
|
||||
"""把标杆 8维配方渲染成 prompt 块。只借'方法结构',硬约束禁抄竞品品牌/功效原话。"""
|
||||
if not refs:
|
||||
return ""
|
||||
lines: list[str] = []
|
||||
for i, f in enumerate(refs[:3], 1): # 最多取3条标杆,避免prompt膨胀
|
||||
dims = [f"{label}=「{str(f.get(key, '')).strip()}」"
|
||||
for key, label in _BM_DIM_LABELS if str(f.get(key, "")).strip()]
|
||||
if dims:
|
||||
lines.append(f" 标杆{i}:" + ";".join(dims))
|
||||
if not lines:
|
||||
return ""
|
||||
body = "\n".join(lines)
|
||||
return (
|
||||
"\n【对标爆款配方参考(只借方法层结构,绝不照抄)】\n"
|
||||
f"{body}\n"
|
||||
"硬性约束:仅参考上面的标题套路/开篇方式/结构节奏/情绪基调来组织本产品文案;"
|
||||
"禁止照搬竞品品牌名、产品名、功效原话或具体数字;产品信息一律以本产品为准。"
|
||||
)
|
||||
|
||||
|
||||
def build_prompt(product: dict, count: int, extra_rules: str = "") -> str:
|
||||
"""
|
||||
组装文案生成 user_prompt。
|
||||
@@ -153,6 +185,7 @@ def build_prompt(product: dict, count: int, extra_rules: str = "") -> str:
|
||||
|
||||
angle_hint = f"文案角度要覆盖:{'、'.join(angles)}(每条用不同角度)。" if angles else ""
|
||||
brand_rule = f"每条正文和标题中植入品牌词「{brand_kw}」一次(自然融入,不生硬)。" if brand_kw else ""
|
||||
benchmark_block = _build_benchmark_block(product.get("benchmark_refs") or [])
|
||||
|
||||
lines = [
|
||||
f"产品:{name}",
|
||||
@@ -161,6 +194,7 @@ def build_prompt(product: dict, count: int, extra_rules: str = "") -> str:
|
||||
angle_hint,
|
||||
brand_rule,
|
||||
custom,
|
||||
benchmark_block,
|
||||
f"\n【Q1随机变量池·每条身份/起因/小缺点各不相同,严格按下方分配使用】",
|
||||
combos_text,
|
||||
extra_rules,
|
||||
|
||||
@@ -70,6 +70,23 @@ PAGE_ROLES = [
|
||||
]
|
||||
PAGE_ROLE_MAP = {r["role"]: r for r in PAGE_ROLES}
|
||||
|
||||
# ── R5多图:分镜role → 优先产品图场景(scene) 偏好表 ──────────
|
||||
# 生图时按分镜 role 选该场景的产品图当参考;取不到回落主图(primary)。
|
||||
# scene 取值见 enums.ProductImageScene:primary/scene/texture/ingredient/model
|
||||
ROLE_SCENE_PREFERENCE = {
|
||||
"hook": ["scene", "primary"], # 封面:真实生活场景优先
|
||||
"pain_scene": ["scene", "primary"], # 痛点共鸣:使用前情境
|
||||
"product_closeup": ["primary"], # 单品特写:白底主图
|
||||
"ingredient": ["ingredient", "primary"], # 成分拆解:成分/包装细节
|
||||
"texture": ["texture", "primary"], # 质地展示:质地特写
|
||||
"applied_proof": ["model", "scene", "primary"], # 上脸:上脸图/场景
|
||||
"social_proof": ["scene", "primary"], # 社交背书:场景
|
||||
"closer": ["primary"], # 促单收尾:主图
|
||||
"scenario": ["scene", "primary"],
|
||||
"tutorial": ["model", "scene", "primary"],
|
||||
}
|
||||
|
||||
|
||||
# ── 生图风格预设(扒 image.js STYLE_PROMPTS:26-29)──────────
|
||||
# 按 style 参数选小红书风格调性,注入 base_prompt 的"视觉风格"行
|
||||
STYLE_PROMPTS = {
|
||||
|
||||
@@ -14,13 +14,36 @@ import logging
|
||||
import os
|
||||
from typing import Any, Protocol
|
||||
|
||||
from .constants import IMAGE_RETRY_ATTEMPTS, IMAGE_RETRY_BACKOFF_BASE, IMAGE_SIZE_DEFAULT
|
||||
from .constants import IMAGE_RETRY_ATTEMPTS, IMAGE_RETRY_BACKOFF_BASE, IMAGE_SIZE_DEFAULT, ROLE_SCENE_PREFERENCE
|
||||
from .image_scorer import score_image
|
||||
from .storyboard import plan_image_set, sanitize_text
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _pick_reference_for_role(
|
||||
role: str,
|
||||
images_by_scene: dict[str, list[bytes]] | None,
|
||||
fallback: list[bytes] | None,
|
||||
) -> tuple[list[bytes] | None, str]:
|
||||
"""R5多图:按分镜 role 选该场景的产品图。取不到回落主图。
|
||||
|
||||
返回 (参考图bytes列表, 命中scene标签用于日志)。
|
||||
"""
|
||||
if images_by_scene:
|
||||
for scene in ROLE_SCENE_PREFERENCE.get(role, ["primary"]):
|
||||
imgs = images_by_scene.get(scene)
|
||||
if imgs:
|
||||
return imgs, scene
|
||||
# 偏好全落空:用任意可用图兜底(仍优先 primary)
|
||||
if images_by_scene.get("primary"):
|
||||
return images_by_scene["primary"], "primary"
|
||||
for scene, imgs in images_by_scene.items():
|
||||
if imgs:
|
||||
return imgs, f"{scene}(兜底)"
|
||||
return fallback, "fallback"
|
||||
|
||||
|
||||
class ImageClient(Protocol):
|
||||
"""worker 注入的图片生成客户端协议(隔离 key 细节)"""
|
||||
async def gpt_edits(
|
||||
@@ -129,12 +152,18 @@ async def generate_storyboard_images(
|
||||
strategy: str | None = None,
|
||||
target_role: str | None = None,
|
||||
custom_prompt: str | None = None,
|
||||
images_by_scene: dict[str, list[bytes]] | None = None,
|
||||
flywheel_fragment: str | None = None,
|
||||
) -> list[dict]:
|
||||
"""
|
||||
按 storyboard 逐张生图(asyncio.gather 并发),返回每张结果列表。
|
||||
strategy: None=默认叙事,'A'/'B'/'C'=三套正交叙事策略
|
||||
target_role: 非空时只生成该 role 那一张(R2 单张重生)
|
||||
custom_prompt: 非空时追加到每张 per_prompt 末尾(R2 人工提示词)
|
||||
images_by_scene: R5多图,{scene: [bytes]},按分镜 role 选对应场景图;
|
||||
为空则全分镜共用 reference_images(向后兼容)。
|
||||
flywheel_fragment: R7 飞轮偏好片段(最近选图/打回真实信号聚合),注入图片
|
||||
排版偏好;仅影响文字角度/版式取向,绝不改瓶身(合规红线)。
|
||||
每项:{role, name, image_bytes, error}
|
||||
"""
|
||||
plan = plan_image_set(note, product, image_count, analysis, strategy=strategy)
|
||||
@@ -169,8 +198,20 @@ async def generate_storyboard_images(
|
||||
# R2 人工提示词:追加到末尾权重最高,但不覆盖前面合规/真实约束
|
||||
if custom_prompt:
|
||||
per_prompt += f"\n运营补充要求(在不违反上述合规与真实约束前提下尽量满足):{sanitize_text(custom_prompt, 200)}。"
|
||||
# R7 飞轮偏好:仅作用于文字角度/版式取向参考,绝不改瓶身(合规+真实红线)
|
||||
if flywheel_fragment:
|
||||
per_prompt += (
|
||||
f"\n历史偏好参考(仅影响标题文字角度与排版取向,不得据此改动产品瓶身):"
|
||||
f"{sanitize_text(flywheel_fragment, 300)}。"
|
||||
)
|
||||
try:
|
||||
img_bytes = await generate_one_image(client, per_prompt, reference_images)
|
||||
# R5多图:按本张分镜 role 选对应场景产品图;无多图则共用 reference_images
|
||||
ref_for_item, _scene_hit = _pick_reference_for_role(
|
||||
item["role"], images_by_scene, reference_images
|
||||
)
|
||||
if images_by_scene:
|
||||
logger.info("分镜 %s 选用产品图场景=%s", item["role"], _scene_hit)
|
||||
img_bytes = await generate_one_image(client, per_prompt, ref_for_item)
|
||||
# 注:gpt-image-2 渲染中文偶发错别字(约1/6)。vision/OCR 文字校验闸门实测
|
||||
# 不可靠(漏报形近字+幻觉误伤品牌词),倩倩姐2026-06-16拍板先撤,纯生图,
|
||||
# 错别字作已知问题记录,后续迭代再处理。详见记忆 clover-image-text-check-shelved。
|
||||
|
||||
@@ -52,7 +52,8 @@ def aggregate_preference_context(
|
||||
weight = int(e.get("signal_weight", 1))
|
||||
|
||||
# text_edit(改稿)是最强真实信号,角度按权重计入(倩倩姐2026-06-16拍板)
|
||||
if sig_type in ("text_select", "approve", "text_edit") and angle:
|
||||
# image_select(选图)按套别叙事角度计入,让选图偏好真正闭环回生图(R7断点2)
|
||||
if sig_type in ("text_select", "approve", "text_edit", "image_select") and angle:
|
||||
angle_counts[angle] += weight
|
||||
elif sig_type == "reject_with_reason":
|
||||
reason = str(e.get("reason") or "").strip()
|
||||
|
||||
@@ -60,6 +60,19 @@ def retry_fission_note_images(
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("裂变补图参考图读取失败,无参考图模式: %s", e)
|
||||
|
||||
# R5多图:补图也按场景分组,重生失败分镜时选对应场景图
|
||||
images_by_scene: dict[str, list[bytes]] = {}
|
||||
for _im in (product.get("images") or []):
|
||||
_p = _resolve_image_path(_im.get("path", ""))
|
||||
if _p and os.path.isfile(_p):
|
||||
try:
|
||||
with open(_p, "rb") as _f:
|
||||
images_by_scene.setdefault(_im.get("scene") or "primary", []).append(_f.read())
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
if reference_images and not images_by_scene.get("primary"):
|
||||
images_by_scene.setdefault("primary", []).extend(reference_images)
|
||||
|
||||
upload_base = get_settings().UPLOAD_ABS_ROOT
|
||||
img_dir = os.path.join(upload_base, str(ft.workspace_id), f"fission_{ft.id}", str(fn.seq))
|
||||
os.makedirs(img_dir, exist_ok=True)
|
||||
@@ -73,6 +86,7 @@ def retry_fission_note_images(
|
||||
client=clients, note=note, product=product,
|
||||
image_count=image_count, reference_images=reference_images,
|
||||
target_role=role,
|
||||
images_by_scene=images_by_scene or None,
|
||||
))
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.error("裂变补图 seq=%s role=%s 仍失败: %s", fn.seq, role, exc)
|
||||
|
||||
@@ -39,6 +39,19 @@ def generate_fission_images(
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("裂变参考图读取失败,无参考图模式: %s", e)
|
||||
|
||||
# R5多图:裂变同样按场景分组,生图按分镜 role 选对应图
|
||||
images_by_scene: dict[str, list[bytes]] = {}
|
||||
for _im in (product.get("images") or []):
|
||||
_p = _resolve_image_path(_im.get("path", ""))
|
||||
if _p and os.path.isfile(_p):
|
||||
try:
|
||||
with open(_p, "rb") as _f:
|
||||
images_by_scene.setdefault(_im.get("scene") or "primary", []).append(_f.read())
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
if reference_images and not images_by_scene.get("primary"):
|
||||
images_by_scene.setdefault("primary", []).extend(reference_images)
|
||||
|
||||
upload_base = get_settings().UPLOAD_ABS_ROOT
|
||||
for nid in note_ids:
|
||||
fn = db.query(FissionNote).filter(FissionNote.id == nid).first()
|
||||
@@ -52,6 +65,7 @@ def generate_fission_images(
|
||||
results = asyncio.run(generate_storyboard_images(
|
||||
client=clients, note=note, product=product,
|
||||
image_count=image_count, reference_images=reference_images,
|
||||
images_by_scene=images_by_scene or None,
|
||||
))
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.error("裂变套 seq=%s 生图失败: %s", fn.seq, exc)
|
||||
|
||||
@@ -8,10 +8,10 @@ preference_aggregator:查最近50条 → 最常选角度 + 打回原因近3条
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import desc, func
|
||||
from sqlalchemy import desc
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.constants.enums import SIGNAL_WEIGHTS, DataOwnership, SignalType
|
||||
from app.constants.enums import SIGNAL_WEIGHTS, DataOwnership
|
||||
from app.middleware.workspace_guard import CurrentUser
|
||||
from app.models.flywheel import PreferenceEvent
|
||||
from app.models.task import GenerationTask
|
||||
@@ -20,8 +20,6 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
# 实时聚合窗口:最近50条事件
|
||||
_AGGREGATION_WINDOW = 50
|
||||
# 冷启动阈值:不足5条信号用产品档案冷启动
|
||||
_COLD_START_THRESHOLD = 5
|
||||
|
||||
|
||||
def record_signal(
|
||||
@@ -32,12 +30,14 @@ def record_signal(
|
||||
candidate_id: int | None = None,
|
||||
angle_label: str | None = None,
|
||||
reason: str | None = None,
|
||||
signal_meta: str | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
写入飞轮信号。
|
||||
workspace_id + product_id 都必须有(基石C + 按产品分开学)。
|
||||
signal_weight 用枚举默认值,北哥可校准。
|
||||
data_ownership 默认 client_data(选择行为归客户)。
|
||||
signal_meta:JSON 扩展(如选图存 strategy),不参与角度聚合主逻辑。
|
||||
"""
|
||||
weight = SIGNAL_WEIGHTS.get(signal_type, 0)
|
||||
event = PreferenceEvent(
|
||||
@@ -50,6 +50,7 @@ def record_signal(
|
||||
candidate_id=candidate_id,
|
||||
angle_label=angle_label,
|
||||
reason=reason,
|
||||
signal_meta=signal_meta,
|
||||
data_ownership=DataOwnership.CLIENT_DATA,
|
||||
)
|
||||
try:
|
||||
@@ -69,14 +70,17 @@ def record_signal(
|
||||
|
||||
|
||||
def get_preference_context(
|
||||
db: Session, workspace_id: int, product_id: int
|
||||
db: Session, workspace_id: int, product_id: int,
|
||||
product_dict: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
实时聚合偏好上下文(最近50条 events)。
|
||||
返回:recent_preference摘要 + reject_reasons近3条 + injected_count。
|
||||
不足5条 → 冷启动提示(产品档案兜底,由 AIE prompt 层读 products.custom_prompt)。
|
||||
实时聚合偏好上下文(最近50条 events)供前端展示。
|
||||
R7断点3:统一口径——委托给生产链同一个 aggregate_preference_context(权重口径),
|
||||
消除"前端展示按次数/生成按权重"的口径分裂(说一套做一套)。
|
||||
按 workspace_id + product_id 严格过滤(不串数据,基石C)。
|
||||
"""
|
||||
from app.services.ai_engine.preference_aggregator import aggregate_preference_context
|
||||
|
||||
recent = (
|
||||
db.query(PreferenceEvent)
|
||||
.filter(
|
||||
@@ -87,35 +91,18 @@ def get_preference_context(
|
||||
.limit(_AGGREGATION_WINDOW)
|
||||
.all()
|
||||
)
|
||||
|
||||
if len(recent) < _COLD_START_THRESHOLD:
|
||||
return {
|
||||
"recent_preference": "信号不足,使用产品档案基线(冷启动)",
|
||||
"reject_reasons": [],
|
||||
"injected_count": len(recent),
|
||||
}
|
||||
|
||||
# 统计最常被选中的角度(text_edit 改稿=最强真实信号,按权重计入,倩倩姐2026-06-16)
|
||||
angle_counts: dict[str, int] = {}
|
||||
for ev in recent:
|
||||
if ev.signal_type in (SignalType.TEXT_SELECT, SignalType.APPROVE, SignalType.TEXT_EDIT) and ev.angle_label:
|
||||
angle_counts[ev.angle_label] = angle_counts.get(ev.angle_label, 0) + 1
|
||||
|
||||
top_angles = sorted(angle_counts.items(), key=lambda x: x[1], reverse=True)[:3]
|
||||
if top_angles:
|
||||
pref_desc = ";".join(f"{a}(已选{c}次)" for a, c in top_angles)
|
||||
preference_summary = f"最近偏好:{pref_desc}"
|
||||
else:
|
||||
preference_summary = "暂无明显角度偏好"
|
||||
|
||||
# 取最近3条打回原因原文(不做 AI 归纳,契约§3)
|
||||
reject_reasons = [
|
||||
ev.reason for ev in recent
|
||||
if ev.signal_type == SignalType.REJECT_WITH_REASON and ev.reason
|
||||
][:3]
|
||||
|
||||
events_dicts = [
|
||||
{"signal_type": e.signal_type, "workspace_id": e.workspace_id,
|
||||
"product_id": e.product_id, "angle_label": e.angle_label or "",
|
||||
"signal_weight": e.signal_weight, "reason": e.reason or ""}
|
||||
for e in recent
|
||||
]
|
||||
ctx = aggregate_preference_context(
|
||||
events_dicts, product_dict or {}, workspace_id, product_id
|
||||
)
|
||||
# 前端展示不需要 prompt_fragment(注入用),剥掉只回摘要+原因+计数
|
||||
return {
|
||||
"recent_preference": preference_summary,
|
||||
"reject_reasons": reject_reasons,
|
||||
"injected_count": len(recent),
|
||||
"recent_preference": ctx.get("recent_preference", ""),
|
||||
"reject_reasons": ctx.get("reject_reasons", []),
|
||||
"injected_count": ctx.get("injected_count", 0),
|
||||
}
|
||||
|
||||
@@ -30,6 +30,28 @@ def _check_user_has_key(db: Session, user_id: int, workspace_id: int) -> None:
|
||||
raise_business("尚未配置 API Key,请先在设置中录入")
|
||||
|
||||
|
||||
def _check_concurrency_limit(db: Session, user_id: int, workspace_id: int) -> None:
|
||||
"""
|
||||
校验该用户未完成任务数未超并发上限(红线=5,可配置)。
|
||||
只算 pending/generating(真占 worker),挑选/审核态不计。超限引导稍后再试。
|
||||
"""
|
||||
from app.core.config import get_settings
|
||||
from app.constants.enums import TaskStatus
|
||||
|
||||
limit = get_settings().MAX_CONCURRENT_TASKS_PER_USER
|
||||
running = (
|
||||
db.query(GenerationTask)
|
||||
.filter(
|
||||
GenerationTask.operator_id == user_id,
|
||||
GenerationTask.workspace_id == workspace_id,
|
||||
GenerationTask.status.in_([TaskStatus.PENDING.value, TaskStatus.GENERATING.value]),
|
||||
)
|
||||
.count()
|
||||
)
|
||||
if running >= limit:
|
||||
raise_business(f"您有 {running} 个任务正在生成,已达并发上限 {limit} 个,请等待完成后再发起")
|
||||
|
||||
|
||||
def create_generation_task(
|
||||
db: Session,
|
||||
current_user: CurrentUser,
|
||||
@@ -42,6 +64,9 @@ def create_generation_task(
|
||||
if body.track == "ai":
|
||||
# 轨A:先检查有没有 key
|
||||
_check_user_has_key(db, current_user.user_id, current_user.workspace_id)
|
||||
# 并发上限:只算正在消耗生成资源的任务(pending/generating),
|
||||
# 已生成完等挑选/审核的不占 worker。红线=每用户5个(可配置)。
|
||||
_check_concurrency_limit(db, current_user.user_id, current_user.workspace_id)
|
||||
|
||||
# 禁降级铁律:本次产品入镜(need_product_image=True)时,产品必须已上传参考图,
|
||||
# 否则拒绝建任务(不允许降级纯文生图,防产品包装跑偏/过抽检失败)。
|
||||
@@ -57,6 +82,11 @@ def create_generation_task(
|
||||
if not (product.image_path or "").strip():
|
||||
raise_business("该产品未上传参考图,无法生成产品入镜内容;请先到产品库上传产品图,或关闭「产品入镜」开关")
|
||||
|
||||
# 第2环:关联标杆笔记ID存库(JSON list)。pipeline 据此读 features_json 注入文案 prompt。
|
||||
import json
|
||||
_bids = getattr(body, "benchmark_ids", None) or []
|
||||
benchmark_ids_json = json.dumps([int(i) for i in _bids]) if _bids else None
|
||||
|
||||
task = GenerationTask(
|
||||
workspace_id=current_user.workspace_id,
|
||||
product_id=body.product_id,
|
||||
@@ -66,6 +96,7 @@ def create_generation_task(
|
||||
image_count=body.image_count,
|
||||
track=body.track,
|
||||
need_product_image=need_img,
|
||||
benchmark_ids=benchmark_ids_json,
|
||||
status="pending",
|
||||
)
|
||||
db.add(task)
|
||||
|
||||
Reference in New Issue
Block a user