Spaces:
Build error
Build error
Redo whole script
Browse files123456787 unmodified lines16171819202122232473 unmodified lines989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813910 unmodified lines1501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791804 unmodified lines1851861871881891901911921931945 unmodified lines2002012022032042052062072082098 unmodified lines2182192202212222232242 unmodified lines227228229230231232233234235236237238239240# 1. Install all necessary libraries for the full application# This line is for Colab. On Hugging Face, these should be in your requirements.txt# !pip install gradio "demucs>=4.0.0" librosa soundfile matplotlib# 2. Import librariesimport gradio as grimport osimport shutil7 unmodified linesimport tempfileimport matplotlib.pyplot as pltimport matplotlibmatplotlib.use('Agg') # Use a non-interactive backend for plotting# --- Helper/Processing Functions ---def update_output_visibility(choice):if "2 Stems" in choice:73 unmodified linesfig, ax = plt.subplots(figsize=(10, 3))fig.patch.set_facecolor('#1f2937')ax.set_facecolor('#111827')librosa.display.waveshow(y, sr=sample_rate, ax=ax, color='#32f6ff', alpha=0.7)for t in onset_times:ax.axvline(x=t, color='#ff3b3b', linestyle='--', linewidth=1)ax.tick_params(colors='gray')ax.xaxis.label.set_color('gray')ax.yaxis.label.set_color('gray')ax.set_xlabel("Time (s)")ax.set_ylabel("Amplitude")ax.set_title("Detected Slices", color='white')plt.tight_layout()progress(1, desc="Done!")return fig, onset_times, stem_audio_datadef preview_slice(active_stem_audio, onset_times, evt: gr.SelectData):if active_stem_audio is None or onset_times is None:return Nonesample_rate, y = active_stem_audioclicked_time = evt.index[0]start_time = 0end_time = len(y) / sample_ratefor i, t in enumerate(onset_times):if t > clicked_time:end_time = tbreakstart_time = tstart_sample = librosa.time_to_samples(start_time, sr=sample_rate)end_sample = librosa.time_to_samples(end_time, sr=sample_rate)sliced_audio = y[start_sample:end_sample]return (sample_rate, sliced_audio)10 unmodified linesreturn [], []def create_final_pack(selection_list, progress=gr.Progress(track_tqdm=True)):if not selection_list:raise gr.Error("No slices have been selected to create a pack!")progress(0, desc="Preparing final pack...")zip_path = "Custom_Loop_Pack.zip"temp_dir = tempfile.mkdtemp()with zipfile.ZipFile(zip_path, 'w') as zf:for i, audio_data in enumerate(selection_list):progress(i / len(selection_list), desc=f"Adding slice {i+1} to pack...")sample_rate, y = audio_datafilename = os.path.join(temp_dir, f"slice_{i+1:03d}.wav")sf.write(filename, y, sample_rate, subtype='PCM_16')zf.write(filename, os.path.basename(filename))shutil.rmtree(temp_dir)progress(1, desc="Pack Ready!")return zip_path, gr.update(visible=True)# --- Create the full Gradio Interface ---with gr.Blocks(theme=gr.themes.Default(primary_hue="blue", secondary_hue="red")) as demo:gr.Markdown("# 🎵 Loop Architect")# State componentsonset_times_state = gr.State(value=None)active_stem_state = gr.State(value=None)selected_slices_state = gr.State(value=[])4 unmodified linesaudio_input = gr.Audio(type="filepath", label="Upload a Track")stem_options = gr.Radio(["4 Stems (Vocals, Drums, Bass, Other)", "2 Stems (Vocals + Instrumental)"], label="Separation Type", value="4 Stems (Vocals, Drums, Bass, Other)")submit_button = gr.Button("Separate Stems")with gr.Accordion("Slicing Options", open=True):gr.Markdown("These options are for the final pack creation.")loop_options_radio = gr.Radio(["One-Shots (All Transients)", "4 Bar Loops", "8 Bar Loops"], label="Loop Type (for 'Slice All')", value="One-Shots (All Transients)")sensitivity_slider = gr.Slider(minimum=0.01, maximum=0.5, value=0.05, step=0.01, label="One-Shot Sensitivity")with gr.Column(scale=2):with gr.Accordion("Separated Stems", open=True):5 unmodified linesslice_drums_btn = gr.Button("Visualize Slices", scale=1)with gr.Row():bass_output = gr.Audio(label="Bass", scale=4)slice_bass_btn = gr.Button("Slice", scale=1)with gr.Row():other_output = gr.Audio(label="Other / Instrumental", scale=4)slice_other_btn = gr.Button("Slice", scale=1)gr.Markdown("### Slice Editor")slice_plot = gr.Plot(label="Click a region on the waveform to preview a slice")8 unmodified linesselected_gallery = gr.Gallery(label="Selected Slices", columns=8, object_fit="contain", height="auto")download_zip_file = gr.File(label="Download Your Custom Pack", visible=False)# --- Define Event Listeners ---submit_button.click(fn=separate_stems, inputs=[audio_input, stem_options], outputs=[vocals_output, drums_output, bass_output, other_output])stem_options.change(fn=update_output_visibility, inputs=stem_options, outputs=[vocals_output, drums_output, bass_output, other_output])2 unmodified linesslice_bass_btn.click(fn=visualize_slices, inputs=bass_output, outputs=[slice_plot, onset_times_state, active_stem_state])slice_other_btn.click(fn=visualize_slices, inputs=other_output, outputs=[slice_plot, onset_times_state, active_stem_state])# Correct event listener for plot interactionslice_plot.select(fn=preview_slice, inputs=[active_stem_state, onset_times_state], outputs=preview_player)add_to_pack_btn.click(fn=add_slice_to_pack, inputs=[preview_player, selected_slices_state], outputs=[selected_slices_state, selected_gallery])clear_selection_btn.click(fn=clear_selection, outputs=[selected_slices_state, selected_gallery])create_pack_btn.click(fn=create_final_pack, inputs=selected_slices_state, outputs=[download_zip_file, download_zip_file])# --- Launch the UI ---# Use demo.launch() for Hugging Face Spaces# Use demo.launch(debug=True) for local testingdemo.launch()1237 unmodified lines1112131415161773 unmodified lines91929394959697989910010110210310410510610710810911011111211311411511610 unmodified lines1271281291301311321331341351361371381391401411421431441451461471484 unmodified lines1531541551561571585 unmodified lines1641651661671681691701711721738 unmodified lines1821831841851861872 unmodified lines190191192193194195196197198199import gradio as grimport osimport shutil7 unmodified linesimport tempfileimport matplotlib.pyplot as pltimport matplotlibmatplotlib.use('Agg')def update_output_visibility(choice):if "2 Stems" in choice:73 unmodified linesfig, ax = plt.subplots(figsize=(10, 3))fig.patch.set_facecolor('#1f2937')ax.set_facecolor('#111827')librosa.display.waveshow(y, sr=sample_rate, ax=ax, color='#32f6ff', alpha=0.7)for t in onset_times:ax.axvline(x=t, color='#ff3b3b', linestyle='--', linewidth=1)ax.tick_params(colors='gray'); ax.xaxis.label.set_color('gray'); ax.yaxis.label.set_color('gray')ax.set_xlabel("Time (s)"); ax.set_ylabel("Amplitude"); ax.set_title("Detected Slices", color='white')plt.tight_layout()progress(1, desc="Done!")return fig, onset_times, stem_audio_datadef preview_slice(active_stem_audio, onset_times, evt: gr.SelectData):if active_stem_audio is None or onset_times is None: return Nonesample_rate, y = active_stem_audio; clicked_time = evt.index[0]start_time = 0; end_time = len(y) / sample_ratefor i, t in enumerate(onset_times):if t > clicked_time:end_time = t; breakstart_time = tstart_sample = librosa.time_to_samples(start_time, sr=sample_rate)end_sample = librosa.time_to_samples(end_time, sr=sample_rate)sliced_audio = y[start_sample:end_sample]return (sample_rate, sliced_audio)10 unmodified linesreturn [], []def create_final_pack(selection_list, progress=gr.Progress(track_tqdm=True)):if not selection_list: raise gr.Error("No slices have been selected!")progress(0, desc="Preparing final pack...")zip_path = "Custom_Loop_Pack.zip"; temp_dir = tempfile.mkdtemp()with zipfile.ZipFile(zip_path, 'w') as zf:for i, audio_data in enumerate(selection_list):progress(i / len(selection_list), desc=f"Adding slice {i+1}...")sample_rate, y = audio_datafilename = os.path.join(temp_dir, f"slice_{i+1:03d}.wav")sf.write(filename, y, sample_rate, subtype='PCM_16')zf.write(filename, os.path.basename(filename))shutil.rmtree(temp_dir)progress(1, desc="Pack Ready!")return zip_path, gr.update(visible=True)with gr.Blocks(theme=gr.themes.Default(primary_hue="blue", secondary_hue="red")) as demo:gr.Markdown("# 🎵 Loop Architect")onset_times_state = gr.State(value=None)active_stem_state = gr.State(value=None)selected_slices_state = gr.State(value=[])4 unmodified linesaudio_input = gr.Audio(type="filepath", label="Upload a Track")stem_options = gr.Radio(["4 Stems (Vocals, Drums, Bass, Other)", "2 Stems (Vocals + Instrumental)"], label="Separation Type", value="4 Stems (Vocals, Drums, Bass, Other)")submit_button = gr.Button("Separate Stems")with gr.Column(scale=2):with gr.Accordion("Separated Stems", open=True):5 unmodified linesslice_drums_btn = gr.Button("Visualize Slices", scale=1)with gr.Row():bass_output = gr.Audio(label="Bass", scale=4)slice_bass_btn = gr.Button("Visualize Slices", scale=1)with gr.Row():other_output = gr.Audio(label="Other / Instrumental", scale=4)slice_other_btn = gr.Button("Visualize Slices", scale=1)gr.Markdown("### Slice Editor")slice_plot = gr.Plot(label="Click a region on the waveform to preview a slice")8 unmodified linesselected_gallery = gr.Gallery(label="Selected Slices", columns=8, object_fit="contain", height="auto")download_zip_file = gr.File(label="Download Your Custom Pack", visible=False)submit_button.click(fn=separate_stems, inputs=[audio_input, stem_options], outputs=[vocals_output, drums_output, bass_output, other_output])stem_options.change(fn=update_output_visibility, inputs=stem_options, outputs=[vocals_output, drums_output, bass_output, other_output])2 unmodified linesslice_bass_btn.click(fn=visualize_slices, inputs=bass_output, outputs=[slice_plot, onset_times_state, active_stem_state])slice_other_btn.click(fn=visualize_slices, inputs=other_output, outputs=[slice_plot, onset_times_state, active_stem_state])slice_plot.select(fn=preview_slice, inputs=[active_stem_state, onset_times_state], outputs=preview_player)add_to_pack_btn.click(fn=add_slice_to_pack, inputs=[preview_player, selected_slices_state], outputs=[selected_slices_state, selected_gallery])clear_selection_btn.click(fn=clear_selection, outputs=[selected_slices_state, selected_gallery])create_pack_btn.click(fn=create_final_pack, inputs=selected_slices_state, outputs=[download_zip_file, download_zip_file])demo.launch()
app.py+13-54