Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,40 +1,42 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
-
import yt_dlp
|
| 3 |
import os
|
| 4 |
-
import
|
| 5 |
-
|
| 6 |
-
def sanitize_filename(filename):
|
| 7 |
-
"""Remove or replace characters that are unsafe for filenames."""
|
| 8 |
-
unsafe_chars = r'[<>:"/\\|?*\u0000-\u001F]'
|
| 9 |
-
return re.sub(unsafe_chars, '_', filename)
|
| 10 |
|
| 11 |
def download_youtube_video(youtube_url):
|
| 12 |
-
"""Downloads a YouTube video using yt_dlp and returns the
|
| 13 |
try:
|
| 14 |
ydl_opts = {
|
| 15 |
'format': 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best',
|
| 16 |
-
'outtmpl': '
|
| 17 |
-
'postprocessors': [{
|
| 18 |
-
'key': 'FFmpegVideoConvertor',
|
| 19 |
-
'preferedformat': 'mp4',
|
| 20 |
-
}],
|
| 21 |
}
|
| 22 |
|
| 23 |
-
with
|
| 24 |
-
|
| 25 |
-
video_title =
|
| 26 |
-
video_ext = '
|
| 27 |
-
|
| 28 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
|
| 30 |
except Exception as e:
|
| 31 |
print("An error occurred:", e)
|
| 32 |
-
return None
|
| 33 |
|
| 34 |
def app(video_link):
|
| 35 |
-
|
| 36 |
-
if
|
| 37 |
-
return
|
| 38 |
else:
|
| 39 |
return None, "Download failed. Please check the URL and try again."
|
| 40 |
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
+
import yt_dlp
|
| 3 |
import os
|
| 4 |
+
import io
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
|
| 6 |
def download_youtube_video(youtube_url):
|
| 7 |
+
"""Downloads a YouTube video using yt_dlp and returns the video data and filename."""
|
| 8 |
try:
|
| 9 |
ydl_opts = {
|
| 10 |
'format': 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best',
|
| 11 |
+
'outtmpl': 'video.%(ext)s',
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
}
|
| 13 |
|
| 14 |
+
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
|
| 15 |
+
info = ydl.extract_info(youtube_url, download=False)
|
| 16 |
+
video_title = info.get('title', 'video')
|
| 17 |
+
video_ext = info.get('ext', 'mp4')
|
| 18 |
+
|
| 19 |
+
# Use a simple filename
|
| 20 |
+
filename = f"youtube_video.{video_ext}"
|
| 21 |
+
|
| 22 |
+
# Download to memory
|
| 23 |
+
ydl_opts['outtmpl'] = '-'
|
| 24 |
+
ydl_opts['logtostderr'] = True
|
| 25 |
+
|
| 26 |
+
with io.BytesIO() as video_buffer:
|
| 27 |
+
ydl.download([youtube_url])
|
| 28 |
+
video_data = video_buffer.getvalue()
|
| 29 |
+
|
| 30 |
+
return video_data, filename, video_title
|
| 31 |
|
| 32 |
except Exception as e:
|
| 33 |
print("An error occurred:", e)
|
| 34 |
+
return None, None, None
|
| 35 |
|
| 36 |
def app(video_link):
|
| 37 |
+
video_data, filename, video_title = download_youtube_video(video_link)
|
| 38 |
+
if video_data and filename:
|
| 39 |
+
return (filename, video_data), f"Download successful! Video: {video_title}"
|
| 40 |
else:
|
| 41 |
return None, "Download failed. Please check the URL and try again."
|
| 42 |
|