import gradio as gr import cv2 import yt_dlp import os import numpy as np def download_video(url, download_path): """ Download a video from YouTube using yt-dlp. Parameters: url (str): The URL of the video to download. download_path (str): Directory to save the downloaded video. Returns: str: Path to the downloaded video """ # Create download directory if it doesn't exist os.makedirs(download_path, exist_ok=True) ydl_opts = { 'format': 'best', 'outtmpl': f'{download_path}/%(title)s.%(ext)s', 'noplaylist': True, 'quiet': False, } try: with yt_dlp.YoutubeDL(ydl_opts) as ydl: info_dict = ydl.extract_info(url, download=True) video_filename = ydl.prepare_filename(info_dict) return video_filename except Exception as e: raise gr.Error(f"Video download failed: {e}") def process_video(input_path, brightness_threshold=100, slow_factor=2): """ Process the input video with brightness analysis and slow motion. Parameters: input_path (str): Path to the input video brightness_threshold (int): Threshold for brightness classification slow_factor (int): Factor to slow down the video Returns: str: Path to the processed video """ # Ensure output directory exists output_dir = 'processed_videos' os.makedirs(output_dir, exist_ok=True) # Generate output filename output_path = os.path.join(output_dir, 'processed_video.mp4') # Open the input video video = cv2.VideoCapture(input_path) # Get video properties fps = int(video.get(cv2.CAP_PROP_FPS)) width = int(video.get(cv2.CAP_PROP_FRAME_WIDTH)) height = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT)) # Adjust FPS for slower playback new_fps = fps // slow_factor fourcc = cv2.VideoWriter_fourcc(*'mp4v') writer = cv2.VideoWriter(output_path, fourcc, new_fps, (width, height)) def calculate_brightness(frame): """Calculate the brightness of a frame using the V channel in HSV color space.""" hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) return np.mean(hsv[:, :, 2]) # Process each frame while True: ret, frame = video.read() if not ret: break # Calculate brightness and classify brightness = calculate_brightness(frame) if brightness > brightness_threshold: text = f"Morning: {brightness:.2f}%" text_color = (0, 255, 0) # Green for morning else: text = f"Night: {brightness:.2f}%" text_color = (255, 0, 0) # Red for night # Overlay text on the frame cv2.putText(frame, text, (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, text_color, 2) # Write the frame to the output video writer.write(frame) # Release resources video.release() writer.release() return output_path def process_youtube_video(youtube_url, brightness_threshold, slow_factor): """ Combine video download and processing with error handling. Parameters: youtube_url (str): YouTube video URL brightness_threshold (int): Threshold for brightness classification slow_factor (int): Factor to slow down the video Returns: str: Path to the processed video """ try: # Download video downloaded_video_path = download_video(youtube_url, 'downloads') # Process video processed_video_path = process_video( downloaded_video_path, brightness_threshold, slow_factor ) return processed_video_path except Exception as e: raise gr.Error(f"Error processing video: {e}") # Create Gradio Interface demo = gr.Interface( fn=process_youtube_video, inputs=[ gr.Textbox(label="YouTube Video URL"), gr.Slider(minimum=0, maximum=255, value=100, label="Brightness Threshold"), gr.Slider(minimum=1, maximum=10, value=2, step=1, label="Slow Motion Factor") ], outputs=gr.Video(label="Processed Video"), title="YouTube Video Brightness Analyzer", description="Upload a YouTube video link and analyze its brightness with slow-motion effect." ) # Launch the interface if __name__ == "__main__": demo.launch()