mobenta commited on
Commit
ac0c832
·
verified ·
1 Parent(s): 03ebb12

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +81 -52
app.py CHANGED
@@ -30,59 +30,88 @@ PROXIES = [
30
  # Function to search YouTube videos using yt-dlp for better reliability
31
  def youtube_search(query, max_results=10):
32
  cookies_file = "cookies.txt" # You need to provide this file with cookies exported from YouTube
33
- ydl_opts = {
34
- 'quiet': False, # Set to False to get more detailed output from yt-dlp
35
- 'logger': logging.getLogger(), # Use the logging module to capture yt-dlp logs
36
- 'simulate': True,
37
- 'noplaylist': True, # Avoid extracting playlists
38
- 'format': 'best',
39
- 'proxy': random.choice(PROXIES), # Randomly choose a proxy for each request
40
- 'http_headers': {
41
- 'User-Agent': ua.random # Rotate user agents to make requests appear less like a bot
42
- },
43
- }
44
-
45
- if os.path.exists(cookies_file):
46
- ydl_opts['cookiefile'] = cookies_file
47
- logging.debug("Using cookies for YouTube authentication.")
48
-
49
- search_url = f"ytsearch{max_results}:{query}"
50
- logging.debug(f"Starting YouTube search for query: {query}")
51
-
52
- try:
53
- # Introduce a random delay to avoid rate-limiting issues
54
- time.sleep(random.uniform(2, 5))
55
-
56
- with yt_dlp.YoutubeDL(ydl_opts) as ydl:
57
- result = ydl.extract_info(search_url, download=False)
58
- gallery_items = []
59
-
60
- if 'entries' in result:
61
- logging.debug(f"Number of entries found: {len(result['entries'])}")
62
- for entry in result['entries']:
63
- video_id = entry.get('id')
64
- # Fallback to YouTube static thumbnails if missing
65
- thumbnail_url = entry.get('thumbnail') if entry.get('thumbnail') else f"https://img.youtube.com/vi/{video_id}/hqdefault.jpg"
66
- video_title = entry.get('title', "Unknown Title")
67
- video_description = entry.get('description', "No description available.")
68
-
69
- if video_id:
70
- gallery_items.append({
71
- "thumbnail": thumbnail_url,
72
- "video_id": video_id,
73
- "title": video_title,
74
- "description": video_description
75
- })
76
- logging.debug(f"Added video: ID={video_id}, Thumbnail={thumbnail_url}, Title={video_title}")
77
- else:
78
- logging.debug(f"Missing video ID for entry: {entry}")
79
- else:
80
- logging.warning("No entries found in search result.")
81
- return gallery_items, ""
82
- except Exception as e:
83
- error_message = f"Error during YouTube yt-dlp request: {e}"
84
- logging.error(error_message)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
  return [], error_message
 
86
 
87
  # Function to display the video using the video URL
88
  def show_video(video_url):
 
30
  # Function to search YouTube videos using yt-dlp for better reliability
31
  def youtube_search(query, max_results=10):
32
  cookies_file = "cookies.txt" # You need to provide this file with cookies exported from YouTube
33
+ proxies_attempted = 0
34
+ max_proxy_attempts = len(PROXIES)
35
+ success = False
36
+ gallery_items = []
37
+ error_message = ""
38
+
39
+ while not success and proxies_attempted <= max_proxy_attempts:
40
+ if proxies_attempted < max_proxy_attempts:
41
+ # Use a proxy
42
+ proxy = PROXIES[proxies_attempted]
43
+ logging.debug(f"Trying proxy: {proxy}")
44
+ ydl_opts = {
45
+ 'quiet': False, # Set to False to get more detailed output from yt-dlp
46
+ 'logger': logging.getLogger(), # Use the logging module to capture yt-dlp logs
47
+ 'simulate': True,
48
+ 'noplaylist': True, # Avoid extracting playlists
49
+ 'format': 'best',
50
+ 'proxy': proxy,
51
+ 'http_headers': {
52
+ 'User-Agent': ua.random # Rotate user agents to make requests appear less like a bot
53
+ },
54
+ }
55
+ else:
56
+ # Fallback to direct access after all proxies fail
57
+ logging.debug("Falling back to direct connection without a proxy.")
58
+ ydl_opts = {
59
+ 'quiet': False,
60
+ 'logger': logging.getLogger(),
61
+ 'simulate': True,
62
+ 'noplaylist': True,
63
+ 'format': 'best',
64
+ 'http_headers': {
65
+ 'User-Agent': ua.random
66
+ },
67
+ }
68
+
69
+ if os.path.exists(cookies_file):
70
+ ydl_opts['cookiefile'] = cookies_file
71
+ logging.debug("Using cookies for YouTube authentication.")
72
+
73
+ search_url = f"ytsearch{max_results}:{query}"
74
+ logging.debug(f"Starting YouTube search for query: {query}")
75
+
76
+ try:
77
+ # Introduce a random delay to avoid rate-limiting issues
78
+ time.sleep(random.uniform(2, 5))
79
+
80
+ with yt_dlp.YoutubeDL(ydl_opts) as ydl:
81
+ result = ydl.extract_info(search_url, download=False)
82
+
83
+ if 'entries' in result:
84
+ logging.debug(f"Number of entries found: {len(result['entries'])}")
85
+ for entry in result['entries']:
86
+ video_id = entry.get('id')
87
+ # Fallback to YouTube static thumbnails if missing
88
+ thumbnail_url = entry.get('thumbnail') if entry.get('thumbnail') else f"https://img.youtube.com/vi/{video_id}/hqdefault.jpg"
89
+ video_title = entry.get('title', "Unknown Title")
90
+ video_description = entry.get('description', "No description available.")
91
+
92
+ if video_id:
93
+ gallery_items.append({
94
+ "thumbnail": thumbnail_url,
95
+ "video_id": video_id,
96
+ "title": video_title,
97
+ "description": video_description
98
+ })
99
+ logging.debug(f"Added video: ID={video_id}, Thumbnail={thumbnail_url}, Title={video_title}")
100
+ else:
101
+ logging.debug(f"Missing video ID for entry: {entry}")
102
+
103
+ success = True
104
+ else:
105
+ logging.warning("No entries found in search result.")
106
+
107
+ except Exception as e:
108
+ error_message = f"Error during YouTube yt-dlp request: {e}"
109
+ logging.error(error_message)
110
+ proxies_attempted += 1 # Increment the proxy attempt counter
111
+
112
+ if not success:
113
  return [], error_message
114
+ return gallery_items, ""
115
 
116
  # Function to display the video using the video URL
117
  def show_video(video_url):