Skip to content

PRINTFILM: AI short-video marketing and AI short-drama creation platform

fix(drama): treat fragment retry limit as internal-only and soften Seedream policy hits

yi2c09e4fcc8e1
diff --git a/backend/app/api/drama/episodes.py b/backend/app/api/drama/episodes.py
index 9aefd5f..024756b 100644
--- a/backend/app/api/drama/episodes.py
+++ b/backend/app/api/drama/episodes.py
@@ -485,6 +485,8 @@ async def generate_episode(
queued_at = datetime.now(UTC).isoformat()
for f in idle_frags:
params = dict(f.params or {})
+ # 用户主动点生成:清零内部重试计数(上限只约束同一次任务内的自动重试)
+ params.pop("generation_attempts", None)
params["generation"] = {"status": "queued", "queued_at": queued_at, "message": "已入队"}
f.params = params
diff --git a/backend/app/services/ark.py b/backend/app/services/ark.py
index 648bc07..9cd5341 100644
--- a/backend/app/services/ark.py
+++ b/backend/app/services/ark.py
@@ -132,6 +132,12 @@ _SEEDREAM_STRIP_PROPER: re.Pattern[str] = re.compile(
r"猎鹰一号|猎鹰\s*9|猎鹰重型|猎鹰|马斯克|埃隆|特斯拉)"
)
+# 真人 / 写实人脸审核命中后追加的画风引导,压低照片级真人触发概率
+_SEEDREAM_CG_STYLE = (
+ "用CG厚涂、游戏CG的风格打造的画面,色彩层次丰富,质感细腻逼真,"
+ "真实的光影效果赋予画面生动感"
+)
+
@dataclass
class ShotPlan:
@@ -609,28 +615,45 @@ class ArkGateway:
last_err: Exception | None = None
for idx, base in enumerate(prompts):
- full_prompt = f"{base}。避免:{negative}" if negative else base
- try:
- return await self._seedream_once(
- full_prompt,
- ref_urls,
- project_id=project_id,
- shot_no=shot_no,
- size=size,
- model=model,
- prompt_hash_src=prompt,
- )
- except Exception as exc: # noqa: BLE001
- last_err = exc
- msg = str(exc)
- if "PolicyViolation" in msg or "SensitiveContent" in msg:
- logger.warning(
- "Seedream policy hit shot=%s attempt=%s; retrying softened prompt",
- shot_no,
- idx + 1,
+ # queue 同档提示词;文案/输出策略命中后再追加 CG 厚涂变体重试
+ queue = [base]
+ qi = 0
+ while qi < len(queue):
+ current = queue[qi]
+ qi += 1
+ full_prompt = f"{current}。避免:{negative}" if negative else current
+ try:
+ return await self._seedream_once(
+ full_prompt,
+ ref_urls,
+ project_id=project_id,
+ shot_no=shot_no,
+ size=size,
+ model=model,
+ prompt_hash_src=prompt,
)
- continue
- raise
+ except Exception as exc: # noqa: BLE001
+ last_err = exc
+ msg = str(exc)
+ # 参考图真人等输入侧拦截:改文案无效,直接失败
+ if self._is_seedream_input_privacy_error(msg):
+ raise
+ if not self._is_seedream_policy_error(msg):
+ raise
+ cg = self._with_seedream_cg_style(current)
+ if cg != current and cg not in queue:
+ logger.warning(
+ "Seedream policy hit shot=%s attempt=%s; retrying with CG style",
+ shot_no,
+ idx + 1,
+ )
+ queue.append(cg)
+ else:
+ logger.warning(
+ "Seedream policy hit shot=%s attempt=%s; advancing softened candidate",
+ shot_no,
+ idx + 1,
+ )
raise RuntimeError(str(last_err) if last_err else "Seedream failed")
async def _seedream_once(
@@ -698,6 +721,37 @@ class ArkGateway:
upstream_cost_fen=upstream_cost_fen,
)
+ @staticmethod
+ def _is_seedream_input_privacy_error(msg: str) -> bool:
+ """参考图 / 输入侧真人隐私拦截(改文案无效)。"""
+ text = msg or ""
+ return any(
+ k in text
+ for k in ("PrivacyInformation", "InputImageSensitive")
+ )
+
+ @staticmethod
+ def _is_seedream_policy_error(msg: str) -> bool:
+ """文案或输出内容策略拦截(可走脱敏 / CG 重试)。"""
+ text = msg or ""
+ if ArkGateway._is_seedream_input_privacy_error(text):
+ return False
+ return (
+ "PolicyViolation" in text
+ or "SensitiveContent" in text
+ or "OutputImageSensitive" in text
+ )
+
+ @staticmethod
+ def _with_seedream_cg_style(prompt: str) -> str:
+ """在提示词末尾追加 CG 厚涂风格(已含则原样返回)。"""
+ base = (prompt or "").strip()
+ if not base:
+ return _SEEDREAM_CG_STYLE
+ if _SEEDREAM_CG_STYLE in base:
+ return base
+ return f"{base}。{_SEEDREAM_CG_STYLE}"
+
@staticmethod
def _sanitize_seedream_prompt(prompt: str) -> str:
out = prompt or ""
@@ -730,12 +784,14 @@ class ArkGateway:
"绘本",
"写意",
"概念插画",
+ "CG厚涂",
+ "游戏CG",
):
if key in (prompt or ""):
style_bits.append(key)
style = ",".join(style_bits) + "," if style_bits else "统一插画风格,"
return (
- f"{style}高质量画面,竖屏构图,主体偏中下,顶部留白,"
+ f"{style}{_SEEDREAM_CG_STYLE},竖屏构图,主体偏中下,顶部留白,"
"同一画风贯穿,禁止写实摄影与真人脸,无文字水印"
)
diff --git a/backend/app/services/drama/generation.py b/backend/app/services/drama/generation.py
index 06355c6..007a5ea 100644
--- a/backend/app/services/drama/generation.py
+++ b/backend/app/services/drama/generation.py
@@ -196,7 +196,11 @@ def fragment_generation_status(fragment: DramaEpisodeFragment) -> dict[str, Any]
# 是否为「重试超限」包装句(不含真实根因)
def _is_retry_limit_error(text: str) -> bool:
t = (text or "").strip()
- return bool(t) and ("重试超过" in t or "超过重试" in t)
+ return bool(t) and (
+ "重试超过" in t
+ or "超过重试" in t
+ or "内部自动重试超过" in t
+ )
# 组装失败态 generation:保留 root_error,避免被重试超限覆盖
@@ -225,17 +229,33 @@ def build_failed_generation_params(
display = msg
if _is_retry_limit_error(msg) and root and not _is_retry_limit_error(root):
- display = f"{msg}:{root[:400]}"
+ # 已拼过「上限:root」则不再二次拼接(_fail_task 会再走一遍)
+ root_snip = root[:400]
+ if msg.rstrip().endswith(root_snip) or f":{root[:80]}" in msg:
+ display = msg
+ else:
+ display = f"{msg}:{root_snip}"
out: dict[str, Any] = {
"status": "failed",
"error": display[:500],
"root_error": root[:500],
}
+ # attempts / attempt_limit:显式入参优先,否则保留 prev
if attempts is not None:
out["attempts"] = attempts
+ elif prev.get("attempts") is not None:
+ try:
+ out["attempts"] = int(prev.get("attempts"))
+ except (TypeError, ValueError):
+ pass
if attempt_limit is not None:
out["attempt_limit"] = attempt_limit
+ elif prev.get("attempt_limit") is not None:
+ try:
+ out["attempt_limit"] = int(prev.get("attempt_limit"))
+ except (TypeError, ValueError):
+ pass
return out
diff --git a/backend/app/services/drama/jobs.py b/backend/app/services/drama/jobs.py
index cfa1634..a2e52fc 100644
--- a/backend/app/services/drama/jobs.py
+++ b/backend/app/services/drama/jobs.py
@@ -758,23 +758,31 @@ async def submit_fragment_video_task(task: TaskRun) -> dict[str, Any]:
return {"ok": False, "cancelled": True}
gen = frag.params.get("generation") if isinstance(frag.params, dict) else None
+ # 仅统计「同一次任务」内 prepare 被重新拉起的次数(中断重入等),
+ # 用户再次点生成 / 任务重试会清零 generation_attempts。
persisted_attempts = int((frag.params or {}).get("generation_attempts") or 0)
prev_attempts = persisted_attempts
if isinstance(gen, dict):
- prev_attempts = max(prev_attempts, int(gen.get("attempts") or 0))
+ # queued 态不应继承上次失败的 attempts 展示值
+ if str(gen.get("status") or "") in {"queued", "idle", "cancelled", "done"}:
+ prev_attempts = persisted_attempts
+ else:
+ prev_attempts = max(prev_attempts, int(gen.get("attempts") or 0))
max_attempts = max(1, int(get_settings().drama_fragment_max_attempts or 3))
attempts = prev_attempts + 1 if nio_phase == "prepare" else int(payload.get("generation_attempts") or prev_attempts + 1)
if nio_phase == "prepare" and attempts > max_attempts:
params = dict(frag.params or {})
+ # raise 用纯超限文案;展示拼接交给 build_failed_generation_params / _fail_task
+ limit_msg = f"分镜内部自动重试超过上限({max_attempts} 次)"
params["generation"] = build_failed_generation_params(
gen if isinstance(gen, dict) else None,
- f"分镜重试超过上限({max_attempts} 次)",
+ limit_msg,
attempts=prev_attempts,
attempt_limit=max_attempts,
)
frag.params = params
await db.commit()
- raise RuntimeError(params["generation"]["error"])
+ raise RuntimeError(limit_msg)
if nio_phase == "prepare":
params = dict(frag.params or {})
diff --git a/backend/app/services/tasks/executor.py b/backend/app/services/tasks/executor.py
index 5d959a8..0fcc295 100644
--- a/backend/app/services/tasks/executor.py
+++ b/backend/app/services/tasks/executor.py
@@ -171,14 +171,17 @@ async def _fail_task(db, task, exc: Exception) -> None:
)
if task.fragment_id:
from app.models_drama import DramaEpisodeFragment
+ from app.services.drama.generation import build_failed_generation_params
frag = await db.get(DramaEpisodeFragment, int(task.fragment_id))
if frag:
params = dict(frag.params or {})
- params["generation"] = {
- "status": "failed",
- "error": task.error_message,
- }
+ prev_gen = params.get("generation") if isinstance(params.get("generation"), dict) else None
+ # 保留 root_error(避免「内部重试超限」盖掉真人审核等真实原因)
+ params["generation"] = build_failed_generation_params(
+ prev_gen if isinstance(prev_gen, dict) else None,
+ task.error_message or str(exc),
+ )
frag.params = params
if task.domain == "kepu" and task.project_id:
from app.models import Project, ProjectStatus
diff --git a/backend/app/services/tasks/service.py b/backend/app/services/tasks/service.py
index 199e3f3..c111ed1 100644
--- a/backend/app/services/tasks/service.py
+++ b/backend/app/services/tasks/service.py
@@ -920,9 +920,29 @@ async def retry_task_for_user(db: AsyncSession, user: User, task_id: int) -> Tas
if not frag_ids:
raise ValueError(_STALE_FRAGMENT_REASON)
for frag_id in frag_ids:
- if await db.get(DramaEpisodeFragment, frag_id) is None:
+ frag = await db.get(DramaEpisodeFragment, frag_id)
+ if frag is None:
raise ValueError(_STALE_FRAGMENT_REASON)
- payload = dict(task.payload or {}) if isinstance(task.payload, dict) else None
+ # 用户/后台点重试:清零内部重试计数,并从 prepare 阶段重跑
+ params = dict(frag.params or {})
+ params.pop("generation_attempts", None)
+ params["generation"] = {
+ "status": "queued",
+ "queued_at": datetime.now(UTC).isoformat(),
+ "message": "任务重试已入队",
+ }
+ frag.params = params
+ payload = dict(task.payload or {}) if isinstance(task.payload, dict) else {}
+ # 分镜视频重试不沿用旧 nio 阶段与内部 attempt,避免被「超过上限」直接拦住
+ if task.domain == "drama" and task.task_type == "fragment_video":
+ for key in (
+ "nio_phase",
+ "generation_attempts",
+ "attempt_limit",
+ "prepared",
+ "provider_task_id",
+ ):
+ payload.pop(key, None)
body = TaskCreateRequest(
domain=task.domain,
task_type=task.task_type,
@@ -933,7 +953,7 @@ async def retry_task_for_user(db: AsyncSession, user: User, task_id: int) -> Tas
provider_task_id=None,
cancelable=task.cancelable,
scheduled_at=datetime.now(UTC),
- payload=payload,
+ payload=payload or None,
result_payload=None,
project_id=task.project_id,
drama_project_id=task.drama_project_id,
diff --git a/docs/releases/2026-09-07.md b/docs/releases/2026-09-07.md
new file mode 100644
index 0000000..14b8526
--- /dev/null
+++ b/docs/releases/2026-09-07.md
@@ -0,0 +1,16 @@
+## 2026-09-07 · 分镜重试上限修正 + Seedream CG 策略重试
+
+- **操作者**:Agent
+- **方式**:全量发布(`deploy_kepu_8136.py`)
+- **范围**:api / web
+- **变更摘要**:
+ - 分镜 `generation_attempts` 3 次上限改为只约束同一次任务内自动重试;用户点生成 / 任务重试会清零计数,不再误拦
+ - 超限失败文案幂等拼接,保留真实 `root_error`(如参考图 PrivacyInformation),避免「上限:root:root」
+ - Seedream 文案/输出策略命中时追加 CG 厚涂风格重试;参考图 `PrivacyInformation` / `InputImageSensitive` 不空跑
+ - 前端错误提示同步说明:超限不是禁止再点生成
+- **验证**:
+ - [ ] `https://www.printfilm.com/api/health`
+ - [ ] 前台首页 200
+ - [ ] (如有)admin 首页 200
+- **备注 / 回滚**:回滚下列文件后重启 API,并重发前端 dist:
+ `episodes.py` / `ark.py` / `generation.py` / `jobs.py` / `executor.py` / `service.py` / `dramaGenError.ts`
diff --git a/frontend/src/lib/dramaGenError.ts b/frontend/src/lib/dramaGenError.ts
index d77ebf2..bf3e803 100644
--- a/frontend/src/lib/dramaGenError.ts
+++ b/frontend/src/lib/dramaGenError.ts
@@ -115,12 +115,12 @@ export function formatDramaGenError(raw: string | null | undefined): DramaGenErr
}
}
- if (/重试超过上限|超过重试上限/.test(text)) {
+ if (/重试超过上限|超过重试上限|内部自动重试超过上限/.test(text)) {
return {
title: '多次生成仍失败',
message: text,
suggestion:
- '常见原因是参考图触发真人肖像审核。请打开左侧资产,为相关角色/场景更换或重新生成形象后再点生成。',
+ '这是同一次任务内的自动重试耗尽,不是禁止你再点生成。请根据真实原因(常见是参考图真人审核)改素材或文案后,再重新点生成。',
}
}