From 6f3798d4355474bb6b7e9fc2041d26f7d75b808b Mon Sep 17 00:00:00 2001 From: LeoMortari Date: Sun, 28 Sep 2025 01:54:28 -0300 Subject: [PATCH] =?UTF-8?q?Demais=20ajustes=20na=20fun=C3=A7=C3=A3o?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- main.py | 48 +++++++++++++++++++++++++++++++++++------------- 1 file changed, 35 insertions(+), 13 deletions(-) diff --git a/main.py b/main.py index 1382138..4849b4f 100644 --- a/main.py +++ b/main.py @@ -156,35 +156,57 @@ def download_video( target = f"https://www.youtube.com/watch?v={videoId}" video_id = videoId - quality_map = { - "low": "bestvideo[height<=480]+bestaudio/best[height<=480]", - "medium": "bestvideo[height<=720]+bestaudio/best[height<=720]", - "high": "bestvideo+bestaudio/best" + quality_presets = { + "low": [ + "bestvideo[height<=480]+bestaudio/best[height<=480]", + "best[height<=480]", + "best" + ], + "medium": [ + "bestvideo[height<=720]+bestaudio/best[height<=720]", + "best[height<=720]", + "best" + ], + "high": [ + "bestvideo+bestaudio/best", + "best" + ] } + qualidade = qualidade.lower() - if qualidade not in quality_map: + if qualidade not in quality_presets: raise HTTPException(status_code=400, detail="Qualidade deve ser: low, medium ou high") + + format_options = quality_presets[qualidade] videos_dir = "/app/videos" os.makedirs(videos_dir, exist_ok=True) unique_id = str(uuid.uuid4()) output_template = os.path.join(videos_dir, f"{unique_id}.%(ext)s") - + ydl_opts = { - "format": quality_map[qualidade], - "outtmpl": output_template, + 'outtmpl': output_template, 'quiet': True, 'no_warnings': True, - 'skip_download': True, 'nocheckcertificate': True, - 'ignoreerrors': True, + 'ignoreerrors': False, 'no_color': True, 'extract_flat': 'in_playlist', 'force_generic_extractor': True, 'allow_unplayable_formats': True, } + def try_download(ydl, format_spec, attempt=1): + ydl.params['format'] = format_spec + + try: + return ydl.extract_info(target, download=True) + except Exception as e: + if attempt < len(format_options): + return try_download(ydl, format_options[attempt], attempt + 1) + raise + try: with YoutubeDL(ydl_opts) as ydl: base = ydl.extract_info(target, download=False) @@ -210,7 +232,7 @@ def download_video( filename = f"{clean_title}_{qualidade}.mp4" final_path = os.path.join(videos_dir, filename) - print('Info ok') + print('Informações do vídeo obtidas com sucesso') if os.path.exists(final_path): return { @@ -218,9 +240,9 @@ def download_video( "filename": filename } - print('Lets download') + print(f'Iniciando download com qualidade: {qualidade}') - result = ydl.extract_info(target, download=True) + result = try_download(ydl, format_options[0]) if "requested_downloads" in result and len(result["requested_downloads"]) > 0: real_file_path = result["requested_downloads"][0]["filepath"]