File size: 2,271 Bytes
5099e75 6d42786 5099e75 6d42786 5099e75 |
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 |
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:
# Create a YouTube object with a custom user-agent
yt = YouTube(url, use_oauth=False, allow_oauth_cache=True, on_progress_callback=on_progress)
# Get the highest resolution stream
video = yt.streams.get_highest_resolution()
# Download the video
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:
# Check if the URL is a valid YouTube video URL
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
# Create the Gradio interface
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."
)
# Launch the Gradio interface
iface.launch() |