Spaces:
Sleeping
Sleeping
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() | |