import gradio as gr import yt_dlp import os from pydub import AudioSegment import re # Create downloads directory if it doesn't exist os.makedirs("downloads", exist_ok=True) def sanitize_filename(filename): """Sanitize the filename by removing or replacing special characters.""" return re.sub(r'[^a-zA-Z0-9_-]', '_', filename) def process_youtube_url(url, uploaded_file): """Process the YouTube URL or uploaded file to create ringtones.""" try: filename = None song_name = None # Download the song if a URL is provided if url: ydl_opts = { 'format': 'bestaudio/best', 'outtmpl': 'downloads/%(id)s.%(ext)s', 'cookiefile': 'cookies.txt' # Optional: use cookies for authentication } with yt_dlp.YoutubeDL(ydl_opts) as ydl: info = ydl.extract_info(url, download=True) filename = os.path.join('downloads', f"{info['id']}.webm") song_name = sanitize_filename(info['title']) # Use uploaded file if URL is not provided elif uploaded_file: filename = uploaded_file.name song_name = sanitize_filename(os.path.splitext(uploaded_file.name)[0]) # Ensure file exists if not filename or not os.path.exists(filename): return None, None, None # Convert to MP3 if not already converted mp3_filename = f"downloads/{song_name}.mp3" if not os.path.exists(mp3_filename): audio = AudioSegment.from_file(filename) audio.export(mp3_filename, format="mp3") # Convert to M4R (iPhone ringtone format), limiting length to 20 seconds ringtone_filename_m4r = f"downloads/{song_name}.m4r" if not os.path.exists(ringtone_filename_m4r): ringtone_audio = AudioSegment.from_file(mp3_filename)[:20000] # 20 seconds ringtone_audio.export(ringtone_filename_m4r, format="mp4") # Return file names for download return mp3_filename, ringtone_filename_m4r except Exception as e: print(f"Error: {e}") return None, None # Gradio UI with gr.Blocks() as interface: gr.HTML("""

Python YouTube Ringtones

Insert a URL to create ringtones or Upload an MP3 to convert.

""") with gr.Row(): youtube_url = gr.Textbox(label="Enter YouTube URL", placeholder="Paste the URL here...") mp3_upload = gr.File(label="Upload MP3 (Optional)") with gr.Row(): mp3_download = gr.File(label="Download Android Ringtone") iphone_ringtone = gr.File(label="Download iPhone Ringtone") process_button = gr.Button("Create Ringtones") process_button.click(process_youtube_url, inputs=[youtube_url, mp3_upload], outputs=[mp3_download, iphone_ringtone]) interface.launch(share=True)