import gradio as gr import yt_dlp import os import tempfile import shutil from pathlib import Path import re import uuid import json from datetime import datetime import google.generativeai as genai class YouTubeDownloader: def __init__(self): self.download_dir = tempfile.mkdtemp() # Use temp directory for Gradio compatibility self.temp_downloads = tempfile.mkdtemp(prefix="youtube_downloads_") # Also create user downloads folder for copying self.downloads_folder = os.path.join(os.path.expanduser("~"), "Downloads", "YouTube_Downloads") os.makedirs(self.downloads_folder, exist_ok=True) self.gemini_model = None def configure_gemini(self, api_key): """Configure Gemini API with the provided key""" try: genai.configure(api_key=api_key) self.gemini_model = genai.GenerativeModel(model_name="gemini-1.5-flash-latest") return True, "✅ Gemini API configured successfully!" except Exception as e: return False, f"❌ Failed to configure Gemini API: {str(e)}" def cleanup(self): """Clean up temporary directories and files""" try: if hasattr(self, 'download_dir') and os.path.exists(self.download_dir): shutil.rmtree(self.download_dir) print(f"✅ Cleaned up temporary directory: {self.download_dir}") if hasattr(self, 'temp_downloads') and os.path.exists(self.temp_downloads): shutil.rmtree(self.temp_downloads) print(f"✅ Cleaned up temp downloads directory: {self.temp_downloads}") except Exception as e: print(f"⚠️ Warning: Could not clean up temporary directory: {e}") def is_valid_youtube_url(self, url): youtube_regex = re.compile( r'(https?://)?(www\.)?(youtube|youtu|youtube-nocookie)\.(com|be)/' r'(watch\?v=|embed/|v/|.+\?v=)?([^&=%\?]{11})' ) return youtube_regex.match(url) is not None def generate_scene_breakdown_gemini(self, video_info): """Generate AI-powered scene breakdown using Gemini""" if not self.gemini_model: return self.generate_scene_breakdown_fallback(video_info) try: duration = video_info.get('duration', 0) title = video_info.get('title', '') description = video_info.get('description', '')[:1500] # Increased limit for better context if not duration: return ["**[Duration Unknown]**: Unable to generate timestamped breakdown - video duration not available"] # Create enhanced prompt for Gemini prompt = f""" Analyze this YouTube video and create a highly detailed, scene-by-scene breakdown with precise timestamps and specific descriptions: Title: {title} Duration: {duration} seconds Description: {description} IMPORTANT INSTRUCTIONS: 1. Create detailed scene descriptions that include: - Physical appearance of people (age, gender, clothing, hair, etc.) - Exact actions being performed - Dialogue or speech (include actual lines if audible, or infer probable spoken lines based on actions and setting; format them as "Character: line...") - Setting and environment details - Props, objects, or products being shown - Visual effects, text overlays, or graphics - Mood, tone, and atmosphere - Camera movements or angles (if apparent) 2. Dialogue Emphasis: - Include short dialogue lines in **every scene** wherever plausible. - Write lines like: Character: "Actual or inferred line..." - If dialogue is not available, intelligently infer probable phrases (e.g., "Welcome!", "Try this now!", "It feels amazing!"). - Do NOT skip dialogue unless it’s clearly impossible. 3. Timestamp Guidelines: - For videos under 1 minute: 2-3 second segments - For videos 1-5 minutes: 3-5 second segments - For videos 5-15 minutes: 5-10 second segments - For videos over 15 minutes: 10-15 second segments - Maximum 20 scenes total for longer videos 4. Format each scene EXACTLY like this: **[MM:SS-MM:SS]**: Detailed description including who is visible, what they're wearing, what they're doing, what they're saying (if applicable), setting details, objects shown, and any visual elements. 5. Write descriptions as if you're watching the video in real-time, noting everything visible and audible. Based on the title and description, intelligently infer what would likely happen in each time segment. Consider the video type and create contextually appropriate, detailed descriptions. """ response = self.gemini_model.generate_content(prompt) # Parse the response into individual scenes if response and response.text: scenes = [] lines = response.text.split('\n') current_scene = "" for line in lines: line = line.strip() if line.strip().startswith("**[") and "]**:" in line: # This is a new scene timestamp line if current_scene: scenes.append(current_scene.strip()) current_scene = line.strip() elif current_scene: # This is continuation of the current scene description current_scene += "\n" + line.strip() # Add the last scene if exists if current_scene: scenes.append(current_scene.strip()) return scenes if scenes else self.generate_scene_breakdown_fallback(video_info) else: return self.generate_scene_breakdown_fallback(video_info) except Exception as e: print(f"Gemini API error: {e}") return self.generate_scene_breakdown_fallback(video_info) def generate_scene_breakdown_fallback(self, video_info): """Enhanced fallback scene generation when Gemini is not available""" duration = video_info.get('duration', 0) title = video_info.get('title', '').lower() description = video_info.get('description', '').lower() uploader = video_info.get('uploader', 'Content creator') if not duration: return ["**[Duration Unknown]**: Unable to generate timestamped breakdown"] # Determine segment length based on duration if duration <= 60: segment_length = 3 elif duration <= 300: segment_length = 5 elif duration <= 900: segment_length = 10 else: segment_length = 15 scenes = [] num_segments = min(duration // segment_length + 1, 20) # Detect video type for better descriptions video_type = self.detect_video_type_detailed(title, description) for i in range(num_segments): start_time = i * segment_length end_time = min(start_time + segment_length - 1, duration) start_formatted = f"{start_time//60}:{start_time%60:02d}" end_formatted = f"{end_time//60}:{end_time%60:02d}" # Generate contextual descriptions based on video type and timing desc = self.generate_contextual_description(i, num_segments, video_type, uploader, title) scenes.append(f"**[{start_formatted}-{end_formatted}]**: {desc}") return scenes def detect_video_type_detailed(self, title, description): """Detect video type with more detail for better fallback descriptions""" text = (title + " " + description).lower() if any(word in text for word in ['tutorial', 'how to', 'guide', 'learn', 'diy', 'step by step']): return 'tutorial' elif any(word in text for word in ['review', 'unboxing', 'test', 'comparison', 'vs']): return 'review' elif any(word in text for word in ['vlog', 'daily', 'routine', 'day in', 'morning', 'skincare']): return 'vlog' elif any(word in text for word in ['music', 'song', 'cover', 'lyrics', 'dance']): return 'music' elif any(word in text for word in ['comedy', 'funny', 'prank', 'challenge', 'reaction']): return 'entertainment' elif any(word in text for word in ['news', 'breaking', 'update', 'report']): return 'news' elif any(word in text for word in ['cooking', 'recipe', 'food', 'kitchen']): return 'cooking' elif any(word in text for word in ['workout', 'fitness', 'exercise', 'yoga']): return 'fitness' else: return 'general' def generate_contextual_description(self, scene_index, total_scenes, video_type, uploader, title): """Generate contextual descriptions based on video type and scene position""" # Common elements presenter_desc = f"The content creator" if 'woman' in title.lower() or 'girl' in title.lower(): presenter_desc = "A woman" elif 'man' in title.lower() or 'guy' in title.lower(): presenter_desc = "A man" # Position-based descriptions if scene_index == 0: # Opening scene if video_type == 'tutorial': return f"{presenter_desc} appears on screen, likely introducing themselves and the topic. They may be in a well-lit indoor setting, wearing casual clothing, and addressing the camera directly with a welcoming gesture." elif video_type == 'vlog': return f"{presenter_desc} greets the camera with a smile, possibly waving. They appear to be in their usual filming location, wearing their typical style, and beginning their introduction to today's content." elif video_type == 'review': return f"{presenter_desc} introduces the product or topic they'll be reviewing, likely holding or displaying the item. The setting appears organized, possibly with the product prominently featured." else: return f"{presenter_desc} appears on screen to begin the video, introducing the topic with engaging body language and clear speech directed at the audience." elif scene_index == total_scenes - 1: # Closing scene if video_type == 'tutorial': return f"{presenter_desc} concludes the tutorial, possibly showing the final result. They may be thanking viewers, asking for engagement (likes/comments), and suggesting related content." elif video_type == 'vlog': return f"{presenter_desc} wraps up their vlog, possibly reflecting on the day's events. They appear relaxed and are likely saying goodbye to viewers with a friendly gesture." else: return f"{presenter_desc} concludes the video with final thoughts, thanking viewers for watching, and encouraging engagement through likes, comments, and subscriptions." else: # Middle scenes - content-specific if video_type == 'tutorial': step_num = scene_index return f"{presenter_desc} demonstrates step {step_num} of the process, showing specific techniques and explaining the procedure. They may be using tools or materials, with close-up shots of their hands working." elif video_type == 'review': return f"{presenter_desc} examines different aspects of the product, pointing out features and sharing their opinions. They may be holding, using, or demonstrating the item while speaking to the camera." elif video_type == 'vlog': return f"{presenter_desc} continues sharing their experience, possibly showing different locations or activities. The scene captures candid moments with natural lighting and casual interactions." elif video_type == 'cooking': return f"{presenter_desc} works in the kitchen, preparing ingredients or cooking. They demonstrate techniques while explaining each step, with kitchen tools and ingredients visible on the counter." elif video_type == 'fitness': return f"{presenter_desc} demonstrates exercise movements, likely in workout attire in a gym or home setting. They show proper form while providing instruction and motivation." else: return f"{presenter_desc} continues with the main content, engaging with the audience through clear explanations and demonstrations. The setting remains consistent with good lighting and clear audio." def detect_video_type(self, title, description): """Detect video type based on title and description""" text = (title + " " + description).lower() if any(word in text for word in ['music', 'song', 'album', 'artist', 'band', 'lyrics']): return "🎵 Music Video" elif any(word in text for word in ['tutorial', 'how to', 'guide', 'learn', 'teaching']): return "📚 Tutorial/Educational" elif any(word in text for word in ['funny', 'comedy', 'entertainment', 'vlog', 'challenge']): return "🎭 Entertainment/Comedy" elif any(word in text for word in ['news', 'breaking', 'report', 'update']): return "📰 News/Information" elif any(word in text for word in ['review', 'unboxing', 'test', 'comparison']): return "⭐ Review/Unboxing" elif any(word in text for word in ['commercial', 'ad', 'brand', 'product']): return "📺 Commercial/Advertisement" else: return "🎬 General Content" def detect_background_music(self, video_info): """Detect background music style""" title = video_info.get('title', '').lower() description = video_info.get('description', '').lower() if any(word in title for word in ['music', 'song', 'soundtrack']): return "🎵 Original Music/Soundtrack - Primary audio content" elif any(word in title for word in ['commercial', 'ad', 'brand']): return "🎶 Upbeat Commercial Music - Designed to enhance brand appeal" elif any(word in title for word in ['tutorial', 'how to', 'guide']): return "🔇 Minimal/No Background Music - Focus on instruction" elif any(word in title for word in ['vlog', 'daily', 'life']): return "🎼 Ambient Background Music - Complementary to narration" else: return "🎵 Background Music - Complementing video mood and pacing" def detect_influencer_status(self, video_info): """Detect influencer status""" subscriber_count = video_info.get('channel_followers', 0) view_count = video_info.get('view_count', 0) if subscriber_count > 10000000: return "🌟 Mega Influencer (10M+ subscribers)" elif subscriber_count > 1000000: return "⭐ Major Influencer (1M+ subscribers)" elif subscriber_count > 100000: return "🎯 Mid-tier Influencer (100K+ subscribers)" elif subscriber_count > 10000: return "📈 Micro Influencer (10K+ subscribers)" elif view_count > 100000: return "🔥 Viral Content Creator" else: return "👤 Regular Content Creator" def format_number(self, num): if num is None or num == 0: return "0" if num >= 1_000_000_000: return f"{num/1_000_000_000:.1f}B" elif num >= 1_000_000: return f"{num/1_000_000:.1f}M" elif num >= 1_000: return f"{num/1_000:.1f}K" return str(num) def format_video_info(self, video_info): """Streamlined video information formatting""" if not video_info: return "❌ No video information available." # Basic information title = video_info.get("title", "Unknown") uploader = video_info.get("uploader", "Unknown") duration = video_info.get("duration", 0) duration_str = f"{duration//60}:{duration%60:02d}" if duration else "Unknown" view_count = video_info.get("view_count", 0) like_count = video_info.get("like_count", 0) comment_count = video_info.get("comment_count", 0) upload_date = video_info.get("upload_date", "Unknown") # Format upload date if len(upload_date) == 8: formatted_date = f"{upload_date[:4]}-{upload_date[4:6]}-{upload_date[6:8]}" else: formatted_date = upload_date # Generate enhanced analysis scene_descriptions = self.generate_scene_breakdown_gemini(video_info) video_type = self.detect_video_type(title, video_info.get('description', '')) background_music = self.detect_background_music(video_info) influencer_status = self.detect_influencer_status(video_info) # Calculate engagement metrics engagement_rate = (like_count / view_count) * 100 if view_count > 0 else 0 # Generate streamlined report report = f""" 🎬 YOUTUBE VIDEO ANALYSIS REPORT {'='*50} 📋 BASIC INFORMATION {'─'*25} 📹 **Title:** {title} 👤 **Uploader:** {uploader} 📅 **Upload Date:** {formatted_date} ⏱️ **Duration:** {duration_str} 🆔 **Video ID:** {video_info.get('id', 'Unknown')} 📊 PERFORMANCE METRICS {'─'*25} 👀 **Views:** {self.format_number(view_count)} ({view_count:,}) 👍 **Likes:** {self.format_number(like_count)} ({like_count:,}) 💬 **Comments:** {self.format_number(comment_count)} ({comment_count:,}) 📈 **Engagement Rate:** {engagement_rate:.2f}% 🎯 CONTENT ANALYSIS {'─'*25} 📂 **Video Type:** {video_type} 🎵 **Background Music:** {background_music} 👑 **Creator Status:** {influencer_status} 🎬 DETAILED SCENE BREAKDOWN {'─'*30} {chr(10).join(scene_descriptions)} 📝 DESCRIPTION PREVIEW {'─'*25} {video_info.get('description', 'No description available')[:500]} {'...(truncated)' if len(video_info.get('description', '')) > 500 else ''} {'='*50} 📊 **Analysis completed:** {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} 🤖 **AI Enhancement:** {'Gemini AI' if self.gemini_model else 'Standard Analysis'} """ return report.strip() def get_video_info(self, url, progress=gr.Progress(), cookiefile=None): """Extract video information""" if not url or not url.strip(): return None, "❌ Please enter a YouTube URL" if not self.is_valid_youtube_url(url): return None, "❌ Invalid YouTube URL format" try: progress(0.1, desc="Initializing YouTube extractor...") ydl_opts = { 'noplaylist': True, 'extract_flat': False, } if cookiefile and os.path.exists(cookiefile): ydl_opts['cookiefile'] = cookiefile progress(0.5, desc="Extracting video metadata...") with yt_dlp.YoutubeDL(ydl_opts) as ydl: info = ydl.extract_info(url, download=False) progress(1.0, desc="✅ Analysis complete!") return info, "✅ Video information extracted successfully" except Exception as e: return None, f"❌ Error: {str(e)}" def download_video(self, url, quality="best", audio_only=False, progress=gr.Progress(), cookiefile=None): """Download video with progress tracking""" if not url or not url.strip(): return None, "❌ Please enter a YouTube URL" if not self.is_valid_youtube_url(url): return None, "❌ Invalid YouTube URL format" try: progress(0.1, desc="Preparing download...") # Create unique filename timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") # Download to temp directory first (Gradio compatible) ydl_opts = { 'outtmpl': os.path.join(self.temp_downloads, f'%(title)s_{timestamp}.%(ext)s'), 'noplaylist': True, } if audio_only: ydl_opts['format'] = 'bestaudio/best' ydl_opts['postprocessors'] = [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '192', }] else: if quality == "best": ydl_opts['format'] = 'best[height<=1080]' elif quality == "720p": ydl_opts['format'] = 'best[height<=720]' elif quality == "480p": ydl_opts['format'] = 'best[height<=480]' else: ydl_opts['format'] = 'best' if cookiefile and os.path.exists(cookiefile): ydl_opts['cookiefile'] = cookiefile # Progress hook def progress_hook(d): if d['status'] == 'downloading': if 'total_bytes' in d: percent = (d['downloaded_bytes'] / d['total_bytes']) * 100 progress(0.1 + (percent / 100) * 0.7, desc=f"Downloading... {percent:.1f}%") else: progress(0.5, desc="Downloading...") elif d['status'] == 'finished': progress(0.8, desc="Processing download...") ydl_opts['progress_hooks'] = [progress_hook] with yt_dlp.YoutubeDL(ydl_opts) as ydl: info = ydl.extract_info(url, download=True) progress(0.9, desc="Copying to Downloads folder...") # Find the downloaded file in temp directory downloaded_file_temp = None for file in os.listdir(self.temp_downloads): if timestamp in file: downloaded_file_temp = os.path.join(self.temp_downloads, file) break if not downloaded_file_temp: return None, "❌ Downloaded file not found in temp directory" # Copy to user's Downloads folder final_filename = os.path.basename(downloaded_file_temp) final_path = os.path.join(self.downloads_folder, final_filename) try: shutil.copy2(downloaded_file_temp, final_path) copy_success = True except Exception as e: print(f"Warning: Could not copy to Downloads folder: {e}") copy_success = False final_path = "File downloaded to temp location only" progress(1.0, desc="✅ Download complete!") success_msg = f"""✅ Download successful! 📁 Temp file (for download): {os.path.basename(downloaded_file_temp)} 📁 Permanent location: {final_path if copy_success else 'Copy failed'} 🎯 File size: {os.path.getsize(downloaded_file_temp) / (1024*1024):.1f} MB""" return downloaded_file_temp, success_msg except Exception as e: return None, f"❌ Download failed: {str(e)}" # Initialize global downloader downloader = YouTubeDownloader() def configure_api_key(api_key): """Configure Gemini API key""" if not api_key or not api_key.strip(): return "❌ Please enter a valid Google API key", gr.update(visible=False) success, message = downloader.configure_gemini(api_key.strip()) if success: return message, gr.update(visible=True) else: return message, gr.update(visible=False) def analyze_with_cookies(url, cookies_file, progress=gr.Progress()): """Main analysis function""" try: progress(0.05, desc="Starting analysis...") cookiefile = None if cookies_file and os.path.exists(cookies_file): cookiefile = cookies_file info, msg = downloader.get_video_info(url, progress=progress, cookiefile=cookiefile) if info: progress(0.95, desc="Generating comprehensive report...") formatted_info = downloader.format_video_info(info) progress(1.0, desc="✅ Complete!") return formatted_info else: return f"❌ Analysis Failed: {msg}" except Exception as e: return f"❌ System Error: {str(e)}" def download_with_cookies(url, quality, audio_only, cookies_file, progress=gr.Progress()): """Main download function""" try: progress(0.05, desc="Preparing download...") cookiefile = None if cookies_file and os.path.exists(cookies_file): cookiefile = cookies_file file_path, msg = downloader.download_video(url, quality, audio_only, progress=progress, cookiefile=cookiefile) if file_path: return file_path, msg else: return None, msg except Exception as e: return None, f"❌ System Error: {str(e)}" def create_interface(): """Create and configure the Gradio interface""" with gr.Blocks(theme=gr.themes.Soft(), title="🎥 YouTube Video Analyzer & Downloader Pro") as interface: gr.HTML("
✨ Benefits of using Gemini API: