habulaj commited on
Commit
4cfca83
·
verified ·
1 Parent(s): 7cf381e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +73 -11
app.py CHANGED
@@ -1,5 +1,6 @@
1
  from fastapi import FastAPI, HTTPException
2
  from fastapi.responses import JSONResponse
 
3
  from typing import Optional
4
  import os
5
  import tempfile
@@ -17,7 +18,8 @@ app = FastAPI(title="Gemini Chat API", description="API para interagir com Googl
17
 
18
  # Inicializar chatbot globalmente
19
 
20
- chatbot = None
 
21
  upscale_chatbot = None
22
 
23
  async def update_cookie_if_needed(cookie_path: str, secure_1psid: str, secure_1psidts: str, additional_cookies: dict):
@@ -35,7 +37,7 @@ async def init_chatbot(retry_count=0, max_retries=2):
35
  Tenta atualizar cookies automaticamente se falhar.
36
  """
37
 
38
- global chatbot, upscale_chatbot
39
  cookie_path = os.getenv("COOKIE_PATH", "cookies.json")
40
 
41
  if not os.path.exists(cookie_path):
@@ -49,15 +51,29 @@ async def init_chatbot(retry_count=0, max_retries=2):
49
  if retry_count == 0:
50
  secure_1psidts = await update_cookie_if_needed(cookie_path, secure_1psid, secure_1psidts, additional_cookies)
51
 
52
- # Criar AsyncChatbot diretamente
53
- chatbot = await AsyncChatbot.create(
54
  secure_1psid=secure_1psid,
55
  secure_1psidts=secure_1psidts,
56
- model=Model.G_2_5_PRO,
57
  additional_cookies=additional_cookies,
58
  cookie_path=cookie_path
59
  )
60
- print(f"Chatbot inicializado com sucesso usando {cookie_path}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
 
62
  # Criar instância de Upscale separada
63
  upscale_chatbot = await AsyncChatbot.create(
@@ -304,12 +320,52 @@ def download_file_with_retry(url: str, max_retries: int = 3, timeout: int = 300)
304
  detail=f"Falha ao baixar arquivo após {max_retries} tentativas"
305
  )
306
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
307
  @app.get("/subtitle")
308
  async def generate_subtitle(
309
  file: str,
310
  context: Optional[str] = None,
311
  start: Optional[float] = None,
312
- end: Optional[float] = None
 
313
  ):
314
  """
315
  Endpoint para gerar legendas SRT a partir de um arquivo (imagem, vídeo ou áudio).
@@ -323,9 +379,15 @@ async def generate_subtitle(
323
  Retorna:
324
  - Arquivo SRT formatado (cortado se start e end forem fornecidos)
325
  """
326
- if chatbot is None:
327
  raise HTTPException(status_code=500, detail="Chatbot não inicializado")
328
 
 
 
 
 
 
 
329
  if not file:
330
  raise HTTPException(status_code=400, detail="Parâmetro 'file' é obrigatório")
331
 
@@ -497,11 +559,11 @@ TRADUZA TUDO DE IMPORTANTE NO {media_desc_final}, que tenha dialogo... Nunca dei
497
 
498
  # Determinar qual parâmetro usar baseado no tipo de mídia
499
  if media_type == 'image':
500
- response_gemini = await chatbot.ask(full_prompt, image=temp_file.name)
501
  elif media_type == 'video':
502
- response_gemini = await chatbot.ask(full_prompt, video=temp_file.name)
503
  else: # audio
504
- response_gemini = await chatbot.ask(full_prompt, audio=temp_file.name)
505
 
506
  if response_gemini.get("error"):
507
  raise HTTPException(
 
1
  from fastapi import FastAPI, HTTPException
2
  from fastapi.responses import JSONResponse
3
+ from pydantic import BaseModel
4
  from typing import Optional
5
  import os
6
  import tempfile
 
18
 
19
  # Inicializar chatbot globalmente
20
 
21
+ # Inicializar chatbots globalmente
22
+ chatbots = {}
23
  upscale_chatbot = None
24
 
25
  async def update_cookie_if_needed(cookie_path: str, secure_1psid: str, secure_1psidts: str, additional_cookies: dict):
 
37
  Tenta atualizar cookies automaticamente se falhar.
38
  """
39
 
40
+ global chatbots, upscale_chatbot
41
  cookie_path = os.getenv("COOKIE_PATH", "cookies.json")
42
 
43
  if not os.path.exists(cookie_path):
 
51
  if retry_count == 0:
52
  secure_1psidts = await update_cookie_if_needed(cookie_path, secure_1psid, secure_1psidts, additional_cookies)
53
 
54
+ # Criar Chatbot Flash (Padrão/Rápido)
55
+ chatbots['flash'] = await AsyncChatbot.create(
56
  secure_1psid=secure_1psid,
57
  secure_1psidts=secure_1psidts,
58
+ model=Model.G_3_0_FLASH,
59
  additional_cookies=additional_cookies,
60
  cookie_path=cookie_path
61
  )
62
+ print(f"Chatbot Flash (3.0) inicializado com sucesso")
63
+
64
+ # Criar Chatbot Thinking (Raciocínio) - Timeout maior
65
+ chatbots['thinking'] = await AsyncChatbot.create(
66
+ secure_1psid=secure_1psid,
67
+ secure_1psidts=secure_1psidts,
68
+ model=Model.G_3_0_THINKING,
69
+ additional_cookies=additional_cookies,
70
+ cookie_path=cookie_path,
71
+ timeout=120 # Timeout maior para thinking
72
+ )
73
+ print(f"Chatbot Thinking (3.0) inicializado com sucesso")
74
+
75
+ # Fallback/Default
76
+ chatbots['default'] = chatbots['flash']
77
 
78
  # Criar instância de Upscale separada
79
  upscale_chatbot = await AsyncChatbot.create(
 
320
  detail=f"Falha ao baixar arquivo após {max_retries} tentativas"
321
  )
322
 
323
+ class ChatRequest(BaseModel):
324
+ message: str
325
+ context: Optional[str] = None
326
+ model: Optional[str] = "flash" # 'flash' or 'thinking'
327
+
328
+ @app.post("/chat")
329
+ async def chat_endpoint(request: ChatRequest):
330
+ """
331
+ Endpoint para conversas de texto simples.
332
+ """
333
+ if not chatbots:
334
+ raise HTTPException(status_code=500, detail="Chatbot não inicializado")
335
+
336
+ try:
337
+ requested_model = request.model.lower() if request.model else "flash"
338
+ if "thinking" in requested_model:
339
+ selected_chatbot = chatbots.get('thinking', chatbots['default'])
340
+ else:
341
+ selected_chatbot = chatbots.get('flash', chatbots['default'])
342
+
343
+ prompt = request.message
344
+ if request.context:
345
+ prompt = f"Contexto: {request.context}\n\nMensagem: {request.message}"
346
+
347
+ print(f"💬 Chat request ({requested_model}): {prompt[:50]}...")
348
+ response_gemini = await selected_chatbot.ask(prompt)
349
+
350
+ if response_gemini.get("error"):
351
+ raise HTTPException(
352
+ status_code=500,
353
+ detail=f"Erro no Gemini: {response_gemini.get('content', 'Erro desconhecido')}"
354
+ )
355
+
356
+ return {"response": response_gemini.get("content", "")}
357
+
358
+ except Exception as e:
359
+ raise HTTPException(status_code=500, detail=str(e))
360
+
361
+
362
  @app.get("/subtitle")
363
  async def generate_subtitle(
364
  file: str,
365
  context: Optional[str] = None,
366
  start: Optional[float] = None,
367
+ end: Optional[float] = None,
368
+ model: Optional[str] = "flash" # 'flash' or 'thinking'
369
  ):
370
  """
371
  Endpoint para gerar legendas SRT a partir de um arquivo (imagem, vídeo ou áudio).
 
379
  Retorna:
380
  - Arquivo SRT formatado (cortado se start e end forem fornecidos)
381
  """
382
+ if not chatbots:
383
  raise HTTPException(status_code=500, detail="Chatbot não inicializado")
384
 
385
+ requested_model = model.lower() if model else "flash"
386
+ if "thinking" in requested_model:
387
+ selected_chatbot = chatbots.get('thinking', chatbots['default'])
388
+ else:
389
+ selected_chatbot = chatbots.get('flash', chatbots['default'])
390
+
391
  if not file:
392
  raise HTTPException(status_code=400, detail="Parâmetro 'file' é obrigatório")
393
 
 
559
 
560
  # Determinar qual parâmetro usar baseado no tipo de mídia
561
  if media_type == 'image':
562
+ response_gemini = await selected_chatbot.ask(full_prompt, image=temp_file.name)
563
  elif media_type == 'video':
564
+ response_gemini = await selected_chatbot.ask(full_prompt, video=temp_file.name)
565
  else: # audio
566
+ response_gemini = await selected_chatbot.ask(full_prompt, audio=temp_file.name)
567
 
568
  if response_gemini.get("error"):
569
  raise HTTPException(