-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathchords.py
More file actions
1825 lines (1663 loc) · 74.3 KB
/
Copy pathchords.py
File metadata and controls
1825 lines (1663 loc) · 74.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# chords.py
import numpy as np
import librosa
import soundfile as sf
import vamp # from vamphost
# Enharmonic naming: choose sharps or flats later based on key context
SHARP_NAMES = ["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"]
FLAT_NAMES = ["C","Db","D","Eb","E","F","Gb","G","Ab","A","Bb","B"]
def chord_templates():
"""Return normalized templates for: 12 maj, 12 min, 12 dom7, 12 maj7, 12 min7.
Shapes returned as a tuple of 5 arrays, each (12, 12): maj, min, dom7, maj7, min7.
"""
maj = np.zeros((12, 12), dtype=float)
mino = np.zeros((12, 12), dtype=float)
dom7 = np.zeros((12, 12), dtype=float)
maj7 = np.zeros((12, 12), dtype=float)
min7 = np.zeros((12, 12), dtype=float)
for root in range(12):
# Triads
for t in (0, 4, 7): # major triad
maj[root, (root + t) % 12] = 1
for t in (0, 3, 7): # minor triad
mino[root, (root + t) % 12] = 1
# 7th chords
for t in (0, 4, 7, 10): # dominant 7th (1,3,5,b7)
dom7[root, (root + t) % 12] = 1
for t in (0, 4, 7, 11): # major 7th (1,3,5,7)
maj7[root, (root + t) % 12] = 1
for t in (0, 3, 7, 10): # minor 7th (1,b3,5,b7)
min7[root, (root + t) % 12] = 1
# L2 normalize each row so template matching is cosine-like
for M in (maj, mino, dom7, maj7, min7):
M /= np.linalg.norm(M, axis=1, keepdims=True) + 1e-12
return maj, mino, dom7, maj7, min7
def chord_likelihoods(chroma):
maj, mino, dom7, maj7, min7 = chord_templates()
chroma_n = chroma / (np.linalg.norm(chroma, axis=0, keepdims=True) + 1e-12)
maj_scores = maj @ chroma_n # (12,T)
min_scores = mino @ chroma_n # (12,T)
dom7_scores = dom7 @ chroma_n # (12,T)
maj7_scores = maj7 @ chroma_n # (12,T)
min7_scores = min7 @ chroma_n # (12,T)
return np.vstack([maj_scores, min_scores, dom7_scores, maj7_scores, min7_scores]) # (60,T)
# --- Key estimation (Krumhansl-Schmuckler profiles) and naming helpers ---
_MAJOR_PROFILE = np.array([6.35,2.23,3.48,2.33,4.38,4.09,2.52,5.19,2.39,3.66,2.29,2.88])
_MINOR_PROFILE = np.array([6.33,2.68,3.52,5.38,2.60,3.53,2.54,4.75,3.98,2.69,3.34,3.17])
def _estimate_key_from_chroma(chroma):
"""Return (tonic_idx, mode) with mode in {"maj","min"}.
Base: Krumhansl–Schmuckler profile correlation on time-averaged chroma.
Enhancement: add a small bias toward MAJOR keys whose I/IV/V pitch-class energy is strong
(computed from per-class maxima across time). This helps disambiguate A major vs C# minor, etc.
"""
if chroma.ndim != 2 or chroma.shape[0] != 12:
# Fallback to a safe default
return 0, "maj"
chroma_mean = chroma.mean(axis=1)
if np.allclose(chroma_mean.sum(), 0):
return 0, "maj" # default C major if silence
chroma_vec = chroma_mean / (np.linalg.norm(chroma_mean) + 1e-9)
# Base profile correlation for all 24 keys
maj_scores = np.zeros(12, dtype=float)
min_scores = np.zeros(12, dtype=float)
profM = _MAJOR_PROFILE / np.linalg.norm(_MAJOR_PROFILE)
profm = _MINOR_PROFILE / np.linalg.norm(_MINOR_PROFILE)
for k in range(12):
maj_scores[k] = float(np.dot(chroma_vec, np.roll(profM, k)))
min_scores[k] = float(np.dot(chroma_vec, np.roll(profm, k)))
# Cadence bias based on per-pitch-class maxima (robust to sparse textures)
pc_max = chroma.max(axis=1)
if pc_max.sum() > 1e-12:
pc_max = pc_max / (np.linalg.norm(pc_max) + 1e-12)
cadence = np.zeros(12, dtype=float)
for k in range(12):
I = k % 12; IV = (k + 5) % 12; V = (k + 7) % 12
cadence[k] = pc_max[I] + pc_max[IV] + pc_max[V]
# Normalize cadence to [0,1]
cmin, cmax = float(cadence.min()), float(cadence.max())
if cmax > cmin:
cadence = (cadence - cmin) / (cmax - cmin)
# Small weight keeps profile correlation dominant but nudges toward clear I/IV/V
gamma = 0.15
maj_scores = maj_scores + gamma * cadence
# Choose best over 24 keys
k_maj = int(np.argmax(maj_scores))
k_min = int(np.argmax(min_scores))
best_maj = float(maj_scores[k_maj])
best_min = float(min_scores[k_min])
if best_maj >= best_min:
return k_maj, "maj"
else:
# If minor wins but its relative MAJOR has a much stronger cadence, flip to MAJOR
rel_maj = (k_min + 3) % 12
rel_maj_score = float(maj_scores[rel_maj])
if rel_maj_score >= best_min + 0.05:
return rel_maj, "maj"
return k_min, "min"
# Major flat keys: F, Bb, Eb, Ab, Db, Gb, Cb -> indices {5,10,3,8,1,6,11}
_FLAT_MAJOR_TONICS = {5, 10, 3, 8, 1, 6, 11}
def _use_flats_for_key(tonic_idx: int, mode: str) -> bool:
"""Return True if we should prefer flat spellings for this key."""
if mode == "min":
# Relative major is +3 semitones from minor tonic
tonic_idx = (tonic_idx + 3) % 12
return tonic_idx in _FLAT_MAJOR_TONICS
def _pc_name(pc: int, use_flats: bool) -> str:
return FLAT_NAMES[pc] if use_flats else SHARP_NAMES[pc]
# --- Key hint parser ---
def _parse_key_hint(key_hint) -> tuple[int | None, str | None]:
"""Return (tonic_idx, mode) from a flexible key_hint dict.
Accepts keys like: 'tonic_idx' (int), 'tonic_name'/'tonic' (str), and 'mode'/'scale' ('maj'/'major'/'min'/'minor').
Returns (None, None) if unusable.
"""
if not isinstance(key_hint, dict):
return None, None
tonic_idx = None
mode = None
try:
if 'tonic_idx' in key_hint and key_hint['tonic_idx'] is not None:
tonic_idx = int(key_hint['tonic_idx']) % 12
else:
name = key_hint.get('tonic_name') or key_hint.get('tonic')
if isinstance(name, str):
lookup = {
'C':0,'C#':1,'Db':1,'D':2,'D#':3,'Eb':3,'E':4,'F':5,'F#':6,'Gb':6,
'G':7,'G#':8,'Ab':8,'A':9,'A#':10,'Bb':10,'B':11
}
if name.strip() in lookup:
tonic_idx = lookup[name.strip()]
m = key_hint.get('mode') or key_hint.get('scale')
if isinstance(m, str):
m = m.strip().lower()
if m.startswith('maj'):
mode = 'maj'
elif m.startswith('min'):
mode = 'min'
except Exception:
pass
return tonic_idx, mode
def viterbi(log_probs, trans=0.995):
"""
log_probs: (N_states, T) framewise log-likelihoods
Simple self-biased transition matrix with uniform off-diagonal.
"""
N, T = log_probs.shape
stay = np.log(trans)
switch = np.log((1.0-trans)/(N-1))
dp = np.zeros_like(log_probs)
back = np.zeros((N, T), dtype=np.int16)
dp[:,0] = log_probs[:,0]
for t in range(1, T):
# For each state, max over prev states
prev = dp[:,t-1][:,None] + np.full((N,N), switch)
np.fill_diagonal(prev, dp[:,t-1] + stay)
back[:,t] = np.argmax(prev, axis=0)
dp[:,t] = log_probs[:,t] + np.max(prev, axis=0)
path = np.zeros(T, dtype=np.int16)
path[-1] = np.argmax(dp[:, -1])
for t in range(T-2, -1, -1):
path[t] = back[path[t+1], t+1]
return path
# --- Beat & tempo estimation -------------------------------------------------
# --- Beat & tempo estimation -------------------------------------------------
def _estimate_beats_vamp(audio_path: str, units_per_bar: int = 4, log_fn=None):
"""
Try to get beats and downbeats using QM BarBeatTracker via vamp.collect.
Returns dict compatible with estimate_beats (tempo might be None if plugin doesn't report it).
"""
try:
import soundfile as sf
import numpy as np
import vamp
except Exception:
return None
try:
y, sr = sf.read(audio_path, always_2d=False)
except Exception:
return None
if y is None or np.asarray(y).size == 0:
return None
if y.ndim > 1:
y_mono = y.mean(axis=1)
else:
y_mono = y
try:
res = vamp.collect(y_mono, sr, "qm-vamp-plugins:qm-barbeattracker")
except Exception:
return None
# Parse outputs defensively: different builds may return dicts or lists
beats_sec = []
downbeats_sec = []
def _iter_feature_items(res_dict):
# res_dict: mapping name -> dict-with-{"list"/"values"} OR directly a list
for _, out in (res_dict or {}).items():
if isinstance(out, dict):
items = out.get("list") or out.get("values") or []
for it in items:
yield it
elif isinstance(out, list):
for it in out:
yield it
any_items = False
for it in _iter_feature_items(res):
any_items = True
if not isinstance(it, dict):
continue
t = it.get("timestamp")
if t is None:
continue
# Always collect beat time
try:
beats_sec.append(float(t))
except Exception:
continue
# Try to detect downbeats from value or label
vals = it.get("values")
lab = it.get("label")
beat_num = None
if isinstance(vals, (list, tuple)) and len(vals) > 0:
v0 = vals[0]
try:
beat_num = int(round(float(v0)))
except Exception:
beat_num = None
elif isinstance(lab, (int, float)):
try:
beat_num = int(round(float(lab)))
except Exception:
beat_num = None
elif isinstance(lab, str):
s = lab.strip()
if s.isdigit():
beat_num = int(s)
if beat_num == 1:
downbeats_sec.append(float(t))
beats_sec = sorted(set(beats_sec))
# If we didn't manage to parse downbeats explicitly, infer phase by picking the strongest modulo-N
if not downbeats_sec and beats_sec:
# Simple heuristic: assume constant meter units_per_bar
# Choose the offset k in [0..N-1] whose subset is most evenly spaced.
N = max(1, int(units_per_bar))
arr = np.asarray(beats_sec, dtype=float)
best_k, best_var = 0, 1e99
for k in range(N):
subset = arr[k::N]
if subset.size >= 3:
diffs = np.diff(subset)
v = float(np.var(diffs))
else:
v = 1e6
if v < best_var:
best_var = v
best_k = k
downbeats_sec = arr[best_k::N].tolist()
# Estimate tempo as median instantaneous tempo if possible
tempo = None
try:
if len(beats_sec) >= 2:
diffs = np.diff(np.asarray(beats_sec))
med = float(np.median(diffs))
if med > 0:
tempo = 60.0 / med
except Exception:
tempo = None
# Beat strengths are not provided by the plugin; fill with 1.0
beat_strengths = [1.0] * len(beats_sec)
return {
"tempo": float(tempo) if tempo is not None else 0.0,
"beats": [float(t) for t in beats_sec],
"downbeats": [float(t) for t in downbeats_sec],
"beat_strengths": beat_strengths,
"sr": int(sr),
"hop": int(512), # not meaningful for Vamp path; keep a conventional value
}
def estimate_beats(audio_path: str, sr=22050, hop=512, units_per_bar: int = 4, tightness: float = 100.0, prefer_vamp: bool = True):
"""Estimate tempo, beats (sec), and downbeats (bar starts in sec).
Returns dict:
{
"tempo": float, # BPM
"beats": List[float], # seconds
"downbeats": List[float], # seconds, inferred bar starts (phase-aligned)
"beat_strengths": List[float], # normalized [0,1] onset strengths at beat times
"sr": int,
"hop": int,
}
Method:
• Prefer QM BarBeatTracker (vamp) if available.
• Otherwise: track beats from onset envelope (librosa), infer downbeat phase by maximizing average onset on beats modulo N.
"""
# 0) Try Vamp BarBeatTracker first
if prefer_vamp:
vb = _estimate_beats_vamp(audio_path, units_per_bar=units_per_bar)
if isinstance(vb, dict) and vb.get("beats"):
return vb
# 1) Fallback: Librosa
from audio_engine import _load_audio_any
y_stereo, sr_loaded = _load_audio_any(audio_path)
if sr is None:
sr = sr_loaded
y = y_stereo.mean(axis=1)
# Onset envelope & beat tracking
oenv = librosa.onset.onset_strength(y=y, sr=sr, hop_length=hop)
tempo, beat_frames = librosa.beat.beat_track(
onset_envelope=oenv, sr=sr, hop_length=hop, tightness=tightness, units='frames'
)
beat_times = librosa.frames_to_time(beat_frames, sr=sr, hop_length=hop)
# If no beats, bail gracefully
if beat_times.size == 0:
return {"tempo": float(tempo), "beats": [], "downbeats": [], "beat_strengths": [], "sr": int(sr), "hop": int(hop)}
# Onset energy at each beat frame
oenv_at_beats = []
for f in beat_frames:
idx = int(min(len(oenv) - 1, max(0, f)))
oenv_at_beats.append(float(oenv[idx]))
oenv_at_beats = np.asarray(oenv_at_beats, dtype=float)
# Normalize beat strengths to [0,1] for later use
if oenv_at_beats.size:
bs_min = float(oenv_at_beats.min())
bs_max = float(oenv_at_beats.max())
if bs_max > bs_min:
beat_strengths = ((oenv_at_beats - bs_min) / (bs_max - bs_min)).tolist()
else:
beat_strengths = [1.0 for _ in oenv_at_beats]
else:
beat_strengths = []
# Heuristic downbeat phase: choose offset k in [0..N-1] maximizing average onset
N = max(1, int(units_per_bar))
best_k = 0
best_score = -1.0
for k in range(N):
sel = oenv_at_beats[k::N]
score = float(sel.mean()) if sel.size else -1.0
if score > best_score:
best_score = score
best_k = k
downbeat_times = beat_times[best_k::N]
return {
"tempo": float(tempo),
"beats": [float(t) for t in beat_times],
"downbeats": [float(t) for t in downbeat_times],
"beat_strengths": beat_strengths,
"sr": int(sr),
"hop": int(hop),
}
def viterbi_timevarying(log_probs, stay_probs):
"""
Time-varying self-biased Viterbi.
Args:
log_probs: (N, T) log-likelihoods.
stay_probs: (T,) or (N,T) self-transition probability in [0,1] per time step (applies between t-1 -> t).
Off-diagonal mass is distributed uniformly.
Returns:
path: (T,) best state indices.
"""
N, T = log_probs.shape
if stay_probs.ndim == 1:
stay_probs = np.broadcast_to(stay_probs[None, :], (N, T))
dp = np.zeros_like(log_probs)
back = np.zeros((N, T), dtype=np.int16)
dp[:, 0] = log_probs[:, 0]
for t in range(1, T):
stay_t = np.clip(stay_probs[:, t], 1e-6, 1.0 - 1e-6)
switch_t = (1.0 - stay_t) / max(1, N - 1)
# Build (N,N) log transition for time t
prev = np.full((N, N), -np.inf, dtype=np.float64)
# Off-diagonal
prev[:] = dp[:, t - 1][:, None] + np.log(switch_t)[:, None]
# Diagonal (stay)
diag = dp[:, t - 1] + np.log(stay_t)
np.fill_diagonal(prev, diag)
back[:, t] = np.argmax(prev, axis=0)
dp[:, t] = log_probs[:, t] + np.max(prev, axis=0)
path = np.zeros(T, dtype=np.int16)
path[-1] = np.argmax(dp[:, -1])
for t in range(T - 2, -1, -1):
path[t] = back[path[t + 1], t + 1]
return path
# --- Minor triad vs minor 7th refinement ------------------------------------
# --- Harmonic mix and beat-sync chroma helpers ------------------------------
def _mix_from_stems(stems: dict | None, sr_expected: int | None = None):
"""
Combine available stems into a 'harmonic' mono mix for chord features.
Excludes percussion. Accepts keys like: 'vocals','other','guitar','piano','bass','drums','accompaniment','harmonic'.
Returns (y_harm, sr_or_None). If stems is None or empty, returns (None, None).
"""
if not stems:
return None, None
# Priority 1: explicit harmonic/accompaniment provided
for k in ('harmonic', 'accompaniment'):
if k in stems and stems[k] is not None:
y = stems[k]
if y.ndim == 2:
y = y.mean(axis=1)
return y.astype(np.float32), sr_expected
# Otherwise sum non-percussive sources
prefer = ['vocals', 'guitar', 'piano', 'other', 'bass']
acc = None
for k in prefer:
if k in stems and stems[k] is not None:
yk = stems[k]
if yk.ndim == 2:
yk = yk.mean(axis=1)
acc = yk.astype(np.float32) if acc is None else (acc + yk.astype(np.float32))
if acc is None:
return None, None
# Gentle limiter to avoid clipping when summing
m = np.max(np.abs(acc)) + 1e-9
acc = acc / m
return acc, sr_expected
def _beat_sync_chroma(chroma: np.ndarray, frame_times: np.ndarray, beats_sec: list[float], reduce='median'):
"""
Aggregate framewise chroma (12,F) to beat-synchronous (12,B) using median/mean.
Returns (C_beat, beat_idxs) where beat_idxs holds the frame indices used per beat start.
"""
if chroma.size == 0 or not beats_sec:
return chroma, np.arange(chroma.shape[1])
beats = np.asarray(beats_sec, dtype=float)
idxs = np.searchsorted(frame_times, beats, side='left')
idxs = np.clip(idxs, 0, chroma.shape[1]-1)
segs = []
used = []
for i in range(len(idxs)):
a = idxs[i]
b = idxs[i+1] if i+1 < len(idxs) else chroma.shape[1]
if b <= a:
b = min(a+1, chroma.shape[1])
X = chroma[:, a:b]
if X.size == 0:
X = chroma[:, a:a+1]
if reduce == 'mean':
v = X.mean(axis=1)
else:
v = np.median(X, axis=1)
# log + l2 normalize
v = np.log1p(v)
v = v / (np.linalg.norm(v) + 1e-12)
segs.append(v)
used.append(a)
Cb = np.stack(segs, axis=1) if segs else chroma
return Cb, np.asarray(used, dtype=int)
# --- Small resample helper ---
def _resample_mono(y: np.ndarray, orig_sr: int, target_sr: int) -> np.ndarray:
"""Return mono signal at target_sr. Accepts mono or stereo arrays."""
if target_sr == orig_sr:
if y.ndim == 1:
return y.astype(np.float32)
return y.mean(axis=1).astype(np.float32)
# ensure mono before resample for speed
y_mono = y.mean(axis=1) if y.ndim == 2 else y
return librosa.resample(y_mono.astype(np.float32), orig_sr=orig_sr, target_sr=target_sr)
# --- Tuning-aware chroma helper ---------------------------------------------
def _chroma_cqt_tuned(y: np.ndarray, sr: int, hop: int, tuning_bins: float | None = None) -> np.ndarray:
"""Compute chroma CQT with an optional global tuning correction (in bins)."""
if tuning_bins is None:
try:
tuning_bins = float(librosa.estimate_tuning(y=y, sr=sr))
except Exception:
tuning_bins = 0.0
return librosa.feature.chroma_cqt(y=y, sr=sr, hop_length=hop, tuning=tuning_bins)
# --- Bass root hint from bass stem -------------------------------------------------
def _bass_root_logits(bass_y: np.ndarray | None, sr: int, hop: int = 2048,
frame_times: np.ndarray | None = None,
beats_sec: list[float] | None = None) -> tuple[np.ndarray, np.ndarray]:
"""Return (logits_pc, times) where logits_pc is (12,Tb) over pitch classes.
If `beats_sec` provided, aggregates to beats; otherwise framewise.
"""
if bass_y is None or bass_y.size == 0:
return np.zeros((12, 0), dtype=np.float32), np.asarray(beats_sec or [], dtype=float)
# Focus on low range for bass root evidence
C = librosa.feature.chroma_cqt(y=bass_y.astype(np.float32), sr=sr, hop_length=hop, tuning=None)
times = librosa.frames_to_time(np.arange(C.shape[1]), sr=sr, hop_length=hop)
if beats_sec:
Cb, _ = _beat_sync_chroma(C, times, beats_sec, reduce='median')
else:
Cb = C
# Softmax-ish logits per time over PCs
Cb = Cb + 1e-6
Cb = Cb / (np.linalg.norm(Cb, axis=0, keepdims=True) + 1e-12)
Cb = Cb ** 2.5 # sharpen more (clearer bass roots)
Cb = Cb / (np.sum(Cb, axis=0, keepdims=True) + 1e-12)
logits = np.log(Cb + 1e-9)
tvec = np.asarray(beats_sec, dtype=float) if beats_sec else times
return logits.astype(np.float32), tvec
def snap_time_to_beats(t: float, beats: list[float]) -> float:
"""Return the beat time closest to t (in seconds)."""
if not beats:
return float(t)
arr = np.asarray(beats, dtype=float)
idx = int(np.argmin(np.abs(arr - float(t))))
return float(arr[idx])
def snap_interval_to_beats(a: float, b: float, beats: list[float]) -> tuple[float, float]:
"""Snap an interval [a,b] to nearest beats, preserving order and minimum width."""
if not beats:
return float(min(a, b)), float(max(a, b))
a_s = snap_time_to_beats(a, beats)
b_s = snap_time_to_beats(b, beats)
if b_s < a_s:
a_s, b_s = b_s, a_s
if abs(b_s - a_s) < 1e-3:
b_s = a_s + 1e-2 # ensure non-zero loop
return float(a_s), float(b_s)
# Public helper: estimate musical key from an audio file
# Returns a dict with: {"tonic_idx": int, "mode": "maj"|"min", "tonic_name": str, "pretty": str}
def estimate_key(audio_path: str, sr=22050, hop=2048, prefer_vamp: bool = True, log_fn=None):
# Prefer Vamp (QM Key Detector) if requested
if prefer_vamp:
try:
kv = estimate_key_vamp(audio_path, log_fn=log_fn)
if kv and isinstance(kv, dict) and "tonic_idx" in kv and "mode" in kv:
return kv
except Exception:
pass
# --- Fallback: internal KS-based key from chroma ---
from audio_engine import _load_audio_any
y_stereo, sr_loaded = _load_audio_any(audio_path)
if sr is None:
sr = sr_loaded
# resample mono to requested sr
y = _resample_mono(y_stereo, sr_loaded, sr)
# tuning-aware chroma
try:
tuning_bins = float(librosa.estimate_tuning(y=y, sr=sr))
except Exception:
tuning_bins = 0.0
chroma = librosa.feature.chroma_cqt(y=y, sr=sr, hop_length=hop, tuning=tuning_bins)
tonic_idx, mode = _estimate_key_from_chroma(chroma)
use_flats = _use_flats_for_key(tonic_idx, mode)
tonic_name = _pc_name(tonic_idx, use_flats)
pretty = f"{tonic_name} {'major' if mode=='maj' else 'minor'}"
if callable(log_fn):
try:
log_fn(f"key(internal): {pretty}")
except Exception:
pass
return {
"tonic_idx": int(tonic_idx),
"mode": mode,
"tonic_name": tonic_name,
"pretty": pretty,
}
# --- Minor triad vs minor 7th refinement ------------------------------------
def _pc_index(semitone_name: str) -> int:
names = {
'C':0,'C#':1,'Db':1,'D':2,'D#':3,'Eb':3,'E':4,'F':5,'F#':6,'Gb':6,
'G':7,'G#':8,'Ab':8,'A':9,'A#':10,'Bb':10,'B':11
}
return names[semitone_name]
def _refine_minor_sevenths(
segments: list,
audio_path: str,
sr: int = 22050,
hop: int = 512,
seventh_db_threshold: float = -26.0, # dB relative to per-frame peak (gentler)
seventh_rel_threshold: float = 0.40, # fraction of triad peak in a frame (gentler)
min_frames_ratio_for_upgrade: float = 0.60, # >=60% frames show clear b7 to upgrade m→m7
max_frames_ratio_for_keep_m7: float = 0.40, # <40% frames show b7 → downgrade m7→m
min_duration_for_upgrade: float = 0.50, # keep short guard
) -> list:
"""Post-process labels to better separate m vs m7 (stricter, frame-wise voting).
For each minor/minor7 segment:
• Compute frame-wise chroma (CQT), normalize each frame to its max.
• In each frame, check if b7 >= rel_threshold * triad_peak AND b7_dB >= dB_threshold.
• Let ratio = (# frames satisfying) / (# frames). Decisions:
- If label is m7 and ratio < max_frames_ratio_for_keep_m7 → downgrade to m.
- If label is m and ratio >= min_frames_ratio_for_upgrade AND duration >= min_duration_for_upgrade → upgrade to m7.
"""
from audio_engine import _load_audio_any
if not segments:
return segments
y_stereo, sr_loaded = _load_audio_any(audio_path)
if sr is None:
sr = sr_loaded
y = _resample_mono(y_stereo, sr_loaded, sr)
# pre-compute tuning once for this track
try:
tuning_bins_all = float(librosa.estimate_tuning(y=y, sr=sr))
except Exception:
tuning_bins_all = 0.0
def seg_chroma_frames(a: float, b: float):
a_s = max(0, int(a * sr)); b_s = max(a_s + 1, int(b * sr))
y_seg = y[a_s:b_s]
if y_seg.size < hop:
pad = np.zeros(min(hop, max(0, hop - y_seg.size)), dtype=y.dtype)
y_seg = np.concatenate([y_seg, pad])
C = librosa.feature.chroma_cqt(y=y_seg, sr=sr, hop_length=hop, tuning=tuning_bins_all) # (12, F)
if C.shape[1] == 0:
return C
# normalize each frame to its max so per-frame peak = 1
m = np.max(C, axis=0, keepdims=True) + 1e-12
return C / m
b7_min_lin = 10 ** (seventh_db_threshold / 20.0) # relative to per-frame peak (1.0)
out = []
for s in segments:
lab = s.get('label', '')
if len(lab) < 2:
out.append(s); continue
# Parse root with optional accidental
root = lab[0]
i = 1
if i < len(lab) and lab[i] in ('#', 'b'):
root += lab[i]; i += 1
qual = lab[i:]
if qual not in ('m', 'm7'):
out.append(s); continue
a_t = float(s['start']); b_t = float(s['end'])
dur = max(0.0, b_t - a_t)
C = seg_chroma_frames(a_t, b_t)
if C.size == 0 or C.shape[1] == 0:
out.append(s); continue
r = _pc_index(root)
triad_pcs = [(r + 0) % 12, (r + 3) % 12, (r + 7) % 12]
b7_pc = (r + 10) % 12
triad_peak_per_frame = np.max(C[triad_pcs, :], axis=0) # (F,)
b7_per_frame = C[b7_pc, :] # (F,)
good = (b7_per_frame >= b7_min_lin) & (b7_per_frame >= seventh_rel_threshold * (triad_peak_per_frame + 1e-12))
ratio = float(np.mean(good.astype(np.float32)))
new_lab = lab
# Robustness: also check median b7 vs triad
median_b7 = float(np.median(b7_per_frame))
median_triad = float(np.median(triad_peak_per_frame + 1e-12))
strong_median = (median_b7 >= (0.8 * seventh_rel_threshold) * median_triad) and (median_b7 >= 0.8 * b7_min_lin)
if qual == 'm7':
if ratio < max_frames_ratio_for_keep_m7:
new_lab = root + 'm'
else: # qual == 'm'
if ratio >= min_frames_ratio_for_upgrade and dur >= min_duration_for_upgrade and strong_median:
new_lab = root + 'm7'
if new_lab != lab:
s = dict(s); s['label'] = new_lab
out.append(s)
return out
# --- Root sanity check: keep family, re-pick root by template fit -----------
def _parse_chord_label(lab: str):
"""Return (family_id, root_pc, root_text, qual_text).
family_id: 0=maj,1=min,2=dom7,3=maj7,4=min7
"""
fam = 0
# detect suffixes (order matters: maj7 before 7, m7 before m)
if lab.endswith('maj7'):
fam = 3; core = lab[:-4]
elif lab.endswith('m7'):
fam = 4; core = lab[:-2]
elif lab.endswith('m'):
fam = 1; core = lab[:-1]
elif lab.endswith('7'):
fam = 2; core = lab[:-1]
else:
fam = 0; core = lab
core = core.strip()
if not core:
return fam, 0, 'C', ''
root = core[0]
if len(core) > 1 and core[1] in ('#', 'b'):
root += core[1]
try:
pc = _pc_index(root)
except KeyError:
pc = 0
qual = lab[len(root):]
return fam, pc, root, qual
def _family_name(fam: int) -> str:
return {0:'', 1:'m', 2:'7', 3:'maj7', 4:'m7'}.get(fam, '')
def _root_sanity_pass(segments: list, audio_path: str, use_flats: bool | None = None,
sr: int = 22050, hop: int = 2048, min_improvement: float = 0.12) -> list:
"""Re-evaluate root inside each segment for its chord *family* using template fit.
Keeps the family (maj/min/7th type) but allows the root to change if its
family-template cosine score improves by at least `min_improvement`.
This helps fix cases like labeling Db when F is a much better fit for the same family.
"""
from audio_engine import _load_audio_any
if not segments:
return segments
y_stereo, sr_loaded = _load_audio_any(audio_path)
if sr is None:
sr = sr_loaded
y = _resample_mono(y_stereo, sr_loaded, sr)
# Key-based naming unless provided (tuning-aware)
if use_flats is None:
try:
try:
tuning_bins = float(librosa.estimate_tuning(y=y, sr=sr))
except Exception:
tuning_bins = 0.0
chroma_all = librosa.feature.chroma_cqt(y=y, sr=sr, hop_length=hop, tuning=tuning_bins)
tonic_idx, mode = _estimate_key_from_chroma(chroma_all)
use_flats = _use_flats_for_key(tonic_idx, mode)
except Exception:
use_flats = True
maj, mino, dom7, maj7, min7 = chord_templates()
fam_to_M = {0: maj, 1: mino, 2: dom7, 3: maj7, 4: min7}
out = []
for s in segments:
lab = s.get('label', '')
fam, root_pc, root_txt, _ = _parse_chord_label(lab)
M = fam_to_M.get(fam)
if M is None:
out.append(s); continue
a = max(0, int(float(s['start']) * sr))
b = max(a + 1, int(float(s['end']) * sr))
y_seg = y[a:b]
if y_seg.size < hop:
pad = np.zeros(min(hop, max(0, hop - y_seg.size)), dtype=y.dtype)
y_seg = np.concatenate([y_seg, pad])
# tuning-aware chroma for segment
try:
tuning_bins = float(librosa.estimate_tuning(y=y_seg, sr=sr))
except Exception:
tuning_bins = 0.0
C = librosa.feature.chroma_cqt(y=y_seg, sr=sr, hop_length=hop, tuning=tuning_bins)
v = C.mean(axis=1)
nrm = np.linalg.norm(v) + 1e-12
v = v / nrm
# Current vs best
cur_score = float(M[root_pc, :] @ v)
scores = M @ v # 12 roots
best_pc = int(np.argmax(scores))
best_score = float(scores[best_pc])
if best_score - cur_score >= min_improvement:
# Re-label with best root
new_root_txt = _pc_name(best_pc, use_flats)
new_lab = new_root_txt + _family_name(fam)
ns = dict(s); ns['label'] = new_lab
out.append(ns)
else:
out.append(s)
return out
def estimate_chords_stem_aware(
audio_path: str,
sr=22050,
hop=2048,
beats: list[float] | None = None,
downbeats: list[float] | None = None,
beat_strengths: list[float] | None = None,
stems: dict | None = None,
use_key_prior: bool = True,
alpha_harm: float = 0.40,
beta_bass: float = 0.70,
weights: dict | None = None,
log_fn=None,
style: str = "default",
key_hint: dict | None = None,
):
"""Beat-synchronous, stem-aware chord estimator.
Combines harmonic chroma (guitar/piano/other/vocals) with bass-root evidence.
Returns list of segments [{start,end,label,conf,beat_sync=True}].
"""
from audio_engine import _load_audio_any
# Normalize style names (robust to non-string inputs)
style_map = {
'default': 'rock_pop',
'rock': 'rock_pop', 'rock/pop': 'rock_pop', 'pop': 'rock_pop',
'blues': 'blues', 'reggae': 'reggae', 'jazz': 'jazz',
'rock_pop': 'rock_pop'
}
_style_key = style
try:
if _style_key is None:
_style_key = 'rock_pop'
# If someone passed a QAction, function, etc., coerce to string safely
if not isinstance(_style_key, str):
_style_key = str(_style_key)
_style_key = _style_key.lower()
except Exception:
_style_key = 'rock_pop'
style = style_map.get(_style_key, 'rock_pop')
_use_fl = False
y_stereo, sr_loaded = _load_audio_any(audio_path)
sr = sr_loaded if sr is None else int(sr)
# Build mono reference at target sr
y_mono = _resample_mono(y_stereo, sr_loaded, sr)
if callable(log_fn):
try:
log_fn(f"stem_aware: sr_loaded={sr_loaded}, sr_used={sr}")
except Exception:
pass
# Build harmonic mix from stems (exclude vocals/drums); fallback to mono
y_harm = None
used_stems = []
if stems:
w = {'guitar': 1.0, 'piano': 1.0, 'other': 0.5, 'bass': 0.0, 'vocals': 0.0, 'drums': 0.0}
if isinstance(weights, dict):
w.update(weights)
acc = None
for k, arr in stems.items():
try:
# resample each stem to sr
mono_in = arr.mean(axis=1).astype(np.float32) if arr.ndim == 2 else arr.astype(np.float32)
# resample to match target sr
if 'sr' in getattr(arr, '__dict__', {}):
mono = _resample_mono(arr, getattr(arr, 'sr'), sr)
else:
# stems are same sr as source audio; use sr_loaded
mono = librosa.resample(mono_in, orig_sr=sr_loaded, target_sr=sr) if sr_loaded != sr else mono_in
gain = float(w.get(k.lower(), w.get(k, 0.0)))
if gain <= 0.0:
continue
used_stems.append(f"{k}:{gain:.2f}")
if acc is None:
acc = gain * mono
else:
L = max(acc.shape[0], mono.shape[0])
if acc.shape[0] < L: acc = np.pad(acc, (0, L - acc.shape[0]))
if mono.shape[0] < L: mono = np.pad(mono, (0, L - mono.shape[0]))
acc = acc + gain * mono
except Exception:
continue
if acc is not None:
y_harm = acc
if y_harm is None:
y_harm = y_mono
# Framewise chroma and times
chroma_frames = librosa.feature.chroma_cqt(y=y_harm, sr=sr, hop_length=hop)
frame_times = librosa.frames_to_time(np.arange(chroma_frames.shape[1]), sr=sr, hop_length=hop)
# Beats (if not given)
if beats is None:
bd = estimate_beats(audio_path, sr=sr, hop=512)
beats = bd.get("beats", [])
downbeats = bd.get("downbeats", []) if downbeats is None else downbeats
beat_strengths = bd.get("beat_strengths", []) if beat_strengths is None else beat_strengths
# Beat-sync chroma
if beats:
chroma, _ = _beat_sync_chroma(chroma_frames, frame_times, beats, reduce='median')
times = np.asarray(beats, dtype=float)
else:
chroma = chroma_frames
times = frame_times
# Normalize chroma columns
chroma = chroma / (np.linalg.norm(chroma, axis=0, keepdims=True) + 1e-12)
# Harmonic template log-likelihoods (60,T)
harm_scores = chord_likelihoods(chroma) + 1e-6
log_harm = np.log(harm_scores)
# Bass root evidence from bass stem (12,Tb) → expand to (60,Tb)
bass_y = None
if stems and isinstance(stems.get('bass', None), np.ndarray):
b = stems['bass']
bass_y = _resample_mono(b, sr_loaded, sr)
bass_logits, _ = _bass_root_logits(bass_y, sr, hop=hop,
frame_times=frame_times,
beats_sec=beats if beats else None)
# --- Bass-root-first decoding path ---
use_bass_first = bass_logits.shape[1] > 0
if use_bass_first:
# Align lengths with harmonic emissions
T_align = min(log_harm.shape[1], bass_logits.shape[1])
log_h = log_harm[:, :T_align]
log_b = bass_logits[:, :T_align]
times = times[:T_align]
if callable(log_fn):
try:
log_fn(f"DBG[bass_first]: T_align={T_align}, beats={len(beats or [])}, log_h={log_h.shape}, log_b={log_b.shape}, times={len(times)}")
except Exception:
pass
# Augment bass logits to account for bass playing the fifth instead of the root (common in reggae/rock)
# Mix a portion of probability mass from ±7 semitones (perfect fifth up/down) into each class.
try:
with np.errstate(over='ignore'):
pb_b = np.exp(log_b - np.max(log_b, axis=0, keepdims=True))
pb_b /= (np.sum(pb_b, axis=0, keepdims=True) + 1e-12)
def _roll(x, k):
return np.roll(x, k, axis=0)
eps = 0.25 # share from fifths
pb_aug = (1.0 - eps) * pb_b + (eps/2.0) * (_roll(pb_b, +7) + _roll(pb_b, -7))
log_b = np.log(pb_aug + 1e-9)
except Exception:
pass
# Build a surrogate "bass" from the harmonic mix (guitar/piano/other) for early bars without bass
try:
# Reuse the already computed y_harm (mono acc mix) and create logits the same way as bass
harm_logits_full, _ = _bass_root_logits(y_harm, sr, hop=hop,
frame_times=frame_times,
beats_sec=beats if beats else None)
log_b_harm = harm_logits_full[:, :T_align] if harm_logits_full.shape[1] >= T_align else harm_logits_full
if log_b_harm.shape[1] != T_align:
# pad with minimal uniform evidence if needed
pad_T = T_align - log_b_harm.shape[1]
if pad_T > 0:
log_b_harm = np.pad(log_b_harm, ((0,0),(0,pad_T)), mode='edge')
except Exception:
log_b_harm = None
# Confidence gating: if bass is weak, fall back to harmonic-root evidence for those beats
TH_CONF = 0.40
with np.errstate(over='ignore'):
pb = np.exp(log_b - np.max(log_b, axis=0, keepdims=True)); pb /= (np.sum(pb, axis=0, keepdims=True) + 1e-12)
maxpb = np.max(pb, axis=0)
if log_b_harm is not None and log_b_harm.shape[1] == T_align:
with np.errstate(over='ignore'):
ph = np.exp(log_b_harm - np.max(log_b_harm, axis=0, keepdims=True)); ph /= (np.sum(ph, axis=0, keepdims=True) + 1e-12)
maxph = np.max(ph, axis=0)
# Use harmonic surrogate where bass is not yet confident; otherwise keep bass
use_harm_mask = (maxpb < TH_CONF) & (maxph >= (TH_CONF - 0.05))
if np.any(use_harm_mask):
log_b[:, use_harm_mask] = log_b_harm[:, use_harm_mask]
pb[:, use_harm_mask] = ph[:, use_harm_mask]
maxpb[use_harm_mask] = maxph[use_harm_mask]
# Compute current top bass root per beat (after augmentation/merge)
top_pc = np.argmax(pb, axis=0) # (T_align,)
top_conf = maxpb.copy() # (T_align,)