File size: 2,311 Bytes
510ee15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import zipfile
import subprocess

# Function to install missing packages
def install_packages():
    try:
        import yt_dlp
        import moviepy
        import gradio
    except ImportError:
        subprocess.check_call(["python", "-m", "pip", "install", "yt-dlp==2024.8.6", "moviepy", "gradio"])

install_packages()

from moviepy.editor import VideoFileClip
import yt_dlp
import gradio as gr

def download_video(url, output_dir="downloads"):
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
    
    ydl_opts = {
        'format': 'bestvideo+bestaudio/best',
        'outtmpl': os.path.join(output_dir, 'video.mp4'),
        'noplaylist': True,
        'quiet': True
    }
    
    with yt_dlp.YoutubeDL(ydl_opts) as ydl:
        ydl.download([url])

def split_video(input_path, output_dir="segments", segment_length=60):
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
    
    clip = VideoFileClip(input_path)
    duration = int(clip.duration)
    segments = []
    
    for start in range(0, duration, segment_length):
        end = min(start + segment_length, duration)
        segment = clip.subclip(start, end)
        segment_filename = os.path.join(output_dir, f"segment_{start // segment_length + 1}.mp4")
        segment.write_videofile(segment_filename, codec="libx264")
        segments.append(segment_filename)
    
    return segments

def create_zip(files, zip_filename="video_segments.zip"):
    with zipfile.ZipFile(zip_filename, 'w') as zipf:
        for file in files:
            zipf.write(file, os.path.basename(file))
    return zip_filename

def process_video(url):
    download_video(url)
    
    input_path = "downloads/video.mp4"
    segments_dir = "segments"
    zip_filename = "video_segments.zip"
    
    segments = split_video(input_path, segments_dir)
    zip_file = create_zip(segments, zip_filename)
    
    return zip_file

# Gradio Interface
def gradio_interface(url):
    zip_file = process_video(url)
    return zip_file

interface = gr.Interface(
    fn=gradio_interface,
    inputs="text",
    outputs="file",
    title="YouTube Video Downloader and Splitter",
    description="Download a YouTube video at the highest quality, split it into 1-minute segments, and zip the segments."
)

interface.launch()