| | |
| | | import json |
| | | import logging |
| | | import os |
| | | import re |
| | | import shutil |
| | | import threading |
| | | import time |
| | | import copy |
| | |
| | | "image_t2i_model", |
| | | "image_it2i_model", |
| | | "video_model", |
| | | "video_first_frame_model", |
| | | "video_start_end_model", |
| | | "video_reference_model", |
| | | "video_generation_mode", |
| | | "video_style", |
| | | "enable_concurrency", |
| | | "web_search", |
| | |
| | | nested_meta = data.get("meta") |
| | | if isinstance(nested_meta, dict): |
| | | meta.update({k: _normalize_meta_value(v) for k, v in nested_meta.items() if v is not None}) |
| | | # Legacy session compatibility: old session JSON stored these fields at the root instead of under meta. |
| | | for key in SESSION_META_KEYS: |
| | | if key not in meta and key in data and data[key] is not None: |
| | | meta[key] = _normalize_meta_value(data[key]) |
| | |
| | | class WorkflowState: |
| | | """工作流状态""" |
| | | |
| | | # 状态说明: |
| | | # - pending: 新建会话,还没有任何数据,也没有在运行 |
| | | # - running: 会话正在运行 |
| | | # - waiting: 会话在某一阶段内等待用户介入(如选择角色、选择图片等) |
| | | # - completed: 会话完成了某一阶段,等待用户确定开始下一阶段 |
| | | # - completed: 会话全部完成 |
| | | # - stopped: 用户手动停止 |
| | | # - error: 执行中遇到错误 |
| | | # 阶段状态说明: |
| | | # - pending: 阶段还没有产物,也没有在运行 |
| | | # - running: 阶段正在执行 |
| | | # - waiting: 阶段已产出内容,但需要用户介入(如选择角色、选择图片等) |
| | | # - completed: 阶段已完成,可进入下一阶段 |
| | | # - stopped: 阶段被用户手动停止 |
| | | # - error: 阶段执行中遇到错误 |
| | | |
| | | def __init__(self, session_id: str): |
| | | self.session_id = session_id |
| | |
| | | if session_id not in self._stop_events: |
| | | 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() |
| | |
| | | # 已经有数据且没有 pending 项,标记为完成 |
| | | state.status[s_val] = "completed" |
| | | |
| | | @staticmethod |
| | | def _is_background_item_regeneration(stage: WorkflowStage, intervention: Optional[Dict]) -> bool: |
| | | if not isinstance(intervention, dict): |
| | | return False |
| | | if stage == WorkflowStage.CHARACTER_DESIGN: |
| | | return isinstance(intervention.get("regenerate_characters"), list) or isinstance(intervention.get("regenerate_settings"), list) |
| | | if stage == WorkflowStage.REFERENCE_GENERATION: |
| | | return isinstance(intervention.get("regenerate_scenes"), list) |
| | | if stage == WorkflowStage.VIDEO_GENERATION: |
| | | return isinstance(intervention.get("regenerate_clips"), list) |
| | | return False |
| | | |
| | | @staticmethod |
| | | def _background_regeneration_targets(stage: WorkflowStage, intervention: Optional[Dict]) -> Dict[str, Set[str]]: |
| | | if not isinstance(intervention, dict): |
| | | return {} |
| | | if stage == WorkflowStage.CHARACTER_DESIGN: |
| | | return { |
| | | "characters": set(intervention.get("regenerate_characters") or []), |
| | | "settings": set(intervention.get("regenerate_settings") or []), |
| | | } |
| | | if stage == WorkflowStage.REFERENCE_GENERATION: |
| | | return {"scenes": set(intervention.get("regenerate_scenes") or [])} |
| | | if stage == WorkflowStage.VIDEO_GENERATION: |
| | | return {"clips": set(intervention.get("regenerate_clips") or [])} |
| | | return {} |
| | | |
| | | @staticmethod |
| | | def _merge_item_regeneration_payload( |
| | | existing: Any, |
| | | payload: Any, |
| | | item_keys: List[str], |
| | | target_ids_by_key: Optional[Dict[str, Set[str]]] = None, |
| | | ) -> Dict: |
| | | """Merge concurrent single-item regeneration results without clobbering fresher items.""" |
| | | if not isinstance(existing, dict): |
| | | existing = {} |
| | | if not isinstance(payload, dict): |
| | | return copy.deepcopy(existing) |
| | | |
| | | merged = copy.deepcopy(existing) |
| | | for key, value in payload.items(): |
| | | if key not in item_keys: |
| | | merged[key] = copy.deepcopy(value) |
| | | |
| | | for key in item_keys: |
| | | existing_items = merged.get(key, []) |
| | | payload_items = payload.get(key, []) |
| | | if not isinstance(existing_items, list): |
| | | existing_items = [] |
| | | if not isinstance(payload_items, list): |
| | | merged[key] = existing_items |
| | | continue |
| | | |
| | | target_ids = (target_ids_by_key or {}).get(key) |
| | | by_id = { |
| | | item.get("id"): copy.deepcopy(item) |
| | | for item in existing_items |
| | | if isinstance(item, dict) and item.get("id") |
| | | } |
| | | order = [ |
| | | item.get("id") |
| | | for item in existing_items |
| | | if isinstance(item, dict) and item.get("id") |
| | | ] |
| | | |
| | | for item in payload_items: |
| | | if not isinstance(item, dict) or not item.get("id"): |
| | | continue |
| | | item_id = item["id"] |
| | | if target_ids is not None and item_id not in target_ids: |
| | | continue |
| | | current = by_id.get(item_id) |
| | | if item_id not in order: |
| | | order.append(item_id) |
| | | if not current: |
| | | by_id[item_id] = copy.deepcopy(item) |
| | | continue |
| | | current_versions = current.get("versions") if isinstance(current.get("versions"), list) else [] |
| | | item_versions = item.get("versions") if isinstance(item.get("versions"), list) else [] |
| | | merged_versions = WorkflowEngine._merge_asset_versions(current_versions, item_versions) |
| | | if len(item_versions) > len(current_versions): |
| | | merged_item = {**current, **copy.deepcopy(item)} |
| | | merged_item["versions"] = merged_versions |
| | | if current.get("selected"): |
| | | merged_item["selected"] = current.get("selected") |
| | | if item.get("status") in {"done", "failed"}: |
| | | merged_item["status"] = "done" |
| | | by_id[item_id] = merged_item |
| | | elif len(item_versions) == len(current_versions): |
| | | merged_item = {**current, **copy.deepcopy(item)} |
| | | if not item.get("selected") and current.get("selected"): |
| | | merged_item["selected"] = current.get("selected") |
| | | if current.get("selected"): |
| | | merged_item["selected"] = current.get("selected") |
| | | if item.get("status") in {"done", "failed"}: |
| | | merged_item["status"] = "done" |
| | | if merged_versions: |
| | | merged_item["versions"] = merged_versions |
| | | if ( |
| | | current.get("status") == "failed" |
| | | and item.get("status") == "done" |
| | | and not current.get("selected") |
| | | ): |
| | | merged_item["status"] = "failed" |
| | | by_id[item_id] = merged_item |
| | | |
| | | merged[key] = [by_id[item_id] for item_id in order if item_id in by_id] |
| | | return merged |
| | | |
| | | @staticmethod |
| | | def _merge_asset_versions(current_versions: Any, new_versions: Any) -> List[str]: |
| | | merged: List[str] = [] |
| | | for value in list(current_versions if isinstance(current_versions, list) else []) + list(new_versions if isinstance(new_versions, list) else []): |
| | | if value and value not in merged: |
| | | merged.append(value) |
| | | return merged |
| | | |
| | | @staticmethod |
| | | def _selected_after_asset_update(current_selected: Any, new_selected: Any) -> Any: |
| | | return current_selected or new_selected or "" |
| | | |
| | | async def execute_stage(self, |
| | | state: WorkflowState, |
| | | stage: WorkflowStage, |
| | |
| | | |
| | | agent = self.agent_factories[stage]() |
| | | active_registered = False |
| | | background_item_regeneration = self._is_background_item_regeneration(stage, intervention) |
| | | |
| | | # 合并会话级停止信号与请求级取消检查 |
| | | session_stop = self.get_stop_event(state.session_id) |
| | |
| | | |
| | | for item in items: |
| | | if isinstance(item, dict) and item.get("id") == item_id: |
| | | item["status"] = asset_update.get("status", item.get("status")) |
| | | next_status = asset_update.get("status", item.get("status")) |
| | | if item.get("selected") and next_status in {"done", "failed"}: |
| | | next_status = "done" |
| | | item["status"] = next_status |
| | | if "selected" in asset_update: |
| | | item["selected"] = asset_update.get("selected") or item.get("selected", "") |
| | | item["selected"] = self._selected_after_asset_update( |
| | | item.get("selected"), |
| | | asset_update.get("selected"), |
| | | ) |
| | | if "versions" in asset_update: |
| | | item["versions"] = asset_update.get("versions") or item.get("versions", []) |
| | | item["versions"] = self._merge_asset_versions( |
| | | item.get("versions"), |
| | | asset_update.get("versions"), |
| | | ) |
| | | return |
| | | |
| | | items.append({ |
| | |
| | | if progress_callback: |
| | | agent.set_progress_callback(wrapped_progress_callback) |
| | | |
| | | with self._state_lock: |
| | | if state.session_id in self._active_sessions: |
| | | raise RuntimeError(f"Session {state.session_id} is already running a stage.") |
| | | self._active_sessions.add(state.session_id) |
| | | active_registered = True |
| | | state.current_stage = stage |
| | | state.status[stage.value] = "running" |
| | | state.updated_at = datetime.now() |
| | | state.stage_progress[stage.value] = { |
| | | "phase": stage.value, |
| | | "step": "启动中...", |
| | | "message": "启动中...", |
| | | "percent": 0, |
| | | "updated_at": time.time(), |
| | | } |
| | | try: |
| | | self.save_session_to_disk(state.session_id) |
| | | except Exception: |
| | | self._active_sessions.discard(state.session_id) |
| | | active_registered = False |
| | | raise |
| | | if not background_item_regeneration: |
| | | with self._state_lock: |
| | | if state.session_id in self._active_sessions: |
| | | raise RuntimeError(f"Session {state.session_id} is already running a stage.") |
| | | self._active_sessions.add(state.session_id) |
| | | active_registered = True |
| | | state.current_stage = stage |
| | | state.status[stage.value] = "running" |
| | | state.updated_at = datetime.now() |
| | | state.stage_progress[stage.value] = { |
| | | "phase": stage.value, |
| | | "step": "启动中...", |
| | | "message": "启动中...", |
| | | "percent": 0, |
| | | "updated_at": time.time(), |
| | | } |
| | | try: |
| | | self.save_session_to_disk(state.session_id) |
| | | except Exception: |
| | | self._active_sessions.discard(state.session_id) |
| | | active_registered = False |
| | | raise |
| | | |
| | | try: |
| | | result = await agent.process(input_data, intervention=intervention) |
| | |
| | | state.artifacts[stage.value] = clean_art |
| | | else: |
| | | # 其他阶段正常执行跨阶段同步和赋值 |
| | | if background_item_regeneration: |
| | | if stage == WorkflowStage.CHARACTER_DESIGN: |
| | | keys = ["characters", "settings"] |
| | | elif stage == WorkflowStage.REFERENCE_GENERATION: |
| | | keys = ["scenes"] |
| | | elif stage == WorkflowStage.VIDEO_GENERATION: |
| | | keys = ["clips"] |
| | | else: |
| | | keys = [] |
| | | target_ids = self._background_regeneration_targets(stage, intervention) |
| | | payload = self._merge_item_regeneration_payload(state.artifacts.get(stage.value, {}), payload, keys, target_ids) |
| | | self._sync_artifacts_cross_stages(state, stage, payload) |
| | | state.artifacts[stage.value] = payload |
| | | |
| | |
| | | |
| | | except asyncio.CancelledError: |
| | | with self._state_lock: |
| | | state.status[stage.value] = "stopped" |
| | | if not background_item_regeneration: |
| | | state.status[stage.value] = "stopped" |
| | | state.error = None |
| | | state.updated_at = datetime.now() |
| | | state.stage_progress[stage.value] = { |
| | |
| | | |
| | | except Exception as e: |
| | | with self._state_lock: |
| | | state.status[stage.value] = "error" |
| | | if not background_item_regeneration: |
| | | state.status[stage.value] = "error" |
| | | state.error = str(e) |
| | | state.updated_at = datetime.now() |
| | | state.stage_progress[stage.value] = { |
| | |
| | | if active_registered: |
| | | with self._state_lock: |
| | | self._active_sessions.discard(state.session_id) |
| | | |
| | | async def handle_intervention(self, |
| | | session_id: str, |
| | | stage: str, |
| | | modifications: Dict[str, Any]) -> Dict: |
| | | 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, {})) |
| | | stage_enum = WorkflowStage(stage) |
| | | |
| | | input_data = current_artifact if isinstance(current_artifact, dict) else {} |
| | | input_data.update(modifications) |
| | | |
| | | res = await self.execute_stage(state, stage_enum, input_data, intervention=modifications) |
| | | with self._state_lock: |
| | | # 处理完干预后再次校验状态 |
| | | self._recalculate_all_statuses(state) |
| | | self.save_session_to_disk(session_id) |
| | | return res |
| | | |
| | | async def continue_workflow(self, session_id: str) -> Dict: |
| | | with self._state_lock: |
| | |
| | | "current_status": current_status, |
| | | } |
| | | |
| | | # ──────────── Artifact 统一管理 ──────────── |
| | | |
| | | def update_artifact(self, session_id: str, stage: str, body: Dict[str, Any]) -> Dict[str, Any]: |
| | | """Apply a user edit to an artifact, then recalculate and persist state.""" |
| | | with self._state_lock: |
| | | state = self.get_state(session_id) |
| | | if not state: |
| | | raise KeyError(f"Session not found: {session_id}") |
| | | |
| | | self._apply_artifact_update(state, stage, body if isinstance(body, dict) else {}) |
| | | self._recalculate_all_statuses(state) |
| | | self.save_session_to_disk(session_id) |
| | | return { |
| | | "status": "ok", |
| | | "status_map": copy.deepcopy(state.status), |
| | | "artifact": copy.deepcopy(state.artifacts.get(stage)), |
| | | } |
| | | |
| | | def _apply_artifact_update(self, state: WorkflowState, stage: str, body: Dict[str, Any]): |
| | | """Apply a user edit to in-memory artifacts before the session is persisted.""" |
| | | merge_keys_by_stage = { |
| | | "character_design": ("characters", "settings"), |
| | | "reference_generation": ("scenes",), |
| | | "video_generation": ("clips",), |
| | | } |
| | | if stage in merge_keys_by_stage: |
| | | current_art = state.artifacts.get(stage, {}) |
| | | if isinstance(current_art, dict): |
| | | for list_key in merge_keys_by_stage[stage]: |
| | | if list_key not in body: |
| | | continue |
| | | current_items = current_art.get(list_key, []) |
| | | incoming_items = body.get(list_key, []) |
| | | if not isinstance(current_items, list) or not isinstance(incoming_items, list): |
| | | continue |
| | | current_by_id = { |
| | | item.get("id"): item |
| | | for item in current_items |
| | | if isinstance(item, dict) and item.get("id") |
| | | } |
| | | merged_items = [] |
| | | seen_ids = set() |
| | | for incoming in incoming_items: |
| | | if not isinstance(incoming, dict) or not incoming.get("id"): |
| | | continue |
| | | item_id = incoming["id"] |
| | | current = current_by_id.get(item_id, {}) |
| | | merged = {**current, **incoming} |
| | | if current.get("selected") and not incoming.get("selected"): |
| | | merged["selected"] = current.get("selected") |
| | | merged["versions"] = self._merge_asset_versions( |
| | | current.get("versions"), |
| | | incoming.get("versions"), |
| | | ) |
| | | if current.get("selected") and incoming.get("status") in {"failed", "pending"}: |
| | | merged["status"] = current.get("status", "done") |
| | | merged_items.append(merged) |
| | | seen_ids.add(item_id) |
| | | for current in current_items: |
| | | if isinstance(current, dict) and current.get("id") not in seen_ids: |
| | | merged_items.append(current) |
| | | body[list_key] = merged_items |
| | | |
| | | if stage == "storyboard" and any(k in body for k in ("episodes", "segments", "shots")): |
| | | for shot in body.get('shots', []): |
| | | if isinstance(shot, dict) and 'is_new' in shot: |
| | | shot['is_new'] = False |
| | | |
| | | input_segments = list(body.get('segments', [])) |
| | | for ep in body.get('episodes', []): |
| | | if isinstance(ep, dict): |
| | | input_segments.extend(seg for seg in ep.get('segments', []) if isinstance(seg, dict)) |
| | | |
| | | seg_info_list = [] |
| | | for seg in input_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, |
| | | "visual_prompt": seg.get("visual_prompt", ""), |
| | | }) |
| | | |
| | | video_art = state.artifacts.get('video_generation', {}) |
| | | if isinstance(video_art, dict) and isinstance(video_art.get('clips'), list): |
| | | for clip in video_art['clips']: |
| | | target = next((item for item in seg_info_list if item["segment_id"] == clip.get('id')), None) |
| | | if target: |
| | | clip['duration'] = target['duration'] |
| | | clip['description'] = target['desc'] |
| | | |
| | | ref_art = state.artifacts.get('reference_generation', {}) |
| | | if isinstance(ref_art, dict) and isinstance(ref_art.get('scenes'), list): |
| | | for scene in ref_art['scenes']: |
| | | target = next((item for item in seg_info_list if item["segment_id"] == scene.get('id')), None) |
| | | if target and target.get("visual_prompt"): |
| | | scene['description'] = target['visual_prompt'] |
| | | |
| | | if "segments" in body and "episodes" not in body: |
| | | body = {k: v for k, v in body.items() if k != "segments"} |
| | | body.pop('new_shot_ids', None) |
| | | |
| | | elif stage == "reference_generation": |
| | | if "segments" in body: |
| | | seg_id_to_prompt = { |
| | | s['segment_id']: s.get('visual_prompt', '') |
| | | for s in body['segments'] |
| | | if isinstance(s, dict) and 'segment_id' in s |
| | | } |
| | | |
| | | storyboard_art = state.artifacts.get('storyboard', {}) |
| | | if isinstance(storyboard_art, dict): |
| | | for ep in storyboard_art.get('episodes', []): |
| | | if not isinstance(ep, dict): |
| | | continue |
| | | for seg in ep.get('segments', []): |
| | | if isinstance(seg, dict) and seg.get('segment_id') in seg_id_to_prompt: |
| | | seg['visual_prompt'] = seg_id_to_prompt[seg.get('segment_id')] |
| | | |
| | | ref_art = state.artifacts.get('reference_generation', {}) |
| | | if isinstance(ref_art, dict): |
| | | for scene in ref_art.get('scenes', []): |
| | | if isinstance(scene, dict) and scene.get('id') in seg_id_to_prompt: |
| | | scene['description'] = seg_id_to_prompt[scene.get('id')] |
| | | |
| | | body = {k: v for k, v in body.items() if k != "segments"} |
| | | |
| | | ref_art = state.artifacts.get('reference_generation', {}) |
| | | if isinstance(ref_art, dict): |
| | | scenes = ref_art.get('scenes', []) |
| | | is_selection_format = any(isinstance(k, str) and not isinstance(v, (list, dict)) for k, v in body.items()) |
| | | if is_selection_format and scenes: |
| | | for scene in scenes: |
| | | if isinstance(scene, dict) and scene.get('id') in body: |
| | | scene['selected'] = body[scene.get('id')] |
| | | body = {} |
| | | |
| | | elif stage == "video_generation": |
| | | clip_id_to_duration = {} |
| | | clip_id_to_description = {} |
| | | for clip_id, value in body.items(): |
| | | if isinstance(value, dict): |
| | | if 'duration' in value: |
| | | clip_id_to_duration[clip_id] = value['duration'] |
| | | if 'description' in value: |
| | | clip_id_to_description[clip_id] = value['description'] |
| | | |
| | | if clip_id_to_duration or clip_id_to_description: |
| | | storyboard_art = state.artifacts.get('storyboard', {}) |
| | | if isinstance(storyboard_art, dict): |
| | | for ep in storyboard_art.get('episodes', []): |
| | | if not isinstance(ep, dict): |
| | | continue |
| | | for seg in ep.get('segments', []): |
| | | if isinstance(seg, dict) and seg.get('segment_id') in clip_id_to_duration: |
| | | seg['total_duration'] = clip_id_to_duration[seg.get('segment_id')] |
| | | |
| | | vid_art = state.artifacts.get('video_generation', {}) |
| | | if isinstance(vid_art, dict): |
| | | for clip in vid_art.get('clips', []): |
| | | if not isinstance(clip, dict): |
| | | continue |
| | | clip_id = clip.get('id') |
| | | if clip_id in clip_id_to_duration: |
| | | clip['duration'] = clip_id_to_duration[clip_id] |
| | | if clip_id in clip_id_to_description: |
| | | clip['description'] = clip_id_to_description[clip_id] |
| | | |
| | | vid_art = state.artifacts.get('video_generation', {}) |
| | | if isinstance(vid_art, dict): |
| | | clips = vid_art.get('clips', []) |
| | | is_selection_format = any(isinstance(k, str) and not isinstance(v, (list, dict)) for k, v in body.items()) |
| | | if is_selection_format and clips: |
| | | for clip in clips: |
| | | if isinstance(clip, dict) and clip.get('id') in body: |
| | | clip['selected'] = body[clip.get('id')] |
| | | body = {} |
| | | |
| | | current = state.artifacts.get(stage) |
| | | if current is None: |
| | | state.artifacts[stage] = body |
| | | elif isinstance(current, dict): |
| | | current.update(body) |
| | | else: |
| | | state.artifacts[stage] = body |
| | | |
| | | def upload_artifact_image( |
| | | self, |
| | | session_id: str, |
| | | stage: str, |
| | | item_type: str, |
| | | item_id: str, |
| | | file_obj: Any, |
| | | filename: str = "", |
| | | ) -> Dict[str, Any]: |
| | | """Save a user-provided image and attach it to the target artifact item.""" |
| | | allowed_exts = {".jpg", ".jpeg", ".png", ".webp", ".bmp"} |
| | | ext = os.path.splitext(filename or "")[1].lower() or ".png" |
| | | if ext not in allowed_exts: |
| | | raise ValueError(f"仅支持 {', '.join(sorted(allowed_exts))} 格式的图片") |
| | | |
| | | with self._state_lock: |
| | | state = self.get_state(session_id) |
| | | if not state: |
| | | raise KeyError(f"Session not found: {session_id}") |
| | | |
| | | cfg = self._upload_item_config(stage, item_type, item_id) |
| | | absolute_path, relative_path = self._next_upload_path(session_id, cfg, ext) |
| | | try: |
| | | with open(absolute_path, "wb") as buffer: |
| | | shutil.copyfileobj(file_obj, buffer) |
| | | except Exception as exc: |
| | | raise RuntimeError(f"图片保存失败: {exc}") from exc |
| | | |
| | | artifact = state.artifacts.setdefault(stage, {}) |
| | | items = artifact.setdefault(cfg["list_key"], []) |
| | | if not isinstance(items, list): |
| | | items = [] |
| | | artifact[cfg["list_key"]] = items |
| | | |
| | | target = next((item for item in items if isinstance(item, dict) and item.get("id") == item_id), None) |
| | | if target is None: |
| | | target = {"id": item_id, "name": item_id, "description": "", "versions": []} |
| | | items.append(target) |
| | | |
| | | versions = target.get("versions") |
| | | if not isinstance(versions, list): |
| | | versions = [] |
| | | if relative_path not in versions: |
| | | versions.append(relative_path) |
| | | target["versions"] = versions |
| | | target["selected"] = relative_path |
| | | target["status"] = "done" |
| | | |
| | | self._recalculate_all_statuses(state) |
| | | self.save_session_to_disk(session_id) |
| | | return { |
| | | "status": "ok", |
| | | "path": relative_path, |
| | | "item_id": item_id, |
| | | "item_type": item_type, |
| | | "artifact": copy.deepcopy(state.artifacts.get(stage)), |
| | | "status_map": copy.deepcopy(state.status), |
| | | } |
| | | |
| | | @staticmethod |
| | | def _upload_item_config(stage: str, item_type: str, item_id: str) -> Dict[str, str]: |
| | | if stage == "character_design" and item_type == "characters": |
| | | base = item_id if item_id.startswith("char_") else f"char_{item_id}" |
| | | return {"list_key": "characters", "dir": os.path.join("Assets", "characters"), "base": base} |
| | | if stage == "character_design" and item_type == "settings": |
| | | base = item_id if item_id.startswith("set_") else f"set_{item_id}" |
| | | return {"list_key": "settings", "dir": os.path.join("Assets", "settings"), "base": base} |
| | | if stage == "reference_generation" and item_type == "scenes": |
| | | return {"list_key": "scenes", "dir": "Scenes", "base": item_id} |
| | | raise ValueError("Unsupported upload target") |
| | | |
| | | @staticmethod |
| | | def _next_upload_path(session_id: str, cfg: Dict[str, str], ext: str) -> tuple[str, str]: |
| | | from config import settings |
| | | |
| | | save_dir = os.path.join(settings.RESULT_DIR, "image", str(session_id), cfg["dir"]) |
| | | os.makedirs(save_dir, exist_ok=True) |
| | | |
| | | pattern = re.compile(rf"^{re.escape(cfg['base'])}_upload_v(\d+)\.", re.IGNORECASE) |
| | | max_version = 0 |
| | | for name in os.listdir(save_dir): |
| | | match = pattern.match(name) |
| | | if match: |
| | | max_version = max(max_version, int(match.group(1))) |
| | | version = f"v{max_version + 1}" |
| | | upload_filename = f"{cfg['base']}_upload_{version}{ext}" |
| | | absolute_path = os.path.join(save_dir, upload_filename) |
| | | relative_path = os.path.relpath(absolute_path, settings.BASE_DIR) |
| | | return absolute_path, relative_path |
| | | |
| | | # ──────────── 会话持久化 ──────────── |
| | | |
| | | def save_session_to_disk(self, session_id: str, meta: Dict = None): |
| | |
| | | if "created_at" not in data: |
| | | data["created_at"] = time.time() |
| | | |
| | | # 会话级生成参数统一保存在 meta 中;清理旧版本遗留的根字段。 |
| | | # Legacy session compatibility: clean root-level generation fields left by old session JSON. |
| | | for key in SESSION_META_KEYS: |
| | | data.pop(key, None) |
| | | |
| | |
| | | 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: |