From 9558cb63d47ecf231b55ecf8ce09481bcd63e3cd Mon Sep 17 00:00:00 2001
From: hit-cxf <2024111082@stu.hit.edu.cn>
Date: Thu, 09 Apr 2026 12:01:51 +0800
Subject: [PATCH] 添加了续写功能
---
aigc-director/aigc-claw/backend/api_server.py | 252 +++++++++++++++++++++++++++++++++++---------------
1 files changed, 177 insertions(+), 75 deletions(-)
diff --git a/aigc-director/aigc-claw/backend/api_server.py b/aigc-director/aigc-claw/backend/api_server.py
index e6d22f0..8fcd732 100644
--- a/aigc-director/aigc-claw/backend/api_server.py
+++ b/aigc-director/aigc-claw/backend/api_server.py
@@ -22,6 +22,7 @@
# 控制台处理器(主线程输出)
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'
@@ -50,6 +51,7 @@
# 启动并发日志监听器
_log_listener = setup_concurrent_logging()
+logger = logging.getLogger("api_server")
# =================================
from fastapi import FastAPI, Request, HTTPException
from fastapi.responses import StreamingResponse
@@ -92,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 ==============================
@@ -111,7 +114,9 @@
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 = "running"
+ if not isinstance(state.status, dict):
+ state.status = {}
+ state.status[state.current_stage.value] = "completed"
# 保存会话元数据(未传参数时使用 config.py 中的默认值)
meta = {
@@ -126,6 +131,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)
@@ -138,6 +144,7 @@
"style": req.style,
"llm_model": req.llm_model,
"vlm_model": req.vlm_model,
+ "episodes": req.episodes,
}
}
@@ -376,96 +383,185 @@
@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
@@ -635,15 +731,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")
@@ -651,16 +740,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):
@@ -712,7 +793,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', [])
# 筛选该场景的分镜
@@ -720,8 +815,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:
@@ -734,8 +832,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:
@@ -758,7 +859,7 @@
{"id": "script_generation", "name": "剧本生成", "order": 1, "description": "将灵感���化为结构化剧本"},
{"id": "character_design", "name": "角色/场景设计", "order": 2, "description": "生成角色设计图和场景背景"},
{"id": "storyboard", "name": "分镜设计", "order": 3, "description": "设计镜头语言和分镜脚本"},
- {"id": "reference_generation", "name": "参考图生成", "order": 4, "description": "生��高精度参考图"},
+ {"id": "reference_generation", "name": "参考图生成", "order": 4, "description": "生成高精度参考图"},
{"id": "video_generation", "name": "视频生成", "order": 5, "description": "将参考图/分镜图生成视频"},
{"id": "post_production", "name": "后期剪辑", "order": 6, "description": "拼接视频片段为最终成片"},
]
@@ -890,6 +991,7 @@
model: str
prompt: str
image: str # 参考图片URL或base64
+ ratio: Optional[str] = "16:9"
class SandboxVideoRequest(BaseModel):
@@ -995,8 +1097,8 @@
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 是图片路径列表
# 保存到历史记录
@@ -1020,7 +1122,7 @@
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",
--
Gitblit v1.8.0