267 lines
11 KiB
Python
267 lines
11 KiB
Python
"""Exact timeline, profile facts, local randomness, and bounded resource tests."""
|
|
|
|
from fractions import Fraction
|
|
from pathlib import Path
|
|
from random import getstate
|
|
|
|
import pytest
|
|
|
|
from riff_groove_builder.articulations import compile_score
|
|
from riff_groove_builder.compose import CompositionError, compose_score
|
|
from riff_groove_builder.description import resolve_description
|
|
from riff_groove_builder.errors import SerializationError, UnsupportedArticulationError
|
|
from riff_groove_builder.profiles import InstrumentProfile, load_profile_registry, parse_profile
|
|
from riff_groove_builder.schemas import (
|
|
DrumNote,
|
|
GenerateMusicRequest,
|
|
MusicalIntent,
|
|
Part,
|
|
PitchedNote,
|
|
ProfileSelection,
|
|
)
|
|
|
|
|
|
def intent(text: str = "music", seed: int = 0) -> MusicalIntent:
|
|
return resolve_description(
|
|
GenerateMusicRequest(description=text, basename="compose", seed=seed)
|
|
).intent
|
|
|
|
|
|
def profiles(value: MusicalIntent) -> dict[Part, InstrumentProfile]:
|
|
return load_profile_registry().select(
|
|
value.parts,
|
|
ProfileSelection(
|
|
**{
|
|
part: "standard.gm-drums.v1" if part == "drums" else f"standard.{part}.v1"
|
|
for part in value.parts
|
|
}
|
|
),
|
|
)
|
|
|
|
|
|
@pytest.mark.parametrize("meter", ["3/4", "6/8", "7/8", "1/16", "16/1"])
|
|
@pytest.mark.parametrize("rhythm", ["quarter", "eighth", "sixteenth"])
|
|
def test_exact_meter_end_bar_truncation_and_no_overlap(meter: str, rhythm: str) -> None:
|
|
value = intent(f"lead bass drums 3 bars in {meter} {rhythm}")
|
|
selected = profiles(value)
|
|
score = compose_score(value, selected)
|
|
assert score.start.value == 0
|
|
assert score.end.value == value.duration_beats
|
|
for track in score.tracks:
|
|
previous: dict[int | str, Fraction] = {}
|
|
for note in track.notes:
|
|
end = note.start.value + note.duration.value
|
|
assert end <= value.duration_beats
|
|
bar_index = note.start.value // value.time_signature.beats_per_bar
|
|
assert end <= (bar_index + 1) * value.time_signature.beats_per_bar
|
|
pitch = note.pitch if isinstance(note, PitchedNote) else note.voice
|
|
assert note.start.value >= previous.get(pitch, Fraction(0))
|
|
previous[pitch] = end
|
|
plan = compile_score(score, selected)
|
|
assert plan.musical_start_tick == 0
|
|
assert plan.musical_end_tick == plan.end_tick == value.duration_beats * 960
|
|
|
|
|
|
@pytest.mark.parametrize("text", ["lead", "bass", "drums", "music"])
|
|
def test_seed_reproducibility_variation_and_global_state(text: str) -> None:
|
|
value = intent(text)
|
|
selected = profiles(value)
|
|
state = getstate()
|
|
score = compose_score(value, selected)
|
|
assert score == compose_score(value, selected)
|
|
assert state == getstate()
|
|
changed = compose_score(intent(text, seed=10), selected)
|
|
assert score.tracks != changed.tracks
|
|
assert state == getstate()
|
|
|
|
|
|
@pytest.mark.parametrize("key", ["C major", "F# minor", "Bb major", "Eb minor", "Cb major"])
|
|
def test_independent_scale_classes_and_registers(key: str) -> None:
|
|
value = intent(f"lead bass 4 bars {key}")
|
|
score = compose_score(value, profiles(value))
|
|
roots = {"C": 0, "F#": 6, "A#": 10, "D#": 3, "B": 11}
|
|
name, mode = value.key.split()
|
|
root = roots[name]
|
|
scale = {0, 2, 4, 5, 7, 9, 11} if mode == "major" else {0, 2, 3, 5, 7, 8, 10}
|
|
for track in score.tracks:
|
|
for note in track.notes:
|
|
assert isinstance(note, PitchedNote)
|
|
assert (note.pitch - root) % 12 in scale
|
|
if track.part == "bass":
|
|
assert (note.pitch - root) % 12 in {0, 7}
|
|
assert 34 <= note.pitch <= 53
|
|
else:
|
|
assert 58 <= note.pitch <= 80
|
|
|
|
|
|
def test_requested_subdivision_rests_and_template_change_real_notes() -> None:
|
|
values = [
|
|
intent(f"bass drums 1 bar {term}")
|
|
for term in ("quarter", "eighth", "sixteenth", "eighth rests", "eighth metal")
|
|
]
|
|
scores = [compose_score(value, profiles(value)) for value in values]
|
|
assert [len(score.tracks[0].notes) for score in scores] == [4, 8, 16, 7, 8]
|
|
assert [len(score.tracks[1].notes) for score in scores] == [8, 12, 20, 11, 16]
|
|
assert scores[1].tracks[0].notes != scores[4].tracks[0].notes
|
|
assert all(score.end.value == 4 for score in scores)
|
|
assert all(
|
|
note.start.value < Fraction(7, 2) for track in scores[3].tracks for note in track.notes
|
|
)
|
|
|
|
|
|
def test_partial_slot_and_all_rest_bar_policy() -> None:
|
|
value = intent("bass 1 bar in 7/8 quarter")
|
|
notes = compose_score(value, profiles(value)).tracks[0].notes
|
|
assert [note.duration.value for note in notes] == [1, 1, 1, Fraction(1, 2)]
|
|
value = intent("music 2 bars 1/16 quarter rests")
|
|
score = compose_score(value, profiles(value))
|
|
assert all(track.notes == [] for track in score.tracks)
|
|
assert compile_score(score, profiles(value)).end_tick == 480
|
|
|
|
|
|
@pytest.mark.parametrize("technique", ["normal", "sustain"])
|
|
def test_standard_supported_techniques(technique: str) -> None:
|
|
value = intent(f"lead bass drums {technique}")
|
|
score = compose_score(value, profiles(value))
|
|
assert {note.articulation for track in score.tracks for note in track.notes} == {"normal"}
|
|
assert compile_score(score, profiles(value)).musical_start_tick == 0
|
|
|
|
|
|
@pytest.mark.parametrize("part", ["lead", "bass", "drums"])
|
|
def test_standard_palm_mute_fails_without_approximation(part: str) -> None:
|
|
value = intent(f"{part} palm mute")
|
|
with pytest.raises(UnsupportedArticulationError) as caught:
|
|
compose_score(value, profiles(value))
|
|
assert caught.value.details["technique"] == "palm_mute"
|
|
assert caught.value.details["part"] == part
|
|
|
|
|
|
def test_synthetic_switch_profile_uses_real_compiler_not_vendor_claims() -> None:
|
|
path = Path(__file__).resolve().parents[1] / "fixtures" / "profiles" / "synthetic-lead.json"
|
|
profile = parse_profile(path.read_bytes())
|
|
value = intent("lead palm mute 1 bar quarter")
|
|
score = compose_score(value, {"lead": profile})
|
|
plan = compile_score(score, {"lead": profile})
|
|
assert profile.provenance.status == "test_only"
|
|
assert any(event.role == "keyswitch" for event in plan.tracks[0].events)
|
|
assert plan.musical_start_tick > 0
|
|
|
|
|
|
@pytest.mark.parametrize(("part", "low", "high"), [("lead", 0, 10), ("bass", 100, 105)])
|
|
def test_narrow_maps_fail_instead_of_clamping(part: Part, low: int, high: int) -> None:
|
|
value = intent(f"{part} C major")
|
|
selected = profiles(value)
|
|
data = selected[part].model_dump()
|
|
data["playable_range"] = {"low": low, "high": high}
|
|
selected[part] = InstrumentProfile.model_validate(data)
|
|
with pytest.raises(CompositionError, match="intent cannot be composed") as caught:
|
|
compose_score(value, selected)
|
|
assert caught.value.details["reason"] == "range_cannot_fit_root_fifth_or_complete_lead_scale"
|
|
|
|
|
|
def test_nonpreferred_but_viable_range_is_respected() -> None:
|
|
value = intent("lead C major")
|
|
selected = profiles(value)
|
|
data = selected["lead"].model_dump()
|
|
data["playable_range"] = {"low": 84, "high": 95}
|
|
selected["lead"] = InstrumentProfile.model_validate(data)
|
|
score = compose_score(value, selected)
|
|
assert all(
|
|
isinstance(note, PitchedNote) and 84 <= note.pitch <= 95 for note in score.tracks[0].notes
|
|
)
|
|
|
|
|
|
def test_drum_alias_required_and_physical_notes_never_guessed() -> None:
|
|
value = intent("drums")
|
|
selected = profiles(value)
|
|
data = selected["drums"].model_dump()
|
|
for voice in data["drum_voices"]:
|
|
if "snare" in voice["aliases"]:
|
|
voice["aliases"].remove("snare")
|
|
selected["drums"] = InstrumentProfile.model_validate(data)
|
|
with pytest.raises(CompositionError) as caught:
|
|
compose_score(value, selected)
|
|
assert caught.value.details["voice"] == "snare"
|
|
data = profiles(value)["drums"].model_dump()
|
|
for voice in data["drum_voices"]:
|
|
voice["note"] += 1
|
|
selected["drums"] = InstrumentProfile.model_validate(data)
|
|
score = compose_score(value, selected)
|
|
assert {note.voice for note in score.tracks[0].notes if isinstance(note, DrumNote)} == {
|
|
"kick",
|
|
"snare",
|
|
"closed_hat",
|
|
}
|
|
plan = compile_score(score, selected)
|
|
assert {event.note for event in plan.tracks[0].events if hasattr(event, "note")} == {37, 39, 43}
|
|
|
|
|
|
def test_unrepresentable_grid_fails_without_rounding() -> None:
|
|
value = intent("lead eighth")
|
|
with pytest.raises(SerializationError) as caught:
|
|
compose_score(value, profiles(value), ppq=3)
|
|
assert caught.value.details["reason"] == "off_grid_beats"
|
|
compose_score(intent("bass quarter"), profiles(intent("bass")), ppq=3)
|
|
|
|
|
|
def test_event_budget_precedes_note_construction(monkeypatch: pytest.MonkeyPatch) -> None:
|
|
value = intent("lead bass drums 256 bars in 16/1 sixteenth")
|
|
|
|
def forbidden(*args: object, **kwargs: object) -> None:
|
|
pytest.fail("note allocation must not begin")
|
|
|
|
monkeypatch.setattr("riff_groove_builder.compose.PitchedNote", forbidden)
|
|
monkeypatch.setattr("riff_groove_builder.compose.DrumNote", forbidden)
|
|
with pytest.raises(CompositionError) as caught:
|
|
compose_score(value, profiles(value))
|
|
assert caught.value.details["reason"] == "note_pair_event_budget_exceeded"
|
|
|
|
|
|
@pytest.mark.parametrize("terms", [["swing"], ["quarter", "eighth"], ["rests", "no_rests"]])
|
|
def test_direct_intent_cannot_smuggle_unsupported_rhythm(terms: list[str]) -> None:
|
|
value = intent("lead")
|
|
value.rhythm_terms = terms
|
|
with pytest.raises(CompositionError):
|
|
compose_score(value, profiles(value))
|
|
|
|
|
|
def test_direct_intent_technique_and_profile_validation() -> None:
|
|
value = intent("lead")
|
|
with pytest.raises(CompositionError):
|
|
compose_score(value, {})
|
|
value.techniques = ["normal", "slide"]
|
|
with pytest.raises(UnsupportedArticulationError):
|
|
compose_score(value, profiles(value))
|
|
value.bars = 0
|
|
with pytest.raises(CompositionError):
|
|
compose_score(value, profiles(intent("lead")))
|
|
|
|
|
|
def test_structured_part_order_and_unrelated_part_seed_independence() -> None:
|
|
request = GenerateMusicRequest(
|
|
description="music", basename="order", parts=["drums", "bass", "lead"], seed=77
|
|
)
|
|
value = resolve_description(request).intent
|
|
score = compose_score(value, profiles(value))
|
|
assert [track.part for track in score.tracks] == ["drums", "bass", "lead"]
|
|
for track in score.tracks:
|
|
solo = intent(track.part, seed=77)
|
|
assert compose_score(solo, profiles(solo)).tracks[0].notes == track.notes
|
|
|
|
|
|
def test_wrong_part_shared_channel_and_mutated_profile_rejected() -> None:
|
|
value = intent("lead bass")
|
|
selected = profiles(value)
|
|
with pytest.raises(CompositionError) as caught:
|
|
compose_score(value, {"lead": selected["bass"], "bass": selected["lead"]})
|
|
assert caught.value.details["reason"] == "profile_part_mismatch"
|
|
selected["bass"].channel = selected["lead"].channel
|
|
with pytest.raises(CompositionError) as caught:
|
|
compose_score(value, selected)
|
|
assert caught.value.details["reason"] == "shared_channel"
|
|
selected = profiles(value)
|
|
assert selected["lead"].playable_range is not None
|
|
selected["lead"].playable_range.low = 128
|
|
with pytest.raises(SerializationError):
|
|
compose_score(value, selected)
|