mobenta commited on
Commit
dc5e8f2
·
verified ·
1 Parent(s): cbc31f1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +19 -30
app.py CHANGED
@@ -8,41 +8,30 @@ import gradio as gr
8
  import requests
9
  from bs4 import BeautifulSoup
10
  import re
 
11
 
12
- # Function to search YouTube videos using web scraping
13
  def youtube_search(query, max_results=50):
14
- search_url = f"https://www.youtube.com/results?search_query={query}"
15
- headers = {
16
- "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"
17
  }
 
18
 
19
  try:
20
- # Make the HTTP request to YouTube search results page
21
- response = requests.get(search_url, headers=headers)
22
- response.raise_for_status() # Raise an error for bad responses (4xx or 5xx)
23
-
24
- # Parse the HTML content
25
- soup = BeautifulSoup(response.text, "html.parser")
26
- video_elements = soup.find_all("a", href=True, class_="yt-uix-tile-link")
27
-
28
- # Extract up to 'max_results' video details
29
- gallery_items = []
30
- for idx, video in enumerate(video_elements):
31
- if idx >= max_results:
32
- break
33
-
34
- video_id = video['href'].split('=')[-1]
35
- video_title = video.get_text(strip=True)
36
- thumbnail_url = f"https://img.youtube.com/vi/{video_id}/mqdefault.jpg"
37
-
38
- # Append tuple (thumbnail, video ID)
39
- gallery_items.append((thumbnail_url, video_id))
40
-
41
- return gallery_items
42
-
43
- except requests.exceptions.RequestException as e:
44
- # Print the error message to help debug issues
45
- print(f"Error during YouTube web scraping request: {e}")
46
  return []
47
 
48
  # Function to display the video using the video URL
 
8
  import requests
9
  from bs4 import BeautifulSoup
10
  import re
11
+ import yt_dlp
12
 
13
+ # Function to search YouTube videos using yt-dlp for better reliability
14
  def youtube_search(query, max_results=50):
15
+ ydl_opts = {
16
+ 'quiet': True,
17
+ 'extract_flat': 'in_playlist',
18
  }
19
+ search_url = f"ytsearch{max_results}:{query}"
20
 
21
  try:
22
+ with yt_dlp.YoutubeDL(ydl_opts) as ydl:
23
+ result = ydl.extract_info(search_url, download=False)
24
+ gallery_items = []
25
+
26
+ if 'entries' in result:
27
+ for entry in result['entries']:
28
+ video_id = entry.get('id')
29
+ thumbnail_url = entry.get('thumbnail')
30
+ if video_id and thumbnail_url:
31
+ gallery_items.append((thumbnail_url, video_id))
32
+ return gallery_items
33
+ except Exception as e:
34
+ print(f"Error during YouTube yt-dlp request: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
35
  return []
36
 
37
  # Function to display the video using the video URL