Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from pytube import YouTube
|
3 |
+
import os
|
4 |
+
import time
|
5 |
+
import random
|
6 |
+
|
7 |
+
def download_video(url, output_path='.'):
|
8 |
+
max_retries = 5
|
9 |
+
retries = 0
|
10 |
+
backoff_factor = 1
|
11 |
+
|
12 |
+
while retries < max_retries:
|
13 |
+
try:
|
14 |
+
# Create a YouTube object with a custom user-agent
|
15 |
+
yt = YouTube(url, use_oauth=False, allow_oauth_cache=True, on_progress_callback=on_progress)
|
16 |
+
|
17 |
+
# Get the highest resolution stream
|
18 |
+
video = yt.streams.get_highest_resolution()
|
19 |
+
|
20 |
+
# Download the video
|
21 |
+
print(f"Downloading: {yt.title}")
|
22 |
+
video.download(output_path=output_path)
|
23 |
+
print(f"Download completed: {yt.title}")
|
24 |
+
return f"Download completed: {yt.title}"
|
25 |
+
|
26 |
+
except Exception as e:
|
27 |
+
retries += 1
|
28 |
+
if retries == max_retries:
|
29 |
+
return f"An error occurred after {max_retries} retries: {e}"
|
30 |
+
else:
|
31 |
+
delay = backoff_factor * (2 ** (retries - 1)) + random.uniform(0, 1)
|
32 |
+
print(f"Retrying in {delay:.2f} seconds... (Attempt {retries}/{max_retries})")
|
33 |
+
time.sleep(delay)
|
34 |
+
|
35 |
+
def on_progress(stream, chunk, bytes_remaining):
|
36 |
+
total_size = stream.filesize
|
37 |
+
bytes_downloaded = total_size - bytes_remaining
|
38 |
+
percentage_of_completion = bytes_downloaded / total_size * 100
|
39 |
+
print(f"Download progress: {percentage_of_completion:.2f}%")
|
40 |
+
|
41 |
+
def validate_url(url):
|
42 |
+
try:
|
43 |
+
# Check if the URL is a valid YouTube video URL
|
44 |
+
yt = YouTube(url)
|
45 |
+
return True
|
46 |
+
except Exception as e:
|
47 |
+
return False
|
48 |
+
|
49 |
+
def gradio_interface(url, output_directory):
|
50 |
+
if not validate_url(url):
|
51 |
+
return "Invalid YouTube URL"
|
52 |
+
|
53 |
+
result = download_video(url, output_directory)
|
54 |
+
return result
|
55 |
+
|
56 |
+
# Create the Gradio interface
|
57 |
+
iface = gr.Interface(
|
58 |
+
fn=gradio_interface,
|
59 |
+
inputs=[
|
60 |
+
gr.inputs.Textbox(label="Enter the YouTube video URL"),
|
61 |
+
gr.inputs.Textbox(label="Enter the output directory (leave blank for current directory)")
|
62 |
+
],
|
63 |
+
outputs=gr.outputs.Textbox(label="Download Status"),
|
64 |
+
title="YouTube Video Downloader",
|
65 |
+
description="Enter a YouTube video URL and optionally specify an output directory to download the video."
|
66 |
+
)
|
67 |
+
|
68 |
+
# Launch the Gradio interface
|
69 |
+
iface.launch()
|