|
import gradio as gr |
|
import yt_dlp |
|
import os |
|
import re |
|
from moviepy.video.io.VideoFileClip import VideoFileClip |
|
|
|
|
|
def sanitize_filename(title): |
|
|
|
return re.sub(r'[<>:"/\\|?*]', '_', title) |
|
|
|
|
|
def download_video(url): |
|
download_path = './downloads' |
|
if not os.path.exists(download_path): |
|
os.makedirs(download_path) |
|
|
|
ydl_opts = { |
|
'outtmpl': download_path + '/%(title)s.%(ext)s', |
|
'format': 'best', |
|
} |
|
|
|
try: |
|
with yt_dlp.YoutubeDL(ydl_opts) as ydl: |
|
info_dict = ydl.extract_info(url, download=True) |
|
title = info_dict.get('title', None) |
|
if title: |
|
sanitized_title = sanitize_filename(title) |
|
file_path = os.path.join(download_path, f"{sanitized_title}.mp4") |
|
return file_path if os.path.exists(file_path) else None |
|
return None |
|
except Exception as e: |
|
return str(e) |
|
|
|
|
|
def crop_video(input_path, start_time, end_time): |
|
output_path = input_path.replace('.mp4', '_cropped.mp4') |
|
try: |
|
with VideoFileClip(input_path) as video: |
|
cropped_video = video.subclip(start_time, end_time) |
|
cropped_video.write_videofile(output_path, codec='libx264') |
|
return output_path |
|
except Exception as e: |
|
return str(e) |
|
|
|
|
|
def gradio_interface(): |
|
with gr.Blocks() as demo: |
|
gr.Markdown("# YouTube Video Downloader and Cropper") |
|
gr.Markdown("Enter the YouTube URL to download and crop the video.") |
|
|
|
|
|
url_input = gr.Textbox(label="YouTube URL", placeholder="Enter YouTube video URL here...") |
|
|
|
|
|
start_time_input = gr.Number(label="Start Time (seconds)", value=0) |
|
end_time_input = gr.Number(label="End Time (seconds)", value=10) |
|
|
|
|
|
output_file = gr.File(label="Download Cropped Video") |
|
|
|
|
|
process_btn = gr.Button("Download and Crop Video") |
|
|
|
|
|
def process_video(url, start_time, end_time): |
|
video_path = download_video(url) |
|
if video_path: |
|
cropped_video_path = crop_video(video_path, start_time, end_time) |
|
return cropped_video_path |
|
return None |
|
|
|
process_btn.click(process_video, inputs=[url_input, start_time_input, end_time_input], outputs=output_file) |
|
|
|
return demo |
|
|
|
|
|
if __name__ == "__main__": |
|
gradio_interface().launch() |
|
|