From 890ce33d291f9e7ed8d8dee7b11596ed1bd7a0be Mon Sep 17 00:00:00 2001
From: Xinfan Chen <2024111082@stu.hit.edu.cn>
Date: Thu, 23 Apr 2026 14:39:32 +0800
Subject: [PATCH] 简化gpt-image调用

---
 aigc-director/aigc-claw/backend/api_server.py |  263 +++++++++++++++++++++++++++++++++++++---------------
 1 files changed, 185 insertions(+), 78 deletions(-)

diff --git a/aigc-director/aigc-claw/backend/api_server.py b/aigc-director/aigc-claw/backend/api_server.py
index 85762cc..3c5d45e 100644
--- a/aigc-director/aigc-claw/backend/api_server.py
+++ b/aigc-director/aigc-claw/backend/api_server.py
@@ -53,17 +53,19 @@
 _log_listener = setup_concurrent_logging()
 logger = logging.getLogger("api_server")
 # =================================
-from fastapi import FastAPI, Request, HTTPException
+from fastapi import FastAPI, Request, HTTPException, UploadFile, File
 from fastapi.responses import StreamingResponse
 from fastapi.staticfiles import StaticFiles
 from fastapi.middleware.cors import CORSMiddleware
 from pydantic import BaseModel
 from typing import Any, Optional, Dict, List
+import shutil
 
 sys.path.append(os.path.dirname(os.path.abspath(__file__)))
 
 from config import settings
 from core.orchestrator import WorkflowEngine, WorkflowStage
+from tool.file_reader import FileReader
 
 app = FastAPI(title="AI导演工作室", version="2.0.0")
 workflow_engine = WorkflowEngine()
@@ -84,8 +86,9 @@
 
 class ProjectStartRequest(BaseModel):
     idea: str
-    style: Optional[str] = "anime"
-    video_ratio: Optional[str] = "16:9"
+    file_path: Optional[str] = None  # 用户上传的文件路径
+    style: Optional[str] = "realistic"
+    video_ratio: Optional[str] = "9:16"
     expand_idea: Optional[bool] = True  # 默认启用创意扩写
     llm_model: Optional[str] = None
     vlm_model: Optional[str] = None
@@ -94,10 +97,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 ==============================
@@ -108,18 +112,70 @@
     return {"status": "ok", "timestamp": time.time()}
 
 
+@app.post("/api/upload_file")
+async def upload_file(file: UploadFile = File(...)):
+    """
+    接收用户上传的文件 (.docx, .doc, .txt, .md, .pdf),将其保存到 temp 目录。
+    返回保存的相对路径给前端。
+    """
+    allowed_exts = [".docx", ".doc", ".txt", ".md", ".pdf"]
+    filename = file.filename
+    ext = os.path.splitext(filename)[1].lower()
+    if ext not in allowed_exts:
+        raise HTTPException(status_code=400, detail=f"仅支持 {', '.join(allowed_exts)} 格式的文件")
+
+    # 1. 确保临时目录存在
+    os.makedirs(settings.TEMP_DIR, exist_ok=True)
+    
+    # 2. 生成唯一文件名并保存
+    safe_filename = f"{int(time.time())}_{filename}"
+    file_path = os.path.join(settings.TEMP_DIR, safe_filename)
+    try:
+        with open(file_path, "wb") as buffer:
+            shutil.copyfileobj(file.file, buffer)
+    except Exception as e:
+        logger.error(f"保存上传文件失败: {e}")
+        raise HTTPException(status_code=500, detail=f"文件保存失败: {str(e)}")
+
+    return {
+        "filename": filename,
+        "file_path": safe_filename  # 只返回文件名部分,相对于 TEMP_DIR
+    }
+
+
 @app.post("/api/project/start")
 async def start_project(req: ProjectStartRequest):
+    # 处理上传的文件
+    final_idea = req.idea
+    if req.file_path:
+        # file_path 是储存在 settings.TEMP_DIR 下的文件名
+        full_path = os.path.join(settings.TEMP_DIR, req.file_path)
+        if os.path.exists(full_path):
+            content = FileReader.extract_text(full_path)
+            if content:
+                # 提取原始文件名 (去掉时间戳前缀)
+                original_filename = "_".join(req.file_path.split("_")[1:])
+                prompt_fragment = FileReader.format_as_prompt(original_filename, content)
+                # 静默拼接到 idea 中
+                final_idea = f"{final_idea}\n\n{prompt_fragment}"
+            logger.info(f"成功处理上传文件: {full_path}")
+            logger.debug(f"文件内容预览:\n{content[:500]}")  # 调试输出,查看提取的文本内容
+        else:
+            logger.warning(f"上传的文件未找到: {full_path}")
+
     session_id = str(int(time.time() * 1000))
     state = workflow_engine.get_or_create_state(session_id)
     state.started_at = __import__('datetime').datetime.now()
-    state.status = "stage_completed"
+    if not isinstance(state.status, dict):
+        state.status = {}
+    state.status[state.current_stage.value] = "completed"
 
     # 保存会话元数据(未传参数时使用 config.py 中的默认值)
     meta = {
-        "idea": req.idea,
-        "style": req.style or "anime",
-        "video_ratio": req.video_ratio or "16:9",
+        "idea": final_idea,
+        "user_textbox_input": req.idea, # 保留原始的用户输入,用于前端展示
+        "style": req.style or "realistic",
+        "video_ratio": req.video_ratio or "9:16",
         "expand_idea": req.expand_idea if req.expand_idea is not None else True,
         "llm_model": req.llm_model or settings.LLM_MODEL,
         "vlm_model": req.vlm_model or settings.VLM_MODEL,
@@ -128,6 +184,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)
@@ -136,10 +193,13 @@
         "session_id": session_id,
         "status": state.status,
         "params": {
-            "idea": req.idea,
+            "idea": final_idea,
+            "file_path": req.file_path,
             "style": req.style,
             "llm_model": req.llm_model,
             "vlm_model": req.vlm_model,
+            "episodes": req.episodes,
+            "video_ratio": req.video_ratio,
         }
     }
 
@@ -198,8 +258,10 @@
     # 注入会话级元数据(模型配置等),确保模型参数始终可用
     if state.meta:
         for k, v in state.meta.items():
-            if v is not None and k not in body:  # 区分 None 和 False
-                body[k] = v
+            # 即使 body[k] 存在但为空字符串(如 idea),也应该使用 meta 中的完整内容
+            if v is not None:
+                if k not in body or not body[k]:
+                    body[k] = v
 
     # 从已持久化的 artifacts 中注入用户选项(selected_images / selected_clips)
     _inject_user_selections(state, stage, body)
@@ -210,12 +272,19 @@
     cancellation_check = lambda: stop_event.is_set() or session_stop.is_set()
 
     progress_events = queue.Queue()
+    event_trigger = asyncio.Event()
 
     def progress_callback(phase, step, percent, data=None):
         event = {"phase": phase, "step": step, "percent": percent}
         if data:
             event["data"] = data
         progress_events.put(event)
+        # 触发事件,通知 stream 循环有新进度
+        try:
+            loop = asyncio.get_running_loop()
+            loop.call_soon_threadsafe(event_trigger.set)
+        except RuntimeError:
+            pass
 
     async def stream_execution():
         stage_enum = WorkflowStage(stage)
@@ -230,6 +299,17 @@
             )
 
             while not task.done():
+                # 使用 wait_for 同时观察:1. 是否有新进度 (event_trigger.set) 2. 任务是否结束 3. 是否超时需要心跳
+                # 我们不再强制 sleep,而是被动等待事件
+                try:
+                    await asyncio.wait_for(event_trigger.wait(), timeout=15.0)
+                except asyncio.TimeoutError:
+                    # 15秒没动静,发送心跳保活
+                    yield json.dumps({"type": "heartbeat", "time": time.time()}) + "\n"
+                
+                # 重置触发器,开始批量处理当前队列中的进度
+                event_trigger.clear()
+
                 while not progress_events.empty():
                     try:
                         p = progress_events.get_nowait()
@@ -243,7 +323,6 @@
                         if p.get("data"):
                             evt["data"] = p["data"]
                         yield json.dumps(evt) + "\n"
-                        await asyncio.sleep(0)  # 强制立即发送 SSE 事件
                     except queue.Empty:
                         break
 
@@ -251,9 +330,6 @@
                     stop_event.set()
                     yield json.dumps({"type": "error", "content": "Client disconnected"}) + "\n"
                     return
-
-                yield json.dumps({"type": "heartbeat", "time": time.time()}) + "\n"
-                await asyncio.sleep(0.1)  # 减少心跳间隔,加快事件处理
 
             # Drain any remaining progress events after task completion
             while not progress_events.empty():
@@ -415,24 +491,38 @@
             if 'is_new' in shot:
                 shot['is_new'] = False
 
-        # 同步到 video_generation
-        shot_id_to_duration = {s['shot_id']: s.get('duration', 10) for s in body['shots'] if 'shot_id' in s}
-        shot_id_to_plot = {s['shot_id']: s.get('plot', '') for s in body['shots'] if 'shot_id' in s}
+        # 从 body['segments'] 提取同步信息(修改后的逻辑按 segment 同步)
+        seg_info_list = []
+        for seg in body.get('segments', []):
+            seg_id = seg.get('segment_id')
+            if not seg_id: continue
+            
+            shots = seg.get('shots', [])
+            desc_video = " ".join([sh.get("plot") or sh.get("content") or "" for sh in shots]).strip()
+            total_dur = seg.get("total_duration") or sum([sh.get("duration", 0) for sh in shots]) or 10
+            
+            seg_info_list.append({
+                "segment_id": seg_id,
+                "desc": desc_video,
+                "duration": total_dur
+            })
 
+        # 同步到 video_generation
         video_art = state.artifacts.get('video_generation', {})
         if isinstance(video_art, dict) and 'clips' in video_art:
             for clip in video_art['clips']:
-                shot_id = clip.get('id')
-                if shot_id in shot_id_to_duration:
-                    clip['duration'] = shot_id_to_duration[shot_id]
-                if shot_id in shot_id_to_plot:
-                    clip['description'] = shot_id_to_plot[shot_id]
+                c_id = clip.get('id')
+                # 匹配 segment_id
+                target = next((item for item in seg_info_list if item["segment_id"] == c_id), None)
+                if target:
+                    clip['duration'] = target['duration']
+                    clip['description'] = target['desc']
 
-        # 移除 shots,避免覆盖 storyboard artifact
-        body = {k: v for k, v in body.items() if k != "shots"}
+        # 移除 segments,避免覆盖 storyboard artifact
+        body = {k: v for k, v in body.items() if k != "segments"}
 
         # 清除 new_shot_ids 标记
-        if "new_shot_ids" in body and body.get('new_shot_ids') == []:
+        if "new_shot_ids" in body:
             del body['new_shot_ids']
 
     # ══════════════════════════════════════════════════════════════
@@ -441,21 +531,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 +556,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 +597,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', {})
@@ -569,12 +661,19 @@
     cancellation_check = lambda: stop_event.is_set() or session_stop.is_set()
 
     progress_events = queue.Queue()
+    event_trigger = asyncio.Event()
 
     def progress_callback(phase, step, percent, data=None):
         event = {"phase": phase, "step": step, "percent": percent}
         if data:
             event["data"] = data
         progress_events.put(event)
+        # 触发事件回调
+        try:
+            loop = asyncio.get_running_loop()
+            loop.call_soon_threadsafe(event_trigger.set)
+        except RuntimeError:
+            pass
 
     async def stream_intervention():
         stage_enum = WorkflowStage(req.stage)
@@ -602,6 +701,13 @@
             )
 
             while not task.done():
+                try:
+                    await asyncio.wait_for(event_trigger.wait(), timeout=15.0)
+                except asyncio.TimeoutError:
+                    yield json.dumps({"type": "heartbeat", "time": time.time()}) + "\n"
+                
+                event_trigger.clear()
+
                 while not progress_events.empty():
                     try:
                         p = progress_events.get_nowait()
@@ -615,7 +721,6 @@
                         if p.get("data"):
                             evt["data"] = p["data"]
                         yield json.dumps(evt) + "\n"
-                        await asyncio.sleep(0)  # 强制立即发送 SSE 事件
                     except queue.Empty:
                         break
 
@@ -623,9 +728,6 @@
                     stop_event.set()
                     yield json.dumps({"type": "error", "content": "Client disconnected"}) + "\n"
                     return
-
-                yield json.dumps({"type": "heartbeat", "time": time.time()}) + "\n"
-                await asyncio.sleep(0.1)  # 减少心跳间隔,加快事件处理
 
             # Drain remaining
             while not progress_events.empty():
@@ -710,15 +812,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 +821,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 +874,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 +896,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 +913,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