Spaces:
Paused
Paused
Update app2.py
Browse files5 unmodified lines678910111213141516171819202122231 unmodified line25262728293031321 unmodified line343536373839404142434445464748495012 unmodified lines636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641655 unmodified linesDOWNLOADS_FOLDER = "downloads"os.makedirs(DOWNLOADS_FOLDER, exist_ok=True)def download_audio(url, file_format, duration_sec):"""Download audio from YouTube or SoundCloud and convert to desired format"""try:# Download best audio availableydl_opts = {'format': 'bestaudio/best','outtmpl': os.path.join(DOWNLOADS_FOLDER, '%(title)s.%(ext)s'),'quiet': True,'no_warnings': True,'extract_flat': False,}with YoutubeDL(ydl_opts) as ydl:1 unmodified lineoriginal_file = os.path.join(DOWNLOADS_FOLDER, f"{info['title']}.{info['ext']}")# Clean filename (remove special characters)safe_title = "".join(c for c in info['title'] if c.isalnum() or c in (' ', '-', '_')).rstrip()original_file_safe = os.path.join(DOWNLOADS_FOLDER, f"{safe_title}.{info['ext']}")# Rename if necessary1 unmodified lineos.rename(original_file, original_file_safe)original_file = original_file_safe# Load audio and trim to durationaudio = AudioSegment.from_file(original_file)# Handle duration parameterif duration_sec > 0:duration_ms = min(len(audio), int(duration_sec * 1000))trimmed_audio = audio[:duration_ms]else:trimmed_audio = audio # Full track if duration is 0# Determine output file path based on desired formatbase_name = os.path.splitext(original_file)[0]if file_format.lower() == "mp3":12 unmodified linesoutput_file = base_name + ".m4a"trimmed_audio.export(output_file, format="ipod", codec="aac")else: # keep original formatoutput_file = original_file# Optional: Remove original downloaded file to save spaceif output_file != original_file and os.path.exists(original_file):os.remove(original_file)return output_fileexcept Exception as e:raise gr.Error(f"Error downloading audio: {str(e)}")# Create Gradio interfacewith gr.Blocks(title="Audio Downloader") as iface:gr.Markdown("# 🎵 YouTube & SoundCloud Audio Downloader")gr.Markdown("Download audio from YouTube or SoundCloud and convert to your preferred format")with gr.Row():url_input = gr.Textbox(label="Enter URL",placeholder="Paste YouTube or SoundCloud URL here...",scale=4)with gr.Row():with gr.Column(scale=1):format_choice = gr.Dropdown(choices=["mp3", "m4a", "opus", "wav"],value="mp3",label="Output Format")with gr.Column(scale=3):duration_slider = gr.Slider(minimum=0,maximum=600, # Increased to 10 minutesvalue=60,step=5,label="Duration (seconds)",info="Maximum duration to download (0 = full track)")with gr.Row():download_button = gr.Button("Download Audio", variant="primary", size="lg")with gr.Row():download_file = gr.File(label="Download your audio", interactive=False)# Example URLswith gr.Accordion("Example URLs (click to use)", open=False):gr.Examples(examples=[["https://www.youtube.com/watch?v=dQw4w9WgXcQ"],["https://soundcloud.com/antonio-antetomaso/mutiny-on-the-bounty-closing-titles-cover"],["https://www.youtube.com/watch?v=JGwWNGJdvx8"],["https://soundcloud.com/officialnikkig/kill-bill-sza-kill-bill-remix"]],inputs=url_input,label="")# Add instructionswith gr.Accordion("Instructions", open=False):gr.Markdown("""### How to use:1. Paste a YouTube or SoundCloud URL2. Choose your desired output format3. Set the maximum duration (or set to 0 for full track)4. Click "Download Audio"### Supported formats:- **MP3**: Most compatible, good quality- **M4A**: Apple format, smaller file size- **Opus**: Best quality at low bitrates- **WAV**: Lossless, large file size### Notes:- Downloads are saved to a 'downloads' folder- Some tracks may have download restrictions- Very long videos may take time to process- Minimum duration is now 0 (for full tracks)""")download_button.click(fn=download_audio,inputs=[url_input, format_choice, duration_slider],outputs=download_file,show_progress=True)# Launch the interfaceif __name__ == "__main__":iface.launch(theme=gr.themes.Soft(),show_error=True,share=False, # Set to True to create a public linkserver_name="0.0.0.0" if os.getenv("GRADIO_SHARE") else "127.0.0.1",server_port=7860,ssr_mode=False # Disable SSR to avoid the warning)5 unmodified lines6789101112131415161718192021221 unmodified line2425262728293031321 unmodified line343536373839404142434445464748495012 unmodified lines636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143155 unmodified linesDOWNLOADS_FOLDER = "downloads"os.makedirs(DOWNLOADS_FOLDER, exist_ok=True)def download_youtube_audio(url, file_format, duration_sec):"""Download and process audio from YouTube"""try:# Download best audio availableydl_opts = {'format': 'bestaudio/best','outtmpl': os.path.join(DOWNLOADS_FOLDER, '%(title)s.%(ext)s'),'quiet': False,'no_warnings': False,'extract_flat': False,'noplaylist': True, # Don't download playlists}with YoutubeDL(ydl_opts) as ydl:1 unmodified lineoriginal_file = os.path.join(DOWNLOADS_FOLDER, f"{info['title']}.{info['ext']}")# Clean filenamesafe_title = "".join(c for c in info['title'] if c.isalnum() or c in (' ', '-', '_')).rstrip()safe_title = safe_title[:100] # Limit filename lengthoriginal_file_safe = os.path.join(DOWNLOADS_FOLDER, f"{safe_title}.{info['ext']}")# Rename if necessary1 unmodified lineos.rename(original_file, original_file_safe)original_file = original_file_safe# Load audioaudio = AudioSegment.from_file(original_file)# Handle durationif duration_sec > 0:duration_ms = min(len(audio), int(duration_sec * 1000))trimmed_audio = audio[:duration_ms]else:trimmed_audio = audio # Full track# Determine output filebase_name = os.path.splitext(original_file)[0]if file_format.lower() == "mp3":12 unmodified linesoutput_file = base_name + ".m4a"trimmed_audio.export(output_file, format="ipod", codec="aac")else: # keep originaloutput_file = original_file# Clean up original if convertedif output_file != original_file and os.path.exists(original_file):os.remove(original_file)return output_file, f"✅ Downloaded: {os.path.basename(output_file)}"except Exception as e:raise gr.Error(f"Error downloading from YouTube: {str(e)}")def download_soundcloud_audio(url, file_format, duration_sec):"""Download and process audio from SoundCloud"""try:# SoundCloud specific optionsydl_opts = {'format': 'bestaudio/best','outtmpl': os.path.join(DOWNLOADS_FOLDER, '%(title)s.%(ext)s'),'quiet': False,'no_warnings': False,'extract_flat': False,}with YoutubeDL(ydl_opts) as ydl:info = ydl.extract_info(url, download=True)original_file = os.path.join(DOWNLOADS_FOLDER, f"{info['title']}.{info['ext']}")# Clean filenamesafe_title = "".join(c for c in info['title'] if c.isalnum() or c in (' ', '-', '_')).rstrip()safe_title = safe_title[:100]original_file_safe = os.path.join(DOWNLOADS_FOLDER, f"{safe_title}.{info['ext']}")if original_file != original_file_safe:os.rename(original_file, original_file_safe)original_file = original_file_safe# Load and process audioaudio = AudioSegment.from_file(original_file)if duration_sec > 0:duration_ms = min(len(audio), int(duration_sec * 1000))trimmed_audio = audio[:duration_ms]else:trimmed_audio = audio# Convert to desired formatbase_name = os.path.splitext(original_file)[0]if file_format.lower() == "mp3":output_file = base_name + ".mp3"trimmed_audio.export(output_file, format="mp3", bitrate="192k")elif file_format.lower() == "opus":output_file = base_name + ".opus"trimmed_audio.export(output_file, format="opus", bitrate="128k")elif file_format.lower() == "wav":output_file = base_name + ".wav"trimmed_audio.export(output_file, format="wav")elif file_format.lower() == "m4a":output_file = base_name + ".m4a"trimmed_audio.export(output_file, format="ipod", codec="aac")else:output_file = original_file# Clean upif output_file != original_file and os.path.exists(original_file):os.remove(original_file)return output_file, f"✅ Downloaded: {os.path.basename(output_file)}"except Exception as e:raise gr.Error(f"Error downloading from SoundCloud: {str(e)}")# Create Gradio interfacewith gr.Blocks(title="Audio Downloader", css=""".tab-nav { background-color: #f0f0f0; }.download-btn { margin-top: 20px; }.status-box { margin-top: 10px; }""") as iface:gr.Markdown("# 🎵 Audio Downloader")gr.Markdown("Download audio from YouTube or SoundCloud")# Create tabswith gr.Tabs():# YouTube Tabwith gr.TabItem("YouTube", id="youtube"):with gr.Row():with gr.Column():youtube_url = gr.Textbox(label="YouTube URL",placeholder="https://www.youtube.com/watch?v=...",lines=1)with gr.Row():youtube_format = gr.Dropdown(choices=["mp3", "m4a", "opus", "wav"],value="mp3",label="Output Format")youtube_duration = gr.Slider(minimum=0,maximum=1800, # 30 minutes max for YouTubevalue=60,step=5,label="Duration (seconds)",info="0 = full video")youtube_btn = gr.Button("Download from YouTube",variant="primary",size="lg",elem_classes="download-btn")youtube_status = gr.Textbox(label="Status",interactive=False,elem_classes="status-box")youtube_output = gr.File(label="Downloaded File",interactive=False)# YouTube exampleswith gr.Accordion("YouTube Examples", open=False):gr.Examples(examples=[["https://www.youtube.com/watch?v=dQw4w9WgXcQ"],["https://www.youtube.com/watch?v=JGwWNGJdvx8"],["https://www.youtube.com/watch?v=9bZkp7q19f0"],["https://www.youtube.com/watch?v=kJQP7kiw5Fk"]],inputs=youtube_url,label="Try these URLs:")# SoundCloud Tabwith gr.TabItem("SoundCloud", id="soundcloud"):with gr.Row():with gr.Column():soundcloud_url = gr.Textbox(label="SoundCloud URL",placeholder="https://soundcloud.com/...",lines=1)with gr.Row():soundcloud_format = gr.Dropdown(choices=["mp3", "m4a", "opus", "wav"],value="mp3",label="Output Format")soundcloud_duration = gr.Slider(minimum=0,maximum=600, # 10 minutes max for SoundCloudvalue=60,step=5,label="Duration (seconds)",info="0 = full track")soundcloud_btn = gr.Button("Download from SoundCloud",variant="primary",size="lg",elem_classes="download-btn")soundcloud_status = gr.Textbox(label="Status",interactive=False,elem_classes="status-box")soundcloud_output = gr.File(label="Downloaded File",interactive=False)# SoundCloud exampleswith gr.Accordion("SoundCloud Examples", open=False):gr.Examples(examples=[["https://soundcloud.com/antonio-antetomaso/mutiny-on-the-bounty-closing-titles-cover"],["https://soundcloud.com/officialnikkig/kill-bill-sza-kill-bill-remix"],["https://soundcloud.com/lofi-girl"],["https://soundcloud.com/user-123456789/sample-track"]],inputs=soundcloud_url,label="Try these URLs:")# Instructionswith gr.Accordion("📖 Instructions & Info", open=False):gr.Markdown("""### How to Use:1. **Select the platform tab** (YouTube or SoundCloud)2. **Paste a URL** from the selected platform3. **Choose output format** (MP3, M4A, Opus, or WAV)4. **Set duration** (0 for full track, or specify seconds)5. **Click Download** button### Features:- **YouTube**: Download audio from any YouTube video- **SoundCloud**: Download tracks from SoundCloud- **Format Conversion**: Convert to MP3, M4A, Opus, or WAV- **Duration Control**: Extract specific segments or full tracks- **Clean Interface**: Separate tabs for each platform### Notes:- Files are saved in the 'downloads' folder- Some content may have download restrictions- Long videos may take time to process- Original files are deleted after conversion""")# Connect button eventsyoutube_btn.click(fn=download_youtube_audio,inputs=[youtube_url, youtube_format, youtube_duration],outputs=[youtube_output, youtube_status])soundcloud_btn.click(fn=download_soundcloud_audio,inputs=[soundcloud_url, soundcloud_format, soundcloud_duration],outputs=[soundcloud_output, soundcloud_status])# Launch the appif __name__ == "__main__":iface.launch(server_name="127.0.0.1",server_port=7860,show_error=True,share=False,theme=gr.themes.Soft())
app2.py+238-88