mobenta commited on
Commit
3e07a33
·
verified ·
1 Parent(s): 1f858a2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +43 -62
app.py CHANGED
@@ -43,7 +43,7 @@ def youtube_search(query, upload_date, video_type, duration, max_results=50):
43
  "part": "snippet",
44
  "q": query,
45
  "maxResults": 50,
46
- "order": "relevance"
47
  }
48
 
49
  if upload_date:
@@ -63,62 +63,50 @@ def youtube_search(query, upload_date, video_type, duration, max_results=50):
63
  params["videoDuration"] = duration_mapping.get(duration, "any")
64
 
65
  try:
66
- params["key"] = get_api_key()
67
- response = requests.get(search_url, params=params)
68
-
69
- if response.status_code in [403, 429]:
70
- print(f"Quota exceeded or forbidden for API key. Trying next key...")
71
- return []
72
- response.raise_for_status()
73
-
74
- results = response.json().get("items", [])
75
- for result in results:
76
- if result["id"]["kind"] == "youtube#channel":
77
- # Return only the first channel result
78
- return [{
79
- 'thumbnail_url': result["snippet"]["thumbnails"]["high"]["url"],
80
- 'id': result["id"]["channelId"],
81
- 'title': result["snippet"]["title"],
82
- 'type': "channel"
83
- }]
84
- elif result["id"]["kind"] == "youtube#video":
85
- video_info = {
86
- 'thumbnail_url': result["snippet"]["thumbnails"]["high"]["url"],
87
- 'id': result["id"]["videoId"],
88
- 'title': result["snippet"]["title"],
89
- 'type': "video"
90
- }
 
 
 
 
 
 
 
 
 
 
91
  all_results.append(video_info)
92
 
93
- return all_results
 
94
 
95
- except requests.exceptions.RequestException as e:
96
- print(f"Error during YouTube API request: {e}")
97
- return []
98
 
99
- def get_channel_videos(channel_id, max_results=10):
100
- search_url = "https://www.googleapis.com/youtube/v3/search"
101
- params = {
102
- "part": "snippet",
103
- "channelId": channel_id,
104
- "maxResults": max_results,
105
- "order": "date",
106
- "type": "video",
107
- "key": get_api_key()
108
- }
109
- try:
110
- response = requests.get(search_url, params=params)
111
- response.raise_for_status()
112
- results = response.json().get("items", [])
113
- channel_videos = []
114
- for result in results:
115
- channel_videos.append({
116
- 'thumbnail_url': result["snippet"]["thumbnails"]["high"]["url"],
117
- 'id': result["id"]["videoId"],
118
- 'title': result["snippet"]["title"],
119
- 'type': "video"
120
- })
121
- return channel_videos
122
  except requests.exceptions.RequestException as e:
123
  print(f"Error during YouTube API request: {e}")
124
  return []
@@ -173,7 +161,6 @@ with gr.Blocks(css="""
173
  gr.Markdown("## YouTube Video Search, Selection, and Playback")
174
  video_ids_state = gr.State()
175
  video_types_state = gr.State()
176
- channel_mode_state = gr.State(False)
177
 
178
  with gr.Row(elem_id="video_container"):
179
  video_output = gr.HTML(label="Video Player", elem_id="video_output")
@@ -212,13 +199,7 @@ with gr.Blocks(css="""
212
  index = evt.index
213
  selected_video_id = video_ids[index]
214
  selected_video_type = video_types[index]
215
- if selected_video_type == "channel":
216
- # Fetch videos from the channel
217
- channel_videos = get_channel_videos(selected_video_id)
218
- gallery_items = [(video['thumbnail_url'], video['title']) for video in channel_videos]
219
- return gallery_items, video_ids, video_types
220
- else:
221
- return f"https://www.youtube.com/watch?v={selected_video_id}", selected_video_type
222
 
223
  def play_video(video_id, video_type):
224
  return show_video(video_id.split("=")[-1], video_type)
@@ -231,7 +212,7 @@ with gr.Blocks(css="""
231
  search_output.select(
232
  on_video_select,
233
  inputs=[video_ids_state, video_types_state],
234
- outputs=[search_output, video_ids_state, video_types_state]
235
  )
236
  play_video_button.click(
237
  play_video,
 
43
  "part": "snippet",
44
  "q": query,
45
  "maxResults": 50,
46
+ "order": "relevance" # Default ordering
47
  }
48
 
49
  if upload_date:
 
63
  params["videoDuration"] = duration_mapping.get(duration, "any")
64
 
65
  try:
66
+ while len(all_results) < max_results:
67
+ params["key"] = get_api_key()
68
+ response = requests.get(search_url, params=params)
69
+
70
+ if response.status_code in [403, 429]:
71
+ print(f"Quota exceeded or forbidden for API key. Trying next key...")
72
+ continue
73
+ response.raise_for_status()
74
+
75
+ results = response.json().get("items", [])
76
+ for result in results:
77
+ if result["id"]["kind"] == "youtube#video":
78
+ video_info = {
79
+ 'thumbnail_url': result["snippet"]["thumbnails"]["high"]["url"],
80
+ 'id': result["id"]["videoId"],
81
+ 'title': result["snippet"]["title"],
82
+ 'type': "video"
83
+ }
84
+ elif result["id"]["kind"] == "youtube#channel":
85
+ video_info = {
86
+ 'thumbnail_url': result["snippet"]["thumbnails"]["high"]["url"],
87
+ 'id': result["id"]["channelId"],
88
+ 'title': result["snippet"]["title"],
89
+ 'type': "channel"
90
+ }
91
+ elif result["id"]["kind"] == "youtube#playlist":
92
+ video_info = {
93
+ 'thumbnail_url': result["snippet"]["thumbnails"]["high"]["url"],
94
+ 'id': result["id"]["playlistId"],
95
+ 'title': result["snippet"]["title"],
96
+ 'type': "playlist"
97
+ }
98
+ else:
99
+ continue
100
+
101
  all_results.append(video_info)
102
 
103
+ if 'nextPageToken' not in response.json() or len(all_results) >= max_results:
104
+ break
105
 
106
+ params['pageToken'] = response.json()['nextPageToken']
107
+
108
+ return all_results
109
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110
  except requests.exceptions.RequestException as e:
111
  print(f"Error during YouTube API request: {e}")
112
  return []
 
161
  gr.Markdown("## YouTube Video Search, Selection, and Playback")
162
  video_ids_state = gr.State()
163
  video_types_state = gr.State()
 
164
 
165
  with gr.Row(elem_id="video_container"):
166
  video_output = gr.HTML(label="Video Player", elem_id="video_output")
 
199
  index = evt.index
200
  selected_video_id = video_ids[index]
201
  selected_video_type = video_types[index]
202
+ return f"https://www.youtube.com/watch?v={selected_video_id}", selected_video_type
 
 
 
 
 
 
203
 
204
  def play_video(video_id, video_type):
205
  return show_video(video_id.split("=")[-1], video_type)
 
212
  search_output.select(
213
  on_video_select,
214
  inputs=[video_ids_state, video_types_state],
215
+ outputs=[selected_video_link, selected_video_type]
216
  )
217
  play_video_button.click(
218
  play_video,