240 lines
10 KiB
Python
240 lines
10 KiB
Python
"""Original request verbatim via real text-only source and installed-wheel transports."""
|
|
|
|
import asyncio
|
|
import hashlib
|
|
import json
|
|
import shutil
|
|
import sys
|
|
import uuid
|
|
import xml.etree.ElementTree as ET
|
|
from pathlib import Path
|
|
from typing import Any
|
|
|
|
import mido # type: ignore[import-untyped]
|
|
import pytest
|
|
from jsonschema import Draft202012Validator
|
|
from test_stdio import TIMEOUT, RawStdio, _environment
|
|
|
|
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.formats.agp import validate_riffer_file
|
|
from riff_groove_builder.profiles import load_profile_registry
|
|
from riff_groove_builder.schemas import GenerateMusicRequest, ProfileSelection, tool_output_schema
|
|
|
|
ROOT = Path(__file__).resolve().parents[2]
|
|
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."
|
|
)
|
|
MIDI_STARTS = [0, 480, 960, 1440, 1920, 2400, 2880, 3200, 3520]
|
|
MIDI_ENDS = [480, 960, 1440, 1920, 2400, 2880, 3200, 3520, 7680]
|
|
|
|
|
|
@pytest.fixture
|
|
def anyio_backend() -> str:
|
|
return "asyncio"
|
|
|
|
|
|
def inspect_saved(public: dict[str, Any], description: str, *, variant: bool) -> dict[str, Any]:
|
|
"""Assert numeric expected music first, independently of the producer's score/serializers."""
|
|
resolved = public["resolved"]
|
|
assert resolved["parts"] == ["lead"] and resolved["bars"] == 2
|
|
assert resolved["key"] == "E minor" and resolved["tempo_bpm"] == 120
|
|
assert resolved["musical_start_tick"] == 0 and resolved["musical_end_tick"] == 7680
|
|
assert resolved["profile_ids"]["lead"] == "ample.ame.4.0.1.riffer.v1"
|
|
assert not resolved["profile_ids"]["bass"] and not resolved["profile_ids"]["drums"]
|
|
assert "count-A" in "\n".join(resolved["assumptions"])
|
|
assert [a["format"] for a in public["artifacts"]] == ["mid", "griff"]
|
|
starts, ends = (MIDI_STARTS[2:], MIDI_ENDS[2:]) if variant else (MIDI_STARTS, MIDI_ENDS)
|
|
musical: list[tuple[int, int, int, int]] = []
|
|
switches: list[tuple[int, int, int, int]] = []
|
|
files = []
|
|
for artifact in public["artifacts"]:
|
|
assert artifact["fallback_for"] == [] and artifact["parts"] == ["lead"]
|
|
path = Path(artifact["path"])
|
|
data = path.read_bytes()
|
|
assert len(data) == artifact["size_bytes"]
|
|
if not variant:
|
|
assert (
|
|
hashlib.sha256(data).hexdigest()
|
|
== {
|
|
"mid": "c1967e698a50b8c22a22e458c3e2dd02d04407d1ad1d61f8a462d790b0810e62",
|
|
"griff": "e8195e74c60ac93b1a4c92967a0834a64b2a2ebd74f453d6d3640ea465c4104c",
|
|
}[artifact["format"]]
|
|
)
|
|
files.append(
|
|
{"name": path.name, "sha256": hashlib.sha256(data).hexdigest(), "size_bytes": len(data)}
|
|
)
|
|
if artifact["format"] != "mid":
|
|
continue
|
|
midi = mido.MidiFile(path)
|
|
assert midi.ticks_per_beat == 960 and midi.type == 1
|
|
assert [track.name for track in midi.tracks] == ["Conductor", "Lead"]
|
|
assert [sum(m.time for m in track) for track in midi.tracks] == [7680, 7680]
|
|
assert not any(m.type == "control_change" for t in midi.tracks for m in t)
|
|
assert not any(m.type == "program_change" for t in midi.tracks for m in t)
|
|
assert [m.tempo for t in midi.tracks for m in t if m.type == "set_tempo"] == [500000]
|
|
assert [
|
|
(m.numerator, m.denominator)
|
|
for t in midi.tracks
|
|
for m in t
|
|
if m.type == "time_signature"
|
|
] == [(4, 4)]
|
|
active: dict[int, tuple[int, int]] = {}
|
|
tick = 0
|
|
event_order = []
|
|
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)
|
|
event_order.append((tick, message.note))
|
|
elif message.type == "note_off" or (
|
|
message.type == "note_on" and message.velocity == 0
|
|
):
|
|
begin, velocity = active.pop(message.note)
|
|
target = musical if message.note == 40 else switches
|
|
target.append((begin, tick, message.note, velocity))
|
|
assert not active
|
|
assert [(n[0], n[1], n[2]) for n in musical] == [
|
|
(begin, end, 40) for begin, end in zip(starts, ends, strict=True)
|
|
]
|
|
assert [(n[0], n[1], n[2]) for n in switches] == [
|
|
(starts[0], starts[0] + 30, 26),
|
|
(3520, 3550, 31),
|
|
]
|
|
assert event_order.index((3520, 31)) < event_order.index((3520, 40))
|
|
assert all(1 <= n[3] <= 127 for n in musical)
|
|
assert not any(n[0] == 3840 for n in musical)
|
|
native_path = Path(public["artifacts"][1]["path"])
|
|
root = ET.fromstring(native_path.read_bytes())
|
|
assert root.tag == "Riff"
|
|
assert (root.attrib["PPQBase"], root.attrib["Measures"], root.attrib["loopEnd"]) == (
|
|
"480",
|
|
"2",
|
|
"3840",
|
|
)
|
|
assert root.attrib["Time-Signature"] == "4/4"
|
|
assert root.attrib["Inst"] == "AME" and root.attrib["Key"] == "Em"
|
|
assert not any(node.tag.startswith("cc-") for node in root)
|
|
native = sorted(
|
|
[
|
|
(
|
|
int(n.attrib["Begin"]),
|
|
int(n.attrib["End"]),
|
|
int(n.attrib["NoteID"]),
|
|
int(n.attrib["Velocity"]),
|
|
n.attrib["Articulation"],
|
|
int(s.attrib["ID"]),
|
|
int(n.attrib["Fret"]),
|
|
)
|
|
for s in root.findall("String")
|
|
for n in s.findall("Note")
|
|
],
|
|
key=lambda n: n[0],
|
|
)
|
|
assert native == [
|
|
(begin // 2, end // 2, 40, musical[i][3], "PH" if i == len(starts) - 1 else "PM", 6, 4)
|
|
for i, (begin, end) in enumerate(zip(starts, ends, strict=True))
|
|
]
|
|
request = GenerateMusicRequest(description=description, basename="compare")
|
|
intent = resolve_description(request).intent
|
|
profiles = load_profile_registry().select(intent.parts, ProfileSelection())
|
|
plan = compile_score(compose_score(intent, profiles), profiles)
|
|
readback = validate_riffer_file(native_path, plan, "lead", profiles["lead"])
|
|
assert len(readback.notes) == len(starts) and readback.end_tick == 3840
|
|
assert readback.notes[-1].articulation == "PH"
|
|
return {
|
|
"musical_midi": musical,
|
|
"switches": switches,
|
|
"native": native,
|
|
"artifacts": files,
|
|
"resolved": resolved,
|
|
}
|
|
|
|
|
|
async def exercise_phrase_stdio(client: RawStdio, outputs: Path, *, label: str) -> None:
|
|
evidence: dict[str, Any] = {}
|
|
before = sorted(outputs.iterdir())
|
|
for name, text in (
|
|
("phrase-original", ORIGINAL),
|
|
("phrase-nearby", ORIGINAL.replace("1 to 3&", "2 to 3&")),
|
|
("phrase-overlap", ORIGINAL.replace("1 to 3&", "1 to 4")),
|
|
("phrase-too-short", ORIGINAL + " 1 bar"),
|
|
):
|
|
arguments: dict[str, object] = {"description": text, "basename": name}
|
|
if name != "phrase-original":
|
|
arguments["allow_midi_fallback"] = False
|
|
response = await client.request(
|
|
name, "tools/call", {"name": "generate_music", "arguments": arguments}
|
|
)
|
|
result = response["result"]
|
|
assert len(result["content"]) == 1
|
|
public = json.loads(result["content"][0]["text"])
|
|
assert public == result["structuredContent"]
|
|
Draft202012Validator(tool_output_schema("generate_music")).validate(public)
|
|
if name in ("phrase-overlap", "phrase-too-short"):
|
|
assert result["isError"] and public["code"] == "UNSUPPORTED_DESCRIPTION"
|
|
assert not (outputs / name).exists()
|
|
evidence[name] = public
|
|
else:
|
|
assert not result["isError"] and public["status"] == "complete"
|
|
evidence[name] = inspect_saved(public, text, variant=name == "phrase-nearby")
|
|
assert sorted(outputs.iterdir()) == sorted(
|
|
[*before, outputs / "phrase-original", outputs / "phrase-nearby"]
|
|
)
|
|
assert not list(outputs.glob(".riff-stage-*"))
|
|
retained = ROOT / ".test-artifacts" / "step16" / label / "phrase-original"
|
|
retained.mkdir(parents=True, exist_ok=True)
|
|
for artifact in (outputs / "phrase-original").iterdir():
|
|
shutil.copyfile(artifact, retained / artifact.name)
|
|
(retained / "evidence.json").write_text(json.dumps(evidence, indent=2), encoding="utf-8")
|
|
print(f"Exact phrase {label}: " + json.dumps(evidence, sort_keys=True))
|
|
|
|
|
|
@pytest.mark.anyio
|
|
async def test_original_source_stdio_and_nearby_range() -> None:
|
|
outputs = ROOT / ".test-artifacts" / f"phrase-source-{uuid.uuid4().hex}"
|
|
outputs.mkdir()
|
|
process = await asyncio.wait_for(
|
|
asyncio.create_subprocess_exec(
|
|
sys.executable,
|
|
"-I",
|
|
"-B",
|
|
"-m",
|
|
"riff_groove_builder",
|
|
"--output-dir",
|
|
str(outputs),
|
|
cwd=ROOT,
|
|
env=_environment(),
|
|
stdin=asyncio.subprocess.PIPE,
|
|
stdout=asyncio.subprocess.PIPE,
|
|
stderr=asyncio.subprocess.PIPE,
|
|
),
|
|
TIMEOUT,
|
|
)
|
|
client = RawStdio(process)
|
|
try:
|
|
handshake = await client.initialize()
|
|
await exercise_phrase_stdio(client, outputs, label="source")
|
|
finally:
|
|
await client.close()
|
|
shutil.rmtree(outputs)
|
|
assert process.returncode == 0 and client.diagnostics == b""
|
|
retained = ROOT / ".test-artifacts" / "step16" / "source"
|
|
(retained / "phrase-transport.json").write_text(
|
|
json.dumps(
|
|
{
|
|
"handshake": handshake["result"],
|
|
"exit_code": process.returncode,
|
|
"stdout_lines": len(client.lines),
|
|
"stderr": client.diagnostics.decode("utf-8"),
|
|
"original_arguments": {"description": ORIGINAL, "basename": "phrase-original"},
|
|
},
|
|
indent=2,
|
|
),
|
|
encoding="utf-8",
|
|
)
|