Repository navigation
Expand file tree
/
Copy pathcutter.py
More file actions
76 lines (60 loc) · 2.52 KB
/
Copy pathcutter.py
File metadata and controls
76 lines (60 loc) · 2.52 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
import os
import re
import subprocess
from logger import logger
def cut(video_path: str, segments: list[dict], output_dir: str) -> tuple[list[str], list[dict]]:
"""
按片段列表裁切视频,输出到指定目录。
返回:(输出文件路径列表, 有效片段列表)
"""
os.makedirs(output_dir, exist_ok=True)
output_paths = []
valid_segments = []
logger.debug(f"开始裁切视频:{video_path}")
logger.debug(f"输出目录:{output_dir}")
for i, seg in enumerate(segments, start=1):
if seg["end"] <= seg["start"]:
logger.warning(f" ⚠️ 跳过无效片段(时间为零):{seg.get('title', '')}")
continue
title = _safe_filename(seg["title"])
output_path = os.path.join(output_dir, f"{i:02d}_{title}.mp4")
_cut_segment(video_path, seg["start"], seg["end"], output_path)
output_paths.append(output_path)
valid_segments.append(seg)
duration = seg["end"] - seg["start"]
seg_type = seg.get("type", "未知类型")
logger.info(f" {i:02d}. [{seg_type}] {seg['title']} "
f"{_seconds_to_timestamp(seg['start'])} - {_seconds_to_timestamp(seg['end'])} "
f"({duration:.0f}秒)")
# 检查文件大小
if os.path.exists(output_path):
size = os.path.getsize(output_path)
logger.debug(f" 文件大小:{size / 1024 / 1024:.1f} MB")
logger.info(f"✅ 裁切完成,共 {len(output_paths)} 个文件")
return output_paths, valid_segments
def _cut_segment(video_path: str, start: float, end: float, output_path: str):
"""用 ffmpeg 裁切单个片段(无损复制流)。"""
cmd = [
"ffmpeg", "-y",
"-ss", str(start),
"-to", str(end),
"-i", video_path,
"-c", "copy",
output_path
]
logger.debug(f"执行 ffmpeg:{' '.join(cmd)}")
result = subprocess.run(cmd, check=True, capture_output=True)
if result.returncode != 0:
logger.error(f"ffmpeg 错误:{result.stderr.decode()}")
def _safe_filename(name: str) -> str:
"""将标题转换为安全的文件名。"""
name = re.sub(r'[\\/:*?"<>|]', "_", name)
name = name.strip().replace(" ", "_")
return name[:50] # 限制文件名长度
def _seconds_to_timestamp(seconds: float) -> str:
"""将秒数转换为 HH:MM:SS 格式。"""
seconds = int(seconds)
h = seconds // 3600
m = (seconds % 3600) // 60
s = seconds % 60
return f"{h:02d}:{m:02d}:{s:02d}"