1 files added
5 files modified
| | |
| | | with open(result_file, 'r', encoding='utf-8') as f: |
| | | results = json.load(f) |
| | | |
| | | storyboard = results.get(session_id, {}).get('storyboard', {}) |
| | | # 如果 results 是列表(旧版或某些 agent 的存储方式),则不能使用 .get(session_id) |
| | | # 根据 script_agent.py 的实现,final_json 是一个包含 session_id 的字典 |
| | | if isinstance(results, dict): |
| | | # 兼容两种结构:{session_id: {...}} 或 {...} |
| | | script_data = results.get(session_id, results) if results.get(session_id) else results |
| | | else: |
| | | # 如果是列表,尝试按 session_id 过滤 |
| | | script_data = next((item for item in results if isinstance(item, dict) and item.get("session_id") == session_id), {}) |
| | | |
| | | # 尝试从 script_data 或 state.artifacts 中获取 storyboard |
| | | storyboard = script_data.get('storyboard', {}) |
| | | if not storyboard: |
| | | # 兼容旧版本可能直接存储在 results 下的情况 |
| | | storyboard = results.get('storyboard', {}) if isinstance(results, dict) else {} |
| | | |
| | | shots = storyboard.get('shots', []) |
| | | |
| | | # 筛选该场景的分镜 |
| | |
| | | shot_ids = [s.get('shot_id') for s in scene_shots if s.get('shot_id')] |
| | | |
| | | # 检查参考图 |
| | | ref_artifact = results.get(session_id, {}).get('reference_generation', {}) |
| | | ref_scenes = ref_artifact.get('scenes', []) |
| | | ref_artifact = script_data.get('reference_generation', {}) |
| | | if not ref_artifact: |
| | | ref_artifact = state.artifacts.get('reference_generation', {}) |
| | | |
| | | ref_scenes = ref_artifact.get('scenes', []) if isinstance(ref_artifact, dict) else [] |
| | | ref_image_count = 0 |
| | | for sc in ref_scenes: |
| | | if sc.get('id') in shot_ids: |
| | |
| | | ref_image_count += 1 |
| | | |
| | | # 检查视频 |
| | | video_artifact = results.get(session_id, {}).get('video_generation', {}) |
| | | video_clips = video_artifact.get('clips', []) |
| | | video_artifact = script_data.get('video_generation', {}) |
| | | if not video_artifact: |
| | | video_artifact = state.artifacts.get('video_generation', {}) |
| | | |
| | | video_clips = video_artifact.get('clips', []) if isinstance(video_artifact, dict) else [] |
| | | video_count = 0 |
| | | for vc in video_clips: |
| | | if vc.get('id') in shot_ids: |
| | |
| | | super().__init__(name="ScriptWriter") |
| | | |
| | | @staticmethod |
| | | def _extract_json_from_text(text: str) -> Optional[dict]: |
| | | def _extract_json_from_text(text: str) -> Optional[Any]: |
| | | text = text.strip() |
| | | text = re.sub(r'^```(?:json)?\s*', '', text) |
| | | text = re.sub(r'\s*```$', '', text) |
| | |
| | | return json.loads(text) |
| | | except json.JSONDecodeError: |
| | | pass |
| | | start = text.find('{') |
| | | end = text.rfind('}') |
| | | |
| | | # 尝试匹配第一个 { 或 [ 到底部对应的 } 或 ] |
| | | start_obj = text.find('{') |
| | | start_arr = text.find('[') |
| | | |
| | | # 确定起始位置 |
| | | if start_obj == -1 and start_arr == -1: |
| | | return None |
| | | |
| | | start = start_obj if (start_obj != -1 and (start_arr == -1 or start_obj < start_arr)) else start_arr |
| | | end_char = '}' if start == start_obj else ']' |
| | | end = text.rfind(end_char) |
| | | |
| | | if start != -1 and end != -1 and end > start: |
| | | try: |
| | | return json.loads(text[start:end + 1]) |
| | |
| | | loop = asyncio.get_running_loop() |
| | | full_script_text = await loop.run_in_executor(None, self._cancellable_query, llm, prompt, [], llm_model, True, sid, web_search) |
| | | logger.info(f"[ScriptWriter] Full script generated ({len(full_script_text)} chars)") |
| | | _log_progress(40, "原稿生成完成,正在提取元数据...") |
| | | _log_progress(40, "原稿生成完成,正在提取人物/场景信息...") |
| | | |
| | | # 2. Extract meta data -> total_episodes, characters, settings |
| | | meta_prompt = _get_script_prompt("meta_extract", "zh" if is_zh else "en").format(script_text=full_script_text, outline=full_script_text) |
| | | meta_raw = await loop.run_in_executor(None, self._cancellable_query, llm, meta_prompt, [], llm_model, True, sid, web_search) |
| | | meta_data = self._extract_json_from_text(meta_raw) or {} |
| | | |
| | | meta_res = self._extract_json_from_text(meta_raw) |
| | | meta_data = meta_res if isinstance(meta_res, dict) else {} |
| | | |
| | | all_characters = meta_data.get("characters", []) |
| | | all_settings = meta_data.get("settings", []) |
| | | for c in all_characters: |
| | |
| | | asset_chars_str = json.dumps([{"name": c.get("name"), "description": c.get("description"), "role": c.get("role")} for c in all_characters], ensure_ascii=False) |
| | | asset_sets_str = json.dumps([{"name": s.get("name"), "description": s.get("description")} for s in all_settings], ensure_ascii=False) |
| | | |
| | | _log_progress(50, "正在解析各集数据...") |
| | | # 3. 解析各集数据 - 针对新版数组输出格式进行优化 |
| | | _log_progress(70, "开始结构化全集数据...") |
| | | |
| | | total_eps = meta_data.get("total_episodes", 4) |
| | | if not isinstance(total_eps, int) or total_eps < 1: |
| | | total_eps = 1 |
| | | |
| | | async def extract_one_episode(ep_num): |
| | | self._check_cancel() |
| | | |
| | | extract_prompt = _get_script_prompt("act_extract", "zh" if is_zh else "en").format( |
| | | act_number=ep_num, scene_start=1, script_text=full_script_text, outline=full_script_text, |
| | | asset_characters=asset_chars_str, asset_settings=asset_sets_str |
| | | ) |
| | | |
| | | # 并行调用 LLM(使用异步包装) |
| | | loop = asyncio.get_running_loop() |
| | | raw_act = await loop.run_in_executor(None, self._cancellable_query, llm, extract_prompt, [], llm_model, True, sid, web_search) |
| | | parsed_act = self._extract_json_from_text(raw_act) or {} |
| | | extract_prompt = _get_script_prompt("act_extract", "zh" if is_zh else "en").format( |
| | | script_text=full_script_text |
| | | ) |
| | | |
| | | raw_acts = await loop.run_in_executor(None, self._cancellable_query, llm, extract_prompt, [], llm_model, True, sid, web_search) |
| | | parsed_acts = self._extract_json_from_text(raw_acts) |
| | | |
| | | all_episodes = [] |
| | | if isinstance(parsed_acts, list): |
| | | for act in parsed_acts: |
| | | if isinstance(act, dict): |
| | | all_episodes.append({ |
| | | "episode_number": act.get("episode_number"), |
| | | "act_title": act.get("act_title") or f"第{act.get('episode_number')}集", |
| | | "content": act.get("content", "") |
| | | }) |
| | | |
| | | return ep_num, { |
| | | "episode_number": ep_num, |
| | | "act_title": parsed_act.get("episode_title") or parsed_act.get("act_title") or f"第{ep_num}集", |
| | | "content": parsed_act.get("episode_content") or parsed_act.get("content", "") |
| | | } |
| | | |
| | | # 创建并发任务 |
| | | tasks = [extract_one_episode(i) for i in range(1, total_eps + 1)] |
| | | results = await asyncio.gather(*tasks) |
| | | |
| | | # 保持原始顺序 |
| | | results.sort(key=lambda x: x[0]) |
| | | all_episodes = [r[1] for r in results] |
| | | |
| | | if not all_episodes: |
| | | logger.error(f"[ScriptWriter] Failed to parse episodes from LLM output. Raw: {raw_acts[:200]}...") |
| | | |
| | | final_json = { |
| | | "project_id": f"proj_{sid}", |
| | | "session_id": sid, |
| | |
| | | |
| | | try: |
| | | result = await agent.process(input_data, intervention=intervention) |
| | | if not isinstance(result, dict): |
| | | logger.error(f"[execute_stage] Agent {stage.value} returned non-dict result: {type(result)}") |
| | | result = {"payload": result} |
| | | |
| | | state.artifacts[stage.value] = result.get("payload") |
| | | |
| | | # 第三阶段修改分镜时:同步更新第四、第五阶段的相关内容 |
| | | if stage.value == "storyboard" and intervention and "modified_storyboard" in intervention: |
| | | # 只有在 storyboard 阶段明确有修改时才执行同步 |
| | | if stage.value == "storyboard" and isinstance(intervention, dict) and "modified_storyboard" in intervention: |
| | | modified_shots = intervention["modified_storyboard"] |
| | | if isinstance(modified_shots, list): |
| | | shot_durations = {s.get('shot_id'): s.get('duration', 10) |
| | |
| | | 【拆分要求】 |
| | | |
| | | 1. 请将输入的剧本内容按集数归纳到对应的 `episode_number` 下。 |
| | | 2. `act_title` 请提取该集的标题或前10个字。 |
| | | 2. `act_title` 请根据该集的剧情,总结一个精炼、引人注意的标题,10个字以内。 |
| | | 3. `content` 请保留该集的完整剧本正文(包含场景描述、动作说明和角色台词)。 |
| | | |
| | | **注意(严格遵守):** |
| | |
| | | [ |
| | | {{ |
| | | "episode_number": 1, |
| | | "act_title": "激励事件/剧集标题", |
| | | "act_title": "剧集标题", |
| | | "content": "具体的剧本正文内容..." |
| | | }}, |
| | | {{ |
| | | "episode_number": 2, |
| | | "act_title": "进入新世界/剧集标题", |
| | | "act_title": "剧集标题", |
| | | "content": "具体的剧本正文内容..." |
| | | }} |
| | | ] |
| | |
| | | 【输出格式示例(仅返回此 JSON 对象)】 |
| | | {{ |
| | | "title": "剧本名称", |
| | | "num_episodes": 4, |
| | | "mood": "影片情绪基调", |
| | | "characters": [ |
| | | {{ |
| New file |
| | |
| | | full_script_text = await loop.run_in_executor(None, self._cancellable_query, llm, prompt, [], llm_model, True, sid, web_search) |
| | | logger.info(f"[ScriptWriter] Full script generated ({len(full_script_text)} chars)") |
| | | _log_progress(40, "鍘熺鐢熸垚瀹屾垚锛屾鍦ㄦ彁鍙栧厓鏁版嵁...") |
| | | |
| | | # 2. Extract meta data -> total_episodes, characters, settings |
| | | meta_prompt = _get_script_prompt("meta_extract", "zh" if is_zh else "en").format(script_text=full_script_text, outline=full_script_text) |
| | | meta_raw = await loop.run_in_executor(None, self._cancellable_query, llm, meta_prompt, [], llm_model, True, sid, web_search) |
| | | meta_data = self._extract_json_from_text(meta_raw) or {} |
| | | |
| | | all_characters = meta_data.get("characters", []) |
| | | all_settings = meta_data.get("settings", []) |
| | | for c in all_characters: |
| | | c["character_id"] = c.get("character_id") or self._gen_id("char") |
| | | for s in all_settings: |
| | | s["setting_id"] = s.get("setting_id") or self._gen_id("set") |
| | | |
| | | asset_chars_str = json.dumps([{"name": c.get("name"), "description": c.get("description"), "role": c.get("role")} for c in all_characters], ensure_ascii=False) |
| | | asset_sets_str = json.dumps([{"name": s.get("name"), "description": s.get("description")} for s in all_settings], ensure_ascii=False) |
| | | |
| | | _log_progress(50, "姝e湪瑙f瀽鍚勯泦鏁版嵁...") |