mobenta commited on
Commit
072569c
·
verified ·
1 Parent(s): ac0c832

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +30 -67
app.py CHANGED
@@ -1,32 +1,23 @@
1
- import subprocess
2
- import sys
3
  import random
 
 
4
  import time
5
-
6
- # Ensure compatible versions of httpx and httpcore are installed
7
- subprocess.check_call([sys.executable, "-m", "pip", "install", "httpx==0.18.2", "httpcore==0.13.6"])
8
-
9
  import gradio as gr
10
- import requests
11
- import re
12
- import yt_dlp
13
- import logging
14
- import os
15
- from fake_useragent import UserAgent
16
 
17
  # Configure logging for debugging purposes
18
  logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
19
 
20
- # Set up User-Agent rotation
21
- ua = UserAgent()
22
-
23
- # Define a list of proxies (example placeholders, replace with your working proxies)
24
  PROXIES = [
25
- "http://proxy1.example.com:8080",
26
- "http://proxy2.example.com:8080",
27
- "http://proxy3.example.com:8080",
28
  ]
29
 
 
 
 
 
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
@@ -36,37 +27,19 @@ def youtube_search(query, max_results=10):
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
 
@@ -115,13 +88,12 @@ def youtube_search(query, max_results=10):
115
 
116
  # Function to display the video using the video URL
117
  def show_video(video_url):
118
- # Regular expression to extract the YouTube video ID from the URL
119
  video_id = None
120
  patterns = [
121
- r"youtube\.com/watch\?v=([^&?\/]+)",
122
- r"youtube\.com/embed/([^&?\/]+)",
123
- r"youtube\.com/v/([^&?\/]+)",
124
- r"youtu\.be/([^&?\/]+)"
125
  ]
126
 
127
  for pattern in patterns:
@@ -131,16 +103,13 @@ def show_video(video_url):
131
  logging.debug(f"Extracted video ID: {video_id}")
132
  break
133
 
134
- # If no video ID is found, return an error message
135
  if not video_id:
136
  logging.error("Invalid YouTube URL. Please enter a valid YouTube video link.")
137
  return "Invalid YouTube URL. Please enter a valid YouTube video link."
138
 
139
- # Create the embed URL
140
  embed_url = f"https://www.youtube.com/embed/{video_id}"
141
  logging.debug(f"Embed URL generated: {embed_url}")
142
 
143
- # Return an iframe with the video
144
  html_code = f'''
145
  <iframe width="560" height="315" src="{embed_url}"
146
  frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
@@ -148,7 +117,7 @@ def show_video(video_url):
148
  '''
149
  return html_code
150
 
151
- # Create the Gradio interface
152
  with gr.Blocks() as demo:
153
  gr.Markdown("## YouTube Video Search, Selection, and Playback")
154
 
@@ -164,26 +133,21 @@ with gr.Blocks() as demo:
164
  play_video_button = gr.Button("Play Video")
165
  video_output = gr.HTML(label="Video Player")
166
 
167
- # Define search button behavior
168
  def update_search_results(query):
169
  gallery_items, error_message = youtube_search(query)
170
  if error_message:
171
  return [], error_message, gr.update(visible=True)
172
-
173
- # Prepare gallery items
174
- gallery_items_display = [(item["thumbnail"], f"{item['title']}\n{item['description']}", item["video_id"]) for item in gallery_items]
175
 
176
  return gallery_items_display, "", gr.update(visible=False)
177
 
178
- # Update the selected video link field when a video is clicked in the gallery
179
  def on_video_select(evt: gr.SelectData):
180
- # Extract the video ID from the event value, which is a dictionary containing details of the selected item
181
  selected_video_id = evt.value["caption"]
182
  video_url = f"https://www.youtube.com/watch?v={selected_video_id}"
183
  logging.debug(f"Video selected: {video_url}")
184
  return video_url
185
 
186
- # Play the video when the Play Video button is clicked
187
  def play_video(video_url):
188
  logging.debug(f"Playing video with URL: {video_url}")
189
  return show_video(video_url)
@@ -192,5 +156,4 @@ with gr.Blocks() as demo:
192
  search_output.select(on_video_select, inputs=None, outputs=selected_video_link)
193
  play_video_button.click(play_video, inputs=selected_video_link, outputs=video_output)
194
 
195
- # Launch the Gradio interface
196
  demo.launch()
 
 
 
1
  import random
2
+ import logging
3
+ import yt_dlp
4
  import time
 
 
 
 
5
  import gradio as gr
 
 
 
 
 
 
6
 
7
  # Configure logging for debugging purposes
8
  logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
9
 
10
+ # Define the list of proxies provided by you
 
 
 
11
  PROXIES = [
12
+ '43.134.229.98:3128', '35.220.254.137:8080', '31.129.253.30:40223', '41.204.53.17:80', '193.233.84.88:1080',
13
+ '4.158.61.222:8080', '66.29.154.105:3128', '160.86.242.23:8080', '20.26.249.29:8080', '85.210.84.189:8080',
14
+ # Add more as needed...
15
  ]
16
 
17
+ # Function to get a random proxy from the list
18
+ def get_random_proxy():
19
+ return random.choice(PROXIES)
20
+
21
  # Function to search YouTube videos using yt-dlp for better reliability
22
  def youtube_search(query, max_results=10):
23
  cookies_file = "cookies.txt" # You need to provide this file with cookies exported from YouTube
 
27
  gallery_items = []
28
  error_message = ""
29
 
30
+ while not success and proxies_attempted < max_proxy_attempts:
31
+ proxy = get_random_proxy()
32
+ logging.debug(f"Trying proxy: {proxy}")
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': f'http://{proxy}',
40
+ }
41
+
42
+ if cookies_file and os.path.exists(cookies_file):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  ydl_opts['cookiefile'] = cookies_file
44
  logging.debug("Using cookies for YouTube authentication.")
45
 
 
88
 
89
  # Function to display the video using the video URL
90
  def show_video(video_url):
 
91
  video_id = None
92
  patterns = [
93
+ r"youtube\\.com/watch\\?v=([^&?\\/]+)",
94
+ r"youtube\\.com/embed/([^&?\\/]+)",
95
+ r"youtube\\.com/v/([^&?\\/]+)",
96
+ r"youtu\\.be/([^&?\\/]+)"
97
  ]
98
 
99
  for pattern in patterns:
 
103
  logging.debug(f"Extracted video ID: {video_id}")
104
  break
105
 
 
106
  if not video_id:
107
  logging.error("Invalid YouTube URL. Please enter a valid YouTube video link.")
108
  return "Invalid YouTube URL. Please enter a valid YouTube video link."
109
 
 
110
  embed_url = f"https://www.youtube.com/embed/{video_id}"
111
  logging.debug(f"Embed URL generated: {embed_url}")
112
 
 
113
  html_code = f'''
114
  <iframe width="560" height="315" src="{embed_url}"
115
  frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
 
117
  '''
118
  return html_code
119
 
120
+ # Gradio Interface Setup
121
  with gr.Blocks() as demo:
122
  gr.Markdown("## YouTube Video Search, Selection, and Playback")
123
 
 
133
  play_video_button = gr.Button("Play Video")
134
  video_output = gr.HTML(label="Video Player")
135
 
 
136
  def update_search_results(query):
137
  gallery_items, error_message = youtube_search(query)
138
  if error_message:
139
  return [], error_message, gr.update(visible=True)
140
+
141
+ gallery_items_display = [(item["thumbnail"], f"{item['title']}\\n{item['description']}", item["video_id"]) for item in gallery_items]
 
142
 
143
  return gallery_items_display, "", gr.update(visible=False)
144
 
 
145
  def on_video_select(evt: gr.SelectData):
 
146
  selected_video_id = evt.value["caption"]
147
  video_url = f"https://www.youtube.com/watch?v={selected_video_id}"
148
  logging.debug(f"Video selected: {video_url}")
149
  return video_url
150
 
 
151
  def play_video(video_url):
152
  logging.debug(f"Playing video with URL: {video_url}")
153
  return show_video(video_url)
 
156
  search_output.select(on_video_select, inputs=None, outputs=selected_video_link)
157
  play_video_button.click(play_video, inputs=selected_video_link, outputs=video_output)
158
 
 
159
  demo.launch()