Download anime-2d-reference-kit/engine/modules/client.py from DenSnoychik/ArenaAISpace: direct link, hf CLI and curl.
- Browser
- Download file 6.21 kB
-
https://huggingface.co/datasets/DenSnoychik/ArenaAISpace/resolve/main/anime-2d-reference-kit/engine/modules/client.py
- Command line
-
hf download hf://datasets/DenSnoychik/ArenaAISpace/anime-2d-reference-kit/engine/modules/client.py
-
curl -L -o client.py https://huggingface.co/datasets/DenSnoychik/ArenaAISpace/resolve/main/anime-2d-reference-kit/engine/modules/client.py
6.21 kB
| # ========================================================== | |
| # MODULES / CLIENT.PY | |
| # Клиент Gemini API с умной ротацией ключей и фильтрацией ошибок | |
| # ========================================================== | |
| import re | |
| import requests | |
| import config | |
| def get_all_api_keys() -> list[str]: | |
| raw = getattr(config, "API_KEY", []) | |
| if isinstance(raw, list): | |
| keys = [str(k).strip() for k in raw if str(k).strip()] | |
| if keys: | |
| return keys | |
| elif isinstance(raw, str) and raw.strip(): | |
| return [raw.strip()] | |
| raise ValueError("Задайте переменную GEMINI_API_KEY.") | |
| def extract_code_block(text: str) -> str: | |
| text = text.strip() | |
| match = re.search(r"```(?:python|json)?\s*([\s\S]*?)\s*```", text, flags=re.IGNORECASE) | |
| if match: | |
| return match.group(1).strip() | |
| clean = re.sub(r"^```(?:python|json)?\s*", "", text, flags=re.IGNORECASE) | |
| clean = re.sub(r"\s*```$", "", clean).strip() | |
| return clean | |
| def is_google_side_error(status_code: int, response_text: str) -> bool: | |
| """Определяет, относится ли ошибка к стороне Google/Ключа или это локальная ошибка.""" | |
| if status_code in (429, 500, 502, 503, 504, 524): | |
| return True | |
| if status_code == 403: | |
| # Исчерпан лимит или ключ заблокирован | |
| return True | |
| if status_code == 400: | |
| err_lower = response_text.lower() | |
| if any(w in err_lower for w in ["api_key_invalid", "key expired", "api key not valid", "quota", "resource_exhausted"]): | |
| return True | |
| return False | |
| def call_gemini(system_prompt: str, user_prompt: str, model: str = None, thinking: bool = True, images: list = None) -> str: | |
| keys = get_all_api_keys() | |
| selected_model = model or getattr(config, "MODEL_NAME", "gemini-3.5-flash-lite") | |
| proxy_url = getattr(config, "PROXY_URL", "").strip() | |
| base_url = proxy_url.rstrip("/") if proxy_url else "https://generativelanguage.googleapis.com" | |
| proxies = getattr(config, "PROXIES", None) | |
| parts = [{"text": f"{system_prompt}\n\nUSER REQUEST: {user_prompt}"}] | |
| if images and isinstance(images, list): | |
| for img in images[:10]: | |
| if isinstance(img, dict) and "data" in img and "mime_type" in img: | |
| parts.append({ | |
| "inline_data": { | |
| "mime_type": img["mime_type"], | |
| "data": img["data"] | |
| } | |
| }) | |
| payload = { | |
| "contents": [{"parts": parts}], | |
| "generationConfig": { | |
| "temperature": 0.7, | |
| "maxOutputTokens": 65536 | |
| } | |
| } | |
| if thinking: | |
| payload["generationConfig"]["thinkingConfig"] = {"thinkingLevel": "medium"} | |
| print(f"[+] [Gemini API] Модель: {selected_model} | 🧠 Thinking: ВКЛ") | |
| else: | |
| print(f"[+] [Gemini API] Модель: {selected_model} | ⚡ Thinking: ВЫКЛ") | |
| last_google_error = "" | |
| for index, key in enumerate(keys): | |
| print(f"[*] Попытка запроса с ключом #{index + 1}/{len(keys)}") | |
| url = f"{base_url}/v1beta/models/{selected_model}:generateContent" | |
| try: | |
| res = requests.post( | |
| url, | |
| json=payload, | |
| headers={"Content-Type": "application/json; charset=utf-8", "x-goog-api-key": key}, | |
| proxies=proxies, | |
| timeout=120 | |
| ) | |
| except requests.exceptions.Timeout: | |
| print(f"[!] Ключ #{index + 1}: Таймаут соединения с сервером Google.") | |
| last_google_error = "Таймаут соединения с Gemini API" | |
| continue | |
| except requests.exceptions.RequestException as e: | |
| # Ошибка локального сетевого стека или DNS клиента | |
| raise RuntimeError(f"Локальная сетевая ошибка соединения: {type(e).__name__}") | |
| # Успешный ответ | |
| if res.status_code == 200: | |
| data = res.json() | |
| candidates = data.get("candidates", []) | |
| if not candidates: | |
| raise RuntimeError("Gemini API вернул ответ, но список 'candidates' пуст.") | |
| cand_parts = candidates[0].get("content", {}).get("parts", []) | |
| text = "".join(p.get("text", "") for p in cand_parts if not p.get("thought", False)) | |
| if not text and cand_parts: | |
| text = cand_parts[-1].get("text", "") | |
| clean = extract_code_block(text) | |
| if not clean: | |
| raise RuntimeError("Не удалось извлечь код из ответа модели.") | |
| return clean | |
| # Проверяем причину ошибки | |
| err_text = res.text | |
| if is_google_side_error(res.status_code, err_text): | |
| try: | |
| err_msg = res.json().get("error", {}).get("message", err_text[:200]) | |
| except Exception: | |
| err_msg = err_text[:200] | |
| print(f"[!] Ошибка Google (код {res.status_code}): {err_msg}. Переключаемся на следующий ключ...") | |
| last_google_error = f"Код {res.status_code}: {err_msg}" | |
| continue | |
| else: | |
| # Ошибка вызвана некорректным телом запроса/клиентскими параметрами — прерываем перебор | |
| try: | |
| client_err = res.json().get("error", {}).get("message", res.text) | |
| except Exception: | |
| client_err = res.text | |
| raise RuntimeError(f"Фатальная ошибка клиента (код {res.status_code}): {client_err}") | |
| # Если цикл завершился и все ключи исчерпаны | |
| raise RuntimeError(f"Все доступные API-ключи ({len(keys)} шт.) исчерпали лимит или недоступны. Последняя ошибка Google: {last_google_error}") |