carnatic-practice 0.1.0__py3-none-any.whl
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.
- carnatic_practice/__init__.py +3 -0
- carnatic_practice/__main__.py +3 -0
- carnatic_practice/analysis.py +264 -0
- carnatic_practice/cli.py +107 -0
- carnatic_practice/reports.py +99 -0
- carnatic_practice/svg.py +298 -0
- carnatic_practice-0.1.0.dist-info/METADATA +211 -0
- carnatic_practice-0.1.0.dist-info/RECORD +12 -0
- carnatic_practice-0.1.0.dist-info/WHEEL +4 -0
- carnatic_practice-0.1.0.dist-info/entry_points.txt +2 -0
- carnatic_practice-0.1.0.dist-info/licenses/LICENSE +21 -0
- carnatic_practice-0.1.0.dist-info/licenses/THIRD_PARTY_NOTICES.md +36 -0
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
"""Check the pitch of sung swaras against your shruthi.
|
|
2
|
+
|
|
3
|
+
Detects pitch with SwiftF0, splits a WAV recording into held notes, and names
|
|
4
|
+
notes against just-intonation reference ratios. Carnatic intonation varies by
|
|
5
|
+
raga and phrase, so treat the numbers as a practice aid.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import re
|
|
11
|
+
import unicodedata
|
|
12
|
+
from dataclasses import dataclass
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
import numpy as np
|
|
16
|
+
|
|
17
|
+
# Swarasthanas in cents above Sa (just-intonation reference ratios).
|
|
18
|
+
SWARA_CENTS = {
|
|
19
|
+
"Sa": 0, "Ri1": 112, "Ri2": 204, "Ga2": 316, "Ga3": 386, "Ma1": 498,
|
|
20
|
+
"Ma2": 590, "Pa": 702, "Da1": 814, "Da2": 884, "Ni2": 996, "Ni3": 1088,
|
|
21
|
+
}
|
|
22
|
+
RAGAS = {
|
|
23
|
+
"mayamalavagowla": ["Sa", "Ri1", "Ga3", "Ma1", "Pa", "Da1", "Ni3"],
|
|
24
|
+
"shankarabharanam": ["Sa", "Ri2", "Ga3", "Ma1", "Pa", "Da2", "Ni3"],
|
|
25
|
+
"kalyani": ["Sa", "Ri2", "Ga3", "Ma2", "Pa", "Da2", "Ni3"],
|
|
26
|
+
"kharaharapriya": ["Sa", "Ri2", "Ga2", "Ma1", "Pa", "Da2", "Ni2"],
|
|
27
|
+
"harikambhoji": ["Sa", "Ri2", "Ga3", "Ma1", "Pa", "Da2", "Ni2"],
|
|
28
|
+
"mohanam": ["Sa", "Ri2", "Ga3", "Pa", "Da2"],
|
|
29
|
+
"hamsadhwani": ["Sa", "Ri2", "Ga3", "Pa", "Ni3"],
|
|
30
|
+
"chromatic": list(SWARA_CENTS), # all 12 swarasthanas
|
|
31
|
+
}
|
|
32
|
+
DEFAULT_SA = "C"
|
|
33
|
+
DEFAULT_RAGA = "mayamalavagowla"
|
|
34
|
+
NOTE_NAMES = ["C", "C♯", "D", "D♯", "E", "F", "F♯", "G", "G♯", "A", "A♯", "B"]
|
|
35
|
+
NOTE_INDEX = {"C": 0, "D": 2, "E": 4, "F": 5, "G": 7, "A": 9, "B": 11}
|
|
36
|
+
|
|
37
|
+
FMIN, FMAX = 60.0, 800.0 # vocal range searched
|
|
38
|
+
VOICED = 0.5 # SwiftF0 confidence threshold
|
|
39
|
+
SPLIT_CENTS = 70 # a jump this big starts a new note
|
|
40
|
+
MIN_NOTE = 0.30 # seconds; shorter blips are ignored
|
|
41
|
+
ONSET = 0.25 # seconds skipped at the start of a note (the slide in)
|
|
42
|
+
IN_TUNE = 20 # cents; counted as "close" in the summary
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass
|
|
46
|
+
class Note:
|
|
47
|
+
start: float
|
|
48
|
+
end: float
|
|
49
|
+
hz: float
|
|
50
|
+
swara: str # display name, e.g. "Ma", "Ṡa", "Ṇi"
|
|
51
|
+
off: float # cents from the reference swara
|
|
52
|
+
wobble: float # std dev in cents while held
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@dataclass
|
|
56
|
+
class Analysis:
|
|
57
|
+
source: str
|
|
58
|
+
sa_hz: float
|
|
59
|
+
sa_source: str
|
|
60
|
+
raga: str
|
|
61
|
+
t: np.ndarray
|
|
62
|
+
f0: np.ndarray # Hz, NaN where unvoiced
|
|
63
|
+
notes: list[Note]
|
|
64
|
+
|
|
65
|
+
def swara_lines(self, lo_cents: float, hi_cents: float) -> list[tuple[str, float]]:
|
|
66
|
+
"""(display name, cents above Sa) for raga swaras within a range."""
|
|
67
|
+
out = []
|
|
68
|
+
for octave in range(-2, 3):
|
|
69
|
+
for name in RAGAS[self.raga]:
|
|
70
|
+
c = SWARA_CENTS[name] + 1200 * octave
|
|
71
|
+
if lo_cents <= c <= hi_cents:
|
|
72
|
+
out.append((display_name(name, octave), c))
|
|
73
|
+
return out
|
|
74
|
+
|
|
75
|
+
def cents(self) -> np.ndarray:
|
|
76
|
+
return 1200 * np.log2(self.f0 / self.sa_hz)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
# --------------------------------------------------------------------------
|
|
80
|
+
# Names & tuning
|
|
81
|
+
# --------------------------------------------------------------------------
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def display_name(swara: str, octave: int) -> str:
|
|
85
|
+
"""'Ri1' -> 'Ri' (raga makes the variant clear); dot above = upper octave,
|
|
86
|
+
dot below = lower octave."""
|
|
87
|
+
base = swara[:2]
|
|
88
|
+
mark = "\u0307" if octave > 0 else "\u0323" if octave < 0 else ""
|
|
89
|
+
# NFC turns e.g. S + combining dot into the single character Ṡ, which
|
|
90
|
+
# fonts render more reliably.
|
|
91
|
+
return unicodedata.normalize("NFC", base[0] + mark * abs(octave) + base[1])
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def parse_sa(value) -> float:
|
|
95
|
+
"""'A#', 'Bb', 'C#3', or a frequency like 117.3 -> Hz.
|
|
96
|
+
|
|
97
|
+
A bare note name is placed in the octave around 100-200 Hz for a
|
|
98
|
+
lower-register Sa; give an octave (e.g. 'G#3') to be explicit.
|
|
99
|
+
"""
|
|
100
|
+
if isinstance(value, (bool, np.bool_)):
|
|
101
|
+
raise ValueError("shruthi must be a positive, finite frequency in Hz, not a boolean")
|
|
102
|
+
text = str(value).strip().replace("♯", "#").replace("♭", "b")
|
|
103
|
+
try:
|
|
104
|
+
hz = float(text)
|
|
105
|
+
except ValueError:
|
|
106
|
+
m = re.fullmatch(r"([A-Ga-g])([#b]?)(-?\d+)?", text)
|
|
107
|
+
if not m:
|
|
108
|
+
raise ValueError(f"can't understand shruthi {value!r} (use e.g. A#, Bb3, 117.3)")
|
|
109
|
+
semis = NOTE_INDEX[m[1].upper()] + {"#": 1, "b": -1, "": 0}[m[2]]
|
|
110
|
+
if m[3] is not None:
|
|
111
|
+
midi = 12 * (int(m[3]) + 1) + semis
|
|
112
|
+
try:
|
|
113
|
+
hz = 440.0 * 2 ** ((midi - 69) / 12)
|
|
114
|
+
except OverflowError as e:
|
|
115
|
+
raise ValueError("shruthi must be a positive, finite frequency in Hz") from e
|
|
116
|
+
else:
|
|
117
|
+
hz = 440.0 * 2 ** ((semis - 9) / 12) # octave 4
|
|
118
|
+
while hz >= 200:
|
|
119
|
+
hz /= 2
|
|
120
|
+
while hz < 100:
|
|
121
|
+
hz *= 2
|
|
122
|
+
if not np.isfinite(hz) or hz <= 0:
|
|
123
|
+
raise ValueError("shruthi must be a positive, finite frequency in Hz")
|
|
124
|
+
return hz
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def western(hz: float) -> str:
|
|
128
|
+
midi = 69 + 12 * np.log2(hz / 440.0)
|
|
129
|
+
n = int(round(midi))
|
|
130
|
+
cents = (midi - n) * 100
|
|
131
|
+
return f"{NOTE_NAMES[n % 12]}{n // 12 - 1} {cents:+.0f}¢"
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
# --------------------------------------------------------------------------
|
|
135
|
+
# Analysis
|
|
136
|
+
# --------------------------------------------------------------------------
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _validate_audio(audio: np.ndarray) -> None:
|
|
140
|
+
if not audio.size:
|
|
141
|
+
raise ValueError("audio is empty")
|
|
142
|
+
if not np.all(np.isfinite(audio)):
|
|
143
|
+
raise ValueError("audio contains non-finite samples")
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def load_audio(path: Path) -> tuple[np.ndarray, int]:
|
|
147
|
+
"""Read a WAV file as mono float32 audio and its sample rate."""
|
|
148
|
+
import soundfile as sf
|
|
149
|
+
|
|
150
|
+
path = path.expanduser()
|
|
151
|
+
try:
|
|
152
|
+
with sf.SoundFile(path) as wav:
|
|
153
|
+
if wav.format not in {"WAV", "WAVEX", "RF64"}:
|
|
154
|
+
raise ValueError(f"only WAV audio is supported: {path} (found {wav.format})")
|
|
155
|
+
audio = wav.read(dtype="float32", always_2d=True)
|
|
156
|
+
sr = wav.samplerate
|
|
157
|
+
except (OSError, RuntimeError) as e:
|
|
158
|
+
raise ValueError(f"can't read WAV audio {path}: {e}") from e
|
|
159
|
+
_validate_audio(audio)
|
|
160
|
+
audio = audio.mean(axis=1)
|
|
161
|
+
_validate_audio(audio)
|
|
162
|
+
return audio, sr
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def track(audio: np.ndarray, sr: int) -> tuple[np.ndarray, np.ndarray]:
|
|
166
|
+
_validate_audio(audio)
|
|
167
|
+
from swift_f0 import SwiftF0
|
|
168
|
+
|
|
169
|
+
peak = float(np.max(np.abs(audio))) if audio.size else 0.0
|
|
170
|
+
if peak > 0:
|
|
171
|
+
audio = audio * (0.7 / peak) # SwiftF0 wants reasonably loud input
|
|
172
|
+
r = SwiftF0().detect(audio, sr, fmin=FMIN, fmax=FMAX)
|
|
173
|
+
f0 = np.where(r.confidence >= VOICED, r.pitch_hz, np.nan).astype(np.float64)
|
|
174
|
+
return np.asarray(r.timestamps, dtype=np.float64), f0
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def held_segments(t: np.ndarray, f0: np.ndarray) -> list[tuple[int, int]]:
|
|
178
|
+
"""Index ranges [i, j) of steadily held pitches."""
|
|
179
|
+
segs, start = [], None
|
|
180
|
+
dt = float(np.median(np.diff(t))) if len(t) > 1 else 0.016
|
|
181
|
+
|
|
182
|
+
def close(i, j):
|
|
183
|
+
if j - i >= max(1, round(MIN_NOTE / dt)):
|
|
184
|
+
segs.append((i, j))
|
|
185
|
+
|
|
186
|
+
for i in range(len(f0)):
|
|
187
|
+
if np.isnan(f0[i]):
|
|
188
|
+
if start is not None:
|
|
189
|
+
close(start, i)
|
|
190
|
+
start = None
|
|
191
|
+
continue
|
|
192
|
+
if start is None:
|
|
193
|
+
start = i
|
|
194
|
+
continue
|
|
195
|
+
recent = f0[max(start, i - 10):i]
|
|
196
|
+
if abs(1200 * np.log2(f0[i] / np.median(recent))) > SPLIT_CENTS:
|
|
197
|
+
close(start, i)
|
|
198
|
+
start = i
|
|
199
|
+
if start is not None:
|
|
200
|
+
close(start, len(f0))
|
|
201
|
+
return segs
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def estimate_sa(t: np.ndarray, f0: np.ndarray, segs: list[tuple[int, int]]) -> float:
|
|
205
|
+
"""Sa = the most-sung pitch class (beginner exercises keep returning to Sa)."""
|
|
206
|
+
idx = np.concatenate([np.arange(i, j) for i, j in segs]) if segs else np.where(~np.isnan(f0))[0]
|
|
207
|
+
if len(idx) == 0:
|
|
208
|
+
raise ValueError("no sung notes found in the recording")
|
|
209
|
+
cents = 1200 * np.log2(f0[idx] / 440.0)
|
|
210
|
+
pc = np.mod(cents, 1200)
|
|
211
|
+
hist, _ = np.histogram(pc, bins=120, range=(0, 1200))
|
|
212
|
+
smooth = np.convolve(np.tile(hist, 3), np.ones(5) / 5, mode="same")[120:240]
|
|
213
|
+
peak = (np.argmax(smooth) + 0.5) * 10
|
|
214
|
+
near = np.abs(((pc - peak + 600) % 1200) - 600) < 40
|
|
215
|
+
# Pick the octave where that pitch class is sung most.
|
|
216
|
+
octaves = np.floor((cents[near] - peak + 600) / 1200)
|
|
217
|
+
best = np.bincount((octaves - octaves.min()).astype(int)).argmax() + octaves.min()
|
|
218
|
+
chosen = near.copy()
|
|
219
|
+
chosen[near] = octaves == best
|
|
220
|
+
return float(np.median(f0[idx][chosen]))
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def name_note(cents: float, raga: str) -> tuple[str, float]:
|
|
224
|
+
best = None
|
|
225
|
+
for octave in range(-2, 3):
|
|
226
|
+
for name in RAGAS[raga]:
|
|
227
|
+
ref = SWARA_CENTS[name] + 1200 * octave
|
|
228
|
+
if best is None or abs(cents - ref) < abs(best[2]):
|
|
229
|
+
best = (name, octave, cents - ref)
|
|
230
|
+
name, octave, off = best
|
|
231
|
+
return display_name(name, octave), off
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def analyze(source: Path, sa=DEFAULT_SA, raga: str = DEFAULT_RAGA) -> Analysis:
|
|
235
|
+
"""Analyze held notes in a WAV; use None or 'auto' to estimate Sa."""
|
|
236
|
+
if raga not in RAGAS:
|
|
237
|
+
raise ValueError(f"unknown raga {raga!r}; known: {', '.join(RAGAS)}")
|
|
238
|
+
auto = sa is None or (isinstance(sa, str) and sa.strip().lower() == "auto")
|
|
239
|
+
if not auto:
|
|
240
|
+
sa_hz, sa_source = parse_sa(sa), f"shruthi {sa}"
|
|
241
|
+
audio, sr = load_audio(source)
|
|
242
|
+
t, f0 = track(audio, sr)
|
|
243
|
+
voiced = ~np.isnan(f0)
|
|
244
|
+
if not np.any(voiced):
|
|
245
|
+
raise ValueError("no sung notes found in the recording (no voiced pitch frames)")
|
|
246
|
+
if not np.all(np.isfinite(f0[voiced]) & (f0[voiced] > 0)):
|
|
247
|
+
raise ValueError("pitch tracking returned non-positive or non-finite voiced frequencies")
|
|
248
|
+
segs = held_segments(t, f0)
|
|
249
|
+
if not segs:
|
|
250
|
+
raise ValueError(f"no held notes found in the recording (need at least {MIN_NOTE:.2f} seconds of steady pitch)")
|
|
251
|
+
if auto:
|
|
252
|
+
sa_hz, sa_source = estimate_sa(t, f0, segs), "estimated from the recording"
|
|
253
|
+
|
|
254
|
+
dt = float(np.median(np.diff(t))) if len(t) > 1 else 0.016
|
|
255
|
+
notes = []
|
|
256
|
+
for i, j in segs:
|
|
257
|
+
skip = min(round(ONSET / dt), (j - i) // 3)
|
|
258
|
+
held = f0[i + skip:j]
|
|
259
|
+
c = 1200 * np.log2(held / sa_hz)
|
|
260
|
+
med = float(np.median(c))
|
|
261
|
+
swara, off = name_note(med, raga)
|
|
262
|
+
notes.append(Note(float(t[i]), float(t[j - 1]), float(sa_hz * 2 ** (med / 1200)),
|
|
263
|
+
swara, off, float(np.std(c - med))))
|
|
264
|
+
return Analysis(str(source), sa_hz, sa_source, raga, t, f0, notes)
|
carnatic_practice/cli.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
"""Command-line interface for a recorded Carnatic practice session."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import sys
|
|
7
|
+
from collections.abc import Sequence
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from . import __version__
|
|
11
|
+
from .analysis import DEFAULT_RAGA, DEFAULT_SA, RAGAS, analyze, display_name, parse_sa
|
|
12
|
+
from .reports import json_report, report
|
|
13
|
+
from .svg import render_svg
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def parser() -> argparse.ArgumentParser:
|
|
17
|
+
p = argparse.ArgumentParser(
|
|
18
|
+
prog="carnatic-practice",
|
|
19
|
+
description="Check held swaras in a WAV recording against your Sa (Shadjam).",
|
|
20
|
+
epilog="Just-intonation references are a practice aid; follow your teacher's guidance.",
|
|
21
|
+
)
|
|
22
|
+
p.add_argument("source", nargs="?", type=Path, help="practice recording (.wav or .wave)")
|
|
23
|
+
p.add_argument(
|
|
24
|
+
"--sa", default=DEFAULT_SA, metavar="NOTE_OR_HZ",
|
|
25
|
+
help="Sa as C, A#, Bb3, 130.81 Hz, or auto (default: C = C3, 130.81 Hz)",
|
|
26
|
+
)
|
|
27
|
+
p.add_argument("--raga", default=DEFAULT_RAGA, choices=RAGAS, help="reference raga (default: %(default)s)")
|
|
28
|
+
p.add_argument("--list-ragas", action="store_true", help="list supported ragas and exit")
|
|
29
|
+
p.add_argument("--format", choices=("markdown", "json"), default="markdown", help="report format (default: %(default)s)")
|
|
30
|
+
p.add_argument("-o", "--output", type=Path, help="save the report instead of printing it")
|
|
31
|
+
p.add_argument("--svg", type=Path, help="also save a standalone SVG pitch plot")
|
|
32
|
+
p.add_argument("--force", action="store_true", help="replace existing output files (never the input recording)")
|
|
33
|
+
p.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
|
|
34
|
+
return p
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def same_path(left: Path, right: Path) -> bool:
|
|
38
|
+
if left.resolve() == right.resolve():
|
|
39
|
+
return True
|
|
40
|
+
return left.exists() and right.exists() and left.samefile(right)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def validate_outputs(source: Path, outputs: list[Path], force: bool) -> None:
|
|
44
|
+
for i, output in enumerate(outputs):
|
|
45
|
+
if same_path(output, source):
|
|
46
|
+
raise ValueError("an output path refers to the input recording")
|
|
47
|
+
if any(same_path(output, other) for other in outputs[:i]):
|
|
48
|
+
raise ValueError("the report and SVG must have different output paths")
|
|
49
|
+
if output.is_symlink():
|
|
50
|
+
raise ValueError(f"refusing to write through an output symlink: {output}")
|
|
51
|
+
if output.exists() and (not output.is_file() or not force):
|
|
52
|
+
raise ValueError(f"output already exists: {output} (use --force to replace a file)")
|
|
53
|
+
if not output.parent.is_dir():
|
|
54
|
+
raise ValueError(f"output directory does not exist: {output.parent}")
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def write_output(path: Path, text: str, force: bool) -> None:
|
|
58
|
+
with path.open("w" if force else "x", encoding="utf-8", newline="\n") as f:
|
|
59
|
+
f.write(text)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
63
|
+
# Keep octave dots and accidentals readable when redirected on Windows too.
|
|
64
|
+
for stream in (sys.stdout, sys.stderr):
|
|
65
|
+
if hasattr(stream, "reconfigure"):
|
|
66
|
+
stream.reconfigure(encoding="utf-8")
|
|
67
|
+
p = parser()
|
|
68
|
+
args = p.parse_args(argv)
|
|
69
|
+
if args.list_ragas:
|
|
70
|
+
for name, swaras in RAGAS.items():
|
|
71
|
+
print(f"{name}: {' '.join(display_name(s, 0) for s in swaras)}")
|
|
72
|
+
return 0
|
|
73
|
+
if args.source is None:
|
|
74
|
+
p.error("a WAV recording is required (or use --list-ragas)")
|
|
75
|
+
|
|
76
|
+
source = args.source.expanduser()
|
|
77
|
+
output = args.output.expanduser() if args.output else None
|
|
78
|
+
svg = args.svg.expanduser() if args.svg else None
|
|
79
|
+
try:
|
|
80
|
+
if not source.is_file():
|
|
81
|
+
raise ValueError(f"recording not found or not a file: {source}")
|
|
82
|
+
if source.suffix.lower() not in {".wav", ".wave"}:
|
|
83
|
+
raise ValueError("input must be a WAV recording (.wav or .wave)")
|
|
84
|
+
sa = None if args.sa.strip().lower() == "auto" else args.sa
|
|
85
|
+
if sa is not None:
|
|
86
|
+
parse_sa(sa)
|
|
87
|
+
validate_outputs(source, [path for path in (output, svg) if path is not None], args.force)
|
|
88
|
+
except (ValueError, OSError) as e:
|
|
89
|
+
p.error(str(e))
|
|
90
|
+
|
|
91
|
+
try:
|
|
92
|
+
a = analyze(source, sa, args.raga)
|
|
93
|
+
text = json_report(a) if args.format == "json" else report(a)
|
|
94
|
+
image = render_svg(a) if svg else None
|
|
95
|
+
if output:
|
|
96
|
+
write_output(output, text, args.force)
|
|
97
|
+
else:
|
|
98
|
+
print(text, end="")
|
|
99
|
+
if svg and image is not None:
|
|
100
|
+
write_output(svg, image, args.force)
|
|
101
|
+
except (ValueError, OSError, RuntimeError, ImportError) as e:
|
|
102
|
+
print(f"error: {e}", file=sys.stderr)
|
|
103
|
+
return 1
|
|
104
|
+
except KeyboardInterrupt:
|
|
105
|
+
print("Analysis interrupted.", file=sys.stderr)
|
|
106
|
+
return 130
|
|
107
|
+
return 0
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
"""Markdown and JSON reports for held-note pitch analysis."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from dataclasses import asdict
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
|
|
10
|
+
from .analysis import IN_TUNE, RAGAS, Analysis, display_name, western
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
# --------------------------------------------------------------------------
|
|
14
|
+
# Report
|
|
15
|
+
# --------------------------------------------------------------------------
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def fmt_time(s: float) -> str:
|
|
19
|
+
return f"{int(s) // 60}:{s % 60:04.1f}"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def report(a: Analysis) -> str:
|
|
23
|
+
"""Render the pitch report as Markdown."""
|
|
24
|
+
lines = [
|
|
25
|
+
"# Pitch report",
|
|
26
|
+
"",
|
|
27
|
+
f"- Source: `{a.source}`",
|
|
28
|
+
f"- Sa: {a.sa_hz:.1f} Hz ({western(a.sa_hz)}), {a.sa_source}",
|
|
29
|
+
f"- Raga: {a.raga} ({' '.join(display_name(s, 0) for s in RAGAS[a.raga])})",
|
|
30
|
+
"- Detected with SwiftF0; reference = just-intonation ratios.",
|
|
31
|
+
"",
|
|
32
|
+
"Cents: 100 = one semitone. − is flat, + is sharp. Wobble = how much the",
|
|
33
|
+
"pitch moved while holding the note (lower is steadier).",
|
|
34
|
+
"",
|
|
35
|
+
"| Time | Swara | Hz | Off (cents) | Wobble |",
|
|
36
|
+
"|---:|:---|---:|---:|---:|",
|
|
37
|
+
]
|
|
38
|
+
for n in a.notes:
|
|
39
|
+
flag = " ⚠" if abs(n.off) > 50 else ""
|
|
40
|
+
lines.append(f"| {fmt_time(n.start)} | {n.swara} | {n.hz:.1f} | "
|
|
41
|
+
f"{n.off:+.0f}{flag} | ±{n.wobble:.0f} |")
|
|
42
|
+
|
|
43
|
+
by_swara: dict[str, list[float]] = {}
|
|
44
|
+
for n in a.notes:
|
|
45
|
+
by_swara.setdefault(n.swara, []).append(n.off)
|
|
46
|
+
order = sorted(by_swara, key=lambda s: next(c for name, c in a.swara_lines(-2400, 3600) if name == s))
|
|
47
|
+
lines += ["", "## By swara", "", "| Swara | Times | Average off | Range |", "|:---|---:|---:|---:|"]
|
|
48
|
+
for s in order:
|
|
49
|
+
v = by_swara[s]
|
|
50
|
+
lines.append(f"| {s} | {len(v)} | {np.mean(v):+.0f} | {min(v):+.0f} … {max(v):+.0f} |")
|
|
51
|
+
|
|
52
|
+
if a.notes:
|
|
53
|
+
close = sum(abs(n.off) <= IN_TUNE for n in a.notes)
|
|
54
|
+
lines += ["", "## Summary", "",
|
|
55
|
+
f"- Notes within ±{IN_TUNE} cents: {close} of {len(a.notes)}",
|
|
56
|
+
"- Average distance from the reference: "
|
|
57
|
+
f"{np.mean([abs(n.off) for n in a.notes]):.0f} cents",
|
|
58
|
+
f"- Median wobble: ±{np.median([n.wobble for n in a.notes]):.0f} cents"]
|
|
59
|
+
if any(abs(n.off) > 50 for n in a.notes):
|
|
60
|
+
lines += ["", "⚠ more than 50 cents off: either quite out of tune, or a swara "
|
|
61
|
+
"outside this raga (check `--raga`)."]
|
|
62
|
+
return "\n".join(lines) + "\n"
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def as_dict(a: Analysis) -> dict:
|
|
66
|
+
"""Return note fields and the report's summary metrics, without raw frames."""
|
|
67
|
+
by_swara: dict[str, list[float]] = {}
|
|
68
|
+
for n in a.notes:
|
|
69
|
+
by_swara.setdefault(n.swara, []).append(n.off)
|
|
70
|
+
order = sorted(by_swara, key=lambda s: next(c for name, c in a.swara_lines(-2400, 3600) if name == s))
|
|
71
|
+
return {
|
|
72
|
+
"source": a.source,
|
|
73
|
+
"sa_hz": float(a.sa_hz),
|
|
74
|
+
"sa_source": a.sa_source,
|
|
75
|
+
"raga": a.raga,
|
|
76
|
+
"reference": "just_intonation",
|
|
77
|
+
"notes": [asdict(n) for n in a.notes],
|
|
78
|
+
"summary": {
|
|
79
|
+
"notes": len(a.notes),
|
|
80
|
+
"in_tune": sum(abs(n.off) <= IN_TUNE for n in a.notes),
|
|
81
|
+
"tolerance_cents": IN_TUNE,
|
|
82
|
+
"mean_absolute_error_cents": float(np.mean([abs(n.off) for n in a.notes])) if a.notes else None,
|
|
83
|
+
"median_wobble_cents": float(np.median([n.wobble for n in a.notes])) if a.notes else None,
|
|
84
|
+
},
|
|
85
|
+
"by_swara": {
|
|
86
|
+
s: {
|
|
87
|
+
"count": len(by_swara[s]),
|
|
88
|
+
"mean_off_cents": float(np.mean(by_swara[s])),
|
|
89
|
+
"min_off_cents": float(min(by_swara[s])),
|
|
90
|
+
"max_off_cents": float(max(by_swara[s])),
|
|
91
|
+
}
|
|
92
|
+
for s in order
|
|
93
|
+
},
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def json_report(a: Analysis) -> str:
|
|
98
|
+
"""Render strict JSON with Unicode note names and no raw frame arrays."""
|
|
99
|
+
return json.dumps(as_dict(a), ensure_ascii=False, allow_nan=False, indent=2) + "\n"
|
carnatic_practice/svg.py
ADDED
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
"""Draw a median-smoothed pitch trace over octave-aware swara guide lines.
|
|
2
|
+
|
|
3
|
+
``pitch_svg`` retains the original banner/thumbnail renderer's geometry and
|
|
4
|
+
classes (``guide``, ``guide sa``, ``trace``, ``label``). ``render_svg`` adds a
|
|
5
|
+
readable heading, source, tonic and time axis for a standalone practice chart.
|
|
6
|
+
Both return self-contained SVG, with no inference or file access.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import html
|
|
12
|
+
import math
|
|
13
|
+
import warnings
|
|
14
|
+
from numbers import Integral
|
|
15
|
+
|
|
16
|
+
import numpy as np
|
|
17
|
+
|
|
18
|
+
from .analysis import ONSET, Analysis
|
|
19
|
+
|
|
20
|
+
__all__ = ["pitch_svg", "render_svg"]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _positive_int(value: int, name: str) -> int:
|
|
24
|
+
if isinstance(value, bool) or not isinstance(value, Integral) or value <= 0:
|
|
25
|
+
raise ValueError(f"{name} must be a positive integer")
|
|
26
|
+
try:
|
|
27
|
+
if not math.isfinite(float(value)):
|
|
28
|
+
raise ValueError(f"{name} must be finite")
|
|
29
|
+
except OverflowError as exc:
|
|
30
|
+
raise ValueError(f"{name} must be finite") from exc
|
|
31
|
+
return int(value)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _finite(value: float, name: str) -> float:
|
|
35
|
+
try:
|
|
36
|
+
result = float(value)
|
|
37
|
+
except (TypeError, ValueError, OverflowError) as exc:
|
|
38
|
+
raise ValueError(f"{name} must be finite") from exc
|
|
39
|
+
if not math.isfinite(result):
|
|
40
|
+
raise ValueError(f"{name} must be finite")
|
|
41
|
+
return result
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _bounds(value: tuple[float, float], limit: int, name: str) -> tuple[float, float]:
|
|
45
|
+
try:
|
|
46
|
+
first, last = value
|
|
47
|
+
except (TypeError, ValueError) as exc:
|
|
48
|
+
raise ValueError(f"{name} must contain two coordinates") from exc
|
|
49
|
+
first, last = _finite(first, name), _finite(last, name)
|
|
50
|
+
if not 0 <= first < last <= limit:
|
|
51
|
+
raise ValueError(f"{name} must increase within the canvas (0 to {limit})")
|
|
52
|
+
return first, last
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _xml(value: object) -> str:
|
|
56
|
+
# Escaping markup is not enough: XML 1.0 also forbids most control characters
|
|
57
|
+
# and lone surrogates, which can occur in user-provided source descriptions.
|
|
58
|
+
text = "".join(
|
|
59
|
+
c if (c in "\t\n\r" or 0x20 <= ord(c) <= 0xD7FF
|
|
60
|
+
or 0xE000 <= ord(c) <= 0xFFFD or 0x10000 <= ord(c) <= 0x10FFFF) else "\ufffd"
|
|
61
|
+
for c in str(value)
|
|
62
|
+
)
|
|
63
|
+
return html.escape(text)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _fit_text(value: object, width: float, font_size: float) -> str:
|
|
67
|
+
text = " ".join(str(value).split())
|
|
68
|
+
count = max(1, int(width / (font_size * 0.65)))
|
|
69
|
+
return text if len(text) <= count else text[:count - 1] + "…"
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _plot_data(
|
|
73
|
+
a: Analysis, start: float | None, end: float | None,
|
|
74
|
+
pad_cents: float, smooth_frames: int, held_only: bool,
|
|
75
|
+
) -> tuple[np.ndarray, np.ndarray, float, float, float, float]:
|
|
76
|
+
sa_hz = _finite(a.sa_hz, "Sa frequency")
|
|
77
|
+
if sa_hz <= 0:
|
|
78
|
+
raise ValueError("Sa frequency must be positive")
|
|
79
|
+
t, f0 = np.asarray(a.t, dtype=float), np.asarray(a.f0, dtype=float)
|
|
80
|
+
if t.ndim != 1 or f0.ndim != 1 or t.shape != f0.shape:
|
|
81
|
+
raise ValueError("timestamps and pitch must be matching one-dimensional arrays")
|
|
82
|
+
if not t.size:
|
|
83
|
+
raise ValueError("no voiced pitch data: the track is empty")
|
|
84
|
+
if not np.all(np.isfinite(t)) or np.any(t[1:] <= t[:-1]):
|
|
85
|
+
raise ValueError("timestamps must be finite and strictly increasing")
|
|
86
|
+
|
|
87
|
+
default_start, default_end = start is None, end is None
|
|
88
|
+
start = float(t[0]) if default_start else _finite(start, "start time")
|
|
89
|
+
end = float(t[-1]) if default_end else _finite(end, "end time")
|
|
90
|
+
# A single detected frame still makes a useful (point) chart. Only expand
|
|
91
|
+
# omitted bounds; an explicitly requested zero-length window is an error.
|
|
92
|
+
if len(t) == 1 and start == end:
|
|
93
|
+
if default_start:
|
|
94
|
+
start -= 0.5
|
|
95
|
+
if default_end:
|
|
96
|
+
end += 0.5
|
|
97
|
+
if not math.isfinite(end - start) or end <= start:
|
|
98
|
+
raise ValueError("time window must have a finite, positive duration")
|
|
99
|
+
|
|
100
|
+
keep = (t >= start) & (t <= end)
|
|
101
|
+
with np.errstate(divide="ignore", invalid="ignore", over="ignore"):
|
|
102
|
+
cents = np.asarray(a.cents(), dtype=float)
|
|
103
|
+
if cents.shape != t.shape:
|
|
104
|
+
raise ValueError("cents must have the same shape as timestamps")
|
|
105
|
+
cents = np.where(np.isfinite(f0) & (f0 > 0) & np.isfinite(cents), cents, np.nan)[keep]
|
|
106
|
+
t = t[keep]
|
|
107
|
+
if held_only:
|
|
108
|
+
held_mask = np.zeros(len(t), dtype=bool)
|
|
109
|
+
for note in a.notes:
|
|
110
|
+
if math.isfinite(note.start) and math.isfinite(note.end):
|
|
111
|
+
held_mask |= (t >= note.start + ONSET) & (t <= note.end)
|
|
112
|
+
cents = np.where(held_mask, cents, np.nan)
|
|
113
|
+
if not np.any(np.isfinite(cents)):
|
|
114
|
+
raise ValueError(f"no voiced pitch data between {start:g}s and {end:g}s")
|
|
115
|
+
|
|
116
|
+
# Preserve the original NaN-aware median smoothing, including gaps at
|
|
117
|
+
# unvoiced frames. Larger windows need no more than the complete track.
|
|
118
|
+
half = min(smooth_frames // 2, len(cents) - 1)
|
|
119
|
+
windows = np.lib.stride_tricks.sliding_window_view(
|
|
120
|
+
np.pad(cents, half, constant_values=np.nan), 2 * half + 1,
|
|
121
|
+
)
|
|
122
|
+
with warnings.catch_warnings():
|
|
123
|
+
warnings.simplefilter("ignore", RuntimeWarning) # all-NaN windows
|
|
124
|
+
smooth = np.where(np.isfinite(cents), np.nanmedian(windows, axis=1), np.nan)
|
|
125
|
+
|
|
126
|
+
# Held-note pitches define the useful range, as in the original renderer;
|
|
127
|
+
# otherwise use robust percentiles of the voiced trace.
|
|
128
|
+
held = [
|
|
129
|
+
1200 * (math.log2(note.hz) - math.log2(sa_hz))
|
|
130
|
+
for note in a.notes
|
|
131
|
+
if start <= note.start <= end and math.isfinite(note.hz) and note.hz > 0
|
|
132
|
+
]
|
|
133
|
+
if not held:
|
|
134
|
+
held = list(np.percentile(smooth[np.isfinite(smooth)], [5, 95]))
|
|
135
|
+
lo, hi = float(min(held) - pad_cents), float(max(held) + pad_cents)
|
|
136
|
+
if lo == hi:
|
|
137
|
+
lo, hi = lo - 50, hi + 50
|
|
138
|
+
if not math.isfinite(lo) or not math.isfinite(hi) or not math.isfinite(hi - lo) or hi <= lo:
|
|
139
|
+
raise ValueError("pitch range must have a finite, positive span")
|
|
140
|
+
return t, smooth, start, end, lo, hi
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _render(
|
|
144
|
+
a: Analysis, start: float | None, end: float | None, *,
|
|
145
|
+
width: int, height: int, x_range: tuple[float, float], y_range: tuple[float, float],
|
|
146
|
+
pad_cents: float, smooth_frames: int, labels: str | None, held_only: bool,
|
|
147
|
+
heading: bool = False,
|
|
148
|
+
) -> str:
|
|
149
|
+
width, height = _positive_int(width, "width"), _positive_int(height, "height")
|
|
150
|
+
(x0, x1), (y_top, y_bottom) = _bounds(x_range, width, "x_range"), _bounds(y_range, height, "y_range")
|
|
151
|
+
pad_cents = _finite(pad_cents, "pad_cents")
|
|
152
|
+
if pad_cents < 0:
|
|
153
|
+
raise ValueError("pad_cents must be non-negative")
|
|
154
|
+
smooth_frames = _positive_int(smooth_frames, "smooth_frames")
|
|
155
|
+
if labels not in (None, "sa", "all"):
|
|
156
|
+
raise ValueError('labels must be None, "sa", or "all"')
|
|
157
|
+
t, smooth, start, end, lo, hi = _plot_data(a, start, end, pad_cents, smooth_frames, held_only)
|
|
158
|
+
|
|
159
|
+
def x(seconds: float) -> float:
|
|
160
|
+
return _finite(x0 + (seconds - start) / (end - start) * (x1 - x0), "x coordinate")
|
|
161
|
+
|
|
162
|
+
def y(cents: float) -> float:
|
|
163
|
+
return _finite(y_bottom - (cents - lo) / (hi - lo) * (y_bottom - y_top), "y coordinate")
|
|
164
|
+
|
|
165
|
+
scale = min(1.0, width / (480 if heading else 160), height / (240 if heading else 80))
|
|
166
|
+
font_size, margin = 13 * scale, 8 * scale
|
|
167
|
+
parts = [
|
|
168
|
+
f'<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="{height}" '
|
|
169
|
+
f'viewBox="0 0 {width} {height}" role="img" aria-labelledby="pitch-title pitch-description" '
|
|
170
|
+
'style="font-family:system-ui,sans-serif;background:#f8fafc">',
|
|
171
|
+
f'<title id="pitch-title">Pitch trace — {_xml(a.source)}</title>',
|
|
172
|
+
f'<desc id="pitch-description">{_xml(a.raga)} pitch relative to Sa {_xml(f"{a.sa_hz:.2f}")} Hz '
|
|
173
|
+
f'({_xml(a.sa_source)}), from {start:g} to {end:g} seconds. '
|
|
174
|
+
'The blue trace shows sung pitch; gaps are unvoiced. Swara guides use dots above or below '
|
|
175
|
+
'the name for upper or lower octaves.</desc>',
|
|
176
|
+
f'<rect class="background" width="{width}" height="{height}" style="fill:#f8fafc"/>',
|
|
177
|
+
'<defs><clipPath id="pitch-plot-clip">'
|
|
178
|
+
f'<rect x="{x0:g}" y="{y_top:g}" width="{x1 - x0:g}" height="{y_bottom - y_top:g}"/>'
|
|
179
|
+
'</clipPath></defs>',
|
|
180
|
+
]
|
|
181
|
+
if heading:
|
|
182
|
+
for cls, value, baseline, size, color in (
|
|
183
|
+
("heading", f"Pitch practice · {a.raga}", 28, 20, "#0f172a"),
|
|
184
|
+
("source", f"Source: {a.source}", 50, 13, "#475569"),
|
|
185
|
+
("tonic", f"Sa: {a.sa_hz:.2f} Hz · {a.sa_source}", 70, 13, "#475569"),
|
|
186
|
+
):
|
|
187
|
+
text = _fit_text(value, width - x0 - margin, size * scale)
|
|
188
|
+
parts.append(
|
|
189
|
+
f'<text class="{cls}" x="{x0:g}" y="{baseline * scale:g}" '
|
|
190
|
+
f'style="fill:{color};font-size:{size * scale:g}px">{_xml(text)}</text>'
|
|
191
|
+
)
|
|
192
|
+
|
|
193
|
+
try:
|
|
194
|
+
guides = a.swara_lines(lo, hi)
|
|
195
|
+
except KeyError as exc:
|
|
196
|
+
raise ValueError(f"unknown raga: {a.raga!r}") from exc
|
|
197
|
+
for name, cents in guides:
|
|
198
|
+
if not math.isfinite(cents) or not lo <= cents <= hi:
|
|
199
|
+
continue
|
|
200
|
+
is_sa = cents % 1200 == 0
|
|
201
|
+
cls, color = ("guide sa", "#64748b") if is_sa else ("guide", "#cbd5e1")
|
|
202
|
+
yy = y(cents)
|
|
203
|
+
parts.append(
|
|
204
|
+
f'<line class="{cls}" x1="0" x2="{width}" y1="{yy:.3f}" y2="{yy:.3f}" '
|
|
205
|
+
f'style="stroke:{color};stroke-width:{1.2 if is_sa else 1};fill:none"/>'
|
|
206
|
+
)
|
|
207
|
+
if labels == "all" or (labels == "sa" and is_sa):
|
|
208
|
+
label = _fit_text(name, width - 2 * margin, font_size)
|
|
209
|
+
label_width = len(label) * font_size * 0.65
|
|
210
|
+
label_x, anchor = x1 + 14 * scale, "start"
|
|
211
|
+
if label_x + label_width > width - margin:
|
|
212
|
+
label_x, anchor = width - margin, "end"
|
|
213
|
+
label_y = min(height - font_size * 0.75, max(font_size * 0.75, yy))
|
|
214
|
+
parts.append(
|
|
215
|
+
f'<text class="label{" sa" if is_sa else ""}" x="{label_x:g}" y="{label_y:.3f}" '
|
|
216
|
+
f'text-anchor="{anchor}" dominant-baseline="middle" '
|
|
217
|
+
f'style="fill:#334155;font-size:{font_size:g}px;'
|
|
218
|
+
f'font-weight:{600 if is_sa else 400}">{_xml(label)}</text>'
|
|
219
|
+
)
|
|
220
|
+
|
|
221
|
+
# Downsample each voiced run, not the whole array: otherwise a one-frame
|
|
222
|
+
# gap at an odd index disappears. Keep run endpoints and singleton points.
|
|
223
|
+
path = []
|
|
224
|
+
voiced = np.flatnonzero(np.isfinite(smooth))
|
|
225
|
+
runs = np.split(voiced, np.flatnonzero(np.diff(voiced) > 1) + 1)
|
|
226
|
+
for run in runs:
|
|
227
|
+
sampled = run[::2]
|
|
228
|
+
if sampled[-1] != run[-1]:
|
|
229
|
+
sampled = np.append(sampled, run[-1])
|
|
230
|
+
previous, segment_size, point = None, 0, ""
|
|
231
|
+
for index in sampled:
|
|
232
|
+
cents = float(smooth[index])
|
|
233
|
+
if previous is None or abs(cents - previous) >= 150:
|
|
234
|
+
if segment_size == 1:
|
|
235
|
+
path.append(f"L{point}") # a round-capped visible singleton
|
|
236
|
+
command, segment_size = "M", 1
|
|
237
|
+
else:
|
|
238
|
+
command, segment_size = "L", segment_size + 1
|
|
239
|
+
point = f"{x(float(t[index])):.3f},{y(cents):.3f}"
|
|
240
|
+
path.append(f"{command}{point}")
|
|
241
|
+
previous = cents
|
|
242
|
+
if segment_size == 1:
|
|
243
|
+
path.append(f"L{point}")
|
|
244
|
+
parts.append(
|
|
245
|
+
f'<path class="trace" d="{" ".join(path)}" clip-path="url(#pitch-plot-clip)" '
|
|
246
|
+
'style="fill:none;stroke:#2563eb;stroke-width:2.2;stroke-linecap:round;stroke-linejoin:round"/>'
|
|
247
|
+
)
|
|
248
|
+
if heading:
|
|
249
|
+
for fraction in (0.0, 0.25, 0.5, 0.75, 1.0):
|
|
250
|
+
seconds = start + (end - start) * fraction
|
|
251
|
+
xx = x(seconds)
|
|
252
|
+
parts.append(
|
|
253
|
+
f'<line class="tick" x1="{xx:.3f}" x2="{xx:.3f}" y1="{y_bottom:g}" '
|
|
254
|
+
f'y2="{y_bottom + 5 * scale:g}" style="stroke:#64748b;stroke-width:1"/>'
|
|
255
|
+
)
|
|
256
|
+
parts.append(
|
|
257
|
+
f'<text class="time-label" x="{xx:.3f}" y="{y_bottom + 22 * scale:g}" '
|
|
258
|
+
f'text-anchor="middle" style="fill:#475569;font-size:{11 * scale:g}px">'
|
|
259
|
+
f'{seconds:g}s</text>'
|
|
260
|
+
)
|
|
261
|
+
parts.append("</svg>")
|
|
262
|
+
return "\n".join(parts)
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def pitch_svg(
|
|
266
|
+
a: Analysis, start: float | None, end: float | None, *,
|
|
267
|
+
width: int, height: int, x_range: tuple[float, float], y_range: tuple[float, float],
|
|
268
|
+
pad_cents: float = 150, smooth_frames: int = 7, labels: str | None = None,
|
|
269
|
+
held_only: bool = False,
|
|
270
|
+
) -> str:
|
|
271
|
+
"""Draw a pitch window in the supplied canvas and plot coordinates.
|
|
272
|
+
|
|
273
|
+
``None`` bounds select the full recording. ``labels`` is ``None``, ``"sa"``
|
|
274
|
+
or ``"all"``. ``held_only`` omits the first ``ONSET`` seconds of each note.
|
|
275
|
+
Guides span the canvas; trace coordinates use ``x_range`` and ``y_range``.
|
|
276
|
+
Invalid dimensions, ranges, windows, or absence of voiced data raise
|
|
277
|
+
``ValueError``. A single-frame track gets a one-second default window.
|
|
278
|
+
"""
|
|
279
|
+
return _render(
|
|
280
|
+
a, start, end, width=width, height=height, x_range=x_range, y_range=y_range,
|
|
281
|
+
pad_cents=pad_cents, smooth_frames=smooth_frames, labels=labels, held_only=held_only,
|
|
282
|
+
)
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def render_svg(a: Analysis, width: int = 1200, height: int = 400) -> str:
|
|
286
|
+
"""Return a standalone, accessible SVG practice chart of the whole track.
|
|
287
|
+
|
|
288
|
+
Includes inline styling, background, swara/octave labels, source, tonic and
|
|
289
|
+
seconds along the time axis. No assets or fonts are fetched externally.
|
|
290
|
+
Raises ``ValueError`` for invalid inputs or a track without voiced data.
|
|
291
|
+
"""
|
|
292
|
+
width, height = _positive_int(width, "width"), _positive_int(height, "height")
|
|
293
|
+
scale = min(1.0, width / 480, height / 240)
|
|
294
|
+
return _render(
|
|
295
|
+
a, None, None, width=width, height=height,
|
|
296
|
+
x_range=(52 * scale, width - 76 * scale), y_range=(96 * scale, height - 44 * scale),
|
|
297
|
+
pad_cents=150, smooth_frames=7, labels="all", held_only=False, heading=True,
|
|
298
|
+
)
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: carnatic-practice
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: An offline pitch-practice companion for Carnatic music learners
|
|
5
|
+
Project-URL: Homepage, https://github.com/baijum/carnatic-practice
|
|
6
|
+
Project-URL: Repository, https://github.com/baijum/carnatic-practice
|
|
7
|
+
Project-URL: Issues, https://github.com/baijum/carnatic-practice/issues
|
|
8
|
+
Author: Baiju Muthukadan
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
License-File: THIRD_PARTY_NOTICES.md
|
|
12
|
+
Keywords: audio,carnatic,music,pitch,practice,swara
|
|
13
|
+
Classifier: Development Status :: 3 - Alpha
|
|
14
|
+
Classifier: Environment :: Console
|
|
15
|
+
Classifier: Intended Audience :: Education
|
|
16
|
+
Classifier: Operating System :: OS Independent
|
|
17
|
+
Classifier: Programming Language :: Python :: 3
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
22
|
+
Classifier: Topic :: Education
|
|
23
|
+
Classifier: Topic :: Multimedia :: Sound/Audio :: Analysis
|
|
24
|
+
Requires-Python: >=3.11
|
|
25
|
+
Requires-Dist: numpy>=2
|
|
26
|
+
Requires-Dist: soundfile>=0.12
|
|
27
|
+
Requires-Dist: soxr>=0.3
|
|
28
|
+
Requires-Dist: swift-f0<0.4,>=0.3
|
|
29
|
+
Provides-Extra: dev
|
|
30
|
+
Requires-Dist: build>=1.2; extra == 'dev'
|
|
31
|
+
Requires-Dist: pytest>=8; extra == 'dev'
|
|
32
|
+
Requires-Dist: ruff>=0.9; extra == 'dev'
|
|
33
|
+
Requires-Dist: twine>=6; extra == 'dev'
|
|
34
|
+
Description-Content-Type: text/markdown
|
|
35
|
+
|
|
36
|
+
# carnatic-practice
|
|
37
|
+
|
|
38
|
+
An offline command-line companion for Carnatic music learners. Give it a WAV
|
|
39
|
+
recording and your **Sa (Shadjam / shruthi)**; it detects held notes and reports
|
|
40
|
+
how their pitch compares with the swaras of your chosen raga.
|
|
41
|
+
|
|
42
|
+
Adapted from the practice-analysis tools developed for
|
|
43
|
+
[NaadamToRaagam](https://github.com/baijum/NaadamToRaagam). Pitch detection uses
|
|
44
|
+
[SwiftF0](https://github.com/lars76/swift-f0).
|
|
45
|
+
|
|
46
|
+
## Install
|
|
47
|
+
|
|
48
|
+
Requires **Python 3.11 or later**.
|
|
49
|
+
|
|
50
|
+
```sh
|
|
51
|
+
pip install carnatic-practice
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
For an isolated CLI installation, use `pipx install carnatic-practice` or
|
|
55
|
+
`uv tool install carnatic-practice` instead. Python dependencies and the SwiftF0
|
|
56
|
+
model are installed with the package dependencies. Analysis runs locally: no
|
|
57
|
+
recording is uploaded, and no account or API key is required.
|
|
58
|
+
|
|
59
|
+
## Quick start
|
|
60
|
+
|
|
61
|
+
```sh
|
|
62
|
+
# Default Sa: C3 (130.81 Hz); default raga: Mayamalavagowla.
|
|
63
|
+
carnatic-practice practice.wav
|
|
64
|
+
|
|
65
|
+
# Quote a tonic containing a sharp or a flat.
|
|
66
|
+
carnatic-practice practice.wav --sa 'A#'
|
|
67
|
+
carnatic-practice practice.wav --sa Bb3 --raga mohanam
|
|
68
|
+
|
|
69
|
+
# An explicit octave or a measured frequency in Hz.
|
|
70
|
+
carnatic-practice practice.wav --sa C4
|
|
71
|
+
carnatic-practice practice.wav --sa 130.81
|
|
72
|
+
|
|
73
|
+
# Save the report and a standalone SVG pitch plot.
|
|
74
|
+
carnatic-practice practice.wav --sa C --output report.md --svg pitch.svg
|
|
75
|
+
|
|
76
|
+
# Machine-readable report, or a list of supported ragas.
|
|
77
|
+
carnatic-practice practice.wav --format json > report.json
|
|
78
|
+
carnatic-practice --list-ragas
|
|
79
|
+
|
|
80
|
+
# Opt in to the original most-sung-pitch tonic estimator.
|
|
81
|
+
carnatic-practice practice.wav --sa auto
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
`python -m carnatic_practice` is equivalent to `carnatic-practice`.
|
|
85
|
+
|
|
86
|
+
### Choosing Sa
|
|
87
|
+
|
|
88
|
+
A bare note such as `C`, `A#`, or `Bb` selects its frequency in the range
|
|
89
|
+
**100–200 Hz**, preserving the original analyzer's convention. In particular,
|
|
90
|
+
`C` means **C3**, not C4. Give an octave (`C4`, `A#2`, `Bb3`) or a positive
|
|
91
|
+
frequency (`130.81`) when you need a different register or a more precise tonic.
|
|
92
|
+
Unicode accidentals (`C♯3`, `B♭2`) are also accepted. Western note names use
|
|
93
|
+
A4 = 440 Hz; swara targets are relative to the supplied Sa.
|
|
94
|
+
|
|
95
|
+
`--sa auto` assumes that the most-sung pitch class, in its most-sung octave, is
|
|
96
|
+
Sa. This is a simple beginner-exercise heuristic, **not** a dedicated tonic
|
|
97
|
+
recognizer. Supplying your actual shruthi is more reliable.
|
|
98
|
+
|
|
99
|
+
### Supported ragas
|
|
100
|
+
|
|
101
|
+
| CLI name | Swaras above Sa |
|
|
102
|
+
|---|---|
|
|
103
|
+
| `mayamalavagowla` (default) | Sa Ri1 Ga3 Ma1 Pa Da1 Ni3 |
|
|
104
|
+
| `shankarabharanam` | Sa Ri2 Ga3 Ma1 Pa Da2 Ni3 |
|
|
105
|
+
| `kalyani` | Sa Ri2 Ga3 Ma2 Pa Da2 Ni3 |
|
|
106
|
+
| `kharaharapriya` | Sa Ri2 Ga2 Ma1 Pa Da2 Ni2 |
|
|
107
|
+
| `harikambhoji` | Sa Ri2 Ga3 Ma1 Pa Da2 Ni2 |
|
|
108
|
+
| `mohanam` | Sa Ri2 Ga3 Pa Da2 |
|
|
109
|
+
| `hamsadhwani` | Sa Ri2 Ga3 Pa Ni3 |
|
|
110
|
+
| `chromatic` | All 12 reference swarasthanas |
|
|
111
|
+
|
|
112
|
+
The analyzer assigns each held note to the **nearest allowed swara**, across
|
|
113
|
+
octaves. It does not recognize the raga, know which note you intended to sing,
|
|
114
|
+
or align your recording to an exercise. Select the raga you practiced.
|
|
115
|
+
|
|
116
|
+
## Understanding the report
|
|
117
|
+
|
|
118
|
+
The default Markdown report includes each held note's time, swara, frequency,
|
|
119
|
+
pitch error in **cents**, and wobble, followed by per-swara and session summaries.
|
|
120
|
+
|
|
121
|
+
- **100 cents** is one semitone. Negative error is flat; positive error is sharp.
|
|
122
|
+
- **Wobble** is the standard deviation of pitch in cents during the held portion
|
|
123
|
+
of a note, after the initial slide-in is skipped. It is not a musical quality score.
|
|
124
|
+
- The summary counts notes within **±20 cents** of the reference. A warning marks
|
|
125
|
+
notes more than 50 cents away; also check your chosen raga and Sa in that case.
|
|
126
|
+
- A dot above a swara means an upper octave (`Ṡa`); a dot below means a lower
|
|
127
|
+
octave (`Ṇi`). The raga determines the variant, so display labels omit numbers.
|
|
128
|
+
|
|
129
|
+
`--format json` includes `source`, `sa_hz`, `sa_source`, `raga`, `reference`,
|
|
130
|
+
`notes`, `by_swara`, and `summary`. Note objects contain `start`, `end` (seconds),
|
|
131
|
+
`hz`, `swara`, `off` (cents), and `wobble` (cents). Raw frame-by-frame pitch arrays
|
|
132
|
+
are available through the Python API rather than included in every JSON report.
|
|
133
|
+
|
|
134
|
+
By default the report goes to standard output. `--output PATH` saves it instead.
|
|
135
|
+
`--svg PATH` additionally writes a self-contained pitch plot that can be opened
|
|
136
|
+
in a browser. Parent directories must already exist. Existing output files are
|
|
137
|
+
not replaced unless `--force` is supplied; the input recording, symlink outputs,
|
|
138
|
+
and conflicting report/plot paths are always protected.
|
|
139
|
+
|
|
140
|
+
### Recording tips and limitations
|
|
141
|
+
|
|
142
|
+
- Use a **WAV** file (`.wav` or `.wave`). Mono and multichannel WAVs are supported;
|
|
143
|
+
channels are averaged to mono. Export Audacity projects to WAV first.
|
|
144
|
+
- Use a clear, single melodic voice, with little background noise. A tanpura,
|
|
145
|
+
accompaniment, or another singer can confuse the pitch detector; it does not
|
|
146
|
+
separate sources.
|
|
147
|
+
- Hold practice swaras for at least about **0.3 seconds**, preferably longer.
|
|
148
|
+
Short blips are ignored and the beginning of each held note is skipped to
|
|
149
|
+
reduce the effect of sliding into it.
|
|
150
|
+
- The inherited detector range is **60–800 Hz**. Notes outside this range may be
|
|
151
|
+
missed; supplying a high Sa does not increase the detection range.
|
|
152
|
+
- Swara targets use rounded **just-intonation reference offsets**, not an
|
|
153
|
+
authoritative tuning system. Intonation varies by raga, phrase, and tradition.
|
|
154
|
+
Gamakas, expressive movement, and exercise correctness are not assessed.
|
|
155
|
+
- Use the results to choose one or two things to practice, not to grade musical
|
|
156
|
+
expression. Follow your teacher's guidance.
|
|
157
|
+
|
|
158
|
+
Invalid command arguments return exit status 2. Audio/analysis or output-writing
|
|
159
|
+
failures return 1; a successful report returns 0.
|
|
160
|
+
|
|
161
|
+
## Python API
|
|
162
|
+
|
|
163
|
+
```python
|
|
164
|
+
from pathlib import Path
|
|
165
|
+
from carnatic_practice.analysis import analyze
|
|
166
|
+
from carnatic_practice.reports import report
|
|
167
|
+
|
|
168
|
+
analysis = analyze(Path("practice.wav"), sa="C", raga="mayamalavagowla")
|
|
169
|
+
print(report(analysis))
|
|
170
|
+
# analysis.t and analysis.f0 contain frame timestamps and pitch (NaN if unvoiced).
|
|
171
|
+
# Use sa=None for explicit automatic tonic estimation.
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
## Development
|
|
175
|
+
|
|
176
|
+
```sh
|
|
177
|
+
uv sync --extra dev
|
|
178
|
+
uv run pytest
|
|
179
|
+
uv run ruff check .
|
|
180
|
+
uv build
|
|
181
|
+
uv run twine check --strict dist/*
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
Tests synthesize their own audio; no practice recordings are included. Integration
|
|
185
|
+
tests run the real SwiftF0 detector. Use `uv run pytest -m 'not integration'` for
|
|
186
|
+
unit tests only.
|
|
187
|
+
|
|
188
|
+
### Releases
|
|
189
|
+
|
|
190
|
+
CI runs tests, lint, and distribution checks. Publication uses GitHub's OpenID
|
|
191
|
+
Connect identity through a PyPI trusted publisher; no upload token is stored in
|
|
192
|
+
the repository.
|
|
193
|
+
|
|
194
|
+
For the first release, the PyPI account owner must add a **pending publisher** at
|
|
195
|
+
<https://pypi.org/manage/account/publishing/> with these exact values:
|
|
196
|
+
|
|
197
|
+
- PyPI project name: `carnatic-practice`
|
|
198
|
+
- GitHub owner: `baijum`
|
|
199
|
+
- Repository: `carnatic-practice`
|
|
200
|
+
- Workflow filename: `publish.yml`
|
|
201
|
+
- GitHub environment: `pypi`
|
|
202
|
+
|
|
203
|
+
After configuring it, publish a GitHub release whose tag matches the package
|
|
204
|
+
version (for example, `v0.1.0`). The release workflow tests and builds the package,
|
|
205
|
+
then publishes the checked distributions from the `pypi` environment. PyPI
|
|
206
|
+
versions are immutable: increment `__version__` for every subsequent release.
|
|
207
|
+
|
|
208
|
+
## License
|
|
209
|
+
|
|
210
|
+
[MIT](LICENSE). See [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md) for attribution
|
|
211
|
+
and dependency notices.
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
carnatic_practice/__init__.py,sha256=2eLfC9ipe5X1P1xIxtATZjdOqoBRBhdbnUnpTOWJ43U,94
|
|
2
|
+
carnatic_practice/__main__.py,sha256=k1ocEWawweo1qCJWNFAAvyxz3tcY13dzvCenHszij30,48
|
|
3
|
+
carnatic_practice/analysis.py,sha256=iRusdsJ_3Z2lCsvY1481aixPNUb8zm8pkOXP8uCV2Lk,10205
|
|
4
|
+
carnatic_practice/cli.py,sha256=NFju2tH_0kYFn3dib-9xfofgaOemtYfMDg3mlrPcWno,4695
|
|
5
|
+
carnatic_practice/reports.py,sha256=WZpv55Ok4Z37a3rj8KQcnghzMnjvZ78NjPIHRuJZs4U,3962
|
|
6
|
+
carnatic_practice/svg.py,sha256=WjB4Xrd7H0dhegOXbHxYMkxks74hxNONOtL_2szZfu4,13731
|
|
7
|
+
carnatic_practice-0.1.0.dist-info/METADATA,sha256=loTNU_j7sWbGTzP8EFjlOfsa9N0aPRlYkN42HB8T2SU,8687
|
|
8
|
+
carnatic_practice-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
9
|
+
carnatic_practice-0.1.0.dist-info/entry_points.txt,sha256=wasTzeQ7J8UtbTjU016cDw3aIo5LzeiOaTsQRCpQx5c,65
|
|
10
|
+
carnatic_practice-0.1.0.dist-info/licenses/LICENSE,sha256=aRG4ocFYaTwMUMKiuL5uT-AUU4DgOAo6YPDAZa7dr04,1073
|
|
11
|
+
carnatic_practice-0.1.0.dist-info/licenses/THIRD_PARTY_NOTICES.md,sha256=8TW-WQKku0CG-8ZNZV7D1SeltC6K1ScrtOlksuIKur8,1838
|
|
12
|
+
carnatic_practice-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Baiju Muthukadan
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
# Third-party notices
|
|
2
|
+
|
|
3
|
+
The analysis and SVG rendering code was adapted from the author's
|
|
4
|
+
[NaadamToRaagam](https://github.com/baijum/NaadamToRaagam) practice-analysis
|
|
5
|
+
scripts. This standalone package does not include that project's recordings,
|
|
6
|
+
episode content, or production tools.
|
|
7
|
+
|
|
8
|
+
Pitch detection uses [SwiftF0](https://github.com/lars76/swift-f0), by Lars
|
|
9
|
+
Nieradzik. SwiftF0 is installed as a separate dependency; its implementation and
|
|
10
|
+
model are not bundled in the `carnatic-practice` wheel or source distribution.
|
|
11
|
+
SwiftF0 is MIT-licensed. Its notice is reproduced here for attribution:
|
|
12
|
+
|
|
13
|
+
> MIT License
|
|
14
|
+
>
|
|
15
|
+
> Copyright (c) 2025-2026 Lars Nieradzik
|
|
16
|
+
>
|
|
17
|
+
> Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
18
|
+
> of this software and associated documentation files (the "Software"), to deal
|
|
19
|
+
> in the Software without restriction, including without limitation the rights
|
|
20
|
+
> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
21
|
+
> copies of the Software, and to permit persons to whom the Software is
|
|
22
|
+
> furnished to do so, subject to the following conditions:
|
|
23
|
+
>
|
|
24
|
+
> The above copyright notice and this permission notice shall be included in all
|
|
25
|
+
> copies or substantial portions of the Software.
|
|
26
|
+
>
|
|
27
|
+
> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
28
|
+
> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
29
|
+
> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
30
|
+
> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
31
|
+
> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
32
|
+
> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
33
|
+
> SOFTWARE.
|
|
34
|
+
|
|
35
|
+
NumPy, SoundFile, soxr, ONNX Runtime, and other transitive dependencies retain
|
|
36
|
+
their own licenses, distributed with those packages.
|