Xinfan Chen
2026-04-28 95c0f1779a765f5430ba3f045d97b514b037ab7d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
# -*- coding: utf-8 -*-
"""
阶段5: 视频生成智能体 (适配 Session JSON 格式)
- 从 session.json 的 artifacts["storyboard"] 读取拍摄片段(Segments)
- 视频提示词:风格前缀 + 分镜列表(分镜1: [时长] content...)
- 参考图:从 session.json 的 artifacts["reference_generation"] 读取
- 支持逐项并发生成、实时预览、重新生成
"""
 
import os
import re
import glob
import json
import asyncio
import logging
from typing import Any, Optional, Dict, List
from concurrent.futures import ThreadPoolExecutor, as_completed
 
from .base_agent import AgentInterface
 
logger = logging.getLogger(__name__)
 
 
class VideoDirectorAgent(AgentInterface):
    """视频生成:拍摄片段(Segments) → 组装提示词 → 视频片段"""
 
    def __init__(self):
        super().__init__(name="VideoDirector")
 
    # ─── 版本管理 ───
 
    @staticmethod
    def _video_base(sid: str) -> str:
        return os.path.join('code/result/video', str(sid))
 
    def _list_versions(self, sid: str, segment_id: str) -> List[str]:
        """列出某个片段视频的所有历史版本"""
        video_dir = self._video_base(sid)
        pattern = os.path.join(video_dir, f"{segment_id}*.mp4")
        files = [f for f in sorted(glob.glob(pattern), key=os.path.getmtime)
                 if not f.endswith('_final.mp4')]
        return files
 
    def _next_version_path(self, sid: str, segment_id: str) -> str:
        """获取下一个版本路径"""
        video_dir = self._video_base(sid)
        os.makedirs(video_dir, exist_ok=True)
 
        existing = self._list_versions(sid, segment_id)
        if not existing:
            return os.path.join(video_dir, f"{segment_id}.mp4")
 
        max_v = 1
        for fp in existing:
            bn = os.path.splitext(os.path.basename(fp))[0]
            m = re.search(r'_v(\d+)$', bn)
            if m:
                max_v = max(max_v, int(m.group(1)))
 
        return os.path.join(video_dir, f"{segment_id}_v{max_v + 1}.mp4")
 
    # ─── 视频生成 ───
 
    def _generate_one(self, sid: str, segment_id: str, prompt: str,
                      img_path: str, video_model: str,
                      duration: int = 10, sound: str = "",
                      shot_type: str = "multi",
                      video_ratio: str = "16:9") -> tuple:
        """生成单个视频片段,返回 (segment_id, path_or_None)"""
        if self.cancellation_check and self.cancellation_check():
            logger.info(f"VideoDirectorAgent: {segment_id} 跳过(用户取消)")
            return segment_id, None
 
        if not os.path.exists(img_path):
            logger.warning(f"Image missing for {segment_id}: {img_path}")
            return segment_id, None
 
        save_path = self._next_version_path(sid, segment_id)
        try:
            from tool.video_client import VideoClient
            client = VideoClient()
            client.generate_video(
                prompt=prompt,
                image_path=img_path,
                save_path=save_path,
                model=video_model,
                duration=duration,
                sound=sound,
                shot_type=shot_type,
                video_ratio=video_ratio,
            )
            return segment_id, save_path
        except Exception as e:
            logger.error(f"Video gen failed for {segment_id}: {e}")
            if os.path.exists(save_path):
                try:
                    os.remove(save_path)
                except Exception:
                    pass
        return segment_id, None
 
    # ─── 提示词组装 ───
 
    def _assemble_prompt(self, segment: dict, style: str) -> str:
        """组装视频提示词
        格式:
        风格控制:用户选择的风格, 电影质感
        分镜列表:分镜1:[时长] content... 分镜2:[时长] content...
        """
        prompt = f"风格控制:{style}风格, 电影质感\n"
        prompt += "分镜列表:"
        
        shots = segment.get("shots", [])
        for i, shot in enumerate(shots, 1):
            dur = shot.get("duration", 5)
            content = shot.get("content", "").strip()
            prompt += f"\n分镜{i}:[{dur}秒] {content}"
            
        return prompt
 
    def _get_style_keywords(self, session_data: dict) -> str:
        """从会话数据获取风格关键词"""
        style = session_data.get('style', 'realistic').lower()
        
        STYLE_MAP = {
            "anime": "anime style, vibrant colors, clean lines,",
            "realistic": "photorealistic, cinematic lighting, high-detail textures,",
            "cartoon": "cartoon style, thick outlines, bold colors,",
            "3d-disney": "3D CGI animation, Disney/Pixar style, smooth textures,",
            "oil-painting": "oil painting, artistic brushstrokes, rich textures,",
            "chinese-ink": "Chinese ink wash painting, traditional style, soft strokes,"
        }
        return STYLE_MAP.get(style, "cinematic, high quality,")
 
    # ─── 参考图获取 ───
 
    def _get_reference_image(self, sid: str, segment_id: str, scene_map: dict) -> str:
        """获取参考图路径:优先用选中的版本,次之用最新版本"""
        # 1. 检查 session 中 artifacts.reference_generation.scenes 里的 selected
        if segment_id in scene_map and scene_map[segment_id].get("selected"):
            path = scene_map[segment_id]["selected"]
            if os.path.exists(path):
                return path
 
        # 2. 回退:扫描磁盘 Scenes 目录
        from .reference_agent import ReferenceGeneratorAgent
        versions = ReferenceGeneratorAgent._list_versions_static(sid, segment_id)
        if versions:
            return versions[-1]
 
        # 3. 默认路径
        return os.path.abspath(os.path.join('code/result/image', str(sid), 'Scenes', f"{segment_id}.jpg"))
 
    # ─── 预览 / Payload ───
 
    def _build_preview(self, sid: str, segments: list, scene_map: dict, style_name: str = "") -> list:
        preview = []
        for idx, seg in enumerate(segments, 1):
            segment_id = seg["segment_id"]
            versions = self._list_versions(sid, segment_id)
            ep_n = seg.get('episode_number', 1)
            seg_n = seg.get('segment_number', idx)
            preview.append({
                "id": segment_id,
                "name": f"第{ep_n}集-片段{seg_n}",
                "episode": ep_n,
                "index": seg_n,
                "description": self._assemble_prompt(seg, style_name),
                "duration": seg.get('total_duration', 10),
                "selected": versions[-1] if versions else "",
                "versions": versions,
                "status": "done" if versions else "pending",
            })
        return preview
 
    def _build_payload(self, sid: str, segments: list, style_name: str = "") -> dict:
        clips = []
        for idx, seg in enumerate(segments, 1):
            segment_id = seg["segment_id"]
            versions = self._list_versions(sid, segment_id)
            ep_n = seg.get('episode_number', 1)
            seg_n = seg.get('segment_number', idx)
            clips.append({
                "id": segment_id,
                "name": f"第{ep_n}集-片段{seg_n}",
                "episode": ep_n,
                "index": seg_n,
                "description": self._assemble_prompt(seg, style_name),
                "duration": seg.get('total_duration', 10),
                "selected": versions[-1] if versions else "",
                "versions": versions,
                "status": "done" if versions else "failed",
            })
        return {
            "payload": {
                "session_id": sid,
                "clips": clips,
            },
            "stage_completed": True,
        }
 
    def _update_session_video_data(self, sid: str, segments: list, style_name: str) -> None:
        """同步视频生成结果到 session.json 的 artifacts 中,适配前端读取"""
        session_path = os.path.join('code/data/sessions', f'{sid}.json')
        if not os.path.exists(session_path):
            return
 
        try:
            with open(session_path, 'r', encoding='utf-8') as f:
                data = json.load(f)
            
            payload = self._build_payload(sid, segments, style_name)
            data.setdefault("artifacts", {})["video_generation"] = payload["payload"]
            
            # 同时保留一份给后端的 scene2video (如果需要)
            # data[sid]["scene2video"] = ... (可选)
            
            with open(session_path, 'w', encoding='utf-8') as f:
                json.dump(data, f, indent=4, ensure_ascii=False)
        except Exception as e:
            logger.error(f"Failed to update session video data: {e}")
 
    # ─── 核心流程 ───
 
    async def process(self, input_data: Any, intervention: Optional[Dict] = None) -> Dict:
        from config import settings
        
        input_data = self._merge_session_params(input_data)
        sid = input_data["session_id"]
        
        # ═══ 介入:用户选择指定版本 ═══
        if intervention and "selected_clips" in intervention:
            selected_clips = intervention["selected_clips"] # Dict[segment_id, path]
            logger.info(f"[VideoAgent] 用户更新片段选择: {selected_clips}")
            
            session_path = os.path.join('code/data/sessions', f'{sid}.json')
            if os.path.exists(session_path):
                with open(session_path, 'r', encoding='utf-8') as f:
                    data = json.load(f)
                
                clips = data.get("artifacts", {}).get("video_generation", {}).get("clips", [])
                for clip in clips:
                    cid = clip.get("id")
                    if cid in selected_clips:
                        clip["selected"] = selected_clips[cid]
                
                with open(session_path, 'w', encoding='utf-8') as f:
                    json.dump(data, f, indent=4, ensure_ascii=False)
            
            # 返回当前状态
            artifacts = data.get("artifacts", {})
            episodes = artifacts.get('storyboard', {}).get('episodes', [])
            segments = []
            for ep in episodes:
                segments.extend(ep.get("segments", []))
            return self._build_payload(sid, segments)
 
        video_model = input_data.get("video_model", "") or settings.VIDEO_MODEL
        enable_concurrency = input_data.get("enable_concurrency", True)
        from config_model import get_max_concurrency
        concurrency = get_max_concurrency(video_model, enable_concurrency)
        
        video_ratio = input_data.get("video_ratio", "16:9")
        video_shot_type = input_data.get("video_shot_type", "multi")
        
        # 加载会话数据
        session_path = os.path.join('code/data/sessions', f'{sid}.json')
        with open(session_path, 'r', encoding='utf-8') as f:
            session_data = json.load(f)
            
        artifacts = session_data.get("artifacts", {})
        
        # 1. 获取拍摄片段列表 (从 Storyboard)
        episodes = artifacts.get('storyboard', {}).get('episodes', [])
        segments = []
        for ep in episodes:
            segments.extend(ep.get("segments", []))
            
        if not segments:
            raise Exception("未找到分镜片段数据,请先完成阶段3")
 
        # 2. 获取参考图路径映射 (从 Reference Generation)
        ref_art = artifacts.get('reference_generation', {})
        scene_list = ref_art.get('scenes', [])
        scene_map = {s['id']: s for s in scene_list if 'id' in s}
        
        style_zh = session_data.get('style', 'realistic')
        # 简单映射为中文显示名
        style_map_zh = {
            "anime": "动漫",
            "realistic": "写实",
            "cartoon": "卡通",
            "3d-disney": "3D迪斯尼",
            "oil-painting": "油画",
            "chinese-ink": "国画",
            "comic-book": "美漫",
            "cyberpunk": "赛博朋克"
        }
        style_name = style_map_zh.get(style_zh, style_zh)
 
        # ═══ 介入:重新生成指定片段 ═══
        if intervention:
            regen_ids = intervention.get("regenerate_clips", [])
            if regen_ids:
                self._report_progress("视频生成", "重新生成中...", 5)
                segment_map = {s['segment_id']: s for s in segments}
                
                def regen_run():
                    done = 0
                    with ThreadPoolExecutor(max_workers=concurrency) as executor:
                        futs = {}
                        for seg_id in regen_ids:
                            seg = segment_map.get(seg_id)
                            if not seg: continue
                            prompt = self._assemble_prompt(seg, style_name)
                            img_path = self._get_reference_image(sid, seg_id, scene_map)
                            duration = seg.get("total_duration", 10)
                            fut = executor.submit(
                                self._generate_one, sid, seg_id, prompt,
                                img_path, video_model, duration,
                                "", video_shot_type, video_ratio
                            )
                            futs[fut] = seg_id
                        for fut in as_completed(futs):
                            sid_done = futs[fut]
                            try:
                                _, res_path = fut.result()
                            except Exception as e:
                                logger.error(f"Regen future error for {sid_done}: {e}")
                                res_path = None
                            done += 1
                            pct = 5 + int(90 * done / max(1, len(regen_ids)))
                            if res_path:
                                versions = self._list_versions(sid, sid_done)
                                self._report_progress("视频生成", f"完成: {sid_done}", pct, data={
                                    "asset_complete": {
                                        "type": "clips", "id": sid_done,
                                        "status": "done",
                                        "selected": res_path,
                                        "versions": versions,
                                    }
                                })
                            else:
                                self._report_progress("视频生成", f"失败: {sid_done}", pct, data={
                                    "asset_complete": {
                                        "type": "clips", "id": sid_done,
                                        "status": "failed",
                                        "selected": "", "versions": [],
                                    }
                                })
                loop = asyncio.get_running_loop()
                await loop.run_in_executor(None, regen_run)
                
                # 同步到 session artifacts
                self._update_session_video_data(sid, segments, style_name)
                
                return self._build_payload(sid, segments, style_name)
 
        # ═══ 正常流程:全量生成 ═══
        self._report_progress("视频生成", "正在准备数据...", 2)
        preview = self._build_preview(sid, segments, scene_map, style_name)
        self._report_progress("视频生成", "加载视频列表", 5, data={"assets_preview": {"clips": preview}})
 
        def run():
            tasks = []
            for seg in segments:
                seg_id = seg["segment_id"]
                existing = self._list_versions(sid, seg_id)
                if existing: continue
                prompt = self._assemble_prompt(seg, style_name)
                img_path = self._get_reference_image(sid, seg_id, scene_map)
                duration = seg.get("total_duration", 10)
                tasks.append((seg_id, prompt, img_path, duration))
            if not tasks:
                self._report_progress("视频生成", "所有视频片段已存在", 95)
                return
            done = 0
            with ThreadPoolExecutor(max_workers=concurrency) as executor:
                futs = {}
                for seg_id, prompt, img_path, dur in tasks:
                    # 提交前立即发送正在运行的状态,让前端 UI 更新
                    self._report_progress("视频生成", f"启动生成: {seg_id}", 5, data={
                        "asset_complete": {
                            "type": "clips", "id": seg_id,
                            "status": "running"
                        }
                    })
                    fut = executor.submit(
                        self._generate_one, sid, seg_id, prompt,
                        img_path, video_model, dur,
                        "", video_shot_type, video_ratio
                    )
                    futs[fut] = seg_id
                for fut in as_completed(futs):
                    sid_done = futs[fut]
                    try:
                        _, res_path = fut.result()
                    except Exception as e:
                        logger.error(f"Video future error for {sid_done}: {e}")
                        res_path = None
                    done += 1
                    pct = 5 + int(90 * done / max(1, len(tasks)))
                    if res_path:
                        versions = self._list_versions(sid, sid_done)
                        self._report_progress("视频生成", f"完成: {sid_done}", pct, data={
                            "asset_complete": {
                                "type": "clips", "id": sid_done,
                                "status": "done",
                                "selected": res_path,
                                "versions": versions,
                            }
                        })
                    else:
                        self._report_progress("视频生成", f"失败: {sid_done}", pct, data={
                            "asset_complete": {
                                "type": "clips", "id": sid_done,
                                "status": "failed",
                                "selected": "", "versions": [],
                            }
                        })
                    if self.cancellation_check and self.cancellation_check():
                        for f in futs:
                            if not f.done(): f.cancel()
                        break
        loop = asyncio.get_running_loop()
        await loop.run_in_executor(None, run)
        
        # 同步到 session artifacts
        self._update_session_video_data(sid, segments, style_name)
        
        self._report_progress("视频生成", "完成", 100)
        return self._build_payload(sid, segments, style_name)