Spaces:
Sleeping
Sleeping
File size: 9,279 Bytes
18c7580 d3a4b08 e995928 d3a4b08 75f75bb 1b93e2c d6d36d8 75f75bb 6e2cebe d6d36d8 234f265 95c5405 d6d36d8 234f265 75f75bb 234f265 fa938bf 75f75bb 234f265 75f75bb 234f265 d6d36d8 95c5405 3e07a33 95c5405 3e07a33 d6d36d8 1f858a2 95c5405 fa938bf d6d36d8 234f265 d6d36d8 d3a4b08 9ccb040 7150494 234f265 7150494 9ccb040 234f265 77631c6 9ccb040 a75fa95 9ccb040 e91bc53 9ccb040 234f265 9ccb040 d3a4b08 234f265 ba3b1fd 234f265 ba3b1fd 234f265 d3a4b08 0324f73 77631c6 234f265 ba3b1fd 234f265 d3a4b08 9ccb040 95c5405 664eb2d 6e2cebe 9ccb040 fa938bf 0ef74be 9ccb040 697a066 234f265 697a066 fa938bf 9ccb040 fa938bf 9ccb040 fa938bf 95c5405 0d9d03d 95c5405 9ccb040 fa938bf 03c6b25 18c7580 ba3b1fd 6e2cebe ba3b1fd 0d9d03d ba3b1fd 18c7580 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 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 |
import gradio as gr
import requests
import os
import re
from datetime import datetime, timedelta
# 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
api_key = YOUTUBE_API_KEYS[key_index]
key_index = (key_index + 1) % len(YOUTUBE_API_KEYS) # Rotate to the next key
return api_key
def get_iso8601_date(time_frame):
now = datetime.utcnow()
if time_frame == "Last Hour":
return (now - timedelta(hours=1)).isoformat("T") + "Z"
elif time_frame == "Today":
return (now - timedelta(days=1)).isoformat("T") + "Z"
elif time_frame == "This Week":
return (now - timedelta(weeks=1)).isoformat("T") + "Z"
elif time_frame == "This Month":
return (now - timedelta(days=30)).isoformat("T") + "Z"
elif time_frame == "This Year":
return (now - timedelta(days=365)).isoformat("T") + "Z"
else:
return ""
def youtube_search(query, upload_date, video_type, duration, max_results=50):
search_url = "https://www.googleapis.com/youtube/v3/search"
all_results = []
params = {
"part": "snippet",
"q": query,
"maxResults": 50,
"order": "relevance"
}
if upload_date:
published_after = get_iso8601_date(upload_date)
if published_after:
params["publishedAfter"] = published_after
if video_type and video_type != "All":
params["type"] = video_type.lower()
if duration:
duration_mapping = {
"Short (<4 mins)": "short",
"Medium (4-20 mins)": "medium",
"Long (>20 mins)": "long"
}
params["videoDuration"] = duration_mapping.get(duration, "any")
try:
params["key"] = get_api_key()
response = requests.get(search_url, params=params)
if response.status_code in [403, 429]:
print(f"Quota exceeded or forbidden for API key. Trying next key...")
return []
response.raise_for_status()
results = response.json().get("items", [])
for result in results:
if result["id"]["kind"] == "youtube#video":
video_info = {
'thumbnail_url': result["snippet"]["thumbnails"]["high"]["url"],
'id': result["id"]["videoId"],
'title': result["snippet"]["title"],
'type': "video"
}
elif result["id"]["kind"] == "youtube#channel":
video_info = {
'thumbnail_url': result["snippet"]["thumbnails"]["high"]["url"],
'id': result["id"]["channelId"],
'title': result["snippet"]["title"],
'type': "channel"
}
elif result["id"]["kind"] == "youtube#playlist":
video_info = {
'thumbnail_url': result["snippet"]["thumbnails"]["high"]["url"],
'id': result["id"]["playlistId"],
'title': result["snippet"]["title"],
'type': "playlist"
}
else:
continue
all_results.append(video_info)
return all_results
except requests.exceptions.RequestException as e:
print(f"Error during YouTube API request: {e}")
return []
def get_channel_videos(channel_id, max_results=10):
search_url = "https://www.googleapis.com/youtube/v3/search"
params = {
"part": "snippet",
"channelId": channel_id,
"maxResults": max_results,
"order": "date",
"type": "video",
"key": get_api_key()
}
try:
response = requests.get(search_url, params=params)
response.raise_for_status()
results = response.json().get("items", [])
channel_videos = []
for result in results:
channel_videos.append({
'thumbnail_url': result["snippet"]["thumbnails"]["high"]["url"],
'id': result["id"]["videoId"],
'title': result["snippet"]["title"],
'type': "video"
})
return channel_videos
except requests.exceptions.RequestException as e:
print(f"Error during YouTube API request: {e}")
return []
def show_video(video_id, video_type):
if video_type == "video":
embed_url = f"https://www.youtube.com/embed/{video_id}"
elif video_type == "channel":
embed_url = f"https://www.youtube.com/channel/{video_id}"
elif video_type == "playlist":
embed_url = f"https://www.youtube.com/playlist?list={video_id}"
else:
return "Invalid YouTube URL. Please enter a valid YouTube video link."
html_code = f'''
<iframe width="100%" height="562" src="{embed_url}"
frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen></iframe>
'''
return html_code
with gr.Blocks(css="""
#search_output {
max-width: 1300px;
}
#search_output img {
width: 150px !important;
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;
}
#video_container {
display: flex;
justify-content: center;
align-items: center;
max-width: 1500px;
margin: 0 auto;
padding: 20px;
background-color: #f9f9f9;
border-radius: 8px;
}
""") as demo:
gr.Markdown("## YouTube Video Search, Selection, and Playback")
video_ids_state = gr.State()
video_types_state = gr.State()
with gr.Row(elem_id="video_container"):
video_output = gr.HTML(label="Video Player", elem_id="video_output")
with gr.Row():
selected_video_link = gr.Textbox(label="Selected Video Link", interactive=False)
selected_video_type = gr.Textbox(label="Selected Video Type", visible=False, interactive=False)
play_video_button = gr.Button("Play Video")
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")
upload_date_input = gr.Dropdown(label="Upload Date", choices=["", "Last Hour", "Today", "This Week", "This Month", "This Year"])
video_type_input = gr.Dropdown(label="Type", choices=["All", "Video", "Channel", "Playlist"])
duration_input = gr.Dropdown(label="Duration", choices=["", "Short (<4 mins)", "Medium (4-20 mins)", "Long (>20 mins)"])
search_button = gr.Button("Search")
search_output = gr.Gallery(label="Search Results", columns=1, height="800px", elem_id="search_output")
channel_videos_output = gr.Gallery(label="Channel Videos", columns=1, height="800px", visible=False)
def update_search_results(query, upload_date, video_type, duration):
search_results = youtube_search(query, upload_date, video_type, duration)
gallery_items = []
video_ids = []
video_types = []
for item in search_results:
image_url = item['thumbnail_url']
title = item['title']
caption = f"{title}"
gallery_items.append((image_url, caption))
video_ids.append(item['id'])
video_types.append(item['type'])
return gallery_items, video_ids, video_types
def on_video_select(evt: gr.SelectData, video_ids, video_types):
index = evt.index
selected_video_id = video_ids[index]
selected_video_type = video_types[index]
if selected_video_type == "channel":
# Fetch videos from the channel
channel_videos = get_channel_videos(selected_video_id)
gallery_items = [(video['thumbnail_url'], video['title']) for video in channel_videos]
return gallery_items, video_ids, video_types
else:
return f"https://www.youtube.com/watch?v={selected_video_id}", selected_video_type
def play_video(video_id, video_type):
return show_video(video_id.split("=")[-1], video_type)
search_button.click(
update_search_results,
inputs=[search_query_input, upload_date_input, video_type_input, duration_input],
outputs=[search_output, video_ids_state, video_types_state]
)
search_output.select(
on_video_select,
inputs=[video_ids_state, video_types_state],
outputs=[selected_video_link, selected_video_type]
)
play_video_button.click(
play_video,
inputs=[selected_video_link, selected_video_type],
outputs=video_output
)
demo.launch()
|