Spaces:
Sleeping
Sleeping
File size: 5,700 Bytes
18c7580 d3a4b08 e995928 d3a4b08 1b93e2c d6d36d8 f5acdad d6d36d8 9ccb040 d6d36d8 d3a4b08 9ccb040 7150494 9ccb040 7150494 77631c6 9ccb040 a75fa95 9ccb040 e91bc53 9ccb040 d3a4b08 9ccb040 d3a4b08 0324f73 77631c6 0324f73 d3a4b08 9ccb040 664eb2d 0324f73 db9d378 9ccb040 d3a4b08 0ef74be 9ccb040 0ef74be 9ccb040 697a066 9ccb040 55a2077 18c7580 9ccb040 18c7580 d3a4b08 9ccb040 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 |
import gradio as gr
import requests
import os
import re
# Fetch the keys from the environment variable and convert them into a list
YOUTUBE_API_KEYS = os.getenv("YOUTUBE_API_KEYS")
if YOUTUBE_API_KEYS:
YOUTUBE_API_KEYS = [key.strip() for key in YOUTUBE_API_KEYS.split(",")]
else:
raise ValueError("API keys not found. Make sure the secret 'YOUTUBE_API_KEYS' is set.")
# Index to keep track of which API key to use
key_index = 0
def get_api_key():
global key_index
# Get the current API key and increment the index
api_key = YOUTUBE_API_KEYS[key_index]
key_index = (key_index + 1) % len(YOUTUBE_API_KEYS) # Rotate to the next key
return api_key
# Function to search YouTube videos using the API
def youtube_search(query, max_results=50):
search_url = "https://www.googleapis.com/youtube/v3/search"
all_results = []
params = {
"part": "snippet",
"q": query,
"type": "video",
"maxResults": 50 # YouTube API allows a maximum of 50 per request
}
try:
while len(all_results) < max_results:
params["key"] = get_api_key()
response = requests.get(search_url, params=params)
if response.status_code == 403 or response.status_code == 429:
print(f"Quota exceeded or forbidden for API key. Trying next key...")
continue
response.raise_for_status()
results = response.json().get("items", [])
for result in results:
video_info = {
'thumbnail_url': result["snippet"]["thumbnails"]["high"]["url"],
'video_id': result["id"]["videoId"],
'title': result["snippet"]["title"]
}
all_results.append(video_info)
if 'nextPageToken' not in response.json() or len(all_results) >= max_results:
break
params['pageToken'] = response.json()['nextPageToken']
return all_results
except requests.exceptions.RequestException as e:
print(f"Error during YouTube API request: {e}")
return [], f"Error retrieving video results: {str(e)}"
# Function to display the video using the video URL
def show_video(video_url):
video_id = None
patterns = [
r"youtube\.com/watch\?v=([^\&\?\/]+)",
r"youtube\.com/embed/([^\&\?\/]+)",
r"youtube\.com/v/([^\&\?\/]+)",
r"youtu\.be/([^\&\?\/]+)"
]
for pattern in patterns:
match = re.search(pattern, video_url)
if match:
video_id = match.group(1)
break
if not video_id:
return "Invalid YouTube URL. Please enter a valid YouTube video link."
embed_url = f"https://www.youtube.com/embed/{video_id}"
html_code = f'''
<iframe width="560" height="315" src="{embed_url}"
frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen></iframe>
'''
return html_code
# Create the Gradio interface
with gr.Blocks(css="""
#search_output {
max-width: 400px; /* Adjusts the maximum width of the gallery container */
}
#search_output img {
width: 150px !important; /* Adjusts the width of the images */
height: 150px !important;
margin-right: 10px;
}
#search_output .gallery-item {
display: flex !important;
align-items: center !important;
margin-bottom: 30px !important;
}
#search_output .gallery-caption {
text-align: left !important;
padding-left: 20px;
font-size: 24px !important;
}
""") as demo:
gr.Markdown("## YouTube Video Search, Selection, and Playback")
video_ids_state = gr.State() # To store video IDs corresponding to the search results
with gr.Row():
with gr.Column(scale=3):
search_query_input = gr.Textbox(label="Search YouTube",
placeholder="Enter your search query here",
elem_id="search_query_input") # Add elem_id to target in CSS
search_button = gr.Button("Search")
search_output = gr.Gallery(label="Search Results", columns=1, height="800px", elem_id="search_output")
with gr.Column(scale=2):
selected_video_link = gr.Textbox(label="Selected Video Link", interactive=False)
play_video_button = gr.Button("Play Video")
video_output = gr.HTML(label="Video Player")
# Update the search results and store video IDs
def update_search_results(query):
search_results = youtube_search(query)
gallery_items = []
video_ids = []
for item in search_results:
image_url = item['thumbnail_url']
title = item['title']
caption = f"{title}" # Display only the title as plain text
gallery_items.append((image_url, caption))
video_ids.append(item['video_id'])
return gallery_items, video_ids
# When a video is selected
def on_video_select(evt: gr.SelectData, video_ids):
index = evt.index
selected_video_id = video_ids[index]
video_url = f"https://www.youtube.com/watch?v={selected_video_id}"
return video_url
# Play the video
def play_video(video_url):
return show_video(video_url)
search_button.click(update_search_results, inputs=search_query_input, outputs=[search_output, video_ids_state])
search_output.select(on_video_select, inputs=video_ids_state, outputs=selected_video_link)
play_video_button.click(play_video, inputs=selected_video_link, outputs=video_output)
# Launch the Gradio interface
demo.launch()
|