JUNGU commited on
Commit
5a8ee25
·
verified ·
1 Parent(s): 1b8cfc0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +25 -23
app.py CHANGED
@@ -1,40 +1,42 @@
1
  import gradio as gr
2
- import yt_dlp as youtube_dl
3
  import os
4
- import re
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 downloaded file path."""
13
  try:
14
  ydl_opts = {
15
  'format': 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best',
16
- 'outtmpl': '%(title)s.%(ext)s',
17
- 'postprocessors': [{
18
- 'key': 'FFmpegVideoConvertor',
19
- 'preferedformat': 'mp4',
20
- }],
21
  }
22
 
23
- with youtube_dl.YoutubeDL(ydl_opts) as ydl:
24
- result = ydl.extract_info(youtube_url, download=True)
25
- video_title = sanitize_filename(result.get('title', 'video'))
26
- video_ext = 'mp4' # We're forcing mp4 format
27
- downloaded_file = f"{video_title}.{video_ext}"
28
- return downloaded_file
 
 
 
 
 
 
 
 
 
 
 
29
 
30
  except Exception as e:
31
  print("An error occurred:", e)
32
- return None
33
 
34
  def app(video_link):
35
- video_path = download_youtube_video(video_link)
36
- if video_path:
37
- return video_path, "Download successful! Click the file name to download."
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