Update app.py
Browse files
app.py
CHANGED
|
@@ -5,15 +5,54 @@ import os
|
|
| 5 |
import tempfile
|
| 6 |
from pathlib import Path
|
| 7 |
|
| 8 |
-
from gemini_client import AsyncChatbot, Model, load_cookies
|
|
|
|
|
|
|
| 9 |
|
| 10 |
app = FastAPI(title="Gemini Chat API", description="API para interagir com Google Gemini")
|
| 11 |
|
| 12 |
# Inicializar chatbot globalmente
|
| 13 |
chatbot = None
|
| 14 |
|
| 15 |
-
async def
|
| 16 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
global chatbot
|
| 18 |
cookie_path = os.getenv("COOKIE_PATH", "cookies.json")
|
| 19 |
|
|
@@ -24,6 +63,10 @@ async def init_chatbot():
|
|
| 24 |
# Carregar cookies
|
| 25 |
secure_1psid, secure_1psidts, additional_cookies = load_cookies(cookie_path)
|
| 26 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
# Criar AsyncChatbot diretamente
|
| 28 |
chatbot = await AsyncChatbot.create(
|
| 29 |
secure_1psid=secure_1psid,
|
|
@@ -33,6 +76,50 @@ async def init_chatbot():
|
|
| 33 |
cookie_path=cookie_path
|
| 34 |
)
|
| 35 |
print(f"Chatbot inicializado com sucesso usando {cookie_path}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
except Exception as e:
|
| 37 |
print(f"Erro ao inicializar chatbot: {e}")
|
| 38 |
raise
|
|
|
|
| 5 |
import tempfile
|
| 6 |
from pathlib import Path
|
| 7 |
|
| 8 |
+
from gemini_client import AsyncChatbot, Model, load_cookies, save_cookies
|
| 9 |
+
from gemini_client.enums import Endpoint, Headers
|
| 10 |
+
from curl_cffi.requests import AsyncSession
|
| 11 |
|
| 12 |
app = FastAPI(title="Gemini Chat API", description="API para interagir com Google Gemini")
|
| 13 |
|
| 14 |
# Inicializar chatbot globalmente
|
| 15 |
chatbot = None
|
| 16 |
|
| 17 |
+
async def update_cookie_if_needed(cookie_path: str, secure_1psid: str, secure_1psidts: str, additional_cookies: dict):
|
| 18 |
+
"""
|
| 19 |
+
Tenta atualizar o cookie __Secure-1PSIDTS se necessário.
|
| 20 |
+
Retorna o novo cookie ou o original se não precisar atualizar.
|
| 21 |
+
"""
|
| 22 |
+
try:
|
| 23 |
+
# Criar sessão temporária para verificar/atualizar cookie
|
| 24 |
+
async with AsyncSession() as temp_session:
|
| 25 |
+
# Tentar fazer requisição de rotação de cookies
|
| 26 |
+
rotate_resp = await temp_session.post(
|
| 27 |
+
Endpoint.ROTATE_COOKIES.value,
|
| 28 |
+
headers=Headers.ROTATE_COOKIES.value,
|
| 29 |
+
data='[000,"-0000000000000000000"]',
|
| 30 |
+
cookies={
|
| 31 |
+
"__Secure-1PSID": secure_1psid,
|
| 32 |
+
"__Secure-1PSIDTS": secure_1psidts
|
| 33 |
+
},
|
| 34 |
+
timeout=20
|
| 35 |
+
)
|
| 36 |
+
rotate_resp.raise_for_status()
|
| 37 |
+
|
| 38 |
+
# Obter novo cookie se disponível
|
| 39 |
+
new_1psidts = rotate_resp.cookies.get("__Secure-1PSIDTS")
|
| 40 |
+
if new_1psidts and new_1psidts != secure_1psidts:
|
| 41 |
+
# Salvar novo cookie
|
| 42 |
+
save_cookies(cookie_path, secure_1psid, new_1psidts, additional_cookies)
|
| 43 |
+
print(f"✓ Cookie atualizado automaticamente antes da inicialização")
|
| 44 |
+
return new_1psidts
|
| 45 |
+
except Exception as e:
|
| 46 |
+
print(f"Aviso: Não foi possível atualizar cookie proativamente: {e}")
|
| 47 |
+
# Continuar com o cookie original
|
| 48 |
+
|
| 49 |
+
return secure_1psidts
|
| 50 |
+
|
| 51 |
+
async def init_chatbot(retry_count=0, max_retries=2):
|
| 52 |
+
"""
|
| 53 |
+
Inicializa o chatbot com os cookies de forma assíncrona.
|
| 54 |
+
Tenta atualizar cookies automaticamente se falhar.
|
| 55 |
+
"""
|
| 56 |
global chatbot
|
| 57 |
cookie_path = os.getenv("COOKIE_PATH", "cookies.json")
|
| 58 |
|
|
|
|
| 63 |
# Carregar cookies
|
| 64 |
secure_1psid, secure_1psidts, additional_cookies = load_cookies(cookie_path)
|
| 65 |
|
| 66 |
+
# Tentar atualizar cookie proativamente antes de inicializar
|
| 67 |
+
if retry_count == 0:
|
| 68 |
+
secure_1psidts = await update_cookie_if_needed(cookie_path, secure_1psid, secure_1psidts, additional_cookies)
|
| 69 |
+
|
| 70 |
# Criar AsyncChatbot diretamente
|
| 71 |
chatbot = await AsyncChatbot.create(
|
| 72 |
secure_1psid=secure_1psid,
|
|
|
|
| 76 |
cookie_path=cookie_path
|
| 77 |
)
|
| 78 |
print(f"Chatbot inicializado com sucesso usando {cookie_path}")
|
| 79 |
+
except (ValueError, PermissionError) as e:
|
| 80 |
+
error_str = str(e).lower()
|
| 81 |
+
# Verificar se é erro relacionado a cookie/autenticação
|
| 82 |
+
if retry_count < max_retries and ("snlm0e" in error_str or "authentication" in error_str or "cookie" in error_str or "not found" in error_str):
|
| 83 |
+
print(f"Erro ao inicializar (possível cookie expirado): {e}")
|
| 84 |
+
print(f"Tentando atualizar cookie e reinicializar (tentativa {retry_count + 1}/{max_retries})...")
|
| 85 |
+
|
| 86 |
+
try:
|
| 87 |
+
# Carregar cookies novamente
|
| 88 |
+
secure_1psid, secure_1psidts, additional_cookies = load_cookies(cookie_path)
|
| 89 |
+
|
| 90 |
+
# Forçar atualização do cookie
|
| 91 |
+
async with AsyncSession() as temp_session:
|
| 92 |
+
rotate_resp = await temp_session.post(
|
| 93 |
+
Endpoint.ROTATE_COOKIES.value,
|
| 94 |
+
headers=Headers.ROTATE_COOKIES.value,
|
| 95 |
+
data='[000,"-0000000000000000000"]',
|
| 96 |
+
cookies={
|
| 97 |
+
"__Secure-1PSID": secure_1psid,
|
| 98 |
+
"__Secure-1PSIDTS": secure_1psidts
|
| 99 |
+
},
|
| 100 |
+
timeout=20
|
| 101 |
+
)
|
| 102 |
+
rotate_resp.raise_for_status()
|
| 103 |
+
|
| 104 |
+
new_1psidts = rotate_resp.cookies.get("__Secure-1PSIDTS")
|
| 105 |
+
if new_1psidts:
|
| 106 |
+
# Salvar novo cookie
|
| 107 |
+
save_cookies(cookie_path, secure_1psid, new_1psidts, additional_cookies)
|
| 108 |
+
print(f"✓ Cookie atualizado! Reinicializando...")
|
| 109 |
+
|
| 110 |
+
# Retentar inicialização
|
| 111 |
+
return await init_chatbot(retry_count=retry_count + 1, max_retries=max_retries)
|
| 112 |
+
else:
|
| 113 |
+
raise ValueError("Novo cookie não encontrado na resposta de rotação")
|
| 114 |
+
except Exception as update_error:
|
| 115 |
+
print(f"Erro ao atualizar cookie: {update_error}")
|
| 116 |
+
if retry_count < max_retries:
|
| 117 |
+
# Tentar mais uma vez
|
| 118 |
+
return await init_chatbot(retry_count=retry_count + 1, max_retries=max_retries)
|
| 119 |
+
raise Exception(f"Falha ao inicializar chatbot após {max_retries} tentativas: {update_error}")
|
| 120 |
+
else:
|
| 121 |
+
print(f"Erro ao inicializar chatbot: {e}")
|
| 122 |
+
raise
|
| 123 |
except Exception as e:
|
| 124 |
print(f"Erro ao inicializar chatbot: {e}")
|
| 125 |
raise
|