From 2f48fc1d4c80a4c25a04d5f4e1e6c19fbb3528db Mon Sep 17 00:00:00 2001
From: hit-cxf <2024111082@stu.hit.edu.cn>
Date: Thu, 23 Apr 2026 11:53:33 +0800
Subject: [PATCH] fix: add kimi to models.ts
---
aigc-director/aigc-claw/backend/core/agents/storyboard_agent.py | 649 ++++++++++++++++++++--------------------------------------
1 files changed, 229 insertions(+), 420 deletions(-)
diff --git a/aigc-director/aigc-claw/backend/core/agents/storyboard_agent.py b/aigc-director/aigc-claw/backend/core/agents/storyboard_agent.py
index 9dbe1a7..0d4519f 100644
--- a/aigc-director/aigc-claw/backend/core/agents/storyboard_agent.py
+++ b/aigc-director/aigc-claw/backend/core/agents/storyboard_agent.py
@@ -1,7 +1,8 @@
-# -*- coding: utf-8 -*-
+# -*- coding: utf-8 -*-
"""
阶段3: 分镜智能体
基于剧本JSON,逐场景拆分为带时长标签的分镜(shots),按幕分组输出。
+支持 Segment -> Shots 嵌套结构。
"""
import os
@@ -9,469 +10,277 @@
import json
import asyncio
import logging
+from datetime import datetime
from typing import Any, Optional, Dict, List
-from concurrent.futures import ThreadPoolExecutor, as_completed
from .base_agent import AgentInterface
-from prompts.loader import load_prompt
logger = logging.getLogger(__name__)
# ─── 幕名 ───
ACT_NAMES = {1: "激励事件", 2: "进入新世界", 3: "灵魂黑夜", 4: "高潮决战"}
-
-def _get_shot_prompt(lang: str = 'zh') -> str:
- """获取分镜提取提示词"""
+def _get_shot_prompt(lang: str = "zh") -> str:
from prompts.loader import load_prompt_with_fallback
- return load_prompt_with_fallback('storyboard', 'shot', lang, 'zh')
-
-
-def _get_expand_prompt(lang: str = 'zh') -> str:
- """获取剧本扩写提示词"""
- from prompts.loader import load_prompt_with_fallback
- return load_prompt_with_fallback('storyboard', 'expand', lang, 'zh')
-
-
-def _get_continue_prompt(lang: str = 'zh') -> str:
- """获取续写分镜提示词"""
- from prompts.loader import load_prompt_with_fallback
- return load_prompt_with_fallback('storyboard', 'continue', lang, 'zh')
-
+ return load_prompt_with_fallback("storyboard", "shot", lang, "zh")
class StoryboardAgent(AgentInterface):
- """分镜智能体:逐场景拆分为带时长标签的分镜"""
-
def __init__(self):
super().__init__(name="Storyboard")
- # ─── 辅助方法 ───
-
@staticmethod
def _read_script_json(sid: str) -> dict:
- """从结果文件读取 script_json"""
- from config import settings
- result_file = os.path.join(settings.RESULT_DIR, 'script', f'script_{sid}.json')
- if not os.path.exists(result_file):
+ session_path = os.path.join("code/data/sessions", f"{sid}.json")
+ if not os.path.exists(session_path):
return {}
- with open(result_file, 'r', encoding='utf-8') as f:
- data = json.load(f)
- return data.get(str(sid), {}).get('script_json', {})
+ try:
+ with open(session_path, "r", encoding="utf-8") as f:
+ data = json.load(f)
+ return data.get("artifacts", {}).get("script_generation", {})
+ except Exception:
+ return {}
@staticmethod
def _extract_json_array(text: str) -> Optional[List[dict]]:
- """从LLM输出中提取JSON数组"""
text = text.strip()
- text = re.sub(r'^```(?:json)?\s*', '', text)
- text = re.sub(r'\s*```$', '', text)
- text = text.strip()
+ text = re.sub(r"^```(?:json)?\s*", "", text)
+ text = re.sub(r"\s*```$", "", text)
try:
result = json.loads(text)
- if isinstance(result, list):
- return result
- except json.JSONDecodeError:
- pass
- # 尝试找到 [ ... ] 部分
- m = re.search(r'\[.*\]', text, re.DOTALL)
+ if isinstance(result, list): return result
+ except json.JSONDecodeError: pass
+ m = re.search(r"\[.*\]", text, re.DOTALL)
if m:
try:
result = json.loads(m.group())
- if isinstance(result, list):
- return result
- except json.JSONDecodeError:
- pass
+ if isinstance(result, list): return result
+ except json.JSONDecodeError: pass
return None
@staticmethod
- def _validate_shots(shots: List[dict]) -> List[dict]:
- """校验并清洗分镜数据"""
- valid = []
- for s in shots:
- if not isinstance(s, dict):
- continue
- dur = s.get("duration", 10)
- if dur not in (5, 10, 15):
- dur = 10 # 默认10秒
- valid.append({
- "shot_number": s.get("shot_number", len(valid) + 1),
- "duration": dur,
- "characters": s.get("characters", []),
- "location": s.get("location", ""),
- "plot": s.get("plot", ""),
- "visual_prompt": s.get("visual_prompt", ""),
+ def _validate_episodes(episodes: List[dict]) -> List[dict]:
+ """验证嵌套的 Episode -> Segment -> Shots 结构"""
+ valid_episodes = []
+ for ep in episodes:
+ if not isinstance(ep, dict): continue
+
+ segments = ep.get("segments", [])
+ valid_segments = []
+ for idx, seg in enumerate(segments, 1):
+ if not isinstance(seg, dict): continue
+
+ shots = seg.get("shots", [])
+ valid_shots = []
+ calc_total_duration = 0
+
+ for s in shots:
+ if not isinstance(s, dict): continue
+ dur = s.get("duration", 5)
+ calc_total_duration += dur
+ valid_shots.append({
+ "shot_number": s.get("shot_number", len(valid_shots) + 1),
+ "shot_type": s.get("shot_type", "中景"),
+ "duration": dur,
+ "content": s.get("content", "")
+ })
+
+ valid_segments.append({
+ "segment_id": seg.get("segment_id", f"seg_{str(idx).zfill(8)}"),
+ "segment_number": seg.get("segment_number", len(valid_segments) + 1),
+ "total_duration": seg.get("total_duration", calc_total_duration),
+ "location": seg.get("location", ""),
+ "characters": seg.get("characters", []),
+ "shots": valid_shots
+ })
+
+ valid_episodes.append({
+ "episode_number": ep.get("episode_number", len(valid_episodes) + 1),
+ "episode_title": ep.get("episode_title", ""),
+ "segments": valid_segments
})
- return valid
-
- async def _continue_story(self, input_data: Dict, continue_info: Dict) -> Dict:
- """智能续写:根据已有剧情续写新场景"""
- from config import settings
- from tool.llm_client import LLM
-
- sid = input_data["session_id"]
- style = input_data.get("style", "anime")
- llm_model = input_data.get("llm_model", "qwen3.5-plus")
-
- result_file = os.path.join(settings.RESULT_DIR, 'script', f'script_{sid}.json')
-
- # 读取已有分镜
- with open(result_file, 'r', encoding='utf-8') as f:
- results = json.load(f)
- existing_shots = results.get(str(sid), {}).get('storyboard', {}).get('shots', [])
- if not existing_shots:
- raise Exception("没有已有分镜,无法续写")
-
- # 读取剧本信息
- script_json = self._read_script_json(sid)
- if not script_json:
- raise Exception("未找到剧本数据")
-
- title = script_json.get("title", "")
- characters = script_json.get("characters", [])
- settings_list = script_json.get("settings", [])
-
- # 取所有分镜作为上下文
- last_shots = existing_shots
-
- # 构建上下文描述
- char_names = [c.get("name", "") for c in characters]
- # 只使用现有分镜中实际使用的场景位置
- used_locations = set(s.get("location", "") for s in existing_shots if s.get("location"))
- setting_names = [s.get("name", "") for s in settings_list if s.get("name", "") in used_locations]
-
- # 获取续写提示词
- is_zh = any('\u4e00' <= c <= '\u9fff' for c in title)
- prompt_template = _get_continue_prompt('zh' if is_zh else 'en')
-
- # 格式化已有分镜信息
- shots_context = ""
- for shot in last_shots:
- shots_context += f"- 场景{shot.get('scene_number')} 分镜{shot.get('shot_number')}: {shot.get('plot', '')}\n"
-
- prompt = prompt_template.format(
- title=title,
- style=style,
- characters=", ".join(char_names),
- settings=", ".join(setting_names),
- existing_shots=shots_context,
- )
-
- self._report_progress("分镜", "智能续写中...", 10)
-
- def run():
- llm = LLM()
- raw = self._cancellable_query(llm, prompt, model=llm_model, task_id=sid)
- new_shots = self._extract_json_array(raw)
- if not new_shots:
- raise Exception("续写失败,无法解析LLM输出")
- new_shots = self._validate_shots(new_shots)
- return new_shots
-
- loop = asyncio.get_running_loop()
- new_shots = await loop.run_in_executor(None, run)
-
- # 为新分镜添加全局标识
- last_scene = last_shots[-1] if last_shots else None
- next_scene_num = (last_scene.get("scene_number", 0) + 1) if last_scene else 1
- next_act = last_scene.get("act", 1) if last_scene else 1
-
- for i, shot in enumerate(new_shots):
- shot["shot_id"] = f"shot_{next_scene_num:03d}_{i + 1:02d}"
- shot["scene_number"] = next_scene_num
- shot["act"] = next_act
- shot["is_new"] = True # 标记为新添加的分镜
-
- # 追加到已有分镜
- all_shots = existing_shots + new_shots
-
- # 保存(带有 is_new 标记,供前端识别)
- results.setdefault(str(sid), {})['storyboard'] = {
- 'shots': all_shots,
- 'user_modified': True,
- 'new_shot_ids': [s["shot_id"] for s in new_shots], # 记录新分镜ID
- }
- with open(result_file, 'w', encoding='utf-8') as f:
- json.dump(results, f, indent=4, ensure_ascii=False)
-
- self._report_progress("分镜", "续写完成", 100)
-
- return {
- "payload": {
- "session_id": sid,
- "shots": all_shots,
- "new_shots": new_shots,
- "new_shot_ids": [s["shot_id"] for s in new_shots],
- "continued": True,
- },
- "requires_intervention": True,
- }
-
- # ─── 核心流程 ───
+ return valid_episodes
async def process(self, input_data: Any, intervention: Optional[Dict] = None) -> Dict:
- from config import settings
from tool.llm_client import LLM
-
- sid = input_data["session_id"]
- style = input_data.get("style", "anime")
- llm_model = input_data.get("llm_model", "qwen3.5-plus")
-
- result_file = os.path.join(settings.RESULT_DIR, 'script', f'script_{sid}.json')
-
- # ── 用户修改了分镜 ──
+ input_data = self._merge_session_params(input_data)
+ sid = input_data.get("session_id")
+ if not sid: raise Exception("Missing session_id")
+
+ session_file = os.path.join("code/data/sessions", f"{sid}.json")
+ with open(session_file, "r", encoding="utf-8") as f:
+ session_data = json.load(f)
+
+ llm_model = input_data.get("llm_model") or session_data.get("llm_model") or "qwen-max"
+ style = input_data.get("style") or session_data.get("style") or "anime"
+
+ # 处理人工干预/修改
if intervention and "modified_storyboard" in intervention:
- modified_shots = intervention["modified_storyboard"]
- if isinstance(modified_shots, str):
- modified_shots = json.loads(modified_shots)
-
- with open(result_file, 'r', encoding='utf-8') as f:
- results = json.load(f)
-
- # 同步更新 script_json 中的 scenes
- # 获取修改后的 shots 中包含的场景编号
- new_scene_numbers = set(s.get("scene_number") for s in modified_shots if s.get("scene_number"))
-
- # 更新 script_json.scenes
- script_json = results.get(str(sid), {}).get('script_json', {})
- if script_json and 'scenes' in script_json:
- original_scenes = script_json.get('scenes', [])
- # 保留新分镜中包含的场景,按原始顺序
- filtered_scenes = [s for s in original_scenes if s.get('scene_number') in new_scene_numbers]
- # 重新编号(确保 scene_number 连续)
- for i, scene in enumerate(filtered_scenes, 1):
- scene['scene_number'] = i
- script_json['scenes'] = filtered_scenes
-
- # 清除 new_shot_ids 标记,同时清除 is_new 标志
- for shot in modified_shots:
- if 'is_new' in shot:
- shot['is_new'] = False
- storyboard_data = {
- 'shots': modified_shots,
- 'user_modified': True,
- 'new_shot_ids': [], # 清除新分镜标记
+ modified_episodes = intervention["modified_storyboard"]
+ if isinstance(modified_episodes, str): modified_episodes = json.loads(modified_episodes)
+ session_data.setdefault("artifacts", {})["storyboard"] = {
+ "session_id": sid,
+ "episodes": modified_episodes,
+ "user_modified": True,
+ "updated_at": datetime.now().isoformat()
}
+ # 更新顶层状态
+ session_data["updated_at"] = datetime.now().timestamp()
+ with open(session_file, "w", encoding="utf-8") as f: json.dump(session_data, f, indent=2, ensure_ascii=False)
+ return {"payload": {"session_id": sid, "episodes": modified_episodes}, "stage_completed": True}
+
+ script_data = self._read_script_json(sid)
+ if not script_data: raise Exception("未找到剧本数据")
+
+ episodes = script_data.get("episodes", [])
+ if not episodes:
+ raise Exception("剧本数据中不包含有效集数列表(episodes)")
- results.setdefault(str(sid), {})['storyboard'] = storyboard_data
- if script_json:
- results.setdefault(str(sid), {})['script_json'] = script_json
- with open(result_file, 'w', encoding='utf-8') as f:
- json.dump(results, f, indent=4, ensure_ascii=False)
+ # 检查是否有已存在的分镜数据,识别需要生成的集数
+ existing_storyboard = session_data.get("artifacts", {}).get("storyboard", {})
+ existing_story_eps = existing_storyboard.get("episodes", [])
+
+ # 建立已生成的 segments 索引
+ ready_eps = {e["episode_number"] for e in existing_story_eps if e.get("segments")}
+
+ # 确定需要处理的集数:如果该集还没有 segments,则需要生成
+ episodes_to_proc = [ep for ep in episodes if ep.get("episode_number") not in ready_eps]
+
+ if not episodes_to_proc:
+ logger.info("[Storyboard] All episodes already have storyboard segments. Skipping generation.")
+ return {"payload": {"session_id": sid, "episodes": existing_story_eps}, "stage_completed": True}
- # 返回完整的 payload 包含 user_modified 和 new_shot_ids
- return {
- "payload": {
- "session_id": sid,
- "shots": modified_shots,
- "user_modified": True,
- "new_shot_ids": [],
- },
- "stage_completed": True,
- }
+ chars = script_data.get("characters", [])
+ sets = script_data.get("settings", [])
+ is_zh = any("\u4e00" <= c <= "\u9fff" for c in script_data.get("title", ""))
+ shot_prompt_tpl = _get_shot_prompt("zh" if is_zh else "en")
+
+ self._report_progress("分镜", f"开始生成 {len(episodes_to_proc)} 集缺失的分镜...", 5)
+
+ async def proc_ep(ep):
+ # ... (保持原本处理逻辑不变)
+ ep_n = ep.get("episode_number", 1)
+ # ... (以下为原本 proc_ep 逻辑)
+ ep_t = ep.get("act_title", f"第{ep_n}集")
+ ep_c = ep.get("content", "")
+
+ # 清洗剧本内容:按行拆分,用于提示说明“一行一分镜”
+ lines = [line.strip() for line in ep_c.split('\n') if line.strip()]
+ script_text_with_lines = "\n".join([f"L{idx+1}: {line}" for idx, line in enumerate(lines)])
- # ── 用户点击"智能续写" ──
- if intervention and "continue_story" in intervention:
- return await self._continue_story(input_data, intervention["continue_story"])
-
- # ── 正常流程 ──
- script_json = self._read_script_json(sid)
- if not script_json:
- raise Exception("未找到剧本数据(script_json),请先完成阶段1")
-
- scenes = script_json.get("scenes", [])
- characters = {c["name"]: c for c in script_json.get("characters", [])}
- settings_map = {s["name"]: s for s in script_json.get("settings", [])}
-
- # 拼接完整剧情以供扩写参考
- full_plot_text = "\n".join([f"场景{s.get('scene_number', i+1)}: {s.get('plot', '')}" for i, s in enumerate(scenes)])
-
- is_zh = any('\u4e00' <= c <= '\u9fff' for c in script_json.get("title", ""))
- lang = 'zh' if is_zh else 'en'
- shot_prompt_template = _get_shot_prompt(lang)
- expand_prompt_template = _get_expand_prompt(lang)
-
- self._report_progress("分镜", "读取剧本数据...", 5)
-
- # 获取并发数
- enable_concurrency = input_data.get("enable_concurrency", True)
- from config_model import get_max_concurrency
- # LLM 调用的并发数
- concurrency = get_max_concurrency(llm_model, enable_concurrency)
- logger.info(f"[StoryboardAgent] enable_concurrency={enable_concurrency}, concurrency={concurrency} for model={llm_model}")
-
- # 用于按场景顺序存储结果的字典
- shots_results: Dict[int, List[dict]] = {}
- done_count = 0
- total = len(scenes)
-
- def generate_one_scene(scene_index: int, scene: dict) -> tuple:
- """生成单个场景的分镜"""
- llm = LLM()
- sn = scene.get("scene_number", scene_index + 1)
- act = scene.get("act", 1)
-
- location = scene.get("location", "")
- scene_chars = scene.get("characters", [])
- original_plot = scene.get("plot", "")
-
- # 角色外貌描述
- char_descs = []
- for cn in scene_chars:
- c = characters.get(cn)
- if c:
- char_descs.append(f"{cn}: {c.get('description', '')}")
- char_desc_text = "\n".join(char_descs) if char_descs else "无"
-
- # 场景环境描述
- setting_info = settings_map.get(location, {})
- setting_desc = setting_info.get("description", location)
-
- # 第一步:扩写剧本
- logger.info(f"[StoryboardAgent] Expanding scene {sn}...")
- expand_prompt = expand_prompt_template.format(
- title=script_json.get("title", ""),
- style=style,
- location=location,
- characters=", ".join(scene_chars),
- plot=original_plot,
- char_descriptions=char_desc_text,
- setting_description=setting_desc,
- script=full_plot_text
+ prompt = shot_prompt_tpl.format(
+ act_number=ep_n,
+ act_title=ep_t,
+ script_text=script_text_with_lines,
+ asset_characters=json.dumps(chars, ensure_ascii=False),
+ asset_settings=json.dumps(sets, ensure_ascii=False),
+ style=style
)
- expanded_plot = original_plot
- try:
- expanded_plot = self._cancellable_query(llm, expand_prompt, model=llm_model, task_id=sid)
- logger.info(f"[StoryboardAgent] Scene {sn} expanded.")
- except Exception as e:
- logger.error(f"Scene {sn} expansion failed: {e}")
-
- # 第二步:生成分镜 (使用扩写后的内容)
- prompt = shot_prompt_template.format(
- style=style,
- scene_number=sn,
- location=location,
- characters=", ".join(scene_chars),
- expanded_plot=expanded_plot,
- char_descriptions=char_desc_text,
- setting_description=setting_desc,
- )
-
- # 最多重试3次
- scene_shots = None
- for attempt in range(3):
- if hasattr(self, 'cancellation_check') and self.cancellation_check:
- if self.cancellation_check():
+ llm = LLM()
+ loop = asyncio.get_running_loop()
+
+ # 增加重试机制 (Max 3 retries)
+ max_retries = 3
+ extracted = None
+ raw = ""
+
+ for attempt in range(max_retries):
+ try:
+ self._report_progress("分镜", f"生成集数 {ep_n} (第 {attempt + 1} 次尝试)...", 5 + attempt * 2)
+ raw = await loop.run_in_executor(None, self._cancellable_query, llm, prompt, [], llm_model, False, sid, False)
+ extracted = self._extract_json_array(raw)
+ if extracted:
break
- raw = self._cancellable_query(llm, prompt, model=llm_model, task_id=sid)
- parsed = self._extract_json_array(raw)
- if parsed:
- scene_shots = self._validate_shots(parsed)
- if scene_shots:
- break
- logger.warning(f"Scene {sn} shot parse attempt {attempt+1} failed")
+ logger.warning(f"Episode {ep_n} Attempt {attempt + 1}: Failed to extract JSON array. Retrying...")
+ except Exception as e:
+ logger.error(f"Episode {ep_n} Attempt {attempt + 1}: LLM query error: {str(e)}")
+ if attempt == max_retries - 1: raise e
+
+ if not extracted:
+ logger.error(f"LLM output failed to parse as JSON for Episode {ep_n} after {max_retries} attempts. Raw: {raw}")
+ # 抛出异常以触发 orchestrator 的错误状态处理逻辑
+ raise Exception(f"第 {ep_n} 集分镜生成失败:模型输出无法解析")
+
+ valid_segments = []
+ for i, seg in enumerate(extracted, 1):
+ if not isinstance(seg, dict): continue
+
+ shots = seg.get("shots", [])
+ valid_shots = []
+ calc_total_duration = 0
+ for s in shots:
+ if not isinstance(s, dict): continue
+ dur = s.get("duration", 5)
+ calc_total_duration += dur
+ valid_shots.append({
+ "shot_number": s.get("shot_number", len(valid_shots) + 1),
+ "shot_type": s.get("shot_type", "中景"),
+ "duration": dur,
+ "content": s.get("content", "")
+ })
+
+ valid_segments.append({
+ "segment_id": seg.get("segment_id", f"seg_{ep_n:02d}_{i:02d}"),
+ "segment_number": seg.get("segment_number", len(valid_segments) + 1),
+ "total_duration": seg.get("total_duration", calc_total_duration),
+ "location": seg.get("location", ""),
+ "characters": seg.get("characters", []),
+ "shots": valid_shots,
+ "episode_number": ep_n
+ })
- if not scene_shots:
- # 降级: 整个场景作为一个分镜
- scene_shots = [{
- "shot_number": 1,
- "duration": 15,
- "characters": scene_chars,
- "location": location,
- "plot": original_plot,
- "visual_prompt": original_plot,
- }]
-
- # 为每个分镜添加全局标识
- for shot in scene_shots:
- shot["shot_id"] = f"shot_{sn:03d}_{shot['shot_number']:02d}"
- shot["scene_number"] = sn
- shot["act"] = act
-
- return scene_index, scene_shots, sn, act
-
- def run():
- nonlocal done_count
- # 检测是否有多幕结构(微电影模式只有一幕或无 act 字段)
- act_values = {s.get("act") for s in scenes}
- multi_act = len(act_values - {None}) > 1
-
- with ThreadPoolExecutor(max_workers=concurrency) as executor:
- futs = {}
- for i, scene in enumerate(scenes):
- fut = executor.submit(generate_one_scene, i, scene)
- futs[fut] = i
-
- # 按提交顺序收集结果(不是按完成顺序)
- for scene_index in range(len(scenes)):
- # 找到对应的 future
- found_future = None
- for fut in futs:
- if futs[fut] == scene_index:
- found_future = fut
- break
-
- if found_future:
- try:
- idx, scene_shots, sn, act = found_future.result()
- shots_results[idx] = scene_shots
-
- # 报告进度
- done_count += 1
- pct = 5 + int(90 * done_count / max(total, 1))
- if multi_act:
- act_label = ACT_NAMES.get(act, f"第{act}幕")
- self._report_progress("分镜", f"第{act}幕「{act_label}」 场景{sn}/{total}完成", pct)
- else:
- self._report_progress("分镜", f"场景{sn}完成 ({len(scene_shots)}个分镜)", pct)
-
- # 发送逐场完成事件
- self._report_progress(
- "分镜",
- f"场景{sn}完成 ({len(scene_shots)}个分镜)",
- pct,
- data={"scene_shots_complete": {
- "scene_number": sn,
- "act": act,
- "shots": scene_shots,
- }},
- )
- except Exception as e:
- logger.error(f"Scene {scene_index} generation error: {e}")
- shots_results[scene_index] = []
-
- # 按场景顺序拼接所有分镜
- all_shots = []
- for i in range(len(scenes)):
- if i in shots_results:
- all_shots.extend(shots_results[i])
-
- self._report_progress("分镜", "保存结果...", 96)
-
- # 写入结果文件
- with open(result_file, 'r', encoding='utf-8') as f:
- results = json.load(f)
- results.setdefault(str(sid), {})['storyboard'] = {
- 'shots': all_shots,
- }
- with open(result_file, 'w', encoding='utf-8') as f:
- json.dump(results, f, indent=4, ensure_ascii=False)
-
- self._report_progress("分镜", "完成", 100)
return {
- "payload": {
- "session_id": sid,
- "shots": all_shots,
- },
- "stage_completed": True,
+ "episode_number": ep_n,
+ "episode_title": ep_t,
+ "segments": valid_segments
}
- loop = asyncio.get_running_loop()
- all_shots = await loop.run_in_executor(None, run)
-
- return {
- "payload": {
- "session_id": sid,
- "shots": all_shots,
- },
- "stage_completed": True,
+ # 核心:支持流式保存增量产物,让前端能看到实时进度
+ updated_ep_map = {e["episode_number"]: e for e in existing_story_eps}
+
+ # 立即先保存一次,确保已有的 episodes 在进入 running 状态后依然可见
+ session_data.setdefault("artifacts", {})["storyboard"] = {
+ "session_id": sid,
+ "episodes": sorted(updated_ep_map.values(), key=lambda x: x["episode_number"]),
+ "created_at": datetime.now().isoformat()
}
+ with open(session_file, "w", encoding="utf-8") as f:
+ json.dump(session_data, f, indent=2, ensure_ascii=False)
+ # 报告一次进度,带上 asset_complete 强制前端从磁盘刷新一次初步数据
+ self._report_progress("分镜设计", "准备生成分镜...", 10, {"asset_complete": True})
+
+ results_queue = [proc_ep(ep) for ep in episodes_to_proc]
+
+ for coro in asyncio.as_completed(results_queue):
+ res = await coro
+ updated_ep_map[res["episode_number"]] = res
+
+ # 每完成一集分镜,立即持久化并触发增量同步
+ temp_eps = sorted(updated_ep_map.values(), key=lambda x: x["episode_number"])
+ session_data.setdefault("artifacts", {})["storyboard"] = {
+ "session_id": sid,
+ "episodes": temp_eps,
+ "created_at": datetime.now().isoformat()
+ }
+ with open(session_file, "w", encoding="utf-8") as f:
+ json.dump(session_data, f, indent=2, ensure_ascii=False)
+
+ # 报告带有 asset_complete 的进度,强制编排器刷新前端数据
+ self._report_progress("分镜设计", f"集数 {res['episode_number']} 分镜已生成", 50, {"asset_complete": True})
+
+ final_all_episodes = sorted(updated_ep_map.values(), key=lambda x: x["episode_number"])
+
+ # 核心:将结果持久化到 artifacts.storyboard
+ session_data.setdefault("artifacts", {})["storyboard"] = {
+ "session_id": sid,
+ "episodes": final_all_episodes,
+ "created_at": datetime.now().isoformat()
+ }
+
+ session_data["updated_at"] = datetime.now().timestamp()
+
+ with open(session_file, "w", encoding="utf-8") as f:
+ json.dump(session_data, f, indent=2, ensure_ascii=False)
+
+ self._report_progress("分镜", "完成", 100)
+ return {"payload": {"session_id": sid, "episodes": final_all_episodes}, "stage_completed": True}
--
Gitblit v1.8.0