262 lines
9.7 KiB
Python
262 lines
9.7 KiB
Python
"""Real standard-profile text -> intent -> score -> compiled SMF -> disk read-back."""
|
|
|
|
import shutil
|
|
import uuid
|
|
from collections.abc import Iterator
|
|
from fractions import Fraction
|
|
from pathlib import Path
|
|
|
|
import mido # type: ignore[import-untyped]
|
|
import pytest
|
|
|
|
from riff_groove_builder.articulations import compile_score
|
|
from riff_groove_builder.compose import compose_score
|
|
from riff_groove_builder.description import resolve_description
|
|
from riff_groove_builder.errors import UnsupportedArticulationError, UnsupportedDescriptionError
|
|
from riff_groove_builder.midi import validate_midi_file, write_midi
|
|
from riff_groove_builder.profiles import load_profile_registry
|
|
from riff_groove_builder.schemas import GenerateMusicRequest, Part, ProfileSelection, Score
|
|
|
|
ROOT = Path(__file__).resolve().parents[2]
|
|
pytestmark = pytest.mark.integration
|
|
Event = tuple[int, str, int, int, int]
|
|
|
|
|
|
@pytest.fixture
|
|
def workspace() -> Iterator[Path]:
|
|
path = ROOT / ".test-artifacts" / f"text-midi-{uuid.uuid4().hex}"
|
|
path.mkdir(parents=True)
|
|
try:
|
|
yield path
|
|
finally:
|
|
shutil.rmtree(path)
|
|
|
|
|
|
def generate(text: str, path: Path, seed: int = 0) -> Score:
|
|
request = GenerateMusicRequest(description=text, basename=path.stem, seed=seed)
|
|
resolved = resolve_description(request)
|
|
selected = load_profile_registry().select(
|
|
resolved.intent.parts,
|
|
ProfileSelection(
|
|
**{
|
|
part: "standard.gm-drums.v1" if part == "drums" else f"standard.{part}.v1"
|
|
for part in resolved.intent.parts
|
|
}
|
|
),
|
|
)
|
|
assert all(profile.provenance.status == "standard_midi" for profile in selected.values())
|
|
assert all(profile.summary.mapping_kind == "standard_midi" for profile in selected.values())
|
|
assert {part: profile.id for part, profile in selected.items()} == {
|
|
part: {
|
|
"lead": "standard.lead.v1",
|
|
"bass": "standard.bass.v1",
|
|
"drums": "standard.gm-drums.v1",
|
|
}[part]
|
|
for part in resolved.intent.parts
|
|
}
|
|
score = compose_score(resolved.intent, selected)
|
|
plan = compile_score(score, selected)
|
|
assert write_midi(path, plan) == path
|
|
validate_midi_file(path, plan)
|
|
return score
|
|
|
|
|
|
def events(path: Path) -> list[list[Event]]:
|
|
result: list[list[Event]] = []
|
|
for track in mido.MidiFile(path).tracks[1:]:
|
|
tick = 0
|
|
part: list[Event] = []
|
|
for message in track:
|
|
tick += message.time
|
|
if not message.is_meta:
|
|
assert message.type in ("note_on", "note_off")
|
|
part.append((tick, message.type, message.channel, message.note, message.velocity))
|
|
result.append(part)
|
|
return result
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("text", "parts", "tempo", "bars", "meter", "root", "minor"),
|
|
[
|
|
("lead only 90 BPM 2 bars 3/4 D major quarter", ["lead"], 90, 2, (3, 4), 2, False),
|
|
("bass only 72.5 BPM 3 bars 6/8 Bb minor eighth", ["bass"], 72.5, 3, (6, 8), 10, True),
|
|
("drums only 155 BPM 2 bars 7/8 sixteenth", ["drums"], 155, 2, (7, 8), 4, True),
|
|
(
|
|
"lead bass drums 137.5 BPM 4 bars 4/4 F# minor eighth",
|
|
["lead", "bass", "drums"],
|
|
137.5,
|
|
4,
|
|
(4, 4),
|
|
6,
|
|
True,
|
|
),
|
|
(
|
|
"no drums 111 BPM 1 bar 7/8 Eb major quarter rests",
|
|
["lead", "bass"],
|
|
111,
|
|
1,
|
|
(7, 8),
|
|
3,
|
|
False,
|
|
),
|
|
],
|
|
)
|
|
def test_real_disk_tempo_meter_parts_pitch_timing_and_pairing(
|
|
workspace: Path,
|
|
text: str,
|
|
parts: list[Part],
|
|
tempo: float,
|
|
bars: int,
|
|
meter: tuple[int, int],
|
|
root: int,
|
|
minor: bool,
|
|
) -> None:
|
|
path = workspace / "description.mid"
|
|
score = generate(text, path)
|
|
assert score.intent.parts == parts
|
|
midi = mido.MidiFile(path)
|
|
assert midi.type == 1
|
|
assert midi.ticks_per_beat == 960
|
|
assert len(midi.tracks) == len(parts) + 1
|
|
expected_end = Fraction(bars * meter[0] * 4 * 960, meter[1])
|
|
assert expected_end.denominator == 1
|
|
conductor = midi.tracks[0]
|
|
assert [(msg.tempo, msg.time) for msg in conductor if msg.type == "set_tempo"] == [
|
|
(round(60_000_000 / tempo), 0)
|
|
]
|
|
assert [
|
|
(msg.numerator, msg.denominator, msg.time)
|
|
for msg in conductor
|
|
if msg.type == "time_signature"
|
|
] == [(*meter, 0)]
|
|
assert abs(midi.length - float(expected_end / 960) * round(60_000_000 / tempo) / 1e6) < 1e-9
|
|
for track in midi.tracks:
|
|
assert sum(msg.time for msg in track) == expected_end
|
|
assert track[-1].type == "end_of_track"
|
|
scale = {0, 2, 3, 5, 7, 8, 10} if minor else {0, 2, 4, 5, 7, 9, 11}
|
|
for part, track, actual in zip(parts, midi.tracks[1:], events(path), strict=True):
|
|
assert track[0].name == part.capitalize()
|
|
channel = {"lead": 0, "bass": 1, "drums": 9}[part]
|
|
active: dict[int, int] = {}
|
|
onsets = 0
|
|
for tick, kind, ch, pitch, velocity in actual:
|
|
assert ch == channel
|
|
assert 0 <= tick <= expected_end
|
|
if kind == "note_on":
|
|
assert pitch not in active
|
|
assert tick < expected_end and 1 <= velocity <= 127
|
|
active[pitch] = tick
|
|
onsets += 1
|
|
if part == "drums":
|
|
assert pitch in {36, 38, 42} # Independently known GM kick/snare/hat.
|
|
else:
|
|
assert 0 <= pitch <= 127
|
|
assert (pitch - root) % 12 in (scale if part == "lead" else {0, 7})
|
|
assert (58 <= pitch <= 80) if part == "lead" else (34 <= pitch <= 53)
|
|
else:
|
|
assert pitch in active and active.pop(pitch) < tick
|
|
assert not active
|
|
assert onsets > 0
|
|
|
|
|
|
def test_precise_independent_bass_events(workspace: Path) -> None:
|
|
path = workspace / "bass.mid"
|
|
generate("bass only 1 bar C major quarter", path)
|
|
assert events(path) == [
|
|
[
|
|
(0, "note_on", 1, 36, 64),
|
|
(960, "note_off", 1, 36, 0),
|
|
(960, "note_on", 1, 43, 96),
|
|
(1920, "note_off", 1, 43, 0),
|
|
(1920, "note_on", 1, 36, 64),
|
|
(2880, "note_off", 1, 36, 0),
|
|
(2880, "note_on", 1, 43, 80),
|
|
(3840, "note_off", 1, 43, 0),
|
|
]
|
|
]
|
|
|
|
|
|
def test_precise_independent_drum_events(workspace: Path) -> None:
|
|
path = workspace / "drums.mid"
|
|
generate("drums only 1 bar quarter", path)
|
|
assert events(path) == [
|
|
[
|
|
(0, "note_on", 9, 36, 64),
|
|
(0, "note_on", 9, 42, 64),
|
|
(240, "note_off", 9, 36, 0),
|
|
(240, "note_off", 9, 42, 0),
|
|
(960, "note_on", 9, 38, 64),
|
|
(960, "note_on", 9, 42, 64),
|
|
(1200, "note_off", 9, 38, 0),
|
|
(1200, "note_off", 9, 42, 0),
|
|
(1920, "note_on", 9, 36, 64),
|
|
(1920, "note_on", 9, 42, 64),
|
|
(2160, "note_off", 9, 36, 0),
|
|
(2160, "note_off", 9, 42, 0),
|
|
(2880, "note_on", 9, 38, 80),
|
|
(2880, "note_on", 9, 42, 80),
|
|
(3120, "note_off", 9, 38, 0),
|
|
(3120, "note_off", 9, 42, 0),
|
|
]
|
|
]
|
|
|
|
|
|
def test_seeded_byte_determinism_and_changed_seed_content(workspace: Path) -> None:
|
|
paths = [workspace / f"seed-{index}.mid" for index in range(3)]
|
|
for path, seed in zip(paths, (123, 123, 124), strict=True):
|
|
generate("lead bass drums 2 bars 7/8 metal sixteenth", path, seed)
|
|
assert paths[0].read_bytes() == paths[1].read_bytes()
|
|
assert events(paths[0]) == events(paths[1])
|
|
assert events(paths[0]) != events(paths[2])
|
|
|
|
|
|
def test_text_changes_measurable_rhythm_and_duration(workspace: Path) -> None:
|
|
descriptions = ("quarter", "eighth", "sixteenth", "eighth rests", "eighth metal")
|
|
counts: list[list[int]] = []
|
|
onsets: list[list[list[int]]] = []
|
|
for index, text in enumerate(descriptions):
|
|
path = workspace / f"rhythm-{index}.mid"
|
|
generate(f"bass drums 1 bar {text}", path)
|
|
actual = events(path)
|
|
starts = [[tick for tick, kind, _, _, _ in track if kind == "note_on"] for track in actual]
|
|
onsets.append(starts)
|
|
counts.append([len(track) for track in starts])
|
|
assert all(sum(msg.time for msg in track) == 3840 for track in mido.MidiFile(path).tracks)
|
|
assert counts == [[4, 8], [8, 12], [16, 20], [7, 11], [8, 16]]
|
|
assert onsets[0][0] == [0, 960, 1920, 2880]
|
|
assert onsets[1][0] == list(range(0, 3840, 480))
|
|
assert onsets[2][0] == list(range(0, 3840, 240))
|
|
assert onsets[3][0] == list(range(0, 3360, 480))
|
|
|
|
|
|
def test_scalar_text_changes_survive_disk_readback(workspace: Path) -> None:
|
|
variants = (
|
|
"bass 1 bar C major quarter",
|
|
"bass 1 bar D minor quarter",
|
|
"bass 1 bar C major quarter 90 bpm",
|
|
"bass 2 bars C major quarter",
|
|
"bass 1 bar C major quarter 3/4",
|
|
)
|
|
paths = [workspace / f"scalar-{index}.mid" for index in range(len(variants))]
|
|
for text, path in zip(variants, paths, strict=True):
|
|
generate(text, path)
|
|
assert events(paths[0]) != events(paths[1]) # Key changes actual pitches.
|
|
assert events(paths[0]) == events(paths[2]) # Tempo changes metadata, not tick positions.
|
|
assert paths[0].read_bytes() != paths[2].read_bytes()
|
|
assert [sum(msg.time for msg in mido.MidiFile(path).tracks[0]) for path in paths] == [
|
|
3840,
|
|
3840,
|
|
3840,
|
|
7680,
|
|
2880,
|
|
]
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"text", ["lead palm mute", "bass palm mute", "drums palm mute", "lead slide", "guitar audio"]
|
|
)
|
|
def test_unsupported_material_fails_before_any_artifact(workspace: Path, text: str) -> None:
|
|
with pytest.raises((UnsupportedArticulationError, UnsupportedDescriptionError)):
|
|
generate(text, workspace / "must-not-exist.mid")
|
|
assert list(workspace.iterdir()) == []
|