3 files deleted
18 files modified
| | |
| | | # CLAUDE.md |
| | | # CLAUDE.md |
| | | |
| | | This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. |
| | | |
| | |
| | | ## Architecture |
| | | |
| | | ### Backend Core |
| | | - **[orchestrator.py](aigc-claw/backend/core/orchestrator.py)**: Workflow engine managing the 6-stage state machine. Controls session state (idle/running/waiting_in_stage/stage_completed/session_completed), persists to `aigc-claw/backend/code/data/sessions/`, and coordinates agent execution. |
| | | - **[orchestrator.py](aigc-claw/backend/core/orchestrator.py)**: Workflow engine managing the 6-stage state machine. Controls session state (pending/running/waiting/completed/completed), persists to `aigc-claw/backend/code/data/sessions/`, and coordinates agent execution. |
| | | |
| | | - **[base_agent.py](aigc-claw/backend/core/agents/base_agent.py)**: Abstract base class for all stage agents. Defines `process(input_data, intervention)` interface that returns `{"payload": ..., "requires_intervention": bool, "stage_completed": bool}`. |
| | | - **[base_agent.py](aigc-claw/backend/core/agents/base_agent.py)**: Abstract base class for all stage agents. Defines `process(input_data, intervention)` interface that returns `{"payload": ..., "requires_intervention": bool, "completed": bool}`. |
| | | |
| | | ### 6 Stage Agents |
| | | Each agent handles one workflow stage: |
| | |
| | | --- |
| | | --- |
| | | name: aigc-director |
| | | description: AI 视频生成全流程:通过 6 个阶段(剧本→角色/场景设计→分镜→参考图→视频生成→后期剪辑)将用户想法转化为完整视频。支持临时工作台(单独调用 LLM、VLM、文生图、图生图、视频生成)。触发词:视频生成、AI视频、AIGC、创作视频、制作视频、AI画图。 |
| | | license: MIT License |
| | |
| | | |
| | | ## 🚨 停点处理(强制规则) |
| | | |
| | | **当查询状态为 `stage_completed` 或 `waiting_in_stage` 时,必须按以下步骤执行:** |
| | | **当查询状态为 `completed` 或 `waiting` 时,必须按以下步骤执行:** |
| | | |
| | | ### 步骤1:获取产物 |
| | | ```bash |
| | |
| | | ### ✅ 正确示例 |
| | | ``` |
| | | 1. 阶段中间遇到不确定内容 |
| | | 收到 waiting_in_stage 停点 |
| | | 收到 waiting 停点 |
| | | → 获取 artifact 查看内容 |
| | | → 展示给用户选项 |
| | | → 询问:"是否同意修改?" |
| | | → 用户回复"同意" → 调用 intervene |
| | | |
| | | 2. 阶段完成停点触发 |
| | | 收到 stage_completed 停点 |
| | | 收到 completed 停点 |
| | | → 获取 artifact 查看产物内容 |
| | | → 展示给用户:"第一阶段已完成,生成了剧本内容(x集)..." |
| | | → 询问:"是否继续下一阶段?" |
| | |
| | | |
| | | | status | 含义 | 操作 | |
| | | |--------|------|------| |
| | | | idle | 新建会话 | 启动项目 | |
| | | | pending | 新建会话 | 启动项目 | |
| | | | running | 执行中 | 轮询等待 | |
| | | | waiting_in_stage | 等待用户介入 | 调用 `intervene` | |
| | | | stage_completed | 阶段完成 | 调用 `continue` | |
| | | | session_completed | 全部完成 | 结束 | |
| | | | waiting | 等待用户介入 | 调用 `intervene` | |
| | | | completed | 阶段完成 | 调用 `continue` | |
| | | | completed | 全部完成 | 结束 | |
| | | |
| | | > **注意**:只有 status 变化时才需要干预,不要反复调用 artifact API 去"确认"! |
| | | |
| | |
| | | session_id = str(int(time.time() * 1000)) |
| | | state = workflow_engine.get_or_create_state(session_id) |
| | | state.started_at = __import__('datetime').datetime.now() |
| | | state.status = "stage_completed" |
| | | if not isinstance(state.status, dict): |
| | | state.status = {} |
| | | state.status[state.current_stage.value] = "completed" |
| | | |
| | | # 保存会话元数据(未传参数时使用 config.py 中的默认值) |
| | | meta = { |
| | |
| | | if 'is_new' in shot: |
| | | shot['is_new'] = False |
| | | |
| | | # 同步到 video_generation |
| | | shot_id_to_duration = {s['shot_id']: s.get('duration', 10) for s in body['shots'] if 'shot_id' in s} |
| | | shot_id_to_plot = {s['shot_id']: s.get('plot', '') for s in body['shots'] if 'shot_id' in s} |
| | | # 从 body['segments'] 提取同步信息(修改后的逻辑按 segment 同步) |
| | | seg_info_list = [] |
| | | for seg in body.get('segments', []): |
| | | seg_id = seg.get('segment_id') |
| | | if not seg_id: continue |
| | | |
| | | shots = seg.get('shots', []) |
| | | desc_video = " ".join([sh.get("plot") or sh.get("content") or "" for sh in shots]).strip() |
| | | total_dur = seg.get("total_duration") or sum([sh.get("duration", 0) for sh in shots]) or 10 |
| | | |
| | | seg_info_list.append({ |
| | | "segment_id": seg_id, |
| | | "desc": desc_video, |
| | | "duration": total_dur |
| | | }) |
| | | |
| | | # 同步到 video_generation |
| | | video_art = state.artifacts.get('video_generation', {}) |
| | | if isinstance(video_art, dict) and 'clips' in video_art: |
| | | for clip in video_art['clips']: |
| | | shot_id = clip.get('id') |
| | | if shot_id in shot_id_to_duration: |
| | | clip['duration'] = shot_id_to_duration[shot_id] |
| | | if shot_id in shot_id_to_plot: |
| | | clip['description'] = shot_id_to_plot[shot_id] |
| | | c_id = clip.get('id') |
| | | # 匹配 segment_id |
| | | target = next((item for item in seg_info_list if item["segment_id"] == c_id), None) |
| | | if target: |
| | | clip['duration'] = target['duration'] |
| | | clip['description'] = target['desc'] |
| | | |
| | | # 移除 shots,避免覆盖 storyboard artifact |
| | | body = {k: v for k, v in body.items() if k != "shots"} |
| | | # 移除 segments,避免覆盖 storyboard artifact |
| | | body = {k: v for k, v in body.items() if k != "segments"} |
| | | |
| | | # 清除 new_shot_ids 标记 |
| | | if "new_shot_ids" in body and body.get('new_shot_ids') == []: |
| | | if "new_shot_ids" in body: |
| | | del body['new_shot_ids'] |
| | | |
| | | # ══════════════════════════════════════════════════════════════ |
| | |
| | | first_frame_prompts[segment_id] = ff_prompt |
| | | logger.info(f"[{segment_id}] Prompt ready, starting image generation...") |
| | | |
| | | # 2. 立即提交图像生成任务,不再等待其他片段的提示词 |
| | | # 2. 发送任务开始状态 (Running),以便前端 UI 立即显示加载状态 |
| | | self._report_progress("参考图", f"正在启动: {segment_id}", calc_pct(i * steps_per_segment), data={ |
| | | "asset_complete": { |
| | | "type": "scenes", "id": segment_id, |
| | | "status": "running" |
| | | } |
| | | }) |
| | | |
| | | # 3. 立即提交图像生成任务,不再等待其他片段的提示词 |
| | | refs = self._collect_refs(seg, asset_map, char_id_map, setting_id_map) |
| | | fut = executor.submit( |
| | | self._generate_one, img_client, sid, |
| | |
| | | futs[fut] = segment_id |
| | | |
| | | # 报告进度(提交任务也算一点进度) |
| | | self._report_progress("参考图", f"正在生成: {segment_id}", calc_pct(i * steps_per_segment)) |
| | | self._report_progress("参考图", f"等待生成: {segment_id}", calc_pct(i * steps_per_segment)) |
| | | |
| | | # 3. 等待所有任务完成 |
| | | # 4. 等待所有任务完成 |
| | | cancelled = False |
| | | for fut in as_completed(futs): |
| | | segment_id_done = futs[fut] |
| | |
| | | from prompts.loader import load_prompt_with_fallback |
| | | return load_prompt_with_fallback("storyboard", "shot", 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") |
| | | |
| | | class StoryboardAgent(AgentInterface): |
| | | def __init__(self): |
| | | super().__init__(name="Storyboard") |
| | |
| | | |
| | | if not extracted: |
| | | logger.error(f"LLM output failed to parse as JSON for Episode {ep_n} after {max_retries} attempts. Raw: {raw}") |
| | | return { |
| | | "episode_number": ep_n, |
| | | "episode_title": ep_t, |
| | | "segments": [] |
| | | } |
| | | # 抛出异常以触发 orchestrator 的错误状态处理逻辑 |
| | | raise Exception(f"第 {ep_n} 集分镜生成失败:模型输出无法解析") |
| | | |
| | | # 我们直接手动处理 segments |
| | | 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 |
| | |
| | | "duration": dur, |
| | | "content": s.get("content", "") |
| | | }) |
| | | |
| | | valid_segments.append({ |
| | | "segment_id": f"seg_{ep_n:02d}_{i:02d}", |
| | | "segment_number": i, |
| | | "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", []), |
| | | "total_duration": seg.get("total_duration", calc_total_duration), |
| | | "shots": valid_shots, |
| | | "episode_number": ep_n |
| | | }) |
| | |
| | | "segments": valid_segments |
| | | } |
| | | |
| | | # 并发处理新增集数 |
| | | new_story_results = await asyncio.gather(*(proc_ep(ep) for ep in episodes_to_proc)) |
| | | |
| | | # 合并旧数据和新数据 |
| | | # 核心:支持流式保存增量产物,让前端能看到实时进度 |
| | | updated_ep_map = {e["episode_number"]: e for e in existing_story_eps} |
| | | for res in new_story_results: |
| | | |
| | | # 立即先保存一次,确保已有的 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"]) |
| | | |
| | |
| | | "created_at": datetime.now().isoformat() |
| | | } |
| | | |
| | | # 更新会话状态 |
| | | if "storyboard" not in session_data.get("stages_completed", []): |
| | | session_data.setdefault("stages_completed", []).append("storyboard") |
| | | session_data["status"] = "stage_completed" |
| | | session_data["updated_at"] = datetime.now().timestamp() |
| | | |
| | | with open(session_file, "w", encoding="utf-8") as f: |
| | |
| | | with ThreadPoolExecutor(max_workers=concurrency) as executor: |
| | | futs = {} |
| | | for seg_id, prompt, img_path, dur in tasks: |
| | | # 提交前立即发送正在运行的状态,让前端 UI 更新 |
| | | self._report_progress("视频生成", f"启动生成: {seg_id}", 5, data={ |
| | | "asset_complete": { |
| | | "type": "clips", "id": seg_id, |
| | | "status": "running" |
| | | } |
| | | }) |
| | | fut = executor.submit( |
| | | self._generate_one, sid, seg_id, prompt, |
| | | img_path, video_model, dur, |
| | |
| | | # -*- coding: utf-8 -*- |
| | | # -*- coding: utf-8 -*- |
| | | """ |
| | | 核心编排器 / 工作流引擎 |
| | | 管理六阶段状态机,协调各智能体执行,支持用户在任意阶段介入 |
| | |
| | | REFERENCE_GENERATION = "reference_generation" |
| | | VIDEO_GENERATION = "video_generation" |
| | | POST_PRODUCTION = "post_production" |
| | | COMPLETED = "session_completed" |
| | | COMPLETED = "completed" |
| | | |
| | | |
| | | STAGE_ORDER = [ |
| | |
| | | """工作流状态""" |
| | | |
| | | # 状态说明: |
| | | # - idle: 新建会话,还没有任何数据,也没有在运行 |
| | | # - pending: 新建会话,还没有任何数据,也没有在运行 |
| | | # - running: 会话正在运行 |
| | | # - waiting_in_stage: 会话在某一阶段内等待用户介入(如选择角色、选择图片等) |
| | | # - stage_completed: 会话完成了某一阶段,等待用户确定开始下一阶段 |
| | | # - session_completed: 会话全部完成 |
| | | # - waiting: 会话在某一阶段内等待用户介入(如选择角色、选择图片等) |
| | | # - completed: 会话完成了某一阶段,等待用户确定开始下一阶段 |
| | | # - completed: 会话全部完成 |
| | | # - stopped: 用户手动停止 |
| | | # - error: 执行中遇到错误 |
| | | |
| | | def __init__(self, session_id: str): |
| | | self.session_id = session_id |
| | | self.current_stage: WorkflowStage = WorkflowStage.INIT |
| | | self.status: str = "idle" |
| | | self.stages_completed: List[str] = [] # 已完成的阶段列表 |
| | | self.status: Dict[str, str] = { |
| | | stage.value: "pending" for stage in WorkflowStage if stage != WorkflowStage.INIT and stage != WorkflowStage.COMPLETED |
| | | } |
| | | self.artifacts: Dict[str, Any] = {} |
| | | self.error: Optional[str] = None |
| | | self.started_at: Optional[datetime] = None |
| | |
| | | "current_stage": self.current_stage.value, |
| | | "status": self.status, |
| | | "error": self.error, |
| | | "stages_completed": self.stages_completed, |
| | | "artifacts": self.artifacts, |
| | | "meta": self.meta, |
| | | "updated_at": self.updated_at, |
| | |
| | | |
| | | # 从磁盘数据恢复 WorkflowState |
| | | state = WorkflowState(session_id=session_id) |
| | | state.status = data.get('status', 'idle') |
| | | |
| | | stage_str = data.get('current_stage') |
| | | state.current_stage = WorkflowStage(stage_str) if stage_str else WorkflowStage.INIT |
| | | state.stages_completed = data.get('stages_completed', []) |
| | | |
| | | loaded_status = data.get('status') |
| | | if isinstance(loaded_status, str): |
| | | stages_completed = data.get('stages_completed', []) |
| | | for stage in WorkflowStage: |
| | | if stage != WorkflowStage.INIT and stage != WorkflowStage.COMPLETED: |
| | | if stage.value in stages_completed: |
| | | state.status[stage.value] = "completed" |
| | | elif stage.value == state.current_stage.value: |
| | | state.status[stage.value] = loaded_status |
| | | else: |
| | | state.status[stage.value] = "pending" |
| | | elif isinstance(loaded_status, dict): |
| | | state.status = loaded_status |
| | | |
| | | state.artifacts = data.get('artifacts', {}) |
| | | state.meta = data.get('meta', {}) |
| | | state.updated_at = data.get('updated_at', 0) |
| | |
| | | def stop_session(self, session_id: str): |
| | | self.get_stop_event(session_id).set() |
| | | state = self.get_state(session_id) |
| | | if state and state.status == "running": |
| | | state.status = "stopped" |
| | | if state and state.status.get(state.current_stage.value) == "running": |
| | | state.status[state.current_stage.value] = "stopped" |
| | | state.error = None # 清除错误,因为是主动停止 |
| | | state.updated_at = datetime.now() |
| | | self.save_session_to_disk(session_id) |
| | |
| | | story_art["episodes"] = existing_eps |
| | | state.artifacts[story_stage_key] = story_art |
| | | |
| | | # 案例 2: 分镜生成或修改同步到第四、第五阶段 (Storyboard -> Ref/Video) |
| | | if stage == WorkflowStage.STORYBOARD: |
| | | episodes = payload.get("episodes", []) if isinstance(payload, dict) else payload |
| | | if not isinstance(episodes, list): |
| | | return |
| | | |
| | | all_sync_clips = [] |
| | | for ep in episodes: |
| | | if not isinstance(ep, dict): continue |
| | | ep_n = ep.get("episode_number", 0) |
| | | for s_i, seg in enumerate(ep.get("segments", []), 1): |
| | | if not isinstance(seg, dict): continue |
| | | seg_id = seg.get("segment_id", f"seg_{ep_n:02d}_{s_i:02d}") |
| | | |
| | | # 汇总 segment 级别的描述和时长 |
| | | shots = seg.get("shots", []) |
| | | desc_video = " ".join([sh.get("plot") or sh.get("content") or "" for sh in shots]).strip() |
| | | desc_ref = " ".join([sh.get("visual_prompt") or sh.get("plot") or sh.get("content") or "" for sh in shots]).strip() |
| | | total_dur = seg.get("total_duration") or sum([sh.get("duration", 0) for sh in shots]) or 10 |
| | | |
| | | all_sync_clips.append({ |
| | | "segment_id": seg_id, |
| | | "desc_video": desc_video, |
| | | "desc_ref": desc_ref, |
| | | "duration": total_dur, |
| | | "episode": ep_n, |
| | | "index": s_i, |
| | | "name": f"第{ep_n}集-片段{s_i}" |
| | | }) |
| | | |
| | | if not all_sync_clips: |
| | | return |
| | | |
| | | # (A) 同步到第四阶段 (参考图生成) |
| | | ref_stage_key = WorkflowStage.REFERENCE_GENERATION.value |
| | | ref_art = state.artifacts.get(ref_stage_key) |
| | | if not isinstance(ref_art, dict): |
| | | ref_art = {"scenes": [], "version": 1} |
| | | |
| | | existing_scenes = ref_art.get("scenes", []) |
| | | for c_info in all_sync_clips: |
| | | id = c_info["segment_id"] |
| | | idx = next((i for i, s in enumerate(existing_scenes) if s.get("id") == id), -1) |
| | | if idx == -1: |
| | | existing_scenes.append({ |
| | | "id": id, |
| | | "name": c_info["name"], |
| | | "index": c_info["index"], |
| | | "description": c_info["desc_ref"], |
| | | "selected": "", |
| | | "versions": [], |
| | | "status": "pending", |
| | | "episode": c_info["episode"] |
| | | }) |
| | | else: |
| | | # 更新已有记录 |
| | | existing_scenes[idx]["description"] = c_info["desc_ref"] |
| | | existing_scenes[idx]["episode"] = c_info["episode"] |
| | | existing_scenes[idx]["index"] = c_info["index"] |
| | | existing_scenes[idx]["name"] = c_info["name"] |
| | | |
| | | # 排序:确保片段显示顺序正确 (按 id 排序,例如 seg_01_01 < seg_07_01) |
| | | existing_scenes.sort(key=lambda x: x.get("id", "")) |
| | | ref_art["scenes"] = existing_scenes |
| | | state.artifacts[ref_stage_key] = ref_art |
| | | |
| | | # (B) 同步到第五阶段 (视频生成) |
| | | video_stage_key = WorkflowStage.VIDEO_GENERATION.value |
| | | video_art = state.artifacts.get(video_stage_key) |
| | | if not isinstance(video_art, dict): |
| | | video_art = {"clips": [], "version": 1} |
| | | |
| | | existing_clips = video_art.get("clips", []) |
| | | for c_info in all_sync_clips: |
| | | id = c_info["segment_id"] |
| | | idx = next((i for i, c in enumerate(existing_clips) if c.get("id") == id), -1) |
| | | if idx == -1: |
| | | existing_clips.append({ |
| | | "id": id, |
| | | "name": c_info["name"], |
| | | "index": c_info["index"], |
| | | "description": c_info["desc_video"], |
| | | "duration": c_info["duration"], |
| | | "selected": "", |
| | | "versions": [], |
| | | "status": "pending", |
| | | "episode": c_info["episode"] |
| | | }) |
| | | else: |
| | | existing_clips[idx]["description"] = c_info["desc_video"] |
| | | existing_clips[idx]["duration"] = c_info["duration"] |
| | | existing_clips[idx]["episode"] = c_info["episode"] |
| | | existing_clips[idx]["index"] = c_info["index"] |
| | | existing_clips[idx]["name"] = c_info["name"] |
| | | |
| | | # 排序:确保片段显示顺序正确 |
| | | existing_clips.sort(key=lambda x: x.get("id", "")) |
| | | video_art["clips"] = existing_clips |
| | | state.artifacts[video_stage_key] = video_art |
| | | |
| | | def _recalculate_all_statuses(self, state: WorkflowState): |
| | | """ |
| | | 根据各阶段 artifacts 的数据完整性重新计算 status 字典。 |
| | | 逻辑: |
| | | - 如果 artifacts[stage] 不存在: pending |
| | | - 如果存在且包含核心列表(characters/scenes/clips等): |
| | | - 如果列表项存在 selected 为空的情况: waiting |
| | | - 如果列表项全部已选择(或不需要选择): completed |
| | | """ |
| | | for stage in WorkflowStage: |
| | | if stage in [WorkflowStage.INIT, WorkflowStage.COMPLETED]: |
| | | continue |
| | | s_val = stage.value |
| | | # 如果当前阶段正在运行,不自动覆盖其为 completed/waiting (除非它目前是空) |
| | | current_s_status = state.status.get(s_val, "pending") |
| | | if current_s_status == "running" or current_s_status == "error": |
| | | continue |
| | | |
| | | art = state.artifacts.get(s_val) |
| | | if not art or not isinstance(art, dict): |
| | | state.status[s_val] = "pending" |
| | | continue |
| | | |
| | | # 检查是否有待处理的“空数据占位” |
| | | has_pending = False |
| | | |
| | | if s_val == "character_design": |
| | | chars = art.get("characters", []) |
| | | sets = art.get("settings", []) |
| | | if any(not c.get("selected") for c in chars) or any(not s.get("selected") for s in sets): |
| | | has_pending = True |
| | | elif s_val == "storyboard": |
| | | # 检查分镜阶段:如果存在剧集(episode)但其 segments 为空,视为 waiting |
| | | episodes = art.get("episodes", []) |
| | | if not episodes or any(not ep.get("segments") for ep in episodes): |
| | | has_pending = True |
| | | elif s_val == "reference_generation": |
| | | scenes = art.get("scenes", []) |
| | | if not scenes or any(not s.get("selected") for s in scenes): |
| | | has_pending = True |
| | | elif s_val == "video_generation": |
| | | clips = art.get("clips", []) |
| | | if not clips or any(not c.get("selected") for c in clips): |
| | | has_pending = True |
| | | |
| | | if has_pending: |
| | | state.status[s_val] = "waiting" |
| | | else: |
| | | # 已经有数据且没有 pending 项,标记为完成 |
| | | state.status[s_val] = "completed" |
| | | |
| | | async def execute_stage(self, |
| | | state: WorkflowState, |
| | | stage: WorkflowStage, |
| | |
| | | agent.set_progress_callback(wrapped_progress_callback) |
| | | |
| | | state.current_stage = stage |
| | | state.status = "running" |
| | | state.status[stage.value] = "running" |
| | | state.updated_at = datetime.now() |
| | | |
| | | try: |
| | |
| | | self._sync_artifacts_cross_stages(state, stage, payload) |
| | | state.artifacts[stage.value] = payload |
| | | |
| | | # 只有在 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) |
| | | for s in modified_shots if s.get('shot_id')} |
| | | shot_visual_prompts = {s.get('shot_id'): s.get('visual_prompt', '') |
| | | for s in modified_shots if s.get('shot_id')} |
| | | shot_plots = {s.get('shot_id'): s.get('plot', '') |
| | | for s in modified_shots if s.get('shot_id')} |
| | | |
| | | # 1. 同步 duration 到第五阶段 clips |
| | | video_art = state.artifacts.get('video_generation', {}) |
| | | if isinstance(video_art, dict) and 'clips' in video_art: |
| | | for clip in video_art['clips']: |
| | | shot_id = clip.get('id') |
| | | if shot_id in shot_durations: |
| | | clip['duration'] = shot_durations[shot_id] |
| | | if shot_id in shot_plots: |
| | | clip['description'] = shot_plots[shot_id] |
| | | |
| | | # 2. 同步 visual_prompt 到第四阶段 scenes (description) |
| | | ref_art = state.artifacts.get('reference_generation', {}) |
| | | if isinstance(ref_art, dict) and 'scenes' in ref_art: |
| | | for scene in ref_art['scenes']: |
| | | shot_id = scene.get('id') |
| | | if shot_id in shot_visual_prompts: |
| | | scene['description'] = shot_visual_prompts[shot_id] |
| | | |
| | | # 3. 新增分镜:同步到第四、第五阶段 |
| | | existing_shot_ids = {clip.get('id') for clip in video_art.get('clips', [])} if isinstance(video_art, dict) else set() |
| | | existing_scene_ids = {scene.get('id') for scene in ref_art.get('scenes', [])} if isinstance(ref_art, dict) else set() |
| | | |
| | | for shot in modified_shots: |
| | | shot_id = shot.get('shot_id') |
| | | if not shot_id: |
| | | continue |
| | | # 新增到第五阶段 |
| | | if shot_id not in existing_shot_ids: |
| | | if isinstance(video_art, dict): |
| | | video_art.setdefault('clips', []).append({ |
| | | 'id': shot_id, |
| | | 'name': f"镜头{shot_id.split('_')[-1]}", |
| | | 'description': shot.get('plot', ''), |
| | | 'duration': shot.get('duration', 10), |
| | | 'selected': '', |
| | | 'versions': [], |
| | | 'status': 'pending' |
| | | }) |
| | | # 新增到第四阶段 |
| | | if shot_id not in existing_scene_ids: |
| | | if isinstance(ref_art, dict): |
| | | ref_art.setdefault('scenes', []).append({ |
| | | 'id': shot_id, |
| | | 'name': f"场景{shot_id.split('_')[-2]}", |
| | | 'description': shot.get('visual_prompt', ''), |
| | | 'selected': '', |
| | | 'versions': [], |
| | | 'status': 'pending' |
| | | }) |
| | | |
| | | logger.info(f"Synced stage 3 modifications: {len(shot_durations)} durations, {len(shot_visual_prompts)} prompts") |
| | | |
| | | # 调试日志 |
| | | logger.info(f"[execute_stage] stage={stage.value}, intervention={intervention is not None}, requires_intervention={result.get('requires_intervention')}, stage_completed={result.get('stage_completed')}") |
| | | |
| | | # 状态转换逻辑: |
| | | # - stage_completed=True: 阶段已完成,等待用户确认进入下一阶段 |
| | | # - requires_intervention=True: 阶段内需要用户介入(如选择图片等) |
| | | # - 其他(running):阶段正在执行中 |
| | | if result.get("stage_completed"): |
| | | # 阶段真正完成,标记到已完成的列表 |
| | | if stage.value not in state.stages_completed: |
| | | state.stages_completed.append(stage.value) |
| | | # 如果是最后一个阶段,设置为 session_completed |
| | | if stage == WorkflowStage.POST_PRODUCTION: |
| | | state.status = "session_completed" |
| | | else: |
| | | state.status = "stage_completed" |
| | | # 重新计算所有阶段的状态(基于 artifacts 里的数据完整性) |
| | | self._recalculate_all_statuses(state) |
| | | |
| | | # 如果 result 明确标记了完成且不是干预,则可能需要覆盖为 completed (除非 recalculate 认为是 waiting) |
| | | if result.get("stage_completed") and not result.get("requires_intervention"): |
| | | # 如果 recalculate 没把它设为 waiting,就设为 completed |
| | | if state.status.get(stage.value) != "waiting": |
| | | state.status[stage.value] = "completed" |
| | | elif result.get("requires_intervention"): |
| | | # 阶段内需要用户介入,等待用户选择 |
| | | state.status = "waiting_in_stage" |
| | | else: |
| | | # 阶段正在执行中(中间步骤),保持 running |
| | | state.status = "running" |
| | | state.status[stage.value] = "waiting" |
| | | |
| | | state.updated_at = datetime.now() |
| | | # 立即保存状态到磁盘,确保前端能获取到最新状态 |
| | |
| | | return result |
| | | |
| | | except Exception as e: |
| | | state.status = "error" |
| | | state.status[stage.value] = "error" |
| | | state.error = str(e) |
| | | state.updated_at = datetime.now() |
| | | # 确保保存错误状态 |
| | | self.save_session_to_disk(state.session_id) |
| | | raise |
| | | |
| | | async def handle_intervention(self, |
| | |
| | | input_data = current_artifact if isinstance(current_artifact, dict) else {} |
| | | input_data.update(modifications) |
| | | |
| | | return await self.execute_stage(state, stage_enum, input_data, intervention=modifications) |
| | | res = await self.execute_stage(state, stage_enum, input_data, intervention=modifications) |
| | | # 处理完干预后再次校验状态 |
| | | self._recalculate_all_statuses(state) |
| | | self.save_session_to_disk(session_id) |
| | | return res |
| | | |
| | | async def continue_workflow(self, session_id: str) -> Dict: |
| | | state = self.sessions[session_id] |
| | | logger.info(f"[continue_workflow] session={session_id}, current_stage={state.current_stage}, status={state.status}") |
| | | |
| | | # 检查当前阶段是否已完成 |
| | | current_stage_str = state.current_stage.value if hasattr(state.current_stage, 'value') else str(state.current_stage) |
| | | # 检查当前状态是否已完成 |
| | | current_stage_str = state.current_stage.value if hasattr(state.current_stage, "value") else str(state.current_stage) |
| | | |
| | | # 在继续之前,先重新扫描一次状态,确保最新的选择已被计入 |
| | | self._recalculate_all_statuses(state) |
| | | |
| | | # 如果当前状态是 running,说明阶段还在执行中,不能继续 |
| | | if state.status == "running": |
| | | if state.status.get(current_stage_str) == "running": |
| | | return { |
| | | "status": "waiting", |
| | | "openclaw": f"当前阶段({current_stage_str})还在执行中,请等待完成后再调用 /continue。", |
| | | "message": f"当前阶段({current_stage_str})还在执行中,请等待完成后再调用 /continue。", |
| | | "current_status": state.status, |
| | | "current_status": "running", |
| | | } |
| | | |
| | | # 状态转换逻辑: |
| | | # - waiting_in_stage 或 stage_completed: 用户确认后直接进入下一阶段 |
| | | # 注意:只有当阶段真正完成(waiting_in_stage 或 stage_completed)时才允许继续 |
| | | # - waiting 或 completed: 用户确认后直接进入下一阶段 |
| | | # 如果是 waiting,可能需要阻止进入下一阶段,除非业务允许强制通过 |
| | | # 这里我们遵循用户逻辑:如果有空数据,显示为 waiting,用户需要解决它才能真正 completed。 |
| | | if state.status.get(current_stage_str) == "waiting": |
| | | # 如果是 waiting 状态,通常不应该自动跳到下一阶段 |
| | | # 但如果用户点击了“继续”,可能是想补全或者强制进入 |
| | | pass |
| | | # 注意:只有当阶段真正完成(waiting 或 completed)时才允许继续 |
| | | |
| | | if state.status == "waiting_in_stage" or state.status == "stage_completed": |
| | | # 用户确认后标记阶段完成 |
| | | if current_stage_str not in state.stages_completed: |
| | | state.stages_completed.append(current_stage_str) |
| | | |
| | | current_status = state.status.get(current_stage_str) |
| | | if current_status == "waiting" or current_status == "completed": |
| | | # 直接进入下一阶段 |
| | | state.status = "running" |
| | | state.status[current_stage_str] = "completed" |
| | | next_stage = self._get_next_stage(state.current_stage) |
| | | |
| | | if not next_stage: |
| | | state.status = "session_completed" |
| | | state.status[current_stage_str] = "completed" |
| | | self.save_session_to_disk(state.session_id) |
| | | return {"status": "session_completed"} |
| | | return {"status": "completed", "session_id": state.session_id, "status_map": state.status} |
| | | |
| | | self.save_session_to_disk(state.session_id) |
| | | return {"status": "ready", "next_stage": next_stage.value} |
| | | return {"status": "ready", "next_stage": next_stage.value, "session_id": state.session_id, "status_map": state.status} |
| | | |
| | | # 其他状态(如 idle, stopped, error, session_completed)不允许继续 |
| | | # 其他状态(如 pending, stopped, error, completed)不允许继续 |
| | | return { |
| | | "status": "error", |
| | | "openclaw": f"当前状态 {state.status} 不允许继续,请检查会话状态。", |
| | | "openclaw": f"当前状态 {current_status} 不允许继续,请检查会话状态。", |
| | | "message": f"当前状态不允许继续", |
| | | "current_status": state.status, |
| | | "current_status": current_status, |
| | | } |
| | | |
| | | # ──────────── 会话持久化 ──────────── |
| | |
| | | if state: |
| | | data["current_stage"] = state.current_stage.value |
| | | data["status"] = state.status |
| | | data["stages_completed"] = state.stages_completed |
| | | # 这里的 state.artifacts 应该是已经经过 _sync_artifacts_cross_stages 处理的最新的内存对象 |
| | | data["artifacts"] = state.artifacts |
| | | data["error"] = state.error |
| | |
| | | state.current_stage = WorkflowStage(data.get("current_stage", "init")) |
| | | except ValueError: |
| | | state.current_stage = WorkflowStage.INIT |
| | | # 旧版本兼容:状态名称转换 |
| | | old_status = data.get("status", "idle") |
| | | |
| | | # 旧版本兼容:状态名称转换及迁移 |
| | | old_status = data.get("status", "pending") |
| | | if isinstance(old_status, str): |
| | | if old_status == "waiting_intervention": |
| | | state.status = "waiting_in_stage" |
| | | old_status = "waiting" |
| | | elif old_status == "completed": |
| | | state.status = "session_completed" |
| | | old_status = "completed" |
| | | |
| | | stages_completed = data.get("stages_completed", []) |
| | | for stage in WorkflowStage: |
| | | if stage != WorkflowStage.INIT and stage != WorkflowStage.COMPLETED: |
| | | if stage.value in stages_completed: |
| | | state.status[stage.value] = "completed" |
| | | elif stage.value == state.current_stage.value: |
| | | state.status[stage.value] = old_status |
| | | else: |
| | | state.status[stage.value] = "pending" |
| | | elif isinstance(old_status, dict): |
| | | state.status = old_status |
| | | |
| | | state.stages_completed = data.get("stages_completed", []) |
| | | state.artifacts = data.get("artifacts", {}) |
| | | state.error = data.get("error") |
| | | state.updated_at = data.get("updated_at", 0) |
| | |
| | | "idea": data.get("idea", ""), |
| | | "style": data.get("style", ""), |
| | | "date": data.get("updated_at", 0), |
| | | "stages": data.get("stages_completed", []), |
| | | "status": data.get("status", {}), |
| | | }) |
| | | except Exception: |
| | | continue |
| | |
| | | |
| | | **注意(严格遵守):** |
| | | 1. **输出格式**:必须且仅能输出一个纯净的 JSON 对象。严禁包含任何 Markdown 格式(如 ```json 代码块)、解释性文字、开场白或结尾。 |
| | | 2. 提取所有在剧本中出现的、有台词或重要动作的【角色】(不仅仅是主角)。 |
| | | 2. 提取所有在剧本中出现的、有台词或重要动作的【角色】(不仅仅是主角),但是注意不要提取群体角色(如:若干员工、一些顾客)。 |
| | | 3. 提取所有在剧本中具体描述过的、不同地理位置的【场景】(不仅仅是概括性的)。 |
| | | 4. 角色描述: |
| | | - 采用“年龄+性别+发型/首饰+服装+体型+面部特征/神态”的概括性写法。 |
| | |
| | | 你是一台专业的 JSON 生成器。请根据输入的集数描述,拆分为一系列极具视觉表现力的“拍摄片段”(Segments),并规划详细的“分镜列表”(Shots)。 |
| | | 你是一台专业的拍摄片段设计师。请根据输入的集数描述,拆分为一系列极具视觉表现力的“拍摄片段”(Segments),并规划详细的“分镜列表”(Shots)。 |
| | | |
| | | ### 核心任务 |
| | | 剧本中每一行描述对应一个分镜。若干分镜组合成一个拍摄片段。 |
| | |
| | | --- |
| | | |
| | | 【输出格式示例(仅返回此 JSON 数组)】 |
| | | |
| | | [ |
| | | {{ |
| | | "segment_number": 1, |
| | |
| | | ] |
| | | }} |
| | | ] |
| | | |
| | | 注意,返回的json数组不要用 “```json” 包裹 |
| | |
| | | style?: string; |
| | | date: string; |
| | | status: string; |
| | | stages?: string[]; |
| | | stages?: Record<string, string>; |
| | | } |
| | | |
| | | interface HomePageProps { |
| | |
| | | history: HistoryItem[]; |
| | | } |
| | | |
| | | /* 根据 stages_completed 生成进度文本 */ |
| | | function stageProgressLabel(stages?: string[]): { text: string; color: string } { |
| | | if (!stages || stages.length === 0) return { text: '未开始', color: 'text-gray-400' }; |
| | | if (stages.length >= STAGES.length) return { text: '已完成', color: 'text-green-600' }; |
| | | // 显示最后完成的阶段名称 |
| | | const lastStageId = stages[stages.length - 1]; |
| | | /* 根据 status 映射生成进度文本 */ |
| | | function stageProgressLabel(statusMap?: Record<string, string>): { text: string; color: string } { |
| | | const map = statusMap || {}; |
| | | const completed = Object.keys(map).filter(k => ["completed", "session_completed"].includes(map[k])); |
| | | if (completed.length === 0) return { text: '未开始', color: 'text-gray-400' }; |
| | | if (completed.length >= STAGES.length) return { text: '已完成', color: 'text-green-600' }; |
| | | |
| | | // 对比 STAGES 获取最后一个已完成的 |
| | | const lastStageId = STAGES.filter(s => completed.includes(s.id)).pop()?.id || completed[completed.length - 1]; |
| | | const stageDef = STAGES.find(s => s.id === lastStageId); |
| | | const name = stageDef?.shortName || lastStageId; |
| | | return { text: `已完成: ${name} (${stages.length}/${STAGES.length})`, color: 'text-blue-600' }; |
| | | return { text: `已完成: ${name} (${completed.length}/${STAGES.length})`, color: 'text-blue-600' }; |
| | | } |
| | | |
| | | export default function HomePage({ onStartProject, onResumeProject, onDeleteSession, history }: HomePageProps) { |
| | |
| | | <span className="text-[10px] text-gray-400">{item.date}</span> |
| | | </div> |
| | | <div className={`flex items-center gap-1 mt-1.5 text-[10px] font-medium ${progress.color}`}> |
| | | {item.stages && item.stages.length >= STAGES.length ? ( |
| | | {item.stages && Object.keys(item.stages).filter(k => ["completed", "session_completed"].includes(item.stages![k])).length >= STAGES.length ? ( |
| | | <CheckCircle className="w-3 h-3" /> |
| | | ) : ( |
| | | <span className="w-1.5 h-1.5 rounded-full bg-current flex-shrink-0" /> |
| | |
| | | 'use client'; |
| | | 'use client'; |
| | | |
| | | import React, { useState, useRef, useEffect } from 'react'; |
| | | import { CheckCircle, Circle, Loader, Edit3, AlertCircle, Square, Zap, Settings2, ChevronDown, Hexagon } from 'lucide-react'; |
| | |
| | | modelConfig?: ModelConfig; |
| | | /** 模型配置变更 */ |
| | | onModelConfigChange?: (config: ModelConfig) => void; |
| | | /** 项目状态(如 running, waiting_in_stage, stage_completed, session_completed, idle, error 等) */ |
| | | /** 项目状态(如 running, waiting, completed, completed, idle, error 等) */ |
| | | projectStatus?: string; |
| | | } |
| | | |
| | |
| | | className={clsx( |
| | | 'px-2 py-1 rounded-lg text-xs font-medium flex items-center gap-1', |
| | | projectStatus === 'running' && 'bg-blue-50 text-blue-700', |
| | | projectStatus === 'waiting_in_stage' && 'bg-amber-50 text-amber-700', |
| | | projectStatus === 'stage_completed' && 'bg-green-50 text-green-700', |
| | | projectStatus === 'idle' && 'bg-gray-50 text-gray-600', |
| | | projectStatus === 'waiting' && 'bg-amber-50 text-amber-700', |
| | | projectStatus === 'completed' && 'bg-green-50 text-green-700', |
| | | projectStatus === 'pending' && 'bg-gray-50 text-gray-600', |
| | | projectStatus === 'error' && 'bg-red-50 text-red-700', |
| | | projectStatus === 'stopped' && 'bg-orange-50 text-orange-700' |
| | | )} |
| | | title="项目状态" |
| | | > |
| | | {projectStatus === 'running' && <Loader className="w-3 h-3 animate-spin" />} |
| | | {projectStatus === 'waiting_in_stage' && <Edit3 className="w-3 h-3" />} |
| | | {projectStatus === 'waiting' && <Edit3 className="w-3 h-3" />} |
| | | {projectStatus === 'error' && <AlertCircle className="w-3 h-3" />} |
| | | <span> |
| | | {projectStatus === 'running' ? '执行中' : |
| | | projectStatus === 'waiting_in_stage' ? '等待确认' : |
| | | projectStatus === 'stage_completed' ? '阶段完成' : |
| | | projectStatus === 'session_completed' ? '已完成' : |
| | | projectStatus === 'idle' ? '空闲' : |
| | | projectStatus === 'waiting' ? '等待确认' : |
| | | projectStatus === 'completed' ? '已完成' : |
| | | projectStatus === 'pending' ? '空闲' : |
| | | projectStatus === 'stopped' ? '已停止' : |
| | | projectStatus === 'error' ? '出错' : projectStatus} |
| | | </span> |
| | |
| | | 'use client'; |
| | | 'use client'; |
| | | |
| | | import React, { useState, useRef, useEffect, useCallback } from 'react'; |
| | | import { useRouter, useSearchParams } from 'next/navigation'; |
| | |
| | | style?: string; |
| | | date: string; |
| | | status: string; |
| | | stages?: string[]; // stages_completed 列表 |
| | | stages?: Record<string, string>; // stageId => status 映射 |
| | | } |
| | | |
| | | function initStageStates(): Record<string, StageState> { |
| | |
| | | status = await getProjectStatus(sid); |
| | | } |
| | | if (pollRef.current !== key) return; |
| | | const done = status.stages_completed || []; |
| | | setGlobalStatusMap(status.status || {}); |
| | | const done = Object.keys(status.status || {}).filter(k => ["completed", "session_completed"].includes(status.status[k])); |
| | | const currentStageStatus = status.status?.[stageId] || 'idle'; |
| | | if (done.includes(stageId)) { |
| | | const isWait = status.status === 'waiting_in_stage' && status.current_stage === stageId; |
| | | const isWait = currentStageStatus === 'waiting' && status.current_stage === stageId; |
| | | let artifact = null; |
| | | try { artifact = (await getArtifact(sid, stageId)).artifact; } catch {} |
| | | updateStageState(stageId, { |
| | |
| | | pollRef.current = null; |
| | | return; |
| | | } |
| | | if (status.status === 'error') { |
| | | if (currentStageStatus === 'error') { |
| | | updateStageState(stageId, { |
| | | status: 'error', |
| | | error: status.error || '执行出错', |
| | |
| | | pollRef.current = null; |
| | | return; |
| | | } |
| | | if (status.status === 'stopped') { |
| | | if (currentStageStatus === 'stopped') { |
| | | updateStageState(stageId, { |
| | | status: 'stopped', |
| | | error: '手动停止', |
| | |
| | | pollRef.current = null; |
| | | return; |
| | | } |
| | | // 如果后端状态不再是 running,提前停止轮询(比如变成了 waiting_intervention 或已完成) |
| | | if (status.status !== 'running') { |
| | | // 如果当前阶段不再是 running,提前停止轮询(比如变成了 waiting_intervention 或已完成) |
| | | if (currentStageStatus !== 'running') { |
| | | pollRef.current = null; |
| | | return; |
| | | } |
| | |
| | | const artifacts = status.artifacts || {}; |
| | | const currentArtifact = artifacts[stageId]; |
| | | const update: Partial<StageState> = {}; |
| | | |
| | | // 无论何种状态,只要有数据就更新 artifact |
| | | if (currentArtifact) { |
| | | update.artifact = currentArtifact; |
| | | } |
| | | |
| | | // 始终设置状态为 running(如果尚未设置) |
| | | const currentState = stageStates[stageId]; |
| | |
| | | } |
| | | |
| | | if (currentArtifact) { |
| | | // 检查是否有已生成的参考图/视频 |
| | | // 检查是否有已生成的参考图/视频/分镜 |
| | | const hasProgress = currentArtifact.scenes?.some((s: any) => s.versions?.length > 0) || |
| | | currentArtifact.clips?.some((c: any) => c.versions?.length > 0) || |
| | | currentArtifact.episodes?.some((e: any) => e.segments?.length > 0) || |
| | | currentArtifact.characters?.length > 0 || |
| | | currentArtifact.shots?.length > 0; |
| | | if (hasProgress) { |
| | |
| | | date: s.date |
| | | ? new Date(s.date * 1000).toLocaleDateString('zh-CN') |
| | | : '', |
| | | status: (s.stages?.length || 0) > 0 ? 'partial' : 'new', |
| | | stages: s.stages || [], |
| | | status: Object.keys(s.status || {}).length > 0 ? 'partial' : 'new', |
| | | stages: s.status || {}, |
| | | })) |
| | | ); |
| | | }) |
| | |
| | | style: params.style, |
| | | date: new Date().toLocaleDateString('zh-CN'), |
| | | status: 'running', |
| | | stages: [], |
| | | stages: {}, |
| | | }, |
| | | ...prev, |
| | | ]); |
| | |
| | | } |
| | | |
| | | const status = await getProjectStatus(result.session_id); |
| | | // waiting_in_stage: 等待用户介入(如选择角色/图片),不能自动 continue |
| | | // stage_completed: 阶段完成,等待确认进入下一阶段 |
| | | if (status.status === 'stage_completed') { |
| | | const stageStatus = status?.status?.[stageId]; |
| | | setGlobalStatusMap(status.status || {}); |
| | | // waiting: 等待用户介入(如选择角色/图片),不能自动 continue |
| | | // completed: 阶段完成,等待确认进入下一阶段 |
| | | if (stageStatus === 'completed' || stageStatus === 'session_completed') { |
| | | if (useAutoMode) { |
| | | // 代理模式:自动确认并继续 |
| | | await continueWorkflow(result.session_id); |
| | |
| | | setIsRunning(false); |
| | | return; |
| | | } |
| | | } else if (status.status === 'waiting_in_stage') { |
| | | } else if (stageStatus === 'waiting') { |
| | | // 用户需要介入,停止自动执行 |
| | | updateStageState(stageId, { status: 'waiting' }); |
| | | setActiveStage(stageId); |
| | |
| | | setIsRunning(true); |
| | | |
| | | try { |
| | | const result = await continueWorkflow(sessionId); |
| | | const result: any = await continueWorkflow(sessionId); |
| | | updateStageState(stageId, { status: 'completed', progressMessage: '已确认' }); |
| | | |
| | | // 更新顶栏状态 |
| | | if (result.status_map) { |
| | | setGlobalStatusMap(result.status_map); |
| | | } |
| | | setCompletedStagesFromSession(prev => [...prev, stageId]); |
| | | if (result.next_stage) { |
| | | setCurrentStageFromSession(result.next_stage); |
| | |
| | | await runStage(sessionId, nextStage, inputData); |
| | | |
| | | const status = await getProjectStatus(sessionId); |
| | | // waiting_in_stage: 等待用户介入(如选择角色/图片),不能自动 continue |
| | | // stage_completed: 阶段完成,等待确认进入下一阶段,可以自动 continue |
| | | if (status.status === 'stage_completed') { |
| | | setGlobalStatusMap(status.status || {}); |
| | | const nStageStatus = status?.status?.[nextStage]; |
| | | // waiting: 等待用户介入(如选择角色/图片),不能自动 continue |
| | | // completed: 阶段完成,等待确认进入下一阶段,可以自动 continue |
| | | if (nStageStatus === 'completed' || nStageStatus === 'session_completed') { |
| | | if (autoMode) { |
| | | await continueWorkflow(sessionId); |
| | | updateStageState(nextStage, { status: 'completed', progressMessage: '已自动确认' }); |
| | |
| | | setActiveStage(nextStage); |
| | | break; |
| | | } |
| | | } else if (status.status === 'waiting_in_stage') { |
| | | } else if (nStageStatus === 'waiting') { |
| | | // 用户需要介入,停止自动执行 |
| | | updateStageState(nextStage, { status: 'waiting' }); |
| | | setCurrentStageFromSession(nextStage); |
| | |
| | | const oldScenes = (oldRefArtifact?.scenes || []) as any[]; |
| | | const oldScenesMap = new Map(oldScenes.map((s: any) => [s.id, s])); |
| | | |
| | | // 使用 original_shots(保留 is_new 标记)构建第4阶段 scenes |
| | | const sourceShots = patch.original_shots || patch.shots || []; |
| | | console.log('[handleSaveSelections] sourceShots:', sourceShots); |
| | | const newScenes = sourceShots.map((shot: any, idx: number) => { |
| | | const oldScene = oldScenesMap.get(shot.shot_id) as any; |
| | | const isNew = shot.is_new; |
| | | // 如果是新分镜,使用空值;否则保留原有的 selected/versions |
| | | // 使用 segments 构建第4阶段 scenes 和第5阶段 clips |
| | | const sourceSegments = patch.segments || []; |
| | | console.log('[handleSaveSelections] sourceSegments:', sourceSegments); |
| | | |
| | | const newScenes = sourceSegments.map((seg: any, idx: number) => { |
| | | const seg_id = seg.segment_id; |
| | | const oldScene = oldScenesMap.get(seg_id) as any; |
| | | const isNew = seg.is_new; |
| | | |
| | | const shots = seg.shots || []; |
| | | const desc_ref = shots.map((sh: any) => sh.visual_prompt || sh.plot || sh.content || '').join(' ').trim(); |
| | | |
| | | return { |
| | | id: shot.shot_id, |
| | | name: `场景${shot.scene_number}-镜头${shot.shot_number}`, |
| | | id: seg_id, |
| | | name: `片段_${seg_id}`, |
| | | index: idx + 1, |
| | | description: shot.visual_prompt || '', |
| | | duration: shot.duration || 10, |
| | | description: desc_ref, |
| | | selected: isNew ? '' : (oldScene?.selected || ''), |
| | | versions: isNew ? [] : (oldScene?.versions || []), |
| | | status: isNew ? 'pending' : 'done', |
| | | }; |
| | | }); |
| | | console.log('[handleSaveSelections] newScenes:', newScenes); |
| | | |
| | | // 更新第4阶段的 artifact |
| | | updateStageState('reference_generation', { |
| | | artifact: { session_id: sessionId, scenes: newScenes }, |
| | | status: 'completed' |
| | | }); |
| | | console.log('[handleSaveSelections] 第4阶段已更新'); |
| | | |
| | | // 同步更新第5阶段(video_generation) |
| | | const oldVidArtifact = stageStates['video_generation']?.artifact; |
| | | const oldClips = (oldVidArtifact?.clips || []) as any[]; |
| | | const oldClipsMap = new Map(oldClips.map((c: any) => [c.id, c])); |
| | | |
| | | const newClips = sourceShots.map((shot: any, idx: number) => { |
| | | const oldClip = oldClipsMap.get(shot.shot_id) as any; |
| | | const newClips = sourceSegments.map((seg: any, idx: number) => { |
| | | const seg_id = seg.segment_id; |
| | | const oldClip = oldClipsMap.get(seg_id) as any; |
| | | |
| | | const shots = seg.shots || []; |
| | | const desc_video = shots.map((sh: any) => sh.plot || sh.content || '').join(' ').trim(); |
| | | const total_dur = seg.total_duration || shots.reduce((acc: number, sh: any) => acc + (sh.duration || 0), 0) || 10; |
| | | |
| | | return { |
| | | id: shot.shot_id, |
| | | name: `场景${shot.scene_number}-镜头${shot.shot_number}`, |
| | | id: seg_id, |
| | | name: `片段_${seg_id}`, |
| | | index: idx + 1, |
| | | description: shot.visual_prompt || '', |
| | | duration: shot.duration || 10, |
| | | description: desc_video, |
| | | duration: total_dur, |
| | | selected: oldClip?.selected || '', |
| | | versions: oldClip?.versions || [], |
| | | status: 'pending', |
| | |
| | | await runStage(sessionId, stageId, inputData); |
| | | |
| | | const status = await getProjectStatus(sessionId); |
| | | if (status.status === 'waiting_in_stage') { |
| | | if (status?.status?.[stageId] === 'waiting') { |
| | | updateStageState(stageId, { status: 'waiting' }); |
| | | setActiveStage(stageId); |
| | | } |
| | |
| | | } catch { |
| | | status = await getProjectStatus(sid); |
| | | } |
| | | setGlobalStatusMap(status.status || {}); |
| | | const newStates = initStageStates(); |
| | | const completedStages = status.stages_completed || []; |
| | | const stMap = status.status || {}; |
| | | const allStatusStages = Object.keys(stMap); |
| | | const currentStage = status.current_stage; |
| | | const isWaiting = status.status === 'waiting_in_stage'; |
| | | |
| | | // 保存到 state 供顶栏流程图使用 |
| | | setCurrentStageFromSession(currentStage || null); |
| | | const completedStages = allStatusStages.filter(k => ["completed", "session_completed"].includes(stMap[k])); |
| | | setCompletedStagesFromSession(completedStages); |
| | | |
| | | for (const cs of completedStages) { |
| | | const isCurrentWaiting = cs === currentStage && isWaiting; |
| | | newStates[cs] = { |
| | | status: isCurrentWaiting ? 'waiting' : 'completed', |
| | | progress: 100, |
| | | progressMessage: isCurrentWaiting ? '等待确认' : '已完成', |
| | | artifact: null, |
| | | error: null, |
| | | }; |
| | | try { |
| | | const artResult = await getArtifact(sid, cs); |
| | | newStates[cs].artifact = artResult.artifact; |
| | | } catch { /* ignore */ } |
| | | for (const sName of allStatusStages) { |
| | | const cStatus = stMap[sName]; |
| | | if (cStatus === 'pending' || cStatus === 'idle') { |
| | | // 即使是 pending,如果 artifacts 中有数据,也尝试恢复数据(用于初始占位显示) |
| | | if (status.artifacts?.[sName]) { |
| | | newStates[sName].artifact = status.artifacts[sName]; |
| | | } |
| | | continue; |
| | | } |
| | | |
| | | // 如果 current_stage 不在 completedStages 中,也需要显示(可能是 stage_completed、running, stopped, 或 error 状态) |
| | | if (currentStage && !completedStages.includes(currentStage)) { |
| | | const isError = status.status === 'error'; |
| | | const isWaiting = status.status === 'waiting_in_stage'; |
| | | const isCompleted = status.status === 'stage_completed'; |
| | | const isStopped = status.status === 'stopped'; |
| | | const isCompleted = ["completed", "session_completed"].includes(cStatus); |
| | | const isError = cStatus === 'error'; |
| | | const isWaiting = cStatus === 'waiting'; |
| | | const isStopped = cStatus === 'stopped'; |
| | | const isRunningStatus = cStatus === 'running'; |
| | | |
| | | newStates[currentStage] = { |
| | | status: isError ? 'error' : (isWaiting ? 'waiting' : (isCompleted ? 'completed' : (isStopped ? 'stopped' : 'running'))), |
| | | progress: 100, |
| | | progressMessage: isError ? '执行失败' : (isWaiting ? '等待确认' : (isCompleted ? '已完成' : (isStopped ? '已停止' : '进行中'))), |
| | | artifact: null, |
| | | newStates[sName] = { |
| | | status: isError ? 'error' : (isWaiting ? 'waiting' : (isStopped ? 'stopped' : (isCompleted ? 'completed' : 'running'))), |
| | | progress: isCompleted ? 100 : 0, |
| | | progressMessage: isError ? '执行失败' : (isWaiting ? '等待确认' : (isStopped ? '已停止' : (isCompleted ? '已完成' : (isRunningStatus ? '执行中...' : '进行中')))), |
| | | artifact: status.artifacts?.[sName] || null, |
| | | error: isError ? (status.error || '执行出错') : (isStopped ? '手动停止' : null), |
| | | }; |
| | | |
| | | // 如果内存中没有,尝试异步拉取 |
| | | if (!newStates[sName].artifact) { |
| | | try { |
| | | const artResult = await getArtifact(sid, currentStage); |
| | | newStates[currentStage].artifact = artResult.artifact; |
| | | const artResult = await getArtifact(sid, sName); |
| | | newStates[sName].artifact = artResult.artifact; |
| | | } catch { /* ignore */ } |
| | | } |
| | | } |
| | | |
| | | // 恢复项目参数(从顶层字段读取,sessions json 中模型参数是顶层字段) |
| | |
| | | setStageStates(newStates); |
| | | |
| | | // 轮询当前正在执行的阶段(仅当该阶段有 artifact 数据时) |
| | | if (status.status === 'running' && currentStage && !completedStages.includes(currentStage)) { |
| | | if (currentStage && stMap[currentStage] === 'running') { |
| | | pollForCompletion(sid, currentStage); |
| | | } |
| | | } catch { |
| | |
| | | : undefined; |
| | | |
| | | // ── 计算 stageStatuses for TopBar ── |
| | | // 根据 session 的 current_stage 和 stages_completed 判断图标状态 |
| | | // 直接根据后端返回的 status 数据计算图标状态 |
| | | const [globalStatusMap, setGlobalStatusMap] = useState<Record<string, string>>({}); |
| | | |
| | | const stageStatuses: Record<string, StageStatus> = {}; |
| | | const currentIdx = STAGE_ORDER.indexOf(currentStageFromSession || ''); |
| | | |
| | | for (let i = 0; i < STAGE_ORDER.length; i++) { |
| | | const s = STAGE_ORDER[i]; |
| | | const backendStatus = globalStatusMap[s]; // get status from global mapping updated from backend |
| | | |
| | | if (i < currentIdx) { |
| | | // current_stage 之前的阶段:已完成(绿色对勾) |
| | | if (backendStatus === 'completed') { |
| | | stageStatuses[s] = 'completed'; |
| | | } else if (i > currentIdx) { |
| | | // current_stage 之后的阶段 |
| | | if (completedStagesFromSession.includes(s)) { |
| | | // 在 stages_completed 中(黄色图案) |
| | | } else if (backendStatus === 'waiting') { |
| | | stageStatuses[s] = 'waiting'; |
| | | } else if (backendStatus === 'running') { |
| | | stageStatuses[s] = 'running'; |
| | | } else if (backendStatus === 'error') { |
| | | stageStatuses[s] = 'error'; |
| | | } else { |
| | | // 不在 stages_completed 中:pending |
| | | stageStatuses[s] = 'pending'; |
| | | } |
| | | } else { |
| | | // current_stage 本身:根据 stageStates 判断 |
| | | stageStatuses[s] = stageStates[s]?.status || 'pending'; |
| | | if (stageStatuses[s] === 'stopped') stageStatuses[s] = 'stopped'; |
| | | } |
| | | } |
| | | |
| | | // ── 计算项目状态 ── |
| | | // 后端状态: idle, running, waiting_in_stage, stage_completed, session_completed, error |
| | | // 后端状态: pending, running, waiting, completed, completed, error |
| | | // 前端 StageStatus: pending, running, waiting, completed, error |
| | | const hasRunning = Object.values(stageStates).some(s => s.status === 'running'); |
| | | const hasWaiting = Object.values(stageStates).some(s => s.status === 'waiting'); |
| | |
| | | |
| | | let computedStatus: string; |
| | | if (hasRunning) computedStatus = 'running'; |
| | | else if (hasWaiting) computedStatus = 'waiting_in_stage'; |
| | | else if (hasWaiting) computedStatus = 'waiting'; |
| | | else if (hasError) computedStatus = 'error'; |
| | | // Check if stopped in stageStates |
| | | else if (Object.values(stageStates).some(s => s.status === 'stopped')) computedStatus = 'stopped'; |
| | | else if (allCompleted && stageStates[STAGE_ORDER[STAGE_ORDER.length - 1]]?.status === 'completed') { |
| | | computedStatus = 'session_completed'; |
| | | computedStatus = 'completed'; |
| | | } else if (allCompleted) { |
| | | computedStatus = 'stage_completed'; |
| | | computedStatus = 'completed'; |
| | | } else { |
| | | computedStatus = Object.values(stageStates).some(s => s.status === 'stopped') ? 'stopped' : 'idle'; |
| | | computedStatus = Object.values(stageStates).some(s => s.status === 'stopped') ? 'stopped' : 'pending'; |
| | | } |
| | | |
| | | const projectStatus = sessionId ? computedStatus : undefined; |
| | |
| | | </div> |
| | | ); |
| | | } |
| | | |
| | |
| | | onToggleEdit?: () => void; |
| | | getSelected: (scene: SceneItem) => string; |
| | | }) { |
| | | const isPending = scene.status === 'pending' || isRegenerating; |
| | | const isRunning = scene.status === 'running' || isRegenerating; |
| | | const isPending = scene.status === 'pending'; |
| | | const isFailed = scene.status === 'failed' && !isRegenerating; |
| | | const isPendingEmpty = scene.status === 'pending' && !scene.versions.length && !isRegenerating; |
| | | const hasChanges = editDesc !== scene.description; |
| | |
| | | </span> |
| | | <span className="text-sm font-semibold text-gray-800 truncate">{scene.name || (scene as any).title || `片段 ${scene.index}`}</span> |
| | | {isPending && ( |
| | | <span className="text-[10px] bg-gray-50 text-gray-500 px-1.5 py-0.5 rounded">等待中</span> |
| | | )} |
| | | {isRunning && ( |
| | | <span className="inline-flex items-center gap-1 text-[10px] bg-amber-50 text-amber-600 px-1.5 py-0.5 rounded"> |
| | | <Loader className="w-2.5 h-2.5 animate-spin" />生成中 |
| | | </span> |
| | |
| | | <span>生成首帧参考图</span> |
| | | </div> |
| | | </div> |
| | | ) : isPending && !scene.versions.length ? ( |
| | | ) : isRunning && !scene.versions.length ? ( |
| | | <div className="flex items-center justify-center h-28 aspect-video bg-gray-50 rounded-lg border border-dashed border-gray-200"> |
| | | <div className="flex items-center gap-2 text-gray-400 text-xs"> |
| | | <Loader className="w-4 h-4 animate-spin" /> |
| | | <span>正在生成...</span> |
| | | </div> |
| | | </div> |
| | | ) : isPending && !scene.versions.length ? ( |
| | | <div className="flex items-center justify-center h-28 aspect-video bg-gray-50/30 rounded-lg border border-dashed border-gray-200"> |
| | | <div className="flex items-center gap-2 text-gray-400 text-xs text-center px-4"> |
| | | <span>等待生成...</span> |
| | | </div> |
| | | </div> |
| | | ) : isFailed && !scene.versions.length ? ( |
| | | <div |
| | | className="flex items-center justify-center h-28 aspect-video bg-red-50/50 rounded-lg border border-dashed border-red-200 cursor-pointer hover:bg-red-100/50 transition-colors" |
| | |
| | | // 是否是"重新生成"阶段(1) |
| | | const isRegenStage = STAGES_WITH_NEXT_CHECK.includes(stageId); |
| | | |
| | | // 重新生成/继续生成按钮:在 waiting / completed / error / stopped 状态下显示 |
| | | const showRegen = !!onRegenerate && (status === 'waiting' || status === 'completed' || status === 'error' || status === 'stopped'); |
| | | // 重新生成/继续生成按钮:在 != 'running' 状态下显示 (pending时也不会到这个组件) |
| | | const showRegen = !!onRegenerate && status !== 'running'; |
| | | |
| | | // 按钮是否禁用逻辑 |
| | | let isButtonDisabled = isRunning; |
| | | if (!isRunning) { |
| | | if (isContinueStage && !hasPendingItems && status !== 'error') isButtonDisabled = true; |
| | | if (isRegenStage && hasNextStageStarted) isButtonDisabled = true; |
| | | if (!isRunning && stageId) { |
| | | // 除了第一阶段和第六阶段外,completed 状态下禁用继续生成 |
| | | if (stageId !== 'script_generation' && stageId !== 'post_production' && status === 'completed') { |
| | | isButtonDisabled = true; |
| | | } |
| | | } |
| | | |
| | | // 其余按钮在 waiting、running、completed、stopped 状态显示 |
| | |
| | | let totalSegments = 0; |
| | | let totalDuration = 0; |
| | | episodesToRender.forEach(ep => { |
| | | totalSegments += ep.segments.length; |
| | | ep.segments.forEach(seg => { |
| | | const segs = ep.segments || []; |
| | | totalSegments += segs.length; |
| | | segs.forEach(seg => { |
| | | totalDuration += (seg.total_duration || 0); |
| | | }); |
| | | }); |
| | |
| | | ) : ( |
| | | <div className="space-y-12"> |
| | | {episodesToRender.map((episode, epIdx) => { |
| | | const epTotalTime = episode.segments.reduce((sum, s) => sum + (s.total_duration || 0), 0); |
| | | const segs = episode.segments || []; |
| | | const epTotalTime = segs.reduce((sum, s) => sum + (s.total_duration || 0), 0); |
| | | return ( |
| | | <div key={epIdx} className="space-y-4"> |
| | | {/* 一级:剧集抬头 (参考第一阶段) */} |
| | |
| | | |
| | | {/* 二级:拍摄分段 */} |
| | | <div className="space-y-8 pl-1"> |
| | | {episode.segments.map((segment, segIdx) => ( |
| | | {segs.map((segment, segIdx) => ( |
| | | <div key={segment.segment_id} className="space-y-3"> |
| | | <div className="flex items-center justify-between bg-gray-50/50 rounded-lg px-4 py-2 border border-gray-100"> |
| | | <div className="flex items-center gap-6"> |
| | |
| | | <span className="text-sm font-bold text-gray-800"> |
| | | {isEditing ? ( |
| | | <input |
| | | value={segment.location} |
| | | value={segment.location || ''} |
| | | onChange={e => updateSegmentField(epIdx, segIdx, 'location', e.target.value)} |
| | | className="bg-transparent border-b border-gray-200 focus:border-violet-400 outline-none px-1" |
| | | /> |
| | | ) : segment.location} |
| | | ) : (segment.location || '未知地点')} |
| | | </span> |
| | | </div> |
| | | <div className="flex items-center gap-1.5"> |
| | | <Users className="w-3.5 h-3.5 text-gray-400" /> |
| | | <div className="flex gap-1.5"> |
| | | {segment.characters.map((c, i) => ( |
| | | {(segment.characters || []).map((c, i) => ( |
| | | <span key={i} className="px-2 py-0.5 bg-white border border-gray-200 text-xs text-gray-600 rounded font-bold">{c}</span> |
| | | ))} |
| | | </div> |
| | |
| | | </tr> |
| | | </thead> |
| | | <tbody className="divide-y divide-gray-50"> |
| | | {segment.shots.map((shot, sIdx) => { |
| | | {(segment.shots || []).map((shot, sIdx) => { |
| | | const decor = SHOT_TYPE_DECOR[shot.shot_type as keyof typeof SHOT_TYPE_DECOR] || SHOT_TYPE_DECOR['近景']; |
| | | return ( |
| | | <tr key={sIdx} className="group hover:bg-gray-50/30 transition-colors"> |
| | |
| | | disabled?: boolean; |
| | | isSaving?: boolean; |
| | | }) { |
| | | const isPending = clip.status === 'pending' || isRegenerating; |
| | | const isRunning = clip.status === 'running' || isRegenerating; |
| | | const isPending = clip.status === 'pending'; |
| | | const isFailed = clip.status === 'failed' && !isRegenerating; |
| | | const hasChanges = editDesc !== clip.description; |
| | | |
| | |
| | | <span className="text-[10px] bg-gray-100 text-gray-500 px-1.5 py-0.5 rounded">{clip.duration}s</span> |
| | | )} |
| | | {isPending && ( |
| | | <span className="text-[10px] bg-gray-100 text-gray-500 px-1.5 py-0.5 rounded">等待中</span> |
| | | )} |
| | | {isRunning && ( |
| | | <span className="inline-flex items-center gap-1 text-[10px] bg-amber-50 text-amber-600 px-1.5 py-0.5 rounded"> |
| | | <Loader className="w-2.5 h-2.5 animate-spin" />生成中 |
| | | </span> |
| | |
| | | |
| | | {/* 右侧: 视频画廊 / 占位 */} |
| | | <div className="flex-1 min-w-0 p-3 flex items-center"> |
| | | {isPending && !clip.versions.length ? ( |
| | | {isRunning && !clip.versions.length ? ( |
| | | <div className="flex items-center justify-center h-32 aspect-video bg-gray-50 rounded-lg border border-dashed border-gray-200"> |
| | | <div className="flex items-center gap-2 text-gray-400 text-xs px-4"> |
| | | <Loader className="w-4 h-4 animate-spin" /> |
| | | <span>正在生成视频...</span> |
| | | </div> |
| | | </div> |
| | | ) : isPending && !clip.versions.length ? ( |
| | | <div className="flex items-center justify-center h-32 aspect-video bg-gray-50/30 rounded-lg border border-dashed border-gray-200"> |
| | | <div className="flex items-center gap-2 text-gray-400 text-xs px-4"> |
| | | <span>等待生成视频...</span> |
| | | </div> |
| | | </div> |
| | | ) : isFailed && !clip.versions.length ? ( |
| | | <div |
| | | className="flex items-center justify-center h-32 aspect-video bg-red-50/50 rounded-lg border border-dashed border-red-200 cursor-pointer hover:bg-red-100/50 transition-colors" |
| | |
| | | export interface ProjectStatus { |
| | | session_id: string; |
| | | current_stage: string; |
| | | status: string; |
| | | status: Record<string, string>; |
| | | error: string | null; |
| | | stages_completed: string[]; |
| | | } |
| | | |
| | | export interface StreamEvent { |
| | |
| | | # 创建项目 |
| | | # 创建项目 |
| | | |
| | | 创建一个新的视频生成项目。 |
| | | |
| | |
| | | ```json |
| | | { |
| | | "session_id": "xxx", |
| | | "status": "stage_completed", |
| | | "status": "completed", |
| | | "params": { |
| | | "idea": "故事内容", |
| | | "style": "anime", |