Spaces:
Runtime error
Runtime error
| import gradio as gr | |
| import yt_dlp | |
| import os | |
| import tempfile | |
| def download_video(url, cookies, progress=gr.Progress()): | |
| try: | |
| # Get the path to the cookies file if provided | |
| cookies_path = cookies.get('name') if cookies else None | |
| with tempfile.TemporaryDirectory() as temp_dir: | |
| # Configure yt-dlp options | |
| ydl_opts = { | |
| 'format': 'bestvideo+bestaudio/best', | |
| 'outtmpl': os.path.join(temp_dir, '%(title)s.%(ext)s'), | |
| 'merge_output_format': 'mp4', | |
| 'progress_hooks': [lambda d: progress_hook(d, progress)], | |
| 'cookies': cookies_path, | |
| 'verbose': True, | |
| } | |
| # Download video using yt-dlp | |
| with yt_dlp.YoutubeDL(ydl_opts) as ydl: | |
| info_dict = ydl.extract_info(url, download=True) | |
| # Read downloaded video file into memory | |
| video_file = info_dict.get('filename') | |
| if not video_file: | |
| return "Download Failed: Could not retrieve video file" | |
| with open(video_file, 'rb') as f: | |
| video_bytes = f.read() | |
| # Return the video bytes for download | |
| return {'name': os.path.basename(video_file), 'data': video_bytes} | |
| except yt_dlp.utils.DownloadError as e: | |
| return f"Download Failed: {str(e)}" | |
| except Exception as e: | |
| return f"Unexpected Error: {str(e)}" | |
| def progress_hook(d, progress): | |
| if d['status'] == 'downloading': | |
| p = (d['downloaded_bytes'] / d['total_bytes']) * 100 if d['total_bytes'] else 0 | |
| progress.update(p, desc=f"Downloading ({d['speed'] or '...'} at {d['eta'] or '...'})") | |
| # Gradio interface configuration | |
| iface = gr.Interface( | |
| fn=download_video, | |
| inputs=[ | |
| gr.Textbox(label="YouTube Video URL"), | |
| gr.File(label="Upload your cookies.txt file (optional)", file_types=[".txt"], optional=True), | |
| ], | |
| outputs=gr.File(label="Downloaded Video", type="binary", file_count="single"), | |
| title="YouTube Video Downloader", | |
| description="Enter a YouTube video URL and upload your cookies.txt (if required) to download the video.", | |
| examples=[ | |
| ["https://www.youtube.com/watch?v=dQw4w9WgXcQ", None], | |
| ], | |
| ) | |
| # Launch the Gradio interface | |
| iface.queue() | |
| iface.launch(share=True) |