| import os | |
| import tempfile | |
| from yt_dlp import YoutubeDL | |
| import gradio as gr | |
| def download_video(url): | |
| if not url.strip(): | |
| raise gr.Error("β οΈ Please enter a valid YouTube or TikTok URL.") | |
| temp_dir = tempfile.mkdtemp() | |
| output_path = os.path.join(temp_dir, "%(title)s.%(ext)s") | |
| ydl_opts = { | |
| 'format': 'best', | |
| 'outtmpl': output_path, | |
| 'quiet': True, | |
| 'no_warnings': True, | |
| 'noplaylist': True, | |
| 'socket_timeout': 15, | |
| } | |
| try: | |
| with YoutubeDL(ydl_opts) as ydl: | |
| info = ydl.extract_info(url, download=True) | |
| downloaded_file = ydl.prepare_filename(info) | |
| if not os.path.exists(downloaded_file): | |
| raise gr.Error("β Download failed. File not found.") | |
| return downloaded_file | |
| except Exception as e: | |
| err = str(e) | |
| if "Failed to extract" in err or "player response" in err: | |
| raise gr.Error( | |
| "β Extraction error β YouTube/TikTok may have changed.\n" | |
| "Try updating yt-dlp using:\n\n`pip install -U yt-dlp`" | |
| ) | |
| elif "resolve" in err: | |
| raise gr.Error("β This Space doesn't have internet access. Enable internet in Settings.") | |
| else: | |
| raise gr.Error(f"β Error: {err}") | |
| demo = gr.Interface( | |
| fn=download_video, | |
| inputs=gr.Textbox(label="π₯ Enter YouTube or TikTok URL"), | |
| outputs=gr.File(label="π Downloaded Video File"), | |
| title="π¬ Video Downloader", | |
| description="Download videos from YouTube or TikTok. Paste a valid video link and get the file.", | |
| theme="default" | |
| ) | |
| if __name__ == "__main__": | |
| demo.launch() | |