Spaces:
Runtime error
Runtime error
Download api_manager.py from SG34/video_analyzer_simple: direct link, hf CLI and curl.
- Browser
- Download file 2.32 kB
-
https://huggingface.co/spaces/SG34/video_analyzer_simple/resolve/main/api_manager.py
- Command line
-
hf download hf://spaces/SG34/video_analyzer_simple/api_manager.py
-
curl -L -o api_manager.py https://huggingface.co/spaces/SG34/video_analyzer_simple/resolve/main/api_manager.py
2.32 kB
| import os | |
| from typing import Optional | |
| import google.generativeai as genai | |
| class APIManager: | |
| def __init__(self): | |
| self.api_keys = [] | |
| self.current_index = 0 | |
| self.error_count = {} | |
| # μ¬μ© κ°λ₯ν API ν€λ€ λ‘λ | |
| for i in range(1, 4): | |
| key = os.getenv(f"GEMINI_API_KEY_{i}") | |
| if key and len(key) > 10: | |
| self.api_keys.append(key) | |
| self.error_count[key] = 0 | |
| print(f"π λ°κ²¬λ API ν€: {len(self.api_keys)}κ°") | |
| def get_next_api_key(self) -> Optional[str]: | |
| """λΌμ΄λ λ‘λΉ λ°©μμΌλ‘ API ν€ μν""" | |
| if not self.api_keys: | |
| return None | |
| key = self.api_keys[self.current_index] | |
| self.current_index = (self.current_index + 1) % len(self.api_keys) | |
| return key | |
| def get_best_api_key(self) -> Optional[str]: | |
| """μλ¬κ° κ°μ₯ μ μ API ν€ λ°ν""" | |
| if not self.api_keys: | |
| return None | |
| # μλ¬κ° μ μ ν€λ€λ§ νν°λ§ | |
| available_keys = [k for k in self.api_keys if self.error_count[k] < 3] | |
| if not available_keys: | |
| # λͺ¨λ ν€κ° μλ¬κ° λ§μΌλ©΄ μλ¬ μΉ΄μ΄νΈ 리μ | |
| for k in self.api_keys: | |
| self.error_count[k] = 0 | |
| available_keys = self.api_keys | |
| # μλ¬κ° κ°μ₯ μ μ ν€ λ°ν | |
| return min(available_keys, key=lambda k: self.error_count[k]) | |
| def report_error(self, api_key: str): | |
| """API ν€μμ μλ¬ λ°μ μ νΈμΆ""" | |
| if api_key in self.error_count: | |
| self.error_count[api_key] += 1 | |
| print(f"β API μλ¬ λ°μ: {api_key[:10]}... (μλ¬ νμ: {self.error_count[api_key]})") | |
| def test_api_key(self, api_key: str) -> bool: | |
| """API ν€κ° μλνλμ§ ν μ€νΈ""" | |
| try: | |
| genai.configure(api_key=api_key) | |
| model = genai.GenerativeModel('gemini-2.5-flash-preview-05-20') | |
| response = model.generate_content("Hi") | |
| return bool(response.text) | |
| except Exception as e: | |
| print(f"API ν μ€νΈ μ€ν¨: {e}") | |
| self.report_error(api_key) | |
| return False |