pyquist 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pyquist/score.py ADDED
@@ -0,0 +1,512 @@
1
+ """Score representation, rendering, and MIDI ingestion.
2
+
3
+ A :class:`Score` is a list of :class:`Event` — onset-based musical events.
4
+ ``Score`` behaves like a regular Python list (subclass of
5
+ :class:`collections.UserList`): you can iterate, index, slice, concatenate
6
+ with ``+``, repeat with ``*``, append, etc. — all preserving ``Score`` type.
7
+
8
+ Each event carries a ``time`` (in *seconds* if rendered without a metronome,
9
+ in *ticks* otherwise — a "tick" being whatever discrete time unit the
10
+ metronome maps to seconds) and an instrument-specific ``kwargs`` dict. The
11
+ metronome is kept as a separate object (a :class:`Metronome` instance) and
12
+ passed explicitly to :meth:`Score.render` when needed.
13
+
14
+ To turn a ``Score`` into audio, call :meth:`Score.render` with an
15
+ :class:`Instrument` — a callable invoked as ``instrument(**event.kwargs)``
16
+ that returns :class:`Audio`. An instrument simply declares the kwargs it
17
+ cares about and absorbs the rest with ``**kwargs``::
18
+
19
+ def sine(pitch, duration, **kwargs):
20
+ ...
21
+ return Audio(samples, sample_rate=sr)
22
+
23
+ For per-event dispatch (e.g. different sounds for drums vs. pitched notes),
24
+ capture the deciding key as a named parameter and forward the rest::
25
+
26
+ def my_instrument(is_drum, **kwargs):
27
+ if is_drum:
28
+ return drum_kit(**kwargs)
29
+ return sine(**kwargs)
30
+
31
+ Because instruments are called with ``**event.kwargs``, every kwargs key
32
+ should be a valid Python identifier.
33
+
34
+ Common "tick" units:
35
+
36
+ * **beats** — paired with :class:`BasicMetronome` (e.g., 120 BPM).
37
+ * **MIDI ticks** — paired with :class:`MIDIMetronome` (subdivisions of a
38
+ quarter note as defined by the MIDI file's PPQ resolution and tempo map).
39
+
40
+ For MIDI ingestion, see :meth:`Score.from_midi`.
41
+ """
42
+
43
+ import abc
44
+ import bisect
45
+ import math
46
+ import os
47
+ from collections import UserList
48
+ from typing import (
49
+ IO,
50
+ Any,
51
+ Callable,
52
+ Dict,
53
+ List,
54
+ NamedTuple,
55
+ Optional,
56
+ Tuple,
57
+ TypeAlias,
58
+ Union,
59
+ )
60
+
61
+ import mido
62
+
63
+ from .audio import Audio
64
+
65
+ _KwargsDict: TypeAlias = Dict[str, Any]
66
+
67
+ # An off-by-this-amount epsilon used as the right boundary of Score.segment.
68
+ _SEGMENT_EPS = 1e-9
69
+
70
+
71
+ class Event(NamedTuple):
72
+ """A timestamped, instrument-agnostic musical event.
73
+
74
+ ``time`` is in seconds when the score is rendered without a metronome,
75
+ or in ticks (whatever unit the metronome maps to seconds — beats, MIDI
76
+ ticks, ...) when a metronome is supplied. ``kwargs`` is opaque to the
77
+ score; it is forwarded to the instrument as ``instrument(**kwargs)`` at
78
+ render time, so every key should be a valid Python identifier (e.g.,
79
+ avoid dashes).
80
+
81
+ ``Event`` is a ``NamedTuple``: it unpacks like a regular tuple
82
+ (``time, kwargs = event``), can be constructed positionally
83
+ (``Event(0.5, {"pitch": 60})``) or by keyword.
84
+ """
85
+
86
+ time: float
87
+ kwargs: _KwargsDict
88
+
89
+
90
+ # A callable invoked as ``instrument(**event.kwargs)`` that returns the
91
+ # rendered Audio for one event. Declare the kwargs you use and absorb the
92
+ # rest with ``**kwargs``.
93
+ Instrument: TypeAlias = Callable[..., Audio]
94
+
95
+
96
+ # ---------------------------------------------------------------------------
97
+ # Metronome
98
+ # ---------------------------------------------------------------------------
99
+
100
+
101
+ class Metronome(abc.ABC):
102
+ """Converts between score-time *ticks* and wall-clock *seconds*.
103
+
104
+ A "tick" here is the abstract time unit a :class:`Score` uses; different
105
+ ``Metronome`` subclasses define what a tick means concretely (a beat for
106
+ :class:`BasicMetronome`, a MIDI PPQ tick for :class:`MIDIMetronome`).
107
+ """
108
+
109
+ @abc.abstractmethod
110
+ def tick_to_seconds(self, tick: float) -> float:
111
+ """Returns the wall-clock time in seconds at which ``tick`` occurs."""
112
+
113
+ @abc.abstractmethod
114
+ def seconds_to_tick(self, seconds: float) -> float:
115
+ """Returns the score tick at the given wall-clock time."""
116
+
117
+
118
+ class BasicMetronome(Metronome):
119
+ """A fixed-tempo metronome where 1 tick = 1 beat.
120
+
121
+ Defaults to 60 BPM, which makes 1 tick = 1 second — a convenient
122
+ identity mapping for scores whose ``time`` field is already in seconds.
123
+ Pass an explicit ``bpm`` to map beats to seconds at a different tempo.
124
+ """
125
+
126
+ def __init__(self, bpm: float = 60.0):
127
+ self.bpm = bpm
128
+ self.beat_duration = 60.0 / bpm
129
+
130
+ def tick_to_seconds(self, tick: float) -> float:
131
+ return tick * self.beat_duration
132
+
133
+ def seconds_to_tick(self, seconds: float) -> float:
134
+ return seconds / self.beat_duration
135
+
136
+
137
+ # ---------------------------------------------------------------------------
138
+ # Score
139
+ # ---------------------------------------------------------------------------
140
+
141
+
142
+ class Score(UserList):
143
+ """A list of :class:`Event` with music-specific helpers.
144
+
145
+ ``Score`` subclasses :class:`collections.UserList`, so all the standard
146
+ list operations work and preserve ``Score`` type — ``+``, ``*``,
147
+ slicing, ``+=``, ``.copy()``, ``.append()``, etc.
148
+
149
+ The ``time`` field of each event is interpreted in *seconds* unless you
150
+ pass a :class:`Metronome` to :meth:`render`, in which case ``time`` is
151
+ treated as *ticks* and converted via ``metronome.tick_to_seconds``. The
152
+ metronome is not stored on the score — keep it as a separate variable
153
+ (or use the ``(score, metronome)`` tuple returned by :meth:`from_midi`).
154
+
155
+ Construct from any iterable of events::
156
+
157
+ Score([Event(0.0, {"pitch": 60}), Event(1.0, {"pitch": 64})])
158
+
159
+ Or load from a MIDI file via :meth:`from_midi`.
160
+ """
161
+
162
+ # --- properties --------------------------------------------------------
163
+
164
+ @property
165
+ def start_time(self) -> float:
166
+ """The earliest event's ``time``. Raises ``ValueError`` if empty."""
167
+ if not self:
168
+ raise ValueError("Empty score has no start_time.")
169
+ return min(e.time for e in self)
170
+
171
+ @property
172
+ def end_time(self) -> float:
173
+ """The latest event's ``time``. Raises ``ValueError`` if empty.
174
+
175
+ Note: this is the latest *onset*, not the end of any sustained note.
176
+ Events have no intrinsic duration at the score level — only their
177
+ instrument knows.
178
+ """
179
+ if not self:
180
+ raise ValueError("Empty score has no end_time.")
181
+ return max(e.time for e in self)
182
+
183
+ @property
184
+ def duration(self) -> float:
185
+ """``end_time - start_time``. Raises ``ValueError`` if empty."""
186
+ return self.end_time - self.start_time
187
+
188
+ # --- factory + slicing methods -----------------------------------------
189
+
190
+ @classmethod
191
+ def from_midi(
192
+ cls,
193
+ midi: Union[str, os.PathLike, IO, mido.MidiFile],
194
+ *,
195
+ as_notes: bool = True,
196
+ all_events: bool = False,
197
+ ) -> Tuple["Score", "MIDIMetronome"]:
198
+ """Parses a MIDI file into a ``(score, metronome)`` pair.
199
+
200
+ Every emitted :class:`Event` has ``time`` set to its absolute MIDI
201
+ tick and ``kwargs["mtype"]`` (message type) identifying the kind of
202
+ event. The exact kwargs schema depends on the flags below.
203
+
204
+ When ``as_notes=True`` (default), each ``note_on``/``note_off`` pair
205
+ across all tracks is collapsed into a single ``"note"`` event with:
206
+
207
+ * ``kwargs["mtype"]`` — the literal string ``"note"``.
208
+ * ``kwargs["duration"]`` — the note's duration in seconds.
209
+ * ``kwargs["duration_ticks"]`` — the note's duration in MIDI ticks.
210
+ * ``kwargs["pitch"]`` — MIDI pitch (0–127).
211
+ * ``kwargs["velocity"]`` — MIDI NOTE_ON velocity (0–127).
212
+ * ``kwargs["program"]`` — MIDI program (instrument) number (0–127).
213
+ * ``kwargs["is_drum"]`` — ``True`` if the note is on MIDI channel
214
+ 10 (zero-indexed: 9), the conventional percussion channel.
215
+ * ``kwargs["channel"]`` — MIDI channel (0-15).
216
+
217
+ When ``as_notes=False``, raw ``"note_on"`` and ``"note_off"`` events
218
+ are emitted as separate :class:`Event`\\ s instead — each with
219
+ ``kwargs`` equal to the underlying ``mido`` message's attributes
220
+ (with ``"type"`` renamed to ``"mtype"``) sans its delta-``time``
221
+ field.
222
+
223
+ When ``all_events=True``, all other MIDI messages (tempo changes,
224
+ program changes, control changes, ...) are also emitted with the
225
+ same barebones ``msg.dict()``-style kwargs.
226
+
227
+ Pass the returned ``metronome`` to :meth:`render` so ticks are
228
+ converted to seconds using the file's actual tempo map.
229
+
230
+ Args:
231
+ midi: A path, a file-like object, or an already-parsed
232
+ :class:`mido.MidiFile`.
233
+ as_notes: If ``True`` (default), collapse ``note_on``/``note_off``
234
+ pairs into a single ``"note"`` event. If ``False``, emit them
235
+ as separate events.
236
+ all_events: If ``True``, also emit non-note MIDI messages
237
+ (``set_tempo``, ``program_change``, ``control_change``, ...).
238
+ Defaults to ``False`` (note events only).
239
+ """
240
+ mid = _load_midi(midi)
241
+ metronome = MIDIMetronome(mid)
242
+ events = _parse_midi_events(
243
+ mid, metronome, as_notes=as_notes, all_events=all_events
244
+ )
245
+ events.sort(key=lambda e: e.time)
246
+ return cls(events), metronome
247
+
248
+ def segment(
249
+ self,
250
+ *,
251
+ offset: Optional[float] = None,
252
+ duration: Optional[float] = None,
253
+ relativize: bool = True,
254
+ ) -> "Score":
255
+ """Returns the events whose ``time`` falls in ``[offset, offset+duration)``.
256
+
257
+ The right boundary is open with a small epsilon (``offset + duration
258
+ - 1e-9``) to suppress floating-point off-by-ones at exact-end matches.
259
+
260
+ Args:
261
+ offset: Lower bound on event time (inclusive). Defaults to the
262
+ beginning of the score (``0.0``).
263
+ duration: Length of the window. Defaults to the rest of the score
264
+ (no upper bound).
265
+ relativize: If ``True`` (default), shift every kept event's
266
+ ``time`` by ``-offset`` so the returned score begins at 0.
267
+ If ``False``, keep the original timestamps.
268
+ """
269
+ start = offset or 0.0
270
+ end = float("inf") if duration is None else start + duration - _SEGMENT_EPS
271
+ shift = start if relativize else 0.0
272
+ return Score(
273
+ Event(e.time - shift, e.kwargs) for e in self if start <= e.time < end
274
+ )
275
+
276
+ def render(
277
+ self,
278
+ instrument: Instrument,
279
+ metronome: Optional[Metronome] = None,
280
+ ) -> Audio:
281
+ """Renders this score to a single mixed :class:`Audio`.
282
+
283
+ Each event is rendered by calling ``instrument(**event.kwargs)`` and
284
+ mixed in at its onset time. Onsets are interpreted as ticks (and
285
+ converted via ``metronome.tick_to_seconds``) when a metronome is
286
+ given, otherwise as seconds.
287
+
288
+ The instrument is time-agnostic: it receives only the event's
289
+ ``kwargs``, not its ``time``. To vary an instrument by onset, copy
290
+ the time into ``kwargs`` when building the score. For per-event
291
+ dispatch (e.g. different instruments for drums vs. pitched notes),
292
+ branch inside the instrument.
293
+
294
+ All instrument outputs must share a ``sample_rate`` and a
295
+ ``num_channels``; otherwise ``ValueError`` is raised. An empty
296
+ score returns a zero-length, mono ``Audio``.
297
+ """
298
+ if not self:
299
+ return Audio.zeros(0, 1)
300
+
301
+ rendered: List[Tuple[float, Audio]] = []
302
+ for event in self:
303
+ audio = instrument(**event.kwargs)
304
+ if not isinstance(audio, Audio):
305
+ raise TypeError(
306
+ f"instrument(**event.kwargs) must return an Audio; "
307
+ f"got {type(audio).__name__}."
308
+ )
309
+ seconds = (
310
+ event.time
311
+ if metronome is None
312
+ else metronome.tick_to_seconds(event.time)
313
+ )
314
+ rendered.append((seconds, audio))
315
+
316
+ # All rendered audios must agree on sample_rate and num_channels.
317
+ sample_rates = {audio.sample_rate for _, audio in rendered}
318
+ if len(sample_rates) != 1:
319
+ raise ValueError(f"Inconsistent sample rates: {sample_rates}.")
320
+ sample_rate = sample_rates.pop()
321
+ if sample_rate is None:
322
+ raise ValueError("Rendered audio is missing a sample_rate.")
323
+
324
+ channel_counts = {audio.num_channels for _, audio in rendered}
325
+ if len(channel_counts) != 1:
326
+ raise ValueError(f"Inconsistent channel counts: {channel_counts}.")
327
+ num_channels = channel_counts.pop()
328
+
329
+ # Allocate the output and mix in each event.
330
+ duration = max(seconds + audio.duration for seconds, audio in rendered)
331
+ output = Audio.zeros(
332
+ math.ceil(duration * sample_rate),
333
+ num_channels,
334
+ sample_rate=sample_rate,
335
+ )
336
+ for seconds, audio in rendered:
337
+ sample = int(seconds * sample_rate)
338
+ output[sample : sample + audio.num_samples, :] += audio
339
+ return output
340
+
341
+
342
+ # ---------------------------------------------------------------------------
343
+ # MIDI ingestion (mido-based)
344
+ # ---------------------------------------------------------------------------
345
+
346
+ # A MIDI tempo map: list of (absolute_tick, microseconds_per_quarter_note),
347
+ # sorted by tick, with an entry at tick 0.
348
+ _TempoMap: TypeAlias = List[Tuple[int, int]]
349
+
350
+ # Default MIDI tempo if a file has no set_tempo events: 120 BPM.
351
+ _DEFAULT_MSPB = 500_000
352
+
353
+
354
+ def _load_midi(midi: Union[str, os.PathLike, IO, mido.MidiFile]) -> mido.MidiFile:
355
+ """Returns a :class:`mido.MidiFile` from a path, file-like, or instance."""
356
+ if isinstance(midi, mido.MidiFile):
357
+ return midi
358
+ if isinstance(midi, (str, os.PathLike)):
359
+ return mido.MidiFile(midi)
360
+ return mido.MidiFile(file=midi)
361
+
362
+
363
+ def _extract_tempo_map(mid: mido.MidiFile) -> _TempoMap:
364
+ """Returns a sorted list of ``(absolute_tick, microseconds_per_beat)``.
365
+
366
+ Always begins with an entry at tick 0 (uses the default 120 BPM if no
367
+ earlier ``set_tempo`` event exists).
368
+ """
369
+ events: List[Tuple[int, int]] = []
370
+ for track in mid.tracks:
371
+ abs_tick = 0
372
+ for msg in track:
373
+ abs_tick += msg.time
374
+ if msg.type == "set_tempo":
375
+ events.append((abs_tick, msg.tempo))
376
+ events.sort(key=lambda e: e[0])
377
+ if not events or events[0][0] != 0:
378
+ events.insert(0, (0, _DEFAULT_MSPB))
379
+ return events
380
+
381
+
382
+ class MIDIMetronome(Metronome):
383
+ """A metronome that follows a MIDI file's PPQ resolution and tempo map.
384
+
385
+ 1 tick = 1 MIDI tick (a PPQ subdivision of a quarter note). Tempo
386
+ changes inside the file are honored, so ``tick_to_seconds`` is
387
+ generally non-linear across the file.
388
+
389
+ Args:
390
+ midi: A path, a file-like object, or an already-parsed
391
+ :class:`mido.MidiFile`.
392
+ """
393
+
394
+ def __init__(self, midi: Union[str, os.PathLike, IO, mido.MidiFile]):
395
+ mid = _load_midi(midi)
396
+ self.ticks_per_beat = mid.ticks_per_beat
397
+ tempo_map = _extract_tempo_map(mid)
398
+
399
+ # Precompute (start_tick, start_seconds, mspb) per tempo segment so
400
+ # both directions of the conversion are O(log n).
401
+ self._tick_starts: List[int] = []
402
+ self._second_starts: List[float] = []
403
+ self._mspbs: List[int] = []
404
+
405
+ seconds = 0.0
406
+ prev_tick, prev_mspb = tempo_map[0]
407
+ self._tick_starts.append(prev_tick)
408
+ self._second_starts.append(0.0)
409
+ self._mspbs.append(prev_mspb)
410
+
411
+ for next_tick, next_mspb in tempo_map[1:]:
412
+ seconds += mido.tick2second(
413
+ next_tick - prev_tick, self.ticks_per_beat, prev_mspb
414
+ )
415
+ self._tick_starts.append(next_tick)
416
+ self._second_starts.append(seconds)
417
+ self._mspbs.append(next_mspb)
418
+ prev_tick, prev_mspb = next_tick, next_mspb
419
+
420
+ def tick_to_seconds(self, tick: float) -> float:
421
+ idx = max(0, bisect.bisect_right(self._tick_starts, tick) - 1)
422
+ start_tick = self._tick_starts[idx]
423
+ start_seconds = self._second_starts[idx]
424
+ mspb = self._mspbs[idx]
425
+ return start_seconds + mido.tick2second(
426
+ tick - start_tick, self.ticks_per_beat, mspb
427
+ )
428
+
429
+ def seconds_to_tick(self, seconds: float) -> float:
430
+ idx = max(0, bisect.bisect_right(self._second_starts, seconds) - 1)
431
+ start_tick = self._tick_starts[idx]
432
+ start_seconds = self._second_starts[idx]
433
+ mspb = self._mspbs[idx]
434
+ return start_tick + mido.second2tick(
435
+ seconds - start_seconds, self.ticks_per_beat, mspb
436
+ )
437
+
438
+
439
+ def _parse_midi_events(
440
+ mid: mido.MidiFile,
441
+ metronome: "MIDIMetronome",
442
+ *,
443
+ as_notes: bool = True,
444
+ all_events: bool = False,
445
+ ) -> List[Event]:
446
+ """Walks all tracks and converts MIDI messages to :class:`Event`\\ s.
447
+
448
+ See :meth:`Score.from_midi` for the semantics of ``as_notes`` and
449
+ ``all_events``.
450
+ """
451
+ events: List[Event] = []
452
+ for track in mid.tracks:
453
+ abs_tick = 0
454
+ # Per-track-and-channel program (MIDI Program Change is per-channel,
455
+ # but channels mean different things in different tracks).
456
+ programs: Dict[int, int] = {}
457
+ # Active notes keyed by (channel, pitch); two simultaneous notes on
458
+ # the same channel/pitch in the same track aren't standard MIDI.
459
+ active: Dict[Tuple[int, int], Tuple[int, int, int]] = {}
460
+
461
+ for msg in track:
462
+ abs_tick += msg.time
463
+ is_note_on = msg.type == "note_on" and msg.velocity > 0
464
+ is_note_off = msg.type == "note_off" or (
465
+ msg.type == "note_on" and msg.velocity == 0
466
+ )
467
+ is_note = is_note_on or is_note_off
468
+
469
+ if msg.type == "program_change":
470
+ programs[msg.channel] = msg.program
471
+
472
+ if is_note and as_notes:
473
+ # Pair note_on/note_off into a single "note" event.
474
+ if is_note_on:
475
+ active[(msg.channel, msg.note)] = (
476
+ abs_tick,
477
+ msg.velocity,
478
+ programs.get(msg.channel, 0),
479
+ )
480
+ else: # is_note_off
481
+ key = (msg.channel, msg.note)
482
+ if key not in active:
483
+ continue # Stray note_off; skip silently.
484
+ on_tick, velocity, program = active.pop(key)
485
+ off_tick = abs_tick
486
+ duration = metronome.tick_to_seconds(
487
+ off_tick
488
+ ) - metronome.tick_to_seconds(on_tick)
489
+ events.append(
490
+ Event(
491
+ time=on_tick,
492
+ kwargs={
493
+ "mtype": "note",
494
+ "duration": duration,
495
+ "duration_ticks": off_tick - on_tick,
496
+ "pitch": msg.note,
497
+ "velocity": velocity,
498
+ "program": program,
499
+ "is_drum": msg.channel == 9,
500
+ "channel": msg.channel,
501
+ },
502
+ )
503
+ )
504
+ elif (is_note and not as_notes) or (not is_note and all_events):
505
+ # Barebones path: kwargs = msg attributes (sans delta-time).
506
+ # Rename mido's ``"type"`` to ``"mtype"`` (message type) so it
507
+ # doesn't shadow the ``type`` builtin when unpacked as **kwargs.
508
+ kwargs = msg.dict()
509
+ kwargs.pop("time", None)
510
+ kwargs["mtype"] = kwargs.pop("type")
511
+ events.append(Event(time=abs_tick, kwargs=kwargs))
512
+ return events