Spaces:
Sleeping
Sleeping
File size: 2,175 Bytes
d7bc426 5e107b7 d7bc426 5e107b7 d7bc426 5e107b7 d7bc426 5e107b7 d7bc426 5e107b7 d7bc426 5e107b7 d7bc426 5e107b7 d7bc426 5e107b7 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
import gradio as gr
from pytube import YouTube
import os
import re
def sanitize_filename(title):
"""Remove invalid characters from filename"""
return re.sub(r'[<>:"/\\|?*]', '', title)
def download_audio(url, output_dir="downloads"):
try:
# Create output directory if it doesn't exist
if not os.path.exists(output_dir):
os.makedirs(output_dir)
# Create YouTube object
yt = YouTube(url)
# Get audio stream
audio_stream = yt.streams.filter(only_audio=True).first()
# Sanitize the title for filename
safe_title = sanitize_filename(yt.title)
# Download the audio
output_file = audio_stream.download(
output_path=output_dir,
filename=f"{safe_title}.mp3"
)
return {
"status": "success",
"message": f"Successfully downloaded: {safe_title}",
"title": yt.title,
"author": yt.author,
"duration": f"{yt.length // 60}:{yt.length % 60:02d}",
"file_path": output_file
}
except Exception as e:
return {
"status": "error",
"message": f"Error: {str(e)}",
"title": "",
"author": "",
"duration": "",
"file_path": ""
}
def process_url(url):
if not url.strip():
return "Please enter a YouTube URL"
result = download_audio(url)
if result["status"] == "error":
return result["message"]
return f"""Download successful!
Title: {result['title']}
Author: {result['author']}
Duration: {result['duration']}
Saved to: {result['file_path']}"""
# Create Gradio interface
iface = gr.Interface(
fn=process_url,
inputs=gr.Textbox(label="YouTube URL", placeholder="Enter YouTube video URL here..."),
outputs=gr.Textbox(label="Status"),
title="YouTube to MP3 Downloader",
description="Enter a YouTube URL to download the audio as MP3",
examples=[["https://www.youtube.com/watch?v=dQw4w9WgXcQ"]],
theme=gr.themes.Base()
)
if __name__ == "__main__":
iface.launch() |