Cubase-MCP-GAJ3T.MusicGen.R.../tests/integration/test_explicit_music.py

252 lines
10 KiB
Python

"""Actual original MIDI/griff checks; internal resolver injection is NOT a public parser."""
import hashlib
import json
import shutil
import uuid
import xml.etree.ElementTree as ET
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 CompositionError, compose_score
from riff_groove_builder.description import DescriptionResolution
from riff_groove_builder.errors import NativeFormatUnavailableError, OutputExistsError
from riff_groove_builder.formats.agp import validate_riffer_file
from riff_groove_builder.midi import validate_midi_file
from riff_groove_builder.pitch import parse_chord, parse_pitch, resolve_voicing
from riff_groove_builder.profiles import load_profile_registry
from riff_groove_builder.schemas import (
ExplicitAttack,
ExplicitAttackPlan,
GenerateMusicRequest,
MusicalIntent,
PositiveBeat,
ProfileSelection,
TimeSignature,
)
from riff_groove_builder.service import GenerationService
ROOT = Path(__file__).resolve().parents[2]
pytestmark = pytest.mark.integration
@pytest.fixture
def workspace() -> Iterator[Path]:
path = ROOT / ".test-artifacts" / "step14" / f"rejection-{uuid.uuid4().hex}"
path.mkdir(parents=True)
try:
yield path
finally:
shutil.rmtree(path)
def explicit_intent(
pitches: list[list[int]], assumptions: list[str] | None = None
) -> MusicalIntent:
timings = [
(Fraction(0), Fraction(2, 3), "normal", 0.5),
(Fraction(1), Fraction(1, 3), "palm_mute", 0.25),
(Fraction(4, 3), Fraction(2, 3), "normal", 0.75),
(Fraction(2), Fraction(2), "pinch_harmonic", 1.0),
]
attacks = [
ExplicitAttack.model_validate(
{
"pitches": notes,
"start": {"numerator": start.numerator, "denominator": start.denominator},
"duration": {"numerator": length.numerator, "denominator": length.denominator},
"technique": technique,
"intensity": intensity,
}
)
for notes, (start, length, technique, intensity) in zip(pitches, timings, strict=False)
]
return MusicalIntent(
description="Original internal explicit chord plan.",
parts=["lead"],
tempo_bpm=120,
bars=1,
time_signature=TimeSignature(numerator=4, denominator=4),
key="D minor",
seed=0,
explicit_plan=ExplicitAttackPlan(
part="lead",
duration=PositiveBeat(numerator=4),
attacks=attacks,
assumptions=assumptions or [],
),
)
def inject_intent(monkeypatch: pytest.MonkeyPatch, intent: MusicalIntent) -> None:
assert intent.explicit_plan is not None
resolution = DescriptionResolution(
intent=intent, assumptions=intent.explicit_plan.assumptions, overrides=[]
)
monkeypatch.setattr("riff_groove_builder.service.resolve_description", lambda _: resolution)
def midi_notes(path: Path) -> list[tuple[int, int, int, int]]:
midi = mido.MidiFile(path)
assert (midi.type, midi.ticks_per_beat) == (1, 960)
assert [t.name for t in midi.tracks] == ["Conductor", "Lead"]
assert [sum(m.time for m in t) for t in midi.tracks] == [3840, 3840]
assert not any(m.type in ("control_change", "program_change") for t in midi.tracks for m in t)
active: dict[int, tuple[int, int]] = {}
notes = []
tick = 0
for message in midi.tracks[1]:
tick += message.time
if message.type == "note_on" and message.velocity:
assert message.channel == 0 and message.note not in active
active[message.note] = (tick, message.velocity)
elif message.type == "note_off":
begin, velocity = active.pop(message.note)
notes.append((begin, tick, message.note, velocity))
assert not active
return sorted(notes)
@pytest.mark.parametrize("symbol", ["Em4/B2", "Em4OverB2", "Em4/B", "Em4OverB"])
def test_saved_chords_have_actual_independent_tones_times_and_strings(
monkeypatch: pytest.MonkeyPatch, symbol: str
) -> None:
profiles = load_profile_registry().select(["lead"], ProfileSelection())
profile = profiles["lead"]
slash = resolve_voicing(parse_chord(symbol), profile)
voicings = [
slash.pitches,
resolve_voicing(parse_chord("[C3 E3 G3]"), profile).pitches,
resolve_voicing(parse_chord("F#4"), profile).pitches,
resolve_voicing(parse_pitch("C4"), profile).pitches,
]
intent = explicit_intent([list(v) for v in voicings], list(slash.assumptions))
inject_intent(monkeypatch, intent)
output = ROOT / ".test-artifacts" / "step14" / f"explicit-{uuid.uuid4().hex}"
output.mkdir(parents=True)
service = GenerationService(output)
request = GenerateMusicRequest(
description=intent.description, basename="chords", allow_midi_fallback=False
)
result = service.generate_music(request)
assert result.status == "complete"
assert [a.format for a in result.artifacts] == ["mid", "griff"]
assert all(a.fallback_for == [] for a in result.artifacts)
assert result.resolved.key == "D minor"
if "2" not in symbol:
assert "MIDI59" in "\n".join(result.resolved.assumptions)
bass = 47 if "2" in symbol else 59
expected = sorted(
[(0, 640, pitch, 95) for pitch in (bass, 64, 67, 71)]
+ [(960, 1280, pitch, 32) for pitch in (48, 52, 55)]
+ [(1280, 1920, pitch, 110) for pitch in (66, 70, 73)]
+ [(1920, 3840, 60, 127)]
)
midi_path = Path(result.artifacts[0].path)
native_path = Path(result.artifacts[1].path)
saved = midi_notes(midi_path)
switches = [(0, 30, 24, 100), (960, 990, 26, 100), (1280, 1310, 24, 100), (1920, 1950, 31, 100)]
assert saved == sorted(expected + switches)
assert len(expected) == 11 and len(saved) == 15
native = ET.parse(native_path).getroot()
assert native.tag == "Riff"
assert (native.get("Key"), native.get("PPQBase"), native.get("loopEnd")) == (
"Dm",
"480",
"1920",
)
tuning = {6: 36, 5: 43, 4: 48, 3: 53, 2: 57, 1: 62}
readback: list[tuple[int, int, int, int]] = []
assignments = []
for string in native.findall("String"):
string_id = int(string.attrib["ID"])
occupied_until = 0
for note in string.findall("Note"):
begin, end = int(note.attrib["Begin"]), int(note.attrib["End"])
pitch, fret = int(note.attrib["NoteID"]), int(note.attrib["Fret"])
assert pitch == tuning[string_id] + fret and 0 <= fret <= 22
assert begin >= occupied_until and end > begin
occupied_until = end
assert note.get("Articulation") == {0: "Sus", 480: "PM", 640: "Sus", 960: "PH"}[begin]
assert note.get("Legato") == "No Legato" and note.get("Muted") == "False"
readback.append((begin * 2, end * 2, pitch, int(note.attrib["Velocity"])))
assignments.append((begin, end, pitch, string_id, fret))
assert sorted(readback) == expected
assert len({row[3] for row in assignments if row[0] == 0}) == 4
assert not native.findall("cc-1.Mod")
plan = compile_score(compose_score(intent, profiles), profiles)
assert sum(len(t.events) for t in plan.tracks) == 30
validate_midi_file(midi_path, plan)
assert len(validate_riffer_file(native_path, plan, "lead", profile).notes) == 11
before = {p: p.read_bytes() for p in (midi_path, native_path)}
with pytest.raises(OutputExistsError):
service.generate_music(request)
assert all(p.read_bytes() == data for p, data in before.items())
(output / "evidence.json").write_text(
json.dumps(
{
"symbol": symbol,
"key": "D minor",
"musical_notes": expected,
"keyswitches": switches,
"scheduled_events": 30,
"native_assignments_begin_end_pitch_string_fret": sorted(assignments),
"files": [
{"name": p.name, "bytes": len(data), "sha256": hashlib.sha256(data).hexdigest()}
for p, data in before.items()
],
},
indent=2,
),
encoding="utf-8",
)
@pytest.mark.parametrize("fallback", [True, False])
def test_unassignable_chord_uses_only_existing_truthful_native_fallback(
monkeypatch: pytest.MonkeyPatch, workspace: Path, fallback: bool
) -> None:
intent = explicit_intent([[36, 37, 38]])
inject_intent(monkeypatch, intent)
request = GenerateMusicRequest(
description=intent.description, basename="impossible", allow_midi_fallback=fallback
)
service = GenerationService(workspace)
if fallback:
result = service.generate_music(request)
assert result.status == "midi_fallback"
assert len(result.artifacts) == 1 and result.artifacts[0].format == "mid"
assert result.artifacts[0].fallback_for == ["lead"]
assert any(w.code == "NATIVE_FORMAT_UNAVAILABLE" for w in result.warnings)
saved = midi_notes(Path(result.artifacts[0].path))
assert saved == [(0, 30, 24, 100)] + [(0, 640, p, 95) for p in (36, 37, 38)]
else:
with pytest.raises(NativeFormatUnavailableError) as caught:
service.generate_music(request)
assert caught.value.details["reason"] == "no_physical_string_assignment"
assert list(workspace.iterdir()) == []
@pytest.mark.parametrize("fallback", [True, False])
def test_out_of_map_tones_fail_before_publication_not_fallback(
monkeypatch: pytest.MonkeyPatch, workspace: Path, fallback: bool
) -> None:
intent = explicit_intent([[35, 60, 64]])
inject_intent(monkeypatch, intent)
sentinel = workspace / "accepted.txt"
sentinel.write_bytes(b"accepted")
with pytest.raises(CompositionError):
GenerationService(workspace).generate_music(
GenerateMusicRequest(
description=intent.description, basename="out-of-map", allow_midi_fallback=fallback
)
)
assert sentinel.read_bytes() == b"accepted"
assert list(workspace.iterdir()) == [sentinel]