mobenta commited on
Commit
d6d36d8
·
verified ·
1 Parent(s): f27cec4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +106 -6
app.py CHANGED
@@ -3,7 +3,93 @@ import requests
3
  import os
4
  import re
5
 
6
- # ... [previous code remains the same] ...
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
 
8
  # Create the Gradio interface
9
  with gr.Blocks(css="""
@@ -36,7 +122,7 @@ with gr.Blocks(css="""
36
  search_output = gr.HTML(label="Search Results")
37
 
38
  with gr.Column(scale=2):
39
- selected_video_link = gr.Textbox(label="Selected Video Link", interactive=False)
40
  play_video_button = gr.Button("Play Video")
41
  video_output = gr.HTML(label="Video Player")
42
 
@@ -60,10 +146,24 @@ with gr.Blocks(css="""
60
  '''
61
  html_code += '''
62
  <script>
 
 
 
 
 
 
 
 
 
63
  function selectVideo(video_id) {
64
- const videoLink = 'https://www.youtube.com/watch?v=' + video_id;
65
- document.querySelector('gradio-app').querySelector('#selected_video_link input').value = videoLink;
66
- document.querySelector('gradio-app').querySelector('#selected_video_link input').dispatchEvent(new Event('input', { bubbles: true }));
 
 
 
 
 
67
  }
68
  </script>
69
  '''
@@ -78,4 +178,4 @@ with gr.Blocks(css="""
78
  play_video_button.click(play_video, inputs=selected_video_link, outputs=video_output)
79
 
80
  # Launch the Gradio interface
81
- demo.launch()
 
3
  import os
4
  import re
5
 
6
+ # Fetch the keys from the environment variable and convert them into a list
7
+ YOUTUBE_API_KEYS = os.getenv("YOUTUBE_API_KEYS")
8
+
9
+ if YOUTUBE_API_KEYS:
10
+ YOUTUBE_API_KEYS = [key.strip() for key in YOUTUBE_API_KEYS.split(",")]
11
+ else:
12
+ raise ValueError("API keys not found. Make sure the secret 'YOUTUBE_API_KEYS' is set.")
13
+
14
+ # Index to keep track of which API key to use
15
+ key_index = 0
16
+
17
+ def get_api_key():
18
+ global key_index
19
+ # Get the current API key and increment the index
20
+ api_key = YOUTUBE_API_KEYS[key_index]
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 = []
28
+ params = {
29
+ "part": "snippet",
30
+ "q": query,
31
+ "type": "video",
32
+ "maxResults": 50 # YouTube API allows a maximum of 50 per request
33
+ }
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=([^\&\?\/]+)",
71
+ r"youtube\.com/embed/([^\&\?\/]+)",
72
+ r"youtube\.com/v/([^\&\?\/]+)",
73
+ r"youtu\.be/([^\&\?\/]+)"
74
+ ]
75
+
76
+ for pattern in patterns:
77
+ match = re.search(pattern, video_url)
78
+ if match:
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"
90
+ allowfullscreen></iframe>
91
+ '''
92
+ return html_code
93
 
94
  # Create the Gradio interface
95
  with gr.Blocks(css="""
 
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
 
 
146
  '''
147
  html_code += '''
148
  <script>
149
+ function getGradioApp() {
150
+ const gradioApp = document.querySelector('gradio-app');
151
+ if (gradioApp.shadowRoot) {
152
+ return gradioApp.shadowRoot;
153
+ } else {
154
+ return document;
155
+ }
156
+ }
157
+
158
  function selectVideo(video_id) {
159
+ const gradioApp = getGradioApp();
160
+ const textbox = gradioApp.querySelector('#selected_video_link textarea');
161
+ if (!textbox) {
162
+ console.error('Selected video link textbox not found');
163
+ return;
164
+ }
165
+ textbox.value = 'https://www.youtube.com/watch?v=' + video_id;
166
+ textbox.dispatchEvent(new Event('input', { bubbles: true }));
167
  }
168
  </script>
169
  '''
 
178
  play_video_button.click(play_video, inputs=selected_video_link, outputs=video_output)
179
 
180
  # Launch the Gradio interface
181
+ demo.launch()