MojoHz commited on
Commit
7ab13cd
·
verified ·
1 Parent(s): 5aa5b9a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +38 -15
app.py CHANGED
@@ -50,39 +50,62 @@ def add_local_files(module):
50
  elif module == "paper":
51
  return [{"title": os.path.basename(file_path), "url": None, "file_path": file_path, "type": "paper"}]
52
 
 
 
 
 
53
  def download_youtube_video(video_url, output_dir, title=None):
54
  """Download a YouTube video using yt_dlp."""
55
- sanitized_title = re.sub(r'[\\/*?:"<>|]', '_', title) if title else None
56
  ydl_opts = {
57
  'quiet': True,
58
- 'outtmpl': f"{output_dir}/{sanitized_title}.%(ext)s" if sanitized_title else f"{output_dir}/%(title)s.%(ext)s",
59
  'format': 'best',
60
  }
61
  try:
62
  with YoutubeDL(ydl_opts) as ydl:
63
- ydl.download([video_url])
64
- return os.path.join(output_dir, f"{sanitized_title}.mp4")
 
 
65
  except Exception as e:
66
  print(f"Failed to download video {video_url}. Error: {e}")
67
  return None
68
 
69
- def fetch_and_download_youtube_video(query, output_dir="./downloads"):
70
- """Fetch and download the best YouTube video for a query."""
 
71
  ydl_opts = {
72
- 'quiet': True,
73
- 'outtmpl': f"{output_dir}/{sanitized_title}.%(ext)s",
74
- 'format': 'best',
75
- 'cookiesfrombrowser': ('chrome',), # Adjust for your browser (e.g., 'firefox', 'edge')
76
- }
77
 
78
  try:
79
  with YoutubeDL(ydl_opts) as ydl:
80
- search_results = ydl.extract_info(query, download=False)
81
- video = search_results['entries'][0] # Get the first result
82
- video_title = video['title']
83
- video_url = video['webpage_url']
 
 
 
 
 
 
 
 
 
 
 
 
84
  local_path = download_youtube_video(video_url, output_dir, title=video_title)
 
 
 
 
85
  return [{"title": video_title, "url": video_url, "file_path": local_path, "type": "video"}]
 
86
  except Exception as e:
87
  print(f"Error fetching YouTube video for query '{query}': {e}")
88
  return []
 
50
  elif module == "paper":
51
  return [{"title": os.path.basename(file_path), "url": None, "file_path": file_path, "type": "paper"}]
52
 
53
+ import os
54
+ import re
55
+ from yt_dlp import YoutubeDL
56
+
57
  def download_youtube_video(video_url, output_dir, title=None):
58
  """Download a YouTube video using yt_dlp."""
59
+ sanitized_title = re.sub(r'[\\/*?:"<>|]', '_', title) if title else "unknown_title"
60
  ydl_opts = {
61
  'quiet': True,
62
+ 'outtmpl': f"{output_dir}/{sanitized_title}.%(ext)s",
63
  'format': 'best',
64
  }
65
  try:
66
  with YoutubeDL(ydl_opts) as ydl:
67
+ info = ydl.extract_info(video_url, download=True)
68
+ # Extract the final downloaded file path
69
+ downloaded_file = ydl.prepare_filename(info)
70
+ return downloaded_file
71
  except Exception as e:
72
  print(f"Failed to download video {video_url}. Error: {e}")
73
  return None
74
 
75
+ def fetch_and_download_youtube_video(query, output_dir="./videos"):
76
+ """Fetch and download a YouTube video based on a query."""
77
+ print(f"Fetching YouTube video for query: '{query}'")
78
  ydl_opts = {
79
+ 'quiet': True,
80
+ 'format': 'best',
81
+ 'outtmpl': f"{output_dir}/%(title)s.%(ext)s", # Default template
82
+ }
 
83
 
84
  try:
85
  with YoutubeDL(ydl_opts) as ydl:
86
+ # Perform a search for the query on YouTube
87
+ search_results = ydl.extract_info(f"ytsearch:{query}", download=False)
88
+
89
+ if 'entries' not in search_results or len(search_results['entries']) == 0:
90
+ print(f"No YouTube results found for query: '{query}'")
91
+ return []
92
+
93
+ video_info = search_results['entries'][0] # Take the first result
94
+ video_title = video_info.get("title", "unknown_title")
95
+ video_url = video_info.get("webpage_url", None)
96
+
97
+ if not video_url:
98
+ print("No URL found for the video.")
99
+ return []
100
+
101
+ # Download the video
102
  local_path = download_youtube_video(video_url, output_dir, title=video_title)
103
+ if not local_path:
104
+ return []
105
+
106
+ print(f"Successfully downloaded video: {video_title}")
107
  return [{"title": video_title, "url": video_url, "file_path": local_path, "type": "video"}]
108
+
109
  except Exception as e:
110
  print(f"Error fetching YouTube video for query '{query}': {e}")
111
  return []