|
import gradio as gr |
|
from pytube import YouTube |
|
import os |
|
import time |
|
import random |
|
|
|
def download_video(url, output_path='.'): |
|
max_retries = 5 |
|
retries = 0 |
|
backoff_factor = 1 |
|
|
|
while retries < max_retries: |
|
try: |
|
|
|
yt = YouTube(url, use_oauth=False, allow_oauth_cache=True, on_progress_callback=on_progress) |
|
|
|
|
|
video = yt.streams.get_highest_resolution() |
|
|
|
|
|
print(f"Downloading: {yt.title}") |
|
video.download(output_path=output_path) |
|
print(f"Download completed: {yt.title}") |
|
return f"Download completed: {yt.title}" |
|
|
|
except Exception as e: |
|
retries += 1 |
|
if retries == max_retries: |
|
return f"An error occurred after {max_retries} retries: {e}" |
|
else: |
|
delay = backoff_factor * (2 ** (retries - 1)) + random.uniform(0, 1) |
|
print(f"Retrying in {delay:.2f} seconds... (Attempt {retries}/{max_retries})") |
|
time.sleep(delay) |
|
|
|
def on_progress(stream, chunk, bytes_remaining): |
|
total_size = stream.filesize |
|
bytes_downloaded = total_size - bytes_remaining |
|
percentage_of_completion = bytes_downloaded / total_size * 100 |
|
print(f"Download progress: {percentage_of_completion:.2f}%") |
|
|
|
def validate_url(url): |
|
try: |
|
|
|
yt = YouTube(url) |
|
return True |
|
except Exception as e: |
|
return False |
|
|
|
def gradio_interface(url, output_directory): |
|
if not validate_url(url): |
|
return "Invalid YouTube URL" |
|
|
|
result = download_video(url, output_directory) |
|
return result |
|
|
|
|
|
iface = gr.Interface( |
|
fn=gradio_interface, |
|
inputs=[ |
|
gr.Textbox(label="Enter the YouTube video URL"), |
|
gr.Textbox(label="Enter the output directory (leave blank for current directory)") |
|
], |
|
outputs=gr.Textbox(label="Download Status"), |
|
title="YouTube Video Downloader", |
|
description="Enter a YouTube video URL and optionally specify an output directory to download the video." |
|
) |
|
|
|
|
|
iface.launch() |