-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvideo_editor.py
More file actions
718 lines (617 loc) · 26.9 KB
/
video_editor.py
File metadata and controls
718 lines (617 loc) · 26.9 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
#!/usr/bin/env python3
"""
小语种听写视频自动剪辑工具 v1.0
管线流程:
1. [可选] python-audio-separator 音频分离
2. auto-editor / FFmpeg 静音检测+裁剪
3. FFmpeg 后处理(倍速、音量最大化、扩音器特效、4K 30fps导出)
使用方法:
python video_editor.py input.mp4
python video_editor.py input.mp4 -o output.mp4 --speed 1.4
python video_editor.py --batch ./raw_videos --output-dir ./processed
"""
import argparse
import json
import os
import re
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
# ─────────────────────────────────────────────
# 默认配置
# ─────────────────────────────────────────────
DEFAULTS = {
"speed": 1.2,
"target_duration": None,
"target_duration_max": None,
"max_speed": 3.0,
"max_duration": None,
"silence_threshold_db": -40,
"min_silence_sec": 1.0,
"margin_sec": 0.1,
"fps": 30,
"loudness_lufs": -8,
"megaphone": False,
"audio_separation": False,
"separator_model": "UVR-MDX-NET-Inst_HQ_3",
"codec": "libx264",
"crf": 18,
"preset": "medium",
}
# ─────────────────────────────────────────────
# 工具函数
# ─────────────────────────────────────────────
def log(msg, level="info"):
prefix = {
"info": "[INFO]",
"warn": "[WARN]",
"error": "[ERR ]",
"ok": "[ OK ]",
"step": "[STEP]",
}
print(f"{prefix.get(level, '[INFO]')} {msg}")
def run(cmd, desc=""):
"""执行外部命令,返回 subprocess.CompletedProcess"""
if desc:
log(desc)
result = subprocess.run(
cmd,
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
)
if result.returncode != 0:
stderr_lines = (result.stderr or "").strip().split("\n")
for line in stderr_lines[-5:]:
if line.strip():
log(f" {line.strip()}", "error")
return result
def _resolve_tool(name):
"""查找工具路径:优先 venv 内,其次 PATH"""
# 优先检查当前 Python 所在的 Scripts/bin 目录
venv_dir = Path(sys.executable).parent
if sys.platform == "win32":
candidates = [venv_dir / f"{name}.exe", venv_dir / f"{name}.cmd"]
else:
candidates = [venv_dir / name]
for p in candidates:
if p.exists():
return str(p)
# 回退到 PATH
found = shutil.which(name)
return found
def tool_available(name):
"""检查CLI工具是否可用(venv 或 PATH)"""
path = _resolve_tool(name)
if not path:
return False
try:
cmd = [path, "-version"] if name in ("ffmpeg", "ffprobe") else [path, "--version"]
subprocess.run(cmd, capture_output=True, timeout=30)
return True
except (FileNotFoundError, subprocess.TimeoutExpired, OSError):
return False
def get_tool(name):
"""获取工具的完整路径,不存在则返回 name 本身"""
return _resolve_tool(name) or name
def get_duration(path):
"""获取媒体文件时长(秒)"""
r = run(["ffprobe", "-v", "quiet", "-print_format", "json", "-show_format", str(path)])
if r.returncode != 0:
return 0.0
try:
return float(json.loads(r.stdout)["format"]["duration"])
except (KeyError, ValueError, json.JSONDecodeError):
return 0.0
def format_time(seconds):
"""秒数转可读时间"""
m, s = divmod(int(seconds), 60)
return f"{m}分{s}秒" if m else f"{s}秒"
# ─────────────────────────────────────────────
# 静音检测
# ─────────────────────────────────────────────
def detect_silences(path, threshold_db=-30, min_dur=0.4):
"""使用 FFmpeg silencedetect 检测静音段,返回 [(start, end), ...]"""
r = run(
[
"ffmpeg", "-i", str(path),
"-af", f"silencedetect=noise={threshold_db}dB:d={min_dur}",
"-f", "null", os.devnull,
],
desc=f"检测静音段 (阈值={threshold_db}dB, 最短={min_dur}s)",
)
stderr = r.stderr or ""
starts = [float(x) for x in re.findall(r"silence_start:\s*([\d.]+)", stderr)]
ends = [float(x) for x in re.findall(r"silence_end:\s*([\d.]+)", stderr)]
if len(starts) > len(ends):
ends.append(get_duration(path))
silences = list(zip(starts, ends))
total_silent = sum(e - s for s, e in silences)
log(f"检测到 {len(silences)} 段静音,总计 {format_time(total_silent)}")
return silences
def calc_keep_segments(silences, total_duration, margin=0.08):
"""根据静音段计算需要保留的时间片段"""
if not silences:
return [(0, total_duration)]
keeps = []
# 第一个静音之前的内容
end = min(silences[0][0] + margin, total_duration)
if end > 0.05:
keeps.append((0, end))
# 相邻静音之间的内容
for i in range(len(silences) - 1):
start = max(0, silences[i][1] - margin)
end = min(silences[i + 1][0] + margin, total_duration)
if end > start + 0.05:
keeps.append((start, end))
# 最后一个静音之后的内容
start = max(0, silences[-1][1] - margin)
if start < total_duration - 0.05:
keeps.append((start, total_duration))
kept_dur = sum(e - s for s, e in keeps)
log(f"保留 {len(keeps)} 个有效片段,共 {format_time(kept_dur)}")
return keeps
# ─────────────────────────────────────────────
# 步骤1:音频分离(可选)
# ─────────────────────────────────────────────
def step_audio_separate(input_path, work_dir, model):
"""使用 python-audio-separator 分离音频"""
if not tool_available("audio-separator"):
log("audio-separator 未安装,跳过音频分离", "warn")
log(" 安装: pip install audio-separator[cpu]", "warn")
return None
out_dir = Path(work_dir) / "separated"
out_dir.mkdir(exist_ok=True)
r = run(
[
get_tool("audio-separator"), str(input_path),
"--model_filename", f"{model}.onnx",
"--output_dir", str(out_dir),
"--output_format", "wav",
],
desc=f"音频分离 (模型: {model})",
)
if r.returncode != 0:
log("音频分离失败,将使用原始音频继续", "warn")
return None
# 优先找 Instrumental 轨道(包含环境声+TTS播报)
for pattern in ["*Instrumental*", "*instrument*", "*no_vocal*", "*accompaniment*"]:
found = list(out_dir.glob(pattern))
if found:
log(f"音频分离完成: {found[0].name}", "ok")
return found[0]
# 回退:取非vocal文件
all_wav = list(out_dir.glob("*.wav"))
non_vocal = [f for f in all_wav if "vocal" not in f.stem.lower()]
if non_vocal:
log(f"音频分离完成: {non_vocal[0].name}", "ok")
return non_vocal[0]
log("未找到分离后的音频轨道", "warn")
return None
def step_replace_audio(video_path, audio_path, output_path):
"""将视频的音频轨道替换为指定音频"""
r = run(
[
"ffmpeg", "-i", str(video_path), "-i", str(audio_path),
"-c:v", "copy", "-map", "0:v:0", "-map", "1:a:0",
"-shortest", "-y", str(output_path),
],
desc="替换音频轨道",
)
return r.returncode == 0
# ─────────────────────────────────────────────
# 步骤2:静音去除
# ─────────────────────────────────────────────
def step_remove_silence_auto_editor(input_path, output_path, threshold_pct=4, margin=0.08):
"""使用 auto-editor 去除静音段"""
cmd = [
get_tool("auto-editor"), str(input_path),
"--edit", f"audio:threshold={threshold_pct}%",
"--margin", f"{margin}s",
"--no-open",
"-o", str(output_path),
]
r = run(cmd, desc=f"auto-editor 去除静音 (阈值={threshold_pct}%, 边距={margin}s)")
if r.returncode == 0 and Path(output_path).exists():
dur = get_duration(output_path)
log(f"静音去除完成,输出时长: {format_time(dur)}", "ok")
return True
return False
def step_remove_silence_ffmpeg(input_path, output_path, threshold_db=-30, min_dur=0.4, margin=0.08):
"""使用纯 FFmpeg 去除静音段(auto-editor 的回退方案)"""
silences = detect_silences(input_path, threshold_db, min_dur)
total_dur = get_duration(input_path)
if not silences:
log("未检测到静音,复制原文件")
shutil.copy2(str(input_path), str(output_path))
return True
keeps = calc_keep_segments(silences, total_dur, margin)
if not keeps:
log("去除静音后没有内容剩余", "error")
return False
# 使用 segment 切割 + concat 拼接(比 select 滤镜更快,尤其对4K视频)
with tempfile.TemporaryDirectory(prefix="veditor_seg_") as seg_dir:
seg_files = []
for i, (start, end) in enumerate(keeps):
seg_path = Path(seg_dir) / f"seg_{i:04d}.ts"
duration = end - start
r = run(
[
"ffmpeg",
"-ss", f"{start:.3f}",
"-i", str(input_path),
"-t", f"{duration:.3f}",
"-c:v", "libx264", "-preset", "ultrafast", "-crf", "18",
"-c:a", "aac", "-b:a", "192k",
"-avoid_negative_ts", "make_zero",
"-y", str(seg_path),
],
)
if r.returncode == 0 and seg_path.exists():
seg_files.append(seg_path)
if not seg_files:
log("片段提取失败", "error")
return False
# 生成 concat 清单
concat_list = Path(seg_dir) / "concat.txt"
with open(concat_list, "w", encoding="utf-8") as f:
for seg in seg_files:
safe_path = str(seg).replace("\\", "/")
f.write(f"file '{safe_path}'\n")
r = run(
[
"ffmpeg", "-f", "concat", "-safe", "0",
"-i", str(concat_list),
"-c", "copy",
"-y", str(output_path),
],
desc=f"拼接 {len(seg_files)} 个片段",
)
if r.returncode == 0:
dur = get_duration(output_path)
log(f"静音去除完成,输出时长: {format_time(dur)}", "ok")
return True
return False
# ─────────────────────────────────────────────
# 步骤3:后处理
# ─────────────────────────────────────────────
def build_audio_filter(speed=1.4, megaphone=True, loudness_lufs=-10):
"""构建音频滤镜链"""
filters = []
# 倍速
if speed != 1.0:
filters.append(f"atempo={speed}")
# 扩音器效果:带通限制 + 压缩 + 中频增强
if megaphone:
filters.extend([
"highpass=f=300",
"lowpass=f=4000",
"acompressor=threshold=-15dB:ratio=10:attack=1:release=50",
"equalizer=f=800:t=q:w=0.5:g=8",
"equalizer=f=2000:t=q:w=0.5:g=3",
])
# 音量最大化(loudnorm 始终放最后)
filters.append(f"loudnorm=I={loudness_lufs}:TP=-1:LRA=13")
return ",".join(filters)
def step_post_process(input_path, output_path, speed=1.4, loudness=-10,
megaphone=True, fps=30, codec="libx264", crf=18, preset="medium"):
"""FFmpeg 后处理:倍速 + 音量最大化 + 扩音器特效 + 编码导出"""
vf = f"setpts=PTS/{speed}"
af = build_audio_filter(speed, megaphone, loudness)
effect_desc = f"{speed}x倍速 | {loudness}LUFS | 扩音器={'开' if megaphone else '关'} | {fps}fps | {codec}"
r = run(
[
"ffmpeg", "-i", str(input_path),
"-vf", vf,
"-af", af,
"-c:v", codec, "-preset", preset, "-crf", str(crf),
"-r", str(fps),
"-c:a", "aac", "-b:a", "64k",
"-ar", "44100",
"-movflags", "+faststart",
"-y", str(output_path),
],
desc=f"后处理: {effect_desc}",
)
if r.returncode == 0 and Path(output_path).exists():
dur = get_duration(output_path)
log(f"后处理完成,最终时长: {format_time(dur)}", "ok")
return True
return False
# ─────────────────────────────────────────────
# 主处理流程
# ─────────────────────────────────────────────
def process(input_path, output_path=None, config=None):
"""处理单个视频文件"""
cfg = {**DEFAULTS, **(config or {})}
input_path = Path(input_path).resolve()
if not input_path.exists():
log(f"文件不存在: {input_path}", "error")
return False
if output_path is None:
output_path = input_path.with_stem(input_path.stem + "_edited")
output_path = Path(output_path).resolve()
output_path.parent.mkdir(parents=True, exist_ok=True)
orig_dur = get_duration(input_path)
log(f"输入: {input_path.name} ({format_time(orig_dur)})")
print("=" * 55)
with tempfile.TemporaryDirectory(prefix="veditor_") as tmpdir:
current = str(input_path)
# ── 步骤 1/3: 音频分离 ──
print()
if cfg["audio_separation"]:
log("步骤 1/3: 音频分离", "step")
separated = step_audio_separate(current, tmpdir, cfg["separator_model"])
if separated:
merged = str(Path(tmpdir) / "merged.mp4")
if step_replace_audio(current, separated, merged):
current = merged
log("已替换音频轨道", "ok")
else:
log("步骤 1/3: 音频分离 (已跳过,使用 --separate-audio 启用)", "step")
# ── 步骤 2/3: 去除静音 ──
print()
log("步骤 2/3: 去除静音段", "step")
trimmed = str(Path(tmpdir) / "trimmed.mp4")
use_auto_editor = tool_available("auto-editor")
if use_auto_editor:
# dB → 百分比近似: pct = 10^(dB/20) * 100
threshold_pct = max(1, round(10 ** (cfg["silence_threshold_db"] / 20) * 100))
ok = step_remove_silence_auto_editor(
current, trimmed, threshold_pct, cfg["margin_sec"]
)
if not ok:
log("auto-editor 失败,回退到 FFmpeg", "warn")
ok = step_remove_silence_ffmpeg(
current, trimmed,
cfg["silence_threshold_db"], cfg["min_silence_sec"], cfg["margin_sec"],
)
else:
log("auto-editor 未安装,使用 FFmpeg 方案", "warn")
ok = step_remove_silence_ffmpeg(
current, trimmed,
cfg["silence_threshold_db"], cfg["min_silence_sec"], cfg["margin_sec"],
)
if not ok:
log("静音去除失败", "error")
return False
current = trimmed
# ── 截取前N秒(如指定 max_duration)──
trimmed_dur = get_duration(current)
max_dur = cfg.get("max_duration")
if max_dur and trimmed_dur > max_dur:
truncated = str(Path(tmpdir) / "truncated.mp4")
r = run(
[
"ffmpeg", "-i", current,
"-t", str(max_dur),
"-c", "copy",
"-y", truncated,
],
desc=f"截取前 {max_dur}s(原 {format_time(trimmed_dur)})",
)
if r.returncode == 0 and Path(truncated).exists():
current = truncated
trimmed_dur = get_duration(current)
log(f"截取完成,当前时长: {format_time(trimmed_dur)}", "ok")
# ── 自动倍速计算 ──
actual_speed = cfg["speed"]
if cfg.get("target_duration"):
target = cfg["target_duration"]
target_max = cfg.get("target_duration_max") or target
max_spd = cfg.get("max_speed", 3.0)
# 以目标中点计算倍速
target_mid = (target + target_max) / 2
calculated_speed = trimmed_dur / target_mid
calculated_speed = max(1.0, min(calculated_speed, max_spd))
actual_speed = round(calculated_speed, 2)
expected_dur = trimmed_dur / actual_speed
log(f"自动倍速: 裁剪后 {format_time(trimmed_dur)} ÷ 目标 {target:.0f}-{target_max:.0f}s "
f"→ {actual_speed}x (预计 {expected_dur:.1f}s)", "ok")
# ── 步骤 3/3: 后处理 + 导出 ──
print()
log("步骤 3/3: 后处理 + 导出", "step")
ok = step_post_process(
current, str(output_path),
speed=actual_speed,
loudness=cfg["loudness_lufs"],
megaphone=cfg["megaphone"],
fps=cfg["fps"],
codec=cfg["codec"],
crf=cfg["crf"],
preset=cfg["preset"],
)
if not ok:
log("后处理失败", "error")
return False
# ── 汇总 ──
final_dur = get_duration(output_path)
file_size_mb = output_path.stat().st_size / (1024 * 1024)
print()
print("=" * 55)
log("处理完成!", "ok")
log(f" 输入: {input_path.name} ({format_time(orig_dur)})")
log(f" 输出: {output_path.name} ({format_time(final_dur)})")
log(f" 压缩比: {orig_dur:.0f}s → {final_dur:.1f}s ({final_dur/orig_dur*100:.1f}%)")
log(f" 文件大小: {file_size_mb:.1f} MB")
log(f" 路径: {output_path}")
return True
def batch_process(input_dir, output_dir=None, config=None):
"""批量处理目录中的所有视频文件"""
input_dir = Path(input_dir).resolve()
if not input_dir.is_dir():
log(f"目录不存在: {input_dir}", "error")
return []
if output_dir is None:
output_dir = input_dir / "processed"
output_dir = Path(output_dir).resolve()
output_dir.mkdir(parents=True, exist_ok=True)
video_exts = {".mp4", ".mov", ".mkv", ".avi", ".wmv", ".flv", ".webm"}
videos = sorted(f for f in input_dir.iterdir() if f.suffix.lower() in video_exts)
if not videos:
log(f"目录中未找到视频文件: {input_dir}", "error")
return []
log(f"批量模式: 找到 {len(videos)} 个视频")
results = []
for i, vid in enumerate(videos, 1):
print(f"\n{'#' * 55}")
log(f"[{i}/{len(videos)}] {vid.name}")
print(f"{'#' * 55}")
out = output_dir / f"{vid.stem}_edited{vid.suffix}"
ok = process(vid, out, config)
results.append((vid.name, ok, str(out) if ok else None))
# 汇总
success = sum(1 for _, ok, _ in results if ok)
print(f"\n{'#' * 55}")
log(f"批量处理完成: {success}/{len(results)} 成功", "ok")
for name, ok, out_path in results:
status = "OK" if ok else "FAIL"
log(f" [{status}] {name}")
return results
# ─────────────────────────────────────────────
# CLI 入口
# ─────────────────────────────────────────────
def main():
parser = argparse.ArgumentParser(
description="小语种听写视频自动剪辑工具 v1.0",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
示例:
%(prog)s input.mp4 # 使用默认参数处理
%(prog)s input.mp4 -o output.mp4 # 指定输出路径
%(prog)s input.mp4 --target-duration 10-20 # 自动计算倍速命中目标时长
%(prog)s input.mp4 --speed 1.6 --no-megaphone
%(prog)s --batch ./videos # 批量处理
%(prog)s --batch ./videos --output-dir ./out --codec h264_nvenc # GPU加速
""",
)
# 输入/输出
parser.add_argument("input", nargs="?", help="输入视频文件路径")
parser.add_argument("-o", "--output", help="输出文件路径")
parser.add_argument("--batch", metavar="DIR", help="批量处理: 输入目录路径")
parser.add_argument("--output-dir", metavar="DIR", help="批量处理: 输出目录")
# 核心参数
g = parser.add_argument_group("核心参数")
g.add_argument("--speed", type=float, default=DEFAULTS["speed"],
help=f"播放倍速 (默认: {DEFAULTS['speed']},设置 --target-duration 时自动计算)")
g.add_argument("--target-duration", type=str, default=None, metavar="SEC",
help="目标时长,如 '15' 或 '10-20'(自动计算倍速)")
g.add_argument("--max-speed", type=float, default=DEFAULTS["max_speed"],
help=f"自动倍速上限 (默认: {DEFAULTS['max_speed']})")
g.add_argument("--max-duration", type=float, default=None, metavar="SEC",
help="裁剪后最大保留时长(秒),截取前N秒内容")
g.add_argument("--silence-db", type=int, default=DEFAULTS["silence_threshold_db"],
help=f"静音阈值 dB (默认: {DEFAULTS['silence_threshold_db']})")
g.add_argument("--min-silence", type=float, default=DEFAULTS["min_silence_sec"],
help=f"最短静音时长/秒 (默认: {DEFAULTS['min_silence_sec']})")
g.add_argument("--margin", type=float, default=DEFAULTS["margin_sec"],
help=f"裁剪边距/秒 (默认: {DEFAULTS['margin_sec']})")
# 音频
g2 = parser.add_argument_group("音频处理")
g2.add_argument("--loudness", type=int, default=DEFAULTS["loudness_lufs"],
help=f"目标响度 LUFS (默认: {DEFAULTS['loudness_lufs']})")
g2.add_argument("--no-megaphone", action="store_true", help="禁用扩音器音效")
g2.add_argument("--separate-audio", action="store_true",
help="启用音频分离 (需 audio-separator)")
g2.add_argument("--separator-model", default=DEFAULTS["separator_model"],
help=f"分离模型 (默认: {DEFAULTS['separator_model']})")
# 视频编码
g3 = parser.add_argument_group("视频编码")
g3.add_argument("--fps", type=int, default=DEFAULTS["fps"],
help=f"输出帧率 (默认: {DEFAULTS['fps']})")
g3.add_argument("--codec", default=DEFAULTS["codec"],
choices=["libx264", "libx265", "h264_nvenc", "hevc_nvenc", "h264_amf"],
help=f"编码器 (默认: {DEFAULTS['codec']})")
g3.add_argument("--crf", type=int, default=DEFAULTS["crf"],
help=f"质量 CRF 值, 越小越好 (默认: {DEFAULTS['crf']})")
g3.add_argument("--preset", default=DEFAULTS["preset"],
choices=["ultrafast", "fast", "medium", "slow", "veryslow"],
help=f"编码速度预设 (默认: {DEFAULTS['preset']})")
# 其他
parser.add_argument("--config", metavar="FILE", help="JSON 配置文件路径")
args = parser.parse_args()
# 标题
print("=" * 55)
print(" 小语种听写视频自动剪辑工具 v1.0")
print("=" * 55)
print()
# 检查 FFmpeg
if not tool_available("ffmpeg") or not tool_available("ffprobe"):
log("FFmpeg 未安装或不在 PATH 中!", "error")
log("下载: https://ffmpeg.org/download.html", "error")
sys.exit(1)
# 构建配置
cfg = dict(DEFAULTS)
if args.config:
try:
with open(args.config, encoding="utf-8") as f:
cfg.update(json.load(f))
log(f"已加载配置: {args.config}")
except Exception as e:
log(f"配置文件加载失败: {e}", "error")
sys.exit(1)
# 解析 --target-duration(支持 "15" 或 "10-20" 格式)
target_dur = None
target_dur_max = None
if args.target_duration:
if "-" in args.target_duration:
parts = args.target_duration.split("-")
target_dur = float(parts[0])
target_dur_max = float(parts[1])
else:
target_dur = float(args.target_duration)
target_dur_max = target_dur
cfg.update({
"speed": args.speed,
"target_duration": target_dur,
"target_duration_max": target_dur_max,
"max_speed": args.max_speed,
"max_duration": args.max_duration,
"silence_threshold_db": args.silence_db,
"min_silence_sec": args.min_silence,
"margin_sec": args.margin,
"fps": args.fps,
"loudness_lufs": args.loudness,
"megaphone": not args.no_megaphone,
"audio_separation": args.separate_audio,
"separator_model": args.separator_model,
"codec": args.codec,
"crf": args.crf,
"preset": args.preset,
})
# 工具状态
log("环境检查:")
log(f" FFmpeg: 已安装")
ae = tool_available("auto-editor")
log(f" auto-editor: {'已安装' if ae else '未安装 (将使用FFmpeg方案)'}")
sep = tool_available("audio-separator")
log(f" audio-separator: {'已安装' if sep else '未安装 (音频分离不可用)'}")
print()
# 当前参数
log("当前参数:")
speed_info = f"倍速: {cfg['speed']}x"
if cfg.get("target_duration"):
t = cfg["target_duration"]
tm = cfg.get("target_duration_max") or t
speed_info = f"目标时长: {t:.0f}-{tm:.0f}s (自动倍速, 上限{cfg.get('max_speed', 3.0)}x)"
log(f" {speed_info} | 静音阈值: {cfg['silence_threshold_db']}dB | "
f"边距: {cfg['margin_sec']}s")
log(f" 响度: {cfg['loudness_lufs']}LUFS | 扩音器: {'开' if cfg['megaphone'] else '关'} | "
f"FPS: {cfg['fps']}")
log(f" 编码: {cfg['codec']} / CRF={cfg['crf']} / {cfg['preset']}")
log(f" 音频分离: {'开' if cfg['audio_separation'] else '关'}")
print()
# 执行
if args.batch:
batch_process(args.batch, args.output_dir, cfg)
elif args.input:
ok = process(args.input, args.output, cfg)
sys.exit(0 if ok else 1)
else:
parser.print_help()
sys.exit(1)
if __name__ == "__main__":
main()