tx3bas commited on
Commit
daee03b
·
verified ·
1 Parent(s): 9add12e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +102 -132
app.py CHANGED
@@ -1,180 +1,149 @@
1
  import gradio as gr
2
  from groq import Groq
3
  import openai
4
- import google.generativeai as genai
5
  import requests
6
  import json
 
 
7
  from googleapiclient.discovery import build
8
- from PIL import Image
9
- from io import BytesIO
10
 
11
 
12
- # Función para inicializar el cliente de Groq con la API key proporcionada
13
- def create_groq_client(api_key):
14
- return Groq(api_key=api_key)
15
-
16
- # Función para verificar la API de Groq
17
  def verificar_api_groq(api_key):
18
- client = create_groq_client(api_key)
19
- messages = [
20
- {"role": "user", "content": "Hola"}
21
- ]
22
-
23
  try:
 
24
  completion = client.chat.completions.create(
25
- messages=messages,
26
- model="llama3-70b-8192",
27
- temperature=0.7,
28
- max_tokens=200,
29
- top_p=0.9,
30
- stream=False
 
 
31
  )
32
- return True # API válida
33
- except Exception:
34
- return False # API inválida
35
 
36
- # Función para verificar la API de OpenAI
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  def verificar_api_openai(api_key):
38
  openai.api_key = api_key
39
  try:
40
  response = openai.ChatCompletion.create(
41
  model="gpt-3.5-turbo",
42
- messages=[
43
- {"role": "user", "content": "Hola"}
44
- ],
45
  max_tokens=50,
46
  temperature=0.7
47
  )
48
- return True # API válida
49
- except openai.OpenAIError:
50
- return False # API inválida
51
  except Exception:
52
- return False # API inválida
53
 
54
- # Función para verificar la API de Google Gemini
55
- def verificar_api_gemini(api_key):
56
- try:
57
- # Configurar la API de Google Gemini
58
- genai.configure(api_key=api_key)
59
- model = genai.GenerativeModel('gemini-1.5-pro')
60
- response = model.generate_content("Test message")
61
- return response is not None # API válida si hay respuesta
62
- except Exception:
63
- return False # API inválida
64
 
65
- # Función para verificar la API de OpenRouter
66
  def verificar_api_openrouter(api_key):
67
  url = "https://openrouter.ai/api/v1/chat/completions"
68
- headers = {
69
- "Authorization": f"Bearer {api_key}",
70
- "Content-Type": "application/json"
71
- }
72
  data = {
73
  "model": "google/gemma-2-9b-it:free",
74
- "messages": [
75
- {
76
- "role": "user",
77
- "content": "What is the meaning of life?"
78
- }
79
- ]
80
  }
81
 
82
  try:
83
- response = requests.post(url, headers=headers, data=json.dumps(data))
84
- if response.status_code == 200:
85
- return True # API válida
86
- else:
87
- return False # API inválida
88
  except Exception:
89
- return False # API inválida
 
90
 
91
- # Función para verificar la API de YouTube
92
  def verificar_api_youtube(api_key):
93
  try:
94
- # Configurar el cliente de la API de YouTube
95
  youtube = build("youtube", "v3", developerKey=api_key)
96
-
97
- # Realizar una solicitud de búsqueda para comprobar si la API funciona
98
- search_response = youtube.search().list(
99
- q="test",
100
- part="snippet",
101
- maxResults=1
102
- ).execute()
103
-
104
- # Si se obtiene una respuesta sin errores, la API es válida
105
- return bool(search_response.get("items", []))
106
  except Exception:
107
- return False # API inválida
 
108
 
109
- # Función para verificar la API de Pexels
110
  def verificar_api_pexels(api_key):
111
  try:
112
  url = "https://api.pexels.com/v1/search"
113
- headers = {
114
- "Authorization": api_key
115
- }
116
- params = {
117
- "query": "nature",
118
- "per_page": 1
119
- }
120
-
121
- response = requests.get(url, headers=headers, params=params)
122
-
123
- # Si la respuesta es exitosa, la API es válida
124
- if response.status_code == 200:
125
- data = response.json()
126
- return "photos" in data and len(data["photos"]) > 0
127
- else:
128
- return False # API inválida
129
  except Exception:
130
- return False # API inválida
 
131
 
132
- # Función para verificar la API de Google Places
133
  def verificar_api_google_places(api_key):
134
  try:
135
  url = "https://maps.googleapis.com/maps/api/place/textsearch/json"
136
- params = {
137
- "query": "restaurants",
138
- "location": "0,0",
139
- "radius": 1000,
140
- "key": api_key
141
- }
142
-
143
- response = requests.get(url, params=params)
144
-
145
- # Si la respuesta es exitosa, la API es válida
146
- if response.status_code == 200:
147
- data = response.json()
148
- return "results" in data and len(data["results"]) > 0
149
- else:
150
- return False # API inválida
151
  except Exception:
152
- return False # API inválida
 
153
 
154
- # Función para verificar la API de Unsplash
155
  def verificar_api_unsplash(api_key):
156
  try:
157
  url = "https://api.unsplash.com/search/photos"
158
- headers = {
159
- "Authorization": f"Client-ID {api_key}"
160
- }
161
- params = {
162
- "query": "nature",
163
- "per_page": 1
164
- }
165
-
166
- response = requests.get(url, headers=headers, params=params)
167
-
168
- # Si la respuesta es exitosa, la API es válida
169
- if response.status_code == 200:
170
- data = response.json()
171
- return "results" in data and len(data["results"]) > 0
172
- else:
173
- return False # API inválida
174
  except Exception:
175
- return False # API inválida
176
 
177
- # Función general para verificar una lista de API keys
 
178
  def verificar_apis(api_keys_text, api_type):
179
  api_keys = api_keys_text.strip().split("\n")
180
  apis_validas = []
@@ -204,28 +173,29 @@ def verificar_apis(api_keys_text, api_type):
204
  else:
205
  continue
206
 
207
- # Clasificar las APIs en válidas o inválidas
208
  if es_valida:
209
  apis_validas.append(api_key)
210
  else:
211
  apis_invalidas.append(api_key)
212
 
213
- # Formatear el resultado final con las secciones separadas
214
- resultado_final = "✅ APIs válidas:\n" + "\n".join(apis_validas) + "\n\n⛔ APIs inválidas:\n" + "\n".join(apis_invalidas)
 
 
215
  return resultado_final
216
 
217
- # Interfaz de Gradio
 
218
  iface = gr.Interface(
219
  fn=verificar_apis,
220
  inputs=[
221
- gr.Textbox(label="API Keys (una por línea)", lines=10, placeholder="Introduce cada API key en una línea diferente..."),
222
  gr.Radio(["Groq", "OpenAI", "Google Gemini", "OpenRouter", "YouTube", "Pexels", "Google Places", "Unsplash"], label="Tipo de API")
223
  ],
224
  outputs="text",
225
- title="Verificación de Múltiples APIs (Groq, OpenAI, Google Gemini, OpenRouter, YouTube, Pexels, Google Places, Unsplash)",
226
- description="Ingresa una lista de API keys (una por línea) y selecciona el tipo de API para verificar cuáles están disponibles."
227
  )
228
 
229
- # Ejecutar la interfaz en Hugging Face Space
230
  if __name__ == "__main__":
231
  iface.launch()
 
1
  import gradio as gr
2
  from groq import Groq
3
  import openai
 
4
  import requests
5
  import json
6
+ from google import genai
7
+ from google.genai import types
8
  from googleapiclient.discovery import build
 
 
9
 
10
 
11
+ # ---- VERIFICACIÓN GROQ ----
 
 
 
 
12
  def verificar_api_groq(api_key):
 
 
 
 
 
13
  try:
14
+ client = Groq(api_key=api_key)
15
  completion = client.chat.completions.create(
16
+ model="openai/gpt-oss-20b",
17
+ messages=[{"role": "user", "content": "hola"}],
18
+ temperature=1,
19
+ max_completion_tokens=50,
20
+ top_p=1,
21
+ reasoning_effort="medium",
22
+ stream=False,
23
+ stop=None
24
  )
 
 
 
25
 
26
+ # Verifica que haya texto en la respuesta
27
+ if completion.choices and completion.choices[0].message.content:
28
+ return True
29
+ return False
30
+ except Exception as e:
31
+ print("Error en Groq:", e)
32
+ return False
33
+
34
+
35
+ # ---- VERIFICACIÓN GEMINI (nuevo SDK google-genai) ----
36
+ def verificar_api_gemini(api_key):
37
+ try:
38
+ client = genai.Client(api_key=api_key)
39
+ model = "gemini-2.5-pro"
40
+
41
+ contents = [
42
+ types.Content(
43
+ role="user",
44
+ parts=[types.Part.from_text(text="Hola")]
45
+ )
46
+ ]
47
+
48
+ generate_content_config = types.GenerateContentConfig(
49
+ thinking_config=types.ThinkingConfig(thinking_budget=-1)
50
+ )
51
+
52
+ # No usamos streaming para solo testear
53
+ response = client.models.generate_content(
54
+ model=model,
55
+ contents=contents,
56
+ config=generate_content_config
57
+ )
58
+
59
+ # Si hay texto, la API es válida
60
+ return bool(response.candidates and response.candidates[0].content.parts[0].text.strip())
61
+ except Exception as e:
62
+ print("Error en Gemini:", e)
63
+ return False
64
+
65
+
66
+ # ---- RESTO DE FUNCIONES IGUALES ----
67
  def verificar_api_openai(api_key):
68
  openai.api_key = api_key
69
  try:
70
  response = openai.ChatCompletion.create(
71
  model="gpt-3.5-turbo",
72
+ messages=[{"role": "user", "content": "Hola"}],
 
 
73
  max_tokens=50,
74
  temperature=0.7
75
  )
76
+ return True
 
 
77
  except Exception:
78
+ return False
79
 
 
 
 
 
 
 
 
 
 
 
80
 
 
81
  def verificar_api_openrouter(api_key):
82
  url = "https://openrouter.ai/api/v1/chat/completions"
83
+ headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}
 
 
 
84
  data = {
85
  "model": "google/gemma-2-9b-it:free",
86
+ "messages": [{"role": "user", "content": "What is the meaning of life?"}]
 
 
 
 
 
87
  }
88
 
89
  try:
90
+ r = requests.post(url, headers=headers, data=json.dumps(data))
91
+ return r.status_code == 200
 
 
 
92
  except Exception:
93
+ return False
94
+
95
 
 
96
  def verificar_api_youtube(api_key):
97
  try:
 
98
  youtube = build("youtube", "v3", developerKey=api_key)
99
+ resp = youtube.search().list(q="test", part="snippet", maxResults=1).execute()
100
+ return bool(resp.get("items", []))
 
 
 
 
 
 
 
 
101
  except Exception:
102
+ return False
103
+
104
 
 
105
  def verificar_api_pexels(api_key):
106
  try:
107
  url = "https://api.pexels.com/v1/search"
108
+ headers = {"Authorization": api_key}
109
+ params = {"query": "nature", "per_page": 1}
110
+ r = requests.get(url, headers=headers, params=params)
111
+ if r.status_code == 200:
112
+ d = r.json()
113
+ return "photos" in d and len(d["photos"]) > 0
114
+ return False
 
 
 
 
 
 
 
 
 
115
  except Exception:
116
+ return False
117
+
118
 
 
119
  def verificar_api_google_places(api_key):
120
  try:
121
  url = "https://maps.googleapis.com/maps/api/place/textsearch/json"
122
+ params = {"query": "restaurants", "location": "0,0", "radius": 1000, "key": api_key}
123
+ r = requests.get(url, params=params)
124
+ if r.status_code == 200:
125
+ d = r.json()
126
+ return "results" in d and len(d["results"]) > 0
127
+ return False
 
 
 
 
 
 
 
 
 
128
  except Exception:
129
+ return False
130
+
131
 
 
132
  def verificar_api_unsplash(api_key):
133
  try:
134
  url = "https://api.unsplash.com/search/photos"
135
+ headers = {"Authorization": f"Client-ID {api_key}"}
136
+ params = {"query": "nature", "per_page": 1}
137
+ r = requests.get(url, headers=headers, params=params)
138
+ if r.status_code == 200:
139
+ d = r.json()
140
+ return "results" in d and len(d["results"]) > 0
141
+ return False
 
 
 
 
 
 
 
 
 
142
  except Exception:
143
+ return False
144
 
145
+
146
+ # ---- VERIFICADOR GENERAL ----
147
  def verificar_apis(api_keys_text, api_type):
148
  api_keys = api_keys_text.strip().split("\n")
149
  apis_validas = []
 
173
  else:
174
  continue
175
 
 
176
  if es_valida:
177
  apis_validas.append(api_key)
178
  else:
179
  apis_invalidas.append(api_key)
180
 
181
+ resultado_final = (
182
+ "✅ APIs válidas:\n" + "\n".join(apis_validas) +
183
+ "\n\n⛔ APIs inválidas:\n" + "\n".join(apis_invalidas)
184
+ )
185
  return resultado_final
186
 
187
+
188
+ # ---- INTERFAZ ----
189
  iface = gr.Interface(
190
  fn=verificar_apis,
191
  inputs=[
192
+ gr.Textbox(label="API Keys (una por línea)", lines=10, placeholder="Introduce cada API key..."),
193
  gr.Radio(["Groq", "OpenAI", "Google Gemini", "OpenRouter", "YouTube", "Pexels", "Google Places", "Unsplash"], label="Tipo de API")
194
  ],
195
  outputs="text",
196
+ title="Verificación de APIs (Groq, OpenAI, Gemini, etc.)",
197
+ description="Comprueba si tus API keys siguen activas y funcionando."
198
  )
199
 
 
200
  if __name__ == "__main__":
201
  iface.launch()