Artificial-superintelligence commited on
Commit
a74c154
·
verified ·
1 Parent(s): 6d42786

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +67 -57
app.py CHANGED
@@ -1,69 +1,79 @@
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.Textbox(label="Enter the YouTube video URL"),
61
- gr.Textbox(label="Enter the output directory (leave blank for current directory)")
62
- ],
63
- outputs=gr.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()
 
 
1
+ import gradio as gr
2
+ import yt_dlp
3
  import os
4
+ import re
5
+ from moviepy.video.io.VideoFileClip import VideoFileClip
6
 
7
+ # Function to sanitize the filename
8
+ def sanitize_filename(title):
9
+ # Replace invalid characters with an underscore
10
+ return re.sub(r'[<>:"/\\|?*]', '_', title)
11
 
12
+ # Function to download video and return the file path
13
+ def download_video(url):
14
+ download_path = './downloads' # Folder to store downloads
15
+ if not os.path.exists(download_path):
16
+ os.makedirs(download_path)
17
 
18
+ ydl_opts = {
19
+ 'outtmpl': download_path + '/%(title)s.%(ext)s',
20
+ 'format': 'best', # Download the best available quality
21
+ }
22
+
23
+ try:
24
+ with yt_dlp.YoutubeDL(ydl_opts) as ydl:
25
+ info_dict = ydl.extract_info(url, download=True) # Set download=True to download the video
26
+ title = info_dict.get('title', None)
27
+ if title:
28
+ sanitized_title = sanitize_filename(title)
29
+ file_path = os.path.join(download_path, f"{sanitized_title}.mp4") # Adjust the extension as needed
30
+ return file_path if os.path.exists(file_path) else None # Ensure the file exists before returning
31
+ return None
32
+ except Exception as e:
33
+ return str(e)
34
 
35
+ # Function to crop the video
36
+ def crop_video(input_path, start_time, end_time):
37
+ output_path = input_path.replace('.mp4', '_cropped.mp4')
38
+ try:
39
+ with VideoFileClip(input_path) as video:
40
+ cropped_video = video.subclip(start_time, end_time)
41
+ cropped_video.write_videofile(output_path, codec='libx264')
42
+ return output_path
43
+ except Exception as e:
44
+ return str(e)
45
 
46
+ # Create Gradio interface
47
+ def gradio_interface():
48
+ with gr.Blocks() as demo:
49
+ gr.Markdown("# YouTube Video Downloader and Cropper")
50
+ gr.Markdown("Enter the YouTube URL to download and crop the video.")
 
 
 
51
 
52
+ # Input for YouTube URL
53
+ url_input = gr.Textbox(label="YouTube URL", placeholder="Enter YouTube video URL here...")
54
+
55
+ # Inputs for cropping
56
+ start_time_input = gr.Number(label="Start Time (seconds)", value=0)
57
+ end_time_input = gr.Number(label="End Time (seconds)", value=10)
58
 
59
+ # File output for downloaded video
60
+ output_file = gr.File(label="Download Cropped Video")
61
+
62
+ # Download and Crop button
63
+ process_btn = gr.Button("Download and Crop Video")
 
 
64
 
65
+ # Define the action on button click
66
+ def process_video(url, start_time, end_time):
67
+ video_path = download_video(url)
68
+ if video_path:
69
+ cropped_video_path = crop_video(video_path, start_time, end_time)
70
+ return cropped_video_path
71
+ return None
72
 
73
+ process_btn.click(process_video, inputs=[url_input, start_time_input, end_time_input], outputs=output_file)
 
74
 
75
+ return demo
 
 
 
 
 
 
 
 
 
 
76
 
77
+ # Launch the interface
78
+ if __name__ == "__main__":
79
+ gradio_interface().launch()