Remove proxys e ajusta qualidade dos videos
This commit is contained in:
129
main.py
129
main.py
@@ -8,7 +8,6 @@ from youtube_transcript_api.formatters import SRTFormatter
|
||||
from youtube_transcript_api._errors import TranscriptsDisabled, NoTranscriptFound
|
||||
from yt_dlp import YoutubeDL
|
||||
from utils import extract_video_id, sanitize_title
|
||||
from proxy_manager import execute_with_proxy_retry, ProxyError
|
||||
|
||||
app = FastAPI(
|
||||
title="YouTube Transcript, Download and Metadata API",
|
||||
@@ -77,7 +76,7 @@ def get_video_metadata(
|
||||
}
|
||||
|
||||
try:
|
||||
def extract_metadata(ydl):
|
||||
with YoutubeDL(ydl_opts) as ydl:
|
||||
info = ydl.extract_info(target, download=False, process=False)
|
||||
|
||||
if not info or 'title' not in info:
|
||||
@@ -102,17 +101,6 @@ def get_video_metadata(
|
||||
|
||||
if 'title' not in info:
|
||||
info['title'] = f"Vídeo {videoId or 'desconhecido'}"
|
||||
|
||||
return info
|
||||
|
||||
info = execute_with_proxy_retry(ydl_opts, extract_metadata, retry_per_proxy=1, max_proxies_to_try=3)
|
||||
|
||||
except ProxyError as e:
|
||||
error_msg = str(e).replace('\n', ' ').strip()
|
||||
raise HTTPException(
|
||||
status_code=503,
|
||||
detail=f"Erro com proxies: {error_msg}"
|
||||
)
|
||||
except Exception as e:
|
||||
error_msg = str(e).replace('\n', ' ').strip()
|
||||
try:
|
||||
@@ -163,7 +151,7 @@ def download_video(
|
||||
quality_map = {
|
||||
"low": "bestvideo[height<=480]+bestaudio/best[height<=480]/bestvideo[height<=480]/best[height<=480]/best",
|
||||
"medium": "bestvideo[height<=720]+bestaudio/best[height<=720]/bestvideo[height<=720]/best[height<=720]/best",
|
||||
"high": "bestvideo+bestaudio/best"
|
||||
"high": "bestvideo[height>=1080]+bestaudio/bestvideo+bestaudio/best"
|
||||
}
|
||||
qualidade = qualidade.lower()
|
||||
if qualidade not in quality_map:
|
||||
@@ -175,24 +163,12 @@ def download_video(
|
||||
unique_id = str(uuid.uuid4())
|
||||
output_template = os.path.join(videos_dir, f"{unique_id}.%(ext)s")
|
||||
|
||||
# Opções base para extração de metadados (operação rápida com proxy)
|
||||
metadata_opts = {
|
||||
"quiet": True,
|
||||
"no_warnings": True,
|
||||
"skip_download": True,
|
||||
"nocheckcertificate": True,
|
||||
"socket_timeout": 8,
|
||||
"retries": 0,
|
||||
"force_ipv4": True,
|
||||
"geo_bypass": True,
|
||||
"extractor_args": {"youtube": {"player_client": ["android"], "player_skip": ["webpage"]}},
|
||||
"http_headers": {
|
||||
"Accept-Language": "pt-BR,pt;q=0.9,en-US;q=0.8,en;q=0.7",
|
||||
"User-Agent": "com.google.android.youtube/19.17.36 (Linux; U; Android 13) gzip",
|
||||
},
|
||||
}
|
||||
|
||||
# Opções para download (operação pesada - tentará com e sem proxy)
|
||||
download_opts = {
|
||||
"format": quality_map[qualidade],
|
||||
"outtmpl": output_template,
|
||||
@@ -200,36 +176,13 @@ def download_video(
|
||||
"noplaylist": True,
|
||||
"merge_output_format": "mp4",
|
||||
"nocheckcertificate": True,
|
||||
"socket_timeout": 45, # Timeout menor para detectar falha de proxy rapidamente
|
||||
"retries": 0,
|
||||
"extractor_retries": 0,
|
||||
"force_ipv4": True,
|
||||
"geo_bypass": True,
|
||||
"fragment_retries": 3,
|
||||
"file_access_retries": 3,
|
||||
"extractor_args": {"youtube": {"player_client": ["android"], "player_skip": ["webpage"]}},
|
||||
"http_headers": {
|
||||
"Accept-Language": "pt-BR,pt;q=0.9,en-US;q=0.8,en;q=0.7",
|
||||
"User-Agent": "com.google.android.youtube/19.17.36 (Linux; U; Android 13) gzip",
|
||||
},
|
||||
"http_chunk_size": 1048576, # 1MB chunks
|
||||
}
|
||||
|
||||
try:
|
||||
# ETAPA 1: Extrair metadados COM PROXY (operação rápida)
|
||||
def extract_metadata_operation(ydl):
|
||||
info = ydl.extract_info(target, download=False)
|
||||
if not info or 'title' not in info:
|
||||
with YoutubeDL(metadata_opts) as ydl:
|
||||
metadata = ydl.extract_info(target, download=False)
|
||||
if not metadata or 'title' not in metadata:
|
||||
raise Exception("Não foi possível extrair metadados do vídeo")
|
||||
return info
|
||||
|
||||
# Tenta apenas 3 proxies para metadados antes de fallback
|
||||
metadata = execute_with_proxy_retry(
|
||||
metadata_opts,
|
||||
extract_metadata_operation,
|
||||
retry_per_proxy=1,
|
||||
max_proxies_to_try=3
|
||||
)
|
||||
|
||||
title = metadata.get("title", unique_id)
|
||||
clean_title = sanitize_title(title)
|
||||
@@ -244,43 +197,12 @@ def download_video(
|
||||
"cached": True
|
||||
}
|
||||
|
||||
# ETAPA 2: Download COM PROXY (tentativa rápida)
|
||||
def download_with_proxy(ydl):
|
||||
with YoutubeDL(download_opts) as ydl:
|
||||
result = ydl.extract_info(target, download=True)
|
||||
return result
|
||||
|
||||
download_success = False
|
||||
result = None
|
||||
|
||||
try:
|
||||
# Tenta apenas 2 proxies para download antes de fallback
|
||||
result = execute_with_proxy_retry(
|
||||
download_opts,
|
||||
download_with_proxy,
|
||||
retry_per_proxy=1,
|
||||
max_proxies_to_try=2
|
||||
)
|
||||
download_success = True
|
||||
except ProxyError as proxy_err:
|
||||
# ETAPA 3: Download SEM PROXY (fallback)
|
||||
|
||||
# Aumenta timeout para download sem proxy
|
||||
download_opts_no_proxy = {**download_opts, "socket_timeout": 180}
|
||||
|
||||
try:
|
||||
with YoutubeDL(download_opts_no_proxy) as ydl:
|
||||
result = ydl.extract_info(target, download=True)
|
||||
download_success = True
|
||||
except Exception as e:
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail=f"Falha no download com e sem proxy: {str(e)}"
|
||||
)
|
||||
|
||||
if not download_success or not result:
|
||||
if not result:
|
||||
raise HTTPException(status_code=500, detail="Erro desconhecido no download")
|
||||
|
||||
# Renomear arquivo para nome final
|
||||
|
||||
if "requested_downloads" in result and len(result["requested_downloads"]) > 0:
|
||||
real_file_path = result["requested_downloads"][0]["filepath"]
|
||||
elif "filepath" in result:
|
||||
@@ -301,8 +223,6 @@ def download_video(
|
||||
|
||||
except HTTPException:
|
||||
raise
|
||||
except ProxyError as e:
|
||||
raise HTTPException(status_code=503, detail=f"Erro com proxies: {e}")
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=f"Erro ao baixar vídeo: {e}")
|
||||
|
||||
@@ -323,7 +243,7 @@ def search_youtube_yt_dlp(
|
||||
search_query = f"ytsearch{max_results}:{q}"
|
||||
|
||||
try:
|
||||
def search_operation(ydl):
|
||||
with YoutubeDL(ydl_opts) as ydl:
|
||||
search_result = ydl.extract_info(search_query, download=False)
|
||||
entries = search_result.get("entries", [])[:max_results]
|
||||
|
||||
@@ -339,49 +259,32 @@ def search_youtube_yt_dlp(
|
||||
})
|
||||
return {"results": results}
|
||||
|
||||
return execute_with_proxy_retry(ydl_opts, search_operation, retry_per_proxy=1, max_proxies_to_try=3)
|
||||
|
||||
except ProxyError as e:
|
||||
raise HTTPException(status_code=503, detail=f"Erro com proxies: {e}")
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=f"Erro ao buscar vídeos: {e}")
|
||||
|
||||
@app.get("/list-formats")
|
||||
def list_formats(url: str):
|
||||
opts = {
|
||||
"quiet": False,
|
||||
"no_warnings": False,
|
||||
"noplaylist": True,
|
||||
"quiet": True,
|
||||
"skip_download": True,
|
||||
"nocheckcertificate": True,
|
||||
"force_ipv4": True,
|
||||
"geo_bypass": True,
|
||||
"extractor_args": {"youtube": {"player_client": ["android"], "player_skip": ["webpage"]}},
|
||||
"http_headers": {
|
||||
"Accept-Language": "pt-BR,pt;q=0.9,en-US;q=0.8,en;q=0.7",
|
||||
"User-Agent": "com.google.android.youtube/19.17.36 (Linux; U; Android 13) gzip",
|
||||
},
|
||||
"socket_timeout": 8,
|
||||
"retries": 0,
|
||||
"no_check_certificates": True,
|
||||
}
|
||||
|
||||
try:
|
||||
def list_formats_operation(ydl):
|
||||
with YoutubeDL(opts) as ydl:
|
||||
info = ydl.extract_info(url, download=False)
|
||||
fmts = info.get("formats") or []
|
||||
brief = [{
|
||||
"id": f.get("format_id"),
|
||||
"ext": f.get("ext"),
|
||||
"h": f.get("height"),
|
||||
"height": f.get("height"),
|
||||
"fps": f.get("fps"),
|
||||
"v": f.get("vcodec"),
|
||||
"a": f.get("acodec"),
|
||||
"vcodec": f.get("vcodec"),
|
||||
"acodec": f.get("acodec"),
|
||||
"tbr": f.get("tbr"),
|
||||
} for f in fmts]
|
||||
return {"total": len(brief), "formats": brief[:60]}
|
||||
|
||||
return execute_with_proxy_retry(opts, list_formats_operation, retry_per_proxy=1, max_proxies_to_try=3)
|
||||
|
||||
except ProxyError as e:
|
||||
raise HTTPException(status_code=503, detail=f"Erro com proxies: {e}")
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=f"Erro ao listar formatos: {e}")
|
||||
|
||||
Reference in New Issue
Block a user