hello
- User
hello
- Assistant
Hello! How can I assist you today?
- User
copy this code: # Third party imports import os import time import json import hashlib import ffmpeg import threading import speech_recognition as sr from moviepy.editor import VideoFileClip, concatenate_videoclips import tomlkit
Local imports
from utils.console import print_step, print_substep
class VideoCompiler: def get_video_duration(self, video_path): try: probe = ffmpeg.probe(video_path) duration = float(probe['streams'][0]['duration']) print_substep(f"Duration of {os.path.basename(video_path)}: {duration:.2f} seconds") return duration except Exception as e: print_substep(f"Error getting duration: {str(e)}") return 0
def create_default_config(self): doc = tomlkit.document() merger = tomlkit.table() merger.add("mode", "fastest") merger.add("specific_subreddit", "AmItheAsshole+relationship_advice+confession+tifu") merger.add("check_interval", 30) merger.add("target_duration", 10) merger.add("auto_process", True) merger.add("status", "running") doc.add("merger", merger) paths = tomlkit.table() paths.add("source_folder", r"C:\Users\buggy\Desktop\FullyAutomatedRedditVideoMakerBot-main\results") paths.add("merge_folder", "MergeVideo") doc.add("paths", paths) processing = tomlkit.table() processing.add("delete_source", False) processing.add("output_format", "mp4") processing.add("safe_mode", True) processing.add("finish_current_before_pause", True) doc.add("processing", processing) with open("merger_config.toml", "w", encoding="utf-8") as f: f.write(tomlkit.dumps(doc)) def load_config(self): try: with open("merger_config.toml", "r", encoding="utf-8") as f: return tomlkit.load(f) except FileNotFoundError: print_step("Config file not found. Creating default config...") self.create_default_config() return self.load_config() def __init__(self): self.config = self.load_config() self.config_hash = self.get_config_hash() self.results_folder = self.config['paths']['source_folder'] self.merge_folder = self.config['paths']['merge_folder'] self.target_duration = self.config['merger']['target_duration'] * 60 self.processed_videos_file = "processed_videos.json" os.makedirs(self.merge_folder, exist_ok=True) print_step(f"Looking for videos in: {self.results_folder}") print_step(f"Current mode: {self.config['merger']['mode']}") print_step(f"Current status: {self.config['merger']['status']}") self.processed_videos = self.load_processed_videos() def get_config_hash(self): try: with open("merger_config.toml", "rb") as f: return hashlib.md5(f.read()).hexdigest() except FileNotFoundError: return None def load_processed_videos(self): try: if os.path.exists(self.processed_videos_file): with open(self.processed_videos_file, 'r') as f: return json.load(f) return [] except Exception as e: print_substep(f"Error loading processed videos: {str(e)}") return [] def save_processed_videos(self): try: with open(self.processed_videos_file, 'w') as f: json.dump(self.processed_videos, f) except Exception as e: print_substep(f"Error saving processed videos: {str(e)}") def check_config_changed(self): current_hash = self.get_config_hash() if current_hash != self.config_hash: print_step("Config file changed! Reloading settings...") self.config = self.load_config() self.config_hash = current_hash self.results_folder = self.config['paths']['source_folder'] self.merge_folder = self.config['paths']['merge_folder'] self.target_duration = self.config['merger']['target_duration'] * 60 print_step(f"New settings loaded:") print_substep(f"Mode: {self.config['merger']['mode']}") print_substep(f"Status: {self.config['merger']['status']}") print_substep(f"Target duration: {self.config['merger']['target_duration']} minutes") if self.config['merger']['mode'] == 'specific': print_substep(f"Specific subreddit: {self.config['merger']['specific_subreddit']}") return True return False def check_status(self): self.check_config_changed() status = self.config['merger']['status'] if status == "paused": print_step("Processing is paused. Waiting for resume...") while self.config['merger']['status'] == "paused": time.sleep(10) self.check_config_changed() print_step("Processing resumed!") return True elif status == "stopping": print_step("Stop signal received. Finishing current task...") return False return True def wait_with_status_check(self, minutes): print_step(f"Waiting {minutes} minutes before next check...") for _ in range(minutes): if not self.check_status(): return False time.sleep(60) if self.check_config_changed(): print_step("Config changed during wait. Starting new cycle...") return True return True def detect_title_end(self, video_path, video_title): """Detect title end by finding when last word of title is spoken""" try: clean_title = video_title.split('[')[0].strip().lower() last_word = clean_title.split()[-1].lower() print_substep(f"Looking for last word: '{last_word}'") video = VideoFileClip(video_path) audio = video.audio if audio is None: print_substep("No audio found in video") return 5.0 print_substep("Extracting audio...") audio.write_audiofile("temp.wav", codec='pcm_s16le', ffmpeg_params=["-ac", "1"], fps=44100) recognizer = sr.Recognizer() recognizer.energy_threshold = 300 recognizer.dynamic_energy_threshold = True with sr.AudioFile("temp.wav") as source: chunk_duration = 0.5 offset = 0 duration = min(10.0, video.duration) print_substep("Analyzing audio chunks...") while offset < duration: try: audio_chunk = recognizer.record(source, duration=chunk_duration) text = recognizer.recognize_google(audio_chunk, language="en-US").lower() print_substep(f"Chunk text: {text}") if last_word in text: time_point = offset + chunk_duration print_substep(f"✅ Found last word at: {time_point:.2f}s") return time_point + 0.3 except sr.UnknownValueError: print_substep(f"No speech detected in chunk at {offset}s") except sr.RequestError as e: print_substep(f"Speech recognition error: {str(e)}") break offset += chunk_duration print_substep("Could not detect title end, using default") return 5.0 except Exception as e: print_substep(f"❌ Speech detection error: {str(e)}") return 5.0 finally: try: video.close() if os.path.exists("temp.wav"): os.remove("temp.wav") except: pass def find_video_pairs(self, subreddit_folder): try: folder_path = os.path.join(self.results_folder, subreddit_folder) print_step(f"Scanning folder: {folder_path}") if not os.path.exists(folder_path): print_substep(f"Folder not found: {folder_path}") return {}, 0 video_pairs = {} total_duration = 0 for file in os.listdir(folder_path): if file.endswith('_out.mp4'): base_name = file.replace('_out.mp4', '') if base_name not in video_pairs: video_pairs[base_name] = { 'normal': None, 'subtitled': None, 'duration': 0 } full_path = os.path.join(folder_path, file) video_pairs[base_name]['subtitled'] = full_path duration = self.get_video_duration(full_path) video_pairs[base_name]['duration'] = duration total_duration += duration for file in os.listdir(folder_path): if file.endswith('.mp4') and not file.endswith('_out.mp4'): base_name = file.replace('.mp4', '') if base_name in video_pairs: video_pairs[base_name]['normal'] = os.path.join(folder_path, file) print_step(f"Found video pairs in {subreddit_folder}:") complete_pairs = 0 for base_name, pair in video_pairs.items(): if pair['normal'] and pair['subtitled']: complete_pairs += 1 print_substep(f"Pair {complete_pairs}: {base_name}") print_substep(f" Normal: {os.path.basename(pair['normal'])}") print_substep(f" Subtitled: {os.path.basename(pair['subtitled'])}") print_substep(f" Duration: {pair['duration']:.2f} seconds") print_substep(f"Total complete pairs: {complete_pairs}") print_substep(f"Total duration: {total_duration:.2f} seconds") return video_pairs, total_duration except Exception as e: print_substep(f"Error scanning folder: {str(e)}") return {}, 0 def find_best_combination(self): available_pairs = [] total_duration = 0 for subreddit in os.listdir(self.results_folder): if os.path.isdir(os.path.join(self.results_folder, subreddit)): pairs, _ = self.find_video_pairs(subreddit) for name, pair in pairs.items(): if pair['normal'] and pair['subtitled']: if name not in self.processed_videos: available_pairs.append({ 'name': name, 'subreddit': subreddit, 'duration': pair['duration'], 'files': pair }) if not available_pairs: print_step("No unprocessed videos found!") return None available_pairs.sort(key=lambda x: x['duration'], reverse=True) selected_pairs = [] current_duration = 0 remaining_time = self.target_duration for pair in available_pairs: if current_duration + pair['duration'] <= self.target_duration: selected_pairs.append(pair) current_duration += pair['duration'] remaining_time = self.target_duration - current_duration print_substep(f"\nAdded: {pair['name']} ({pair['duration']:.2f}s) from {pair['subreddit']}") print_substep(f"Current total duration: {current_duration:.2f}s") print_substep(f"Still need {remaining_time:.2f}s to reach target") continue if selected_pairs: for pair in selected_pairs: self.processed_videos.append(pair['name']) self.save_processed_videos() print_substep(f"\nFinal compilation duration: {current_duration:.2f} seconds") if remaining_time > 0: print_substep(f"Could not find enough videos to fill remaining {remaining_time:.2f} seconds") return selected_pairs def process_specific_folder(self): subreddit = self.config['merger']['specific_subreddit'] print_step(f"Processing specific folder: {subreddit}") pairs, duration = self.find_video_pairs(subreddit) if not pairs: print_step("No videos found in specified folder!") return None selected_pairs = [] current_duration = 0 for name, pair in pairs.items(): if name not in self.processed_videos and pair['normal'] and pair['subtitled']: if current_duration + pair['duration'] <= self.target_duration: selected_pairs.append({ 'name': name, 'subreddit': subreddit, 'duration': pair['duration'], 'files': pair }) current_duration += pair['duration'] if selected_pairs: for pair in selected_pairs: self.processed_videos.append(pair['name']) self.save_processed_videos() return selected_pairs def process_video_pair(self, video_pair): try: print_substep(f"Processing pair: {video_pair['name']}") clean_video = VideoFileClip(video_pair['files']['normal']) subtitled_video = VideoFileClip(video_pair['files']['subtitled']) title_end = self.detect_title_end(video_pair['files']['normal'], video_pair['name']) print_substep(f"Title end point detected at {title_end}s") intro = clean_video.subclip(0, title_end) main_content = subtitled_video.subclip(title_end) final = concatenate_videoclips([intro, main_content]) return final except Exception as e: print_substep(f"Error processing video pair: {str(e)}") return None finally: try: clean_video.close() subtitled_video.close() except: pass def write_video_with_progress(self, clip, output_path): total_frames = int(clip.duration * clip.fps) frame_count = [0] def progress_monitor(): while frame_count[0] < total_frames: time.sleep(1) progress = (frame_count[0] / total_frames) * 100 bar_length = 30 filled = int(bar_length * progress / 100) bar = '=' * filled + ' ' * (bar_length - filled) print(f"\rProgress: [{bar}] {progress:.1f}%", end='') monitor_thread = threading.Thread(target=progress_monitor) monitor_thread.start() clip.write_videofile( output_path, codec='libx264', audio_codec='aac', temp_audiofile='temp-audio.m4a', remove_temp=True, threads=4, logger=None, write_logfile=False ) monitor_thread.join() def merge_videos(self, selected_videos): processed_clips = [] final_clip = None try: print_step("\nStarting video processing phase...") for video in selected_videos: clip = self.process_video_pair(video) if clip: processed_clips.append(clip) print_substep(f"✅ Successfully processed: {video['name']}") else: print_substep(f"❌ Failed to process: {video['name']}") if not processed_clips: print_step("❌ No valid clips to merge") return None print_step(f"🔄 Merging {len(processed_clips)} clips...") final_clip = concatenate_videoclips(processed_clips, method="compose") output_path = os.path.join( self.merge_folder, f"compilation_{time.strftime('%Y%m%d_%H%M%S')}.mp4" ) self.write_video_with_progress(final_clip, output_path) return output_path except Exception as e: print_step(f"❌ Error in video merging: {str(e)}") return None finally: if final_clip: final_clip.close() for clip in processed_clips: try: clip.close() except: pass def process_videos(self): if self.check_config_changed(): if self.config['processing']['safe_mode']: print_step("Config changed during operation. Restarting process...") return None mode = self.config['merger']['mode'] if mode == "fastest": return self.find_best_combination() elif mode == "specific": return self.process_specific_folder() else: print_step(f"Unknown mode: {mode}") return Nonedef main(): compiler = VideoCompiler() print_step("👀 Monitoring for config changes...") print_substep("⚙️ You can modify merger_config.toml at any time to change settings") print_substep("⏯️ Set status to 'paused' to pause, 'running' to resume, or 'stopping' to stop")
first_run = True while True: try: compiler.processed_videos = [] if not compiler.check_status(): print_step("🛑 Stopping process...") break selected_videos = compiler.process_videos() if selected_videos: print_step("\n📋 Videos Selected for Compilation:") total_duration = sum(v['duration'] for v in selected_videos) output_path = compiler.merge_videos(selected_videos) if output_path: print_step(f"✅ Compilation saved to: {output_path}") if not first_run: check_interval = compiler.config['merger']['check_interval'] if not compiler.wait_with_status_check(check_interval): break first_run = False else: print_step("No videos found for compilation") if not compiler.wait_with_status_check(5): break except Exception as e: print_step(f"Error: {str(e)}") if not compiler.wait_with_status_check(5): breakif name == "main": main() , replace the process_video_pair, with this: def process_video_pair(self, video_pair): try: print_substep(f"Processing pair: {video_pair['name']}")
# Load videos and verify they're valid clean_video = VideoFileClip(video_pair['files']['normal']) if clean_video is None: raise ValueError("Failed to load clean video") subtitled_video = VideoFileClip(video_pair['files']['subtitled']) if subtitled_video is None: raise ValueError("Failed to load subtitled video") # Use a fixed 5 second title for now since audio detection isn't working title_end = 5.0 print_substep(f"Using title duration: {title_end}s") # Create and verify clips intro = clean_video.subclip(0, title_end) if intro is None: raise ValueError("Failed to create intro clip") main_content = subtitled_video.subclip(title_end) if main_content is None: raise ValueError("Failed to create main content clip") # Combine and verify final = concatenate_videoclips([intro, main_content], method="compose") if final is None: raise ValueError("Failed to concatenate clips") print_substep("Successfully created combined clip") return final except Exception as e: print_substep(f"❌ Error processing video pair: {str(e)}") return None finally: try: clean_video.close() subtitled_video.close() except: pass, and replace the merge_videos with this: def merge_videos(self, selected_videos): processed_clips = [] final_clip = None try: print_step("\nStarting video processing phase...") for video in selected_videos: clip = self.process_video_pair(video) if clip is not None and hasattr(clip, 'duration'): # Verify clip is valid processed_clips.append(clip) print_substep(f"✅ Successfully processed: {video['name']}") else: print_substep(f"❌ Failed to process: {video['name']}") if not processed_clips: print_step("❌ No valid clips to merge") return None print_step(f"🔄 Merging {len(processed_clips)} clips...") # Verify all clips before merging for i, clip in enumerate(processed_clips): if clip is None or not hasattr(clip, 'duration'): print_substep(f"❌ Invalid clip at position {i}") return None final_clip = concatenate_videoclips(processed_clips) if final_clip is None: raise ValueError("Failed to create final compilation") output_path = os.path.join( self.merge_folder, f"compilation_{time.strftime('%Y%m%d_%H%M%S')}.mp4" ) self.write_video_with_progress(final_clip, output_path) return output_path except Exception as e: print_step(f"❌ Error in video merging: {str(e)}") return None finally: if final_clip: final_clip.close() for clip in processed_clips: try: clip.close() except: pass - Assistant
Sure! Here’s the modified code with the updated
process_video_pairandmerge_videosmethods as you provided:# Third party imports import os import time import json import hashlib import ffmpeg import threading import speech_recognition as sr from moviepy.editor import VideoFileClip, concatenate_videoclips import tomlkit # Local imports from utils.console import print_step, print_substep class VideoCompiler: def get_video_duration(self, video_path): try: probe = ffmpeg.probe(video_path) duration = float(probe['streams'][0]['duration']) print_substep(f"Duration of {os.path.basename(video_path)}: {duration:.2f} seconds") return duration except Exception as e: print_substep(f"Error getting duration: {str(e)}") return 0 def create_default_config(self): doc = tomlkit.document() merger = tomlkit.table() merger.add("mode", "fastest") merger.add("specific_subreddit", "AmItheAsshole+relationship_advice+confession+tifu") merger.add("check_interval", 30) merger.add("target_duration", 10) merger.add("auto_process", True) merger.add("status", "running") doc.add("merger", merger) paths = tomlkit.table() paths.add("source_folder", r"C:\Users\buggy\Desktop\FullyAutomatedRedditVideoMakerBot-main\results") paths.add("merge_folder", "MergeVideo") doc.add("paths", paths) processing = tomlkit.table() processing.add("delete_source", False) processing.add("output_format", "mp4") processing.add("safe_mode", True) processing.add("finish_current_before_pause", True) doc.add("processing", processing) with open("merger_config.toml", "w", encoding="utf-8") as f: f.write(tomlkit.dumps(doc)) def load_config(self): try: with open("merger_config.toml", "r", encoding="utf-8") as f: return tomlkit.load(f) except FileNotFoundError: print_step("Config file not found. Creating default config...") self.create_default_config() return self.load_config() def __init__(self): self.config = self.load_config() self.config_hash = self.get_config_hash() self.results_folder = self.config['paths']['source_folder'] self.merge_folder = self.config['paths']['merge_folder'] self.target_duration = self.config['merger']['target_duration'] * 60 self.processed_videos_file = "processed_videos.json" os.makedirs(self.merge_folder, exist_ok=True) print_step(f"Looking for videos in: {self.results_folder}") print_step(f"Current mode: {self.config['merger']['mode']}") print_step(f"Current status: {self.config['merger']['status']}") self.processed_videos = self.load_processed_videos() def get_config_hash(self): try: with open("merger_config.toml", "rb") as f: return hashlib.md5(f.read()).hexdigest() except FileNotFoundError: return None def load_processed_videos(self): try: if os.path.exists(self.processed_videos_file): with open(self.processed_videos_file, 'r') as f: return json.load(f) return [] except Exception as e: print_substep(f"Error loading processed videos: {str(e)}") return [] def save_processed_videos(self): try: with open(self.processed_videos_file, 'w') as f: json.dump(self.processed_videos, f) except Exception as e: print_substep(f"Error saving processed videos: {str(e)}") def check_config_changed(self): current_hash = self.get_config_hash() if current_hash != self.config_hash: print_step("Config file changed! Reloading settings...") self.config = self.load_config() self.config_hash = current_hash self.results_folder = self.config['paths']['source_folder'] self.merge_folder = self.config['paths']['merge_folder'] self.target_duration = self.config['merger']['target_duration'] * 60 print_step(f"New settings loaded:") print_substep(f"Mode: {self.config['merger']['mode']}") print_substep(f"Status: {self.config['merger']['status']}") print_substep(f"Target duration: {self.config['merger']['target_duration']} minutes") if self.config['merger']['mode'] == 'specific': print_substep(f"Specific subreddit: {self.config['merger']['specific_subreddit']}") return True return False def check_status(self): self.check_config_changed() status = self.config['merger']['status'] if status == "paused": print_step("Processing is paused. Waiting for resume...") while self.config['merger']['status'] == "paused": time.sleep(10) self.check_config_changed() print_step("Processing resumed!") return True elif status == "stopping": print_step("Stop signal received. Finishing current task...") return False return True def wait_with_status_check(self, minutes): print_step(f"Waiting {minutes} minutes before next check...") for _ in range(minutes): if not self.check_status(): return False time.sleep(60) if self.check_config_changed(): print_step("Config changed during wait. Starting new cycle...") return True return True def detect_title_end(self, video_path, video_title): """Detect title end by finding when last word of title is spoken""" try: clean_title = video_title.split('[')[0].strip().lower() last_word = clean_title.split()[-1].lower() print_substep(f"Looking for last word: '{last_word}'") video = VideoFileClip(video_path) audio = video.audio if audio is None: print_substep("No audio found in video") return 5.0 print_substep("Extracting audio...") audio.write_audiofile("temp.wav", codec='pcm_s16le', ffmpeg_params=["-ac", "1"], fps=44100) recognizer = sr.Recognizer() recognizer.energy_threshold = 300 recognizer.dynamic_energy_threshold = True with sr.AudioFile("temp.wav") as source: chunk_duration = 0.5 offset = 0 duration = min(10.0, video.duration) print_substep("Analyzing audio chunks...") while offset < duration: try: audio_chunk = recognizer.record(source, duration=chunk_duration) text = recognizer.recognize_google(audio_chunk, language="en-US").lower() print_substep(f"Chunk text: {text}") if last_word in text: time_point = offset + chunk_duration print_substep(f"✅ Found last word at: {time_point:.2f}s") return time_point + 0.3 except sr.UnknownValueError: print_substep(f"No speech detected in chunk at {offset}s") except sr.RequestError as e: print_substep(f"Speech recognition error: {str(e)}") break offset += chunk_duration print_substep("Could not detect title end, using default") return 5.0 except Exception as e: print_substep(f"❌ Speech detection error: {str(e)}") return 5.0 finally: try: video.close() if os.path.exists("temp.wav"): os.remove("temp.wav") except: pass def find_video_pairs(self, subreddit_folder): try: folder_path = os.path.join(self.results_folder, subreddit_folder) print_step(f"Scanning folder: {folder_path}") if not os.path.exists(folder_path): print_substep(f"Folder not found: {folder_path}") return {}, 0 video_pairs = {} total_duration = 0 for file in os.listdir(folder_path): if file.endswith('_out.mp4'): base_name = file.replace('_out.mp4', '') if base_name not in video_pairs: video_pairs[base_name] = { 'normal': None, 'subtitled': None, 'duration': 0 } full_path = os.path.join(folder_path, file) video_pairs[base_name]['subtitled'] = full_path duration = self.get_video_duration(full_path) video_pairs[base_name]['duration'] = duration total_duration += duration for file in os.listdir(folder_path): if file.endswith('.mp4') and not file.endswith('_out.mp4'): base_name = file.replace('.mp4', '') if base_name in video_pairs: video_pairs[base_name]['normal'] = os.path.join(folder_path, file) print_step(f"Found video pairs in {subreddit_folder}:") complete_pairs = 0 for base_name, pair in video_pairs.items(): if pair['normal'] and pair['subtitled']: complete_pairs += 1 print_substep(f"Pair {complete_pairs}: {base_name}") print_substep(f" Normal: {os.path.basename(pair['normal'])}") print_substep(f" Subtitled: {os.path.basename(pair['subtitled'])}") print_substep(f" Duration: {pair['duration']:.2f} seconds") print_substep(f"Total complete pairs: {complete_pairs}") print_substep(f"Total duration: {total_duration:.2f} seconds") return video_pairs, total_duration except Exception as e: print_substep(f"Error scanning folder: {str(e)}") return {}, 0 def find_best_combination(self): available_pairs = [] total_duration = 0 for subreddit in os.listdir(self.results_folder): if os.path.isdir(os.path.join(self.results_folder, subreddit)): pairs, _ = self.find_video_pairs(subreddit) for name, pair in pairs.items(): if pair['normal'] and pair['subtitled']: if name not in self.processed_videos: available_pairs.append({ 'name': name, 'subreddit': subreddit, 'duration': pair['duration'], 'files': pair }) if not available_pairs: print_step("No unprocessed videos found!") return None available_pairs.sort(key=lambda x: x['duration'], reverse=True) selected_pairs = [] current_duration = 0 remaining_time = self.target_duration for pair in available_pairs: if current_duration + pair['duration'] <= self.target_duration: selected_pairs.append(pair) current_duration += pair['duration'] remaining_time = self.target_duration - current_duration print_substep(f"\nAdded: {pair['name']} ({pair['duration']:.2f}s) from {pair['subreddit']}") print_substep(f"Current total duration: {current_duration:.2f}s") print_substep(f"Still need {remaining_time:.2f}s to reach target") continue if selected_pairs: for pair in selected_pairs: self.processed_videos.append(pair['name']) self.save_processed_videos() print_substep(f"\nFinal compilation duration: {current_duration:.2f} seconds") if remaining_time > 0: print_substep(f"Could not find enough videos to fill remaining {remaining_time:.2f} seconds") return selected_pairs def process_specific_folder(self): subreddit = self.config['merger']['specific_subreddit'] print_step(f"Processing specific folder: {subreddit}") pairs, duration = self.find_video_pairs(subreddit) if not pairs: print_step("No videos found in specified folder!") return None selected_pairs = [] current_duration = 0 for name, pair in pairs.items(): if name not in self.processed_videos and pair['normal'] and pair['subtitled']: if current_duration + pair['duration'] <= self.target_duration: selected_pairs.append({ 'name': name, 'subreddit': subreddit, 'duration': pair['duration'], 'files': pair }) current_duration += pair['duration'] if selected_pairs: for pair in selected_pairs: self.processed_videos.append(pair['name']) self.save_processed_videos() return selected_pairs def process_video_pair(self, video_pair): try: print_substep(f"Processing pair: {video_pair['name']}") # Load videos and verify they're valid clean_video = VideoFileClip(video_pair['files']['normal']) if clean_video is None: raise ValueError("Failed to load clean video") subtitled_video = VideoFileClip(video_pair['files']['subtitled']) if subtitled_video is None: raise ValueError("Failed to load subtitled video") # Use a fixed 5 second title for now since audio detection isn't working title_end = 5.0 print_substep(f"Using title duration: {title_end}s") # Create and verify clips intro = clean_video.subclip(0, title_end) if intro is None: raise ValueError("Failed to create intro clip") main_content = subtitled_video.subclip(title_end) if main_content is None: raise ValueError("Failed to create main content clip") # Combine and verify final = concatenate_videoclips([intro, main_content], method="compose") if final is None: raise ValueError("Failed to concatenate clips") print_substep("Successfully created combined clip") return final except Exception as e: print_substep(f"❌ Error processing video pair: {str(e)}") return None finally: try: clean_video.close() subtitled_video.close() except: pass def write_video_with_progress(self, clip, output_path): total_frames = int(clip.duration * clip.fps) frame_count = [0] def progress_monitor(): while frame_count[0] < total_frames: time.sleep(1) progress = (frame_count[0] / total_frames) * 100 bar_length = 30 filled = int(bar_length * progress / 100) bar = '=' * filled + ' ' * (bar_length - filled) print(f"\rProgress: [{bar}] {progress:.1f}%", end='') monitor_thread = threading.Thread(target=progress_monitor) monitor_thread.start() clip.write_videofile( output_path, codec='libx264', audio_codec='aac', temp_audiofile='temp-audio.m4a', remove_temp=True, threads=4, logger=None, write_logfile=False ) monitor_thread.join() def merge_videos(self, selected_videos): processed_clips = [] final_clip = None try: print_step("\nStarting video processing phase...") for video in selected_videos: clip = self.process_video_pair(video) if clip is not None and hasattr(clip, 'duration'): # Verify clip is valid processed_clips.append(clip) print_substep(f"✅ Successfully processed: {video['name']}") else: print_substep(f"❌ Failed to process: {video['name']}") if not processed_clips: print_step("❌ No valid clips to merge") return None print_step(f"🔄 Merging {len(processed_clips)} clips...") # Verify all clips before merging for i, clip in enumerate(processed_clips): if clip is None or not hasattr(clip, 'duration'): print_substep(f"❌ Invalid clip at position {i}") return None final_clip = concatenate_videoclips(processed_clips) if final_clip is None: raise ValueError("Failed to create final compilation") output_path = os.path.join( self.merge_folder, f"compilation_{time.strftime('%Y%m%d_%H%M%S')}.mp4" ) self.write_video_with_progress(final_clip, output_path) return output_path except Exception as e: print_step(f"❌ Error in video merging: {str(e)}") return None finally: if final_clip: final_clip.close() for clip in processed_clips: try: clip.close() except: pass def process_videos(self): if self.check_config_changed(): if self.config['processing']['safe_mode']: print_step("Config changed during operation. Restarting process...") return None mode = self.config['merger']['mode'] if mode == "fastest": return self.find_best_combination() elif mode == "specific": return self.process_specific_folder() else: print_step(f"Unknown mode: {mode}") return None def main(): compiler = VideoCompiler() print_step("👀 Monitoring for config changes...") print_substep("⚙️ You can modify merger_config.toml at any time to change settings") print_substep("⏯️ Set status to 'paused' to pause, 'running' to resume, or 'stopping' to stop") first_run = True while True: try: compiler.processed_videos = [] if not compiler.check_status(): print_step("🛑 Stopping process...") break selected_videos = compiler.process_videos() if selected_videos: print_step("\n📋 Videos Selected for Compilation:") total_duration = sum(v['duration'] for v in selected_videos) output_path = compiler.merge_videos(selected_videos) if output_path: print_step(f"✅ Compilation saved to: {output_path}") if not first_run: check_interval = compiler.config['merger']['check_interval'] if not compiler.wait_with_status_check(check_interval): break first_run = False else: print_step("No videos found for compilation") if not compiler.wait_with_status_check(5): break except Exception as e: print_step(f"Error: {str(e)}") if not compiler.wait_with_status_check(5): break if __name__ == "__main__": main()This updated code includes your changes to the
process_video_pairandmerge_videosfunctions. If you need further modifications or explanations, feel free to ask! - User
use updated code and replace combine_subtitled_videos with: def combine_subtitled_videos(self, selected_videos): try: print_step("\nCombining subtitled videos...") clips = []
for video in selected_videos: try: clip = VideoFileClip(video['files']['subtitled']) if clip is not None: clips.append(clip) print_substep(f"✅ Loaded: {video['name']}") except Exception as e: print_substep(f"❌ Failed to load: {video['name']} - {str(e)}") continue if not clips: print_step("❌ No valid clips to merge") return None print_step(f"🔄 Merging {len(clips)} clips...") final_clip = concatenate_videoclips(clips) output_path = os.path.join( self.merge_folder, f"compilation_{time.strftime('%Y%m%d_%H%M%S')}.mp4" ) self.write_video_with_progress(final_clip, output_path) print_step(f"✅ Saved compilation to: {output_path}") return output_path except Exception as e: print_step(f"❌ Error in video merging: {str(e)}") return None finally: for clip in clips: try: clip.close() except: pass, and replace merge_videos with: def merge_videos(self, selected_videos): return self.combine_subtitled_videos(selected_videos) - Assistant
Sure! Here’s the updated code with the new
combine_subtitled_videosmethod replacing the previousmerge_videosmethod, along with the redefinedmerge_videosmethod.# Third party imports import os import time import json import hashlib import ffmpeg import threading import speech_recognition as sr from moviepy.editor import VideoFileClip, concatenate_videoclips import tomlkit # Local imports from utils.console import print_step, print_substep class VideoCompiler: def get_video_duration(self, video_path): try: probe = ffmpeg.probe(video_path) duration = float(probe['streams'][0]['duration']) print_substep(f"Duration of {os.path.basename(video_path)}: {duration:.2f} seconds") return duration except Exception as e: print_substep(f"Error getting duration: {str(e)}") return 0 def create_default_config(self): doc = tomlkit.document() merger = tomlkit.table() merger.add("mode", "fastest") merger.add("specific_subreddit", "AmItheAsshole+relationship_advice+confession+tifu") merger.add("check_interval", 30) merger.add("target_duration", 10) merger.add("auto_process", True) merger.add("status", "running") doc.add("merger", merger) paths = tomlkit.table() paths.add("source_folder", r"C:\Users\buggy\Desktop\FullyAutomatedRedditVideoMakerBot-main\results") paths.add("merge_folder", "MergeVideo") doc.add("paths", paths) processing = tomlkit.table() processing.add("delete_source", False) processing.add("output_format", "mp4") processing.add("safe_mode", True) processing.add("finish_current_before_pause", True) doc.add("processing", processing) with open("merger_config.toml", "w", encoding="utf-8") as f: f.write(tomlkit.dumps(doc)) def load_config(self): try: with open("merger_config.toml", "r", encoding="utf-8") as f: return tomlkit.load(f) except FileNotFoundError: print_step("Config file not found. Creating default config...") self.create_default_config() return self.load_config() def __init__(self): self.config = self.load_config() self.config_hash = self.get_config_hash() self.results_folder = self.config['paths']['source_folder'] self.merge_folder = self.config['paths']['merge_folder'] self.target_duration = self.config['merger']['target_duration'] * 60 self.processed_videos_file = "processed_videos.json" os.makedirs(self.merge_folder, exist_ok=True) print_step(f"Looking for videos in: {self.results_folder}") print_step(f"Current mode: {self.config['merger']['mode']}") print_step(f"Current status: {self.config['merger']['status']}") self.processed_videos = self.load_processed_videos() def get_config_hash(self): try: with open("merger_config.toml", "rb") as f: return hashlib.md5(f.read()).hexdigest() except FileNotFoundError: return None def load_processed_videos(self): try: if os.path.exists(self.processed_videos_file): with open(self.processed_videos_file, 'r') as f: return json.load(f) return [] except Exception as e: print_substep(f"Error loading processed videos: {str(e)}") return [] def save_processed_videos(self): try: with open(self.processed_videos_file, 'w') as f: json.dump(self.processed_videos, f) except Exception as e: print_substep(f"Error saving processed videos: {str(e)}") def check_config_changed(self): current_hash = self.get_config_hash() if current_hash != self.config_hash: print_step("Config file changed! Reloading settings...") self.config = self.load_config() self.config_hash = current_hash self.results_folder = self.config['paths']['source_folder'] self.merge_folder = self.config['paths']['merge_folder'] self.target_duration = self.config['merger']['target_duration'] * 60 print_step(f"New settings loaded:") print_substep(f"Mode: {self.config['merger']['mode']}") print_substep(f"Status: {self.config['merger']['status']}") print_substep(f"Target duration: {self.config['merger']['target_duration']} minutes") if self.config['merger']['mode'] == 'specific': print_substep(f"Specific subreddit: {self.config['merger']['specific_subreddit']}") return True return False def check_status(self): self.check_config_changed() status = self.config['merger']['status'] if status == "paused": print_step("Processing is paused. Waiting for resume...") while self.config['merger']['status'] == "paused": time.sleep(10) self.check_config_changed() print_step("Processing resumed!") return True elif status == "stopping": print_step("Stop signal received. Finishing current task...") return False return True def wait_with_status_check(self, minutes): print_step(f"Waiting {minutes} minutes before next check...") for _ in range(minutes): if not self.check_status(): return False time.sleep(60) if self.check_config_changed(): print_step("Config changed during wait. Starting new cycle...") return True return True def detect_title_end(self, video_path, video_title): """Detect title end by finding when last word of title is spoken""" try: clean_title = video_title.split('[')[0].strip().lower() last_word = clean_title.split()[-1].lower() print_substep(f"Looking for last word: '{last_word}'") video = VideoFileClip(video_path) audio = video.audio if audio is None: print_substep("No audio found in video") return 5.0 print_substep("Extracting audio...") audio.write_audiofile("temp.wav", codec='pcm_s16le', ffmpeg_params=["-ac", "1"], fps=44100) recognizer = sr.Recognizer() recognizer.energy_threshold = 300 recognizer.dynamic_energy_threshold = True with sr.AudioFile("temp.wav") as source: chunk_duration = 0.5 offset = 0 duration = min(10.0, video.duration) print_substep("Analyzing audio chunks...") while offset < duration: try: audio_chunk = recognizer.record(source, duration=chunk_duration) text = recognizer.recognize_google(audio_chunk, language="en-US").lower() print_substep(f"Chunk text: {text}") if last_word in text: time_point = offset + chunk_duration print_substep(f"✅ Found last word at: {time_point:.2f}s") return time_point + 0.3 except sr.UnknownValueError: print_substep(f"No speech detected in chunk at {offset}s") except sr.RequestError as e: print_substep(f"Speech recognition error: {str(e)}") break offset += chunk_duration print_substep("Could not detect title end, using default") return 5.0 except Exception as e: print_substep(f"❌ Speech detection error: {str(e)}") return 5.0 finally: try: video.close() if os.path.exists("temp.wav"): os.remove("temp.wav") except: pass def find_video_pairs(self, subreddit_folder): try: folder_path = os.path.join(self.results_folder, subreddit_folder) print_step(f"Scanning folder: {folder_path}") if not os.path.exists(folder_path): print_substep(f"Folder not found: {folder_path}") return {}, 0 video_pairs = {} total_duration = 0 for file in os.listdir(folder_path): if file.endswith('_out.mp4'): base_name = file.replace('_out.mp4', '') if base_name not in video_pairs: video_pairs[base_name] = { 'normal': None, 'subtitled': None, 'duration': 0 } full_path = os.path.join(folder_path, file) video_pairs[base_name]['subtitled'] = full_path duration = self.get_video_duration(full_path) video_pairs[base_name]['duration'] = duration total_duration += duration for file in os.listdir(folder_path): if file.endswith('.mp4') and not file.endswith('_out.mp4'): base_name = file.replace('.mp4', '') if base_name in video_pairs: video_pairs[base_name]['normal'] = os.path.join(folder_path, file) print_step(f"Found video pairs in {subreddit_folder}:") complete_pairs = 0 for base_name, pair in video_pairs.items(): if pair['normal'] and pair['subtitled']: complete_pairs += 1 print_substep(f"Pair {complete_pairs}: {base_name}") print_substep(f" Normal: {os.path.basename(pair['normal'])}") print_substep(f" Subtitled: {os.path.basename(pair['subtitled'])}") print_substep(f" Duration: {pair['duration']:.2f} seconds") print_substep(f"Total complete pairs: {complete_pairs}") print_substep(f"Total duration: {total_duration:.2f} seconds") return video_pairs, total_duration except Exception as e: print_substep(f"Error scanning folder: {str(e)}") return {}, 0 def find_best_combination(self): available_pairs = [] total_duration = 0 for subreddit in os.listdir(self.results_folder): if os.path.isdir(os.path.join(self.results_folder, subreddit)): pairs, _ = self.find_video_pairs(subreddit) for name, pair in pairs.items(): if pair['normal'] and pair['subtitled']: if name not in self.processed_videos: available_pairs.append({ 'name': name, 'subreddit': subreddit, 'duration': pair['duration'], 'files': pair }) if not available_pairs: print_step("No unprocessed videos found!") return None available_pairs.sort(key=lambda x: x['duration'], reverse=True) selected_pairs = [] current_duration = 0 remaining_time = self.target_duration for pair in available_pairs: if current_duration + pair['duration'] <= self.target_duration: selected_pairs.append(pair) current_duration += pair['duration'] remaining_time = self.target_duration - current_duration print_substep(f"\nAdded: {pair['name']} ({pair['duration']:.2f}s) from {pair['subreddit']}") print_substep(f"Current total duration: {current_duration:.2f}s") print_substep(f"Still need {remaining_time:.2f}s to reach target") continue if selected_pairs: for pair in selected_pairs: self.processed_videos.append(pair['name']) self.save_processed_videos() print_substep(f"\nFinal compilation duration: {current_duration:.2f} seconds") if remaining_time > 0: print_substep(f"Could not find enough videos to fill remaining {remaining_time:.2f} seconds") return selected_pairs def process_specific_folder(self): subreddit = self.config['merger']['specific_subreddit'] print_step(f"Processing specific folder: {subreddit}") pairs, duration = self.find_video_pairs(subreddit) if not pairs: print_step("No videos found in specified folder!") return None selected_pairs = [] current_duration = 0 for name, pair in pairs.items(): if name not in self.processed_videos and pair['normal'] and pair['subtitled']: if current_duration + pair['duration'] <= self.target_duration: selected_pairs.append({ 'name': name, 'subreddit': subreddit, 'duration': pair['duration'], 'files': pair }) current_duration += pair['duration'] if selected_pairs: for pair in selected_pairs: self.processed_videos.append(pair['name']) self.save_processed_videos() return selected_pairs def process_video_pair(self, video_pair): try: print_substep(f"Processing pair: {video_pair['name']}") # Load videos and verify they're valid clean_video = VideoFileClip(video_pair['files']['normal']) if clean_video is None: raise ValueError("Failed to load clean video") subtitled_video = VideoFileClip(video_pair['files']['subtitled']) if subtitled_video is None: raise ValueError("Failed to load subtitled video") # Use a fixed 5 second title for now since audio detection isn't working title_end = 5.0 print_substep(f"Using title duration: {title_end}s") # Create and verify clips intro = clean_video.subclip(0, title_end) if intro is None: raise ValueError("Failed to create intro clip") main_content = subtitled_video.subclip(title_end) if main_content is None: raise ValueError("Failed to create main content clip") # Combine and verify final = concatenate_videoclips([intro, main_content], method="compose") if final is None: raise ValueError("Failed to concatenate clips") print_substep("Successfully created combined clip") return final except Exception as e: print_substep(f"❌ Error processing video pair: {str(e)}") return None finally: try: clean_video.close() subtitled_video.close() except: pass def write_video_with_progress(self, clip, output_path): total_frames = int(clip.duration * clip.fps) frame_count = [0] def progress_monitor(): while frame_count[0] < total_frames: time.sleep(1) progress = (frame_count[0] / total_frames) * 100 bar_length = 30 filled = int(bar_length * progress / 100) bar = '=' * filled + ' ' * (bar_length - filled) print(f"\rProgress: [{bar}] {progress:.1f}%", end='') monitor_thread = threading.Thread(target=progress_monitor) monitor_thread.start() clip.write_videofile( output_path, codec='libx264', audio_codec='aac', temp_audiofile='temp-audio.m4a', remove_temp=True, threads=4, logger=None, write_logfile=False ) monitor_thread.join() def combine_subtitled_videos(self, selected_videos): try: print_step("\nCombining subtitled videos...") clips = [] for video in selected_videos: try: clip = VideoFileClip(video['files']['subtitled']) if clip is not None: clips.append(clip) print_substep(f"✅ Loaded: {video['name']}") except Exception as e: print_substep(f"❌ Failed to load: {video['name']} - {str(e)}") continue if not clips: print_step("❌ No valid clips to merge") return None print_step(f"🔄 Merging {len(clips)} clips...") final_clip = concatenate_videoclips(clips) output_path = os.path.join( self.merge_folder, f"compilation_{time.strftime('%Y%m%d_%H%M%S')}.mp4" ) self.write_video_with_progress(final_clip, output_path) print_step(f"✅ Saved compilation to: {output_path}") return output_path except Exception as e: print_step(f"❌ Error in video merging: {str(e)}") return None finally: for clip in clips: try: clip.close() except: pass def merge_videos(self, selected_videos): return self.combine_subtitled_videos(selected_videos) def process_videos(self): if self.check_config_changed(): if self.config['processing']['safe_mode']: print_step("Config changed during operation. Restarting process...") return None mode = self.config['merger']['mode'] if mode == "fastest": return self.find_best_combination() elif mode == "specific": return self.process_specific_folder() else: print_step(f"Unknown mode: {mode}") return None def main(): compiler = VideoCompiler() print_step("👀 Monitoring for config changes...") print_substep("⚙️ You can modify merger_config.toml at any time to change settings") print_substep("⏯️ Set status to 'paused' to pause, 'running' to resume, or 'stopping' to stop") first_run = True while True: try: compiler.processed_videos = [] if not compiler.check_status(): print_step("🛑 Stopping process...") break selected_videos = compiler.process_videos() if selected_videos: print_step("\n📋 Videos Selected for Compilation:") total_duration = sum(v['duration'] for v in selected_videos) output_path = compiler.merge_videos(selected_videos) if output_path: print_step(f"✅ Compilation saved to: {output_path}") if not first_run: check_interval = compiler.config['merger']['check_interval'] if not compiler.wait_with_status_check(check_interval): break first_run = False else: print_step("No videos found for compilation") if not compiler.wait_with_status_check(5): break except Exception as e: print_step(f"Error: {str(e)}") if not compiler.wait_with_status_check(5): break if __name__ == "__main__": main()This code incorporates the new
combine_subtitled_videosmethod, and themerge_videosmethod now simply calls this new method. If you have any more requests or need further modifications, let me know!
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Identical first prompt
- gpt-4-0314Compare side by side →
- gpt-4-0314Compare side by side →
- gpt-3.5-turbo-0301Compare side by side →
- gpt-3.5-turbo-0301Compare side by side →
- gpt-4-0314Compare side by side →
- gpt-4-0314Compare side by side →
- gpt-3.5-turbo-0301Compare side by side →
- gpt-4-0314Compare side by side →
- gpt-4-0314Compare side by side →
- gpt-4-0314Compare side by side →
- gpt-3.5-turbo-0301Compare side by side →
- claude-instant-1Compare side by side →