CCockrum commited on
Commit
5f8b972
·
verified ·
1 Parent(s): 8bcbc12

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +386 -0
app.py ADDED
@@ -0,0 +1,386 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import numpy as np
3
+ import librosa
4
+ import soundfile as sf
5
+ import os
6
+ import tempfile
7
+ from pathlib import Path
8
+ import torch
9
+ from tqdm import tqdm
10
+ import base64
11
+ import io
12
+ from PIL import Image
13
+ import matplotlib.pyplot as plt
14
+
15
+ # Page configuration
16
+ st.set_page_config(
17
+ page_title="Music Stem Splitter",
18
+ page_icon="🎵",
19
+ layout="wide",
20
+ initial_sidebar_state="expanded"
21
+ )
22
+
23
+ # Set maximum audio duration (in seconds) and file size (in MB)
24
+ MAX_AUDIO_DURATION = 300 # 5 minutes
25
+ MAX_FILE_SIZE_MB = 100
26
+
27
+ # Load pretrained separator model
28
+ @st.cache_resource
29
+ def load_separator_model():
30
+ try:
31
+ # Import here to avoid loading until needed
32
+ from demucs.pretrained import get_model
33
+ model = get_model('htdemucs')
34
+ model.eval()
35
+ if torch.cuda.is_available():
36
+ model.cuda()
37
+ return model
38
+ except ImportError:
39
+ st.error("Required package 'demucs' not found. Please install it with 'pip install demucs'.")
40
+ return None
41
+
42
+ # Function to check audio length
43
+ def check_audio_length(audio_path):
44
+ try:
45
+ duration = librosa.get_duration(path=audio_path)
46
+ return duration
47
+ except Exception as e:
48
+ st.error(f"Could not determine audio length: {str(e)}")
49
+ return MAX_AUDIO_DURATION + 1 # Return a value that will fail the check
50
+
51
+ # Function to separate stems from an audio file
52
+ def separate_stems(audio_path, model, sample_rate=44100):
53
+ from demucs.apply import apply_model
54
+ import torchaudio
55
+
56
+ # Load audio with potential resampling to save memory
57
+ waveform, original_sample_rate = torchaudio.load(audio_path)
58
+
59
+ # Resample if needed to optimize memory usage
60
+ if original_sample_rate > sample_rate:
61
+ resampler = torchaudio.transforms.Resample(orig_freq=original_sample_rate, new_freq=sample_rate)
62
+ waveform = resampler(waveform)
63
+ st.info(f"Audio resampled from {original_sample_rate}Hz to {sample_rate}Hz to optimize performance.")
64
+ else:
65
+ sample_rate = original_sample_rate
66
+
67
+ # Create a mono version just for visualization
68
+ if waveform.shape[0] > 1:
69
+ waveform_mono = torch.mean(waveform, dim=0, keepdim=True)
70
+ else:
71
+ waveform_mono = waveform
72
+
73
+ # Get the audio length in seconds for progress tracking
74
+ audio_length = waveform.shape[1] / sample_rate
75
+
76
+ # Create a progress bar
77
+ progress_bar = st.progress(0)
78
+ status_text = st.empty()
79
+
80
+ # Prepare the model input
81
+ if torch.cuda.is_available():
82
+ waveform = waveform.cuda()
83
+
84
+ # For Demucs, we need the audio as (batch, channels, time)
85
+ if waveform.dim() == 2: # (channels, time)
86
+ waveform = waveform.unsqueeze(0)
87
+
88
+ # Create a temp directory for saving stems
89
+ temp_dir = tempfile.mkdtemp()
90
+ stems = {}
91
+
92
+ # Process and separate stems
93
+ status_text.text("Separating stems... This may take a while depending on the audio length.")
94
+
95
+ # Optimize memory usage by processing in chunks if needed
96
+ with torch.no_grad():
97
+ # Use smaller chunks for CPU, larger for GPU
98
+ chunk_size = 10 * sample_rate if torch.cuda.is_available() else 5 * sample_rate
99
+
100
+ if waveform.shape[-1] > chunk_size and waveform.shape[-1] > 30 * sample_rate:
101
+ # Process in chunks for very long audio
102
+ st.info("Processing long audio in chunks to optimize memory usage...")
103
+ sources = []
104
+
105
+ # Calculate number of chunks
106
+ num_chunks = int(np.ceil(waveform.shape[-1] / chunk_size))
107
+
108
+ for i in range(num_chunks):
109
+ # Update progress
110
+ progress = i / num_chunks * 0.7 # 70% of progress for separation
111
+ progress_bar.progress(progress)
112
+ status_text.text(f"Processing chunk {i+1}/{num_chunks}...")
113
+
114
+ # Extract chunk
115
+ start = i * chunk_size
116
+ end = min(start + chunk_size, waveform.shape[-1])
117
+ chunk = waveform[:, :, start:end]
118
+
119
+ # Process chunk
120
+ chunk_sources = apply_model(model, chunk, device="cuda" if torch.cuda.is_available() else "cpu")
121
+
122
+ # Append to sources
123
+ if i == 0:
124
+ sources = chunk_sources
125
+ else:
126
+ # Concatenate along time dimension
127
+ sources = torch.cat([sources, chunk_sources], dim=-1)
128
+
129
+ # Clear GPU memory if needed
130
+ if torch.cuda.is_available():
131
+ torch.cuda.empty_cache()
132
+ else:
133
+ # Process entire audio at once for shorter clips
134
+ sources = apply_model(model, waveform, device="cuda" if torch.cuda.is_available() else "cpu")
135
+
136
+ # sources is (batch, source, channels, time)
137
+ sources = sources[0] # Remove batch dimension
138
+
139
+ # Save each source
140
+ source_names = ["drums", "bass", "other", "vocals"]
141
+ for i, source_name in enumerate(source_names):
142
+ stems[source_name] = sources[i].cpu().numpy()
143
+
144
+ # Update progress
145
+ progress = 0.7 + (i + 1) / len(source_names) * 0.2 # 20% of progress for stem saving
146
+ progress_bar.progress(progress)
147
+ status_text.text(f"Processed {source_name} stem ({i+1}/{len(source_names)})")
148
+
149
+ # Create visualizations (at reduced resolution to save memory)
150
+ visualizations = {}
151
+ for stem_name, audio_data in stems.items():
152
+ # Create spectrogram visualization
153
+ plt.figure(figsize=(10, 4))
154
+
155
+ # Use a smaller portion of audio for visualization if it's too long
156
+ max_samples = min(sample_rate * 30, audio_data.shape[1]) # 30 seconds max
157
+ visualization_data = audio_data[0, :max_samples] if audio_data.shape[1] > max_samples else audio_data[0]
158
+
159
+ # Create spectrogram with reduced resolution
160
+ D = librosa.amplitude_to_db(np.abs(librosa.stft(visualization_data, n_fft=1024, hop_length=512)), ref=np.max)
161
+
162
+ plt.subplot(1, 1, 1)
163
+ librosa.display.specshow(D, y_axis='log', x_axis='time', sr=sample_rate)
164
+ plt.title(f'{stem_name.capitalize()} Spectrogram')
165
+ plt.colorbar(format='%+2.0f dB')
166
+ plt.tight_layout()
167
+
168
+ # Save figure to bytes
169
+ buf = io.BytesIO()
170
+ plt.savefig(buf, format='png', dpi=100) # Lower DPI to save memory
171
+ buf.seek(0)
172
+ visualizations[stem_name] = buf
173
+ plt.close()
174
+
175
+ # Clear GPU memory
176
+ if torch.cuda.is_available():
177
+ torch.cuda.empty_cache()
178
+
179
+ # Update progress to complete
180
+ progress_bar.progress(1.0)
181
+ status_text.text("Stem separation complete!")
182
+
183
+ return stems, sample_rate, visualizations
184
+
185
+ # Function to create a download link for audio files
186
+ def get_binary_file_downloader_html(bin_data, file_label, file_extension):
187
+ b64data = base64.b64encode(bin_data).decode()
188
+ href = f'<a href="data:audio/{file_extension};base64,{b64data}" download="{file_label}.{file_extension}">Download {file_label}</a>'
189
+ return href
190
+
191
+ # Title and description
192
+ st.title("🎵 Music Stem Splitter")
193
+
194
+ st.markdown("""
195
+ This application separates music tracks into individual stems:
196
+ - **Vocals**: Lead and background vocals
197
+ - **Drums**: Drum kit and percussion
198
+ - **Bass**: Bass guitar, synth bass, etc.
199
+ - **Other**: All other instruments and sounds
200
+
201
+ Upload an audio file (MP3, WAV, or FLAC) to get started.
202
+ """)
203
+
204
+ # Add warning about HF Spaces limitations
205
+ st.warning(f"""
206
+ ⚠️ **Hugging Face Spaces Limitations**:
207
+ - Maximum file size: {MAX_FILE_SIZE_MB}MB
208
+ - Maximum audio duration: {MAX_AUDIO_DURATION} seconds ({MAX_AUDIO_DURATION//60} minutes)
209
+ - Processing may take several minutes depending on server load
210
+ """)
211
+
212
+ # Initialize session state for storing results
213
+ if 'stems' not in st.session_state:
214
+ st.session_state.stems = None
215
+ if 'sample_rate' not in st.session_state:
216
+ st.session_state.sample_rate = None
217
+ if 'visualizations' not in st.session_state:
218
+ st.session_state.visualizations = None
219
+
220
+ # File uploader
221
+ st.subheader("Upload Audio File")
222
+ uploaded_file = st.file_uploader("Choose an audio file", type=["mp3", "wav", "flac", "ogg"])
223
+
224
+ # Model loading (only when needed)
225
+ model_load_state = st.empty()
226
+
227
+ # Process the uploaded file
228
+ if uploaded_file is not None:
229
+ # Check file size
230
+ file_size_mb = uploaded_file.size / 1e6
231
+
232
+ if file_size_mb > MAX_FILE_SIZE_MB:
233
+ st.error(f"File too large: {file_size_mb:.1f}MB. Maximum allowed size is {MAX_FILE_SIZE_MB}MB.")
234
+ else:
235
+ # Display file info
236
+ file_details = {"Filename": uploaded_file.name, "FileSize": f"{file_size_mb:.2f} MB"}
237
+ st.write(file_details)
238
+
239
+ # Create a temporary file
240
+ with tempfile.NamedTemporaryFile(delete=False, suffix=os.path.splitext(uploaded_file.name)[1]) as tmp_file:
241
+ tmp_file.write(uploaded_file.getvalue())
242
+ tmp_path = tmp_file.name
243
+
244
+ # Check audio duration
245
+ audio_duration = check_audio_length(tmp_path)
246
+
247
+ if audio_duration > MAX_AUDIO_DURATION:
248
+ st.error(f"Audio duration too long: {audio_duration:.1f} seconds. Maximum allowed duration is {MAX_AUDIO_DURATION} seconds ({MAX_AUDIO_DURATION//60} minutes).")
249
+ # Clean up temporary file
250
+ os.unlink(tmp_path)
251
+ else:
252
+ st.info(f"Audio duration: {audio_duration:.1f} seconds")
253
+
254
+ # Load model (with caching for efficiency)
255
+ with model_load_state:
256
+ st.info("Loading AI model... This may take a moment the first time.")
257
+ model = load_separator_model()
258
+
259
+ if model is not None:
260
+ # Process button
261
+ if st.button("Split into Stems"):
262
+ try:
263
+ # Select processing sample rate based on file duration
264
+ # Shorter files can use higher quality, longer files use lower to save memory
265
+ if audio_duration < 60: # Less than 1 minute
266
+ processing_sample_rate = 44100
267
+ elif audio_duration < 180: # 1-3 minutes
268
+ processing_sample_rate = 32000
269
+ else: # 3-5 minutes
270
+ processing_sample_rate = 22050
271
+
272
+ # Perform stem separation
273
+ st.session_state.stems, st.session_state.sample_rate, st.session_state.visualizations = separate_stems(
274
+ tmp_path, model, sample_rate=processing_sample_rate
275
+ )
276
+ st.success("Stem separation completed! Scroll down to preview and download individual stems.")
277
+ except Exception as e:
278
+ st.error(f"An error occurred during processing: {str(e)}")
279
+ st.info("Try with a shorter audio clip or a different file format.")
280
+ else:
281
+ st.warning("Required packages not available. To run locally, install with 'pip install demucs librosa soundfile'")
282
+
283
+ # Clean up temporary file
284
+ os.unlink(tmp_path)
285
+
286
+ # Display results if available
287
+ if st.session_state.stems is not None:
288
+ st.header("Separated Stems")
289
+
290
+ # Create tabs for each stem
291
+ stem_tabs = st.tabs(["Vocals", "Drums", "Bass", "Other"])
292
+
293
+ # Get stem names in correct order
294
+ stem_names = ["vocals", "drums", "bass", "other"]
295
+
296
+ # Process each stem
297
+ for i, (stem_tab, stem_name) in enumerate(zip(stem_tabs, stem_names)):
298
+ with stem_tab:
299
+ # Create columns for audio player and visualization
300
+ col1, col2 = st.columns([1, 1])
301
+
302
+ with col1:
303
+ st.subheader(f"{stem_name.capitalize()} Stem")
304
+
305
+ # Convert numpy array to audio file for playback
306
+ audio_data = st.session_state.stems[stem_name]
307
+
308
+ # Create a temporary buffer for the audio data
309
+ buf = io.BytesIO()
310
+ sf.write(buf, audio_data.T, st.session_state.sample_rate, format='WAV')
311
+ buf.seek(0)
312
+
313
+ # Display audio player
314
+ st.audio(buf, format='audio/wav')
315
+
316
+ # Download button
317
+ st.markdown(get_binary_file_downloader_html(buf.getvalue(), f"{stem_name}", "wav"), unsafe_allow_html=True)
318
+
319
+ # Additional information
320
+ if stem_name == "vocals":
321
+ st.info("Contains lead vocals and backing vocals.")
322
+ elif stem_name == "drums":
323
+ st.info("Contains drums and percussion elements.")
324
+ elif stem_name == "bass":
325
+ st.info("Contains bass guitar and low-frequency elements.")
326
+ else: # other
327
+ st.info("Contains all other instruments (guitars, keys, synths, etc).")
328
+
329
+ with col2:
330
+ # Display visualization
331
+ if st.session_state.visualizations and stem_name in st.session_state.visualizations:
332
+ st.image(st.session_state.visualizations[stem_name], caption=f"{stem_name.capitalize()} Spectrogram")
333
+
334
+ # Show instructions for downloading all stems
335
+ st.header("Usage Tips")
336
+ st.markdown("""
337
+ ### What can you do with these stems?
338
+ - Create remixes or mashups
339
+ - Practice playing along with isolated instrument tracks
340
+ - Create karaoke versions by removing vocals
341
+ - Analyze individual instrument parts for educational purposes
342
+
343
+ ### Next steps:
344
+ 1. Download each stem you want to use
345
+ 2. Import them into your DAW (Digital Audio Workstation)
346
+ 3. Mix, process, and create!
347
+ """)
348
+
349
+ # Add instructions for local deployment
350
+ st.sidebar.header("About This App")
351
+ st.sidebar.markdown("""
352
+ This application uses the Demucs model to separate audio tracks into individual stems. The model was developed by Facebook AI Research.
353
+
354
+ ### How it works
355
+ The separation process uses a deep neural network to identify and isolate:
356
+ - Vocals
357
+ - Drums
358
+ - Bass
359
+ - Other instruments
360
+
361
+ ### Source code
362
+ [GitHub Repository](https://github.com/huggingface/music-stem-splitter)
363
+ (Link to your repo once created)
364
+ """)
365
+
366
+ # Add a note about processing time
367
+ st.sidebar.markdown("""
368
+ ### Processing Time
369
+ The processing time depends on:
370
+ - Length of the audio file
371
+ - Available computational resources
372
+ - File quality
373
+
374
+ For best results, use high-quality audio files without excessive background noise.
375
+ """)
376
+
377
+ # Show model information
378
+ st.sidebar.markdown("""
379
+ ### Model Information
380
+ This app uses the HTDemucs model, which is trained to separate music into four stems.
381
+
382
+ Audio processing is optimized based on file length:
383
+ - Short files (< 1 min): 44.1kHz processing
384
+ - Medium files (1-3 min): 32kHz processing
385
+ - Longer files (3-5 min): 22kHz processing
386
+ """)