audio-trim / app.py
sheikhed's picture
Update app.py
5e107b7 verified
raw
history blame
2.18 kB
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()