mobenta commited on
Commit
f66cc35
·
verified ·
1 Parent(s): 99ade4d

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -184
app.py DELETED
@@ -1,184 +0,0 @@
1
- import subprocess
2
- import sys
3
- import random
4
- import time
5
- import os # Added import for os module to handle file checks
6
-
7
- # Ensure compatible versions of httpx and httpcore are installed
8
- subprocess.check_call([sys.executable, "-m", "pip", "install", "httpx==0.18.2", "httpcore==0.13.6"])
9
-
10
- import gradio as gr
11
- import requests
12
- import re
13
- import yt_dlp
14
- import logging
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 the list of proxies provided
24
- PROXIES = [
25
- '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',
26
- '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',
27
- # Add more as needed...
28
- ]
29
-
30
- # Function to get a random proxy from the list
31
- def get_random_proxy():
32
- return random.choice(PROXIES)
33
-
34
- # Function to search YouTube videos using yt-dlp for better reliability
35
- def youtube_search(query, max_results=10):
36
- cookies_file = "cookies.txt"
37
- proxies_attempted = 0
38
- max_proxy_attempts = len(PROXIES)
39
- success = False
40
- gallery_items = []
41
- error_message = ""
42
-
43
- while not success and proxies_attempted < max_proxy_attempts + 1: # +1 to allow fallback without a proxy
44
- if proxies_attempted < max_proxy_attempts:
45
- proxy = get_random_proxy()
46
- logging.debug(f"Trying proxy: {proxy}")
47
- ydl_opts = {
48
- 'quiet': False,
49
- 'logger': logging.getLogger(),
50
- 'simulate': True,
51
- 'noplaylist': True,
52
- 'format': 'best',
53
- 'proxy': f'http://{proxy}',
54
- 'socket_timeout': 30 # Extended timeout
55
- }
56
- else:
57
- logging.debug("All proxies failed. Trying without a proxy.")
58
- ydl_opts = {
59
- 'quiet': False,
60
- 'logger': logging.getLogger(),
61
- 'simulate': True,
62
- 'noplaylist': True,
63
- 'format': 'best',
64
- 'socket_timeout': 30 # Extended timeout
65
- }
66
-
67
- if cookies_file and os.path.exists(cookies_file):
68
- ydl_opts['cookiefile'] = cookies_file
69
- logging.debug("Using cookies for YouTube authentication.")
70
-
71
- search_url = f"ytsearch{max_results}:{query}"
72
- logging.debug(f"Starting YouTube search for query: {query}")
73
-
74
- try:
75
- # Introduce a random delay to avoid rate-limiting issues
76
- time.sleep(random.uniform(2, 5))
77
-
78
- with yt_dlp.YoutubeDL(ydl_opts) as ydl:
79
- result = ydl.extract_info(search_url, download=False)
80
-
81
- if 'entries' in result:
82
- logging.debug(f"Number of entries found: {len(result['entries'])}")
83
- for entry in result['entries']:
84
- video_id = entry.get('id')
85
- # Fallback to YouTube static thumbnails if missing
86
- thumbnail_url = entry.get('thumbnail') if entry.get('thumbnail') else f"https://img.youtube.com/vi/{video_id}/hqdefault.jpg"
87
- video_title = entry.get('title', "Unknown Title")
88
- video_description = entry.get('description', "No description available.")
89
-
90
- if video_id:
91
- gallery_items.append({
92
- "thumbnail": thumbnail_url,
93
- "video_id": video_id,
94
- "title": video_title,
95
- "description": video_description
96
- })
97
- logging.debug(f"Added video: ID={video_id}, Thumbnail={thumbnail_url}, Title={video_title}")
98
- else:
99
- logging.debug(f"Missing video ID for entry: {entry}")
100
-
101
- success = True
102
- else:
103
- logging.warning("No entries found in search result.")
104
-
105
- except Exception as e:
106
- error_message = f"Error during YouTube yt-dlp request: {e}"
107
- logging.error(error_message)
108
- proxies_attempted += 1 # Increment the proxy attempt counter
109
-
110
- if not success:
111
- return [], error_message
112
- return gallery_items, ""
113
-
114
- # Function to display the video using the video URL
115
- def show_video(video_url):
116
- video_id = None
117
- patterns = [
118
- r"youtube\.com/watch\?v=([^&?\/]+)",
119
- r"youtube\.com/embed/([^&?\/]+)",
120
- r"youtube\.com/v/([^&?\/]+)",
121
- r"youtu\.be/([^&?\/]+)"
122
- ]
123
-
124
- for pattern in patterns:
125
- match = re.search(pattern, video_url)
126
- if match:
127
- video_id = match.group(1)
128
- logging.debug(f"Extracted video ID: {video_id}")
129
- break
130
-
131
- if not video_id:
132
- logging.error("Invalid YouTube URL. Please enter a valid YouTube video link.")
133
- return "Invalid YouTube URL. Please enter a valid YouTube video link."
134
-
135
- embed_url = f"https://www.youtube.com/embed/{video_id}"
136
- logging.debug(f"Embed URL generated: {embed_url}")
137
-
138
- html_code = f'''
139
- <iframe width="560" height="315" src="{embed_url}"
140
- frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
141
- allowfullscreen></iframe>
142
- '''
143
- return html_code
144
-
145
- # Gradio Interface Setup
146
- with gr.Blocks() as demo:
147
- gr.Markdown("## YouTube Video Search, Selection, and Playback")
148
-
149
- with gr.Row():
150
- with gr.Column(scale=3):
151
- search_query_input = gr.Textbox(label="Search YouTube", placeholder="Enter your search query here")
152
- search_button = gr.Button("Search")
153
- search_output = gr.Gallery(label="Search Results", columns=2, height="1000px", elem_id="gallery")
154
- error_output = gr.Textbox(label="Error Message", interactive=False, visible=False)
155
-
156
- with gr.Column(scale=2):
157
- selected_video_link = gr.Textbox(label="Selected Video Link", interactive=False)
158
- play_video_button = gr.Button("Play Video")
159
- video_output = gr.HTML(label="Video Player")
160
-
161
- def update_search_results(query):
162
- gallery_items, error_message = youtube_search(query)
163
- if error_message:
164
- return [], error_message, gr.update(visible=True)
165
-
166
- gallery_items_display = [(item["thumbnail"], f"{item['title']}\n{item['description']}", item["video_id"]) for item in gallery_items]
167
-
168
- return gallery_items_display, "", gr.update(visible=False)
169
-
170
- def on_video_select(evt: gr.SelectData):
171
- selected_video_id = evt.value["caption"]
172
- video_url = f"https://www.youtube.com/watch?v={selected_video_id}"
173
- logging.debug(f"Video selected: {video_url}")
174
- return video_url
175
-
176
- def play_video(video_url):
177
- logging.debug(f"Playing video with URL: {video_url}")
178
- return show_video(video_url)
179
-
180
- search_button.click(update_search_results, inputs=search_query_input, outputs=[search_output, error_output, error_output])
181
- search_output.select(on_video_select, inputs=None, outputs=selected_video_link)
182
- play_video_button.click(play_video, inputs=selected_video_link, outputs=video_output)
183
-
184
- demo.launch()