Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -21,7 +21,7 @@ def get_api_key():
|
|
21 |
key_index = (key_index + 1) % len(YOUTUBE_API_KEYS) # Rotate to the next key
|
22 |
return api_key
|
23 |
|
24 |
-
# Function to search YouTube videos using the API
|
25 |
def youtube_search(query, max_results=50):
|
26 |
search_url = "https://www.googleapis.com/youtube/v3/search"
|
27 |
all_results = []
|
@@ -34,42 +34,37 @@ def youtube_search(query, max_results=50):
|
|
34 |
|
35 |
try:
|
36 |
while len(all_results) < max_results:
|
37 |
-
params["key"] = get_api_key()
|
38 |
response = requests.get(search_url, params=params)
|
39 |
|
40 |
-
# If we get a bad response, try the next API key
|
41 |
if response.status_code == 403 or response.status_code == 429:
|
42 |
print(f"Quota exceeded or forbidden for API key. Trying next key...")
|
43 |
continue
|
44 |
-
response.raise_for_status()
|
45 |
|
46 |
results = response.json().get("items", [])
|
47 |
for result in results:
|
48 |
video_info = {
|
49 |
-
'thumbnail_url': result["snippet"]["thumbnails"]["
|
50 |
'video_id': result["id"]["videoId"],
|
51 |
'title': result["snippet"]["title"],
|
52 |
'description': result["snippet"]["description"]
|
53 |
}
|
54 |
all_results.append(video_info)
|
55 |
|
56 |
-
# If there is no nextPageToken, we've reached the end
|
57 |
if 'nextPageToken' not in response.json() or len(all_results) >= max_results:
|
58 |
break
|
59 |
|
60 |
-
# Update params with the nextPageToken to get the next batch of results
|
61 |
params['pageToken'] = response.json()['nextPageToken']
|
62 |
|
63 |
return all_results
|
64 |
|
65 |
except requests.exceptions.RequestException as e:
|
66 |
-
# Print the error message to help debug issues
|
67 |
print(f"Error during YouTube API request: {e}")
|
68 |
return [], f"Error retrieving video results: {str(e)}"
|
69 |
|
70 |
# Function to display the video using the video URL
|
71 |
def show_video(video_url):
|
72 |
-
# Regular expression to extract the YouTube video ID from the URL
|
73 |
video_id = None
|
74 |
patterns = [
|
75 |
r"youtube\.com/watch\?v=([^\&\?\/]+)",
|
@@ -84,14 +79,11 @@ def show_video(video_url):
|
|
84 |
video_id = match.group(1)
|
85 |
break
|
86 |
|
87 |
-
# If no video ID is found, return an error message
|
88 |
if not video_id:
|
89 |
return "Invalid YouTube URL. Please enter a valid YouTube video link."
|
90 |
|
91 |
-
# Create the embed URL
|
92 |
embed_url = f"https://www.youtube.com/embed/{video_id}"
|
93 |
|
94 |
-
# Return an iframe with the video
|
95 |
html_code = f'''
|
96 |
<iframe width="560" height="315" src="{embed_url}"
|
97 |
frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
|
@@ -100,48 +92,82 @@ def show_video(video_url):
|
|
100 |
return html_code
|
101 |
|
102 |
# Create the Gradio interface
|
103 |
-
with gr.Blocks(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
104 |
gr.Markdown("## YouTube Video Search, Selection, and Playback")
|
105 |
-
video_ids_state = gr.State() # To store video IDs corresponding to the search results
|
106 |
|
107 |
with gr.Row():
|
108 |
with gr.Column(scale=3):
|
109 |
search_query_input = gr.Textbox(label="Search YouTube", placeholder="Enter your search query here")
|
110 |
search_button = gr.Button("Search")
|
111 |
-
search_output = gr.
|
112 |
-
|
113 |
with gr.Column(scale=2):
|
114 |
-
selected_video_link = gr.Textbox(label="Selected Video Link", interactive=False)
|
115 |
play_video_button = gr.Button("Play Video")
|
116 |
video_output = gr.HTML(label="Video Player")
|
117 |
|
118 |
-
#
|
119 |
def update_search_results(query):
|
120 |
search_results = youtube_search(query)
|
121 |
-
|
122 |
-
video_ids = []
|
123 |
for item in search_results:
|
124 |
-
|
|
|
125 |
title = item['title']
|
126 |
description = item['description']
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
140 |
def play_video(video_url):
|
141 |
return show_video(video_url)
|
142 |
|
143 |
-
search_button.click(update_search_results, inputs=search_query_input, outputs=
|
144 |
-
search_output.select(on_video_select, inputs=video_ids_state, outputs=selected_video_link)
|
145 |
play_video_button.click(play_video, inputs=selected_video_link, outputs=video_output)
|
146 |
|
147 |
# Launch the Gradio interface
|
|
|
21 |
key_index = (key_index + 1) % len(YOUTUBE_API_KEYS) # Rotate to the next key
|
22 |
return api_key
|
23 |
|
24 |
+
# Function to search YouTube videos using the API
|
25 |
def youtube_search(query, max_results=50):
|
26 |
search_url = "https://www.googleapis.com/youtube/v3/search"
|
27 |
all_results = []
|
|
|
34 |
|
35 |
try:
|
36 |
while len(all_results) < max_results:
|
37 |
+
params["key"] = get_api_key()
|
38 |
response = requests.get(search_url, params=params)
|
39 |
|
|
|
40 |
if response.status_code == 403 or response.status_code == 429:
|
41 |
print(f"Quota exceeded or forbidden for API key. Trying next key...")
|
42 |
continue
|
43 |
+
response.raise_for_status()
|
44 |
|
45 |
results = response.json().get("items", [])
|
46 |
for result in results:
|
47 |
video_info = {
|
48 |
+
'thumbnail_url': result["snippet"]["thumbnails"]["high"]["url"],
|
49 |
'video_id': result["id"]["videoId"],
|
50 |
'title': result["snippet"]["title"],
|
51 |
'description': result["snippet"]["description"]
|
52 |
}
|
53 |
all_results.append(video_info)
|
54 |
|
|
|
55 |
if 'nextPageToken' not in response.json() or len(all_results) >= max_results:
|
56 |
break
|
57 |
|
|
|
58 |
params['pageToken'] = response.json()['nextPageToken']
|
59 |
|
60 |
return all_results
|
61 |
|
62 |
except requests.exceptions.RequestException as e:
|
|
|
63 |
print(f"Error during YouTube API request: {e}")
|
64 |
return [], f"Error retrieving video results: {str(e)}"
|
65 |
|
66 |
# Function to display the video using the video URL
|
67 |
def show_video(video_url):
|
|
|
68 |
video_id = None
|
69 |
patterns = [
|
70 |
r"youtube\.com/watch\?v=([^\&\?\/]+)",
|
|
|
79 |
video_id = match.group(1)
|
80 |
break
|
81 |
|
|
|
82 |
if not video_id:
|
83 |
return "Invalid YouTube URL. Please enter a valid YouTube video link."
|
84 |
|
|
|
85 |
embed_url = f"https://www.youtube.com/embed/{video_id}"
|
86 |
|
|
|
87 |
html_code = f'''
|
88 |
<iframe width="560" height="315" src="{embed_url}"
|
89 |
frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
|
|
|
92 |
return html_code
|
93 |
|
94 |
# Create the Gradio interface
|
95 |
+
with gr.Blocks(css="""
|
96 |
+
.search-item {
|
97 |
+
display: flex;
|
98 |
+
align-items: flex-start;
|
99 |
+
margin-bottom: 30px;
|
100 |
+
cursor: pointer;
|
101 |
+
}
|
102 |
+
.search-item img {
|
103 |
+
width: 300px;
|
104 |
+
height: auto;
|
105 |
+
margin-right: 20px;
|
106 |
+
}
|
107 |
+
.search-item h3 {
|
108 |
+
font-size: 24px;
|
109 |
+
margin: 0 0 10px 0;
|
110 |
+
}
|
111 |
+
.search-item p {
|
112 |
+
font-size: 18px;
|
113 |
+
margin: 0;
|
114 |
+
}
|
115 |
+
""") as demo:
|
116 |
gr.Markdown("## YouTube Video Search, Selection, and Playback")
|
|
|
117 |
|
118 |
with gr.Row():
|
119 |
with gr.Column(scale=3):
|
120 |
search_query_input = gr.Textbox(label="Search YouTube", placeholder="Enter your search query here")
|
121 |
search_button = gr.Button("Search")
|
122 |
+
search_output = gr.HTML(label="Search Results")
|
123 |
+
|
124 |
with gr.Column(scale=2):
|
125 |
+
selected_video_link = gr.Textbox(label="Selected Video Link", interactive=False, elem_id='selected_video_link')
|
126 |
play_video_button = gr.Button("Play Video")
|
127 |
video_output = gr.HTML(label="Video Player")
|
128 |
|
129 |
+
# Define search button behavior
|
130 |
def update_search_results(query):
|
131 |
search_results = youtube_search(query)
|
132 |
+
html_code = '<div>'
|
|
|
133 |
for item in search_results:
|
134 |
+
video_id = item['video_id']
|
135 |
+
thumbnail_url = item['thumbnail_url']
|
136 |
title = item['title']
|
137 |
description = item['description']
|
138 |
+
html_code += f'''
|
139 |
+
<div class="search-item" onclick="selectVideo('{video_id}')">
|
140 |
+
<img src="{thumbnail_url}" alt="{title}">
|
141 |
+
<div>
|
142 |
+
<h3>{title}</h3>
|
143 |
+
<p>{description}</p>
|
144 |
+
</div>
|
145 |
+
</div>
|
146 |
+
'''
|
147 |
+
html_code += '''
|
148 |
+
<script>
|
149 |
+
function getGradioApp() {
|
150 |
+
const elems = document.getElementsByTagName('gradio-app');
|
151 |
+
const gradioShadowRoot = elems.length == 0 ? null : elems[0].shadowRoot;
|
152 |
+
return gradioShadowRoot ? gradioShadowRoot : document;
|
153 |
+
}
|
154 |
+
|
155 |
+
function selectVideo(video_id) {
|
156 |
+
const gradioApp = getGradioApp();
|
157 |
+
const textbox = gradioApp.querySelector('#selected_video_link textarea');
|
158 |
+
textbox.value = 'https://www.youtube.com/watch?v=' + video_id;
|
159 |
+
textbox.dispatchEvent(new Event('input', { bubbles: true }));
|
160 |
+
}
|
161 |
+
</script>
|
162 |
+
'''
|
163 |
+
html_code += '</div>'
|
164 |
+
return html_code
|
165 |
+
|
166 |
+
# Play the video when the Play Video button is clicked
|
167 |
def play_video(video_url):
|
168 |
return show_video(video_url)
|
169 |
|
170 |
+
search_button.click(update_search_results, inputs=search_query_input, outputs=search_output)
|
|
|
171 |
play_video_button.click(play_video, inputs=selected_video_link, outputs=video_output)
|
172 |
|
173 |
# Launch the Gradio interface
|