"""Original authored phrases, exact rational math and strict technique boundaries.""" from fractions import Fraction import pytest from pydantic import ValidationError from riff_groove_builder.articulations import apply_scheduled_controls, compile_score from riff_groove_builder.compose import CompositionError, compose_score from riff_groove_builder.description import DescriptionResolution, resolve_description from riff_groove_builder.errors import ( SerializationError, UnsupportedArticulationError, UnsupportedDescriptionError, ) from riff_groove_builder.profiles import ( InstrumentProfile, InvalidProfileError, KeyswitchAction, load_profile_registry, ) from riff_groove_builder.schemas import ( ControlChangeEvent, GenerateMusicRequest, NoteOnEvent, Part, PhrasePlan, PitchedNote, PositiveBeat, ProfileSelection, RationalBeat, ScheduledControl, TimedNote, TimeSignature, ) ORIGINAL = ( "Please produce a 4/4 riff in Em. With Chugging palm muting 8th notes from 1 to 3&;\n" "and triplets on 4&A with the A as a pinch harmonic that carries over a whole note\n" "in the 2nd measure." ) STARTS = [ Fraction(0), Fraction(1, 2), Fraction(1), Fraction(3, 2), Fraction(2), Fraction(5, 2), Fraction(3), Fraction(10, 3), Fraction(11, 3), ] def resolve(text: str = ORIGINAL, /, **kwargs: object) -> DescriptionResolution: return resolve_description( GenerateMusicRequest.model_validate({"description": text, "basename": "phrase", **kwargs}) ) def test_original_plan_and_disclosed_assumptions() -> None: resolved = resolve() intent = resolved.intent assert (intent.parts, intent.bars, intent.key, intent.tempo_bpm) == ( ["lead"], 2, "E minor", 120, ) phrase = intent.phrase_plan assert phrase is not None assert phrase.duration.value == 8 assert [n.start.value for n in phrase.notes] == STARTS assert [n.duration.value for n in phrase.notes] == [Fraction(1, 2)] * 6 + [ Fraction(1, 3), Fraction(1, 3), Fraction(13, 3), ] assert [n.technique for n in phrase.notes] == ["palm_mute"] * 8 + ["pinch_harmonic"] assumptions = "\n".join(resolved.assumptions) assert "120" in assumptions and "E2/MIDI40" in assumptions assert "A is the final count, not a pitch" in assumptions assert "without retrigger" in assumptions and "bars: omitted; using 2" in assumptions assert intent.techniques == intent.rhythm_terms == [] @pytest.mark.parametrize( "text", [ ORIGINAL.replace("4&A", "4 & A"), ORIGINAL.replace("Em", "E minor"), ORIGINAL.replace("palm muting 8th", "palm-muted eighth"), ORIGINAL.replace("palm muting 8th", "palm mute eighth").replace("2nd", "second"), ORIGINAL.replace("1 to 3&", "2 to 3&"), ORIGINAL.replace("Em", "F#m"), ], ) def test_wording_aliases_and_numeric_range_variant(text: str) -> None: phrase = resolve(text).intent.phrase_plan assert phrase is not None expected = STARTS[2:] if "2 to 3&" in text else STARTS assert [n.start.value for n in phrase.notes] == expected assert phrase.notes[-1].duration.value == Fraction(13, 3) @pytest.mark.parametrize( "text", [ ORIGINAL.replace("1 to 3&", "1 to 4"), ORIGINAL.replace("1 to 3&", "4 to 3"), ORIGINAL.replace("1 to 3&", "0 to 3&"), ORIGINAL.replace("4&A", "5&A"), ORIGINAL.replace("4/4", "3/4"), ORIGINAL.replace("riff", "bass riff"), ORIGINAL + " with legato", ORIGINAL + " then 140 bpm", ORIGINAL + " from 120 bpm to 140 bpm", ORIGINAL + " add a melodic flourish", ORIGINAL + " quarter", ORIGINAL.replace("triplets", "sixteenths"), ORIGINAL.replace("3&", "3&&"), ORIGINAL.replace("3&", "3.5"), ORIGINAL.replace("4&A", "0&A"), ORIGINAL + " triplets on 4&A with the A as a pinch harmonic that carries over " "a whole note in the second measure", ], ) def test_invalid_or_unsupported_prose_is_not_approximated(text: str) -> None: with pytest.raises(UnsupportedDescriptionError): resolve(text) @pytest.mark.parametrize( "overrides", [ {"bars": 1}, {"time_signature": {"numerator": 7, "denominator": 8}}, {"parts": ["bass"]}, {"parts": ["lead", "drums"]}, ], ) def test_scalar_overrides_cannot_erase_phrase_semantics(overrides: dict[str, object]) -> None: with pytest.raises(UnsupportedDescriptionError): resolve(**overrides) def test_exact_composition_and_keyswitches_are_not_musical_notes() -> None: intent = resolve().intent profiles = load_profile_registry().select(intent.parts, ProfileSelection()) score = compose_score(intent, profiles) assert score == compose_score(intent, profiles) assert score.end.value == 8 notes = score.tracks[0].notes assert all(isinstance(n, PitchedNote) and n.pitch == 40 for n in notes) assert [n.start.value for n in notes] == STARTS assert [n.articulation for n in notes] == ["palm_mute"] * 8 + ["pinch_harmonic"] assert notes[-1].start.value + notes[-1].duration.value == 8 plan = compile_score(score, profiles) musical = [ e for e in plan.tracks[0].events if isinstance(e, NoteOnEvent) and e.role == "musical_note" ] switches = [ e for e in plan.tracks[0].events if isinstance(e, NoteOnEvent) and e.role == "keyswitch" ] assert [e.tick for e in musical] == [0, 480, 960, 1440, 1920, 2400, 2880, 3200, 3520] assert [(e.tick, e.note) for e in switches] == [(0, 26), (3520, 31)] assert all(1 <= e.velocity <= 127 for e in musical) assert plan.end_tick == plan.musical_end_tick == 7680 assert all(e.kind != "control_change" for e in plan.tracks[0].events) changed = resolve(seed=12).intent assert compose_score(changed, profiles).tracks != score.tracks def test_reusable_plan_per_note_intensity_and_longer_score() -> None: intent = resolve(bars=3).intent assert intent.phrase_plan is not None intent.phrase_plan.notes[0].intensity = 0.25 profiles = load_profile_registry().select(intent.parts, ProfileSelection()) score = compose_score(intent, profiles) assert score.tracks[0].notes[0].intensity == 0.25 assert score.end.value == 12 assert score.tracks[0].notes[-1].start.value + score.tracks[0].notes[-1].duration.value == 8 with pytest.raises(CompositionError): compose_score(intent.model_copy(update={"bars": 1}), profiles) def test_generic_timing_plan_is_not_a_prompt_specific_template() -> None: intent = resolve().intent.model_copy( update={ "parts": ["bass"], "bars": 1, "time_signature": TimeSignature(numerator=3, denominator=4), "phrase_plan": PhrasePlan( part="bass", duration=PositiveBeat(numerator=3), notes=[ TimedNote( start=RationalBeat(numerator=1, denominator=3), duration=PositiveBeat(numerator=2, denominator=3), technique="normal", intensity=0.25, ), TimedNote( start=RationalBeat(numerator=2), duration=PositiveBeat(numerator=1), technique="palm_mute", intensity=0.75, ), ], ), } ) profiles = load_profile_registry().select(["bass"], ProfileSelection()) score = compose_score(intent, profiles) assert [ (n.start.value, n.duration.value, n.articulation, n.intensity) for n in score.tracks[0].notes ] == [ (Fraction(1, 3), Fraction(2, 3), "normal", 0.25), (Fraction(2), Fraction(1), "palm_mute", 0.75), ] assert compile_score(score, profiles).musical_end_tick == 2880 def test_second_numeric_range_and_triplet_beat_are_computed() -> None: phrase = resolve(ORIGINAL.replace("3&", "2&").replace("4&A", "3 & A")).intent.phrase_plan assert phrase is not None assert [n.start.value for n in phrase.notes] == [ Fraction(0), Fraction(1, 2), Fraction(1), Fraction(3, 2), Fraction(2), Fraction(7, 3), Fraction(8, 3), ] assert phrase.notes[-1].duration.value == Fraction(16, 3) def test_plan_rejects_overlaps_and_nonfinite_intensity() -> None: note = TimedNote( start=RationalBeat(numerator=0), duration=PositiveBeat(numerator=1), technique="normal" ) with pytest.raises(ValidationError): PhrasePlan(part="lead", duration=PositiveBeat(numerator=2), notes=[note, note]) with pytest.raises(ValidationError): TimedNote.model_validate({**note.model_dump(), "intensity": float("nan")}) @pytest.mark.parametrize("part", ["lead", "bass", "drums"]) def test_no_ph_promotion_to_other_maps(part: Part) -> None: registry = load_profile_registry() for profile in registry.select([part], ProfileSelection()).values(): if part != "lead": with pytest.raises(KeyError): profile.resolve_articulation("pinch_harmonic") standard = registry.select(["lead"], ProfileSelection(lead="standard.lead.v1")) with pytest.raises(UnsupportedArticulationError): compose_score(resolve().intent, standard) def test_ph_map_and_native_guard_reject_fabrication() -> None: profile = load_profile_registry().select(["lead"], ProfileSelection())["lead"] art = profile.resolve_articulation("PH") assert art.name == "pinch_harmonic" assert profile.summary.mapping_version == "riffer-subset-2" assert profile.riffer is not None and profile.riffer.articulations["pinch_harmonic"] == "PH" data = profile.model_dump() data["articulations"][-1]["actions"][0]["note"] = 30 with pytest.raises(ValidationError): InstrumentProfile.model_validate(data) invalid = profile.model_copy(deep=True) action = invalid.articulations[-1].actions[0] assert isinstance(action, KeyswitchAction) action.note = 30 with pytest.raises(InvalidProfileError): compose_score(resolve().intent, {"lead": invalid}) def test_phrase_budget_checked_before_allocation(monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr("riff_groove_builder.compose.MAX_SCHEDULED_EVENTS", 17) profiles = load_profile_registry().select(["lead"], ProfileSelection()) with pytest.raises(CompositionError) as error: compose_score(resolve().intent, profiles) assert error.value.details["reason"] == "note_pair_event_budget_exceeded" def test_phrase_budget_includes_keyswitch_events(monkeypatch: pytest.MonkeyPatch) -> None: intent = resolve().intent profiles = load_profile_registry().select(intent.parts, ProfileSelection()) score = compose_score(intent, profiles) monkeypatch.setattr("riff_groove_builder.articulations.MAX_SCHEDULED_EVENTS", 20) with pytest.raises(SerializationError): compile_score(score, profiles) @pytest.mark.parametrize("mutation", ["native_label", "unknown_label", "bass_ph"]) def test_only_evidenced_native_ph_representation_is_permitted(mutation: str) -> None: part: Part = "bass" if mutation == "bass_ph" else "lead" profile = load_profile_registry().select([part], ProfileSelection())[part] data = profile.model_dump() if mutation == "unknown_label": data["riffer"]["articulations"]["pinch_harmonic"] = "PH2" elif mutation == "native_label": data["riffer"]["articulations"]["pinch_harmonic"] = "Sus" else: data["riffer"]["articulations"]["pinch_harmonic"] = "PH" with pytest.raises(ValidationError): InstrumentProfile.model_validate(data) def test_phrase_low_tonic_must_fit_profile_without_clamping() -> None: profile = load_profile_registry().select(["lead"], ProfileSelection(lead="standard.lead.v1"))[ "lead" ] data = profile.model_dump() data["playable_range"] = {"low": 0, "high": 2} with pytest.raises(CompositionError) as error: compose_score(resolve().intent, {"lead": InstrumentProfile.model_validate(data)}) assert error.value.details["reason"] == "range_cannot_fit_low_tonic" def test_explicit_cc_on_held_phrase_is_preserved_not_inferred() -> None: intent = resolve().intent profiles = load_profile_registry().select(intent.parts, ProfileSelection()) base = compile_score(compose_score(intent, profiles), profiles) controls = [ ScheduledControl(part="lead", beat=RationalBeat(numerator=4), controller=1, value=73), ScheduledControl(part="lead", beat=RationalBeat(numerator=5), controller=91, value=64), ] actual = apply_scheduled_controls(base, controls, profiles) assert [e for e in actual.tracks[0].events if not isinstance(e, ControlChangeEvent)] == ( base.tracks[0].events ) assert [ (e.tick, e.controller, e.value) for e in actual.tracks[0].events if isinstance(e, ControlChangeEvent) ] == [(3840, 1, 73), (4800, 91, 64)] assert actual.end_tick == base.end_tick == 7680