-
Notifications
You must be signed in to change notification settings - Fork 5
Support spectrograms #133
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
Open
keggsmurph21
wants to merge
6
commits into
master
Choose a base branch
from
support-spectrograms
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Support spectrograms #133
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
6150971
SoundFileLoader: Add experimental (untested) spectrogram support
keggsmurph21 0655670
SoundFileLoader: Flush out spectrogram functionality, add tests
keggsmurph21 f3d9d53
FileBundle: Make <FileLoaderBase> access via getters instead of props
keggsmurph21 60e9f94
ParselmouthLoader: Add new FileLoaderBase type & implementation
keggsmurph21 54beeb8
FileBundle: Automatically create Spectrograms for files w/ Sound
keggsmurph21 11a9fc5
spectrogram: Add the parselmouth loader
keggsmurph21 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
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
101 changes: 101 additions & 0 deletions
101
ultratrace2/model/files/loaders/parselmouth_spectrogram.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,101 @@ | ||
| from PIL import Image # type: ignore | ||
|
|
||
| import logging | ||
| import numpy as np | ||
| import parselmouth # type: ignore | ||
| import pickle | ||
| import warnings | ||
|
|
||
| from .base import FileLoadError, SoundFileLoader, SpectrogramFileLoader | ||
|
|
||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| class ParselmouthLoader(SpectrogramFileLoader): | ||
| def get_path(self) -> str: | ||
| return self._path | ||
|
|
||
| def set_path(self, path) -> None: | ||
| self._path = path | ||
|
|
||
| def __init__(self, path: str, pm_sound: parselmouth.Sound): | ||
| self.set_path(path) | ||
| self.pm_sound = pm_sound | ||
|
|
||
| def save(self) -> None: | ||
| with open(self.get_path(), "wb") as fp: | ||
| pickle.dump(self.pm_sound.as_array(), fp) | ||
| logger.debug(f"Wrote ParselmouthLoader to disk: {self.get_path()}") | ||
|
|
||
| @classmethod | ||
| def from_file(cls, path: str) -> "ParselmouthLoader": | ||
| try: | ||
| with open(path, "rb") as fp: | ||
| pm_sound = parselmouth.Sound(pickle.load(fp)) | ||
| return cls(path, pm_sound) | ||
| except Exception as e: | ||
| raise FileLoadError from e | ||
|
|
||
| load = from_file # alias | ||
|
|
||
| @classmethod | ||
| def from_sound_file(cls, sound_file: SoundFileLoader) -> "ParselmouthLoader": | ||
| try: | ||
| pm_sound = parselmouth.Sound(sound_file.get_path()) | ||
| pm_path = f"{sound_file.get_path()}.pmpkl" | ||
| pm = cls(pm_path, pm_sound) | ||
| pm.save() | ||
| return pm | ||
| except Exception as e: | ||
| raise FileLoadError from e | ||
|
|
||
| def get_image( | ||
| self, | ||
| start_time_ms: int, | ||
| stop_time_ms: int, | ||
| window_length: float, # 0.005, | ||
| max_frequency: float, # 5000, | ||
| dynamic_range: float, # 90, | ||
| n_slices: int, # 10 ** 7, | ||
| ) -> Image.Image: | ||
|
|
||
| # NB: need to do validation of *_time_ms BEFORE calling | ||
| start_time_sec = start_time_ms / 1000 | ||
| stop_time_sec = stop_time_ms / 1000 | ||
| visible_duration_sec = stop_time_sec - start_time_sec | ||
|
|
||
| time_step = visible_duration_sec / n_slices | ||
|
|
||
| spec = self.pm_sound.extract_part( | ||
| from_time=start_time_sec, to_time=stop_time_sec | ||
| ).to_spectrogram( | ||
| window_length=window_length, | ||
| maximum_frequency=max_frequency, | ||
| time_step=time_step, | ||
| ) | ||
|
|
||
| with warnings.catch_warnings(): | ||
| # We filter our numpy's warnings about division by zero, since we expect | ||
| # there to be some "padding" at the start and end of the recording with | ||
| # decibel-level zero. Also, numpy does the sensible thing of defining | ||
| # `np.log10(0) := float("-inf")`, so it's not an issue for us. | ||
| warnings.filterwarnings( | ||
| "ignore", | ||
| message="divide by zero encountered in log10", | ||
| category=RuntimeWarning, | ||
| ) | ||
| spec_arr = 10 * np.log10(np.flipud(spec.values)) | ||
|
|
||
| # Normalize output array | ||
| max_magnitude = spec_arr.max() | ||
| spec_arr = ( | ||
| ( | ||
| spec_arr.clip(max_magnitude - dynamic_range, max_magnitude) | ||
| - max_magnitude | ||
| ) | ||
| * -255 | ||
| / dynamic_range | ||
| ) | ||
|
|
||
| return Image.fromarray(spec_arr).convert("RGB") |
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
78 changes: 78 additions & 0 deletions
78
ultratrace2/model/files/loaders/tests/test_parselmouth_spectrogram.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,78 @@ | ||
| import os | ||
| import PIL # type: ignore | ||
| import pytest | ||
|
|
||
| from ..base import SoundFileLoader | ||
| from ..mp3 import MP3Loader | ||
| from ..parselmouth_spectrogram import ParselmouthLoader | ||
|
|
||
|
|
||
| @pytest.mark.parametrize( | ||
| "sound_file_loader, path", | ||
| [ | ||
| (MP3Loader, "./test-data/example-audio/cello82.mp3"), | ||
| (MP3Loader, "./test-data/example-audio/harpsi-cs.mp3"), | ||
| (MP3Loader, "./test-data/example-audio/gtr-nylon22.mp3"), | ||
| (MP3Loader, "./test-data/example-audio/pno-cs.mp3"), | ||
| (MP3Loader, "./test-data/example-audio/bachfugue.mp3"), | ||
| (MP3Loader, "./test-data/example-bundles/ex016/link00.mp3"), | ||
| (MP3Loader, "./test-data/example-bundles/ex003/file01.mp3"), | ||
| (MP3Loader, "./test-data/example-bundles/ex004/file00.mp3"), | ||
| (MP3Loader, "./test-data/example-bundles/ex002/file00.mp3"), | ||
| (MP3Loader, "./test-data/example-bundles/ex015/file00.mp3"), | ||
| ( | ||
| MP3Loader, | ||
| "./test-data/example-bundles/ex012/sub01/sub00/sub00/sub00/file00.mp3", | ||
| ), | ||
| (MP3Loader, "./test-data/example-bundles/ex009/file00.mp3"), | ||
| (MP3Loader, "./test-data/example-bundles/ex008/file01.mp3"), | ||
| (MP3Loader, "./test-data/example-bundles/ex008/file00.mp3"), | ||
| (MP3Loader, "./test-data/example-bundles/ex008/file02.mp3"), | ||
| ], | ||
| ) | ||
| def test_loading_from_sound_file(sound_file_loader: SoundFileLoader, path: str) -> None: | ||
| try: | ||
| expected_pm_path = path + ".pmpkl" | ||
| assert not os.path.exists(expected_pm_path) | ||
| sound_file = sound_file_loader.from_file(path) | ||
| pm_file = ParselmouthLoader.from_sound_file(sound_file) | ||
| assert isinstance(pm_file, ParselmouthLoader) | ||
| assert pm_file.get_path() == expected_pm_path | ||
| assert os.path.exists(expected_pm_path) | ||
| finally: | ||
| if os.path.exists(expected_pm_path): | ||
| os.remove(expected_pm_path) | ||
|
|
||
|
|
||
| @pytest.mark.parametrize( | ||
| "path", | ||
| [ | ||
| "./test-data/example-parselmouth/00.pmpkl", | ||
| "./test-data/example-parselmouth/01.pmpkl", | ||
| "./test-data/example-parselmouth/02.pmpkl", | ||
| "./test-data/example-parselmouth/03.pmpkl", | ||
| "./test-data/example-parselmouth/04.pmpkl", | ||
| "./test-data/example-parselmouth/05.pmpkl", | ||
| "./test-data/example-parselmouth/06.pmpkl", | ||
| "./test-data/example-parselmouth/07.pmpkl", | ||
| "./test-data/example-parselmouth/08.pmpkl", | ||
| "./test-data/example-parselmouth/09.pmpkl", | ||
| "./test-data/example-parselmouth/10.pmpkl", | ||
| "./test-data/example-parselmouth/11.pmpkl", | ||
| "./test-data/example-parselmouth/12.pmpkl", | ||
| "./test-data/example-parselmouth/13.pmpkl", | ||
| "./test-data/example-parselmouth/14.pmpkl", | ||
| ], | ||
| ) | ||
| def test_loading_from_pmpkl_file(path: str) -> None: | ||
| pm_file = ParselmouthLoader.from_file(path) | ||
| assert isinstance(pm_file, ParselmouthLoader) | ||
| im = pm_file.get_image( | ||
| start_time_ms=0, | ||
| stop_time_ms=10, | ||
| window_length=0.005, | ||
| max_frequency=5000, | ||
| dynamic_range=90, | ||
| n_slices=10 ** 7, | ||
| ) | ||
| assert isinstance(im, PIL.Image.Image) |
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
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
NOTE: This needs special attention, since it breaks some of our assumptions.