Artificial-superintelligence commited on
Commit
735f163
·
verified ·
1 Parent(s): cd91b22

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +79 -48
app.py CHANGED
@@ -2,23 +2,27 @@ 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
  return re.sub(r'[<>:"/\\|?*]', '_', title)
10
 
11
  # Function to download video and return the file path
12
  def download_video(url):
13
- download_path = './downloads'
 
14
  if not os.path.exists(download_path):
15
  os.makedirs(download_path)
16
-
17
  ydl_opts = {
18
  'outtmpl': os.path.join(download_path, '%(title)s.%(ext)s'),
19
- 'format': 'best',
 
20
  }
21
-
22
  try:
23
  with yt_dlp.YoutubeDL(ydl_opts) as ydl:
24
  info_dict = ydl.extract_info(url, download=True)
@@ -29,61 +33,88 @@ def download_video(url):
29
  return file_path if os.path.exists(file_path) else None
30
  return None
31
  except Exception as e:
32
- return str(e)
 
33
 
34
  # Function to crop the video
35
  def crop_video(input_path, start_time, end_time):
36
- output_path = input_path.replace('.mp4', '_cropped.mp4')
 
 
 
37
  try:
38
  with VideoFileClip(input_path) as video:
 
 
 
 
 
 
39
  cropped_video = video.subclip(start_time, end_time)
40
  cropped_video.write_videofile(output_path, codec='libx264', audio_codec='aac')
41
- return output_path
42
  except Exception as e:
43
- return str(e)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
 
45
  # Create Gradio interface
46
- def gradio_interface():
47
  with gr.Blocks() as demo:
48
  gr.Markdown("# YouTube Video Downloader and Cropper")
49
- gr.Markdown("Enter the YouTube URL to download and crop the video.")
50
-
51
- # Input for YouTube URL
52
- url_input = gr.Textbox(label="YouTube URL", placeholder="Enter YouTube video URL here...")
53
-
54
- # Inputs for cropping
55
- start_time_input = gr.Number(label="Start Time (seconds)", value=0, interactive=True)
56
- end_time_input = gr.Number(label="End Time (seconds)", value=10, interactive=True)
57
-
58
- # Status message for user feedback
59
- status_message = gr.Textbox(label="Status", placeholder="Processing...", interactive=False)
60
-
61
- # Download and Crop button
62
- process_btn = gr.Button("Download and Crop Video")
63
-
64
- # Output the cropped video and status message
65
- output_file = gr.File(label="Download Cropped Video")
66
-
67
- # Define the action on button click
68
- def process_video(url, start_time, end_time):
69
- status_message.value = "Downloading video..."
70
- video_path = download_video(url)
71
- if isinstance(video_path, str) and os.path.exists(video_path):
72
- status_message.value = "Cropping video..."
73
- cropped_video_path = crop_video(video_path, start_time, end_time)
74
- if isinstance(cropped_video_path, str) and os.path.exists(cropped_video_path):
75
- return cropped_video_path, "Done! You can download your video below."
76
- else:
77
- status_message.value = "Error cropping video."
78
- else:
79
- status_message.value = "Error downloading video. Please check the URL."
80
- return None, status_message.value
81
-
82
- # Bind button click to processing function
83
- process_btn.click(process_video, inputs=[url_input, start_time_input, end_time_input], outputs=[output_file, status_message])
84
-
85
  return demo
86
 
87
- # Launch the interface
88
- if __name__ == "__main__":
89
- gradio_interface().launch()
 
2
  import yt_dlp
3
  import os
4
  import re
5
+ import time
6
  from moviepy.video.io.VideoFileClip import VideoFileClip
7
 
8
  # Function to sanitize the filename
9
  def sanitize_filename(title):
10
+ # Replace invalid characters with an underscore
11
  return re.sub(r'[<>:"/\\|?*]', '_', title)
12
 
13
  # Function to download video and return the file path
14
  def download_video(url):
15
+ # Use /tmp for temporary storage in Hugging Face Spaces
16
+ download_path = '/tmp/downloads'
17
  if not os.path.exists(download_path):
18
  os.makedirs(download_path)
19
+
20
  ydl_opts = {
21
  'outtmpl': os.path.join(download_path, '%(title)s.%(ext)s'),
22
+ 'format': 'mp4/bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best', # Prefer MP4 format
23
+ 'merge_output_format': 'mp4',
24
  }
25
+
26
  try:
27
  with yt_dlp.YoutubeDL(ydl_opts) as ydl:
28
  info_dict = ydl.extract_info(url, download=True)
 
33
  return file_path if os.path.exists(file_path) else None
34
  return None
35
  except Exception as e:
36
+ print(f"Download error: {str(e)}")
37
+ return None
38
 
39
  # Function to crop the video
40
  def crop_video(input_path, start_time, end_time):
41
+ if not input_path or not os.path.exists(input_path):
42
+ return None
43
+
44
+ output_path = os.path.join('/tmp/downloads', 'cropped_video.mp4')
45
  try:
46
  with VideoFileClip(input_path) as video:
47
+ # Ensure end_time doesn't exceed video duration
48
+ duration = video.duration
49
+ end_time = min(end_time, duration)
50
+ if start_time >= end_time:
51
+ return None
52
+
53
  cropped_video = video.subclip(start_time, end_time)
54
  cropped_video.write_videofile(output_path, codec='libx264', audio_codec='aac')
55
+ return output_path if os.path.exists(output_path) else None
56
  except Exception as e:
57
+ print(f"Cropping error: {str(e)}")
58
+ return None
59
+
60
+ # Main processing function
61
+ def process_video(url, start_time, end_time):
62
+ if not url:
63
+ return None
64
+
65
+ try:
66
+ # Download the video
67
+ video_path = download_video(url)
68
+ if not video_path:
69
+ return None
70
+
71
+ # Crop the video
72
+ cropped_path = crop_video(video_path, start_time, end_time)
73
+ if cropped_path and os.path.exists(cropped_path):
74
+ time.sleep(1) # Ensure file is fully written
75
+ return cropped_path
76
+
77
+ return None
78
+ except Exception as e:
79
+ print(f"Processing error: {str(e)}")
80
+ return None
81
 
82
  # Create Gradio interface
83
+ def create_interface():
84
  with gr.Blocks() as demo:
85
  gr.Markdown("# YouTube Video Downloader and Cropper")
86
+
87
+ with gr.Row():
88
+ url_input = gr.Textbox(
89
+ label="YouTube URL",
90
+ placeholder="Enter YouTube video URL here..."
91
+ )
92
+
93
+ with gr.Row():
94
+ start_time_input = gr.Number(
95
+ label="Start Time (seconds)",
96
+ value=0,
97
+ minimum=0
98
+ )
99
+ end_time_input = gr.Number(
100
+ label="End Time (seconds)",
101
+ value=10,
102
+ minimum=0
103
+ )
104
+
105
+ with gr.Row():
106
+ process_btn = gr.Button("Download and Crop Video")
107
+ output_file = gr.File(label="Download Cropped Video")
108
+
109
+ # Connect the button to the processing function
110
+ process_btn.click(
111
+ fn=process_video,
112
+ inputs=[url_input, start_time_input, end_time_input],
113
+ outputs=output_file
114
+ )
115
+
 
 
 
 
 
 
116
  return demo
117
 
118
+ # Launch the app
119
+ demo = create_interface()
120
+ demo.launch()