Spaces:
Paused
Paused
Update app2.py
Browse files5 unmodified lines678910111291011121314151819161718192021221 unmodified line242526282728293031321 unmodified line34353637373839404041424344454546474748495012 unmodified lines6364656666676869697071727373747576767778798081828384858687888990919293949596979899100101102103104105106787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401081091411421431441451461471481491501111121511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981991141151161171181191201211221231241252002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682691271282702712721301311321331341351361371381391402732742752762772782792802812822832842852862871431441451462882892902912922931491501511521532942952962972982993003013023033043053061563073083091591601611623103111643123133143155 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 """def download_youtube_audio(url, file_format, duration_sec): """Download and process audio from YouTube""" try: # Download best audio available ydl_opts = { 'format': 'bestaudio/best', 'outtmpl': os.path.join(DOWNLOADS_FOLDER, '%(title)s.%(ext)s'), 'quiet': True, 'no_warnings': True, 'quiet': False, 'no_warnings': False, 'extract_flat': False, 'noplaylist': True, # Don't download playlists } with YoutubeDL(ydl_opts) as ydl:1 unmodified line original_file = os.path.join(DOWNLOADS_FOLDER, f"{info['title']}.{info['ext']}") # Clean filename (remove special characters) # Clean filename safe_title = "".join(c for c in info['title'] if c.isalnum() or c in (' ', '-', '_')).rstrip() safe_title = safe_title[:100] # Limit filename length original_file_safe = os.path.join(DOWNLOADS_FOLDER, f"{safe_title}.{info['ext']}") # Rename if necessary1 unmodified line os.rename(original_file, original_file_safe) original_file = original_file_safe # Load audio and trim to duration # Load audio audio = AudioSegment.from_file(original_file) # Handle duration parameter # Handle duration if 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 trimmed_audio = audio # Full track # Determine output file path based on desired format # Determine output file base_name = os.path.splitext(original_file)[0] if file_format.lower() == "mp3":12 unmodified lines output_file = base_name + ".m4a" trimmed_audio.export(output_file, format="ipod", codec="aac") else: # keep original format else: # keep original output_file = original_file # Optional: Remove original downloaded file to save space # Clean up original if converted if output_file != original_file and os.path.exists(original_file): os.remove(original_file) return output_file return output_file, f"✅ Downloaded: {os.path.basename(output_file)}" except Exception as e: raise gr.Error(f"Error downloading audio: {str(e)}") raise gr.Error(f"Error downloading from YouTube: {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 minutes value=60, step=5, label="Duration (seconds)", info="Maximum duration to download (0 = full track)" )def download_soundcloud_audio(url, file_format, duration_sec): """Download and process audio from SoundCloud""" try: # SoundCloud specific options ydl_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 filename safe_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 audio audio = 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 format base_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 up if output_file != original_file and os.path.exists(original_file): os.remove(original_file) return output_file, f"✅ Downloaded: {os.path.basename(output_file)}" with gr.Row(): download_button = gr.Button("Download Audio", variant="primary", size="lg") 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: with gr.Row(): download_file = gr.File(label="Download your audio", interactive=False) gr.Markdown("# 🎵 Audio Downloader") gr.Markdown("Download audio from YouTube or SoundCloud") # Create tabs with gr.Tabs(): # YouTube Tab with 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 YouTube value=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 ) # Example URLs with 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="" ) # YouTube examples with 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 Tab with 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 SoundCloud value=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 examples with 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:" ) # Add instructions with gr.Accordion("Instructions", open=False): # Instructions with gr.Accordion("📖 Instructions & Info", open=False): gr.Markdown(""" ### How to use: 1. Paste a YouTube or SoundCloud URL 2. Choose your desired output format 3. 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 ### How to Use: 1. **Select the platform tab** (YouTube or SoundCloud) 2. **Paste a URL** from the selected platform 3. **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: - 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) - 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 """) download_button.click( fn=download_audio, inputs=[url_input, format_choice, duration_slider], outputs=download_file, show_progress=True # Connect button events youtube_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 interface# Launch the appif __name__ == "__main__": iface.launch( theme=gr.themes.Soft(), show_error=True, share=False, # Set to True to create a public link server_name="0.0.0.0" if os.getenv("GRADIO_SHARE") else "127.0.0.1", server_name="127.0.0.1", server_port=7860, ssr_mode=False # Disable SSR to avoid the warning show_error=True, share=False, theme=gr.themes.Soft() )app2.py+238-88