-
Notifications
You must be signed in to change notification settings - Fork 0
feat: implement local ML stem separation with chunking #111
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from 2 commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
b06911a
feat(analysis): implement audio stem separator with PyTorch
seonghobae e9e800e
ci: skip python sync on macos x86_64 to avoid torch resolution error
seonghobae b3c9f1d
Address review feedback: sync logic, cli gating, local model, test mocks
seonghobae 38284ef
fix: pin macOS x86_64 PyTorch wheel for CI
seonghobae 9e42d22
Merge develop and resolve uv.lock conflict
seonghobae fdf5272
fix(style): resolve E501 line too long errors
seonghobae 4781c29
fix(style): apply ruff check --fix and format
seonghobae 56c124c
chore: ignore untyped demucs load_model call in mypy
seonghobae 23fa28f
Merge branch 'develop' into feature/issue-106-stem-separation
seonghobae 6191bd5
Merge branch 'develop' into feature/issue-106-stem-separation
seonghobae be4cd93
Merge branch 'develop' into feature/issue-106-stem-separation
seonghobae 3ac2343
Merge branch 'develop' into feature/issue-106-stem-separation
seonghobae d0853d8
fix: stabilize stem separation checks
seonghobae bfb6551
Merge branch 'develop' into feature/issue-106-stem-separation
seonghobae 3917e36
Merge branch 'develop' into feature/issue-106-stem-separation
seonghobae File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
121 changes: 121 additions & 0 deletions
121
services/analysis-engine/src/bandscope_analysis/separation/audio_separator.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,121 @@ | ||
| """Audio source separation using Demucs.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import logging | ||
| from typing import Any | ||
|
|
||
| import numpy as np | ||
|
|
||
| try: | ||
| from torch import Tensor | ||
| except ImportError: # pragma: no cover | ||
| Tensor = Any # type: ignore | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| class AudioStemSeparator: | ||
| """Isolates standard stems from an audio mix using Demucs. | ||
|
|
||
| Security Notes: | ||
| - Trust boundary: Audio input is passed as raw numpy arrays from a prior decoding step | ||
| (e.g. librosa), reducing the risk of codec-based exploitation within Demucs itself. | ||
| - Limits: Employs chunked inference (split=True) to strictly bound peak memory (OOM avoidance). | ||
| - Network: Downloads model weights securely to local cache on first run. Future executions | ||
| should ideally be offline. | ||
| """ | ||
|
|
||
| def __init__(self, model_name: str = "htdemucs") -> None: | ||
| """Initialize the audio stem separator. | ||
|
|
||
| Args: | ||
| model_name: The name of the pretrained Demucs model to use. | ||
| """ | ||
| self.model_name = model_name | ||
| self._model = None | ||
|
|
||
| def _load_model(self) -> Any: | ||
| from demucs.pretrained import get_model | ||
|
|
||
| if self._model is None: | ||
| logger.info("Loading demucs model '%s'...", self.model_name) | ||
| self._model = get_model(self.model_name) | ||
| if self._model: | ||
| self._model.eval() | ||
| return self._model | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
|
|
||
| def separate_audio( | ||
| self, | ||
| audio_data: np.ndarray, | ||
| sample_rate: int, | ||
| segment_seconds: float = 10.0, | ||
| ) -> dict[str, np.ndarray]: | ||
| """Perform source separation on the given audio array. | ||
|
|
||
| Args: | ||
| audio_data: The input audio waveform, shape (channels, samples). | ||
| If mono (samples,), it will be converted to stereo. | ||
| sample_rate: The sample rate of the input audio. | ||
| segment_seconds: The length of each chunk for OOM-safe processing. | ||
|
|
||
| Returns: | ||
| A dictionary mapping stem names ('vocals', 'bass', 'drums', 'other') | ||
| to their separated audio waveforms (channels, samples). | ||
| """ | ||
| import torch | ||
| from demucs.apply import apply_model | ||
| from demucs.audio import convert_audio | ||
|
|
||
| model = self._load_model() | ||
|
|
||
| # Ensure 2D (channels, samples) | ||
| if audio_data.ndim == 1: | ||
| audio_data = np.expand_dims(audio_data, axis=0) | ||
|
|
||
| # Convert to torch tensor | ||
| mix = torch.from_numpy(audio_data).float() | ||
|
|
||
| # Convert audio to match model expectations | ||
| mix = convert_audio( # type: ignore | ||
| mix, | ||
| sample_rate, | ||
| model.samplerate, | ||
| model.audio_channels, | ||
| ) | ||
|
|
||
| # Add batch dimension: (1, channels, samples) | ||
| mix = mix.unsqueeze(0) | ||
|
|
||
| # Determine device | ||
| device = "cpu" | ||
| if torch.cuda.is_available(): | ||
| device = "cuda" | ||
| elif torch.backends.mps.is_available(): | ||
| device = "mps" | ||
|
|
||
| model.to(device) | ||
| mix = mix.to(device) | ||
|
|
||
| logger.info("Applying model to mix using device %s...", device) | ||
| # Apply model with chunking | ||
| with torch.no_grad(): | ||
| stems = apply_model( | ||
| model, | ||
| mix, | ||
| shifts=1, | ||
| split=True, | ||
| overlap=0.25, | ||
| segment=segment_seconds, | ||
| progress=False, | ||
| ) | ||
|
|
||
| # stems shape: [batch, sources, channels, samples] | ||
| # Remove batch dim | ||
| stems_np: np.ndarray = stems[0].cpu().numpy() | ||
|
|
||
| result = {} | ||
| for idx, source_name in enumerate(model.sources): | ||
| result[source_name] = stems_np[idx] | ||
|
|
||
| return result | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,124 @@ | ||
| """Tests for audio stem separation.""" | ||
|
|
||
| from unittest import mock | ||
|
|
||
| import numpy as np | ||
| import pytest | ||
|
|
||
| from bandscope_analysis.separation.audio_separator import AudioStemSeparator | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def mock_demucs_model(): | ||
| """Provide a mock demucs model with standard sources.""" | ||
| mock_model = mock.MagicMock() | ||
| mock_model.sources = ["drums", "bass", "other", "vocals"] | ||
| mock_model.samplerate = 44100 | ||
| mock_model.audio_channels = 2 | ||
| return mock_model | ||
|
|
||
|
|
||
| @mock.patch("bandscope_analysis.separation.audio_separator.logger") | ||
| @mock.patch("demucs.audio.convert_audio") | ||
| @mock.patch("demucs.apply.apply_model") | ||
| @mock.patch("demucs.pretrained.get_model") | ||
| def test_audio_stem_separator( | ||
| mock_get_model, mock_apply_model, mock_convert_audio, mock_logger, mock_demucs_model | ||
| ): | ||
| """Test that the AudioStemSeparator correctly coordinates the mock Demucs model.""" | ||
| import torch | ||
|
|
||
| # Setup mocks | ||
| mock_get_model.return_value = mock_demucs_model | ||
|
|
||
| # fake convert_audio output (channels, samples) | ||
| # convert_audio returns the tensor directly | ||
| def fake_convert(wav, from_sr, to_sr, channels): | ||
| # ensure shape matches expectations | ||
| return torch.zeros((2, 100)) | ||
|
|
||
| mock_convert_audio.side_effect = fake_convert | ||
|
|
||
| # fake apply_model output (batch, sources, channels, samples) | ||
| mock_apply_model.return_value = torch.ones((1, 4, 2, 100)) | ||
|
|
||
| separator = AudioStemSeparator(model_name="fake_model") | ||
|
|
||
| # Test mono audio | ||
| audio_data = np.zeros((100,)) | ||
| result = separator.separate_audio(audio_data, sample_rate=22050, segment_seconds=2.0) | ||
|
|
||
| # Assertions | ||
| mock_get_model.assert_called_once_with("fake_model") | ||
| mock_apply_model.assert_called_once() | ||
|
|
||
| # Verify the results match the model sources | ||
| assert set(result.keys()) == {"drums", "bass", "other", "vocals"} | ||
| for stem_name in ["drums", "bass", "other", "vocals"]: | ||
| assert result[stem_name].shape == (2, 100) | ||
| assert np.all(result[stem_name] == 1.0) | ||
|
|
||
| # Check that model gets loaded only once | ||
| separator.separate_audio(audio_data, sample_rate=22050, segment_seconds=2.0) | ||
| assert mock_get_model.call_count == 1 | ||
| assert mock_apply_model.call_count == 2 | ||
|
coderabbitai[bot] marked this conversation as resolved.
Outdated
|
||
|
|
||
|
|
||
| @mock.patch("bandscope_analysis.separation.audio_separator.logger") | ||
| @mock.patch("demucs.audio.convert_audio") | ||
| @mock.patch("demucs.apply.apply_model") | ||
| @mock.patch("demucs.pretrained.get_model") | ||
| @mock.patch("torch.from_numpy") | ||
| @mock.patch("torch.cuda.is_available") | ||
| @mock.patch("torch.backends.mps.is_available") | ||
| def test_audio_stem_separator_device( | ||
| mock_mps, | ||
| mock_cuda, | ||
| mock_from_numpy, | ||
| mock_get_model, | ||
| mock_apply_model, | ||
| mock_convert_audio, | ||
| mock_logger, | ||
| mock_demucs_model, | ||
| ): | ||
| """Test that device selection (mps, cuda, cpu) falls back correctly.""" | ||
| # This test verifies that the correct device string is chosen. | ||
| # By mocking torch.from_numpy and convert_audio, we prevent real tensors | ||
| # from being created, thus avoiding actual PyTorch .to("cuda") calls | ||
| # that would fail on machines compiled without CUDA. | ||
| mock_get_model.return_value = mock_demucs_model | ||
|
|
||
| mock_tensor = mock.MagicMock() | ||
| mock_from_numpy.return_value.float.return_value = mock_tensor | ||
| mock_convert_audio.return_value = mock_tensor | ||
| mock_tensor.unsqueeze.return_value = mock_tensor | ||
| mock_tensor.to.return_value = mock_tensor | ||
|
|
||
| # Mock apply_model return value so stems[0].cpu().numpy() works | ||
| mock_stems_item = mock.MagicMock() | ||
| mock_stems_item.cpu.return_value.numpy.return_value = np.zeros((4, 2, 100)) | ||
| mock_stems = mock.MagicMock() | ||
| mock_stems.__getitem__.return_value = mock_stems_item | ||
| mock_apply_model.return_value = mock_stems | ||
|
|
||
| separator = AudioStemSeparator(model_name="fake_model") | ||
| audio_data = np.zeros((2, 100)) # Test stereo | ||
|
|
||
| # 1. Test cuda | ||
| mock_cuda.return_value = True | ||
| mock_mps.return_value = False | ||
| result = separator.separate_audio(audio_data, sample_rate=22050, segment_seconds=2.0) | ||
| assert set(result.keys()) == {"drums", "bass", "other", "vocals"} | ||
| mock_tensor.to.assert_called_with("cuda") | ||
|
|
||
| # 2. Test mps | ||
| mock_cuda.return_value = False | ||
| mock_mps.return_value = True | ||
| result = separator.separate_audio(audio_data, sample_rate=22050, segment_seconds=2.0) | ||
| mock_tensor.to.assert_called_with("mps") | ||
|
|
||
| # 3. Test cpu | ||
| mock_cuda.return_value = False | ||
| mock_mps.return_value = False | ||
| result = separator.separate_audio(audio_data, sample_rate=22050, segment_seconds=2.0) | ||
| mock_tensor.to.assert_called_with("cpu") | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.