-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbounce.py
More file actions
289 lines (246 loc) · 10.5 KB
/
Copy pathbounce.py
File metadata and controls
289 lines (246 loc) · 10.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
#!/usr/bin/env python3
"""
Bounce - Beat-Synchronized Music Video Creator
Main CLI that orchestrates all steps to create a music video.
"""
import sys
import os
import subprocess
import tempfile
import shutil
import threading
import time
from pathlib import Path
class Spinner:
"""A simple spinner to show progress during long operations."""
def __init__(self, message="Processing"):
self.message = message
self.running = False
self.thread = None
self.frames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]
self.frame_index = 0
def _spin(self):
"""Run the spinner animation."""
while self.running:
frame = self.frames[self.frame_index % len(self.frames)]
sys.stderr.write(f"\r{frame} {self.message}")
sys.stderr.flush()
self.frame_index += 1
time.sleep(0.1)
def start(self):
"""Start the spinner."""
if not sys.stderr.isatty():
# Don't show spinner if not in a terminal
return
self.running = True
self.thread = threading.Thread(target=self._spin)
self.thread.daemon = True
self.thread.start()
def stop(self):
"""Stop the spinner and clear the line."""
if not self.running:
return
self.running = False
if self.thread:
self.thread.join()
sys.stderr.write("\r" + " " * (len(self.message) + 3) + "\r")
sys.stderr.flush()
def run_step(step_name, command, description):
"""
Run a processing step and handle errors.
Args:
step_name: Name of the step for display
command: Command to run (list of arguments)
description: Description of what the step does
"""
print(f"\n{'='*70}")
print(f"Step: {step_name}")
print(f"{'='*70}")
print(f"{description}\n")
# Start spinner while subprocess runs
spinner = Spinner(f"{step_name}...")
spinner.start()
result = subprocess.run(command, capture_output=True, text=True)
spinner.stop()
# Print output
if result.stdout:
print(result.stdout)
if result.returncode != 0:
print(f"\n❌ Error in {step_name}")
if result.stderr:
print(result.stderr)
raise RuntimeError(f"{step_name} failed with exit code {result.returncode}")
return result
def main():
"""Main CLI entry point."""
if len(sys.argv) < 3:
print("Bounce - Beat-Synchronized Music Video Creator")
print("=" * 70)
print("\nUsage: python bounce.py <audio_file> <video_file> [output_file] [options]")
print("\nArguments:")
print(" audio_file - MP3 audio file (the music)")
print(" video_file - MP4 video file (the footage)")
print(" output_file - Output video file (default: output.mp4)")
print("\nOptions:")
print(" --scene-threshold=N - Scene detection sensitivity 0.0-1.0 (default: 0.3)")
print(" Lower = more sensitive, detects more scenes")
print(" --beats-per-measure=N - Beats per measure (default: 4 for 4/4 time)")
print(" --max-scene-measures=N - Maximum scene length in measures (default: no limit)")
print(" Long scenes will be split into chunks")
print(" --skip-boring=N - Skip boring segments (upper half static for N seconds)")
print(" Useful for motorcycle videos, removes straight-line sections")
print("\nExamples:")
print(" python bounce.py song.mp3 video.mp4")
print(" python bounce.py song.mp3 video.mp4 result.mp4")
print(" python bounce.py song.mp3 video.mp4 result.mp4 --scene-threshold=0.2")
print(" python bounce.py song.mp3 video.mp4 result.mp4 --max-scene-measures=16")
print(" python bounce.py song.mp3 video.mp4 result.mp4 --skip-boring=10")
print("\nWhat it does:")
print(" 1. Detects beats in the audio")
print(" 2. Filters beats to measures (downbeats)")
print(" 3. Detects scene changes in the video")
print(" 4. Aligns scenes to measure timestamps")
print(" 5. Assembles final beat-synchronized video")
print("\n" + "=" * 70)
sys.exit(1)
# Parse arguments
audio_file = sys.argv[1]
video_file = sys.argv[2]
output_file = "output.mp4"
scene_threshold = 0.3
beats_per_measure = 4
max_scene_measures = None
skip_boring_seconds = None
# Parse optional arguments
for arg in sys.argv[3:]:
if arg.startswith("--scene-threshold="):
try:
scene_threshold = float(arg.split("=")[1])
except ValueError:
print("⚠ Warning: Invalid scene threshold, using default 0.3")
elif arg.startswith("--beats-per-measure="):
try:
beats_per_measure = int(arg.split("=")[1])
except ValueError:
print("⚠ Warning: Invalid beats per measure, using default 4")
elif arg.startswith("--max-scene-measures="):
try:
max_scene_measures = int(arg.split("=")[1])
except ValueError:
print("⚠ Warning: Invalid max scene measures, ignoring")
elif arg.startswith("--skip-boring="):
try:
skip_boring_seconds = float(arg.split("=")[1])
except ValueError:
print("⚠ Warning: Invalid skip boring seconds, ignoring")
elif not arg.startswith("--"):
output_file = arg
# Validate inputs
if not os.path.exists(audio_file):
print(f"❌ Error: Audio file not found: {audio_file}")
sys.exit(1)
if not os.path.exists(video_file):
print(f"❌ Error: Video file not found: {video_file}")
sys.exit(1)
print("\n" + "=" * 70)
print("🎬 Bounce - Beat-Synchronized Music Video Creator")
print("=" * 70)
print(f"\nInput audio: {audio_file}")
print(f"Input video: {video_file}")
print(f"Output file: {output_file}")
print(f"\nSettings:")
print(f" Scene threshold: {scene_threshold}")
print(f" Beats per measure: {beats_per_measure}")
if max_scene_measures:
print(f" Max scene measures: {max_scene_measures}")
else:
print(f" Max scene measures: no limit")
if skip_boring_seconds:
print(f" Skip boring segments: >{skip_boring_seconds}s static upper half")
else:
print(f" Skip boring segments: disabled")
# Create working directory for temporary files
work_dir = tempfile.mkdtemp(prefix="bounce_")
print(f"\nWorking directory: {work_dir}")
try:
# Define file paths
beats_file = os.path.join(work_dir, "beats.txt")
measures_file = os.path.join(work_dir, "measures.txt")
scenes_dir = os.path.join(work_dir, "scenes")
scene_plan_file = os.path.join(work_dir, "scene_plan.txt")
interesting_segments_file = None
# Step 0 (Optional): Detect boring segments
if skip_boring_seconds:
interesting_segments_file = os.path.join(work_dir, "interesting_segments.txt")
run_step(
"0. Boring Segment Detection",
["python3", "detect_boring_segments.py", video_file, str(skip_boring_seconds), "0.01"],
f"Detecting segments where upper half is static for >{skip_boring_seconds}s..."
)
# Move the output files to work_dir
if os.path.exists("interesting_segments.txt"):
shutil.move("interesting_segments.txt", interesting_segments_file)
if os.path.exists("boring_segments.txt"):
shutil.move("boring_segments.txt", os.path.join(work_dir, "boring_segments.txt"))
# Step 1: Detect beats
run_step(
"1. Beat Detection",
["python3", "detect_beats.py", audio_file, beats_file],
"Analyzing audio to detect beats..."
)
# Step 2: Filter to measures
run_step(
"2. Measure Filtering",
["python3", "filter_beats.py", beats_file, measures_file, str(beats_per_measure)],
f"Filtering beats to measures ({beats_per_measure}/4 time)..."
)
# Step 3: Detect scenes
run_step(
"3. Scene Detection",
["python3", "detect_scenes.py", video_file, scenes_dir, str(scene_threshold)],
"Detecting scene changes in video..."
)
# Step 4: Align scenes to measures
align_cmd = ["python3", "align_scenes.py", scenes_dir, measures_file, scene_plan_file]
if max_scene_measures:
align_cmd.append(str(max_scene_measures))
run_step(
"4. Scene Alignment",
align_cmd,
"Aligning scenes to measure timestamps..."
)
# Step 5: Assemble final video
run_step(
"5. Video Assembly",
["python3", "assemble_video.py", scenes_dir, scene_plan_file, audio_file, output_file],
"Assembling final beat-synchronized video..."
)
print("\n" + "=" * 70)
print("🎉 SUCCESS! Your beat-synchronized music video is ready!")
print("=" * 70)
print(f"\n📄 Output file: {output_file}")
# Show file size and duration
if os.path.exists(output_file):
size_mb = os.path.getsize(output_file) / (1024 * 1024)
print(f"📊 File size: {size_mb:.2f} MB")
# Get duration
cmd = ["ffprobe", "-v", "error", "-show_entries", "format=duration",
"-of", "default=noprint_wrappers=1:nokey=1", output_file]
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode == 0:
duration = float(result.stdout.strip())
print(f"⏱️ Duration: {duration:.2f} seconds")
print("\n" + "=" * 70)
except Exception as e:
print(f"\n❌ Error: {e}")
import traceback
traceback.print_exc()
sys.exit(1)
finally:
# Clean up working directory
if os.path.exists(work_dir):
print(f"\n🧹 Cleaning up temporary files...")
shutil.rmtree(work_dir)
print(f"✓ Removed {work_dir}")
if __name__ == "__main__":
main()