diff --git a/CHANGES.md b/CHANGES.md index 98e27bc..2d3baeb 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,5 +1,16 @@ # Changes +## Version 0.5.1 + +### Fixed + +- `AudioStream` file input with `wait=True` supplies each audio block at its playback time on a separate thread, so slow processing no longer drifts the input timing. + +### Changed + +- Faster forward step for the pitch HMM followers (`"pthmm"`, `"hmm"`). +- Read the Docs builds take the version from the installed package. + ## Version 0.5.0 ### Added diff --git a/README.md b/README.md index 4ec581c..9c54713 100644 --- a/README.md +++ b/README.md @@ -397,6 +397,7 @@ Default method: `"pthmm"` | `"hmm"` | HMM score follower by Cancino-Chacón et al. (2023) | | `"pthmm"` | Pitch-based HMM score follower | | `"pfkorz"` | Particle filter score follower by Korzeniowski et al. (2013) | +| `"dannenberg"` | Dynamic-programming score follower by Bloch and Dannenberg (1985) | | `"SL_OLTW"` | Symbolic-level OLTW note matcher from [parangonar](https://github.com/sildater/parangonar) (Peter et al., 2025) | | `"SLT_OLTW"` | Symbolic-level OLTW note matcher with tempo, from parangonar (Peter et al., 2025) | | `"OTM"` | Online transformer note matcher from parangonar (Peter, 2023) | diff --git a/docs/requirements.txt b/docs/requirements.txt index d985367..9115d0f 100644 --- a/docs/requirements.txt +++ b/docs/requirements.txt @@ -1,4 +1,3 @@ -pymatchmaker myst-parser>=3.0.1 sphinx>=7.4.7 sphinx-rtd-theme>=3.0.2 diff --git a/docs/source/conf.py b/docs/source/conf.py index 24f7d5c..e86f084 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -5,15 +5,12 @@ # -- Project information ----------------------------------------------------- # https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information -import os -import sys - -sys.path.insert(0, os.path.abspath("..")) +import importlib.metadata project = "pymatchmaker" copyright = "2024, matchmaker development team" author = "matchmaker development team" -release = "0.5.0" +release = importlib.metadata.version("pymatchmaker") # -- General configuration --------------------------------------------------- # https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration @@ -25,6 +22,7 @@ "sphinx.ext.todo", "sphinx.ext.coverage", "sphinx.ext.mathjax", + "sphinx.ext.napoleon", "sphinx.ext.viewcode", "myst_parser", ] diff --git a/docs/source/index.rst b/docs/source/index.rst index e8930ca..2b5e87d 100644 --- a/docs/source/index.rst +++ b/docs/source/index.rst @@ -1,19 +1,15 @@ -.. pymatchmaker documentation master file, created by - sphinx-quickstart on Tue Dec 3 17:52:36 2024. - You can adapt this file completely to your liking, but it should at least - contain the root `toctree` directive. - Welcome to Matchmaker's Documentation! ====================================== .. include:: ../../README.md :parser: myst_parser.sphinx_ + :start-after: # Matchmaker + :end-before: ## Setup .. toctree:: :maxdepth: 0 :caption: Contents - introduction install usage configurations @@ -35,10 +31,3 @@ Indices and tables * :ref:`genindex` * :ref:`modindex` * :ref:`search` - -Acknowledgements ----------------- -This work has been supported by the Austrian Science Fund (FWF), -grant agreement PAT 8820923 ("Rach3: A Computational Approach to Study Piano Rehearsals"). -Additionally, this work was supported by the National Research Foundation of Korea (NRF) grant -funded by the Korea government (MSIT) (No. NRF-2023R1A2C3007605). diff --git a/docs/source/introduction.rst b/docs/source/introduction.rst deleted file mode 100644 index 40b1792..0000000 --- a/docs/source/introduction.rst +++ /dev/null @@ -1,7 +0,0 @@ -Introduction -============ - -.. include:: ../../README.md - :parser: myst_parser.sphinx_ - :start-after: # Matchmaker - :end-before: ## Setup diff --git a/docs/source/modules/matchmaker.dp.rst b/docs/source/modules/matchmaker.dp.rst index 2b91fd2..75aa9c6 100644 --- a/docs/source/modules/matchmaker.dp.rst +++ b/docs/source/modules/matchmaker.dp.rst @@ -1,12 +1,26 @@ matchmaker.dp ============= -.. autoclass:: matchmaker.dp.oltw_dixon.OnlineTimeWarpingDixon - :members: run +.. autoclass:: matchmaker.dp.OnlineTimeWarpingDixonFrame :show-inheritance: :special-members: __init__ -.. autoclass:: matchmaker.dp.oltw_arzt.OnlineTimeWarpingArzt - :members: run +.. autoclass:: matchmaker.dp.OnlineTimeWarpingDixonEvent + :show-inheritance: + :special-members: __init__ + +.. autoclass:: matchmaker.dp.OnlineTimeWarpingArztFrame + :show-inheritance: + :special-members: __init__ + +.. autoclass:: matchmaker.dp.OnlineTimeWarpingArztEvent + :show-inheritance: + :special-members: __init__ + +.. autoclass:: matchmaker.dp.OnlineTimeWarpingArztMultiFold + :show-inheritance: + :special-members: __init__ + +.. autoclass:: matchmaker.dp.DPDannenberg :show-inheritance: :special-members: __init__ diff --git a/docs/source/modules/matchmaker.prob.rst b/docs/source/modules/matchmaker.prob.rst index ddd378c..94cae4f 100644 --- a/docs/source/modules/matchmaker.prob.rst +++ b/docs/source/modules/matchmaker.prob.rst @@ -1,7 +1,26 @@ matchmaker.prob -======================= +=============== -.. autoclass:: matchmaker.prob.hmm.PitchIOIHMM - :members: run +.. autoclass:: matchmaker.prob.PitchHMM + :show-inheritance: + :special-members: __init__ + +.. autoclass:: matchmaker.prob.PitchIOIHMM + :show-inheritance: + :special-members: __init__ + +.. autoclass:: matchmaker.prob.OuterProductHMM + :show-inheritance: + :special-members: __init__ + +.. autoclass:: matchmaker.prob.AudioOuterProductHMM + :show-inheritance: + :special-members: __init__ + +.. autoclass:: matchmaker.prob.particle_filter_korzeniowski.ParticleFilterKorzeniowski + :show-inheritance: + :special-members: __init__ + +.. autoclass:: matchmaker.prob.skf.SwitchingKalmanFilterFollower :show-inheritance: :special-members: __init__ diff --git a/docs/source/modules/matchmaker.rst b/docs/source/modules/matchmaker.rst index 12ab8b3..7894f7c 100644 --- a/docs/source/modules/matchmaker.rst +++ b/docs/source/modules/matchmaker.rst @@ -5,3 +5,13 @@ matchmaker :members: run :show-inheritance: :special-members: __init__ + +Every score follower implements the ``OnlineAlignment`` interface. + +.. autoclass:: matchmaker.base.OnlineAlignment + :members: step, run, get_current_position + :special-members: __call__ + +.. autoclass:: matchmaker.external.OnlineParangonarAlignment + :show-inheritance: + :special-members: __init__ diff --git a/matchmaker/__init__.py b/matchmaker/__init__.py index a5feb7d..4abfa6e 100644 --- a/matchmaker/__init__.py +++ b/matchmaker/__init__.py @@ -15,7 +15,7 @@ try: __version__ = version("pymatchmaker") except PackageNotFoundError: # pragma: no cover - __version__ = "0.5.0" + __version__ = "0.5.1" ASSETS_DIR = Path(__file__).parent / "assets" diff --git a/matchmaker/io/audio.py b/matchmaker/io/audio.py index 7ca444f..d69b19b 100644 --- a/matchmaker/io/audio.py +++ b/matchmaker/io/audio.py @@ -5,6 +5,7 @@ """ import queue +import threading import time from types import TracebackType from typing import Dict, Optional, Tuple, Type, Union @@ -52,6 +53,10 @@ class AudioStream(Stream): Name or index of the audio device to be used. Ignored if ``file_path`` is given. + wait : bool + For file input, supply each complete audio block at its playback time + on a separate thread. Processing can lag behind but input is not dropped. + Notes ----- Frame caching: each call to ``_process_feature`` prepends @@ -301,25 +306,57 @@ def run_offline(self) -> None: audio_y = np.concatenate( (audio_y, np.zeros(self.hop_length - remainder, dtype=np.float32)) ) - trimmed_audio = audio_y - time_interval = self.hop_length / float(sr) - # Do not stop early on digital silence (all-zeros tails). - while trimmed_audio.size > 0: - self.input_index += 1 - self.last_data_received = time.time() - target_audio = trimmed_audio[: self.hop_length] - self._process_feature(target_audio, self.last_data_received) - trimmed_audio = trimmed_audio[self.hop_length :] + feeder = None + stop_feeder = threading.Event() + if self.wait: + data_queue = queue.Queue() + feeder = threading.Thread( + target=self._enqueue_audio, args=(audio_y, data_queue, stop_feeder) + ) + feeder.start() + blocks = iter(data_queue.get, None) + else: + blocks = ( + (audio_y[start : start + self.hop_length], time.time()) + for start in range(0, len(audio_y), self.hop_length) + ) - if not self.stream_start.is_set(): + try: + for target_audio, received_time in blocks: + if not self.listen: + break + self.input_index += 1 + self.last_data_received = received_time + self._process_feature(target_audio, received_time) self.stream_start.set() + finally: + stop_feeder.set() + if feeder is not None: + feeder.join() + self.queue.put(STREAM_END) + self.stream_start.set() + self.stop_listening() - if self.wait: - elapsed_time = time.time() - self.last_data_received - time.sleep(max(time_interval - elapsed_time, 0)) - - self.queue.put(STREAM_END) - self.stop_listening() + def _enqueue_audio(self, audio_y, data_queue, stop_event) -> None: + """Supply raw blocks at their end times, independently of processing.""" + self._playback_start = time.perf_counter() + try: + for start in range(0, len(audio_y), self.hop_length): + end = start + self.hop_length + deadline = self._playback_start + end / float(self.target_sr) + # Absolute deadlines prevent accumulated sleep/processing drift. + # A block is not available until all its samples have arrived. + while True: + remaining = deadline - time.perf_counter() + if remaining <= 0: + break + if stop_event.wait(remaining): + return + if stop_event.is_set(): + return + data_queue.put((audio_y[start:end], time.time())) + finally: + data_queue.put(None) def run_online(self) -> None: """Process audio in real-time from input device. diff --git a/matchmaker/prob/hmm.py b/matchmaker/prob/hmm.py index 14b88a7..e006634 100644 --- a/matchmaker/prob/hmm.py +++ b/matchmaker/prob/hmm.py @@ -261,6 +261,7 @@ def _build_hmm_modules( # observation model observation_model = BernoulliPitchObservationModel( pitch_profiles=pitch_profiles, + inserted_states=inserted_states, ) if inserted_states: @@ -932,9 +933,12 @@ class BernoulliPitchObservationModel(ObservationModel): Pre-computed pitch profiles, for each separate possible pitch in the MIDI range. Used in calculating the pitch observation probabilities. + inserted_states : bool, optional + If True, odd states share one uniform profile, evaluated once. + Default is False. """ - def __init__(self, pitch_profiles: NDArrayFloat): + def __init__(self, pitch_profiles: NDArrayFloat, inserted_states: bool = False): """ The initialization method. @@ -944,16 +948,23 @@ def __init__(self, pitch_profiles: NDArrayFloat): he pre-computed pitch profiles, for each separate possible pitch in the MIDI range. Used in calculating the pitch observation probabilities. + inserted_states : bool, optional + If True, odd states share one uniform profile, evaluated once. + Default is False. """ super().__init__(use_log_probabilities=False) # Store the parameters of the object: self.pitch_profiles = pitch_profiles + self.inserted_states = inserted_states def __call__(self, observation: NDArrayFloat) -> NDArrayFloat: - return compute_bernoulli_pitch_probabilities( - pitch_obs=observation, - pitch_profiles=self.pitch_profiles, - ) + if not self.inserted_states or len(self.pitch_profiles) < 2: + return compute_bernoulli_pitch_probabilities(observation, self.pitch_profiles) + # inserted states (odd indices) share one uniform profile: evaluate it once + obs_prob = np.empty(len(self.pitch_profiles)) + obs_prob[0::2] = compute_bernoulli_pitch_probabilities(observation, self.pitch_profiles[0::2]) + obs_prob[1::2] = compute_bernoulli_pitch_probabilities(observation, self.pitch_profiles[1:2])[0] + return obs_prob class GaussianAudioPitchObservationModel(ObservationModel): @@ -1536,6 +1547,15 @@ def __init__( **kwargs, ) + # Rightmost non-zero transition column per row; the cumulative max bounds row slices. + self._last_col = None + if isinstance(self.transition_model, ConstantTransitionModel): + self.transition_model.use_log_probabilities = False + T = self.transition_model.transition_probabilities + self._last_col = np.maximum.accumulate( + len(T) - 1 - np.argmax(T[:, ::-1] != 0, axis=1) + ) + def step(self, features) -> None: perf_time = self.current_perf_time ioi_obs = ( @@ -1545,10 +1565,30 @@ def step(self, features) -> None: ) self._prev_perf_time = perf_time - current_state = self.forward_algorithm_step( - observation=(features, ioi_obs, self.tempo_model.beat_period), - log_probabilities=False, - ) + observation = (features, ioi_obs, self.tempo_model.beat_period) + fv = self.forward_variable + + # The first step uses the initial distribution; other transition models use the original path. + if self._last_col is None or fv is None: + current_state = self.forward_algorithm_step( + observation=observation, log_probabilities=False + ) + else: + self.transition_model.use_log_probabilities = False + self.observation_model.use_log_probabilities = False + prior = np.zeros_like(fv) + nz = np.flatnonzero(fv) + if nz.size: + lo, hi = nz[0], nz[-1] + 1 + m = self._last_col[hi - 1] + 1 + + # Restrict T.T @ fv to reached states; this slice form keeps the product BLAS-friendly. + prior[:m] = fv[lo:hi] @ self.transition_model.transition_probabilities[lo:hi, :m] + fv = self.observation_model(observation) * prior + fv /= max(fv.sum(), 1e-6) + self.forward_variable = fv + current_state = np.argmax(fv) + self.input_index += 1 prev_index = self.current_index diff --git a/matchmaker/prob/skf.py b/matchmaker/prob/skf.py index c9ef791..8ccbb53 100644 --- a/matchmaker/prob/skf.py +++ b/matchmaker/prob/skf.py @@ -275,9 +275,10 @@ class SwitchingKalmanFilterFollower(OnlineAlignment): Each hypothesis is a tuple (k, a) where k is the chord index and a is the age (number of frames the current chord has lasted). Each hypothesis carries: - - prob : float, filtered probability p(k_n, a_n | y^n_1) - - mu_t : float, Kalman-filtered tempo mean E[t_k | ...] - - var_t: float, Kalman-filtered tempo variance Var[t_k | ...] + + - prob : float, filtered probability p(k_n, a_n | y^n_1) + - mu_t : float, Kalman-filtered tempo mean E[t_k | ...] + - var_t: float, Kalman-filtered tempo variance Var[t_k | ...] Parameters ---------- diff --git a/pyproject.toml b/pyproject.toml index 4965cc6..aaea721 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "pymatchmaker" -version = "0.5.0" +version = "0.5.1" description = "A package for real-time music alignment" readme = "README.md" requires-python = ">=3.10,<3.14" diff --git a/tests/test_io_audio.py b/tests/test_io_audio.py index b6e86e2..79d6a80 100644 --- a/tests/test_io_audio.py +++ b/tests/test_io_audio.py @@ -309,3 +309,133 @@ def test_process_frame(self): (np.zeros(self.stream.hop_length, dtype=np.float32), original_data) ) self.assertTrue(np.all(proc_output == expected_output)) + + +class TestPacedFileInput(unittest.TestCase): + def test_absolute_block_end_deadlines(self): + import queue + from types import SimpleNamespace + + clock = [100.0] + arrivals = [] + + class StopEvent: + def wait(self, duration): + # Simulate a scheduler that oversleeps each deadline by 3 ms. + clock[0] += duration + 0.003 + return False + + def is_set(self): + return False + + class InputQueue(queue.Queue): + def _put(self, item): + if item is not None: + arrivals.append(clock[0]) + super()._put(item) + + stream = SimpleNamespace(hop_length=20, target_sr=1000) + source = np.arange(100, dtype=np.float32) + q = InputQueue() + with patch.object(time, "perf_counter", side_effect=lambda: clock[0]): + AudioStream._enqueue_audio(stream, source, q, StopEvent()) + np.testing.assert_allclose( + np.asarray(arrivals) - 100, np.arange(1, 6) * 0.02 + 0.003 + ) + np.testing.assert_array_equal( + np.concatenate([q.get()[0] for _ in range(5)]), source + ) + self.assertIsNone(q.get_nowait()) + + def test_feeder_can_be_cancelled(self): + import queue + import threading + from types import SimpleNamespace + + stopped = threading.Event() + stopped.set() + q = queue.Queue() + AudioStream._enqueue_audio( + SimpleNamespace(hop_length=20, target_sr=1000), np.ones(100), q, stopped + ) + self.assertIsNone(q.get_nowait()) + self.assertTrue(q.empty()) + + def test_paced_and_fast_inputs_produce_identical_features(self): + from matchmaker.io.stream import STREAM_END + + # Includes a silent tail and an incomplete final block. + source = np.r_[np.arange(27, dtype=np.float32), np.zeros(18)] + results = [] + with patch.object( + AudioStream, + "_preload_audio", + lambda stream: setattr(stream, "_preloaded_audio", source.copy()), + ): + for wait in (False, True): + stream = AudioStream( + processor=DummyProcessor(), + file_path="unused.wav", + sample_rate=1000, + target_sr=1000, + hop_length=10, + wait=wait, + ) + stream.run_offline() + frames = [] + while True: + item = stream.queue.get_nowait() + if item is STREAM_END: + break + frames.append(item) + self.assertEqual(stream.input_index, 5) + self.assertTrue(stream.stream_start.is_set()) + self.assertFalse(stream.listen) + results.append(frames) + self.assertEqual(len(results[0]), 4) + self.assertEqual(len(results[1]), 4) + for fast, paced in zip(*results): + np.testing.assert_array_equal(fast[0], paced[0]) + self.assertEqual(fast[1], paced[1]) + + def test_processor_error_stops_feeder(self): + from matchmaker.io.stream import STREAM_END + + def fail(item): + raise ValueError("synthetic processor failure") + + with patch.object( + AudioStream, + "_preload_audio", + lambda stream: setattr(stream, "_preloaded_audio", np.ones(10000)), + ): + stream = AudioStream( + processor=fail, + file_path="unused.wav", + sample_rate=1000, + target_sr=1000, + hop_length=10, + wait=True, + ) + started = time.perf_counter() + with self.assertRaisesRegex(ValueError, "synthetic processor failure"): + stream.run_offline() + self.assertLess(time.perf_counter() - started, 1) + self.assertFalse(stream.listen) + self.assertTrue(stream.stream_start.is_set()) + self.assertIs(stream.queue.get_nowait(), STREAM_END) + + def test_empty_input_unblocks_consumer(self): + from matchmaker.io.stream import STREAM_END + + with patch.object( + AudioStream, + "_preload_audio", + lambda stream: setattr(stream, "_preloaded_audio", np.array([])), + ): + stream = AudioStream( + processor=DummyProcessor(), file_path="unused.wav", wait=True + ) + stream.run_offline() + self.assertTrue(stream.stream_start.is_set()) + self.assertIs(stream.queue.get_nowait(), STREAM_END)