os.makedirs(self.merge_folder, exist_ok=True)
print_step("Initializing Video Concatenator")
print_substep(f"Mode: {self.mode}", True)
print_substep(f"Monitoring: {self.source_folder}", True)
print_substep(f"Target duration: {self.target_duration} seconds", True)
if self.mode == "specific":
print_substep(f"Specific subreddits: {self.specific_subreddit}", True)
def load_config(self):
try:
with open("config.toml", "r", encoding="utf-8") as f:
config = tomlkit.load(f)
print_substep("Configuration loaded successfully", True)
return config
except FileNotFoundError:
print_substep("Error: config.toml not found!", False)
exit(1)
def load_processed_videos(self):
try:
if os.path.exists('processed_videos.json'):
with open('processed_videos.json', 'r') as f:
return json.load(f)
return []
except Exception:
return []
def save_processed_videos(self):
try:
with open('processed_videos.json', 'w') as f:
json.dump(self.processed_videos, f)
except Exception as e:
print_substep(f"Error saving processed videos: {str(e)}", False)
def check_status(self):
self.config = self.load_config()
status = self.config['merger']['status']
if status == "paused":
print_step("⏸️ Processing Paused")
with Progress(
SpinnerColumn(),
TextColumn("[yellow]Waiting for resume signal..."),
refresh_per_second=4
) as progress:
task = progress.add_task("", total=None)
while self.config['merger']['status'] == "paused":
progress.update(task)
time.sleep(1)
self.config = self.load_config()
print_step("▶️ Processing Resumed")
return True
elif status == "stopping":
print_step("🛑 Stop Signal Received")
return False
return True
def get_video_duration(self, video_path):
try:
clip = VideoFileClip(video_path, audio=False) # Load without audio for faster duration check
duration = clip.duration
clip.close()
print_substep(f"Duration for {os.path.basename(video_path)}: {duration:.2f}s", True)
return duration
except Exception as e:
print_substep(f"Error getting duration for {os.path.basename(video_path)}: {str(e)}", False)
return 0
def find_videos(self):
videos = []
total_duration = 0
print_step("🔍 Scanning for Videos")
if self.mode == "specific":
subreddits = self.specific_subreddit.split("+")
else:
subreddits = os.listdir(self.source_folder)
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
BarColumn(),
TextColumn("[progress.percentage]{task.percentage:>3.0f}%"),
TimeElapsedColumn(),
) as progress:
scan_task = progress.add_task("Scanning subreddits...", total=len(subreddits))
for subreddit in subreddits:
progress.update(scan_task, description=f"Scanning r/{subreddit}")
subreddit_path = os.path.join(self.source_folder, subreddit)
if os.path.isdir(subreddit_path):
for file in os.listdir(subreddit_path):
if file.endswith('_out.mp4'):
video_path = os.path.join(subreddit_path, file)
# Skip if video has been processed before
if video_path in self.processed_videos:
print_substep(f"Skipping previously processed: {file}")
continue
duration = self.get_video_duration(video_path)
if duration > 0:
videos.append({
'path': video_path,
'name': file,
'subreddit': subreddit,
'duration': duration
})
total_duration += duration
progress.advance(scan_task)
print_step("📊 Scan Results")
print_substep(f"New videos found: {len(videos)}", True if videos else False)
print_substep(f"Total duration available: {total_duration:.2f}s", True if total_duration > 0 else False)
return videos
def select_videos(self, available_videos):
selected_videos = []
current_duration = 0
print_step("🎯 Selecting Videos")
if self.mode == "fastest":
available_videos.sort(key=lambda x: x['duration'], reverse=True)
print_substep("Sorted videos by duration (fastest mode)", True)
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
BarColumn(),
TextColumn("{task.completed}/{task.total} videos"),
) as progress:
selection_task = progress.add_task("Selecting videos...", total=len(available_videos))
for video in available_videos:
if current_duration + video['duration'] <= self.target_duration:
selected_videos.append(video)
current_duration += video['duration']
progress.update(selection_task, advance=1, description=f"Selected: {video['name']}")
else:
progress.update(selection_task, advance=1, description="Checking videos")
print_step("📝 Selection Results")
print_substep(f"Videos selected: {len(selected_videos)}", True if selected_videos else False)
print_substep(f"Total duration: {current_duration:.2f}s / {self.target_duration:.2f}s",
True if current_duration > 0 else False)
return selected_videos
def write_video_with_progress(self, clip, output_path):
total_frames = int(clip.duration * clip.fps)
frame_count = [0]
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
BarColumn(),
TextColumn("[progress.percentage]{task.percentage:>3.0f}%"),
TimeElapsedColumn(),
) as progress:
render_task = progress.add_task("Rendering video...", total=total_frames)
def progress_monitor():
while frame_count[0] < total_frames:
time.sleep(0.5)
if os.path.exists(output_path):
estimated_progress = min(frame_count[0] + 1, total_frames)
progress.update(render_task, completed=estimated_progress)
frame_count[0] += 1
monitor_thread = threading.Thread(target=progress_monitor)
monitor_thread.daemon = True
monitor_thread.start()
clip.write_videofile(
output_path,
codec='libx264',
audio_codec='aac',
temp_audiofile='temp-audio.m4a',
remove_temp=True,
fps=30,
threads=2,
preset='ultrafast',
bitrate='2000k',
verbose=False,
logger=None,
write_logfile=False
)
frame_count[0] = total_frames
progress.update(render_task, completed=total_frames)
monitor_thread.join(timeout=1)
def concatenate_videos(self, selected_videos):
if not selected_videos:
print_substep("No videos selected for concatenation", False)
return None
clips = []
try:
print_step("🎬 Starting Video Concatenation")
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
BarColumn(),
TextColumn("{task.completed}/{task.total}"),
) as progress:
load_task = progress.add_task("Loading videos...", total=len(selected_videos))
for video in selected_videos:
progress.update(load_task, description=f"Loading: {video['name']}")
try:
clip = VideoFileClip(
video['path'],
target_resolution=(720, 1280),
verbose=False
).set_fps(30) # Force consistent FPS
if clip.duration > 0:
clips.append(clip)
progress.advance(load_task)
else:
print_substep(f"Skipping invalid clip: {video['name']}", False)
except Exception as e:
print_substep(f"Error loading {video['name']}: {str(e)}", False)
continue
if not clips:
print_substep("No valid clips to concatenate", False)
return None
print_substep("All videos loaded successfully", True)
output_filename = f"compilation_{time.strftime('%Y%m%d_%H%M%S')}.mp4"
output_path = os.path.join(self.merge_folder, output_filename)
print_step("💾 Creating Final Video")
# Mark videos as processed before rendering
for video in selected_videos:
self.processed_videos.append(video['path'])
self.save_processed_videos()
try:
# Try chain method first
final_clip = concatenate_videoclips(clips, method='chain')
except Exception as e:
print_substep("First concatenation method failed, trying alternative...", False)
try:
# If chain fails, try compose
final_clip = concatenate_videoclips(clips, method='compose')
except Exception as e:
raise Exception(f"Both concatenation methods failed: {str(e)}")
self.write_video_with_progress(final_clip, output_path)
print_substep(f"Compilation saved: {output_filename}", True)
return output_path
except Exception as e:
print_substep(f"Error during concatenation: {str(e)}", False)
return None
finally:
for clip in clips:
try:
clip.close()
except:
pass
def monitor_and_process(self):
print_step("🎥 Starting Video Monitor")
print_substep("Monitoring for new videos...")
while True:
try:
if not self.check_status():
break
available_videos = self.find_videos()
if available_videos:
selected_videos = self.select_videos(available_videos)
if selected_videos:
output_path = self.concatenate_videos(selected_videos)
if output_path:
print_step("✨ Compilation Complete")
print_substep(f"Created: {os.path.basename(output_path)}", True)
print_step(f"⏳ Waiting {self.check_interval} minutes")
with Progress(
SpinnerColumn(),
TextColumn("[yellow]Next check in..."),
TimeElapsedColumn(),
) as progress:
wait_task = progress.add_task("", total=None)
for _ in range(self.check_interval * 60):
progress.update(wait_task)
time.sleep(1)
except KeyboardInterrupt:
print_step("👋 Stopping Monitor")
break
except Exception as e:
print_step("❌ Error Occurred")
print_substep(f"Error: {str(e)}", False)
print_substep(f"Retrying in {self.check_interval} minutes", True)
time.sleep(self.check_interval * 60)