Ytstock / app.py
Artificial-superintelligence's picture
Update app.py
6d42786 verified
raw
history blame
2.27 kB
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()