| | |
| | | |
| | | # 控制台处理器(主线程输出) |
| | | console_handler = logging.StreamHandler() |
| | | console_handler.setLevel(logging.INFO) # 只显示 INFO 及以上,避免 HTTP DEBUG 日志刷屏 |
| | | console_handler.setFormatter(logging.Formatter( |
| | | '[%(asctime)s] [%(threadName)-12s] %(levelname)-8s %(message)s', |
| | | datefmt='%H:%M:%S' |
| | |
| | | |
| | | # 启动并发日志监听器 |
| | | _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() |
| | |
| | | |
| | | class ProjectStartRequest(BaseModel): |
| | | idea: str |
| | | file_path: Optional[str] = None # 用户上传的文件路径 |
| | | style: Optional[str] = "anime" |
| | | video_ratio: Optional[str] = "16:9" |
| | | expand_idea: Optional[bool] = True # 默认启用创意扩写 |
| | |
| | | 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 ============================== |
| | |
| | | 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}") |
| | | 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", |
| | | "idea": final_idea, |
| | | "user_textbox_input": req.idea, # 保留原始的用户输入,用于前端展示 |
| | | "style": req.style or "realistic", |
| | | "video_ratio": req.video_ratio or "16:9", |
| | | "expand_idea": req.expand_idea if req.expand_idea is not None else True, |
| | | "llm_model": req.llm_model or settings.LLM_MODEL, |
| | |
| | | "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) |
| | |
| | | "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, |
| | | } |
| | | } |
| | | |
| | |
| | | # 注入会话级元数据(模型配置等),确保模型参数始终可用 |
| | | 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) |
| | |
| | | |
| | | @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") |
| | | # 从 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 的 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_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_prompts: |
| | | clip['description'] = shot_prompts[shot_id] |
| | | if shot_id in shot_durations: |
| | | clip['duration'] = shot_durations[shot_id] |
| | | # 移除 shots,避免合并到 reference_generation artifact |
| | | body = {k: v for k, v in body.items() if k != "shots"} |
| | | 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'] |
| | | |
| | | # 第四阶段选择图片版本:需要更新 scenes 数组中的 selected |
| | | if stage == "reference_generation" and body: |
| | | # 移除 segments,避免覆盖 storyboard artifact |
| | | body = {k: v for k, v in body.items() if k != "segments"} |
| | | |
| | | # 清除 new_shot_ids 标记 |
| | | if "new_shot_ids" in body: |
| | | del body['new_shot_ids'] |
| | | |
| | | # ══════════════════════════════════════════════════════════════ |
| | | # 第四阶段:参考图提示词修改 |
| | | # 修改 scenes[].description(视觉提示词) |
| | | # 同步到:storyboard.shots[].visual_prompt |
| | | # ══════════════════════════════════════════════════════════════ |
| | | elif stage == "reference_generation": |
| | | if "segments" in body: |
| | | # 修改视觉提示词 → 同步到 storyboard |
| | | # 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 结构: {episodes: [{segments: [...]}]} |
| | | if isinstance(storyboard_art, dict): |
| | | 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', {}) |
| | | 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 seg_id_to_prompt: |
| | | scene['description'] = seg_id_to_prompt[scene_id] |
| | | |
| | | # 移除 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', {}) |
| | | 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 变更为了 episodes -> segments |
| | | if isinstance(storyboard_art, dict): |
| | | 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', {}) |
| | | 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 |
| | |
| | | |
| | | |
| | | @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") |
| | |
| | | |
| | | |
| | | @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): |
| | |
| | | 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', []) |
| | | |
| | | # 筛选该场景的分镜 |
| | |
| | | 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: |
| | |
| | | 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: |
| | |
| | | model: str |
| | | prompt: str |
| | | image: str # 参考图片URL或base64 |
| | | ratio: Optional[str] = "16:9" |
| | | |
| | | |
| | | class SandboxVideoRequest(BaseModel): |
| | |
| | | import traceback |
| | | client = ImageClient() |
| | | try: |
| | | print(f"[T2I] Generating image with model: {req.model}, prompt: {req.prompt[:50]}...") |
| | | result = client.generate_image(req.prompt, model=req.model, image_paths=None) |
| | | print(f"[T2I] Generating image with model: {req.model}, prompt: {req.prompt[:50]}..., ratio: {req.ratio}") |
| | | result = client.generate_image(req.prompt, model=req.model, image_paths=None, video_ratio=req.ratio) |
| | | print(f"[T2I] Result: {result}") |
| | | # result 是图片路径列表 |
| | | # 保存到历史记录 |
| | |
| | | from tool.image_client import ImageClient |
| | | client = ImageClient() |
| | | try: |
| | | result = client.generate_image(req.prompt, image_paths=[req.image], model=req.model) |
| | | result = client.generate_image(req.prompt, image_paths=[req.image], model=req.model, video_ratio=req.ratio) |
| | | # 保存到历史记录 |
| | | record_id = _add_record( |
| | | tool="i2i", |