habulaj commited on
Commit
50984c5
·
verified ·
1 Parent(s): d9ee666

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +80 -5
app.py CHANGED
@@ -6,6 +6,7 @@ import tempfile
6
  from pathlib import Path
7
  import re
8
  import requests
 
9
 
10
  from gemini_client import AsyncChatbot, Model, load_cookies
11
 
@@ -210,6 +211,82 @@ def clean_and_validate_srt(srt_content):
210
 
211
  return srt_corrigido.strip()
212
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
213
  @app.get("/subtitle")
214
  async def generate_subtitle(
215
  file: str,
@@ -237,10 +314,8 @@ async def generate_subtitle(
237
 
238
  temp_file = None
239
  try:
240
- # Baixar arquivo da URL
241
- print(f"📥 Baixando arquivo de: {file}")
242
- response = requests.get(file, timeout=300, stream=True)
243
- response.raise_for_status()
244
 
245
  # Determinar tipo de mídia e extensão
246
  content_type = response.headers.get('content-type', '').lower()
@@ -467,4 +542,4 @@ TRADUZA TUDO DE IMPORTANTE NO {media_desc_final}, que tenha dialogo... Nunca dei
467
  try:
468
  os.unlink(temp_file.name)
469
  except:
470
- pass
 
6
  from pathlib import Path
7
  import re
8
  import requests
9
+ import time
10
 
11
  from gemini_client import AsyncChatbot, Model, load_cookies
12
 
 
211
 
212
  return srt_corrigido.strip()
213
 
214
+ def download_file_with_retry(url: str, max_retries: int = 3, timeout: int = 300):
215
+ """
216
+ Baixa arquivo com retry logic e tratamento de rate limiting.
217
+
218
+ Parâmetros:
219
+ - url: URL do arquivo
220
+ - max_retries: Número máximo de tentativas
221
+ - timeout: Timeout em segundos
222
+
223
+ Retorna: Response object do requests
224
+ """
225
+ headers = {
226
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
227
+ 'Accept': '*/*',
228
+ 'Accept-Language': 'en-US,en;q=0.9',
229
+ 'Accept-Encoding': 'gzip, deflate, br',
230
+ 'Connection': 'keep-alive',
231
+ 'Upgrade-Insecure-Requests': '1'
232
+ }
233
+
234
+ for attempt in range(max_retries):
235
+ try:
236
+ if attempt > 0:
237
+ # Backoff exponencial: 2^attempt segundos
238
+ wait_time = 2 ** attempt
239
+ print(f"⏳ Aguardando {wait_time}s antes de tentar novamente (tentativa {attempt + 1}/{max_retries})...")
240
+ time.sleep(wait_time)
241
+
242
+ print(f"📥 Tentativa {attempt + 1}/{max_retries} - Baixando arquivo de: {url}")
243
+ response = requests.get(url, headers=headers, timeout=timeout, stream=True)
244
+
245
+ # Tratar erro 429 (Too Many Requests)
246
+ if response.status_code == 429:
247
+ retry_after = response.headers.get('Retry-After')
248
+ if retry_after:
249
+ wait_time = int(retry_after)
250
+ print(f"⚠️ Rate limit atingido. Aguardando {wait_time}s conforme Retry-After header...")
251
+ time.sleep(wait_time)
252
+ elif attempt < max_retries - 1:
253
+ # Se não houver Retry-After, usar backoff exponencial
254
+ wait_time = (2 ** attempt) * 5 # 5s, 10s, 20s...
255
+ print(f"⚠️ Rate limit atingido. Aguardando {wait_time}s antes de tentar novamente...")
256
+ time.sleep(wait_time)
257
+ continue
258
+ else:
259
+ raise HTTPException(
260
+ status_code=429,
261
+ detail=f"Rate limit atingido após {max_retries} tentativas. Tente novamente mais tarde."
262
+ )
263
+
264
+ response.raise_for_status()
265
+ return response
266
+
267
+ except requests.exceptions.HTTPError as e:
268
+ if e.response.status_code == 429 and attempt < max_retries - 1:
269
+ continue
270
+ elif attempt == max_retries - 1:
271
+ raise HTTPException(
272
+ status_code=400,
273
+ detail=f"Erro ao baixar arquivo após {max_retries} tentativas: {str(e)}"
274
+ )
275
+ else:
276
+ raise
277
+ except requests.exceptions.RequestException as e:
278
+ if attempt == max_retries - 1:
279
+ raise HTTPException(
280
+ status_code=400,
281
+ detail=f"Erro ao baixar arquivo após {max_retries} tentativas: {str(e)}"
282
+ )
283
+ continue
284
+
285
+ raise HTTPException(
286
+ status_code=400,
287
+ detail=f"Falha ao baixar arquivo após {max_retries} tentativas"
288
+ )
289
+
290
  @app.get("/subtitle")
291
  async def generate_subtitle(
292
  file: str,
 
314
 
315
  temp_file = None
316
  try:
317
+ # Baixar arquivo da URL com retry
318
+ response = download_file_with_retry(file, max_retries=3, timeout=300)
 
 
319
 
320
  # Determinar tipo de mídia e extensão
321
  content_type = response.headers.get('content-type', '').lower()
 
542
  try:
543
  os.unlink(temp_file.name)
544
  except:
545
+ pass