Spaces:
Runtime error
Runtime error
| from yt_dlp import YoutubeDL | |
| import os | |
| import browser_cookie3 | |
| def download_video(url, download_dir=None, browser_name='chrome'): | |
| try: | |
| # Set download options | |
| ydl_opts = { | |
| 'format': 'best', # Download the best quality available | |
| 'outtmpl': os.path.join(download_dir, '%(title)s.%(ext)s') if download_dir else '%(title)s.%(ext)s', | |
| 'quiet': True, # Suppress output (set to False for debugging) | |
| } | |
| cookies_file = None | |
| # Extract cookies from the browser | |
| if browser_name == 'chrome': | |
| cookies = browser_cookie3.chrome(domain_name='youtube.com') | |
| elif browser_name == 'firefox': | |
| cookies = browser_cookie3.firefox(domain_name='youtube.com') | |
| elif browser_name == 'edge': | |
| cookies = browser_cookie3.edge(domain_name='youtube.com') | |
| else: | |
| raise ValueError(f"Unsupported browser: {browser_name}") | |
| # Save cookies to a temporary file | |
| cookies_file = 'cookies.txt' | |
| with open(cookies_file, 'w') as f: | |
| for cookie in cookies: | |
| f.write(f"{cookie.name}\t{cookie.value}\t{cookie.domain}\t{cookie.path}\t{cookie.expires}\t{cookie.secure}\n") | |
| # Add cookies to yt-dlp options | |
| ydl_opts['cookiefile'] = cookies_file | |
| with YoutubeDL(ydl_opts) as ydl: | |
| info_dict = ydl.extract_info(url, download=True) # Extract video info and download | |
| video_path = ydl.prepare_filename(info_dict) # Get the path of the downloaded file | |
| return video_path | |
| except Exception as e: | |
| return f"An error occurred: {e}" | |
| finally: | |
| # Clean up the temporary cookies file | |
| if os.path.exists(cookies_file): | |
| os.remove(cookies_file) |