@mthines/reaper-mcp 0.101.1 → 0.102.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +46 -46
- package/bridge-ui/mcp_bridge.html +51 -51
- package/main.js +554 -366
- package/package.json +1 -1
- package/reaper/mcp_bridge.lua +1 -1
- package/sidecar/pitch.py +192 -0
- package/sidecar/server.py +38 -0
- package/sidecar/tests/test_pitch.py +109 -0
package/package.json
CHANGED
package/reaper/mcp_bridge.lua
CHANGED
|
@@ -5185,7 +5185,7 @@ for _, c in ipairs({
|
|
|
5185
5185
|
"set_fx_preset", "get_fx_preset_list", "list_available_fx", "load_fx_chain", "insert_track_template",
|
|
5186
5186
|
"insert_audio_file", "snapshot_save", "snapshot_restore", "snapshot_edit",
|
|
5187
5187
|
"analyze_track_offline", "analyze_audio_file", "measure_track_alignment", "verify_edit", "analyze_track_aesthetics",
|
|
5188
|
-
"detect_transients", "create_transient_automation", "insert_stem_tracks",
|
|
5188
|
+
"detect_transients", "create_transient_automation", "detect_vocal_pitch", "correct_vocal_pitch", "insert_stem_tracks",
|
|
5189
5189
|
"analyze_loudness_curve", "analyze_stereo_bands", "measure_masking", "separate_stems",
|
|
5190
5190
|
"transcribe_voice_sketch",
|
|
5191
5191
|
"freeze_tracks", "unfreeze_tracks", "apply_fx_to_items", "quantize_audio", "align_audio_to_guide", "detect_key", "detect_chords", "import_midi_file", "process_items",
|
package/sidecar/pitch.py
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
"""Vocal pitch contour, notes and scale-snapping offsets for pitch correction.
|
|
2
|
+
|
|
3
|
+
The contour comes from SwiftF0 (MIT, ONNX, installed by `setup-sidecar --with-pitch`) when it is
|
|
4
|
+
available, else from the YIN tracker `voice_sketch` already ships. Correction is per note, not per
|
|
5
|
+
frame: one offset per sung note keeps vibrato and slides inside it, which is what makes the result
|
|
6
|
+
sound natural. Nothing here edits audio; it only says how far each note sits from its target.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import math
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
import numpy as np
|
|
14
|
+
|
|
15
|
+
SCALES: dict[str, list[int]] = {
|
|
16
|
+
"major": [0, 2, 4, 5, 7, 9, 11],
|
|
17
|
+
"minor": [0, 2, 3, 5, 7, 8, 10],
|
|
18
|
+
"harmonic_minor": [0, 2, 3, 5, 7, 8, 11],
|
|
19
|
+
"major_pentatonic": [0, 2, 4, 7, 9],
|
|
20
|
+
"minor_pentatonic": [0, 3, 5, 7, 10],
|
|
21
|
+
"chromatic": list(range(12)),
|
|
22
|
+
}
|
|
23
|
+
NOTE_NAMES = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"]
|
|
24
|
+
# Krumhansl-Kessler key profiles, as in the server's key detection.
|
|
25
|
+
_KK_MAJOR = [6.35, 2.23, 3.48, 2.33, 4.38, 4.09, 2.52, 5.19, 2.39, 3.66, 2.29, 2.88]
|
|
26
|
+
_KK_MINOR = [6.33, 2.68, 3.52, 5.38, 2.60, 3.53, 2.54, 4.75, 3.98, 2.69, 3.34, 3.17]
|
|
27
|
+
|
|
28
|
+
MIN_VOICED_CONFIDENCE = 0.5
|
|
29
|
+
MAX_SECONDS = 180
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def engine_available() -> bool:
|
|
33
|
+
try:
|
|
34
|
+
import swift_f0 # type: ignore # noqa: F401
|
|
35
|
+
return True
|
|
36
|
+
except ImportError:
|
|
37
|
+
return False
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _midi(hz: np.ndarray) -> np.ndarray:
|
|
41
|
+
return 69 + 12 * np.log2(np.maximum(hz, 1e-6) / 440)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def contour(mono: np.ndarray, sr: int, fmin: float, fmax: float, engine: str = "auto"):
|
|
45
|
+
"""(times s, midi pitch, voiced flag, confidence, engine name); unvoiced pitch is NaN."""
|
|
46
|
+
use_neural = engine == "swiftf0" or (engine == "auto" and engine_available())
|
|
47
|
+
if use_neural:
|
|
48
|
+
from swift_f0 import SwiftF0 # type: ignore
|
|
49
|
+
|
|
50
|
+
result = SwiftF0().detect(mono.astype(np.float32), float(sr), fmin=fmin, fmax=fmax)
|
|
51
|
+
hz = np.asarray(result.pitch_hz, dtype=float)
|
|
52
|
+
conf = np.asarray(result.confidence, dtype=float)
|
|
53
|
+
voiced = (conf >= MIN_VOICED_CONFIDENCE) & (hz >= fmin) & (hz <= fmax)
|
|
54
|
+
return np.asarray(result.timestamps, dtype=float), np.where(voiced, _midi(hz), np.nan), voiced, conf, "swiftf0"
|
|
55
|
+
if engine not in ("auto", "yin"):
|
|
56
|
+
raise ValueError(f"Unknown engine '{engine}': use auto, swiftf0 or yin")
|
|
57
|
+
import voice_sketch
|
|
58
|
+
|
|
59
|
+
low = int(math.floor(69 + 12 * math.log2(fmin / 440)))
|
|
60
|
+
high = int(math.ceil(69 + 12 * math.log2(fmax / 440)))
|
|
61
|
+
times, pitches, clarity, _levels, _silent = voice_sketch._pitch_frames(mono, sr, low, high)
|
|
62
|
+
voiced = pitches >= 0
|
|
63
|
+
return times, np.where(voiced, pitches, np.nan), voiced, clarity, "yin"
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def segment_notes(times: np.ndarray, midi: np.ndarray, voiced: np.ndarray, *, split_cents: float = 80,
|
|
67
|
+
min_note: float = 0.08, max_gap: float = 0.06) -> list[dict[str, Any]]:
|
|
68
|
+
"""Voiced runs cut where the pitch leaves the note's running median for three frames in a row."""
|
|
69
|
+
hop = float(np.median(np.diff(times))) if times.size > 1 else 0.016
|
|
70
|
+
gap_frames = max(1, int(round(max_gap / hop)))
|
|
71
|
+
persist = 3
|
|
72
|
+
runs: list[tuple[int, int]] = []
|
|
73
|
+
i, n = 0, len(times)
|
|
74
|
+
while i < n:
|
|
75
|
+
if not voiced[i]:
|
|
76
|
+
i += 1
|
|
77
|
+
continue
|
|
78
|
+
j, last = i, i
|
|
79
|
+
while j < n and (voiced[j] or j - last <= gap_frames):
|
|
80
|
+
if voiced[j]:
|
|
81
|
+
last = j
|
|
82
|
+
j += 1
|
|
83
|
+
runs.append((i, last + 1))
|
|
84
|
+
i = last + 1
|
|
85
|
+
notes: list[dict[str, Any]] = []
|
|
86
|
+
for a, b in runs:
|
|
87
|
+
cut, start = [], a
|
|
88
|
+
idx = [k for k in range(a, b) if voiced[k]]
|
|
89
|
+
members: list[int] = []
|
|
90
|
+
k = 0
|
|
91
|
+
while k < len(idx):
|
|
92
|
+
frame = idx[k]
|
|
93
|
+
if members and abs(midi[frame] - np.median(midi[members])) * 100 > split_cents:
|
|
94
|
+
ahead = idx[k:k + persist]
|
|
95
|
+
if len(ahead) == persist and all(abs(midi[f] - np.median(midi[members])) * 100 > split_cents for f in ahead):
|
|
96
|
+
cut.append((start, members))
|
|
97
|
+
start, members = frame, []
|
|
98
|
+
members.append(frame)
|
|
99
|
+
k += 1
|
|
100
|
+
cut.append((start, members))
|
|
101
|
+
for first, frames in cut:
|
|
102
|
+
end_frame = frames[-1]
|
|
103
|
+
t0, t1 = float(times[first]), float(times[end_frame] + hop)
|
|
104
|
+
if t1 - t0 >= min_note:
|
|
105
|
+
notes.append({"start": t0, "end": t1, "frames": frames})
|
|
106
|
+
return notes
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def detect_key(notes: list[dict[str, Any]], midi: np.ndarray) -> tuple[int, str, float]:
|
|
110
|
+
"""Tonic pitch class, 'major' or 'minor', and the correlation of the winner."""
|
|
111
|
+
hist = np.zeros(12)
|
|
112
|
+
for note in notes:
|
|
113
|
+
hist[int(round(float(np.median(midi[note["frames"]])))) % 12] += len(note["frames"])
|
|
114
|
+
if hist.sum() == 0:
|
|
115
|
+
return 0, "major", 0.0
|
|
116
|
+
best = (-2.0, 0, "major")
|
|
117
|
+
for tonic in range(12):
|
|
118
|
+
for name, profile in (("major", _KK_MAJOR), ("minor", _KK_MINOR)):
|
|
119
|
+
r = float(np.corrcoef(hist, np.roll(profile, tonic))[0, 1])
|
|
120
|
+
if r > best[0]:
|
|
121
|
+
best = (r, tonic, name)
|
|
122
|
+
return best[1], best[2], best[0]
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def parse_key(key: str) -> tuple[int, str | None]:
|
|
126
|
+
"""'A', 'F#', 'Bb' (tonic, scale from the call) or 'auto'."""
|
|
127
|
+
if key.lower() == "auto":
|
|
128
|
+
return -1, None
|
|
129
|
+
letter = key.strip()[:1].upper()
|
|
130
|
+
if letter not in "ABCDEFG" or not letter:
|
|
131
|
+
raise ValueError(f"Unknown key '{key}': use a note name such as C, F# or Bb, or auto")
|
|
132
|
+
base = {"C": 0, "D": 2, "E": 4, "F": 5, "G": 7, "A": 9, "B": 11}[letter]
|
|
133
|
+
shift = key.strip()[1:].replace("♯", "#").replace("♭", "b")
|
|
134
|
+
if shift not in ("", "#", "b"):
|
|
135
|
+
raise ValueError(f"Unknown key '{key}': use a note name such as C, F# or Bb, or auto")
|
|
136
|
+
return (base + (1 if shift == "#" else -1 if shift == "b" else 0)) % 12, None
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _allowed(tonic: int, scale: str) -> list[int]:
|
|
140
|
+
if scale not in SCALES:
|
|
141
|
+
raise ValueError(f"Unknown scale '{scale}': use one of {', '.join(SCALES)}")
|
|
142
|
+
return [(tonic + step) % 12 for step in SCALES[scale]]
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _nearest(value: float, allowed: list[int]) -> int:
|
|
146
|
+
candidates = [m for m in range(int(value) - 7, int(value) + 8) if m % 12 in allowed]
|
|
147
|
+
return min(candidates, key=lambda m: (abs(m - value), m))
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def analyze(mono: np.ndarray, sr: int, *, key: str = "auto", scale: str = "major", strength: float = 1.0,
|
|
151
|
+
max_shift_cents: float = 200, fmin: float = 65, fmax: float = 1100, engine: str = "auto",
|
|
152
|
+
split_cents: float = 80, min_note: float = 0.08, dead_zone_cents: float = 8) -> dict[str, Any]:
|
|
153
|
+
"""Notes with their target and the shift (cents) that moves each onto it.
|
|
154
|
+
|
|
155
|
+
`strength` scales every shift (1 = all the way onto the note); a shift past `max_shift_cents`
|
|
156
|
+
is left alone, because a note that far from its target was probably sung on purpose; shifts
|
|
157
|
+
under `dead_zone_cents` are not worth an edit.
|
|
158
|
+
"""
|
|
159
|
+
if mono.size < int(0.2 * sr):
|
|
160
|
+
raise ValueError("Audio too short: need at least 0.2 s")
|
|
161
|
+
if not 0 <= strength <= 1:
|
|
162
|
+
raise ValueError("strength must be between 0 and 1")
|
|
163
|
+
times, midi, voiced, conf, used = contour(mono, sr, fmin, fmax, engine)
|
|
164
|
+
notes = segment_notes(times, midi, voiced, split_cents=split_cents, min_note=min_note)
|
|
165
|
+
tonic, forced = parse_key(key)
|
|
166
|
+
key_confidence = None
|
|
167
|
+
if tonic < 0:
|
|
168
|
+
tonic, scale, key_confidence = detect_key(notes, midi)
|
|
169
|
+
key_confidence = round(key_confidence, 3)
|
|
170
|
+
allowed = _allowed(tonic, scale)
|
|
171
|
+
out = []
|
|
172
|
+
for note in notes:
|
|
173
|
+
frames = note["frames"]
|
|
174
|
+
median = float(np.median(midi[frames]))
|
|
175
|
+
target = _nearest(median, allowed)
|
|
176
|
+
raw = (target - median) * 100
|
|
177
|
+
shift = raw * strength
|
|
178
|
+
skipped = None
|
|
179
|
+
if abs(raw) > max_shift_cents:
|
|
180
|
+
shift, skipped = 0.0, "too_far"
|
|
181
|
+
elif abs(shift) < dead_zone_cents:
|
|
182
|
+
shift, skipped = 0.0, "in_tune"
|
|
183
|
+
out.append({"start": round(note["start"], 4), "end": round(note["end"], 4),
|
|
184
|
+
"medianMidi": round(median, 3), "name": f"{NOTE_NAMES[target % 12]}{target // 12 - 1}",
|
|
185
|
+
"targetMidi": target, "offsetCents": round(raw, 1), "shiftCents": round(shift, 1),
|
|
186
|
+
"confidence": round(float(np.mean(conf[frames])), 3), **({"skipped": skipped} if skipped else {})})
|
|
187
|
+
offsets = [n["offsetCents"] for n in out]
|
|
188
|
+
return {"engine": used, "key": NOTE_NAMES[tonic], "scale": scale, "keyConfidence": key_confidence,
|
|
189
|
+
"notes": out,
|
|
190
|
+
# A singer who is flat or sharp on average, as opposed to a few wrong notes.
|
|
191
|
+
"averageOffsetCents": round(float(np.mean(offsets)), 1) if offsets else 0.0,
|
|
192
|
+
"voicedShare": round(float(np.mean(voiced)), 3)}
|
package/sidecar/server.py
CHANGED
|
@@ -572,6 +572,43 @@ def handle_voice_render(request_id: Any, params: dict) -> str:
|
|
|
572
572
|
|
|
573
573
|
# JSON-RPC method names must stay in sync with the TypeScript client.
|
|
574
574
|
# When adding a method here, also reference it from apps/reaper-mcp-server/src/sidecar.ts.
|
|
575
|
+
def handle_detect_pitch(request_id: Any, params: dict) -> str:
|
|
576
|
+
"""
|
|
577
|
+
Sung notes in a file range with the shift (cents) that puts each in key. Never edits audio.
|
|
578
|
+
|
|
579
|
+
params: path, startTime?, endTime?, key? (C, F#, Bb or auto), scale?, strength? (0..1),
|
|
580
|
+
maxShiftCents?, engine? (auto|swiftf0|yin), minNoteMs?, splitCents?
|
|
581
|
+
"""
|
|
582
|
+
import analysis
|
|
583
|
+
import pitch
|
|
584
|
+
|
|
585
|
+
error = _check_file(request_id, params, "path")
|
|
586
|
+
if error:
|
|
587
|
+
return error
|
|
588
|
+
try:
|
|
589
|
+
start = float(params.get("startTime", 0))
|
|
590
|
+
end = params.get("endTime")
|
|
591
|
+
if end is not None and float(end) - start > pitch.MAX_SECONDS:
|
|
592
|
+
raise ValueError(f"Select at most {pitch.MAX_SECONDS} seconds per call")
|
|
593
|
+
audio, sr = analysis.load_audio(params["path"], start, None if end is None else float(end))
|
|
594
|
+
if audio.shape[1] > pitch.MAX_SECONDS * sr:
|
|
595
|
+
raise ValueError(f"Select at most {pitch.MAX_SECONDS} seconds per call")
|
|
596
|
+
result = pitch.analyze(
|
|
597
|
+
audio.mean(axis=0), sr, key=str(params.get("key", "auto")), scale=str(params.get("scale", "major")),
|
|
598
|
+
strength=float(params.get("strength", 1.0)), max_shift_cents=float(params.get("maxShiftCents", 200)),
|
|
599
|
+
engine=str(params.get("engine", "auto")), min_note=float(params.get("minNoteMs", 80)) / 1000,
|
|
600
|
+
split_cents=float(params.get("splitCents", 80)))
|
|
601
|
+
for note in result["notes"]:
|
|
602
|
+
note["start"] = round(note["start"] + start, 4)
|
|
603
|
+
note["end"] = round(note["end"] + start, 4)
|
|
604
|
+
result["startTime"] = start
|
|
605
|
+
return _ok(request_id, result)
|
|
606
|
+
except ValueError as exc:
|
|
607
|
+
return _err(request_id, -32602, str(exc))
|
|
608
|
+
except Exception as exc: # noqa: BLE001 - a tracker failure must fail only this RPC
|
|
609
|
+
return _err(request_id, -32000, f"Pitch detection failed: {exc}")
|
|
610
|
+
|
|
611
|
+
|
|
575
612
|
METHODS = {
|
|
576
613
|
"analyze": handle_analyze,
|
|
577
614
|
"analyze_audio": handle_analyze_audio,
|
|
@@ -586,6 +623,7 @@ METHODS = {
|
|
|
586
623
|
"separation_status": handle_separation_status,
|
|
587
624
|
"chords": handle_chords,
|
|
588
625
|
"chords_status": handle_chords_status,
|
|
626
|
+
"detect_pitch": handle_detect_pitch,
|
|
589
627
|
"transcribe_voice_sketch": handle_voice_sketch,
|
|
590
628
|
"render_voice_arrangement": handle_voice_render,
|
|
591
629
|
}
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
"""Synthetic sung notes with known detuning, independent of the tracker used."""
|
|
2
|
+
import sys
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
import pytest
|
|
7
|
+
|
|
8
|
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
|
9
|
+
import pitch
|
|
10
|
+
|
|
11
|
+
SR = 22050
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def voice(midi, seconds, cents=0.0, vibrato_cents=0.0, vibrato_hz=5.5):
|
|
15
|
+
"""A harmonic tone at `midi` detuned by `cents`, optionally with vibrato."""
|
|
16
|
+
t = np.arange(int(seconds * SR)) / SR
|
|
17
|
+
detune = cents + vibrato_cents * np.sin(2 * np.pi * vibrato_hz * t)
|
|
18
|
+
freq = 440 * 2 ** ((midi + detune / 100 - 69) / 12)
|
|
19
|
+
phase = 2 * np.pi * np.cumsum(freq) / SR
|
|
20
|
+
return (0.25 * np.sin(phase) + 0.2 * np.sin(2 * phase) + 0.1 * np.sin(3 * phase)).astype(np.float32)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def phrase(parts):
|
|
24
|
+
"""parts: (midi, cents, vibrato) notes of 0.5 s separated by 0.15 s of silence."""
|
|
25
|
+
pieces = []
|
|
26
|
+
for midi, cents, vibrato in parts:
|
|
27
|
+
pieces += [voice(midi, 0.5, cents, vibrato), np.zeros(int(0.15 * SR), dtype=np.float32)]
|
|
28
|
+
return np.concatenate(pieces)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
ENGINES = ["yin"] + (["swiftf0"] if pitch.engine_available() else [])
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@pytest.mark.parametrize("engine", ENGINES)
|
|
35
|
+
def test_each_note_gets_the_shift_that_puts_it_in_key(engine):
|
|
36
|
+
audio = phrase([(57, -35, 0), (60, 30, 0), (64, -25, 0), (67, 0, 0)]) # A3 C4 E4 G4 in C major
|
|
37
|
+
result = pitch.analyze(audio, SR, key="C", scale="major", engine=engine)
|
|
38
|
+
assert [n["targetMidi"] for n in result["notes"]] == [57, 60, 64, 67]
|
|
39
|
+
shifts = [n["offsetCents"] for n in result["notes"]]
|
|
40
|
+
assert shifts[:3] == pytest.approx([35, -30, 25], abs=12)
|
|
41
|
+
assert abs(shifts[3]) < 12
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@pytest.mark.parametrize("engine", ENGINES)
|
|
45
|
+
def test_a_note_outside_the_key_snaps_to_the_nearest_scale_note(engine):
|
|
46
|
+
audio = phrase([(61, 30, 0), (66, -30, 0)]) # C#4 +30 and F#4 -30 against C major
|
|
47
|
+
result = pitch.analyze(audio, SR, key="C", scale="major", engine=engine)
|
|
48
|
+
assert [n["targetMidi"] for n in result["notes"]] == [62, 65]
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@pytest.mark.parametrize("engine", ENGINES)
|
|
52
|
+
def test_vibrato_stays_one_note_with_one_shift(engine):
|
|
53
|
+
audio = phrase([(60, -30, 40)])
|
|
54
|
+
result = pitch.analyze(audio, SR, key="C", scale="major", engine=engine)
|
|
55
|
+
assert len(result["notes"]) == 1
|
|
56
|
+
assert result["notes"][0]["shiftCents"] == pytest.approx(30, abs=15)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
@pytest.mark.parametrize("engine", ENGINES)
|
|
60
|
+
def test_a_pitch_step_inside_a_voiced_run_makes_two_notes(engine):
|
|
61
|
+
audio = np.concatenate([voice(60, 0.4), voice(64, 0.4)])
|
|
62
|
+
result = pitch.analyze(audio, SR, key="C", scale="major", engine=engine)
|
|
63
|
+
assert [n["targetMidi"] for n in result["notes"]] == [60, 64]
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def test_strength_scales_the_shift_and_a_far_note_is_left_alone():
|
|
67
|
+
audio = phrase([(60, -40, 0)])
|
|
68
|
+
half = pitch.analyze(audio, SR, key="C", scale="major", strength=0.5, engine="yin")
|
|
69
|
+
assert half["notes"][0]["shiftCents"] == pytest.approx(20, abs=10)
|
|
70
|
+
far = pitch.analyze(phrase([(61, -45, 0)]), SR, key="C", scale="major", max_shift_cents=30, engine="yin")
|
|
71
|
+
assert far["notes"][0]["shiftCents"] == 0 and far["notes"][0]["skipped"] == "too_far"
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def test_an_in_tune_note_is_not_worth_an_edit():
|
|
75
|
+
result = pitch.analyze(phrase([(62, 3, 0)]), SR, key="C", scale="major", engine="yin")
|
|
76
|
+
assert result["notes"][0]["shiftCents"] == 0 and result["notes"][0]["skipped"] == "in_tune"
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def test_key_is_found_from_the_notes_when_not_given():
|
|
80
|
+
melody = [(60, 0, 0), (62, 0, 0), (64, 0, 0), (65, 0, 0), (67, 0, 0), (64, 0, 0), (60, 0, 0), (67, 0, 0)]
|
|
81
|
+
result = pitch.analyze(phrase(melody), SR, key="auto", engine="yin")
|
|
82
|
+
assert (result["key"], result["scale"]) == ("C", "major")
|
|
83
|
+
assert result["keyConfidence"] > 0.6
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def test_silence_has_no_notes_and_a_bad_key_is_refused():
|
|
87
|
+
result = pitch.analyze(np.zeros(SR * 2, dtype=np.float32), SR, key="C", engine="yin")
|
|
88
|
+
assert result["notes"] == [] and result["voicedShare"] == 0
|
|
89
|
+
with pytest.raises(ValueError, match="Unknown key"):
|
|
90
|
+
pitch.analyze(phrase([(60, 0, 0)]), SR, key="H", engine="yin")
|
|
91
|
+
with pytest.raises(ValueError, match="Unknown scale"):
|
|
92
|
+
pitch.analyze(phrase([(60, 0, 0)]), SR, key="C", scale="lydian", engine="yin")
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def test_the_sidecar_method_reads_a_file_and_reports_notes_in_file_time(tmp_path):
|
|
96
|
+
import json
|
|
97
|
+
import soundfile as sf
|
|
98
|
+
from server import dispatch
|
|
99
|
+
|
|
100
|
+
path = tmp_path / "vocal.wav"
|
|
101
|
+
sf.write(path, phrase([(60, -30, 0), (64, 25, 0)]), SR)
|
|
102
|
+
reply = json.loads(dispatch(json.dumps({"jsonrpc": "2.0", "id": 1, "method": "detect_pitch",
|
|
103
|
+
"params": {"path": str(path), "key": "C", "startTime": 0.0, "engine": "yin"}})))
|
|
104
|
+
notes = reply["result"]["notes"]
|
|
105
|
+
assert [n["targetMidi"] for n in notes] == [60, 64]
|
|
106
|
+
assert notes[1]["start"] > notes[0]["end"]
|
|
107
|
+
bad = json.loads(dispatch(json.dumps({"jsonrpc": "2.0", "id": 2, "method": "detect_pitch",
|
|
108
|
+
"params": {"path": str(path), "key": "H"}})))
|
|
109
|
+
assert "Unknown key" in bad["error"]["message"]
|