Skip to content

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

merge main into feat/kepu-optimize

yid7f8cec5b891
diff --cc backend/app/services/ark.py
index adceae6,13663d3..7a5eb8e
--- a/backend/app/services/ark.py
+++ b/backend/app/services/ark.py
@@@ -74,15 -39,12 +75,21 @@@ def _raise_seedream_http_error
raise RuntimeError(
"上游 Seedream 账户欠费(AccountOverdueError),生图暂不可用,请联系管理员充值火山方舟账户"
)
+ logger.warning(
+ "出图上游失败 model=%s tokenfree=%s status=%s body=%s",
+ (model or "").strip() or "-",
+ tokenfree,
+ status_code,
+ snippet[:200],
+ )
+ if tokenfree:
+ raise RuntimeError(tokenfree_image_user_error(model=model, status_code=status_code, body=snippet))
+ if "InputTextSensitive" in snippet or "InputTextSensitiveContentDetected" in snippet:
+ raise RuntimeError(
+ "生图文案未通过内容审核(可能含敏感或历史名人相关表述),"
+ "请修改提示词后重试。"
+ f" 详情:{snippet[:240]}"
+ )
raise RuntimeError(f"Seedream error {status_code}: {snippet}")
@@@ -674,29 -593,12 +676,33 @@@ class ArkGateway
shot_no: int | None = None,
size: str | None = None,
model: str | None = None,
+ aspect_ratio: str | None = None,
+ style_ref_urls: list[str] | None = None,
) -> ImageResult:
- # Kie 主流图模型(前台 image_model=kie-*);不走 ARK_MOCK
+ """调用 Seedream 生图。
+
+ 只软化用户正文并保留设定板前缀;InputTextSensitive 时仍用简化三视图重试,
+ 最后一档才缩成「三视图+服装风格」。不做空主体 / CG 厚涂兜底。
+ """
+ from app.services.kie_catalog import get_media_model, resolve_image_model_id
+ from app.services.kie_client import get_kie
+ from app.services.style_lock import split_seedream_subject_style_refs
+
+ resolved = resolve_image_model_id(model)
+ kie_spec = get_media_model(resolved)
+ if kie_spec and kie_spec.provider == "kie" and kie_spec.capability == "image":
+ full_prompt = f"{prompt}。避免:{negative}" if negative else prompt
+ subject_refs, style_refs = split_seedream_subject_style_refs(ref_urls, style_ref_urls)
+ return await get_kie().gen_image(
+ full_prompt,
+ spec=kie_spec,
+ project_id=project_id,
+ shot_no=shot_no,
+ aspect_ratio=aspect_ratio,
+ size=size,
+ ref_urls=[*subject_refs, *style_refs] or None,
+ )
+
if self.mock:
local = await asyncio.to_thread(self._write_mock_image, prompt, size)
# _write_mock_image returns /static/...; publish to OSS when enabled
@@@ -704,98 -606,71 +710,105 @@@
url = storage.publish_local(path) if path and path.exists() else local
return ImageResult(local_url=url, remote_url=None)
+ ark_model = None if resolved in {"", "ark-seedream"} else (model or resolved)
+ from app.services.seedream_text_soften import (
+ compact_seedream_prompt_for_retry,
+ soften_seedream_input_text,
+ style_only_seedream_prompt_for_retry,
+ )
- candidates = [
- self._sanitize_seedream_prompt(prompt),
- self._aggressive_sanitize_seedream(prompt),
- self._generic_scene_prompt(prompt),
- ]
- # de-dupe while preserving order
- seen: set[str] = set()
- prompts: list[str] = []
- for p in candidates:
- p = (p or "").strip()
- if p and p not in seen:
- seen.add(p)
- prompts.append(p)
+ # 只软化用户正文,保留角色/场景/道具结构前缀(三视图等)
+ original = (prompt or "").strip()
+ current = soften_seedream_input_text(original)
+ if current != original:
+ logger.info(
+ "Seedream input softened shot=%s before=%s after=%s",
+ shot_no,
+ len(original),
+ len(current),
+ )
+
+ attempts = [current]
+ for builder in (
+ compact_seedream_prompt_for_retry,
+ style_only_seedream_prompt_for_retry,
+ ):
+ candidate = builder(current)
+ if candidate and candidate not in attempts:
+ attempts.append(candidate)
last_err: Exception | None = None
- for idx, base in enumerate(prompts):
- # 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=ark_model,
- prompt_hash_src=prompt,
- aspect_ratio=aspect_ratio,
- style_ref_urls=style_ref_urls,
- )
- 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:
+ labels = ("softened", "compact", "style_only")
+ for idx, candidate in enumerate(attempts):
+ full_prompt = f"{candidate}。避免:{negative}" if negative else candidate
+ try:
+ return await self._seedream_once(
+ full_prompt,
+ ref_urls,
+ project_id=project_id,
+ shot_no=shot_no,
+ size=size,
- model=model,
++ model=ark_model,
++ aspect_ratio=aspect_ratio,
++ style_ref_urls=style_ref_urls,
+ )
+ except Exception as exc: # noqa: BLE001
+ last_err = exc
+ msg = str(exc)
+ # 仅文本审核可走压缩/风格重试;其它策略/错误直接失败
+ if not self._is_seedream_input_text_sensitive(msg):
+ if self._is_seedream_policy_error(msg):
logger.warning(
- "Seedream policy hit shot=%s attempt=%s; advancing softened candidate",
+ "Seedream policy hit shot=%s; failing without fallback",
shot_no,
- idx + 1,
)
+ raise
+ if idx + 1 < len(attempts):
+ nxt = labels[idx + 1] if idx + 1 < len(labels) else "next"
+ logger.warning(
+ "Seedream InputTextSensitive shot=%s; retrying %s prompt",
+ shot_no,
+ nxt,
+ )
+ continue
+ logger.warning(
+ "Seedream InputTextSensitive shot=%s; retries exhausted",
+ shot_no,
+ )
+ raise
raise RuntimeError(str(last_err) if last_err else "Seedream failed")
+ async def _kie_image_fallback(
+ self,
+ prompt: str,
+ *,
+ project_id: int | None,
+ shot_no: int | None,
+ size: str | None,
+ aspect_ratio: str | None,
+ ref_urls: list[str] | None,
+ ) -> ImageResult | None:
+ """TokenFree 出图挂了且已配 Kie Key 时,改走已验证可用的 nano-banana-2。"""
+ from app.services.kie_catalog import get_media_model
+ from app.services.kie_client import get_kie, resolve_kie_credentials
+
+ key, _ = resolve_kie_credentials()
+ if not key:
+ return None
+ spec = get_media_model("kie-nano-banana-2")
+ if spec is None:
+ return None
+ logger.warning("TokenFree 生图不可用,回退 Kie %s shot=%s", spec.id, shot_no)
+ return await get_kie().gen_image(
+ prompt,
+ spec=spec,
+ project_id=project_id,
+ shot_no=shot_no,
+ aspect_ratio=aspect_ratio,
+ size=size,
+ ref_urls=ref_urls,
+ )
+
async def _seedream_once(
self,
full_prompt: str,
@@@ -804,97 -679,32 +817,97 @@@
project_id: int | None,
shot_no: int | None,
size: str | None,
- prompt_hash_src: str,
model: str | None = None,
+ aspect_ratio: str | None = None,
+ style_ref_urls: list[str] | None = None,
) -> ImageResult:
+ """单次 Seedream 请求并落盘(文件名含 uuid,避免重生成覆盖)。"""
route = self._resolve_ark_route("image", model)
upstream_model = route.upstream_model if route else ((model or "").strip() or self.settings.model_image)
- body: dict[str, Any] = {
- "model": upstream_model,
- "prompt": full_prompt,
- "size": size or self.settings.ark_image_size,
- "response_format": "url",
- "watermark": False,
- }
- from app.services.style_lock import seedream_ref_urls
+ from app.services.drama.seedream_options import (
+ clamp_seedream_pixel_size,
+ is_seedream_pro_model,
+ )
- refs = seedream_ref_urls(*(ref_urls or []))
- if refs:
- body["image"] = refs if len(refs) > 1 else refs[0]
+ resolved_size = size or self.settings.ark_image_size
+ if is_seedream_pro_model(upstream_model):
+ # Pro:3K/4K 档位非法;超大 WxH 等比钳到 4624220
+ tier = str(resolved_size or "").strip().upper()
+ if tier in {"3K", "4K"}:
+ resolved_size = "2K"
+ else:
+ resolved_size = clamp_seedream_pixel_size(str(resolved_size))
+ from app.services.style_lock import split_seedream_subject_style_refs
+
+ subject_refs, style_refs = split_seedream_subject_style_refs(ref_urls, style_ref_urls)
+ refs = [*subject_refs, *style_refs]
+ channel_id = (route.channel_id if route else "") or ""
+ base = (route.base_url if route and route.base_url else self.settings.ark_base_url) or ""
+ on_tokenfree = uses_tokenfree_image(base_url=base, channel_id=channel_id)
+ chosen = tokenfree_working_image_model(upstream_model) if on_tokenfree else upstream_model
+ if on_tokenfree:
+ if chosen != (upstream_model or "").strip():
+ logger.warning("TokenFree 将 %s 改走 %s,避免 Seedream task_protocol_error", upstream_model, chosen)
+ path = "/responses"
+ body = build_tokenfree_image_body(
+ model=chosen,
+ prompt=full_prompt,
+ size=str(resolved_size or ""),
+ ref_urls=subject_refs,
+ style_ref_urls=style_refs,
+ )
+ else:
+ path = "/images/generations"
+ body = {
+ "model": upstream_model,
+ "prompt": full_prompt,
+ "size": resolved_size,
+ "response_format": "url",
+ "watermark": False,
+ }
+ if refs:
+ body["image"] = refs if len(refs) > 1 else refs[0]
async with httpx.AsyncClient(timeout=180.0) as client:
- resp = await client.post(
- self._route_url("/images/generations", route),
- headers=self._route_headers(route),
- json=body,
- )
- if resp.status_code >= 400:
- _raise_seedream_http_error(resp.status_code, resp.text)
+ async def _post():
+ # 单次上游 POST,限流重试由外层包住
+ return await client.post(
+ self._route_url(path, route),
+ headers=self._route_headers(route),
+ json=body,
+ )
+
+ if on_tokenfree:
+ async with tokenfree_image_slot():
+ resp = await post_until_not_rate_limited(_post)
+ else:
+ resp = await _post()
+ if resp.status_code >= 400 or is_tokenfree_retryable_image_error(
+ status_code=resp.status_code, body=resp.text
+ ):
+ if on_tokenfree and tokenfree_image_channel_dead(
+ status_code=resp.status_code, body=resp.text
+ ):
+ try:
+ fallback = await self._kie_image_fallback(
+ full_prompt,
+ project_id=project_id,
+ shot_no=shot_no,
+ size=str(resolved_size or ""),
+ aspect_ratio=aspect_ratio,
+ ref_urls=refs,
+ )
+ except Exception as exc: # noqa: BLE001
+ logger.warning("Kie 出图回退失败 shot=%s: %s", shot_no, exc)
+ fallback = None
+ if fallback is not None:
+ return fallback
+ _raise_seedream_http_error(
+ resp.status_code,
+ resp.text,
+ model=chosen,
+ tokenfree=on_tokenfree,
+ )
data = resp.json()
usage_parsed = parse_usage_dict(data)
@@@ -915,19 -723,11 +928,14 @@@
raise RuntimeError(f"Seedream missing url: {json.dumps(data)[:500]}")
dest_dir = storage.project_dir(project_id or 0)
- # 每次生成唯一文件名,避免覆盖同路径导致前端/CDN 缓存不刷新
- name = (
- f"shot_{(shot_no or 0):03d}_"
- f"{hashlib.md5(prompt_hash_src.encode()).hexdigest()[:8]}_"
- f"{int(time.time() * 1000) % 10_000_000:07d}.png"
- )
+ name = f"shot_{(shot_no or 0):03d}_{uuid.uuid4().hex[:12]}.png"
dest = dest_dir / name
- await storage.download_to(remote, dest)
+ dl_headers = None
+ if is_tokenfree_image_url(remote) or is_tokenfree_content_url(remote):
+ dl_headers = {"Authorization": f"Bearer {self._ark_api_key()}"}
+ await storage.download_to(remote, dest, headers=dl_headers)
return ImageResult(
- local_url=storage.publish_local(dest),
+ local_url=storage.publish_local(dest, sync=True),
remote_url=remote,
total_tokens=int(usage_parsed.get("total_tokens") or 0),
prompt_tokens=int(usage_parsed.get("prompt_tokens") or 0),
diff --cc backend/app/services/tasks/executor.py
index 99afed9,10a5d8a..21d744e
--- a/backend/app/services/tasks/executor.py
+++ b/backend/app/services/tasks/executor.py
@@@ -108,10 -108,10 +108,10 @@@ async def execute_task_run(task_id: int
if isinstance(result, dict) and result.get("cancelled"):
await _mark_cancelled(db, task)
return
- # handler 以 {ok:false} 返回时须记失败,否则前端只能看到空的「生图失败」
+ # handler 返回 ok:False 时必须失败收敛(勿当成 succeeded)
if isinstance(result, dict) and result.get("ok") is False:
- err_text = str(result.get("error") or "").strip() or "任务执行失败"
- err_msg = str(result.get("error") or "任务执行失败")[:500]
- await _fail_task(db, task, RuntimeError(err_msg))
++ err_text = str(result.get("error") or "任务执行失败").strip()[:500] or "任务执行失败"
+ await _fail_task(db, task, RuntimeError(err_text))
return
await _complete_task(db, task, result or {"ok": True})
except asyncio.CancelledError:
diff --cc docs/releases/README.md
index 9c9db5a,2981493..d1a0aab
--- a/docs/releases/README.md
+++ b/docs/releases/README.md
@@@ -33,7 -33,11 +33,12 @@@
| 日期 | 摘要 | 文件 |
|------|------|------|
+| 2026-09-12 | 保存分镜新建镜 MissingGreenlet;分镜保护顺序 + 挂回 #609 成片;杭州热修 | [2026-09-12.md](./2026-09-12.md) |
+ | 2026-09-11 | OSS 缓存仍用已禁用旧 Key;杭州热修 | [2026-09-11.md](./2026-09-11.md) |
+ | 2026-09-11 | main 全量 + 轮换 OSS Key;杭州 | [2026-09-11.md](./2026-09-11.md) |
+ | 2026-09-09 | Seedream 文本审核软化;杭州热修 | [2026-09-09.md](./2026-09-09.md) |
+ | 2026-09-09 | 角色/场景/道具设定板前缀;杭州热修 | [2026-09-09.md](./2026-09-09.md) |
+ | 2026-09-09 | Seedream 生图去兜底 + 失败上浮;杭州全量 | [2026-09-09.md](./2026-09-09.md) |
| 2026-09-08 | Seedance 视频文案策略 CG 重试;杭州热修 | [2026-09-08.md](./2026-09-08.md) |
| 2026-09-07 | 科普分阶段计费;杭州全量 | [2026-09-07.md](./2026-09-07.md) |
| 2026-09-07 | 分镜重试上限 + Seedream CG 策略重试;杭州全量 | [2026-09-07.md](./2026-09-07.md) |
diff --cc frontend/src/lib/dramaImageGenQueue.ts
index 9dc3b55,cbba253..6d158f9
--- a/frontend/src/lib/dramaImageGenQueue.ts
+++ b/frontend/src/lib/dramaImageGenQueue.ts
@@@ -176,15 -173,8 +176,16 @@@ function readGenerationStatus(asset: Dr
return String(gen?.status || '')
}
-// 轮询直到资产生图结束;generating 时回调以便 UI 切到「生成中」
-// 必须先判 failed/cancelled:重试失败时旧 url/cover 仍在,不能当成功
+// 资产当前预览 URL
+function assetMediaUrl(asset: DramaAsset): string {
+ return String(asset.url || asset.cover || '').trim()
+}
+
+/**
+ * 轮询直到本次生图真正结束。
+ * 有旧图时必须见到 queued/generating,或 URL 相对基线变化,避免秒回旧图当成功。
++ * 必须先判 failed/cancelled:重试失败时旧 url/cover 仍在,不能当成功。
+ */
async function waitForAssetImage(
projectId: number,
assetId: number,
@@@ -200,39 -185,15 +201,39 @@@
const list = await dramaApi.listAssets(projectId)
const latest = list.find((a) => a.id === assetId)
if (!latest) throw new Error('资产不存在')
+
const status = readGenerationStatus(latest)
+ const currentUrl = assetMediaUrl(latest)
onRemoteStatus?.(status)
+
+ if (status === 'queued' || status === 'generating') {
+ sawInFlight = true
+ if (currentUrl !== lastNotifiedUrl) {
+ lastNotifiedUrl = currentUrl
+ onAssetUpdate?.(latest)
+ }
+ await new Promise((r) => setTimeout(r, POLL_INTERVAL_MS))
+ continue
+ }
+
- if (status === 'failed') {
+ if (status === 'failed' || status === 'cancelled') {
const gen = (latest.params || {}).generation as { error?: string } | undefined
- throw new Error(String(gen?.error || (status === 'cancelled' ? '生图已取消' : '生图失败')))
+ const raw = String(gen?.error || '').trim()
- throw new Error(raw || '生图失败')
++ throw new Error(raw || (status === 'cancelled' ? '生图已取消' : '生图失败'))
}
- if (status === 'done' && (latest.url || latest.cover)) {
+
+ const urlChanged = Boolean(currentUrl) && currentUrl !== baselineUrl
+ const finishedFresh =
+ status === 'done' &&
+ Boolean(currentUrl) &&
+ (sawInFlight || urlChanged || !baselineUrl)
+
+ if (finishedFresh) {
+ onAssetUpdate?.(latest)
return latest
}
+
+ // 仍是旧图且未进入过 in-flight:继续等(POST 后状态可能尚未可见)
await new Promise((r) => setTimeout(r, POLL_INTERVAL_MS))
}
throw new Error('生图超时,请刷新后重试')