"""Public generic hybrid parser: exact grids, preserved pitches and honest failures.""" import re from fractions import Fraction import pytest from pydantic import ValidationError 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 DomainError, UnsupportedDescriptionError from riff_groove_builder.hybrid import count_grid, materialize from riff_groove_builder.profiles import load_profile_registry from riff_groove_builder.schemas import ( ExplicitAttackPlan, GenerateMusicRequest, MusicalIntent, ProfileSelection, TimeSignature, ) CANONICAL = """Lead guitar, 4/4, 120 BPM, 2 bars. Bar 1: Counts: 1 & 2 & 3 & [4 trip let] Events: x x x x x x [x x ^] Chords: F#2 F#2 D3 D3 Bb2 Bb2 - - - Notes: - - - - - - C4 E4 G4 Hold the final G4 through the end of bar 2 without retriggering.""" ORIGINAL_LANES = """Lead guitar, E minor, 4/4, 120 BPM, 2 bars. Bar 1: Counts: 1& 2& 3& [4 trip let] Events: xx xx xx xx^ Notes: E2E2 E2E2 E2E2 E2E2E2 Hold the final E2 through the end of bar 2 without retriggering.""" def resolve(text: str, **overrides: object) -> MusicalIntent: request = GenerateMusicRequest.model_validate( {"description": text, "basename": "hybrid", **overrides} ) intent = resolve_description(request).intent profiles = load_profile_registry().select(intent.parts, request.profiles or ProfileSelection()) return materialize(intent, profiles) def plan(text: str, **overrides: object) -> ExplicitAttackPlan: result = resolve(text, **overrides).explicit_plan assert result is not None return result def lane( counts: str = "1 & 2 & 3 & 4 &", events: str = "oooooooo", notes: str = "E2E2E2E2E2E2E2E2", context: str = "guitar, 4/4, 1 bar", ) -> str: return f"{context}\nCounts: {counts}\nEvents: {events}\nNotes: {notes}" def test_corrected_canonical_exact_expanded_attacks() -> None: result = plan(CANONICAL) assert [a.pitches for a in result.attacks] == [ [42, 46, 49], [42, 46, 49], [50, 54, 57], [50, 54, 57], [46, 50, 53], [46, 50, 53], [60], [64], [67], ] assert [a.start.value * 960 for a in result.attacks] == [ 0, 480, 960, 1440, 1920, 2400, 2880, 3200, 3520, ] assert [a.duration.value * 960 for a in result.attacks] == [480] * 6 + [320, 320, 4160] assert [a.technique for a in result.attacks] == ["palm_mute"] * 8 + ["pinch_harmonic"] assert sum(len(a.pitches) for a in result.attacks) == 21 @pytest.mark.parametrize( "mutate", [ lambda s: ( s.replace("Counts:", "cOuNtS:") .replace("Events:", "EVENTS:") .replace("Notes:", "notes:") ), lambda s: s.replace(" ", "\t"), lambda s: ( s.replace("x x x x x x [x x ^]", "xxxxxx[xx^]") .replace("F#2 F#2 D3 D3 Bb2 Bb2 - - -", "F#2F#2 D3D3 Bb2Bb2 ---") .replace("- - - - - - C4 E4 G4", "-- -- -- [C4E4G4]") ), ], ) def test_width_case_compact_invariance(mutate: object) -> None: assert callable(mutate) assert plan(mutate(CANONICAL)).attacks == plan(CANONICAL).attacks @pytest.mark.parametrize( ("counts", "grid", "offsets", "lengths"), [ ("1", None, [0], [1]), ("1&", None, [0, Fraction(1, 2)], [Fraction(1, 2)] * 2), ( "1 E & A", None, [0, Fraction(1, 4), Fraction(1, 2), Fraction(3, 4)], [Fraction(1, 4)] * 4, ), ("[1 trip let]", None, [0, Fraction(1, 3), Fraction(2, 3)], [Fraction(1, 3)] * 3), ("1&a", "triplets", [0, Fraction(1, 3), Fraction(2, 3)], [Fraction(1, 3)] * 3), ( "1&a", "sixteenths", [0, Fraction(1, 2), Fraction(3, 4)], [Fraction(1, 2), Fraction(1, 4), Fraction(1, 4)], ), ], ) @pytest.mark.parametrize("denominator", [2, 4, 8, 16]) def test_reusable_denominator_count_math( counts: str, grid: str | None, offsets: list[Fraction], lengths: list[Fraction], denominator: int, ) -> None: unit = Fraction(4, denominator) assert count_grid( counts, TimeSignature.model_validate({"numerator": 3, "denominator": denominator}), grid ) == [ (Fraction(start) * unit, Fraction(length) * unit) for start, length in zip(offsets, lengths, strict=True) ] @pytest.mark.parametrize("directive", ["Grid", "Subdivision"]) @pytest.mark.parametrize( ("grid", "counts", "size"), [ ("eighths", "1&", 2), ("sixteenths", "1e&a", 4), ("eighth-triplets", "1&a", 3), ], ) def test_public_grid_directives(directive: str, grid: str, counts: str, size: int) -> None: assert ( len(plan(lane(counts, "o" * size, "E2" * size) + f"\n{directive}: {grid}").attacks) == size ) def test_three_four_and_second_explicit_bar() -> None: text = lane("1& 2& 3&", "oooooo", "E2" * 6, "bass, 3/4, two bars") text += "\nBar 2:\nCounts: 1 2 3\nEvents: ooo\nNotes: A2B2C3" result = plan(text) assert [a.start.value for a in result.attacks][-3:] == [3, 4, 5] assert result.part == "bass" and result.duration.value == 6 def test_bar_boundaries_and_empty_lane_vs_global_rest() -> None: result = plan( "guitar, 2 bars\nCounts: 1 2 | 1 2\nEvents: o- | oo\nNotes: E2- | -G3\nChords: -- | D3-" ) assert [a.pitches for a in result.attacks] == [[40], [50, 54, 57], [55]] assert [a.start.value for a in result.attacks] == [0, 4, 5] @pytest.mark.parametrize( "continuation", [ "\nBar 2: hold previous note to bar end", "\nBar 2:\nCounts: 1 2 3 4\nEvents: ~~~~\nNotes: ----", ], ) def test_continuation_matches_prose_tie(continuation: str) -> None: tied = ORIGINAL_LANES[: ORIGINAL_LANES.index("Hold")] + continuation assert plan(tied).attacks == plan(ORIGINAL_LANES).attacks @pytest.mark.parametrize( ("symbol", "expected"), [ ("Em4OverB2", [47, 64, 67, 71]), ("Em4/B2", [47, 64, 67, 71]), ("Em4/B", [59, 64, 67, 71]), ("Em4OverB", [59, 64, 67, 71]), ("[C3 E3 G3]", [48, 52, 55]), ("Em4(add4)", [64, 67, 69, 71]), ("D3", [50, 54, 57]), ("D2", [38, 42, 45]), ("F#4", [66, 70, 73]), ("Bb2", [46, 50, 53]), ("F#", [42, 46, 49]), ], ) def test_public_chord_resolution_no_key_retune(symbol: str, expected: list[int]) -> None: result = plan(f"guitar, D minor, 1 bar\nCounts: 1\nEvents: o\nChords: {symbol}") assert result.attacks[0].pitches == expected if symbol in ("F#", "Em4/B", "Em4OverB"): assert "MIDI" in "\n".join(result.assumptions) def test_original_seed_and_compiler_controls_unchanged() -> None: intent = resolve(ORIGINAL_LANES) profiles = load_profile_registry().select(intent.parts, ProfileSelection()) compiled = compile_score(compose_score(intent, profiles), profiles) musical = [e for t in compiled.tracks for e in t.events if e.kind == "note_on" and e.note == 40] assert len(musical) == 9 @pytest.mark.parametrize( "text", [ lane("1&a", "ooo", "E2" * 3), lane("1&", "o", "E2E2"), lane("1&", "oo", "E2"), lane("2 1", "oo", "E2E2"), lane("1 1", "oo", "E2E2"), lane("0", "o", "E2"), lane("5", "o", "E2"), lane("[4 trip nope]", "ooo", "E2" * 3), lane("[[4 trip let]]", "ooo", "E2" * 3), lane("1", "/", "E2"), lane("1", "\\", "E2"), lane("1", "?", "E2"), lane("1", "~", "-"), lane("1 2 3", "o-~", "E2--"), lane("1", "-", "E2"), lane("1", "~", "E2"), lane("1", "o", "E2") + "\nChords: D3", lane("1", "o", "[[E2]]"), lane("1", "o", "H2"), "guitar\nCounts: 1\nNotes: E2", "guitar\nEvents: o\nNotes: E2", lane("1", "o", "E2") + "\nNotes: E2", lane("1", "o", "E2") + "\nGrid: quintuplets", lane("1", "o", "E2") + "\nGrid: eighths\nSubdivision: sixteenths", lane("1", "o", "E2", "guitar all notes G2"), lane("1", "x", "E2", "guitar normal"), lane("1", "o", "E2", "guitar palm mute"), lane("1", "o", "E2", "guitar pinch harmonic"), lane("1", "o", "E2", "guitar in H minor"), lane("1", "o", "E2", "guitar accelerando from 100 to 120 BPM"), lane("1", "o", "E2") + "\nInvent an orchestral bridge.", "guitar\nCounts: 1 | 1\nEvents: o | o\nNotes: E2", "guitar\nBar 2:\nCounts: 1\nEvents: o\nNotes: E2\nBar 1:", "guitar\nBar 1:\nCounts: 1\nEvents: o\nChords: Em4/B4", ORIGINAL_LANES.replace("final E2", "final G4"), ORIGINAL_LANES.replace("2 bars", "1 bar"), ORIGINAL_LANES.replace("end of bar 2", "end of bar 0"), ORIGINAL_LANES.replace( "Lead guitar", "Lead guitar normal, first palm muted then pinch harmonic" ), ORIGINAL_LANES + "\nBar 2:\nCounts: 1 2 3 4\nEvents: ----\nNotes: ----", ORIGINAL_LANES + "\nBar 2:\nCounts: 1\nEvents: o\nNotes: G4", ], ) def test_actionable_errors_never_approximate(text: str) -> None: with pytest.raises(DomainError): resolve(text) @pytest.mark.parametrize( "overrides", [ {"bars": 1}, {"time_signature": {"numerator": 3, "denominator": 4}}, {"parts": ["lead", "bass"]}, {"parts": ["drums"]}, ], ) def test_incompatible_structured_overrides_fail(overrides: dict[str, object]) -> None: with pytest.raises(UnsupportedDescriptionError): resolve(ORIGINAL_LANES, **overrides) def test_bass_ph_requires_actual_capability() -> None: intent = resolve(lane("1", "^", "E2", "bass")) profiles = load_profile_registry().select(intent.parts, ProfileSelection()) with pytest.raises(DomainError) as error: compose_score(intent, profiles) assert error.value.code == "UNSUPPORTED_ARTICULATION" def test_default_low_tonic_is_disclosed_and_not_used_over_precise_source() -> None: result = plan("guitar, 1 bar\nCounts: 1 2\nEvents: oo\nChords: -D3") assert [a.pitches for a in result.attacks] == [[40], [50, 54, 57]] assert "low tonic" in "\n".join(result.assumptions) def test_rests_stop_ties_and_unknown_material_remains_private() -> None: private = "PRIVATE_UNRECOGNIZED_LANE_MATERIAL" with pytest.raises(DomainError) as error: resolve(lane("1", "o", private)) assert private not in str(error.value) + str(error.value.details) @pytest.mark.parametrize("techniques", ["first palm muted then pinch harmonic", "first PM then PH"]) def test_ordered_prose_techniques_not_mistaken_for_global_conflict(techniques: str) -> None: assert ( plan(ORIGINAL_LANES.replace("Lead guitar", f"Lead guitar, {techniques}")).attacks == plan(ORIGINAL_LANES).attacks ) @pytest.mark.parametrize("suffix", ["", " without retriggering."]) @pytest.mark.parametrize("verb", ["Hold", "Tie"]) @pytest.mark.parametrize("connector", ["through", "to"]) @pytest.mark.parametrize("target", ["bar", "measure"]) def test_natural_hold_aliases(suffix: str, verb: str, connector: str, target: str) -> None: text = ORIGINAL_LANES[: ORIGINAL_LANES.index("Hold")] text += f"{verb} the final note {connector} the end of {target} 2{suffix}" assert plan(text).attacks == plan(ORIGINAL_LANES).attacks def test_chord_hold_and_tilde_preserve_whole_voicing() -> None: base = "guitar, 2 bars\nCounts: 1 2 3 4\nEvents: ---x\nChords: ---D3\n" prose = plan(base + "Tie the final chord to the end of measure 2.") tilde = plan(base + "Bar 2:\nCounts: 1 2 3 4\nEvents: ~~~~") assert prose.attacks == tilde.attacks assert prose.attacks[0].pitches == [50, 54, 57] assert prose.attacks[0].duration.value == 5 @pytest.mark.parametrize("notes", ["E2-E2", "E2--E2", "--E2", "E2--"]) def test_compact_empty_lane_boundaries(notes: str) -> None: size = notes.count("E2") + notes.count("-") events = "".join("o" if atom == "E2" else "-" for atom in re.findall(r"E2|-", notes)) counts = " ".join(str(i) for i in range(1, size + 1)) result = plan(lane(counts, events, notes)) assert len(result.attacks) == notes.count("E2") def test_style_context_is_disclosed_not_an_instruction_to_change_precise_notes() -> None: text = CANONICAL.replace( "Lead guitar", "Lead guitar, low-register chord voicings, aggressive tight metal style, " "bounded velocity variation", ) assert plan(text).attacks == plan(CANONICAL).attacks def test_large_malformed_and_overlength_inputs_are_bounded() -> None: with pytest.raises(ValidationError): GenerateMusicRequest(description="Counts: " + "[" * 4000, basename="huge") with pytest.raises(DomainError): resolve("guitar\nCounts: " + "[" * 3900) def test_expanded_tones_and_articulation_controls_share_public_budget( monkeypatch: pytest.MonkeyPatch, ) -> None: monkeypatch.setattr("riff_groove_builder.schemas.MAX_SCHEDULED_EVENTS", 12) monkeypatch.setattr("riff_groove_builder.articulations.MAX_SCHEDULED_EVENTS", 12) text = "guitar, 1 bar\nCounts: 1 2\nEvents: oo\nChords: C3 D3" intent = resolve(text) profiles = load_profile_registry().select(intent.parts, ProfileSelection()) with pytest.raises(DomainError) as error: compose_score(intent, profiles) assert error.value.details["reason"] == "event_budget_exceeded" standard_intent = resolve(text, profiles={"lead": "standard.lead.v1"}) standard = load_profile_registry().select(["lead"], ProfileSelection(lead="standard.lead.v1")) assert len(compose_score(standard_intent, standard).tracks[0].notes) == 6