File size: 11,474 Bytes
1b4b6d2 2e4b939 0b24215 2e4b939 0b24215 1b4b6d2 238a6f3 0b24215 9a9d2d0 238a6f3 1b4b6d2 238a6f3 0b24215 238a6f3 0b24215 1b4b6d2 0b24215 1b4b6d2 e9f689e 0b24215 1b4b6d2 0b24215 1b4b6d2 e9f689e 1b4b6d2 0b24215 1b4b6d2 0b24215 1b4b6d2 0b24215 1b4b6d2 e9f689e 1b4b6d2 0b24215 1b4b6d2 e9f689e 1b4b6d2 e9f689e 1b4b6d2 e9f689e 0b24215 e9f689e 1b4b6d2 e9f689e 1b4b6d2 e9f689e 0b24215 e9f689e 1b4b6d2 | 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 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 | """
ู
ุฏูุฑ ู
ูุงุชูุญ ุงูู API โ ูุฏูุฑ ุจูู ุงูู
ูุงุชูุญ ูุงููู
ุงุฐุฌ ุชููุงุฆูุงู (2D Rotation)
=======================================================
ูุฏูุฑ ุจูู 3 ูู
ุงุฐุฌ ู
ุฎุชููุฉ (Flash, Flash-Lite 2.5, Flash-Lite 3.1)
ู
ุถุฑูุจุฉ ูู ุนุฏุฏ ุงูู
ูุงุชูุญ ูุชุฌุงูุฒ ุญุฏูุฏ ุงูู RPM ูุงูู RPD ุชู
ุงู
ุงู.
=======================================================
"""
import os
import time
import threading
from typing import List, Optional, Tuple
from datetime import datetime, date
# โโ Monkeypatch google.genai.Client to disable HTTP/2 and prevent timeouts on Windows / proxy networks โโ
try:
from google import genai
from google.genai import types
import httpx
_orig_init = genai.Client.__init__
def patched_init(self, *args, **kwargs):
if 'http_options' not in kwargs:
kwargs['http_options'] = {}
http_opts = kwargs['http_options']
if isinstance(http_opts, dict):
timeout_val = http_opts.get('timeout', 90.0)
http_opts['httpx_client'] = httpx.Client(timeout=timeout_val, http2=False)
http_opts['httpx_async_client'] = httpx.AsyncClient(timeout=timeout_val, http2=False)
clean_opts = {k: v for k, v in http_opts.items() if k != 'timeout'}
kwargs['http_options'] = types.HttpOptions(**clean_opts)
elif isinstance(http_opts, types.HttpOptions):
if not http_opts.httpx_client:
http_opts.httpx_client = httpx.Client(timeout=60.0, http2=False)
if not http_opts.httpx_async_client:
http_opts.httpx_async_client = httpx.AsyncClient(timeout=60.0, http2=False)
_orig_init(self, *args, **kwargs)
genai.Client.__init__ = patched_init
except Exception:
pass
# ุงููู
ุงุฐุฌ ุงูุชู ุณูุชู
ุงูุชุฏููุฑ ุจูููุง ู
ุน ูู ู
ูุชุงุญ (ู
ุฑุชุจุฉ ุญุณุจ ุฃุนูู ุฏูุฉ ูุงุณุชุฌุงุจุฉ ุฃููุงูุ ู
ุน ุฅุจูุงุก 3.6-flash ูุงุญุชูุงุทู ุฃุฎูุฑ)
ROTATION_MODELS = [
"gemini-2.5-flash",
"gemini-3-flash-preview",
"gemini-3.5-flash",
"gemini-3.5-flash-lite",
"gemini-3.1-flash-lite",
"gemini-3.6-flash",
]
# โโ ุญุฏูุฏ ุงููู
ุงุฐุฌ ุงูู
ุฎุชููุฉ (RPD) โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
MODEL_DAILY_LIMITS = {
"gemini-2.5-flash": 1500,
"gemini-3-flash-preview": 1500,
"gemini-3.5-flash": 1500,
"gemini-3.5-flash-lite": 1500,
"gemini-3.1-flash-lite": 500,
"gemini-3.6-flash": 1500,
"default": 1500,
}
class KeyManager:
"""
ูุฏูุฑ ู
ุตูููุฉ ุซูุงุฆูุฉ ุงูุฃุจุนุงุฏ (ูู
ูุฐุฌ ร ู
ูุชุงุญ) ููุฏูุฑ ุจูููุง.
- ููุฒูุน ุงูุถุบุท ุนูู ูู ุงูู
ูุงุชูุญ ุนูู ุงููู
ุงุฐุฌ ุงูุฃุนูู ุฏูุฉ ุฃููุงู ูุจู ุงูุงูุชูุงู ูููู
ุงุฐุฌ ุงูุฃุฎู
- ูุชุฎุทู ุงูุชุฑููุจุฉ ุงูุชู ุชุตู ุญุฏูุง (429 / 503) ูู
ุฏุฉ 60 ุซุงููุฉ
- ูุนุทูู ุงููู
ูุฐุฌ ุบูุฑ ุงูู
ุชุงุญ (404) ูุจููุฉ ุงูููู
"""
def __init__(self, keys: List[str]):
self._keys = [k.strip() for k in keys if k and k.strip()]
self._lock = threading.Lock()
# Rotate across ALL keys on the highest-accuracy model first, then next model.
# This maximizes both vision accuracy and RPM distribution across keys.
self._combinations = []
for m in ROTATION_MODELS:
for k in self._keys:
self._combinations.append((k, m))
self._index = 0
self._usage: dict = {}
for k, m in self._combinations:
self._usage[(k, m)] = {"count": 0, "date": date.today(), "exhausted": False, "exhausted_at": 0, "permanent": False}
# โโ Public API โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def get_key_and_model(self) -> Tuple[Optional[str], str]:
"""ูุฑุฌุน ุงูุชุฑููุจุฉ ุงูุญุงููุฉ ุงููุดุทุฉ (ุงูู
ูุชุงุญ ูุงููู
ูุฐุฌ) ููุฒูุฏ ุนุฏุงุฏูุง."""
with self._lock:
self._reset_daily_counts()
combo = self._active_combo()
if combo:
self._usage[combo]["count"] += 1
self._advance()
return combo
return None, "gemini-2.5-flash" # fallback if all exhausted
def mark_rate_limited(self, key: str, model: str):
"""ุงุณุชุฏุนู ูุฐุง ุนูุฏ ุงุณุชูุจุงู 429 ุฃู 503 โ ูุชุฎุทู ูุฐู ุงูุชุฑููุจุฉ ูู
ุฏุฉ 60 ุซุงููุฉ ููุท."""
with self._lock:
combo = (key, model)
if combo in self._usage:
self._usage[combo]["exhausted"] = True
self._usage[combo]["exhausted_at"] = time.time()
def mark_model_unavailable(self, model: str):
"""ุงุณุชุฏุนู ูุฐุง ุนูุฏ ุงุณุชูุจุงู 404 ููู
ูุฐุฌ ุบูุฑ ู
ุชุงุญ โ ูุนุทูู ุงููู
ูุฐุฌ ูุจููุฉ ุงูููู
."""
with self._lock:
now = time.time()
for combo, u in self._usage.items():
if combo[1] == model:
u["exhausted"] = True
u["exhausted_at"] = now
u["permanent"] = True
def mark_exhausted(self, key: str, model: str):
"""ุนููู
ุชุฑููุจุฉ ุจุงุนุชุจุงุฑูุง ู
ูุชููุฉ ูุฏููุงู."""
self.mark_rate_limited(key, model)
def status(self) -> List[dict]:
"""ู
ูุฎุต ุญุงูุฉ ูู ุงูุชุฑููุจุงุช."""
with self._lock:
self._reset_daily_counts()
active_combo = self._active_combo()
res = []
for combo in self._combinations:
k, m = combo
u = self._usage[combo]
limit = MODEL_DAILY_LIMITS.get(m, MODEL_DAILY_LIMITS["default"])
res.append({
"key_hint": f"...{k[-8:]}",
"model": m,
"requests": u["count"],
"limit": limit,
"remaining": max(limit - u["count"], 0),
"exhausted": u["exhausted"],
"active": (combo == active_combo),
})
return res
def total_remaining(self) -> int:
"""ู
ุฌู
ูุน ุงูุทูุจุงุช ุงูู
ุชุจููุฉ ููู ุงูุชุฑููุจุงุช."""
with self._lock:
self._reset_daily_counts()
total = 0
for combo in self._combinations:
k, m = combo
if not self._usage[combo]["exhausted"]:
limit = MODEL_DAILY_LIMITS.get(m, MODEL_DAILY_LIMITS["default"])
total += max(limit - self._usage[combo]["count"], 0)
return total
def key_count(self) -> int:
return len(self._keys)
# โโ Internal โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def _active_combo(self) -> Optional[Tuple[str, str]]:
"""ูุจุญุซ ุนู ุฃูู ุชุฑููุจุฉ ุบูุฑ ู
ูุชููุฉ. ุงูู
ูุงุชูุญ ุงูู
ุนูููุฉ ุชูุชูู ุจุนุฏ 60 ุซุงููุฉ ุชููุงุฆูุงู."""
if not self._combinations:
return None
now = time.time()
for _ in range(len(self._combinations)):
combo = self._combinations[self._index % len(self._combinations)]
u = self._usage[combo]
# Auto-recover temporary 429/503 cooldowns after 60 seconds (never recover 404 permanent models same day)
if u["exhausted"] and not u.get("permanent") and (now - u.get("exhausted_at", 0)) > 60:
u["exhausted"] = False
if not u["exhausted"]:
return combo
self._index += 1
return None
def _advance(self):
if self._combinations:
self._index = (self._index + 1) % len(self._combinations)
def _reset_daily_counts(self):
"""ูุตููุฑ ุงูุนุฏุงุฏ ูู ููู
ุฌุฏูุฏ ูููุดุบูู auto-exhaustion ุนูุฏ ุจููุบ ุงูุญุฏ."""
today = date.today()
for combo in self._combinations:
k, m = combo
u = self._usage[combo]
if u["date"] != today:
self._usage[combo] = {"count": 0, "date": today, "exhausted": False, "exhausted_at": 0, "permanent": False}
else:
# Auto-mark exhausted when daily limit reached
limit = MODEL_DAILY_LIMITS.get(m, MODEL_DAILY_LIMITS["default"])
if u["count"] >= limit and not u["exhausted"]:
u["exhausted"] = True
u["exhausted_at"] = time.time()
# โโ ุชุญู
ูู ุงูู
ูุงุชูุญ ู
ู .env ุฃู ู
ุชุบูุฑุงุช ุงูุจูุฆุฉ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def _load_keys_from_env() -> List[str]:
try:
from dotenv import load_dotenv
import pathlib
env_path = pathlib.Path(__file__).resolve().parent.parent / ".env"
load_dotenv(dotenv_path=env_path, override=False)
except ImportError:
pass
multi = os.environ.get("AI_API_KEYS", "")
if multi:
return [k.strip() for k in multi.split(",") if k.strip()]
numbered = []
for i in range(1, 21):
k = os.environ.get(f"AI_API_KEY_{i}", "")
if k.strip():
numbered.append(k.strip())
if numbered:
return numbered
single = (os.environ.get("GOOGLE_API_KEY") or
os.environ.get("AI_API_KEY") or "")
return [single] if single else []
# โโ Singleton โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
_manager: Optional[KeyManager] = None
_manager_lock = threading.Lock()
def get_key_manager() -> KeyManager:
global _manager
with _manager_lock:
if _manager is None:
keys = _load_keys_from_env()
# If no keys are provided, create a dummy key so the system doesn't crash
if not keys:
keys = ["NO_API_KEY_FOUND"]
_manager = KeyManager(keys)
return _manager
def reload_manager(keys: List[str]):
global _manager
with _manager_lock:
if not keys:
keys = ["NO_API_KEY_FOUND"]
_manager = KeyManager(keys)
def print_status():
mgr = get_key_manager()
print(f"\n{'โ'*80}")
print(f" ู
ุฏูุฑ ุงูู
ูุงุชูุญ ูุงููู
ุงุฐุฌ โ {mgr.key_count()} ู
ูุชุงุญ | ู
ุชุจูู: {mgr.total_remaining()} ุทูุจ")
print(f"{'โ'*80}")
for s in mgr.status():
icon = "โ
" if s["active"] else ("๐ด" if s["exhausted"] else "โช")
bar = "โ" * int(s["requests"] / max(s["limit"], 1) * 20)
bar = bar.ljust(20, "โ")
rem = "(ู
ูุชูู)" if s["exhausted"] else f"ู
ุชุจูู: {s['remaining']}"
m_name = s['model'][:25].ljust(25)
print(f" {icon} {s['key_hint']} | {m_name} | [{bar}] {s['requests']}/{s['limit']} {rem}")
print(f"{'โ'*80}\n")
|