import gradio as gr import requests def check_key_gemini_availability(key): """ 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: 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' in result: return True, None else: return False, "Invalid key: 'models' field not found in response." except requests.exceptions.HTTPError as e: return False, f"Invalid key: HTTP error - {e.response.status_code}" except Exception as e: return False, f"Error: {e}" def check_keys(keys_text): """ 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) 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)") 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], outputs=[infos, errs], api_name="check_keys") demo.launch()