Skip to content

Instantly share code, notes, and snippets.

@Natooz
Last active December 10, 2023 14:31
Show Gist options
  • Save Natooz/1a39413220d038e0ac3981f864039370 to your computer and use it in GitHub Desktop.
Save Natooz/1a39413220d038e0ac3981f864039370 to your computer and use it in GitHub Desktop.
Benchmarking MIDI parsing libraries Symusic VS Miditoolkit
#!/usr/bin/python3 python
"""Benchmark for Python MIDI parsing libraries.
"""
import random
from pathlib import Path
from time import time
from typing import Sequence
import numpy as np
from miditoolkit import Instrument, MidiFile, Note, Pedal
from prettytable import PrettyTable
from symusic import Score
from tqdm import tqdm
HERE = Path(__file__).parent
def are_notes_equals(note1: Note, note2) -> bool:
attrs_to_check = ("start", "pitch", "velocity", "end")
for attr_to_check in attrs_to_check:
if getattr(note1, attr_to_check) != getattr(note2, attr_to_check):
return False
return True
def are_control_changes_equals(cc1, cc2) -> bool:
return cc1.time == cc2.time and cc1.number == cc2.number and cc1.value == cc2.value
def are_pitch_bends_equals(pb1, pb2) -> bool:
return pb1.time == pb2.time and pb1.pitch == pb2.value
def are_pedals_equals(sp1, sp2) -> bool:
return sp1.start == sp2.time and sp1.end == sp2.time + sp2.duration
def are_tracks_equals(track1: Instrument, track2) -> int:
err = 0
for attr_ in ("program", "is_drum"):
if getattr(track1, attr_) != getattr(track2, attr_):
err += 1
track1.notes.sort(key=lambda x: (x.start, x.pitch, x.end, x.velocity))
track2.notes.sort(key=lambda x: (x.time, x.pitch, x.end, x.velocity))
for note1, note2 in zip(track1.notes, track2.notes):
if not are_notes_equals(note1, note2):
err += 1
for cc1, cc2 in zip(track1.control_changes, track2.controls):
if not are_control_changes_equals(cc1, cc2):
err += 1
for pb1, pb2 in zip(track1.pitch_bends, track2.pitch_bends):
if not are_pitch_bends_equals(pb1, pb2):
err += 1
# get pedals from miditoolkit
if len(track1.control_changes) >= 2:
# last_pedal_on_time is None when no Pedal control change is "on", and is equal to the oldest Pedal
# control change time (tick) while no CC to end it has been found
# We first need to sort the CC messages
track1.control_changes.sort(key=lambda cc: cc.time)
last_pedal_on_time = None
pedals_track1 = []
for control_change in track1.control_changes:
if control_change.number != 64:
continue
elif last_pedal_on_time is not None and control_change.value < 64:
pedals_track1.append(Pedal(last_pedal_on_time, control_change.time))
last_pedal_on_time = None
elif last_pedal_on_time is None and control_change.value >= 64:
last_pedal_on_time = control_change.time
for sp1, sp2 in zip(pedals_track1, track2.pedals):
if not are_pedals_equals(sp1, sp2):
err += 1
return err
def are_tempos_equals(tempo_change1, tempo_change2) -> bool:
if tempo_change1.time != tempo_change2.time or round(
tempo_change1.tempo, 3
) != round(tempo_change2.tempo, 3):
return False
return True
def are_time_signatures_equals(time_sig1, time_sig2) -> bool:
if (
time_sig1.time != time_sig2.time
or time_sig1.numerator != time_sig2.numerator
or time_sig1.denominator != time_sig2.denominator
):
return False
return True
def are_key_signatures_equals(key_sig1, key_sig2) -> bool:
# if key_sig1.time != key_sig2.time or key_sig1.key_number != key_sig2.key:
# we don't test key signatures as they are decoded differently
if key_sig1.time != key_sig2.time:
return False
return True
def are_lyrics_or_markers_equals(lyric1, lyric2) -> bool:
if lyric1.time != lyric2.time or lyric1.text != lyric2.text:
return False
return True
def benchmark_midi_parsing(
midi_paths: Sequence[Path],
seed: int = 777,
):
r"""Reads a few MIDI files, convert them into token sequences, convert them back to MIDI files.
The converted back MIDI files should identical to original one, expect with note starting and ending
times quantized, and maybe a some duplicated notes removed
:param midi_paths: sequence of paths to the test MIDIs
:param seed: random seed
"""
random.seed(seed)
times_mtk, times_sms = [], []
for midi_path in tqdm(midi_paths, desc="Loading MIDIs"):
# Miditoolkit
t0 = time()
midi_mtk = MidiFile(midi_path)
times_mtk.append(time() - t0)
# Symusic
t0 = time()
midi_sms = Score(midi_path)
times_sms.append(time() - t0)
err = 0
nb_checks = (
len(midi_mtk.tempo_changes)
+ len(midi_mtk.time_signature_changes)
+ len(midi_mtk.key_signature_changes)
+ len(midi_mtk.lyrics)
+ len(midi_mtk.markers)
)
# midi_ptm = PrettyMIDI(str(midi_path))
# tempos_ptm = midi_ptm.get_tempo_changes()
# Check global MIDI events:
# time signatures, key signatures, tempos, lyrics, markers
assert midi_mtk.ticks_per_beat == midi_sms.ticks_per_quarter
if len(midi_mtk.tempo_changes) != len(midi_sms.tempos):
num_same_consecutive_tempos = 0
previous_tempo = midi_sms.tempos[0].tempo
for tempo in midi_sms.tempos[1:]:
if tempo.tempo == previous_tempo:
num_same_consecutive_tempos += 1
previous_tempo = tempo.tempo
if len(midi_mtk.tempo_changes) + num_same_consecutive_tempos != len(midi_sms.tempos):
print(
f"{midi_path.name}: expected {len(midi_mtk.tempo_changes)} tempos, got {len(midi_sms.tempos)}"
)
err += abs(len(midi_mtk.tempo_changes) - len(midi_sms.tempos))
else:
for tempo1, tempo2 in zip(midi_mtk.tempo_changes, midi_sms.tempos):
if not are_tempos_equals(tempo1, tempo2):
err += 1
if len(midi_mtk.time_signature_changes) != len(midi_sms.time_signatures):
print(
f"{midi_path.name}: expected {len(midi_mtk.time_signature_changes)}"
f"time signatures, got {len(midi_sms.time_signatures)}"
)
err += abs(
len(midi_mtk.time_signature_changes) - len(midi_sms.time_signatures)
)
else:
for ts1, ts2 in zip(
midi_mtk.time_signature_changes, midi_sms.time_signatures
):
if not are_time_signatures_equals(ts1, ts2):
err += 1
if len(midi_mtk.key_signature_changes) != len(midi_sms.key_signatures):
print(
f"{midi_path.name}: expected {len(midi_mtk.key_signature_changes)}"
f"key signatures, got {len(midi_sms.key_signatures)}"
)
err += abs(
len(midi_mtk.key_signature_changes) - len(midi_sms.key_signatures)
)
else:
for ks1, ks2 in zip(
midi_mtk.key_signature_changes, midi_sms.key_signatures
):
if not are_key_signatures_equals(ks1, ks2):
err += 1
if len(midi_mtk.lyrics) != len(midi_sms.lyrics):
print(
f"{midi_path.name}: expected {len(midi_mtk.lyrics)}"
f"lyrics, got {len(midi_sms.lyrics)}"
)
err += abs(len(midi_mtk.lyrics) - len(midi_sms.lyrics))
else:
for lyrics1, lyrics2 in zip(midi_mtk.lyrics, midi_sms.lyrics):
if not are_lyrics_or_markers_equals(lyrics1, lyrics2):
err += 1
if len(midi_mtk.markers) != len(midi_sms.markers):
print(
f"{midi_path.name}: expected {len(midi_mtk.markers)} markers, got {len(midi_sms.markers)}"
)
err += abs(len(midi_mtk.markers) - len(midi_sms.markers))
else:
for marker1, marker2 in zip(midi_mtk.markers, midi_sms.markers):
if not are_lyrics_or_markers_equals(marker1, marker2):
err += 1
# Check tracks: notes, control changes, pitch bends
midi_mtk.instruments.sort(key=lambda t: (t.program, t.is_drum))
programs_sms_0 = [(track.program, track.is_drum) for track in midi_sms.tracks]
midi_sms.tracks.sort_inplace(key=lambda t: (t.program, t.is_drum))
programs_sms_1 = [(track.program, track.is_drum) for track in midi_sms.tracks]
for track1, track2 in zip(midi_mtk.instruments, midi_sms.tracks):
# assert len(track1.notes) == len(track2.notes)
nb_checks += len(track1.notes)
err += are_tracks_equals(track1, track2)
# If something is wrong, we print the error count/rate and save the MIDIs
if err > 0:
print(f"{midi_path.name}: {err} errors ({err / nb_checks:.2f})")
for track in midi_sms.tracks:
notes_mtk = [
Note(
note.velocity,
note.pitch,
note.start,
note.start + note.duration,
)
for note in track.notes
]
notes_mtk.sort(key=lambda x: (x.start, x.pitch, x.end, x.velocity))
track_mtk = Instrument(
0,
False,
notes=notes_mtk,
name=f"{'track.name'} parsed from Symusic",
)
midi_mtk.instruments.append(track_mtk)
(HERE / "MIDIs_failed").mkdir(exist_ok=True)
midi_mtk.dump(HERE / "MIDIs_failed" / midi_path.name)
# Record times
table = PrettyTable(
["Lib", "Speed"],
title="MIDI loading speed comparison",
)
times_mtk, times_sms = np.array(times_mtk), np.array(times_sms)
table.add_row(
["MidiToolkit", f"{np.mean(times_mtk):.4f} ± {np.std(times_mtk):.3f} sec"]
)
table.add_row(
["SyMusic", f"{np.mean(times_sms):.4f} ± {np.std(times_sms):.3f} sec"]
)
print(table)
if __name__ == "__main__":
all_midi_paths = (
list((HERE / "MIDIs_one_track").glob("**/*.mid")) +
list((HERE / "MIDIs_multitrack").glob("**/*.mid"))
)
# all_midi_paths = list((HERE / "MIDIs_multitrack").glob("**/*.mid"))
benchmark_midi_parsing(all_midi_paths)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment