habulaj commited on
Commit
0155ff7
·
verified ·
1 Parent(s): 2b98018

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +85 -176
app.py CHANGED
@@ -1,16 +1,13 @@
1
- from fastapi import FastAPI, HTTPException, File, UploadFile, Form
2
- from fastapi.responses import Response, JSONResponse
3
  from typing import Optional
4
  import os
5
  import tempfile
6
  from pathlib import Path
7
  import re
8
  import requests
9
- import mimetypes
10
 
11
- from gemini_client import AsyncChatbot, Model, load_cookies, save_cookies
12
- from gemini_client.enums import Endpoint, Headers
13
- from curl_cffi.requests import AsyncSession
14
 
15
  app = FastAPI(title="Gemini Chat API", description="API para interagir com Google Gemini")
16
 
@@ -76,6 +73,72 @@ def root():
76
  """Endpoint raiz"""
77
  return {"status": "ok", "message": "Gemini Chat API está funcionando"}
78
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79
  def clean_and_validate_srt(srt_content):
80
  """Limpa e valida conteúdo SRT seguindo o padrão do example.py"""
81
  if "```" in srt_content:
@@ -150,7 +213,9 @@ def clean_and_validate_srt(srt_content):
150
  @app.get("/subtitle")
151
  async def generate_subtitle(
152
  file: str,
153
- context: Optional[str] = None
 
 
154
  ):
155
  """
156
  Endpoint para gerar legendas SRT a partir de um arquivo (imagem, vídeo ou áudio).
@@ -158,9 +223,11 @@ async def generate_subtitle(
158
  Parâmetros:
159
  - file: URL do arquivo (imagem, vídeo ou áudio)
160
  - context: Contexto adicional opcional para a geração de legendas
 
 
161
 
162
  Retorna:
163
- - Arquivo SRT formatado
164
  """
165
  if chatbot is None:
166
  raise HTTPException(status_code=500, detail="Chatbot não inicializado")
@@ -369,6 +436,16 @@ TRADUZA TUDO DE IMPORTANTE NO {media_desc_final}, que tenha dialogo... Nunca dei
369
  detail="Falha ao processar formato SRT - resposta inválida"
370
  )
371
 
 
 
 
 
 
 
 
 
 
 
372
  # Retornar SRT em JSON
373
  return JSONResponse(
374
  content={
@@ -384,174 +461,6 @@ TRADUZA TUDO DE IMPORTANTE NO {media_desc_final}, que tenha dialogo... Nunca dei
384
  raise HTTPException(status_code=400, detail=f"Erro ao baixar arquivo: {str(e)}")
385
  except Exception as e:
386
  raise HTTPException(status_code=500, detail=f"Erro ao gerar legendas: {str(e)}")
387
- finally:
388
- # Limpar arquivo temporário
389
- if temp_file and os.path.exists(temp_file.name):
390
- try:
391
- os.unlink(temp_file.name)
392
- except:
393
- pass
394
-
395
- @app.get("/get")
396
- async def get_response(
397
- message: str,
398
- model: Optional[str] = None
399
- ):
400
- """
401
- Endpoint GET para obter resposta do Gemini.
402
-
403
- Parâmetros:
404
- - message: A mensagem para enviar ao Gemini
405
- - model: Modelo opcional (padrão: G_2_5_PRO)
406
-
407
- Retorna JSON com:
408
- - content: Resposta do Gemini
409
- - model: Modelo utilizado
410
- - error: Se houve erro
411
- """
412
- if chatbot is None:
413
- raise HTTPException(status_code=500, detail="Chatbot não inicializado")
414
-
415
- try:
416
- # Selecionar modelo se especificado (usa o padrão por enquanto)
417
- selected_model = Model.G_2_5_PRO # Padrão
418
- if model:
419
- try:
420
- # Validar modelo, mas usar o padrão por enquanto
421
- Model.from_name(model)
422
- except ValueError:
423
- return JSONResponse(
424
- status_code=400,
425
- content={
426
- "error": True,
427
- "content": f"Modelo inválido: {model}",
428
- "model": None
429
- }
430
- )
431
-
432
- # Enviar mensagem (assíncrono)
433
- response = await chatbot.ask(message)
434
-
435
- # Retornar resposta formatada
436
- return {
437
- "content": response.get("content", ""),
438
- "model": response.get("model", selected_model.model_name),
439
- "error": response.get("error", False)
440
- }
441
- except Exception as e:
442
- return JSONResponse(
443
- status_code=500,
444
- content={
445
- "error": True,
446
- "content": f"Erro ao processar requisição: {str(e)}",
447
- "model": None
448
- }
449
- )
450
-
451
- @app.post("/get")
452
- async def post_response(
453
- message: str = Form(...),
454
- image: Optional[UploadFile] = File(None),
455
- video: Optional[UploadFile] = File(None),
456
- audio: Optional[UploadFile] = File(None),
457
- model: Optional[str] = Form(None)
458
- ):
459
- """
460
- Endpoint POST para obter resposta do Gemini com suporte a mídia.
461
-
462
- Parâmetros:
463
- - message: A mensagem para enviar ao Gemini (obrigatório)
464
- - image: Arquivo de imagem opcional
465
- - video: Arquivo de vídeo opcional
466
- - audio: Arquivo de áudio opcional
467
- - model: Modelo opcional (padrão: G_2_5_PRO)
468
-
469
- Retorna JSON com:
470
- - content: Resposta do Gemini
471
- - model: Modelo utilizado
472
- - error: Se houve erro
473
- """
474
- if chatbot is None:
475
- raise HTTPException(status_code=500, detail="Chatbot não inicializado")
476
-
477
- # Validar que apenas um tipo de mídia é enviado
478
- media_count = sum([image is not None, video is not None, audio is not None])
479
- if media_count > 1:
480
- return JSONResponse(
481
- status_code=400,
482
- content={
483
- "error": True,
484
- "content": "Apenas um tipo de mídia pode ser enviado por vez (image, video ou audio)",
485
- "model": None
486
- }
487
- )
488
-
489
- temp_file = None
490
- try:
491
- # Selecionar modelo se especificado (usa o padrão por enquanto)
492
- selected_model = Model.G_2_5_PRO # Padrão
493
- if model:
494
- try:
495
- # Validar modelo, mas usar o padrão por enquanto
496
- Model.from_name(model)
497
- except ValueError:
498
- return JSONResponse(
499
- status_code=400,
500
- content={
501
- "error": True,
502
- "content": f"Modelo inválido: {model}",
503
- "model": None
504
- }
505
- )
506
-
507
- # Processar mídia se fornecida
508
- media_path = None
509
- if image:
510
- # Salvar imagem temporariamente
511
- temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=Path(image.filename).suffix if image.filename else ".jpg")
512
- content = await image.read()
513
- temp_file.write(content)
514
- temp_file.close()
515
- media_path = temp_file.name
516
-
517
- response = await chatbot.ask(message, image=media_path)
518
- elif video:
519
- # Salvar vídeo temporariamente
520
- temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=Path(video.filename).suffix if video.filename else ".mp4")
521
- content = await video.read()
522
- temp_file.write(content)
523
- temp_file.close()
524
- media_path = temp_file.name
525
-
526
- response = await chatbot.ask(message, video=media_path)
527
- elif audio:
528
- # Salvar áudio temporariamente
529
- temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=Path(audio.filename).suffix if audio.filename else ".mp3")
530
- content = await audio.read()
531
- temp_file.write(content)
532
- temp_file.close()
533
- media_path = temp_file.name
534
-
535
- response = await chatbot.ask(message, audio=media_path)
536
- else:
537
- # Apenas texto
538
- response = await chatbot.ask(message)
539
-
540
- # Retornar resposta formatada
541
- return {
542
- "content": response.get("content", ""),
543
- "model": response.get("model", selected_model.model_name),
544
- "error": response.get("error", False)
545
- }
546
- except Exception as e:
547
- return JSONResponse(
548
- status_code=500,
549
- content={
550
- "error": True,
551
- "content": f"Erro ao processar requisição: {str(e)}",
552
- "model": None
553
- }
554
- )
555
  finally:
556
  # Limpar arquivo temporário
557
  if temp_file and os.path.exists(temp_file.name):
 
1
+ from fastapi import FastAPI, HTTPException
2
+ from fastapi.responses import JSONResponse
3
  from typing import Optional
4
  import os
5
  import tempfile
6
  from pathlib import Path
7
  import re
8
  import requests
 
9
 
10
+ from gemini_client import AsyncChatbot, Model, load_cookies
 
 
11
 
12
  app = FastAPI(title="Gemini Chat API", description="API para interagir com Google Gemini")
13
 
 
73
  """Endpoint raiz"""
74
  return {"status": "ok", "message": "Gemini Chat API está funcionando"}
75
 
76
+ def srt_time_to_seconds(timestamp):
77
+ """Converte timestamp SRT (HH:MM:SS,mmm) para segundos"""
78
+ try:
79
+ time_part, ms_part = timestamp.split(",")
80
+ h, m, s = map(int, time_part.split(":"))
81
+ ms = int(ms_part)
82
+ return h * 3600 + m * 60 + s + ms / 1000.0
83
+ except:
84
+ return 0.0
85
+
86
+ def seconds_to_srt_time(seconds):
87
+ """Converte segundos para timestamp SRT (HH:MM:SS,mmm)"""
88
+ hours = int(seconds // 3600)
89
+ minutes = int((seconds % 3600) // 60)
90
+ secs = int(seconds % 60)
91
+ ms = int((seconds % 1) * 1000)
92
+ return f"{hours:02d}:{minutes:02d}:{secs:02d},{ms:03d}"
93
+
94
+ def cut_srt_by_time(srt_content, start_time, end_time):
95
+ """
96
+ Corta legendas SRT baseado em tempo de início e fim.
97
+ Ajusta os timestamps para começar do zero.
98
+
99
+ Parâmetros:
100
+ - srt_content: Conteúdo SRT original
101
+ - start_time: Tempo de início em segundos
102
+ - end_time: Tempo de fim em segundos
103
+
104
+ Retorna: SRT cortado e ajustado
105
+ """
106
+ if start_time is None or end_time is None:
107
+ return srt_content
108
+
109
+ # Padrão para capturar legendas
110
+ pattern = re.compile(r"(\d+)\s*\n([^-\n]+?) --> ([^-\n]+?)\s*\n((?:(?!^\d+\s*\n).+\n?)*)", re.MULTILINE)
111
+ matches = pattern.findall(srt_content)
112
+
113
+ filtered_subtitles = []
114
+ for num, start, end, text in matches:
115
+ start_seconds = srt_time_to_seconds(start.strip())
116
+ end_seconds = srt_time_to_seconds(end.strip())
117
+
118
+ # Verificar se a legenda está dentro do intervalo [start_time, end_time]
119
+ # Incluir legendas que se sobrepõem parcialmente
120
+ if end_seconds > start_time and start_seconds < end_time:
121
+ # Ajustar timestamps para começar do zero
122
+ new_start = max(0, start_seconds - start_time)
123
+ new_end = min(end_time - start_time, end_seconds - start_time)
124
+
125
+ # Garantir que new_end > new_start
126
+ if new_end > new_start:
127
+ filtered_subtitles.append({
128
+ 'start': new_start,
129
+ 'end': new_end,
130
+ 'text': text.strip()
131
+ })
132
+
133
+ # Gerar SRT cortado
134
+ srt_cut = ""
135
+ for i, sub in enumerate(filtered_subtitles, 1):
136
+ start_srt = seconds_to_srt_time(sub['start'])
137
+ end_srt = seconds_to_srt_time(sub['end'])
138
+ srt_cut += f"{i}\n{start_srt} --> {end_srt}\n{sub['text']}\n\n"
139
+
140
+ return srt_cut.strip()
141
+
142
  def clean_and_validate_srt(srt_content):
143
  """Limpa e valida conteúdo SRT seguindo o padrão do example.py"""
144
  if "```" in srt_content:
 
213
  @app.get("/subtitle")
214
  async def generate_subtitle(
215
  file: str,
216
+ context: Optional[str] = None,
217
+ start: Optional[float] = None,
218
+ end: Optional[float] = None
219
  ):
220
  """
221
  Endpoint para gerar legendas SRT a partir de um arquivo (imagem, vídeo ou áudio).
 
223
  Parâmetros:
224
  - file: URL do arquivo (imagem, vídeo ou áudio)
225
  - context: Contexto adicional opcional para a geração de legendas
226
+ - start: Tempo de início para cortar legendas (em segundos)
227
+ - end: Tempo de fim para cortar legendas (em segundos)
228
 
229
  Retorna:
230
+ - Arquivo SRT formatado (cortado se start e end forem fornecidos)
231
  """
232
  if chatbot is None:
233
  raise HTTPException(status_code=500, detail="Chatbot não inicializado")
 
436
  detail="Falha ao processar formato SRT - resposta inválida"
437
  )
438
 
439
+ # Aplicar corte de legendas se start e end forem fornecidos
440
+ if start is not None and end is not None:
441
+ print(f"✂️ Cortando legendas: {start}s - {end}s")
442
+ srt_cleaned = cut_srt_by_time(srt_cleaned, start, end)
443
+ if not srt_cleaned or len(srt_cleaned.strip()) < 10:
444
+ raise HTTPException(
445
+ status_code=500,
446
+ detail="Nenhuma legenda encontrada no intervalo especificado"
447
+ )
448
+
449
  # Retornar SRT em JSON
450
  return JSONResponse(
451
  content={
 
461
  raise HTTPException(status_code=400, detail=f"Erro ao baixar arquivo: {str(e)}")
462
  except Exception as e:
463
  raise HTTPException(status_code=500, detail=f"Erro ao gerar legendas: {str(e)}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
464
  finally:
465
  # Limpar arquivo temporário
466
  if temp_file and os.path.exists(temp_file.name):