audio-trim / app.py
sheikhed's picture
Update app.py
05e0462 verified
raw
history blame
2.73 kB
import gradio as gr
import yt_dlp
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)
# Configure yt-dlp options
ydl_opts = {
'format': 'bestaudio/best',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192',
}],
'outtmpl': os.path.join(output_dir, '%(title)s.%(ext)s'),
'verbose': True
}
# Download with yt-dlp
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
# Get video info first
info = ydl.extract_info(url, download=False)
title = info.get('title', 'video')
duration = info.get('duration', 0)
author = info.get('uploader', 'Unknown')
# Download the video
ydl.download([url])
# Construct the output filepath
safe_title = sanitize_filename(title)
output_file = os.path.join(output_dir, f"{safe_title}.mp3")
return {
"status": "success",
"message": f"Successfully downloaded: {safe_title}",
"title": title,
"author": author,
"duration": f"{duration // 60}:{duration % 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()