|
1 | 1 | #!/usr/bin/env python3 |
| 2 | +# -*- coding: utf-8 -*- |
2 | 3 | """ |
3 | 4 | Bilibili Video Downloader and Frame Extractor |
4 | | -下载B站视频并拆解成帧图片 |
| 5 | +Download Bilibili videos and extract frames |
5 | 6 | """ |
6 | 7 |
|
7 | 8 | import os |
8 | 9 | import sys |
9 | 10 | import subprocess |
10 | 11 | import argparse |
| 12 | +import shutil |
| 13 | + |
| 14 | +# Fix Windows console encoding |
| 15 | +if sys.platform == "win32": |
| 16 | + sys.stdout.reconfigure(encoding='utf-8', errors='replace') |
| 17 | + sys.stderr.reconfigure(encoding='utf-8', errors='replace') |
| 18 | + |
| 19 | + |
| 20 | +def find_yt_dlp(): |
| 21 | + """Find yt-dlp executable or module |
| 22 | +
|
| 23 | + Returns: |
| 24 | + list: Command to run yt-dlp, or None if not found |
| 25 | + """ |
| 26 | + # Try direct command first |
| 27 | + if shutil.which("yt-dlp"): |
| 28 | + return ["yt-dlp"] |
| 29 | + |
| 30 | + # Try as Python module |
| 31 | + try: |
| 32 | + result = subprocess.run( |
| 33 | + [sys.executable, "-m", "yt_dlp", "--version"], |
| 34 | + capture_output=True, |
| 35 | + timeout=10 |
| 36 | + ) |
| 37 | + if result.returncode == 0: |
| 38 | + return [sys.executable, "-m", "yt_dlp"] |
| 39 | + except Exception: |
| 40 | + pass |
| 41 | + |
| 42 | + return None |
| 43 | + |
| 44 | + |
| 45 | +def find_ffmpeg(): |
| 46 | + """Find ffmpeg executable |
| 47 | +
|
| 48 | + Returns: |
| 49 | + str: Path to ffmpeg, or None if not found |
| 50 | + """ |
| 51 | + if shutil.which("ffmpeg"): |
| 52 | + return "ffmpeg" |
| 53 | + |
| 54 | + # Common Windows paths |
| 55 | + common_paths = [ |
| 56 | + r"C:\ffmpeg\bin\ffmpeg.exe", |
| 57 | + r"C:\Program Files\ffmpeg\bin\ffmpeg.exe", |
| 58 | + r"C:\tools\ffmpeg\bin\ffmpeg.exe", |
| 59 | + ] |
| 60 | + for path in common_paths: |
| 61 | + if os.path.exists(path): |
| 62 | + return path |
| 63 | + |
| 64 | + return None |
11 | 65 |
|
12 | 66 |
|
13 | 67 | def download_video(url: str, output_path: str = "video.mp4") -> bool: |
14 | | - """下载B站视频 |
| 68 | + """Download Bilibili video |
15 | 69 |
|
16 | 70 | Args: |
17 | | - url: B站视频URL |
18 | | - output_path: 输出文件路径 |
| 71 | + url: Bilibili video URL |
| 72 | + output_path: Output file path |
19 | 73 |
|
20 | 74 | Returns: |
21 | | - 是否下载成功 |
| 75 | + Whether download succeeded |
22 | 76 | """ |
23 | | - print(f"[INFO] 正在下载视频: {url}") |
| 77 | + print(f"[INFO] Downloading video: {url}") |
24 | 78 |
|
25 | | - cmd = [ |
26 | | - "yt-dlp", |
| 79 | + yt_dlp_cmd = find_yt_dlp() |
| 80 | + if not yt_dlp_cmd: |
| 81 | + print("[ERROR] yt-dlp not found!") |
| 82 | + print(" Install with: pip install yt-dlp") |
| 83 | + print(f" Current Python: {sys.executable}") |
| 84 | + return False |
| 85 | + |
| 86 | + cmd = yt_dlp_cmd + [ |
27 | 87 | "-f", "bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best", |
28 | 88 | "-o", output_path, |
| 89 | + "--no-warnings", |
29 | 90 | url |
30 | 91 | ] |
31 | 92 |
|
32 | 93 | try: |
| 94 | + print(f"[INFO] Running: {' '.join(cmd[:3])}...") |
33 | 95 | result = subprocess.run(cmd, check=True) |
34 | | - print(f"[OK] 视频下载完成: {output_path}") |
| 96 | + print(f"[OK] Video downloaded: {output_path}") |
35 | 97 | return True |
36 | 98 | except subprocess.CalledProcessError as e: |
37 | | - print(f"[ERROR] 下载失败: {e}") |
| 99 | + print(f"[ERROR] Download failed: {e}") |
38 | 100 | return False |
39 | | - except FileNotFoundError: |
40 | | - print("[ERROR] yt-dlp 未安装,请运行: pip install yt-dlp") |
| 101 | + except Exception as e: |
| 102 | + print(f"[ERROR] Unexpected error: {e}") |
41 | 103 | return False |
42 | 104 |
|
43 | 105 |
|
44 | 106 | def extract_frames(video_path: str, output_dir: str = "./images", fps: float = 1.0) -> bool: |
45 | | - """从视频提取帧图片 |
| 107 | + """Extract frames from video |
46 | 108 |
|
47 | 109 | Args: |
48 | | - video_path: 视频文件路径 |
49 | | - output_dir: 输出目录 |
50 | | - fps: 每秒提取帧数,默认1帧/秒 |
| 110 | + video_path: Video file path |
| 111 | + output_dir: Output directory |
| 112 | + fps: Frames per second, default 1 |
51 | 113 |
|
52 | 114 | Returns: |
53 | | - 是否提取成功 |
| 115 | + Whether extraction succeeded |
54 | 116 | """ |
55 | | - print(f"[INFO] 正在提取帧图片 (fps={fps})") |
| 117 | + print(f"[INFO] Extracting frames (fps={fps})") |
| 118 | + |
| 119 | + ffmpeg_cmd = find_ffmpeg() |
| 120 | + if not ffmpeg_cmd: |
| 121 | + print("[ERROR] ffmpeg not found!") |
| 122 | + print(" Windows: choco install ffmpeg / scoop install ffmpeg") |
| 123 | + print(" macOS: brew install ffmpeg") |
| 124 | + print(" Linux: sudo apt install ffmpeg") |
| 125 | + return False |
56 | 126 |
|
57 | | - # 创建输出目录 |
| 127 | + # Create output directory |
58 | 128 | os.makedirs(output_dir, exist_ok=True) |
59 | 129 |
|
60 | 130 | output_pattern = os.path.join(output_dir, "frame_%04d.jpg") |
61 | 131 |
|
62 | 132 | cmd = [ |
63 | | - "ffmpeg", |
| 133 | + ffmpeg_cmd, |
64 | 134 | "-i", video_path, |
65 | 135 | "-vf", f"fps={fps}", |
66 | 136 | "-q:v", "2", |
| 137 | + "-y", # Overwrite existing files |
67 | 138 | output_pattern |
68 | 139 | ] |
69 | 140 |
|
70 | 141 | try: |
| 142 | + print(f"[INFO] Running ffmpeg...") |
71 | 143 | result = subprocess.run(cmd, check=True, capture_output=True) |
72 | 144 |
|
73 | | - # 统计生成的图片数量 |
| 145 | + # Count generated images |
74 | 146 | frame_count = len([f for f in os.listdir(output_dir) if f.startswith("frame_") and f.endswith(".jpg")]) |
75 | | - print(f"[OK] 帧提取完成: {frame_count} 张图片保存到 {output_dir}/") |
| 147 | + print(f"[OK] Frames extracted: {frame_count} images saved to {output_dir}/") |
76 | 148 | return True |
77 | 149 | except subprocess.CalledProcessError as e: |
78 | | - print(f"[ERROR] 帧提取失败: {e.stderr.decode() if e.stderr else e}") |
| 150 | + stderr = e.stderr.decode('utf-8', errors='replace') if e.stderr else str(e) |
| 151 | + print(f"[ERROR] Frame extraction failed: {stderr}") |
79 | 152 | return False |
80 | | - except FileNotFoundError: |
81 | | - print("[ERROR] ffmpeg 未安装,请安装 ffmpeg") |
| 153 | + except Exception as e: |
| 154 | + print(f"[ERROR] Unexpected error: {e}") |
82 | 155 | return False |
83 | 156 |
|
84 | 157 |
|
85 | 158 | def main(): |
86 | 159 | parser = argparse.ArgumentParser( |
87 | | - description="下载B站视频并拆解成帧图片", |
| 160 | + description="Download Bilibili video and extract frames", |
88 | 161 | formatter_class=argparse.RawDescriptionHelpFormatter, |
89 | 162 | epilog=""" |
90 | | -示例: |
| 163 | +Examples: |
91 | 164 | python prepare.py "https://www.bilibili.com/video/BV1xx411c7mD" |
92 | 165 | python prepare.py "https://www.bilibili.com/video/BV1xx411c7mD" --fps 0.5 |
93 | 166 | python prepare.py "https://www.bilibili.com/video/BV1xx411c7mD" -o ./output |
94 | 167 | """ |
95 | 168 | ) |
96 | 169 |
|
97 | | - parser.add_argument("url", help="B站视频URL") |
98 | | - parser.add_argument("-o", "--output", default=".", help="输出目录,默认当前目录") |
99 | | - parser.add_argument("--fps", type=float, default=1.0, help="每秒提取帧数,默认1") |
100 | | - parser.add_argument("--video-only", action="store_true", help="只下载视频,不提取帧") |
101 | | - parser.add_argument("--frames-only", action="store_true", help="只提取帧(需要已有video.mp4)") |
| 170 | + parser.add_argument("url", help="Bilibili video URL") |
| 171 | + parser.add_argument("-o", "--output", default=".", help="Output directory (default: current)") |
| 172 | + parser.add_argument("--fps", type=float, default=1.0, help="Frames per second (default: 1)") |
| 173 | + parser.add_argument("--video-only", action="store_true", help="Only download video, skip frame extraction") |
| 174 | + parser.add_argument("--frames-only", action="store_true", help="Only extract frames (requires existing video.mp4)") |
102 | 175 |
|
103 | 176 | args = parser.parse_args() |
104 | 177 |
|
105 | | - # 设置路径 |
| 178 | + # Set paths |
106 | 179 | output_dir = args.output |
107 | 180 | video_path = os.path.join(output_dir, "video.mp4") |
108 | 181 | images_dir = os.path.join(output_dir, "images") |
109 | 182 |
|
110 | | - # 创建输出目录 |
| 183 | + # Create output directory |
111 | 184 | os.makedirs(output_dir, exist_ok=True) |
112 | 185 |
|
113 | | - # 下载视频 |
| 186 | + print("=" * 50) |
| 187 | + print("Bilibili Video Analyzer - Prepare Script") |
| 188 | + print("=" * 50) |
| 189 | + print(f"URL: {args.url}") |
| 190 | + print(f"Output: {output_dir}") |
| 191 | + print(f"FPS: {args.fps}") |
| 192 | + print("=" * 50) |
| 193 | + |
| 194 | + # Download video |
114 | 195 | if not args.frames_only: |
115 | 196 | if not download_video(args.url, video_path): |
116 | 197 | sys.exit(1) |
117 | 198 |
|
118 | | - # 提取帧 |
| 199 | + # Extract frames |
119 | 200 | if not args.video_only: |
120 | 201 | if not os.path.exists(video_path): |
121 | | - print(f"[ERROR] 视频文件不存在: {video_path}") |
| 202 | + print(f"[ERROR] Video file not found: {video_path}") |
122 | 203 | sys.exit(1) |
123 | 204 |
|
124 | 205 | if not extract_frames(video_path, images_dir, args.fps): |
125 | 206 | sys.exit(1) |
126 | 207 |
|
127 | | - print("\n[OK] 完成!") |
128 | | - print(f" 视频: {video_path}") |
129 | | - print(f" 图片: {images_dir}/") |
| 208 | + print("") |
| 209 | + print("=" * 50) |
| 210 | + print("[OK] Done!") |
| 211 | + print(f" Video: {video_path}") |
| 212 | + print(f" Images: {images_dir}/") |
| 213 | + print("=" * 50) |
130 | 214 |
|
131 | 215 |
|
132 | 216 | if __name__ == "__main__": |
|
0 commit comments