File size: 4,409 Bytes
ae01c95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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()