"""Real MIDI and wheel checks of synthetic mechanics and standard fallback, not vendors.""" import json import os import shutil import subprocess import sys 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 ArticulationCompileError, compile_score from riff_groove_builder.errors import UnsupportedArticulationError from riff_groove_builder.midi import validate_midi_file, write_midi from riff_groove_builder.profiles import load_profile_registry, parse_profile from riff_groove_builder.schemas import ( ControlChangeEvent, DrumNote, EventPlan, MusicalIntent, Part, PitchedNote, PositiveBeat, ProfileSelection, RationalBeat, Score, ScoreTrack, TimeSignature, ) ROOT = Path(__file__).resolve().parents[2] FIXTURES = ROOT / "tests" / "fixtures" / "profiles" pytestmark = pytest.mark.integration Event = tuple[int, str, int, int] @pytest.fixture def workspace() -> Iterator[Path]: path = ROOT / ".test-artifacts" / f"articulation-{uuid.uuid4().hex}" path.mkdir(parents=True) try: yield path finally: shutil.rmtree(path) def ratio(value: Fraction | int) -> RationalBeat: value = Fraction(value) return RationalBeat(numerator=value.numerator, denominator=value.denominator) def synthetic_score() -> Score: # Explicit independent score, common logical origin 2; no compiler helpers. def pitched( part: Part, start: Fraction | int, length: Fraction | int, pitch: int, articulation: str, intensity: float = 0.5, ) -> PitchedNote: assert part in ("lead", "bass") return PitchedNote( part=part, start=ratio(start), duration=PositiveBeat.model_validate(ratio(length).model_dump()), pitch=pitch, articulation=articulation, intensity=intensity, ) def drum( start: Fraction | int, length: Fraction | int, voice: str, art: str, intensity: float, ) -> DrumNote: return DrumNote( part="drums", start=ratio(start), duration=PositiveBeat.model_validate(ratio(length).model_dump()), voice=voice, articulation=art, intensity=intensity, ) return Score( intent=MusicalIntent( description="SYNTHETIC three-part articulated test", parts=["lead", "bass", "drums"], tempo_bpm=120, bars=1, time_signature=TimeSignature(numerator=4, denominator=4), key="C major", seed=0, ), start=ratio(2), end=ratio(6), tracks=[ ScoreTrack( part="lead", notes=[ pitched("lead", 2, 1, 60, "Palm Mute"), pitched("lead", Fraction(5, 2), 1, 64, "pm", 1), pitched("lead", 4, 1, 60, "normal"), pitched("lead", 5, 1, 60, "sustain"), ], ), ScoreTrack( part="bass", notes=[ pitched("bass", 2, Fraction(1, 2), 40, "normal"), pitched("bass", 3, Fraction(1, 2), 43, "slide"), pitched("bass", Fraction(13, 4), Fraction(3, 4), 45, "slide"), pitched("bass", Fraction(17, 4), Fraction(7, 4), 40, "normal"), ], ), ScoreTrack( part="drums", notes=[ drum(2, Fraction(1, 2), "low", "accent", 0.5), drum(Fraction(9, 4), Fraction(1, 2), "high_hit", "hard hit", 1), drum(3, 1, "low_hit", "normal", 0), drum(Fraction(11, 2), Fraction(1, 2), "high", "accent", 0), ], ), ], ) def expected() -> list[list[Event]]: # Hand-derived absolute ticks/payloads; never iterate production events to build expectations. return [ [ (0, "note_on", 2, 64), (0, "control_change", 20, 64), (60, "note_off", 2, 0), (120, "note_on", 60, 80), (600, "note_on", 64, 100), (1080, "note_off", 60, 0), (1560, "note_off", 64, 0), (1920, "note_on", 1, 64), (1920, "control_change", 20, 0), (1980, "note_off", 1, 0), (2040, "note_on", 60, 64), (3000, "note_off", 60, 0), (3000, "note_on", 60, 64), (3960, "note_off", 60, 0), ], [ (120, "note_on", 3, 60), (120, "control_change", 21, 0), (120, "note_on", 40, 60), (180, "note_off", 3, 0), (600, "note_off", 40, 0), (960, "note_on", 4, 60), (960, "control_change", 21, 90), (1080, "note_on", 43, 60), (1200, "control_change", 21, 90), (1320, "note_on", 45, 60), (1560, "note_off", 43, 0), (2040, "note_off", 45, 0), (2100, "note_off", 4, 0), (2100, "control_change", 21, 0), (2100, "note_on", 3, 60), (2100, "control_change", 21, 0), (2160, "note_off", 3, 0), (2280, "note_on", 40, 60), (3960, "note_off", 40, 0), ], [ (120, "control_change", 22, 0), (120, "control_change", 22, 100), (120, "note_on", 36, 100), (360, "control_change", 22, 100), (360, "note_on", 40, 120), (600, "note_off", 36, 0), (840, "note_off", 40, 0), (900, "control_change", 22, 0), (900, "control_change", 22, 0), (1080, "note_on", 36, 1), (2040, "note_off", 36, 0), (3480, "control_change", 22, 100), (3480, "note_on", 40, 80), (3960, "note_off", 40, 0), (4020, "control_change", 22, 0), (4020, "control_change", 22, 0), ], ] def compiled() -> EventPlan: return compile_score( synthetic_score(), { part: parse_profile((FIXTURES / f"synthetic-{part}.json").read_bytes()) for part in synthetic_score().intent.parts }, ) def test_three_part_exact_events_saved_readback_and_shared_tail(workspace: Path) -> None: plan = compiled() assert (plan.musical_start_tick, plan.musical_end_tick, plan.end_tick) == (120, 3960, 4020) for track, independent in zip(plan.tracks, expected(), strict=True): observed = [ ( e.tick, e.kind, e.controller if isinstance(e, ControlChangeEvent) else e.note, e.value if isinstance(e, ControlChangeEvent) else e.velocity, ) for e in track.events ] assert observed == independent path = write_midi(workspace / "synthetic.mid", plan) validate_midi_file(path, plan) midi = mido.MidiFile(path) assert midi.type == 1 and midi.ticks_per_beat == 960 and len(midi.tracks) == 4 for track, independent, channel in zip(midi.tracks[1:], expected(), [2, 5, 12], strict=True): tick = 0 events: list[Event] = [] active: dict[int, int] = {} for message in track: tick += message.time if message.is_meta: continue assert message.channel == channel if message.type == "control_change": events.append((tick, message.type, message.control, message.value)) else: events.append((tick, message.type, message.note, message.velocity)) if message.type == "note_on": assert message.note not in active active[message.note] = tick else: assert tick > active.pop(message.note) assert events == independent assert active == {} and tick == 4020 assert track[-1].type == "end_of_track" assert sum(m.time for m in midi.tracks[0]) == 4020 assert midi.tracks[0][1].tempo == 500000 other = write_midi(workspace / "repeat.mid", compiled()) assert other.read_bytes() == path.read_bytes() def test_shared_channels_rejected_including_empty_selected_parts() -> None: source = synthetic_score() selected = { part: parse_profile((FIXTURES / f"synthetic-{part}.json").read_bytes()) for part in source.intent.parts } source.tracks[1].notes = [] selected["bass"].channel = selected["lead"].channel with pytest.raises(ArticulationCompileError) as error: compile_score(source, selected) assert error.value.details["reason"] == "shared_channel" def test_unsupported_voice_never_guesses_gm_map() -> None: source = synthetic_score() drum = source.tracks[2].notes[0] assert isinstance(drum, DrumNote) drum.voice = "acoustic_bass_drum" with pytest.raises(ArticulationCompileError) as error: compile_score( source, { part: parse_profile((FIXTURES / f"synthetic-{part}.json").read_bytes()) for part in source.intent.parts }, ) assert error.value.details["reason"] == "unsupported_drum_voice" def standard_score() -> Score: return Score( intent=MusicalIntent( description="Standard MIDI fallback, no verified vendor mapping", parts=["lead", "bass", "drums"], tempo_bpm=120, bars=1, time_signature=TimeSignature(numerator=4, denominator=4), key="C major", seed=0, ), start=ratio(0), end=ratio(4), tracks=[ ScoreTrack( part="lead", notes=[ PitchedNote( part="lead", start=ratio(0), duration=PositiveBeat(numerator=1), pitch=0, articulation="normal", intensity=0, ), PitchedNote( part="lead", start=ratio(1), duration=PositiveBeat(numerator=1), pitch=127, articulation="sustain", intensity=1, ), ], ), ScoreTrack( part="bass", notes=[ PitchedNote( part="bass", start=ratio(0), duration=PositiveBeat(numerator=2), pitch=40, articulation="sustain", intensity=0.5, ), ], ), ScoreTrack( part="drums", notes=[ DrumNote( part="drums", start=ratio(0), duration=PositiveBeat(numerator=1), voice="kick", articulation="normal", intensity=0.25, ), DrumNote( part="drums", start=ratio(1), duration=PositiveBeat(numerator=1), voice="snare", articulation="sustain", intensity=0.75, ), DrumNote( part="drums", start=ratio(2), duration=PositiveBeat(numerator=1), voice="closed_hat", articulation="normal", intensity=0.5, ), ], ), ], ) def test_standard_fallback_compiles_and_roundtrips_real_midi(workspace: Path) -> None: score = standard_score() profiles = load_profile_registry().select( score.intent.parts, ProfileSelection( lead="standard.lead.v1", bass="standard.bass.v1", drums="standard.gm-drums.v1" ), ) plan = compile_score(score, profiles) assert plan == compile_score(score, profiles) assert (plan.musical_start_tick, plan.musical_end_tick, plan.end_tick) == (0, 3840, 3840) independent: list[list[Event]] = [ [ (0, "note_on", 0, 1), (960, "note_off", 0, 0), (960, "note_on", 127, 127), (1920, "note_off", 127, 0), ], [(0, "note_on", 40, 64), (1920, "note_off", 40, 0)], [ (0, "note_on", 36, 32), (960, "note_off", 36, 0), (960, "note_on", 38, 96), (1920, "note_off", 38, 0), (1920, "note_on", 42, 64), (2880, "note_off", 42, 0), ], ] assert [{event.channel for event in track.events} for track in plan.tracks] == [{0}, {1}, {9}] for track, expected_events in zip(plan.tracks, independent, strict=True): assert all(e.role == "musical_note" for e in track.events) assert [ (e.tick, e.kind, e.note, e.velocity) for e in track.events if not isinstance(e, ControlChangeEvent) ] == expected_events path = write_midi(workspace / "standard-fallback.mid", plan) validate_midi_file(path, plan) midi = mido.MidiFile(path) assert midi.type == 1 and midi.ticks_per_beat == 960 and len(midi.tracks) == 4 assert [m.tempo for m in midi.tracks[0] if m.type == "set_tempo"] == [500000] assert [(m.numerator, m.denominator) for m in midi.tracks[0] if m.type == "time_signature"] == [ (4, 4) ] for track, channel, expected_events in zip( midi.tracks[1:], [0, 1, 9], independent, strict=True ): tick = 0 events: list[Event] = [] for message in track: tick += message.time if not message.is_meta: assert message.type in ("note_on", "note_off") assert message.channel == channel events.append((tick, message.type, message.note, message.velocity)) assert events == expected_events assert tick == 3840 and track[-1].type == "end_of_track" @pytest.mark.parametrize( ("part", "technique"), [("lead", "palm_mute"), ("bass", "slide"), ("drums", "accent")] ) def test_standard_fallback_rejects_unsupported_techniques(part: Part, technique: str) -> None: score = standard_score() track = next(track for track in score.tracks if track.part == part) track.notes[0].articulation = technique profiles = load_profile_registry().select( score.intent.parts, ProfileSelection( lead="standard.lead.v1", bass="standard.bass.v1", drums="standard.gm-drums.v1" ), ) with pytest.raises(UnsupportedArticulationError) as error: compile_score(score, profiles) assert error.value.code == "UNSUPPORTED_ARTICULATION" assert "verified profile" not in error.value.public_message def test_standard_fallback_rejects_unknown_voice() -> None: score = standard_score() note = score.tracks[2].notes[0] assert isinstance(note, DrumNote) note.voice = "sd3_custom_voice" profiles = load_profile_registry().select( score.intent.parts, ProfileSelection( lead="standard.lead.v1", bass="standard.bass.v1", drums="standard.gm-drums.v1" ), ) with pytest.raises(ArticulationCompileError) as error: compile_score(score, profiles) assert error.value.details["reason"] == "unsupported_drum_voice" def test_built_wheel_standard_registry_installed_and_zip_resources_outside_repo( workspace: Path, ) -> None: scratch = workspace / "scratch" scratch.mkdir() env = os.environ.copy() for name in ("PYTHONPATH", "PYTHONHOME"): env.pop(name, None) env.update( { "TEMP": str(scratch), "TMP": str(scratch), "TMPDIR": str(scratch), "PIP_NO_INDEX": "1", "PIP_NO_CACHE_DIR": "1", "PYTHONDONTWRITEBYTECODE": "1", "PIP_DISABLE_PIP_VERSION_CHECK": "1", } ) def run(args: list[str], *, outside: bool = False) -> str: result = subprocess.run( [sys.executable, "-I", "-B", *args], cwd=ROOT.parent if outside else ROOT, env=env, capture_output=True, text=True, timeout=180, check=False, ) assert result.returncode == 0, result.stdout + result.stderr return result.stdout # Build the wheel from the sdist so build intermediates stay in this workspace. run(["-m", "build", "--no-isolation", "--outdir", str(workspace / "dist")]) wheel = next((workspace / "dist").glob("*.whl")) installed = workspace / "installed" run( [ "-m", "pip", "install", "--no-deps", "--no-index", "--no-cache-dir", "--target", str(installed), str(wheel), ] ) probe = """ import json import pathlib import sys sys.path.insert(0, sys.argv[1]) import riff_groove_builder.profiles as profiles from importlib.resources import files from riff_groove_builder.data.profiles import PROFILE_RESOURCES from riff_groove_builder.schemas import ProfileListResult, ProfileSelection assert str(profiles.__file__).startswith(sys.argv[1]) assert set(PROFILE_RESOURCES) == { "standard-midi-lead-v1.json", "standard-midi-bass-v1.json", "general-midi-percussion-v1.json", "ample-metal-eclipse-4.0.1-riffer-v1.json", "ample-metal-ray5-4.1.0-riffer-v1.json", "toontrack-sd3-3.4.4-core-v1.json", } root = files("riff_groove_builder.data.profiles") assert root.joinpath("__init__.py").is_file() assert {p.name for p in root.iterdir() if p.name.endswith(".json")} == set(PROFILE_RESOURCES) registry = profiles.load_profile_registry() summaries = registry.summaries() assert [p.id for p in summaries] == [ "ample.ame.4.0.1.riffer.v1", "ample.amr.4.1.0.riffer.v1", "standard.bass.v1", "standard.gm-drums.v1", "standard.lead.v1", "toontrack.sd3.3.4.4.core.v1" ] assert ProfileListResult(profiles=summaries).profiles == summaries defaults = registry.select(["lead", "bass", "drums"], ProfileSelection()) assert all(p.default and p.provenance.status == "verified_subset" for p in defaults.values()) selected = registry.select(["lead", "bass", "drums"], ProfileSelection( lead="standard.lead.v1", bass="standard.bass.v1", drums="standard.gm-drums.v1" )) assert {part: p.channel for part, p in selected.items()} == {"lead": 0, "bass": 1, "drums": 9} for p in selected.values(): assert p.summary.mapping_kind == p.provenance.status == "standard_midi" assert not p.default and not p.summary.native_available assert "NOT a verified" in p.summary.product_name assert not p.id.startswith("test.") and not p.summary.product_name.startswith("SYNTHETIC") assert p.summary.supported_articulations == ["normal"] assert p.resolve_articulation("sustain").actions == [] assert selected["drums"].resolve_voice("kick") == 36 assert selected["drums"].resolve_voice("snare") == 38 assert selected["drums"].resolve_voice("closed_hat") == 42 print(json.dumps({"module": str(profiles.__file__), "cwd": str(pathlib.Path.cwd()), "profiles": [p.id for p in summaries], "isolated": sys.flags.isolated})) """ for location in [installed, wheel]: evidence = json.loads(run(["-c", probe, str(location)], outside=True)) assert evidence["profiles"] == [ "ample.ame.4.0.1.riffer.v1", "ample.amr.4.1.0.riffer.v1", "standard.bass.v1", "standard.gm-drums.v1", "standard.lead.v1", "toontrack.sd3.3.4.4.core.v1", ] assert evidence["isolated"] == 1 assert Path(evidence["cwd"]) == ROOT.parent print(f"Wheel profile-resource evidence: {evidence}")