From cd0797886d16fbdb8589c2e3edc34db0b11c39d7 Mon Sep 17 00:00:00 2001 From: xiaoxia Date: Sat, 3 Oct 2026 14:42:52 +0800 Subject: [PATCH] =?UTF-8?q?fix(viral-video)=20P0/P1:=20Seedance=E6=A8=A1?= =?UTF-8?q?=E5=9E=8BID=E6=98=A0=E5=B0=84+=E5=BE=88=E8=BF=91=E5=85=A8?= =?UTF-8?q?=E5=B1=80=E6=9B=BF=E6=8D=A2+=E5=A4=B1=E8=B4=A5=E7=8A=B6?= =?UTF-8?q?=E6=80=81=E5=BC=BA=E8=90=BD=E5=BA=93?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit P0 Seedance模型404: - ai_client 新增 VIRAL_VIDEO_MODEL_ID_MAP 和 _resolve_video_model_id() - 内部 pricing key (seedance-2.5/seedance-2.0) 映射到方舟真实模型 ID (doubao-seedance-2-5-260628/doubao-seedance-2-0-250628) - 已完整模型ID(doubao-*/ep-*)直接透传,未识别别名回落到 settings.doubao_video_model - 之前直接把 'seedance-2.5' 传给方舟导致 InvalidEndpointOrModel.NotFound 404 P1 render失败状态未落库: - _mark_failed_and_notify 加 session 失效 fallback:原 session 因异常 rollback 时, 自动开新 SessionLocal 重新标记 job 为 failed,确保状态一定落库,前端不会无限转圈 - 失败日志补上实际模型名,便于排查 P1 很近错别字替换不全: - 新增 _replace_henjin_everywhere() 递归遍历 copy_result 所有字符串字段替换 - 覆盖 overview.theme/scene_and_lighting/voiceover_script/final_copy/shots.*.scene_and_dialogue/action_details/audio_bgm/深层嵌套 - 替换后再次 json.dumps 全局扫描是否还有'很近',有则视为不合格触发重试 全量单测 16407 passed。 --- apps/worker/worker_app/tasks/viral_video.py | 72 +++++++++++++++------ packages/shared/ai_client.py | 43 +++++++++++- 2 files changed, 92 insertions(+), 23 deletions(-) diff --git a/apps/worker/worker_app/tasks/viral_video.py b/apps/worker/worker_app/tasks/viral_video.py index 01a77a4fb..d45b3b310 100644 --- a/apps/worker/worker_app/tasks/viral_video.py +++ b/apps/worker/worker_app/tasks/viral_video.py @@ -728,6 +728,23 @@ def _safe_json_loads(raw: str | dict | list | None): return None + +def _replace_henjin_everywhere(obj: Any) -> Any: + """递归遍历 copy_result 里所有字符串值,把'很近'替换成'最近'。 + 覆盖 overview.theme、scene_and_lighting、voiceover_script、 + shots[].scene_and_dialogue/action_details/audio_bgm 等所有字段。 + """ + if isinstance(obj, str): + if "很近" in obj: + return obj.replace("很近", "最近") + return obj + if isinstance(obj, list): + return [_replace_henjin_everywhere(x) for x in obj] + if isinstance(obj, dict): + return {k: _replace_henjin_everywhere(v) for k, v in obj.items()} + return obj + + def _fallback_script(job: ViralVideoJob) -> dict: """脚本生成失败时的兜底脚本(极简但可用)。""" dur = max(5, min(30, int(getattr(job, "duration", 15) or 15))) @@ -920,19 +937,14 @@ def _step_script_generation(job: ViralVideoJob, intent: dict, image_analysis: di voiceover_len = len(voiceover) shots_cnt = len((normalized or {}).get("shots") or []) # 判定是否"退化到兜底质量":口播过短(<20字)或镜头数<1;正常的短口播(如15s视频~40字)不视为兜底 - # v1.6.1 双保险:先做 hard fix 字符串替换("很近" → "最近"),再做不合格判定 - if "很近" in voiceover: - logger.warning("[爆款视频] 编导脚本含错别字'很近',hard fix 替换为'最近' label=%s", label) - voiceover = voiceover.replace("很近", "最近") - normalized["voiceover_script"] = voiceover - # 同时在 shots 对白里替换 - for sh in normalized.get("shots") or []: - if isinstance(sh, dict): - sd = sh.get("scene_and_dialogue") or "" - if "很近" in sd: - sh["scene_and_dialogue"] = sd.replace("很近", "最近") + # v1.6.1 P1修复:递归替换 copy_result 里所有字符串字段的"很近"→"最近"(覆盖 overview/scene_and_lighting/voiceover/shots.* 全部字段) + _before_dump = json.dumps(normalized, ensure_ascii=False) + if "很近" in _before_dump: + logger.warning("[爆款视频] 编导脚本含错别字'很近',递归替换为'最近' label=%s", label) + normalized = _replace_henjin_everywhere(normalized) + voiceover = (normalized or {}).get("voiceover_script") or "" fallback_marker = "我最近在用的好物" in voiceover # _fallback_script 的特征串 - has_typo_henjin = "很近" in voiceover # v1.6.1: 错别字"很近"视为不合格,触发重试 + has_typo_henjin = "很近" in json.dumps(normalized, ensure_ascii=False) # 递归检查仍有"很近"视为不合格 is_fallback = fallback_marker or shots_cnt < 1 or voiceover_len < 20 or has_typo_henjin logger.info( "[爆款视频] 编导脚本结果 label=%s voiceover_len=%d shots=%d fallback=%s raw_type=%s", @@ -1328,16 +1340,36 @@ def run_video_style_analysis(self: Task, job_id: str) -> dict: def _mark_failed_and_notify(job_id: str, session, repo, job, err_msg: str, stage: str = "") -> None: + """标记任务失败并通知。若传入的 session 已失效(因前面异常导致 rollback 状态), + 会自动 fallback 到新建 SessionLocal 重新标记,确保状态一定落库。""" try: - if session is None: - session = SessionLocal() - repo = SQLAlchemyViralVideoJobRepository(session) - job = repo.get(job_id) - if job is not None and not job.is_terminal: - job.mark_failed(err_msg) - _save_job(repo, job, session) + # 尝试用传入的 session 标记 + marked = False + if job is not None and not job.is_terminal and session is not None: + try: + job.mark_failed(err_msg) + _save_job(repo, job, session) + marked = True + except Exception as se: + logger.warning("[爆款视频] 用原 session 标记失败失败,fallback 新session: %s", se) + try: + session.rollback() + except Exception: + pass + if not marked: + # fallback:新建独立 session 重新标记(保证状态一定落库) + ssn = SessionLocal() + try: + r = SQLAlchemyViralVideoJobRepository(ssn) + j = r.get(job_id) + if j is not None and not j.is_terminal: + j.mark_failed(err_msg) + r.update(j) + ssn.commit() + finally: + ssn.close() except Exception as inner: - logger.warning("[爆款视频] 标记失败状态时出错: %s", inner) + logger.warning("[爆款视频] 标记失败状态时出错(最终fallback也失败): %s", inner, exc_info=True) _emit_progress( job_id, stage, diff --git a/packages/shared/ai_client.py b/packages/shared/ai_client.py index 145be55f0..c7d2e2097 100755 --- a/packages/shared/ai_client.py +++ b/packages/shared/ai_client.py @@ -25,6 +25,42 @@ from packages.shared.config import get_shared_settings logger = logging.getLogger(__name__) + +# 内部 pricing key → 火山方舟实际模型 ID +# 前端/后端内部用简短别名 seedance-2.5/seedance-2.0 做 VIRAL_VIDEO_MODEL_PRICES 配置 key, +# 但传给方舟 API 时必须用真实模型 ID(如 doubao-seedance-2-5-260628),否则会 404 InvalidEndpointOrModel.NotFound。 +VIRAL_VIDEO_MODEL_ID_MAP: dict[str, str] = { + "seedance-2.5": "doubao-seedance-2-5-260628", + "seedance-2.0": "doubao-seedance-2-0-250628", +} + + +def _resolve_video_model_id(model: str | None) -> str: + """把内部 pricing key(seedance-2.5/seedance-2.0)解析成方舟实际模型 ID。 + 未识别的别名或空值回落到 settings.doubao_video_model 默认值。 + """ + settings = get_shared_settings() + default_model = getattr(settings, "doubao_video_model", None) or "doubao-seedance-2-5-260628" + m = (model or "").strip() + if not m: + return default_model + # 已经是 doubao- 前缀的完整 ID,直接用 + if m.startswith("doubao-") or m.startswith("ep-"): + return m + # 别名 → 完整 ID + resolved = VIRAL_VIDEO_MODEL_ID_MAP.get(m.lower()) + if resolved: + return resolved + # 未识别:带 seedance 字样且不是 doubao-/ep- 开头的,拼前缀兜底 + if "seedance" in m.lower(): + # seedance-2.5 → doubao-seedance-2-5-260628 等兜底逻辑 + normalized = m.lower().replace(".", "-") + if normalized in VIRAL_VIDEO_MODEL_ID_MAP: + return VIRAL_VIDEO_MODEL_ID_MAP[normalized] + logger.warning("[ai_client] 未识别的 video_model=%r,使用默认模型 %s", m, default_model) + return default_model + + class DoubaoClient: """豆包大模型 API 客户端. @@ -282,8 +318,8 @@ class DoubaoClient: poll_interval = getattr(settings, "doubao_video_poll_interval", 10) or 10 # 收紧总超时:轮询 8min + 下载 2min = 最长 ~10min,防止出现 20min 卡死 total_timeout = getattr(settings, "doubao_video_timeout", 480) or 480 - default_video_model = getattr(settings, "doubao_video_model", None) or "doubao-seedance-2-5-260628" - video_model = model or default_video_model + # 内部 pricing key (seedance-2.5/seedance-2.0) → 方舟实际模型 ID + video_model = _resolve_video_model_id(model) ref_audios = [u for u in (reference_audios or [])[:10] if u and isinstance(u, str)] ref_videos = [u for u in (reference_videos or [])[:3] if u and isinstance(u, str)] @@ -408,12 +444,13 @@ class DoubaoClient: if not task_id: logger.error( "Seedance 创建任务最终失败: model=%s base_url=%s err=%s body=%s 【排查】" - "1) 方舟控制台已开通 doubao-seedance-2-5-260628;2) API Key 有该模型权限;" + "1) 方舟控制台已开通 %s;2) API Key 有该模型权限;" "3) DOUBAO_BASE_URL=https://ark.cn-beijing.volces.com/api/v3;4) 参考素材 URL 公网可访问。", video_model, self.base_url, last_err, (body or "")[:500], + video_model, ) return None