From 6cbbc5caf6afe4d8ff65ab6ecf6e911ee71a222f Mon Sep 17 00:00:00 2001
From: hit-cxf <2024111082@stu.hit.edu.cn>
Date: Mon, 06 Apr 2026 17:37:49 +0800
Subject: [PATCH] 添加了设置剧集数量的功能

---
 aigc-director/aigc-claw/backend/api_server.py |  108 +++++++++++++++++++++++++++++------------------------
 1 files changed, 59 insertions(+), 49 deletions(-)

diff --git a/aigc-director/aigc-claw/backend/api_server.py b/aigc-director/aigc-claw/backend/api_server.py
index 85762cc..dc72485 100644
--- a/aigc-director/aigc-claw/backend/api_server.py
+++ b/aigc-director/aigc-claw/backend/api_server.py
@@ -94,10 +94,11 @@
     video_model: Optional[str] = None
     enable_concurrency: Optional[bool] = True
     web_search: Optional[bool] = False
+    episodes: Optional[int] = 4
 
 class InterventionRequest(BaseModel):
     stage: str
-    modifications: Dict[str, Any] = {}
+    modifications: Dict[str, Any]
 
 
 # ============================== API ==============================
@@ -128,6 +129,7 @@
         "video_model": req.video_model or settings.VIDEO_MODEL,
         "enable_concurrency": req.enable_concurrency if req.enable_concurrency is not None else True,
         "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,
     }
     state.meta = meta
     workflow_engine.save_session_to_disk(session_id, meta)
@@ -140,6 +142,7 @@
             "style": req.style,
             "llm_model": req.llm_model,
             "vlm_model": req.vlm_model,
+            "episodes": req.episodes,
         }
     }
 
@@ -441,21 +444,23 @@
     # 同步到:storyboard.shots[].visual_prompt
     # ══════════════════════════════════════════════════════════════
     elif stage == "reference_generation":
-        if "shots" in body:
+        if "segments" in body:
             # 修改视觉提示词 → 同步到 storyboard
-            # body.shots 是 [{shot_id: "...", visual_prompt: "..."}]
-            shot_id_to_prompt = {s['shot_id']: s.get('visual_prompt', '')
-                                 for s in body['shots'] if 'shot_id' in s}
+            # body.segments 是 [{segment_id: "...", visual_prompt: "..."}]
+            seg_id_to_prompt = {s['segment_id']: s.get('visual_prompt', '')
+                                for s in body['segments'] if 'segment_id' in s}
 
             storyboard_art = state.artifacts.get('storyboard', {})
-            # storyboard 结构: {shots: [...]} (无 payload 包装)
+            # storyboard 结构: {episodes: [{segments: [...]}]}
             if isinstance(storyboard_art, dict):
-                shots = storyboard_art.get('shots', [])
-                for shot in shots:
-                    if isinstance(shot, dict):
-                        shot_id = shot.get('shot_id')
-                        if shot_id in shot_id_to_prompt:
-                            shot['visual_prompt'] = shot_id_to_prompt[shot_id]
+                episodes = storyboard_art.get('episodes', [])
+                for ep in episodes:
+                    if isinstance(ep, dict):
+                        for seg in ep.get('segments', []):
+                            if isinstance(seg, dict):
+                                seg_id = seg.get('segment_id')
+                                if seg_id in seg_id_to_prompt:
+                                    seg['visual_prompt'] = seg_id_to_prompt[seg_id]
 
             # 同步到 reference_generation.scenes 的 description
             ref_art = state.artifacts.get('reference_generation', {})
@@ -464,11 +469,11 @@
                 for scene in scenes:
                     if isinstance(scene, dict):
                         scene_id = scene.get('id')
-                        if scene_id in shot_id_to_prompt:
-                            scene['description'] = shot_id_to_prompt[scene_id]
+                        if scene_id in seg_id_to_prompt:
+                            scene['description'] = seg_id_to_prompt[scene_id]
 
-            # 移除 shots,避免覆盖 reference_generation artifact
-            body = {k: v for k, v in body.items() if k != "shots"}
+            # 移除 segments,避免覆盖 reference_generation artifact
+            body = {k: v for k, v in body.items() if k != "segments"}
 
         # 处理图片版本选择 {sceneId: path}
         ref_art = state.artifacts.get('reference_generation', {})
@@ -505,16 +510,16 @@
         # 同步到 storyboard 和 video_generation.clips
         if clip_id_to_duration or clip_id_to_description:
             storyboard_art = state.artifacts.get('storyboard', {})
-            # storyboard 结构: {shots: [...]} (无 payload 包装)
+            # storyboard 结构: 从 shots 变更为了 episodes -> segments
             if isinstance(storyboard_art, dict):
-                shots = storyboard_art.get('shots', [])
-                for shot in shots:
-                    if isinstance(shot, dict):
-                        shot_id = shot.get('shot_id')
-                        if shot_id in clip_id_to_duration:
-                            shot['duration'] = clip_id_to_duration[shot_id]
-                        if shot_id in clip_id_to_description:
-                            shot['plot'] = clip_id_to_description[shot_id]
+                episodes = storyboard_art.get('episodes', [])
+                for ep in episodes:
+                    if isinstance(ep, dict):
+                        for seg in ep.get('segments', []):
+                            if isinstance(seg, dict):
+                                seg_id = seg.get('segment_id')
+                                if seg_id in clip_id_to_duration:
+                                    seg['total_duration'] = clip_id_to_duration[seg_id]
 
             # 更新 video_generation.clips 的 duration 和 description
             vid_art = state.artifacts.get('video_generation', {})
@@ -710,15 +715,8 @@
 
 
 @app.delete("/api/sessions/{session_id}")
-async def delete_session(session_id: str, request: Request):
-    """删除历史记录(需要管理员密码)"""
-    try:
-        body = await request.json()
-    except Exception:
-        body = {}
-    password = body.get("password", "")
-    if not settings.ADMIN_PASSWORD or password != settings.ADMIN_PASSWORD:
-        raise HTTPException(403, "密码错误")
+async def delete_session(session_id: str):
+    """直接删除历史记录(无密码控制)"""
     deleted = workflow_engine.delete_session(session_id)
     if not deleted:
         raise HTTPException(404, "Session not found")
@@ -726,16 +724,8 @@
 
 
 @app.delete("/api/sessions")
-async def cleanup_orphan_files(request: Request):
-    """清理孤立的结果文件(需要管理员密码)"""
-    try:
-        body = await request.json()
-    except Exception:
-        body = {}
-    password = body.get("password", "")
-    if not settings.ADMIN_PASSWORD or password != settings.ADMIN_PASSWORD:
-        raise HTTPException(403, "密码错误")
-
+async def cleanup_orphan_files():
+    """清理孤立的结果文件(无密码控制)"""
     # 获取所有 session ID
     session_ids = set()
     for f in os.listdir(workflow_engine._session_dir):
@@ -787,7 +777,21 @@
     with open(result_file, 'r', encoding='utf-8') as f:
         results = json.load(f)
 
-    storyboard = results.get(session_id, {}).get('storyboard', {})
+    # 如果 results 是列表(旧版或某些 agent 的存储方式),则不能使用 .get(session_id)
+    # 根据 script_agent.py 的实现,final_json 是一个包含 session_id 的字典
+    if isinstance(results, dict):
+        # 兼容两种结构:{session_id: {...}} 或 {...}
+        script_data = results.get(session_id, results) if results.get(session_id) else results
+    else:
+        # 如果是列表,尝试按 session_id 过滤
+        script_data = next((item for item in results if isinstance(item, dict) and item.get("session_id") == session_id), {})
+
+    # 尝试从 script_data 或 state.artifacts 中获取 storyboard
+    storyboard = script_data.get('storyboard', {})
+    if not storyboard:
+        # 兼容旧版本可能直接存储在 results 下的情况
+        storyboard = results.get('storyboard', {}) if isinstance(results, dict) else {}
+    
     shots = storyboard.get('shots', [])
 
     # 筛选该场景的分镜
@@ -795,8 +799,11 @@
     shot_ids = [s.get('shot_id') for s in scene_shots if s.get('shot_id')]
 
     # 检查参考图
-    ref_artifact = results.get(session_id, {}).get('reference_generation', {})
-    ref_scenes = ref_artifact.get('scenes', [])
+    ref_artifact = script_data.get('reference_generation', {})
+    if not ref_artifact:
+        ref_artifact = state.artifacts.get('reference_generation', {})
+    
+    ref_scenes = ref_artifact.get('scenes', []) if isinstance(ref_artifact, dict) else []
     ref_image_count = 0
     for sc in ref_scenes:
         if sc.get('id') in shot_ids:
@@ -809,8 +816,11 @@
                     ref_image_count += 1
 
     # 检查视频
-    video_artifact = results.get(session_id, {}).get('video_generation', {})
-    video_clips = video_artifact.get('clips', [])
+    video_artifact = script_data.get('video_generation', {})
+    if not video_artifact:
+        video_artifact = state.artifacts.get('video_generation', {})
+    
+    video_clips = video_artifact.get('clips', []) if isinstance(video_artifact, dict) else []
     video_count = 0
     for vc in video_clips:
         if vc.get('id') in shot_ids:

--
Gitblit v1.8.0