Optimize page layout and button rendering logic
| | |
| | | import os |
| | | |
| | | from fastapi import APIRouter, HTTPException |
| | | |
| | | from api.dependencies import workflow_engine |
| | | from config import settings |
| | | |
| | | router = APIRouter(tags=["Sessions"]) |
| | | |
| | |
| | | @router.delete("/api/sessions") |
| | | async def cleanup_orphan_files(): |
| | | """清理孤立的结果文件(无密码控制)""" |
| | | # 获取所有 session ID |
| | | session_ids = set() |
| | | for f in os.listdir(workflow_engine._session_dir): |
| | | if f.endswith('.json'): |
| | | session_ids.add(f.replace('.json', '')) |
| | | |
| | | # 清理孤立文件 |
| | | cleaned = {"scripts": [], "images": [], "videos": []} |
| | | result_base = settings.RESULT_DIR |
| | | |
| | | # 清理孤立剧本 |
| | | script_dir = os.path.join(result_base, 'script') |
| | | for f in os.listdir(script_dir): |
| | | if f.endswith('.json'): |
| | | sid = f[:-5] |
| | | if sid not in session_ids: |
| | | os.remove(os.path.join(script_dir, f)) |
| | | cleaned["scripts"].append(sid) |
| | | |
| | | # 清理孤立图片 |
| | | image_dir = os.path.join(result_base, 'image') |
| | | for d in os.listdir(image_dir): |
| | | if d != 'test_avail' and d not in session_ids: |
| | | import shutil |
| | | shutil.rmtree(os.path.join(image_dir, d)) |
| | | cleaned["images"].append(d) |
| | | |
| | | # 清理孤立视频 |
| | | video_dir = os.path.join(result_base, 'video') |
| | | for d in os.listdir(video_dir): |
| | | if d != 'test_avail' and d not in session_ids: |
| | | import shutil |
| | | shutil.rmtree(os.path.join(video_dir, d)) |
| | | cleaned["videos"].append(d) |
| | | |
| | | return {"status": "cleaned", "cleaned": cleaned} |
| | | return workflow_engine.cleanup_orphan_results() |
| | |
| | | import copy |
| | | import json |
| | | import os |
| | | import time |
| | | from datetime import datetime |
| | | from types import SimpleNamespace |
| | | |
| | | from fastapi import APIRouter, File, Form, HTTPException, Request, UploadFile |
| | | from fastapi.responses import StreamingResponse |
| | |
| | | from api.routers.files import merge_uploaded_file_into_idea |
| | | from api.schemas.project import InterventionRequest, ProjectStartRequest |
| | | from api.services.project_helpers import ( |
| | | inject_user_selections, |
| | | make_cancellation, |
| | | make_progress_channel, |
| | | stream_workflow_task, |
| | |
| | | _require_model_fields(req.model_dump()) |
| | | |
| | | session_id = str(int(time.time() * 1000)) |
| | | state = workflow_engine.get_or_create_state(session_id) |
| | | meta = { |
| | | "idea": final_idea, |
| | | "user_textbox_input": req.idea, |
| | |
| | | "web_search": req.web_search if req.web_search is not None else False, |
| | | "episodes": req.episodes if req.episodes is not None else 4, |
| | | } |
| | | with workflow_engine._state_lock: |
| | | state.started_at = datetime.now() |
| | | if not isinstance(state.status, dict): |
| | | state.status = {} |
| | | state.status[state.current_stage.value] = "completed" |
| | | state.meta = meta |
| | | workflow_engine.save_session_to_disk(session_id, meta) |
| | | session = workflow_engine.create_session(session_id, meta) |
| | | |
| | | return { |
| | | "session_id": session_id, |
| | | "status": copy.deepcopy(state.status), |
| | | "status": session["status"], |
| | | "params": { |
| | | "idea": final_idea, |
| | | "file_path": req.file_path, |
| | |
| | | |
| | | @router.post("/api/project/{session_id}/execute/{stage}") |
| | | async def execute_stage(session_id: str, stage: str, request: Request): |
| | | state = workflow_engine.get_or_create_state(session_id) |
| | | |
| | | try: |
| | | body = await request.json() |
| | | except Exception: |
| | | body = {} |
| | | |
| | | body["session_id"] = session_id |
| | | with workflow_engine._state_lock: |
| | | meta_snapshot = copy.deepcopy(state.meta) |
| | | artifact_snapshot = copy.deepcopy(state.artifacts) |
| | | if meta_snapshot: |
| | | for k, v in meta_snapshot.items(): |
| | | if v is not None and (k not in body or not body[k]): |
| | | body[k] = v |
| | | _require_model_fields(body) |
| | | state, input_data = workflow_engine.prepare_stage_execution(session_id, stage, body) |
| | | _require_model_fields(input_data) |
| | | |
| | | state_for_input = SimpleNamespace(artifacts=artifact_snapshot) |
| | | inject_user_selections(state_for_input, stage, body) |
| | | cancellation_check, on_disconnect = make_cancellation(workflow_engine, session_id) |
| | | progress_events, event_trigger, progress_callback = make_progress_channel() |
| | | |
| | |
| | | workflow_engine=workflow_engine, |
| | | state=state, |
| | | stage=stage, |
| | | input_data=body, |
| | | input_data=input_data, |
| | | cancellation_check=cancellation_check, |
| | | progress_callback=progress_callback, |
| | | progress_events=progress_events, |
| | |
| | | |
| | | @router.get("/api/project/{session_id}/status") |
| | | async def get_project_status(session_id: str): |
| | | state = workflow_engine.get_state(session_id) |
| | | if not state: |
| | | snapshot = workflow_engine.get_status_snapshot(session_id) |
| | | if not snapshot: |
| | | raise HTTPException(404, "Session not found") |
| | | with workflow_engine._state_lock: |
| | | return state.to_dict() |
| | | return snapshot |
| | | |
| | | |
| | | @router.get("/api/project/{session_id}/status/from_disk") |
| | | async def get_project_status_from_disk(session_id: str): |
| | | # 兼容旧前端路由名;实际读取统一走 WorkflowEngine 的内存状态入口。 |
| | | state = workflow_engine.get_state(session_id) |
| | | if not state: |
| | | snapshot = workflow_engine.get_status_snapshot(session_id) |
| | | if not snapshot: |
| | | raise HTTPException(404, "Session not found") |
| | | with workflow_engine._state_lock: |
| | | return state.to_dict() |
| | | return snapshot |
| | | |
| | | |
| | | @router.get("/api/project/{session_id}/artifact/{stage}") |
| | | async def get_artifact(session_id: str, stage: str): |
| | | state = workflow_engine.get_state(session_id) |
| | | if not state: |
| | | try: |
| | | artifact = workflow_engine.get_artifact_snapshot(session_id, stage) |
| | | except KeyError: |
| | | raise HTTPException(404, "Session not found") |
| | | |
| | | with workflow_engine._state_lock: |
| | | artifact = copy.deepcopy(state.artifacts.get(stage)) |
| | | if artifact is not None: |
| | | return {"stage": stage, "artifact": artifact} |
| | | |
| | |
| | | |
| | | @router.patch("/api/project/{session_id}/models") |
| | | async def update_models(session_id: str, request: Request): |
| | | state = workflow_engine.get_state(session_id) |
| | | if not state: |
| | | raise HTTPException(404, "Session not found") |
| | | body = await request.json() |
| | | allowed_keys = ("llm_model", "vlm_model", "image_t2i_model", "image_it2i_model", "video_model", "video_ratio", "video_resolution", "style", "enable_concurrency") |
| | | with workflow_engine._state_lock: |
| | | if not state.meta: |
| | | state.meta = {} |
| | | for k in allowed_keys: |
| | | if k in body: |
| | | state.meta[k] = body[k] |
| | | workflow_engine.save_session_to_disk(session_id) |
| | | return {"status": "ok"} |
| | | try: |
| | | return workflow_engine.update_session_meta(session_id, body if isinstance(body, dict) else {}, allowed_keys) |
| | | except KeyError: |
| | | raise HTTPException(404, "Session not found") |
| | | |
| | | |
| | | @router.post("/api/project/{session_id}/artifact/{stage}/upload_image") |
| | |
| | | |
| | | @router.post("/api/project/{session_id}/intervene") |
| | | async def intervene(session_id: str, req: InterventionRequest, request: Request): |
| | | state = workflow_engine.get_state(session_id) |
| | | if not state: |
| | | try: |
| | | state, input_data = workflow_engine.prepare_intervention_execution( |
| | | session_id=session_id, |
| | | stage=req.stage, |
| | | modifications=req.modifications, |
| | | ) |
| | | except KeyError: |
| | | raise HTTPException(404, "Session not found") |
| | | |
| | | cancellation_check, on_disconnect = make_cancellation(workflow_engine, session_id) |
| | | progress_events, event_trigger, progress_callback = make_progress_channel() |
| | | |
| | | with workflow_engine._state_lock: |
| | | current_artifact = copy.deepcopy(state.artifacts.get(req.stage, {})) |
| | | meta_snapshot = copy.deepcopy(state.meta) |
| | | artifact_snapshot = copy.deepcopy(state.artifacts) |
| | | input_data = current_artifact if isinstance(current_artifact, dict) else {} |
| | | input_data["session_id"] = session_id |
| | | if meta_snapshot: |
| | | for k, v in meta_snapshot.items(): |
| | | if v is not None and k not in input_data: |
| | | input_data[k] = v |
| | | state_for_input = SimpleNamespace(artifacts=artifact_snapshot) |
| | | inject_user_selections(state_for_input, req.stage, input_data) |
| | | input_data.update(req.modifications) |
| | | |
| | | return StreamingResponse( |
| | | stream_workflow_task( |
| | |
| | | |
| | | @router.post("/api/project/{session_id}/continue") |
| | | async def continue_workflow(session_id: str): |
| | | state = workflow_engine.get_state(session_id) |
| | | if not state: |
| | | if not workflow_engine.get_status_snapshot(session_id): |
| | | raise HTTPException(404, "Session not found") |
| | | return await workflow_engine.continue_workflow(session_id) |
| | | |
| | |
| | | |
| | | @router.get("/api/project/{session_id}/scene/{scene_number}/assets") |
| | | async def check_scene_assets(session_id: str, scene_number: int): |
| | | state = workflow_engine.get_state(session_id) |
| | | with workflow_engine._state_lock: |
| | | artifacts_snapshot = copy.deepcopy(state.artifacts) if state else {} |
| | | result_file = os.path.join(settings.RESULT_DIR, 'script', f'{session_id}.json') |
| | | if not os.path.exists(result_file): |
| | | return {"scene_number": scene_number, "reference_images": 0, "videos": 0} |
| | | |
| | | with open(result_file, 'r', encoding='utf-8') as f: |
| | | results = json.load(f) |
| | | |
| | | if isinstance(results, dict): |
| | | script_data = results.get(session_id, results) if results.get(session_id) else results |
| | | else: |
| | | script_data = next((item for item in results if isinstance(item, dict) and item.get("session_id") == session_id), {}) |
| | | |
| | | storyboard = script_data.get('storyboard', {}) |
| | | if not storyboard: |
| | | storyboard = results.get('storyboard', {}) if isinstance(results, dict) else {} |
| | | |
| | | shots = storyboard.get('shots', []) |
| | | scene_shots = [s for s in shots if s.get('scene_number') == scene_number] |
| | | shot_ids = [s.get('shot_id') for s in scene_shots if s.get('shot_id')] |
| | | |
| | | ref_artifact = script_data.get('reference_generation', {}) |
| | | if not ref_artifact: |
| | | ref_artifact = artifacts_snapshot.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: |
| | | selected = sc.get('selected') |
| | | if selected and os.path.exists(os.path.join(settings.CODE_DIR, selected.lstrip('/'))): |
| | | ref_image_count += 1 |
| | | versions = sc.get('versions', []) |
| | | for v in versions: |
| | | if v and os.path.exists(os.path.join(settings.CODE_DIR, v.lstrip('/'))): |
| | | ref_image_count += 1 |
| | | |
| | | video_artifact = script_data.get('video_generation', {}) |
| | | if not video_artifact: |
| | | video_artifact = artifacts_snapshot.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: |
| | | selected = vc.get('selected') |
| | | if selected and os.path.exists(os.path.join(settings.CODE_DIR, selected.lstrip('/'))): |
| | | video_count += 1 |
| | | |
| | | return { |
| | | "scene_number": scene_number, |
| | | "reference_images": ref_image_count, |
| | | "videos": video_count, |
| | | "shot_count": len(scene_shots), |
| | | } |
| | | try: |
| | | return workflow_engine.get_scene_asset_counts(session_id, scene_number) |
| | | except KeyError: |
| | | raise HTTPException(404, "Session not found") |
| | |
| | | import asyncio |
| | | import copy |
| | | import json |
| | | import queue |
| | | import threading |
| | |
| | | "video_generation": "视频生成", |
| | | "post_production": "后期剪辑", |
| | | } |
| | | |
| | | |
| | | def inject_user_selections(state, stage: str, data: dict): |
| | | """Inject persisted user choices into downstream stage input.""" |
| | | if stage == 'video_generation' and 'selected_images' not in data: |
| | | ref_art = state.artifacts.get('reference_generation', {}) |
| | | if isinstance(ref_art, dict): |
| | | scenes = ref_art.get('scenes', []) |
| | | selected_images = {s['id']: s['selected'] for s in scenes |
| | | if isinstance(s, dict) and s.get('id') and s.get('selected')} |
| | | if selected_images: |
| | | data['selected_images'] = selected_images |
| | | |
| | | if stage == 'video_generation' and 'clips' not in data: |
| | | vid_art = state.artifacts.get('video_generation', {}) |
| | | if isinstance(vid_art, dict): |
| | | clips = vid_art.get('clips', []) |
| | | if clips: |
| | | data['clips'] = clips |
| | | |
| | | if stage == 'post_production' and 'selected_clips' not in data: |
| | | vid_art = state.artifacts.get('video_generation', {}) |
| | | if isinstance(vid_art, dict): |
| | | clips = vid_art.get('clips', []) |
| | | selected_clips = {c['id']: c['selected'] for c in clips |
| | | if isinstance(c, dict) and c.get('id') and c.get('selected')} |
| | | if selected_clips: |
| | | data['selected_clips'] = selected_clips |
| | | |
| | | |
| | | |
| | | def build_openclaw_message(stage: str, result: Dict[str, Any]) -> str: |
| | |
| | | break |
| | | |
| | | result = task.result() |
| | | workflow_engine.save_session_to_disk(state.session_id) |
| | | with workflow_engine._state_lock: |
| | | status_snapshot = copy.deepcopy(state.status) |
| | | status_snapshot = workflow_engine.persist_session_snapshot(state.session_id) |
| | | |
| | | payload = { |
| | | "type": "stage_complete", |
| | |
| | | |
| | | except Exception as e: |
| | | try: |
| | | workflow_engine.save_session_to_disk(state.session_id) |
| | | workflow_engine.persist_session_snapshot(state.session_id) |
| | | except Exception: |
| | | pass |
| | | yield json.dumps({"type": "error", "content": str(e)}) + "\n" |
| | |
| | | self._stop_events[session_id] = threading.Event() |
| | | return self._stop_events[session_id] |
| | | |
| | | def create_session(self, session_id: str, meta: Dict[str, Any]) -> Dict[str, Any]: |
| | | """Create or initialize a workflow session through the engine-owned state.""" |
| | | with self._state_lock: |
| | | state = self.get_or_create_state(session_id) |
| | | state.started_at = datetime.now() |
| | | if not isinstance(state.status, dict): |
| | | state.status = {} |
| | | state.status[state.current_stage.value] = "completed" |
| | | state.meta = copy.deepcopy(meta) |
| | | state.updated_at = datetime.now() |
| | | self.save_session_to_disk(session_id, meta) |
| | | return { |
| | | "session_id": session_id, |
| | | "status": copy.deepcopy(state.status), |
| | | "meta": copy.deepcopy(state.meta), |
| | | } |
| | | |
| | | def get_status_snapshot(self, session_id: str) -> Optional[Dict[str, Any]]: |
| | | """Return a deep-copied session snapshot from the unified in-memory state.""" |
| | | with self._state_lock: |
| | | state = self.get_state(session_id) |
| | | return state.to_dict() if state else None |
| | | |
| | | def get_artifact_snapshot(self, session_id: str, stage: str) -> Optional[Any]: |
| | | """Return a deep-copied artifact snapshot from the unified in-memory state.""" |
| | | with self._state_lock: |
| | | state = self.get_state(session_id) |
| | | if not state: |
| | | raise KeyError(f"Session not found: {session_id}") |
| | | artifact = state.artifacts.get(stage) |
| | | return copy.deepcopy(artifact) if artifact is not None else None |
| | | |
| | | def update_session_meta(self, session_id: str, updates: Dict[str, Any], allowed_keys: tuple[str, ...]) -> Dict[str, Any]: |
| | | """Update session-level generation settings through the engine-owned meta store.""" |
| | | with self._state_lock: |
| | | state = self.get_state(session_id) |
| | | if not state: |
| | | raise KeyError(f"Session not found: {session_id}") |
| | | if not state.meta: |
| | | state.meta = {} |
| | | for key in allowed_keys: |
| | | if key in updates: |
| | | state.meta[key] = updates[key] |
| | | state.updated_at = datetime.now() |
| | | self.save_session_to_disk(session_id) |
| | | return {"status": "ok", "meta": copy.deepcopy(state.meta)} |
| | | |
| | | def prepare_stage_execution(self, session_id: str, stage: str, body: Dict[str, Any]) -> tuple[WorkflowState, Dict[str, Any]]: |
| | | """Build stage input from current meta/artifacts without exposing mutable state to routers.""" |
| | | with self._state_lock: |
| | | state = self.get_or_create_state(session_id) |
| | | input_data = copy.deepcopy(body) if isinstance(body, dict) else {} |
| | | input_data["session_id"] = session_id |
| | | |
| | | for key, value in copy.deepcopy(state.meta).items(): |
| | | if value is not None and (key not in input_data or not input_data[key]): |
| | | input_data[key] = value |
| | | self._inject_user_selections(copy.deepcopy(state.artifacts), stage, input_data) |
| | | return state, input_data |
| | | |
| | | def prepare_intervention_execution( |
| | | self, |
| | | session_id: str, |
| | | stage: str, |
| | | modifications: Dict[str, Any], |
| | | ) -> tuple[WorkflowState, Dict[str, Any]]: |
| | | """Build intervention input from the latest artifact/meta snapshot.""" |
| | | with self._state_lock: |
| | | state = self.get_state(session_id) |
| | | if not state: |
| | | raise KeyError(f"Session not found: {session_id}") |
| | | |
| | | current_artifact = copy.deepcopy(state.artifacts.get(stage, {})) |
| | | input_data = current_artifact if isinstance(current_artifact, dict) else {} |
| | | input_data["session_id"] = session_id |
| | | for key, value in copy.deepcopy(state.meta).items(): |
| | | if value is not None and key not in input_data: |
| | | input_data[key] = value |
| | | self._inject_user_selections(copy.deepcopy(state.artifacts), stage, input_data) |
| | | input_data.update(modifications or {}) |
| | | return state, input_data |
| | | |
| | | @staticmethod |
| | | def _inject_user_selections(artifacts: Dict[str, Any], stage: str, data: Dict[str, Any]): |
| | | """Inject persisted user choices into downstream stage input.""" |
| | | if stage == 'video_generation' and 'selected_images' not in data: |
| | | ref_art = artifacts.get('reference_generation', {}) |
| | | if isinstance(ref_art, dict): |
| | | scenes = ref_art.get('scenes', []) |
| | | selected_images = { |
| | | s['id']: s['selected'] |
| | | for s in scenes |
| | | if isinstance(s, dict) and s.get('id') and s.get('selected') |
| | | } |
| | | if selected_images: |
| | | data['selected_images'] = selected_images |
| | | |
| | | if stage == 'video_generation' and 'clips' not in data: |
| | | vid_art = artifacts.get('video_generation', {}) |
| | | if isinstance(vid_art, dict): |
| | | clips = vid_art.get('clips', []) |
| | | if clips: |
| | | data['clips'] = clips |
| | | |
| | | if stage == 'post_production' and 'selected_clips' not in data: |
| | | vid_art = artifacts.get('video_generation', {}) |
| | | if isinstance(vid_art, dict): |
| | | clips = vid_art.get('clips', []) |
| | | selected_clips = { |
| | | c['id']: c['selected'] |
| | | for c in clips |
| | | if isinstance(c, dict) and c.get('id') and c.get('selected') |
| | | } |
| | | if selected_clips: |
| | | data['selected_clips'] = selected_clips |
| | | |
| | | def persist_session_snapshot(self, session_id: str) -> Dict[str, Any]: |
| | | """Persist the latest engine-owned state and return a status snapshot.""" |
| | | with self._state_lock: |
| | | state = self.get_state(session_id) |
| | | if not state: |
| | | raise KeyError(f"Session not found: {session_id}") |
| | | self.save_session_to_disk(session_id) |
| | | return copy.deepcopy(state.status) |
| | | |
| | | def stop_session(self, session_id: str): |
| | | self.get_stop_event(session_id).set() |
| | | with self._state_lock: |
| | |
| | | logger.info(f"Session and results deleted: {session_id}") |
| | | return True |
| | | |
| | | def cleanup_orphan_results(self) -> Dict[str, Any]: |
| | | """Remove result files whose session no longer exists.""" |
| | | from config import settings |
| | | |
| | | with self._state_lock: |
| | | session_ids = set(self.sessions.keys()) |
| | | if os.path.isdir(self._session_dir): |
| | | for filename in os.listdir(self._session_dir): |
| | | if filename.endswith('.json'): |
| | | session_ids.add(filename[:-5]) |
| | | |
| | | cleaned = {"scripts": [], "images": [], "videos": []} |
| | | result_base = settings.RESULT_DIR |
| | | |
| | | script_dir = os.path.join(result_base, 'script') |
| | | if os.path.isdir(script_dir): |
| | | for filename in os.listdir(script_dir): |
| | | if not filename.endswith('.json'): |
| | | continue |
| | | sid = filename[:-5] |
| | | if sid not in session_ids: |
| | | os.remove(os.path.join(script_dir, filename)) |
| | | cleaned["scripts"].append(sid) |
| | | |
| | | image_dir = os.path.join(result_base, 'image') |
| | | if os.path.isdir(image_dir): |
| | | for dirname in os.listdir(image_dir): |
| | | if dirname != 'test_avail' and dirname not in session_ids: |
| | | shutil.rmtree(os.path.join(image_dir, dirname)) |
| | | cleaned["images"].append(dirname) |
| | | |
| | | video_dir = os.path.join(result_base, 'video') |
| | | if os.path.isdir(video_dir): |
| | | for dirname in os.listdir(video_dir): |
| | | if dirname != 'test_avail' and dirname not in session_ids: |
| | | shutil.rmtree(os.path.join(video_dir, dirname)) |
| | | cleaned["videos"].append(dirname) |
| | | |
| | | return {"status": "cleaned", "cleaned": cleaned} |
| | | |
| | | def get_scene_asset_counts(self, session_id: str, scene_number: int) -> Dict[str, Any]: |
| | | """Count generated reference images/videos from the current artifact state only.""" |
| | | from config import settings |
| | | |
| | | with self._state_lock: |
| | | state = self.get_state(session_id) |
| | | if not state: |
| | | raise KeyError(f"Session not found: {session_id}") |
| | | artifacts = copy.deepcopy(state.artifacts) |
| | | |
| | | storyboard = artifacts.get('storyboard', {}) |
| | | segment_ids = self._segment_ids_for_scene(storyboard, scene_number) |
| | | |
| | | ref_artifact = artifacts.get('reference_generation', {}) |
| | | ref_scenes = ref_artifact.get('scenes', []) if isinstance(ref_artifact, dict) else [] |
| | | ref_image_count = self._count_existing_assets(ref_scenes, segment_ids, settings.CODE_DIR, include_versions=True) |
| | | |
| | | video_artifact = artifacts.get('video_generation', {}) |
| | | video_clips = video_artifact.get('clips', []) if isinstance(video_artifact, dict) else [] |
| | | video_count = self._count_existing_assets(video_clips, segment_ids, settings.CODE_DIR, include_versions=False) |
| | | |
| | | return { |
| | | "scene_number": scene_number, |
| | | "reference_images": ref_image_count, |
| | | "videos": video_count, |
| | | "shot_count": len(segment_ids), |
| | | } |
| | | |
| | | @staticmethod |
| | | def _segment_ids_for_scene(storyboard: Any, scene_number: int) -> List[str]: |
| | | if not isinstance(storyboard, dict): |
| | | return [] |
| | | |
| | | ids: List[str] = [] |
| | | for shot in storyboard.get('shots', []): |
| | | if isinstance(shot, dict) and shot.get('scene_number') == scene_number and shot.get('shot_id'): |
| | | ids.append(shot['shot_id']) |
| | | |
| | | for episode in storyboard.get('episodes', []): |
| | | if not isinstance(episode, dict): |
| | | continue |
| | | for segment in episode.get('segments', []): |
| | | if not isinstance(segment, dict): |
| | | continue |
| | | segment_scene = segment.get('scene_number') or segment.get('segment_number') |
| | | if segment_scene == scene_number and segment.get('segment_id'): |
| | | ids.append(segment['segment_id']) |
| | | |
| | | return list(dict.fromkeys(ids)) |
| | | |
| | | @staticmethod |
| | | def _asset_exists(code_dir: str, path: str) -> bool: |
| | | if not path: |
| | | return False |
| | | candidate = path if os.path.isabs(path) else os.path.join(code_dir, path.lstrip('/')) |
| | | return os.path.exists(candidate) |
| | | |
| | | @classmethod |
| | | def _count_existing_assets( |
| | | cls, |
| | | items: List[Any], |
| | | target_ids: List[str], |
| | | code_dir: str, |
| | | *, |
| | | include_versions: bool, |
| | | ) -> int: |
| | | count = 0 |
| | | target_set = set(target_ids) |
| | | for item in items: |
| | | if not isinstance(item, dict) or item.get('id') not in target_set: |
| | | continue |
| | | selected = item.get('selected') |
| | | if selected and cls._asset_exists(code_dir, selected): |
| | | count += 1 |
| | | if include_versions: |
| | | versions = item.get('versions', []) |
| | | for version in versions if isinstance(versions, list) else []: |
| | | if version and version != selected and cls._asset_exists(code_dir, version): |
| | | count += 1 |
| | | return count |
| | | |
| | | def list_saved_sessions(self) -> List[Dict]: |
| | | """列出所有已保存的会话概要""" |
| | | with self._state_lock: |
| | |
| | | }); |
| | | } |
| | | |
| | | function hasRunningArtifactItems(artifact: any): boolean { |
| | | if (!artifact) return false; |
| | | return ['clips', 'images', 'scenes', 'characters', 'settings'].some(key => { |
| | | const items = artifact?.[key]; |
| | | return Array.isArray(items) && items.some((item: any) => item?.status === 'running'); |
| | | }); |
| | | } |
| | | |
| | | function getStageProgressSnapshot(status: any, stageId: string): Partial<StageState> { |
| | | const snapshot = status?.stage_progress?.[stageId]; |
| | | if (!snapshot || typeof snapshot !== 'object') return {}; |
| | |
| | | |
| | | const abortRef = useRef<AbortController | null>(null); |
| | | const stoppedRef = useRef(false); |
| | | const pollRef = useRef<string | null>(null); |
| | | const pollRef = useRef<Set<string>>(new Set()); |
| | | |
| | | // 清理轮询 |
| | | useEffect(() => { |
| | | return () => { pollRef.current = null; }; |
| | | return () => { pollRef.current.clear(); }; |
| | | }, []); |
| | | |
| | | // 轮询等待后端阶段完成。运行中优先读后端内存,后端重启后再回退到磁盘快照。 |
| | | const pollForCompletion = useCallback(async (sid: string, stageId: string) => { |
| | | const key = `${sid}:${stageId}`; |
| | | pollRef.current = key; |
| | | pollRef.current.add(key); |
| | | for (let i = 0; i < 300; i++) { // 增加轮询次数(最多10分钟) |
| | | await new Promise(r => setTimeout(r, 2000)); |
| | | if (pollRef.current !== key) return; |
| | | if (!pollRef.current.has(key)) return; |
| | | try { |
| | | let status: any; |
| | | try { |
| | |
| | | } catch { |
| | | status = await getProjectStatusFromDisk(sid); |
| | | } |
| | | if (pollRef.current !== key) return; |
| | | if (!pollRef.current.has(key)) return; |
| | | 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 artifacts = status.artifacts || {}; |
| | | const currentArtifact = artifacts[stageId]; |
| | | const hasRunningItems = hasRunningArtifactItems(currentArtifact); |
| | | if (done.includes(stageId) && !hasRunningItems) { |
| | | const isWait = currentStageStatus === 'waiting' && status.current_stage === stageId; |
| | | let artifact = null; |
| | | try { artifact = (await getArtifact(sid, stageId)).artifact; } catch {} |
| | |
| | | progressMessage: isWait ? '等待确认' : '已完成', |
| | | artifact, |
| | | }); |
| | | pollRef.current = null; |
| | | pollRef.current.delete(key); |
| | | return; |
| | | } |
| | | if (currentStageStatus === 'error') { |
| | | if (currentStageStatus === 'error' && !hasRunningItems) { |
| | | updateStageState(stageId, { |
| | | status: 'error', |
| | | error: status.error || '执行出错', |
| | | progressMessage: '执行失败', |
| | | }); |
| | | pollRef.current = null; |
| | | pollRef.current.delete(key); |
| | | return; |
| | | } |
| | | if (currentStageStatus === 'stopped') { |
| | | if (currentStageStatus === 'stopped' && !hasRunningItems) { |
| | | updateStageState(stageId, { |
| | | status: 'stopped', |
| | | error: '手动停止', |
| | | progressMessage: '已停止', |
| | | }); |
| | | pollRef.current = null; |
| | | pollRef.current.delete(key); |
| | | return; |
| | | } |
| | | // 如果当前阶段不再是 running,提前停止轮询(比如变成了 waiting_intervention 或已完成) |
| | | if (currentStageStatus !== 'running') { |
| | | pollRef.current = null; |
| | | // 后台单卡重生成时,阶段状态可能仍是 waiting/completed;只要 item 还在 running 就继续轮询。 |
| | | if (currentStageStatus !== 'running' && !hasRunningItems) { |
| | | updateStageState(stageId, { |
| | | status: currentStageStatus === 'waiting' |
| | | ? 'waiting' |
| | | : (done.includes(stageId) ? 'completed' : 'pending'), |
| | | progress: done.includes(stageId) ? 100 : undefined, |
| | | progressMessage: currentStageStatus === 'waiting' |
| | | ? '等待确认' |
| | | : (done.includes(stageId) ? '已完成' : undefined), |
| | | artifact: currentArtifact || null, |
| | | }); |
| | | pollRef.current.delete(key); |
| | | return; |
| | | } |
| | | // 更新进度信息(优先使用后端持久化的 stage_progress 快照) |
| | | const artifacts = status.artifacts || {}; |
| | | const currentArtifact = artifacts[stageId]; |
| | | const update: Partial<StageState> = { |
| | | status: 'running', |
| | | ...getStageProgressSnapshot(status, stageId), |
| | |
| | | } |
| | | } catch { /* retry */ } |
| | | } |
| | | pollRef.current.delete(key); |
| | | }, []); |
| | | |
| | | // 检查 URL 参数,加载指定的 session 和阶段 |
| | |
| | | setActiveStage(finalStage); |
| | | setStageStates(newStates); |
| | | |
| | | // 轮询当前正在执行的阶段(仅当该阶段有 artifact 数据时) |
| | | if (currentStage && stMap[currentStage] === 'running') { |
| | | pollForCompletion(sid, currentStage); |
| | | // 轮询正在执行的阶段;后台单卡重生成时阶段可能不是 running,但 item 会是 running。 |
| | | for (const stageId of STAGE_ORDER) { |
| | | if (stMap[stageId] === 'running' || hasRunningArtifactItems(status.artifacts?.[stageId])) { |
| | | pollForCompletion(sid, stageId); |
| | | } |
| | | } |
| | | } catch { |
| | | setActiveStage(STAGE_ORDER[0]); |
| | |
| | | description: string; |
| | | selected: string; // 当前选中的文件路径 |
| | | versions: string[]; // 所有历史版本路径 |
| | | status?: 'pending' | 'done' | 'failed'; // 生成状态 |
| | | status?: 'pending' | 'done' | 'failed' | 'running'; // 生成状态 |
| | | } |
| | | |
| | | /* ─── 水平滚动图片画廊 ─── */ |
| | |
| | | <img |
| | | src={assetUrl(path)} |
| | | alt={`v${i + 1}`} |
| | | className="h-28 w-auto object-cover" |
| | | className="h-32 w-auto object-cover" |
| | | onError={(e) => { (e.target as HTMLImageElement).style.display = 'none'; }} |
| | | /> |
| | | <button |
| | |
| | | ); |
| | | })} |
| | | {showPlaceholder && ( |
| | | <div className="flex-shrink-0 flex items-center justify-center h-28 aspect-video bg-gray-50 rounded-lg border border-dashed border-gray-200"> |
| | | <div className="flex-shrink-0 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"> |
| | | <Loader className="w-4 h-4 animate-spin" /> |
| | | <span>生成中...</span> |
| | |
| | | isRegenerating?: boolean; |
| | | isUploading?: boolean; |
| | | }) { |
| | | const isPending = asset.status === 'pending' || isRegenerating; |
| | | const isRunning = asset.status === 'running' || isRegenerating; |
| | | const isPending = asset.status === 'pending'; |
| | | const isFailed = asset.status === 'failed' && !isRegenerating; |
| | | const hasImage = Boolean(asset.selected) || asset.versions.length > 0; |
| | | const canGenerateMissing = !hasImage && !isPending && !isRegenerating; |
| | | const canGenerateMissing = !hasImage && !isPending && !isRunning; |
| | | const canShowRegenerate = !isRunning && !isPending && (hasImage || isFailed || canGenerateMissing); |
| | | |
| | | return ( |
| | | <div className={`flex flex-col xl:flex-row border rounded-xl overflow-hidden bg-white ${ |
| | |
| | | : <MapPin className="w-3.5 h-3.5 text-emerald-500" /> |
| | | } |
| | | <span className="text-sm font-semibold text-gray-800 truncate">{asset.name}</span> |
| | | {isPending && ( |
| | | {(isPending || 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" />生成中 |
| | | {isRunning && <Loader className="w-2.5 h-2.5 animate-spin" />} |
| | | {isRunning ? '生成中' : '等待中'} |
| | | </span> |
| | | )} |
| | | {isFailed && ( |
| | |
| | | <p className="text-xs text-gray-600 leading-relaxed">{asset.description}</p> |
| | | </div> |
| | | )} |
| | | {/* 已有图片显示重新生成;失败/旧数据空资源允许补生成。 */} |
| | | {!isStageRunning && (hasImage || isFailed || canGenerateMissing) && ( |
| | | <div className="mt-3 flex flex-wrap items-center gap-2"> |
| | | {canShowRegenerate && ( |
| | | <button |
| | | onClick={onRegenerate} |
| | | disabled={isRegenerating} |
| | | className={`mt-3 flex items-center gap-1.5 self-start px-3 py-1.5 rounded-lg text-xs font-medium transition-colors ${ |
| | | isRegenerating |
| | | ? 'text-gray-400 bg-gray-100 cursor-not-allowed' |
| | | : isFailed |
| | | className={`inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium transition-colors ${ |
| | | isFailed |
| | | ? 'text-red-600 bg-red-50 hover:bg-red-100' |
| | | : 'text-violet-600 bg-violet-50 hover:bg-violet-100' |
| | | }`} |
| | | > |
| | | <RefreshCw className={`w-3 h-3 ${isRegenerating ? 'animate-spin' : ''}`} /> |
| | | {isRegenerating ? '生成中...' : isFailed ? '点击重试' : hasImage ? '重新生成' : '生成'} |
| | | <RefreshCw className="w-3 h-3" /> |
| | | {isFailed ? '点击重试' : hasImage ? '重新生成' : '生成'} |
| | | </button> |
| | | )} |
| | | {!isStageRunning && ( |
| | | <label className={`mt-2 ml-auto inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium transition-colors ${ |
| | | <label className={`ml-auto inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium transition-colors ${ |
| | | isUploading |
| | | ? 'text-gray-400 bg-gray-100 cursor-wait' |
| | | : 'text-gray-600 bg-gray-100 hover:bg-gray-200 cursor-pointer' |
| | | }`}> |
| | | {isUploading ? <Loader className="w-3 h-3 animate-spin" /> : <Upload className="w-3 h-3" />} |
| | | {isUploading ? '上传中...' : '上传图片'} |
| | | {isUploading ? '上传中...' : '上传照片'} |
| | | <input |
| | | type="file" |
| | | accept="image/*" |
| | |
| | | }} |
| | | /> |
| | | </label> |
| | | )} |
| | | </div> |
| | | </div> |
| | | |
| | | {/* 右侧: 图片画廊 / 占位 */} |
| | | <div className="flex-1 min-w-0 p-3 flex items-center"> |
| | | {isPending && !hasImage ? ( |
| | | <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 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"> |
| | | <Loader className="w-4 h-4 animate-spin" /> |
| | | <span>正在生成...</span> |
| | | </div> |
| | | </div> |
| | | ) : !hasImage ? ( |
| | | <div className="flex items-center justify-center h-28 aspect-video bg-gray-50/60 rounded-lg border border-dashed border-gray-200"> |
| | | <div className="flex items-center justify-center h-32 aspect-video bg-gray-50/60 rounded-lg border border-dashed border-gray-200"> |
| | | <div className="flex flex-col items-center gap-1 text-gray-400 text-xs"> |
| | | {isFailed ? ( |
| | | <> |
| | | <AlertCircle className="w-4 h-4" /> |
| | | <span>生成失败</span> |
| | | {!isStageRunning && ( |
| | | {!isRunning && ( |
| | | <button |
| | | onClick={onRegenerate} |
| | | disabled={isRegenerating} |
| | |
| | | <> |
| | | <ImagePlus className="w-4 h-4" /> |
| | | <span>暂无图片</span> |
| | | {!isStageRunning && canGenerateMissing && ( |
| | | {canGenerateMissing && ( |
| | | <button |
| | | onClick={onRegenerate} |
| | | disabled={isRegenerating} |
| | |
| | | versions={asset.versions} |
| | | selected={asset.selected} |
| | | onSelect={onSelectVersion} |
| | | showPlaceholder={isRegenerating} |
| | | showPlaceholder={isRunning} |
| | | /> |
| | | {isFailed && ( |
| | | <button |
| | |
| | | <img |
| | | src={assetUrl(path)} |
| | | alt={`v${i + 1}`} |
| | | className="h-28 w-auto object-cover" |
| | | className="h-32 w-auto object-cover" |
| | | onError={(e) => { (e.target as HTMLImageElement).style.display = 'none'; }} |
| | | /> |
| | | <button |
| | |
| | | ); |
| | | })} |
| | | {showPlaceholder && ( |
| | | <div className="flex-shrink-0 flex items-center justify-center h-28 aspect-video bg-gray-50 rounded-lg border border-dashed border-gray-200"> |
| | | <div className="flex-shrink-0 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"> |
| | | <Loader className="w-4 h-4 animate-spin" /> |
| | | <span>生成中...</span> |
| | |
| | | const isFailed = scene.status === 'failed' && !isRegenerating; |
| | | const hasImage = Boolean(getSelected(scene)) || scene.versions.length > 0; |
| | | const canGenerateMissing = Boolean(allowMissingGenerate) && !hasImage && !isRunning && !isRegenerating; |
| | | const canShowRegenerate = !isRunning && !isPending && (hasImage || isFailed || canGenerateMissing); |
| | | const hasChanges = editDesc !== scene.description; |
| | | |
| | | return ( |
| | |
| | | <p className="text-xs text-gray-600 leading-relaxed whitespace-pre-wrap">{scene.description}</p> |
| | | </div> |
| | | )} |
| | | {/* 已有图片显示重新生成;失败/旧数据空资源允许补生成。 */} |
| | | {!isStageRunning && (hasImage || isFailed || canGenerateMissing) && ( |
| | | <div className="mt-3 flex flex-wrap items-center gap-2"> |
| | | {canShowRegenerate && ( |
| | | <button |
| | | onClick={onRegenerate} |
| | | disabled={isRegenerating} |
| | | className={`mt-3 flex items-center gap-1.5 self-start px-3 py-1.5 rounded-lg text-xs font-medium transition-colors ${ |
| | | isRegenerating |
| | | ? 'text-gray-400 bg-gray-100 cursor-not-allowed' |
| | | : isFailed |
| | | className={`inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium transition-colors ${ |
| | | isFailed |
| | | ? 'text-red-600 bg-red-50 hover:bg-red-100' |
| | | : 'text-emerald-600 bg-emerald-50 hover:bg-emerald-100' |
| | | }`} |
| | | > |
| | | <RefreshCw className={`w-3 h-3 ${isRegenerating ? 'animate-spin' : ''}`} /> |
| | | {isRegenerating ? '生成中...' : isFailed ? '点击重试' : hasImage ? '重新生成' : '生成'} |
| | | <RefreshCw className="w-3 h-3" /> |
| | | {isFailed ? '点击重试' : hasImage ? '重新生成' : '生成'} |
| | | </button> |
| | | )} |
| | | {!isStageRunning && ( |
| | | <label className={`mt-2 ml-auto inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium transition-colors ${ |
| | | <label className={`ml-auto inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium transition-colors ${ |
| | | isUploading |
| | | ? 'text-gray-400 bg-gray-100 cursor-wait' |
| | | : 'text-gray-600 bg-gray-100 hover:bg-gray-200 cursor-pointer' |
| | | }`}> |
| | | {isUploading ? <Loader className="w-3 h-3 animate-spin" /> : <Upload className="w-3 h-3" />} |
| | | {isUploading ? '上传中...' : '上传图片'} |
| | | {isUploading ? '上传中...' : '上传照片'} |
| | | <input |
| | | type="file" |
| | | accept="image/*" |
| | |
| | | }} |
| | | /> |
| | | </label> |
| | | )} |
| | | </div> |
| | | </div> |
| | | |
| | | {/* 右侧: 图片画廊 / 占位 */} |
| | | <div className="flex-1 min-w-0 p-3 flex items-center"> |
| | | {isRunning && !hasImage ? ( |
| | | <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 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"> |
| | | <Loader className="w-4 h-4 animate-spin" /> |
| | | <span>正在生成...</span> |
| | | </div> |
| | | </div> |
| | | ) : !hasImage ? ( |
| | | <div className="flex items-center justify-center h-28 aspect-video bg-gray-50/60 rounded-lg border border-dashed border-gray-200"> |
| | | <div className="flex items-center justify-center h-32 aspect-video bg-gray-50/60 rounded-lg border border-dashed border-gray-200"> |
| | | <div className="flex flex-col items-center gap-1 text-gray-400 text-xs"> |
| | | {isFailed ? ( |
| | | <> |
| | | <AlertCircle className="w-4 h-4" /> |
| | | <span>生成失败</span> |
| | | {!isStageRunning && ( |
| | | {!isRunning && ( |
| | | <button |
| | | onClick={onRegenerate} |
| | | disabled={isRegenerating} |
| | |
| | | <> |
| | | <ImagePlus className="w-4 h-4" /> |
| | | <span>{isPending ? '等待生成...' : '暂无图片'}</span> |
| | | {!isStageRunning && canGenerateMissing && ( |
| | | {canGenerateMissing && ( |
| | | <button |
| | | onClick={onRegenerate} |
| | | disabled={isRegenerating} |
| | |
| | | versions={scene.versions} |
| | | selected={getSelected(scene)} |
| | | onSelect={onSelectVersion} |
| | | showPlaceholder={isRegenerating} |
| | | showPlaceholder={isRunning} |
| | | /> |
| | | {isFailed && ( |
| | | <button |
| | |
| | | versions={clip.versions} |
| | | selected={clip.selected} |
| | | onSelect={onSelectVersion} |
| | | showPlaceholder={isRegenerating} |
| | | showPlaceholder={isRunning} |
| | | /> |
| | | {isFailed && ( |
| | | <button |