myVideo / app.py
shiue20's picture
Update app.py
4e6a7ae verified
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()