From 0cce95fd610aec4b36d7830e74358e7686355e27 Mon Sep 17 00:00:00 2001
From: Xinfan Chen <2024111082@stu.hit.edu.cn>
Date: Mon, 30 Mar 2026 23:43:56 +0800
Subject: [PATCH] Fixed the issue where visual cues could not be modified during the reference image generation and video generation phases

---
 aigc-director/aigc-claw/backend/api_server.py                         |  160 ++++++++++++++-----
 aigc-director/aigc-claw/backend/docs/session_format.md                |  282 +++++++++++++++++++++++++++++++++++
 aigc-director/aigc-claw/frontend/components/stages/ReferenceStage.tsx |    9 +
 aigc-director/aigc-claw/frontend/components/stages/VideoStage.tsx     |    7 
 4 files changed, 409 insertions(+), 49 deletions(-)

diff --git a/aigc-director/aigc-claw/backend/api_server.py b/aigc-director/aigc-claw/backend/api_server.py
index 0531940..734f4ec 100644
--- a/aigc-director/aigc-claw/backend/api_server.py
+++ b/aigc-director/aigc-claw/backend/api_server.py
@@ -50,6 +50,7 @@
 
 # 启动并发日志监听器
 _log_listener = setup_concurrent_logging()
+logger = logging.getLogger("api_server")
 # =================================
 from fastapi import FastAPI, Request, HTTPException
 from fastapi.responses import StreamingResponse
@@ -376,96 +377,169 @@
 
 @app.patch("/api/project/{session_id}/artifact/{stage}")
 async def update_artifact(session_id: str, stage: str, request: Request):
-    """保存用户在某阶段的选择(如选定的图片/视频版本)
+    """保存用户在某阶段的选择/修改
 
     数据存储策略:
     - 用户修改只保存到 sessions json(state.artifacts)
     - result/script json 只作为 LLM 初始生成,不接受用户修改
+
+    按阶段分类处理:
+    - 第二阶段(character_design): 修改 characters[]/settings[] 的 description
+    - 第三阶段(storyboard): 修改 shots[] 的 duration/plot/visual_prompt
+    - 第四阶段(reference_generation): 修改 scenes[] 的 description(视觉提示词)
+    - 第五阶段(video_generation): 修改 clips[] 的 duration/description
     """
     state = workflow_engine.get_state(session_id)
     if not state:
         raise HTTPException(404, "Session not found")
     body = await request.json()
 
-    # 第三阶段分镜修改:同步更新 video_generation 的 clips duration
-    if stage == "storyboard" and "shots" in body:
-        shot_durations = {s['shot_id']: s.get('duration', 10) for s in body['shots'] if 'shot_id' in s}
-        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]
-                    logger.info(f"Synced duration {shot_durations[shot_id]}s to video_generation clip {shot_id}")
-        # 移除 shots,避免合并到 storyboard artifact
-        body = {k: v for k, v in body.items() if k != "shots"}
+    # ══════════════════════════════════════════════════════════════
+    # 第二阶段:角色/背景描述修改
+    # 修改 characters[].description 或 settings[].description
+    # 不涉及跨阶段同步
+    # ══════════════════════════════════════════════════════════════
+    if stage == "character_design":
+        # 直接更新 body,由后续逻辑合并到 artifact
+        pass
 
-    # 第三阶段确认新分镜:清除 is_new 标记
-    if stage == "storyboard" and "shots" in body:
-        updated_shots = body.get('shots', [])
-        # 清除所有 is_new 标记
-        for shot in updated_shots:
+    # ══════════════════════════════════════════════════════════════
+    # 第三阶段:分镜修改
+    # 修改 payload.shots[].duration / payload.shots[].plot / payload.shots[].visual_prompt
+    # 同步到:video_generation.clips[].duration, video_generation.clips[].description
+    # ══════════════════════════════════════════════════════════════
+    elif stage == "storyboard" and "shots" in body:
+        # 清除 is_new 标记(确认新分镜)
+        for shot in body['shots']:
             if 'is_new' in shot:
                 shot['is_new'] = False
-        logger.info(f"Confirmed new shots, cleared is_new flag for {len(updated_shots)} shots")
 
-    # 第三阶段清除 new_shot_ids 标记
-    if stage == "storyboard" and "new_shot_ids" in body and body.get('new_shot_ids') == []:
-        # 清除 new_shot_ids 标记
-        logger.info("Cleared new_shot_ids marker")
+        # 同步到 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}
 
-    # 第五阶段视频提示词修改:更新 video_generation 的 clips
-    if stage == "reference_generation" and "shots" in body:
-        shot_prompts = {s['shot_id']: s.get('video_prompt', s.get('visual_prompt', ''))
-                        for s in body['shots'] if 'shot_id' in s}
-        shot_durations = {s['shot_id']: s.get('duration', 10) for s in body['shots'] if 'shot_id' in s}
         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_prompts:
-                    clip['description'] = shot_prompts[shot_id]
-                if shot_id in shot_durations:
-                    clip['duration'] = shot_durations[shot_id]
-        # 移除 shots,避免合并到 reference_generation artifact
+                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]
+
+        # 移除 shots,避免覆盖 storyboard artifact
         body = {k: v for k, v in body.items() if k != "shots"}
 
-    # 第四阶段选择图片版本:需要更新 scenes 数组中的 selected
-    if stage == "reference_generation" and body:
+        # 清除 new_shot_ids 标记
+        if "new_shot_ids" in body and body.get('new_shot_ids') == []:
+            del body['new_shot_ids']
+
+    # ══════════════════════════════════════════════════════════════
+    # 第四阶段:参考图提示词修改
+    # 修改 scenes[].description(视觉提示词)
+    # 同步到:storyboard.shots[].visual_prompt
+    # ══════════════════════════════════════════════════════════════
+    elif stage == "reference_generation":
+        if "shots" 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}
+
+            storyboard_art = state.artifacts.get('storyboard', {})
+            # storyboard 结构: {shots: [...]} (无 payload 包装)
+            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]
+
+            # 同步到 reference_generation.scenes 的 description
+            ref_art = state.artifacts.get('reference_generation', {})
+            if isinstance(ref_art, dict):
+                scenes = ref_art.get('scenes', [])
+                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]
+
+            # 移除 shots,避免覆盖 reference_generation artifact
+            body = {k: v for k, v in body.items() if k != "shots"}
+
+        # 处理图片版本选择 {sceneId: path}
         ref_art = state.artifacts.get('reference_generation', {})
         if isinstance(ref_art, dict):
             scenes = ref_art.get('scenes', [])
-            # 检查 body 是否是 {sceneId: path} 格式
             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:
-                # body 是 {sceneId: path} 格式,需要更新 scenes 数组
                 for scene in scenes:
                     scene_id = scene.get('id')
                     if scene_id and scene_id in body:
                         scene['selected'] = body[scene_id]
-                # 清空 body,避免覆盖 scenes
                 body = {}
 
-    # 第五阶段选择视频版本:需要更新 clips 数组中的 selected
-    if stage == "video_generation" and body:
+    # ══════════════════════════════════════════════════════════════
+    # 第五阶段:视频片段修改
+    # 修改 clips[].duration / clips[].description
+    # 同步到:storyboard.shots[].duration / storyboard.shots[].plot
+    # ══════════════════════════════════════════════════════════════
+    elif stage == "video_generation":
+        # 收集 clips 的修改
+        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']
+
+        # 同步到 storyboard 和 video_generation.clips
+        if clip_id_to_duration or clip_id_to_description:
+            storyboard_art = state.artifacts.get('storyboard', {})
+            # storyboard 结构: {shots: [...]} (无 payload 包装)
+            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]
+
+            # 更新 video_generation.clips 的 duration 和 description
+            vid_art = state.artifacts.get('video_generation', {})
+            if isinstance(vid_art, dict):
+                clips = vid_art.get('clips', [])
+                for clip in clips:
+                    if isinstance(clip, dict):
+                        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]
+
+        # 处理视频版本选择 {clipId: path}
         vid_art = state.artifacts.get('video_generation', {})
         if isinstance(vid_art, dict):
             clips = vid_art.get('clips', [])
-            # 检查 body 是否是 {clipId: path} 格式
             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:
-                # body 是 {clipId: path} 格式,需要更新 clips 数组
                 for clip in clips:
                     clip_id = clip.get('id')
                     if clip_id and clip_id in body:
                         clip['selected'] = body[clip_id]
-                # 清空 body,避免覆盖 clips
                 body = {}
 
     # 更新 state.artifacts 并保存到 sessions json
diff --git a/aigc-director/aigc-claw/backend/docs/session_format.md b/aigc-director/aigc-claw/backend/docs/session_format.md
new file mode 100644
index 0000000..5a0bc40
--- /dev/null
+++ b/aigc-director/aigc-claw/backend/docs/session_format.md
@@ -0,0 +1,282 @@
+# Session 数据格式
+
+Session 数据存储在 `code/data/sessions/{session_id}.json`,包含完整的项目会话信息。
+
+## 根级字段
+
+| 字段 | 类型 | 说明 |
+|------|------|------|
+| `session_id` | string | 会话唯一 ID |
+| `idea` | string | 用户原始创意/故事想法 |
+| `style` | string | 视觉风格,如 `realistic`、`anime` |
+| `video_ratio` | string | 视频比例,如 `16:9`、`9:16` |
+| `expand_idea` | bool | 是否扩展创意 |
+| `llm_model` | string | LLM 模型名称 |
+| `vlm_model` | string | VLM 模型名称 |
+| `image_t2i_model` | string | 文生图模型 |
+| `image_it2i_model` | string | 图生图模型 |
+| `video_model` | string | 视频生成模型 |
+| `enable_concurrency` | string/bool | 是否启用并发 |
+| `web_search` | bool | 是否启用网络搜索 |
+| `created_at` | float | 创建时间戳 |
+| `updated_at` | float | 更新时间戳 |
+| `current_stage` | string | 当前阶段 |
+| `status` | string | 会话状态 |
+| `stages_completed` | string[] | 已完成的阶段列表 |
+| `error` | null / string | 错误信息 |
+| `artifacts` | object | 各阶段产物(见下文) |
+
+## Status 状态值
+
+| 状态 | 说明 |
+|------|------|
+| `idle` | 初始状态 |
+| `running` | 运行中 |
+| `waiting` | 等待用户确认 |
+| `stage_completed` | 阶段完成 |
+| `session_completed` | 会话完成 |
+
+## Stages Completed 阶段列表
+
+按顺序完成的所有阶段:
+```
+script_generation → character_design → storyboard → reference_generation → video_generation → post_production
+```
+
+---
+
+## Artifacts 各阶段产物
+
+### 1. script_generation
+
+```json
+{
+  "session_id": "...",
+  "title": "守",
+  "logline": "一句话概括故事",
+  "genre": ["奇幻", "温情"],
+  "target_duration": 180,
+  "synopsis": "详细故事梗概",
+  "characters": [
+    {
+      "name": "角色名",
+      "character_id": "char_xxx",
+      "description": "角色描述",
+      "personality": ["特质1", "特质2"],
+      "motivation": "角色动机",
+      "arc_description": "角色弧线描述",
+      "role": "主角/配角/反派",
+      "age": "年龄",
+      "species": "物种(人类/狗等)"
+    }
+  ],
+  "settings": [
+    {
+      "name": "场景名",
+      "setting_id": "set_xxx",
+      "description": "场景描述"
+    }
+  ],
+  "scenes": [
+    {
+      "scene_number": 1,
+      "location": "场景位置",
+      "characters": ["角色名"],
+      "plot": "场景剧情描述"
+    }
+  ],
+  "overall_style": "realistic",
+  "mood": "整体情绪基调",
+  "project_id": "proj_xxx",
+  "version": 1,
+  "metadata": {
+    "generation_model": "模型名",
+    "generation_prompt": "原始生成提示词",
+    "mode": "movie/micro"
+  },
+  "logline_data": {
+    "logline": "完整logline",
+    "who": "主角是谁",
+    "goal": "主角目标",
+    "conflict": "核心冲突",
+    "twist": "反转点",
+    "theme": "主题"
+  }
+}
+```
+
+### 2. character_design
+
+```json
+{
+  "session_id": "...",
+  "characters": [
+    {
+      "id": "char_xxx",
+      "name": "角色名",
+      "description": "角色外观描述",
+      "selected": "选中的角色图路径",
+      "versions": ["所有版本路径"]
+    }
+  ],
+  "settings": [
+    {
+      "id": "set_xxx",
+      "name": "场景名",
+      "description": "场景描述",
+      "selected": "选中的场景图路径",
+      "versions": ["所有版本路径"]
+    }
+  ]
+}
+```
+
+### 3. storyboard
+
+```json
+{
+  "session_id": "...",
+  "shots": [
+    {
+      "shot_number": 1,
+      "duration": 5,
+      "characters": ["角色名"],
+      "location": "场景位置",
+      "plot": "镜头剧情描述",
+      "visual_prompt": "视觉生成提示词",
+      "shot_id": "shot_001_01",
+      "scene_number": 1,
+      "act": 1
+    }
+  ],
+  "user_modified": true,
+  "new_shot_ids": []
+}
+```
+
+> **注意**:storyboard 结构是 `{shots: [...]}`,**没有** `payload` 包装层。
+
+### 4. reference_generation
+
+```json
+{
+  "session_id": "...",
+  "scenes": [
+    {
+      "id": "shot_001_01",
+      "name": "场景1-镜头1",
+      "index": 1,
+      "description": "视觉生成提示词(由 storyboard.visual_prompt 同步过来)",
+      "selected": "用户选中的参考图路径",
+      "versions": ["所有版本路径"],
+      "status": "done/pending/failed"
+    }
+  ],
+  "shots": [
+    {
+      "shot_id": "shot_001_01",
+      "video_prompt": "视频生成提示词"
+    }
+  ]
+}
+```
+
+> **注意**:
+> - `scenes[].id` = `storyboard.shots[].shot_id`,用于跨阶段关联
+> - `shots[]` 是给视频生成用的提示词,格式为 `{shot_id, video_prompt}`
+
+### 5. video_generation
+
+```json
+{
+  "session_id": "...",
+  "clips": [
+    {
+      "id": "shot_001_01",
+      "name": "场景1-镜头1",
+      "index": 1,
+      "description": "视频片段描述(由 storyboard.plot 同步)",
+      "duration": 5,
+      "selected": "用户选中的视频路径",
+      "versions": ["所有版本路径"],
+      "status": "done/pending/failed"
+    }
+  ]
+}
+```
+
+> **注意**:`clips[].id` = `storyboard.shots[].shot_id`
+
+### 6. post_production
+
+```json
+{
+  "session_id": "...",
+  "final_video": "code/result/video/xxx_final.mp4"
+}
+```
+
+---
+
+## 跨阶段数据同步关系
+
+```
+storyboard (修改 plot/visual_prompt/duration)
+    ↓
+video_generation.clips (description/duration)
+    ↑ (修改 description/duration)
+    ↑
+video_generation (修改 clips.description/clips.duration)
+    ↓ (修改后同步回 storyboard)
+storyboard (修改后同步回 storyboard.shots.plot)
+
+reference_generation (修改 scenes.description)
+    ↓
+storyboard.shots.visual_prompt (由 reference_generation 同步)
+    ↑ (修改后同步)
+    ↑
+reference_generation (修改 scenes.description)
+```
+
+---
+
+## PATCH /artifact/{stage} 请求格式
+
+### storyboard
+```json
+{
+  "shots": [
+    {"shot_id": "shot_001_01", "duration": 5, "plot": "新描述", "visual_prompt": "新提示词"}
+  ]
+}
+```
+
+### reference_generation(修改视觉提示词)
+```json
+{
+  "shots": [
+    {"shot_id": "shot_001_01", "visual_prompt": "新提示词"}
+  ]
+}
+```
+
+### reference_generation(选择图片版本)
+```json
+{
+  "shot_001_01": "code/result/image/xxx/shot_001_01_v2.jpg"
+}
+```
+
+### video_generation(修改片段描述/时长)
+```json
+{
+  "shot_001_01": {"description": "新描述", "duration": 5}
+}
+```
+
+### video_generation(选择视频版本)
+```json
+{
+  "shot_001_01": "code/result/video/xxx/shot_001_01_v2.mp4"
+}
+```
diff --git a/aigc-director/aigc-claw/frontend/components/stages/ReferenceStage.tsx b/aigc-director/aigc-claw/frontend/components/stages/ReferenceStage.tsx
index 05d8943..96a5887 100644
--- a/aigc-director/aigc-claw/frontend/components/stages/ReferenceStage.tsx
+++ b/aigc-director/aigc-claw/frontend/components/stages/ReferenceStage.tsx
@@ -343,7 +343,7 @@
     setSavingIds(prev => new Set(prev).add(sceneId));
     try {
       // 调用后端 API 保存提示词
-      const response = await fetch(`/api/project/${sessionId}/artifact/storyboard`, {
+      const response = await fetch(`/api/project/${sessionId}/artifact/reference_generation`, {
         method: 'PATCH',
         headers: { 'Content-Type': 'application/json' },
         body: JSON.stringify({
@@ -362,6 +362,13 @@
         });
         // 更新本地状态,使用保存后的值
         setEditDescs(prev => ({ ...prev, [sceneId]: newPrompt }));
+        // 同步更新 artifact 以便后续阶段能获取最新的提示词
+        if (onUpdateArtifact && state.artifact?.scenes) {
+          const updatedScenes = state.artifact.scenes.map((s: SceneItem) =>
+            s.id === sceneId ? { ...s, description: newPrompt } : s
+          );
+          onUpdateArtifact({ scenes: updatedScenes });
+        }
       }
     } catch (error) {
       console.error('保存提示词失败:', error);
diff --git a/aigc-director/aigc-claw/frontend/components/stages/VideoStage.tsx b/aigc-director/aigc-claw/frontend/components/stages/VideoStage.tsx
index 3995ded..3fc85f2 100644
--- a/aigc-director/aigc-claw/frontend/components/stages/VideoStage.tsx
+++ b/aigc-director/aigc-claw/frontend/components/stages/VideoStage.tsx
@@ -336,14 +336,11 @@
 
     setSavingIds(prev => new Set(prev).add(clipId));
     try {
-      const response = await fetch(`/api/project/${sessionId}/artifact/reference_generation`, {
+      const response = await fetch(`/api/project/${sessionId}/artifact/video_generation`, {
         method: 'PATCH',
         headers: { 'Content-Type': 'application/json' },
         body: JSON.stringify({
-          shots: clips.map(c => ({
-            shot_id: c.id,
-            video_prompt: c.id === clipId ? newPrompt : c.description
-          }))
+          [clipId]: { description: newPrompt }
         })
       });
       if (response.ok) {

--
Gitblit v1.8.0