File size: 3,489 Bytes
ee416f4 2885319 ee416f4 fce4a54 ee416f4 fce4a54 2885319 676b862 429f146 2885319 fce4a54 1c6e5a1 fce4a54 07dca08 ee416f4 459544a fce4a54 ee416f4 07dca08 ee416f4 07dca08 ee416f4 2d1366e ee416f4 2d1366e ee416f4 c889167 ee416f4 2885319 ee416f4 |
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 |
import gradio as gr
import requests
def check_key_gemini_availability(key, ai_model):
"""
Checks the availability of a Gemini API key.
Args:
key: The API key to check.
Returns:
A tuple containing a boolean indicating whether the key is valid and an error message (or None if the key is valid).
"""
try:
# First, check if the key allows access to the list of models
url_getListModel = f"https://generativelanguage.googleapis.com/v1beta/models?key={key}"
rq = requests.get(url_getListModel)
rq.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
result = rq.json()
if 'models' not in result:
return False, f"Invalid key: 'models' field not found in response from list models endpoint."
# Second, attempt to generate content to further validate the key
ai_model_ = ai_model.strip() or "gemini-1.5-flash"
models = [ x["name"].split('/',1)[1] for x in result['models'] ]
if ai_model_ not in models:
return False, f"Specified model {ai_model_} is not in available 'models'."
url_generateContent = f"https://generativelanguage.googleapis.com/v1beta/models/{ai_model_}:generateContent?key={key}"
# headers = {'Content-Type': 'application/json'}
data = {"contents": [{"parts": [{"text": "Say \"this is a test\""}]}]}
rq = requests.post(url_generateContent, json=data) #headers=headers, data=json.dumps(data)
if 400 <= rq.status_code < 500:
return False, f"{rq.status_code}"
else:
# rq.raise_for_status() # Raise other errors for other status codes
print(key)
return True, None
except requests.exceptions.HTTPError as e:
return False, f"Invalid: HTTP {e.response.status_code} - {e}"
except Exception as e:
return False, f"Error: {e}"
def check_keys(keys_text, ai_model):
"""
Checks a list of Gemini API keys and categorizes them into valid and invalid.
Args:
keys_text: A string containing API keys separated by lines.
Returns:
A tuple containing two strings: a list of valid keys and a list of invalid keys with error messages.
"""
key_list = keys_text.strip().splitlines()
key_list = list(set(key_list)) # Remove duplicates
valid_keys = []
invalid_keys = []
for key in key_list:
is_valid, error_msg = check_key_gemini_availability(key, ai_model)
if is_valid:
valid_keys.append(key)
else:
invalid_keys.append(f"{key} - {error_msg}")
return "\n".join(valid_keys), "\n".join(invalid_keys)
def clear_inputs():
"""Clears the input text area."""
return ""
with gr.Blocks() as demo:
gr.Markdown('''
# Gemini API Key Status Checker - batch mode
''')
with gr.Row():
with gr.Column():
keys = gr.TextArea(label="API Keys (by lines)")
ai_model = gr.Textbox(label="gemini model")
with gr.Row():
clear_button = gr.Button("Clear")
submit_button = gr.Button("Submit", variant="primary")
with gr.Column():
infos = gr.TextArea(label="Alive Keys")
errs = gr.TextArea(label="Invalid Keys-status code")
clear_button.click(fn=clear_inputs, outputs=[keys])
submit_button.click(fn=check_keys, inputs=[keys,ai_model], outputs=[infos, errs], api_name="check_keys")
demo.launch() |