-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrender_manager.py
More file actions
759 lines (648 loc) · 27.5 KB
/
Copy pathrender_manager.py
File metadata and controls
759 lines (648 loc) · 27.5 KB
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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
"""
render_manager.py —— RenderManager Agent
项目:《面向无字幕赛事录像的体育视频自动字幕与高光剪辑多智能体系统》
职责:
1. 读取 EditPlannerOutput(剪辑脚本),执行最终的音画渲染与导出。
2. MediaDecorator 子系统:为每个片段烧录字幕与氛围贴纸。
3. RenderManager 子系统:片段拼接、转场特效、BGM 混音、CPU 优化导出。
4. 输出标准化 RenderReport,记录渲染性能指标与血缘关系。
设计原则:
- 防御式内存管理:MoviePy 在纯 CPU 环境下极易内存泄露,必须严格执行
"每帧提取 → 即时关闭 → 强制 GC" 的三段式回收策略。
- 零长周期持有 Clip:禁止在循环外部持有 subclip 引用,每个片段处理完毕后
立即调用 .close() 并清空列表。
- 降级容错:任何单片段渲染失败都不应阻断整条流水线,记录警告后继续。
- 纯 CPU 轻量化:禁用 GPU 加速,通过 preset='ultrafast'、合理降分辨率等手段
控制渲染耗时。
"""
from __future__ import annotations
import gc
import logging
import os
import warnings
from datetime import datetime
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Tuple
import numpy as np
import pysrt
from PIL import Image, ImageDraw, ImageFont
# ---------------------------------------------------------------------------
# MoviePy 兼容性补丁:Pillow 10+ 移除了 ANTIALIAS,MoviePy 1.0.3 仍引用
# 必须在导入 moviepy.editor 之前执行,否则 resize() 会崩溃
# ---------------------------------------------------------------------------
from PIL import Image as _Image
if not hasattr(_Image, "ANTIALIAS"):
_Image.ANTIALIAS = _Image.LANCZOS # type: ignore[misc]
from moviepy.editor import (
AudioClip,
CompositeAudioClip,
CompositeVideoClip,
ImageClip,
VideoFileClip,
concatenate_audioclips,
concatenate_videoclips,
afx,
)
from config import settings
from schema import (
AgentName,
ClipItem,
EditPlannerOutput,
RenderReport,
load_edit_planner_output,
save_to_json,
)
# ---------------------------------------------------------------------------
# 日志配置
# ---------------------------------------------------------------------------
logging.basicConfig(
level=getattr(logging, settings.log_level, logging.INFO),
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
)
logger = logging.getLogger("RenderManagerAgent")
# ---------------------------------------------------------------------------
# 异常类
# ---------------------------------------------------------------------------
class RenderManagerError(Exception):
"""RenderManager Agent 通用异常基类。"""
pass
class RenderPipelineError(RenderManagerError):
"""渲染流水线执行阶段异常。"""
pass
class SourceVideoNotFoundError(RenderManagerError):
"""原始视频文件不存在。"""
pass
# ---------------------------------------------------------------------------
# 常量:渲染参数
# ---------------------------------------------------------------------------
# 贴纸默认显示时长(秒)
_STICKER_DISPLAY_SEC: float = 1.0
# 贴纸淡出时长(秒)
_STICKER_FADEOUT_SEC: float = 0.3
# BGM 音量增益(相对原音量)
_BGM_VOLUME_MULTIPLIER: float = 0.15
# 字幕区域底部边距(像素)
_SUBTITLE_BOTTOM_MARGIN: int = 60
# 字幕字体大小(像素)
_SUBTITLE_FONT_SIZE: int = 24
# 贴纸字体大小(像素)
_STICKER_FONT_SIZE: int = 64
# ---------------------------------------------------------------------------
# 工具函数:PIL 文字图片生成
# ---------------------------------------------------------------------------
def _make_text_image(
text: str,
width: int,
height: int = 60,
fontsize: int = 28,
text_color: Tuple[int, int, int, int] = (255, 255, 255, 255),
outline: bool = True,
bg_color: Tuple[int, int, int, int] = (0, 0, 0, 0),
) -> np.ndarray:
"""
使用 PIL 生成带描边的文字透明底图,供 MoviePy ImageClip 使用。
无需依赖 ImageMagick,纯 PIL 实现,兼容 Windows / Linux / macOS。
Args:
text: 文字内容。
width: 画布宽度(像素)。
height: 画布高度(像素)。
fontsize: 字体大小。
text_color: 文字 RGBA 颜色。
outline: 是否绘制黑色描边以增强可读性。
bg_color: 背景 RGBA 颜色(默认全透明)。
Returns:
np.ndarray: RGBA 图像数组,形状 (height, width, 4)。
"""
img = Image.new("RGBA", (width, height), bg_color)
draw = ImageDraw.Draw(img)
# 字体加载:优先系统字体,回退默认
font: ImageFont.FreeTypeFont | ImageFont.ImageFont
try:
# Windows 常见字体
font = ImageFont.truetype("arial.ttf", fontsize)
except OSError:
try:
# Linux 常见字体
font = ImageFont.truetype("DejaVuSans.ttf", fontsize)
except OSError:
font = ImageFont.load_default()
# 计算文字位置(水平居中,垂直居中)
bbox = draw.textbbox((0, 0), text, font=font)
text_w = bbox[2] - bbox[0]
text_h = bbox[3] - bbox[1]
text_x = max(10, (width - text_w) // 2)
text_y = max(5, (height - text_h) // 2)
# 黑色描边(4 方向偏移)
if outline:
for dx, dy in [(-1, -1), (-1, 1), (1, -1), (1, 1), (-2, 0), (2, 0), (0, -2), (0, 2)]:
draw.text((text_x + dx, text_y + dy), text, font=font, fill=(0, 0, 0, 255))
draw.text((text_x, text_y), text, font=font, fill=text_color)
return np.array(img)
# ---------------------------------------------------------------------------
# 工具函数:SRT 字幕解析与窗口过滤
# ---------------------------------------------------------------------------
def _load_subtitles_for_clip(
srt_path: str,
clip_start_sec: float,
clip_end_sec: float,
) -> List[Tuple[float, float, str]]:
"""
加载 SRT 字幕文件,并过滤出与当前片段时间窗口重叠的字幕条目。
返回的时间戳已转换为相对于片段起始时间的偏移量。
Args:
srt_path: SRT 文件绝对路径。
clip_start_sec: 片段在原始视频中的起始时间(秒)。
clip_end_sec: 片段在原始视频中的结束时间(秒)。
Returns:
List[Tuple[float, float, str]]: (相对起始, 相对结束, 文字) 列表。
"""
if not Path(srt_path).exists():
logger.warning(f"字幕文件不存在: {srt_path}")
return []
try:
subs = pysrt.open(srt_path, encoding="utf-8")
except Exception as exc:
logger.warning(f"解析字幕文件失败: {exc}")
return []
results: List[Tuple[float, float, str]] = []
for sub in subs:
sub_start = sub.start.ordinal / 1000.0
sub_end = sub.end.ordinal / 1000.0
# 判断是否重叠
if sub_end < clip_start_sec or sub_start > clip_end_sec:
continue
# 转换为片段内相对时间
rel_start = max(0.0, sub_start - clip_start_sec)
rel_end = min(clip_end_sec - clip_start_sec, sub_end - clip_start_sec)
duration = rel_end - rel_start
if duration <= 0:
continue
results.append((rel_start, rel_end, sub.text.strip()))
return results
# ---------------------------------------------------------------------------
# MediaDecorator:单片段装饰(字幕 + 贴纸)
# ---------------------------------------------------------------------------
def _decorate_single_clip(
source_video_path: str,
clip_item: ClipItem,
srt_path: Optional[str],
target_size: Optional[Tuple[int, int]] = None,
) -> Optional[CompositeVideoClip]:
"""
对单个高光片段执行字幕烧录与贴纸叠加,返回装饰后的 CompositeVideoClip。
内存管理铁律:
- 输入的 VideoFileClip(subclip) 由调用方负责关闭。
- 本函数内部创建的所有 ImageClip 由调用方在 CompositeVideoClip 关闭时级联释放。
Args:
source_video_path: 原始视频文件路径。
clip_item: 剪辑脚本中的单个条目。
srt_path: SRT 字幕文件路径(可为 None)。
target_size: 目标输出分辨率 (宽, 高);None 则保持原始分辨率。
Returns:
Optional[CompositeVideoClip]: 装饰后的视频片段;失败则返回 None。
"""
# 1. 提取子片段
try:
video = VideoFileClip(source_video_path).subclip(
clip_item.start_sec, clip_item.end_sec
)
except Exception as exc:
logger.error(f"提取子片段失败 [{clip_item.clip_id}]: {exc}")
return None
# 分辨率调整(若指定)
if target_size is not None and video.size != list(target_size):
try:
video = video.resize(newsize=target_size)
except Exception as exc:
logger.warning(f"分辨率调整失败,保持原分辨率: {exc}")
width, height = video.size
overlays: List[Any] = [video]
# 2. 字幕烧录
if clip_item.subtitle_enabled and srt_path:
subtitle_entries = _load_subtitles_for_clip(
srt_path, clip_item.start_sec, clip_item.end_sec
)
for rel_start, rel_end, text in subtitle_entries:
duration = rel_end - rel_start
if duration <= 0:
continue
try:
arr = _make_text_image(
text,
width=width,
height=60,
fontsize=_SUBTITLE_FONT_SIZE,
)
txt_clip = (
ImageClip(arr, duration=duration)
.set_start(rel_start)
.set_position(("center", height - _SUBTITLE_BOTTOM_MARGIN))
)
overlays.append(txt_clip)
except Exception as exc:
logger.warning(f"字幕叠加失败: {exc}")
# 3. 贴纸烧录
if clip_item.sticker_text:
try:
sticker_duration = min(_STICKER_DISPLAY_SEC, video.duration)
arr = _make_text_image(
clip_item.sticker_text,
width=400,
height=80,
fontsize=48,
text_color=(255, 255, 0, 255), # 亮黄色
)
sticker = (
ImageClip(arr, duration=sticker_duration)
.set_start(0)
.set_position("center")
.fadeout(_STICKER_FADEOUT_SEC)
)
overlays.append(sticker)
except Exception as exc:
logger.warning(f"贴纸叠加失败: {exc}")
# 4. 合成
try:
composite = CompositeVideoClip(overlays, size=(width, height))
# 🔴 将 overlays 列表附加到 composite 上,便于后续统一关闭
composite._overlay_clips = overlays # type: ignore[attr-defined]
return composite
except Exception as exc:
logger.error(f"片段合成失败 [{clip_item.clip_id}]: {exc}")
# 紧急清理已创建的 overlay
for o in overlays:
if o is not video and hasattr(o, "close"):
o.close()
video.close()
return None
# ---------------------------------------------------------------------------
# RenderManager:片段拼接、转场、BGM 混音、导出
# ---------------------------------------------------------------------------
def _resolve_export_params(
source_video_path: str,
) -> Tuple[float, Optional[Tuple[int, int]], str, str]:
"""
根据 settings 和原始视频参数,解析最终导出配置。
Returns:
Tuple[fps, target_size, video_bitrate, audio_bitrate]
"""
# FPS
if settings.output_fps > 0:
fps = settings.output_fps
else:
# 从原视频探测
try:
probe = VideoFileClip(source_video_path)
fps = probe.fps if probe.fps else 30.0
probe.close()
except Exception:
fps = 30.0
# 分辨率
target_size: Optional[Tuple[int, int]] = None
if settings.output_width > 0 or settings.output_height > 0:
# 至少有一个维度被显式指定
try:
probe = VideoFileClip(source_video_path)
orig_w, orig_h = probe.size
probe.close()
except Exception:
orig_w, orig_h = 1920, 1080
if settings.output_width > 0 and settings.output_height > 0:
target_size = (settings.output_width, settings.output_height)
elif settings.output_width > 0:
# 保持宽高比,按宽度缩放
ratio = settings.output_width / orig_w
target_size = (settings.output_width, int(orig_h * ratio))
elif settings.output_height > 0:
ratio = settings.output_height / orig_h
target_size = (int(orig_w * ratio), settings.output_height)
# 码率
video_bitrate = f"{settings.output_video_bitrate_kbps}k"
audio_bitrate = f"{settings.output_audio_bitrate_kbps}k"
return fps, target_size, video_bitrate, audio_bitrate
def _build_bgm_audio(
bgm_path: str,
target_duration: float,
) -> Optional[Any]:
"""
加载 BGM 并循环/截断至目标时长,应用音量衰减。
Args:
bgm_path: BGM 文件路径。
target_duration: 目标音频时长(秒)。
Returns:
Optional[AudioClip]: 处理后的 BGM 音频;失败则返回 None。
"""
if not Path(bgm_path).exists():
logger.warning(f"BGM 文件不存在: {bgm_path}")
return None
try:
from moviepy.editor import AudioFileClip
bgm = AudioFileClip(bgm_path)
# 若 BGM 短于目标时长,循环拼接
if bgm.duration < target_duration:
loops_needed = int(np.ceil(target_duration / bgm.duration))
bgm = concatenate_audioclips([bgm] * loops_needed)
# 截断至目标时长
bgm = bgm.subclip(0, target_duration)
# 音量衰减(垫乐级别)
bgm = bgm.fx(afx.volumex, _BGM_VOLUME_MULTIPLIER)
return bgm
except Exception as exc:
logger.warning(f"BGM 处理失败: {exc}")
return None
def _render_pipeline(
script: EditPlannerOutput,
srt_path: Optional[str],
output_video_path: str,
fps: float,
target_size: Optional[Tuple[int, int]],
video_bitrate: str,
audio_bitrate: str,
) -> Tuple[bool, List[str]]:
"""
执行完整的渲染流水线:装饰 → 拼接 → BGM 混音 → 导出。
内存管理策略:
- 每处理完一个片段,立即关闭其 CompositeVideoClip 和所有 overlay。
- 拼接前将 decorated clips 收集到列表,拼接完成后立即清空列表并 GC。
- 最终的 CompositeVideoClip(含音频)在 write_videofile 后置于 try...finally 中关闭。
Args:
script: 剪辑脚本。
srt_path: 字幕文件路径(可为 None)。
output_video_path: 输出视频路径。
fps: 输出帧率。
target_size: 目标分辨率。
video_bitrate: 视频码率字符串。
audio_bitrate: 音频码率字符串。
Returns:
Tuple[bool, List[str]]: (是否成功, 警告列表)。
"""
warnings_list: List[str] = []
source_video = script.source_video
# ------------------------------------------------------------------
# 阶段 1:逐个片段装饰(字幕 + 贴纸)
# ------------------------------------------------------------------
decorated_clips: List[Any] = []
for clip_item in script.clips:
logger.info(f"装饰片段 {clip_item.clip_id}: [{clip_item.start_sec:.1f}s-{clip_item.end_sec:.1f}s]")
composite = _decorate_single_clip(
source_video, clip_item, srt_path, target_size=target_size
)
if composite is None:
msg = f"片段 {clip_item.clip_id} 装饰失败,已跳过"
logger.warning(msg)
warnings_list.append(msg)
continue
# 转场预处理:fade 类型应用 crossfadein
if clip_item.transition_type == "fade" and clip_item.transition_duration_sec > 0:
try:
composite = composite.crossfadein(clip_item.transition_duration_sec)
except Exception as exc:
msg = f"片段 {clip_item.clip_id} crossfadein 失败: {exc}"
logger.warning(msg)
warnings_list.append(msg)
decorated_clips.append(composite)
if not decorated_clips:
raise RenderPipelineError("所有片段装饰均失败,无内容可渲染")
# ------------------------------------------------------------------
# 阶段 2:片段拼接
# ------------------------------------------------------------------
logger.info(f"拼接 {len(decorated_clips)} 个片段...")
try:
final_video = concatenate_videoclips(decorated_clips, method="compose")
except Exception as exc:
raise RenderPipelineError(f"片段拼接失败: {exc}") from exc
# 🔴 注意:concatenate_videoclips(method='compose') 创建的 final_video
# 内部仍持有对 decorated_clips 的帧级引用,而非深拷贝。
# 若在此处关闭 decorated_clips,final_video 在导出时会报
# 'NoneType' object has no attribute 'get_frame'。
# 因此 decorated_clips 的释放必须推迟到 final_video 导出完成后。
# ------------------------------------------------------------------
# 阶段 3:BGM 混音
# ------------------------------------------------------------------
bgm_audio: Optional[Any] = None
if script.bgm_path:
bgm_audio = _build_bgm_audio(script.bgm_path, final_video.duration)
if bgm_audio and final_video.audio is not None:
try:
mixed = CompositeAudioClip([final_video.audio, bgm_audio])
final_video = final_video.set_audio(mixed)
logger.info("BGM 混音完成")
except Exception as exc:
msg = f"BGM 混音失败: {exc}"
logger.warning(msg)
warnings_list.append(msg)
elif script.bgm_path and final_video.audio is None:
msg = "原视频无音频轨道,跳过 BGM 混音"
logger.warning(msg)
warnings_list.append(msg)
# ------------------------------------------------------------------
# 阶段 4:导出(try...finally 确保关闭)
# ------------------------------------------------------------------
try:
logger.info(f"开始导出成片: {output_video_path}")
logger.info(f" 参数: fps={fps}, size={target_size}, vbitrate={video_bitrate}, abitrate={audio_bitrate}")
final_video.write_videofile(
output_video_path,
codec="libx264",
audio_codec="aac",
fps=fps,
bitrate=video_bitrate,
audio_bitrate=audio_bitrate,
preset="medium", # 画质优先:medium 比 ultrafast 画质更好、噪点更少
threads=min(4, settings.num_workers),
ffmpeg_params=[
"-crf", "23", # 恒定质量因子,23 是默认值,越小画质越好(18-28 范围)
"-tune", "film", # 针对电影/视频内容优化(减少噪点、保留细节)
"-profile:v", "high", # 使用 High Profile,支持更多编码特性
"-level", "4.1", # 兼容性级别
],
verbose=False,
logger=None,
)
logger.info(f"成片导出完成: {output_video_path}")
return True, warnings_list
except Exception as exc:
raise RenderPipelineError(f"视频导出失败: {exc}") from exc
finally:
# 🔴 铁律:无论导出成功或失败,强制关闭最终 CompositeVideoClip
try:
if final_video is not None:
final_video.close()
except Exception as exc:
logger.warning(f"关闭 final_video 时异常: {exc}")
# 🔴 关键: decorated_clips 必须在 final_video 关闭后再释放,
# 因为 concatenate_videoclips(method='compose') 内部持有引用
for clip in decorated_clips:
try:
# 先关闭 composite 内部的所有 overlay(字幕、贴纸、底层视频)
if hasattr(clip, "_overlay_clips"):
for o in clip._overlay_clips:
try:
o.close()
except Exception:
pass
clip._overlay_clips.clear()
clip.close()
except Exception:
pass
decorated_clips.clear()
# 关闭 BGM 音频
if bgm_audio is not None:
try:
bgm_audio.close()
except Exception:
pass
# 强制垃圾回收
gc.collect()
# ---------------------------------------------------------------------------
# Agent 主入口
# ---------------------------------------------------------------------------
class RenderManagerAgent:
"""
RenderManager Agent 封装类。
对外提供统一的 `process(...)` 接口,
吃进 edit_script.json,吐出成片视频 + render_report.json。
"""
def process(
self,
edit_script_json_path: str,
subtitle_srt_path: Optional[str] = None,
report_filename: Optional[str] = None,
) -> Tuple[str, str]:
"""
执行完整的 RenderManager 流水线。
Args:
edit_script_json_path: EditPlannerOutput JSON 文件路径。
subtitle_srt_path: 字幕 SRT 文件路径。
若为 None,则尝试从脚本中的 source_video 路径推断。
Returns:
Tuple[str, str]: (成片视频绝对路径, 渲染报告 JSON 绝对路径)。
Raises:
RenderManagerError: 各阶段异常。
"""
edit_script_json_path = str(Path(edit_script_json_path).resolve())
if not Path(edit_script_json_path).exists():
raise RenderManagerError(f"输入文件不存在: {edit_script_json_path}")
# 1. 读取剪辑脚本
try:
script = load_edit_planner_output(edit_script_json_path)
except Exception as exc:
raise RenderManagerError(f"读取剪辑脚本失败: {exc}") from exc
source_video = script.source_video
if not Path(source_video).exists():
raise SourceVideoNotFoundError(f"原始视频不存在: {source_video}")
# 2. 推断字幕路径(若未提供)
if subtitle_srt_path is None:
# 尝试与原始视频同目录下的 .srt,或 temp/subtitles 下的标准命名
video_stem = Path(source_video).stem
candidates = [
str(Path(source_video).with_suffix(".srt")),
str(settings.get_temp_subdir("subtitles") / f"{video_stem}_whisper-small-en.srt"),
str(settings.get_temp_subdir("subtitles") / f"{video_stem}_whisper-base-zh.srt"),
]
for cand in candidates:
if Path(cand).exists():
subtitle_srt_path = cand
break
if subtitle_srt_path:
logger.info(f"使用字幕: {subtitle_srt_path}")
else:
logger.warning("未找到字幕文件,将跳过字幕烧录")
# 3. 解析导出参数
fps, target_size, video_bitrate, audio_bitrate = _resolve_export_params(source_video)
logger.info(
f"========== RenderManager Agent 开始处理 ==========\n"
f" 原始视频: {source_video}\n"
f" 输出分辨率: {target_size or '保持原始'}\n"
f" 输出帧率: {fps}\n"
f" 视频码率: {video_bitrate}\n"
f" 音频码率: {audio_bitrate}"
)
# 4. 确定输出路径
video_stem = Path(source_video).stem
output_dir = settings.get_output_subdir("videos")
output_video_path = str(output_dir / script.output_filename)
# 5. 执行渲染流水线
render_start_at = datetime.now().isoformat()
render_cost_sec = 0.0
success = False
warnings_list: List[str] = []
try:
import time
t0 = time.perf_counter()
success, warnings_list = _render_pipeline(
script=script,
srt_path=subtitle_srt_path,
output_video_path=output_video_path,
fps=fps,
target_size=target_size,
video_bitrate=video_bitrate,
audio_bitrate=audio_bitrate,
)
render_cost_sec = time.perf_counter() - t0
except RenderPipelineError:
raise
except Exception as exc:
raise RenderPipelineError(f"渲染流水线未捕获异常: {exc}") from exc
render_end_at = datetime.now().isoformat()
# 6. 计算产出文件信息
output_duration_sec = 0.0
output_size_mb = 0.0
if Path(output_video_path).exists():
output_size_mb = Path(output_video_path).stat().st_size / (1024 * 1024)
try:
probe = VideoFileClip(output_video_path)
output_duration_sec = probe.duration if probe.duration else 0.0
probe.close()
except Exception:
pass
# 7. 生成 RenderReport
report = RenderReport(
source_video=source_video,
output_video_path=output_video_path,
output_video_duration_sec=round(output_duration_sec, 3),
output_video_size_mb=round(output_size_mb, 2),
upstream_script_path=edit_script_json_path,
upstream_subtitle_path=subtitle_srt_path,
render_start_at=render_start_at,
render_end_at=render_end_at,
render_cost_sec=round(render_cost_sec, 2),
warnings=warnings_list,
)
report_dir = settings.get_output_subdir("reports")
safe_report_filename = Path(report_filename).name if report_filename else f"{video_stem}_render_report.json"
report_path = str(report_dir / safe_report_filename)
save_to_json(report, report_path)
logger.info(
f"RenderManager Agent 处理完成:\n"
f" 成片: {output_video_path} ({output_size_mb:.1f} MB, {output_duration_sec:.1f}s)\n"
f" 报告: {report_path}\n"
f" 耗时: {render_cost_sec:.1f}s\n"
f" 警告: {len(warnings_list)} 条"
)
return output_video_path, report_path
# ---------------------------------------------------------------------------
# 命令行直接运行入口
# ---------------------------------------------------------------------------
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="RenderManager Agent —— 音画渲染与导出")
parser.add_argument("input_json", help="EditPlannerOutput JSON 文件路径")
parser.add_argument(
"--subtitle-srt",
default=None,
help="字幕 SRT 文件路径(可选,默认自动推断)",
)
args = parser.parse_args()
agent = RenderManagerAgent()
try:
video_path, report_path = agent.process(
edit_script_json_path=args.input_json,
subtitle_srt_path=args.subtitle_srt,
)
print(f"\n✅ RenderManager Agent 执行成功")
print(f"🎬 成片视频: {video_path}")
print(f"📄 渲染报告: {report_path}")
except RenderManagerError as exc:
logger.error(f"RenderManager Agent 执行失败: {exc}")
raise SystemExit(1) from exc