fix yt-dlp error in prod

This commit is contained in:
juancarlos.cavero 2025-12-19 21:30:53 +01:00
parent fbe2871ed0
commit 99eb1b19ce

58
main.py
View file

@ -205,30 +205,45 @@ def download_youtube_video(url, output_dir="."):
step_start_time = time.time() step_start_time = time.time()
# 2. Common Options (Try Android client to bypass bot check) # 2. Try multiple clients to bypass bot check
common_opts = { clients_to_try = ['ios', 'android', 'web', 'tv']
info = None
# Check if cookies are available
has_cookies = cookies_path and os.path.exists(cookies_path)
if not has_cookies:
print("⚠️ No cookies found. This increases the risk of bot detection.")
for client in clients_to_try:
print(f"🔄 Attempting extraction with client: {client}...")
current_opts = {
'quiet': True, 'quiet': True,
'no_warnings': True, 'no_warnings': True,
'cookiefile': cookies_path if os.path.exists(cookies_path) else None, 'cookiefile': cookies_path if has_cookies else None,
'extractor_args': { 'extractor_args': {
'youtube': { 'youtube': {
'player_client': ['android', 'web'] 'player_client': [client, 'web'],
} 'player_skip': ['webpage', 'configs'] if client in ['android', 'ios'] else []
} }
},
# Force IPv4 as IPv6 datacenter ranges are often blocked
'source_address': '0.0.0.0',
# Add sleep interval to avoid rate limiting
'sleep_interval': 2,
'max_sleep_interval': 5,
} }
# Extract Info
try: try:
with yt_dlp.YoutubeDL(common_opts) as ydl: with yt_dlp.YoutubeDL(current_opts) as ydl:
info = ydl.extract_info(url, download=False) info = ydl.extract_info(url, download=False)
print(f"✅ Success with client: {client}")
break
except Exception as e: except Exception as e:
print(f"⚠️ Extraction with Android client failed: {e}") print(f"⚠️ Failed with {client}: {e}")
print("🔄 Retrying with default client...")
# Fallback to default client if not info:
fallback_opts = common_opts.copy() print("❌ All clients failed. You MUST provide cookies via YOUTUBE_COOKIES env var.")
fallback_opts.pop('extractor_args', None) raise Exception("YouTube blocked all access attempts. Cookies required.")
with yt_dlp.YoutubeDL(fallback_opts) as ydl:
info = ydl.extract_info(url, download=False)
video_title = info.get('title', 'youtube_video') video_title = info.get('title', 'youtube_video')
sanitized_title = sanitize_filename(video_title) sanitized_title = sanitize_filename(video_title)
@ -239,15 +254,22 @@ def download_youtube_video(url, output_dir="."):
os.remove(expected_file) os.remove(expected_file)
print(f"🗑️ Removed existing file to re-download with H.264 codec") print(f"🗑️ Removed existing file to re-download with H.264 codec")
# Download # Download with the successful client configuration
ydl_opts = common_opts.copy() ydl_opts = {
ydl_opts.update({
'format': 'bestvideo[vcodec^=avc1][ext=mp4]+bestaudio[ext=m4a]/bestvideo[vcodec^=avc1]+bestaudio/best[ext=mp4]/best', 'format': 'bestvideo[vcodec^=avc1][ext=mp4]+bestaudio[ext=m4a]/bestvideo[vcodec^=avc1]+bestaudio/best[ext=mp4]/best',
'outtmpl': output_template, 'outtmpl': output_template,
'merge_output_format': 'mp4', 'merge_output_format': 'mp4',
'quiet': False, 'quiet': False,
'overwrites': True, 'overwrites': True,
}) 'cookiefile': cookies_path if has_cookies else None,
'extractor_args': {
'youtube': {
'player_client': [client, 'web'],
'player_skip': ['webpage', 'configs'] if client in ['android', 'ios'] else []
}
},
'source_address': '0.0.0.0',
}
# We use the same opts logic (try Android first, fallback implies logic complexity so for download we stick to opts) # We use the same opts logic (try Android first, fallback implies logic complexity so for download we stick to opts)
# If extraction worked with common_opts, download should too. # If extraction worked with common_opts, download should too.