v9: Major quality upgrade — SuperFlux onsets, transient-only NCC, mel pre-filter, MIDI quantization, singleton merging
Browse files- sample_extractor.py +295 -221
sample_extractor.py
CHANGED
|
@@ -1,19 +1,27 @@
|
|
| 1 |
#!/usr/bin/env python3
|
| 2 |
"""
|
| 3 |
-
Sample Extractor
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
"""
|
| 8 |
|
| 9 |
-
import argparse, json, os, sys, warnings, hashlib
|
| 10 |
from collections import defaultdict
|
| 11 |
from dataclasses import dataclass, field
|
| 12 |
from pathlib import Path
|
| 13 |
from typing import Optional
|
|
|
|
| 14 |
|
| 15 |
import librosa, numpy as np, soundfile as sf, torch
|
| 16 |
from scipy.signal import fftconvolve
|
|
|
|
| 17 |
|
| 18 |
warnings.filterwarnings("ignore", category=FutureWarning)
|
| 19 |
warnings.filterwarnings("ignore", category=UserWarning)
|
|
@@ -22,7 +30,7 @@ warnings.filterwarnings("ignore", category=UserWarning)
|
|
| 22 |
class Hit:
|
| 23 |
audio: np.ndarray; sr: int; onset_time: float; duration: float; index: int
|
| 24 |
rms_energy: float = 0.0; spectral_centroid: float = 0.0
|
| 25 |
-
label: str = "";
|
| 26 |
def save(self, path): sf.write(path, self.audio, self.sr, subtype='PCM_24')
|
| 27 |
|
| 28 |
@dataclass
|
|
@@ -35,29 +43,27 @@ class Cluster:
|
|
| 35 |
def count(self): return len(self.hits)
|
| 36 |
|
| 37 |
DEMUCS_MODELS = ["htdemucs","htdemucs_ft","htdemucs_6s","mdx","mdx_extra","mdx_extra_q"]
|
| 38 |
-
DEMUCS_STEMS = {
|
| 39 |
-
"htdemucs":["drums","bass","other","vocals"],"htdemucs_ft":["drums","bass","other","vocals"],
|
| 40 |
"htdemucs_6s":["drums","bass","other","vocals","guitar","piano"],
|
| 41 |
"mdx":["drums","bass","other","vocals"],"mdx_extra":["drums","bass","other","vocals"],
|
| 42 |
-
"mdx_extra_q":["drums","bass","other","vocals"]
|
| 43 |
-
}
|
| 44 |
|
| 45 |
# ─── Cache ────────────────────────────────────────────────────────────────────
|
| 46 |
_cache = {}
|
| 47 |
-
def
|
| 48 |
def cache_get(k): return _cache.get(k)
|
| 49 |
def cache_set(k,v): _cache[k]=v; return v
|
| 50 |
def cache_clear(): _cache.clear()
|
| 51 |
|
| 52 |
-
# ─── Stage 1 ───────────────────────────────────────────────────────────
|
| 53 |
def extract_stem(audio_path,stem="drums",device="cpu",model_name="htdemucs_ft",shifts=1,overlap=0.25):
|
| 54 |
if stem=="all":
|
| 55 |
y,sr=librosa.load(audio_path,sr=44100,mono=True); return y.astype(np.float32),sr
|
| 56 |
with open(audio_path,'rb') as f: fh=hashlib.md5(f.read(200000)).hexdigest()
|
| 57 |
ck=("stem",fh,stem,model_name,shifts,overlap); c=cache_get(ck)
|
| 58 |
-
if c: print(f"[
|
| 59 |
from demucs.pretrained import get_model; from demucs.apply import apply_model
|
| 60 |
-
print(f"[
|
| 61 |
model=get_model(model_name); model.eval().to(device); sr=model.samplerate
|
| 62 |
if stem not in model.sources: raise ValueError(f"'{stem}' not in {model.sources}")
|
| 63 |
a,_=librosa.load(audio_path,sr=sr,mono=False)
|
|
@@ -69,40 +75,60 @@ def extract_stem(audio_path,stem="drums",device="cpu",model_name="htdemucs_ft",s
|
|
| 69 |
r=src[0,model.sources.index(stem)].mean(dim=0).cpu().numpy()
|
| 70 |
print(f" ✓ {len(r)/sr:.1f}s"); return cache_set(ck,(r.astype(np.float32),sr))
|
| 71 |
|
| 72 |
-
# ─── Stage 2 ──────────────────────────────────────
|
| 73 |
-
def detect_onsets(y,sr,pre_pad=0.
|
| 74 |
-
energy_threshold_db=-35.0,mode="auto",
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
yh,_=librosa.effects.hpss(y)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
def _n(x): m=x.max(); return x/m if m>0 else x
|
| 82 |
-
oe=np.maximum.reduce([_n(
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
times=librosa.frames_to_time(fr,sr=sr)
|
|
|
|
|
|
|
| 90 |
thr=10**(energy_threshold_db/20); hits=[]
|
| 91 |
for i,t in enumerate(times):
|
| 92 |
s=max(0,int((t-pre_pad)*sr))
|
| 93 |
-
e=min(int(times[i+1]*sr) if i+1<len(times) else len(y),s+int(max_dur*sr))
|
| 94 |
seg=y[s:e]
|
| 95 |
if len(seg)<int(min_dur*sr): continue
|
| 96 |
rms=np.sqrt(np.mean(seg**2))
|
| 97 |
if rms<thr: continue
|
| 98 |
-
fl=min(int(0.
|
| 99 |
if fl>0: seg=seg.copy(); seg[-fl:]*=np.linspace(1,0,fl)
|
| 100 |
sc=float(librosa.feature.spectral_centroid(y=seg,sr=sr).mean())
|
| 101 |
hits.append(Hit(audio=seg,sr=sr,onset_time=t,duration=len(seg)/sr,
|
| 102 |
index=len(hits),rms_energy=float(rms),spectral_centroid=sc))
|
| 103 |
print(f" ✓ {len(hits)} hits"); return hits
|
| 104 |
|
| 105 |
-
# ─── Stage 3 ─────────────────────────────────────────────────
|
| 106 |
LABEL_RULES=[("kick",lambda lr,mr,hr,c,zcr,d:lr>0.5 and c<800),
|
| 107 |
("hihat_closed",lambda lr,mr,hr,c,zcr,d:hr>0.35 and c>4000 and d<0.15),
|
| 108 |
("hihat_open",lambda lr,mr,hr,c,zcr,d:hr>0.35 and c>4000 and d>=0.15),
|
|
@@ -115,36 +141,85 @@ LABEL_RULES=[("kick",lambda lr,mr,hr,c,zcr,d:lr>0.5 and c<800),
|
|
| 115 |
def classify_hit(hit):
|
| 116 |
y,sr=hit.audio,hit.sr; D=np.abs(librosa.stft(y,n_fft=2048))
|
| 117 |
f=librosa.fft_frequencies(sr=sr,n_fft=2048)
|
| 118 |
-
le=np.sum(D[(f>=20)&(f<200)]**2); me=np.sum(D[(f>=200)&(f<4000)]**2)
|
| 119 |
-
|
| 120 |
zcr=float(librosa.feature.zero_crossing_rate(y=y).mean())
|
| 121 |
for n,fn in LABEL_RULES:
|
| 122 |
if fn(lr,mr,hr,hit.spectral_centroid,zcr,hit.duration): return n
|
| 123 |
return "other"
|
| 124 |
def classify_hits(hits):
|
| 125 |
-
print(f"[
|
| 126 |
for h in hits: h.label=classify_hit(h)
|
| 127 |
c=defaultdict(int)
|
| 128 |
for h in hits: c[h.label]+=1
|
| 129 |
for l,n in sorted(c.items(),key=lambda x:-x[1]): print(f" {l}: {n}")
|
| 130 |
return hits
|
| 131 |
|
| 132 |
-
# ─── Stage 4 ──────────
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 148 |
cm=defaultdict(list)
|
| 149 |
for i,l in enumerate(labels): cm[l].append(i)
|
| 150 |
clusters=[]
|
|
@@ -156,64 +231,122 @@ def _labels_to_clusters(labels,hits):
|
|
| 156 |
clusters.sort(key=lambda c:c.count,reverse=True)
|
| 157 |
for i,c in enumerate(clusters): c.cluster_id=i
|
| 158 |
return clusters
|
| 159 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 160 |
from sklearn.cluster import AgglomerativeClustering as AC
|
| 161 |
if not hits: return []
|
| 162 |
-
N=len(hits)
|
| 163 |
if N==1: return [Cluster(cluster_id=0,label=f"{hits[0].label}_0",hits=[hits[0]])]
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
if use_t:
|
| 170 |
print(f" Target: {tmin}–{tmax}")
|
| 171 |
-
lo,hi=0.001,1.
|
| 172 |
for _ in range(30):
|
| 173 |
-
mid=(lo+hi)/2
|
|
|
|
| 174 |
n=len(set(lb))
|
| 175 |
-
if tmin<=n<=tmax: bl,bn
|
| 176 |
elif n>tmax: lo=mid
|
| 177 |
else: hi=mid
|
| 178 |
-
if bl is None or abs(n-(tmin+tmax)/2)<abs(bn-(tmin+tmax)/2): bl,bn
|
| 179 |
if bn<tmin or bn>tmax:
|
| 180 |
-
tm=min((tmin+tmax)//2,N-1)
|
| 181 |
try: bl=AC(n_clusters=tm,metric='precomputed',linkage=linkage).fit_predict(D); bn=tm
|
| 182 |
except: pass
|
| 183 |
-
labels=bl; print(f" → {bn}")
|
| 184 |
else:
|
| 185 |
-
dt=max(0.001,1.0-ncc_threshold)
|
| 186 |
labels=AC(n_clusters=None,distance_threshold=dt,metric='precomputed',linkage=linkage).fit_predict(D)
|
|
|
|
| 187 |
print(f" ✓ {len(set(labels))} clusters")
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 191 |
|
| 192 |
-
# ─── Stage 5 ────────────────────────────────────────────────
|
| 193 |
def sample_quality_score(y,sr,label="other"):
|
| 194 |
import scipy.stats
|
| 195 |
re=librosa.feature.rms(y=y,frame_length=512,hop_length=128)[0]
|
| 196 |
if len(re)>=10:
|
| 197 |
pk=np.argmax(re); po=re[pk:]
|
| 198 |
c1=max(0,1.0-np.mean(po[-max(3,len(po)//5):])/( re[pk]+1e-8)*5)
|
| 199 |
-
c2=(max(0,scipy.stats.linregress(np.arange(len(po)),np.log(po+1e-8))[2]**2)
|
|
|
|
| 200 |
else: c1,c2=0.5,0.0
|
| 201 |
-
comp=c1*0.6+c2*0.4
|
| 202 |
-
|
|
|
|
|
|
|
|
|
|
| 203 |
if len(ons)>0:
|
| 204 |
o=int(ons[0]); pre=y[max(0,o-int(sr*.02)):o]; sig=y[o:o+int(sr*.1)]
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
cl=ns*0.5+np2*0.5
|
| 208 |
-
|
|
|
|
| 209 |
return {'total':float((comp*0.30+cl*0.40+oq*0.20+0.5*0.10)*100),'completeness':float(comp),'cleanness':float(cl),'onset_quality':float(oq)}
|
| 210 |
def select_best(clusters):
|
| 211 |
-
print(f"[
|
| 212 |
for c in clusters:
|
| 213 |
if c.count<=1: c.best_hit_idx=0; continue
|
| 214 |
c.best_hit_idx=int(np.argmax([sample_quality_score(h.audio,h.sr,c.label.rsplit('_',1)[0])['total'] for h in c.hits]))
|
| 215 |
|
| 216 |
-
# ─── Stage 6 ──────────────────────────────────────────────────────
|
| 217 |
def synthesize_from_cluster(cluster):
|
| 218 |
if cluster.count<2: return None
|
| 219 |
tl=int(np.median([len(h.audio) for h in cluster.hits])); al,wt=[],[]; pp=None
|
|
@@ -225,25 +358,35 @@ def synthesize_from_cluster(cluster):
|
|
| 225 |
elif s<0: a=a[-s:]
|
| 226 |
a=a[:tl] if len(a)>=tl else np.pad(a,(0,tl-len(a)))
|
| 227 |
pk=np.abs(a).max()
|
| 228 |
-
if pk>0: a
|
| 229 |
al.append(a); wt.append(2.0 if i==cluster.best_hit_idx else 1.0)
|
| 230 |
-
al=np.array(al); w=np.array(wt); w/=w.sum()
|
|
|
|
| 231 |
return (sy*0.95/pk).astype(np.float32) if pk>0 else sy.astype(np.float32)
|
| 232 |
|
| 233 |
-
# ─── Stage 7 ─────────────────────────────────────────
|
| 234 |
-
def
|
| 235 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 236 |
for i,c in enumerate(clusters): c.midi_note=min(36+i,127)
|
| 237 |
inst=pretty_midi.Instrument(program=0,is_drum=True,name='Samples'); pm.instruments.append(inst)
|
| 238 |
for c in clusters:
|
| 239 |
for h in c.hits:
|
| 240 |
-
|
| 241 |
-
|
|
|
|
|
|
|
| 242 |
inst.notes.sort(key=lambda n:n.start); return pm
|
| 243 |
-
def export_midi(clusters,path,bpm=120.0):
|
| 244 |
-
pm=build_midi(clusters,bpm); pm.write(path)
|
|
|
|
| 245 |
def detect_bpm(y,sr):
|
| 246 |
-
ck=("bpm",
|
| 247 |
if c: return c
|
| 248 |
oe=librosa.onset.onset_strength(y=y,sr=sr,aggregate=np.median)
|
| 249 |
bpm=float(librosa.feature.tempo(onset_envelope=oe,sr=sr).item())
|
|
@@ -290,147 +433,78 @@ def build_archive(clusters,bpm,sr,midi_path=None,rendered_audio=None):
|
|
| 290 |
zf.writestr('rendered_reconstruction.wav',rb.getvalue())
|
| 291 |
return zp
|
| 292 |
|
| 293 |
-
# ─── Auto-tuner with
|
| 294 |
-
|
| 295 |
-
def _spectral_envelope_corr(orig,rend,sr,n_fft=4096,hop=2048):
|
| 296 |
-
n=min(len(orig),len(rend))
|
| 297 |
-
if n<n_fft: return 0.0
|
| 298 |
-
eo=np.abs(librosa.stft(orig[:n],n_fft=n_fft,hop_length=hop)).mean(axis=1)
|
| 299 |
-
er=np.abs(librosa.stft(rend[:n],n_fft=n_fft,hop_length=hop)).mean(axis=1)
|
| 300 |
-
if eo.std()<1e-10 or er.std()<1e-10: return 0.0
|
| 301 |
-
return float(np.corrcoef(eo,er)[0,1])
|
| 302 |
-
|
| 303 |
-
def _rms_envelope_corr(orig,rend,sr,hop=1024):
|
| 304 |
-
n=min(len(orig),len(rend))
|
| 305 |
-
if n<hop*4: return 0.0
|
| 306 |
-
ro=librosa.feature.rms(y=orig[:n],hop_length=hop)[0]; rr=librosa.feature.rms(y=rend[:n],hop_length=hop)[0]
|
| 307 |
-
n2=min(len(ro),len(rr))
|
| 308 |
-
if n2<4: return 0.0
|
| 309 |
-
ro,rr=ro[:n2],rr[:n2]
|
| 310 |
-
if ro.std()<1e-10 or rr.std()<1e-10: return 0.0
|
| 311 |
-
return float(np.corrcoef(ro,rr)[0,1])
|
| 312 |
-
|
| 313 |
def _reconstruction_score(orig,rend,sr):
|
| 314 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 315 |
lr=min(len(rend),len(orig))/(max(len(rend),len(orig))+1)
|
| 316 |
return max(0.0,(sc*0.5+rc*0.4+lr*0.1)*100)
|
| 317 |
|
| 318 |
-
|
| 319 |
def auto_tune(stem_audio, sr, mode="auto", locks=None, log_fn=None):
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
log.append(m)
|
| 336 |
-
if log_fn: log_fn(m)
|
| 337 |
-
print(m)
|
| 338 |
-
|
| 339 |
-
locked_names = list(locks.keys())
|
| 340 |
-
_log(f"[Auto-tune] {len(stem_audio)/sr:.1f}s audio, locked: {locked_names or 'none'}")
|
| 341 |
-
|
| 342 |
-
# Build onset config grid — replace locked values with fixed ones
|
| 343 |
-
base_onset_configs = [
|
| 344 |
-
{"onset_delta": 0.08, "energy_threshold_db": -40, "min_gap": 0.02},
|
| 345 |
-
{"onset_delta": 0.10, "energy_threshold_db": -35, "min_gap": 0.025},
|
| 346 |
-
{"onset_delta": 0.12, "energy_threshold_db": -35, "min_gap": 0.03},
|
| 347 |
-
{"onset_delta": 0.15, "energy_threshold_db": -30, "min_gap": 0.04},
|
| 348 |
-
{"onset_delta": 0.20, "energy_threshold_db": -28, "min_gap": 0.05},
|
| 349 |
-
{"onset_delta": 0.25, "energy_threshold_db": -25, "min_gap": 0.06},
|
| 350 |
-
]
|
| 351 |
-
|
| 352 |
-
# Apply locks to onset configs
|
| 353 |
-
onset_configs = []
|
| 354 |
-
seen = set()
|
| 355 |
-
for oc in base_onset_configs:
|
| 356 |
-
for k in ['onset_delta', 'energy_threshold_db', 'min_gap']:
|
| 357 |
-
if k in locks:
|
| 358 |
-
oc[k] = locks[k]
|
| 359 |
-
# Deduplicate configs that become identical after locking
|
| 360 |
-
key = (oc['onset_delta'], oc['energy_threshold_db'], oc['min_gap'])
|
| 361 |
-
if key not in seen:
|
| 362 |
-
seen.add(key)
|
| 363 |
-
onset_configs.append(oc)
|
| 364 |
-
|
| 365 |
-
# Build cluster target grid — respect locks
|
| 366 |
if 'target_min' in locks and 'target_max' in locks:
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
cluster_targets = [3, 5, 8, 10, 15, 20, 30]
|
| 385 |
-
|
| 386 |
-
best_score, best_params = -1, {}
|
| 387 |
-
|
| 388 |
-
for oc_idx, oc in enumerate(onset_configs):
|
| 389 |
-
_log(f"\n [{oc_idx+1}/{len(onset_configs)}] delta={oc['onset_delta']}, "
|
| 390 |
-
f"energy={oc['energy_threshold_db']}dB, gap={oc['min_gap']}")
|
| 391 |
-
hits = detect_onsets(stem_audio, sr, mode=mode, **oc)
|
| 392 |
-
if len(hits) < 2: _log(f" {len(hits)} hits, skip"); continue
|
| 393 |
-
hits = classify_hits(hits)
|
| 394 |
-
|
| 395 |
-
for nt in cluster_targets:
|
| 396 |
-
if nt >= len(hits): continue
|
| 397 |
-
clusters = cluster_hits(hits, target_min=nt, target_max=nt, linkage='average')
|
| 398 |
-
if not clusters: continue
|
| 399 |
-
for c in clusters:
|
| 400 |
if c.count<=1: c.best_hit_idx=0
|
| 401 |
else: c.best_hit_idx=int(np.argmax([h.rms_energy for h in c.hits]))
|
| 402 |
-
|
| 403 |
-
score
|
| 404 |
-
if score
|
| 405 |
-
best_score
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
_log(f" ★ target={nt} → {len(clusters)} cl, score={score:.1f} BEST")
|
| 409 |
-
else:
|
| 410 |
-
_log(f" target={nt} → {len(clusters)} cl, score={score:.1f}")
|
| 411 |
-
|
| 412 |
-
# Fine-tune around best
|
| 413 |
if best_params:
|
| 414 |
-
bt
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
if not clusters: continue
|
| 425 |
-
for c in clusters:
|
| 426 |
if c.count<=1: c.best_hit_idx=0
|
| 427 |
else: c.best_hit_idx=int(np.argmax([h.rms_energy for h in c.hits]))
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
|
| 433 |
-
_log(f" ★ target={ft} → {len(clusters)} cl, score={score:.1f} BEST")
|
| 434 |
-
|
| 435 |
-
_log(f"\n[Auto-tune] Best: score={best_score:.1f}, params={best_params}")
|
| 436 |
return best_params, best_score, log
|
|
|
|
| 1 |
#!/usr/bin/env python3
|
| 2 |
"""
|
| 3 |
+
Sample Extractor v9 — Production quality.
|
| 4 |
+
|
| 5 |
+
Major improvements:
|
| 6 |
+
- SuperFlux onset detection (Böck & Widmer 2013) tuned for 140+ BPM
|
| 7 |
+
- Transient-only NCC: compare first 25ms (attack) not full clip
|
| 8 |
+
- Mel-spectrogram cosine pre-filter: eliminates 70% of NCC pairs
|
| 9 |
+
- Singleton cluster merging into nearest neighbor
|
| 10 |
+
- MIDI quantization to BPM grid (16th/32nd note snap)
|
| 11 |
+
- Parallel NCC computation via ThreadPoolExecutor
|
| 12 |
+
- All previous features: caching, target range, parameter locking
|
| 13 |
"""
|
| 14 |
|
| 15 |
+
import argparse, json, os, sys, warnings, hashlib, itertools
|
| 16 |
from collections import defaultdict
|
| 17 |
from dataclasses import dataclass, field
|
| 18 |
from pathlib import Path
|
| 19 |
from typing import Optional
|
| 20 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 21 |
|
| 22 |
import librosa, numpy as np, soundfile as sf, torch
|
| 23 |
from scipy.signal import fftconvolve
|
| 24 |
+
from scipy.spatial.distance import cdist
|
| 25 |
|
| 26 |
warnings.filterwarnings("ignore", category=FutureWarning)
|
| 27 |
warnings.filterwarnings("ignore", category=UserWarning)
|
|
|
|
| 30 |
class Hit:
|
| 31 |
audio: np.ndarray; sr: int; onset_time: float; duration: float; index: int
|
| 32 |
rms_energy: float = 0.0; spectral_centroid: float = 0.0
|
| 33 |
+
label: str = ""; cluster_id: int = -1
|
| 34 |
def save(self, path): sf.write(path, self.audio, self.sr, subtype='PCM_24')
|
| 35 |
|
| 36 |
@dataclass
|
|
|
|
| 43 |
def count(self): return len(self.hits)
|
| 44 |
|
| 45 |
DEMUCS_MODELS = ["htdemucs","htdemucs_ft","htdemucs_6s","mdx","mdx_extra","mdx_extra_q"]
|
| 46 |
+
DEMUCS_STEMS = {"htdemucs":["drums","bass","other","vocals"],"htdemucs_ft":["drums","bass","other","vocals"],
|
|
|
|
| 47 |
"htdemucs_6s":["drums","bass","other","vocals","guitar","piano"],
|
| 48 |
"mdx":["drums","bass","other","vocals"],"mdx_extra":["drums","bass","other","vocals"],
|
| 49 |
+
"mdx_extra_q":["drums","bass","other","vocals"]}
|
|
|
|
| 50 |
|
| 51 |
# ─── Cache ────────────────────────────────────────────────────────────────────
|
| 52 |
_cache = {}
|
| 53 |
+
def _ahash(a): return hashlib.md5(a[:4000].tobytes()).hexdigest()
|
| 54 |
def cache_get(k): return _cache.get(k)
|
| 55 |
def cache_set(k,v): _cache[k]=v; return v
|
| 56 |
def cache_clear(): _cache.clear()
|
| 57 |
|
| 58 |
+
# ─── Stage 1: Stem ───────────────────────────────────────────────────────────
|
| 59 |
def extract_stem(audio_path,stem="drums",device="cpu",model_name="htdemucs_ft",shifts=1,overlap=0.25):
|
| 60 |
if stem=="all":
|
| 61 |
y,sr=librosa.load(audio_path,sr=44100,mono=True); return y.astype(np.float32),sr
|
| 62 |
with open(audio_path,'rb') as f: fh=hashlib.md5(f.read(200000)).hexdigest()
|
| 63 |
ck=("stem",fh,stem,model_name,shifts,overlap); c=cache_get(ck)
|
| 64 |
+
if c: print(f"[Stem] cached"); return c
|
| 65 |
from demucs.pretrained import get_model; from demucs.apply import apply_model
|
| 66 |
+
print(f"[Stem] {stem} via {model_name}...")
|
| 67 |
model=get_model(model_name); model.eval().to(device); sr=model.samplerate
|
| 68 |
if stem not in model.sources: raise ValueError(f"'{stem}' not in {model.sources}")
|
| 69 |
a,_=librosa.load(audio_path,sr=sr,mono=False)
|
|
|
|
| 75 |
r=src[0,model.sources.index(stem)].mean(dim=0).cpu().numpy()
|
| 76 |
print(f" ✓ {len(r)/sr:.1f}s"); return cache_set(ck,(r.astype(np.float32),sr))
|
| 77 |
|
| 78 |
+
# ─── Stage 2: SuperFlux Onset Detection ──────────────────────────────────────
|
| 79 |
+
def detect_onsets(y,sr,pre_pad=0.003,min_dur=0.02,max_dur=1.5,min_gap=0.03,
|
| 80 |
+
energy_threshold_db=-35.0,mode="auto",onset_delta=0.12,
|
| 81 |
+
hop_length=220,n_fft=1024,max_size=3,lag=1,backtrack=True):
|
| 82 |
+
"""SuperFlux-based onset detection. hop_length=220 (~5ms) for 140+ BPM."""
|
| 83 |
+
print(f"[Onsets] mode={mode}, delta={onset_delta}, hop={hop_length}")
|
| 84 |
+
|
| 85 |
+
if mode == "percussive":
|
| 86 |
+
S = librosa.feature.melspectrogram(y=y,sr=sr,n_fft=n_fft,hop_length=hop_length,
|
| 87 |
+
n_mels=128,fmax=8000,power=1)
|
| 88 |
+
oe = librosa.onset.onset_strength(S=librosa.power_to_db(S,ref=np.max),sr=sr,
|
| 89 |
+
hop_length=hop_length,lag=lag,max_size=max_size)
|
| 90 |
+
elif mode == "harmonic":
|
| 91 |
yh,_=librosa.effects.hpss(y)
|
| 92 |
+
S = librosa.feature.melspectrogram(y=yh,sr=sr,n_fft=n_fft,hop_length=hop_length,
|
| 93 |
+
n_mels=128,fmax=8000,power=1)
|
| 94 |
+
oe = librosa.onset.onset_strength(S=librosa.power_to_db(S,ref=np.max),sr=sr,
|
| 95 |
+
hop_length=hop_length,lag=2,max_size=5)
|
| 96 |
+
elif mode == "broadband":
|
| 97 |
+
oe = librosa.onset.onset_strength(y=y,sr=sr,hop_length=hop_length)
|
| 98 |
+
else: # auto: SuperFlux multi-band
|
| 99 |
+
yh,_=librosa.effects.hpss(y)
|
| 100 |
+
def _sf(audio,fmin=None,fmax=None,ms=3,l=1):
|
| 101 |
+
S=librosa.feature.melspectrogram(y=audio,sr=sr,n_fft=n_fft,hop_length=hop_length,
|
| 102 |
+
n_mels=128,fmin=fmin or 20,fmax=fmax or sr//2,power=1)
|
| 103 |
+
return librosa.onset.onset_strength(S=librosa.power_to_db(S,ref=np.max),
|
| 104 |
+
sr=sr,hop_length=hop_length,lag=l,max_size=ms)
|
| 105 |
def _n(x): m=x.max(); return x/m if m>0 else x
|
| 106 |
+
oe = np.maximum.reduce([_n(_sf(y,20,300)), _n(_sf(y,300,4000)),
|
| 107 |
+
_n(_sf(y,4000,16000)), _n(_sf(yh,lag=2,ms=5))])
|
| 108 |
+
|
| 109 |
+
wait = max(1, int(min_gap * sr / hop_length))
|
| 110 |
+
fr = librosa.onset.onset_detect(onset_envelope=oe,sr=sr,hop_length=hop_length,
|
| 111 |
+
wait=wait,pre_avg=3,post_avg=3,pre_max=3,post_max=5,
|
| 112 |
+
delta=onset_delta,backtrack=backtrack,units='frames')
|
| 113 |
+
times = librosa.frames_to_time(fr,sr=sr,hop_length=hop_length)
|
| 114 |
+
print(f" Raw: {len(times)}")
|
| 115 |
+
|
| 116 |
thr=10**(energy_threshold_db/20); hits=[]
|
| 117 |
for i,t in enumerate(times):
|
| 118 |
s=max(0,int((t-pre_pad)*sr))
|
| 119 |
+
e=min(int(times[i+1]*sr) if i+1<len(times) else len(y), s+int(max_dur*sr))
|
| 120 |
seg=y[s:e]
|
| 121 |
if len(seg)<int(min_dur*sr): continue
|
| 122 |
rms=np.sqrt(np.mean(seg**2))
|
| 123 |
if rms<thr: continue
|
| 124 |
+
fl=min(int(0.003*sr),len(seg)//4)
|
| 125 |
if fl>0: seg=seg.copy(); seg[-fl:]*=np.linspace(1,0,fl)
|
| 126 |
sc=float(librosa.feature.spectral_centroid(y=seg,sr=sr).mean())
|
| 127 |
hits.append(Hit(audio=seg,sr=sr,onset_time=t,duration=len(seg)/sr,
|
| 128 |
index=len(hits),rms_energy=float(rms),spectral_centroid=sc))
|
| 129 |
print(f" ✓ {len(hits)} hits"); return hits
|
| 130 |
|
| 131 |
+
# ─── Stage 3: Classification ─────────────────────────────────────────────────
|
| 132 |
LABEL_RULES=[("kick",lambda lr,mr,hr,c,zcr,d:lr>0.5 and c<800),
|
| 133 |
("hihat_closed",lambda lr,mr,hr,c,zcr,d:hr>0.35 and c>4000 and d<0.15),
|
| 134 |
("hihat_open",lambda lr,mr,hr,c,zcr,d:hr>0.35 and c>4000 and d>=0.15),
|
|
|
|
| 141 |
def classify_hit(hit):
|
| 142 |
y,sr=hit.audio,hit.sr; D=np.abs(librosa.stft(y,n_fft=2048))
|
| 143 |
f=librosa.fft_frequencies(sr=sr,n_fft=2048)
|
| 144 |
+
le=np.sum(D[(f>=20)&(f<200)]**2); me=np.sum(D[(f>=200)&(f<4000)]**2); he=np.sum(D[(f>=4000)]**2)
|
| 145 |
+
t=le+me+he+1e-10; lr,mr,hr=le/t,me/t,he/t
|
| 146 |
zcr=float(librosa.feature.zero_crossing_rate(y=y).mean())
|
| 147 |
for n,fn in LABEL_RULES:
|
| 148 |
if fn(lr,mr,hr,hit.spectral_centroid,zcr,hit.duration): return n
|
| 149 |
return "other"
|
| 150 |
def classify_hits(hits):
|
| 151 |
+
print(f"[Classify] {len(hits)} hits...")
|
| 152 |
for h in hits: h.label=classify_hit(h)
|
| 153 |
c=defaultdict(int)
|
| 154 |
for h in hits: c[h.label]+=1
|
| 155 |
for l,n in sorted(c.items(),key=lambda x:-x[1]): print(f" {l}: {n}")
|
| 156 |
return hits
|
| 157 |
|
| 158 |
+
# ─── Stage 4: Two-stage clustering (mel pre-filter + transient NCC) ──────────
|
| 159 |
+
|
| 160 |
+
def _extract_transient(y, sr, onset_time, attack_ms=25.0):
|
| 161 |
+
"""Extract the 25ms attack transient — the perceptually defining part."""
|
| 162 |
+
n = int(attack_ms * sr / 1000)
|
| 163 |
+
s = max(0, int(onset_time * sr) - int(0.002 * sr)) # 2ms pre-onset
|
| 164 |
+
return y[s:s+n] if s+n <= len(y) else np.pad(y[s:], (0, s+n-len(y)))
|
| 165 |
+
|
| 166 |
+
def _transient_ncc(a, b):
|
| 167 |
+
"""NCC on equal-length transients. Fast: ~0.02ms per pair for 25ms clips."""
|
| 168 |
+
n = min(len(a), len(b)); a,b = a[:n].copy(), b[:n].copy()
|
| 169 |
+
a -= a.mean(); b -= b.mean()
|
| 170 |
+
na, nb = np.linalg.norm(a), np.linalg.norm(b)
|
| 171 |
+
if na < 1e-8 or nb < 1e-8: return 0.0
|
| 172 |
+
a /= na; b /= nb
|
| 173 |
+
cc = np.fft.irfft(np.fft.rfft(a, n=2*n) * np.conj(np.fft.rfft(b, n=2*n)))
|
| 174 |
+
return float(np.max(np.abs(cc)))
|
| 175 |
+
|
| 176 |
+
def _mel_fingerprint(y, sr, onset_time, window_ms=100, n_mels=64):
|
| 177 |
+
"""Compact mel fingerprint for cosine pre-filtering."""
|
| 178 |
+
s = max(0, int(onset_time * sr))
|
| 179 |
+
seg = y[s:s+int(window_ms/1000*sr)]
|
| 180 |
+
if len(seg) < 512: seg = np.pad(seg, (0, 512-len(seg)))
|
| 181 |
+
S = librosa.feature.melspectrogram(y=seg,sr=sr,n_fft=512,hop_length=256,n_mels=n_mels,power=2)
|
| 182 |
+
v = librosa.power_to_db(S, ref=np.max).flatten().astype(np.float32)
|
| 183 |
+
norm = np.linalg.norm(v)
|
| 184 |
+
return v / norm if norm > 1e-8 else v
|
| 185 |
+
|
| 186 |
+
def build_similarity_matrix(hits, sr, audio, attack_ms=25.0, mel_threshold=0.75):
|
| 187 |
+
"""Two-stage: mel cosine pre-filter → transient NCC only on candidates."""
|
| 188 |
+
N = len(hits)
|
| 189 |
+
key = ("sim_matrix", tuple(_ahash(h.audio) for h in hits), attack_ms)
|
| 190 |
+
c = cache_get(key)
|
| 191 |
+
if c is not None: print(f" Cached similarity matrix"); return c
|
| 192 |
+
|
| 193 |
+
print(f" Stage A: Mel fingerprints ({N} hits)...")
|
| 194 |
+
fps = [_mel_fingerprint(audio, sr, h.onset_time) for h in hits]
|
| 195 |
+
# Pad fingerprints to same length
|
| 196 |
+
maxl = max(len(f) for f in fps)
|
| 197 |
+
fps_padded = np.array([np.pad(f, (0, maxl-len(f))) if len(f)<maxl else f for f in fps])
|
| 198 |
+
mel_sim = 1.0 - cdist(fps_padded, fps_padded, metric='cosine') # (N,N)
|
| 199 |
+
|
| 200 |
+
print(f" Stage B: Transient NCC on {int((mel_sim > mel_threshold).sum()/2)} candidates...")
|
| 201 |
+
transients = [_extract_transient(audio, sr, h.onset_time, attack_ms) for h in hits]
|
| 202 |
+
sim = np.zeros((N, N), dtype=np.float32)
|
| 203 |
+
np.fill_diagonal(sim, 1.0)
|
| 204 |
+
|
| 205 |
+
# Only compute NCC for pairs that pass mel pre-filter
|
| 206 |
+
pairs = [(i,j) for i in range(N) for j in range(i+1,N) if mel_sim[i,j] > mel_threshold]
|
| 207 |
+
print(f" {len(pairs)} NCC pairs (of {N*(N-1)//2} total, saved {100-len(pairs)*100/max(1,N*(N-1)//2):.0f}%)")
|
| 208 |
+
|
| 209 |
+
# Parallel NCC for large pair counts
|
| 210 |
+
if len(pairs) > 500:
|
| 211 |
+
def _compute_chunk(chunk):
|
| 212 |
+
return [(i,j,_transient_ncc(transients[i],transients[j])) for i,j in chunk]
|
| 213 |
+
chunks = [pairs[k:k+64] for k in range(0,len(pairs),64)]
|
| 214 |
+
with ThreadPoolExecutor() as ex:
|
| 215 |
+
for res in ex.map(_compute_chunk, chunks):
|
| 216 |
+
for i,j,v in res: sim[i,j]=sim[j,i]=v
|
| 217 |
+
else:
|
| 218 |
+
for i,j in pairs: v=_transient_ncc(transients[i],transients[j]); sim[i,j]=sim[j,i]=v
|
| 219 |
+
|
| 220 |
+
return cache_set(key, sim)
|
| 221 |
+
|
| 222 |
+
def _labels_to_clusters(labels, hits):
|
| 223 |
cm=defaultdict(list)
|
| 224 |
for i,l in enumerate(labels): cm[l].append(i)
|
| 225 |
clusters=[]
|
|
|
|
| 231 |
clusters.sort(key=lambda c:c.count,reverse=True)
|
| 232 |
for i,c in enumerate(clusters): c.cluster_id=i
|
| 233 |
return clusters
|
| 234 |
+
|
| 235 |
+
def _merge_singletons(clusters, sim_matrix, hits, merge_ratio=2.0):
|
| 236 |
+
"""Merge singleton clusters into nearest multi-hit cluster if close enough."""
|
| 237 |
+
if len(clusters) < 2: return clusters
|
| 238 |
+
multi = [c for c in clusters if c.count > 1]
|
| 239 |
+
singles = [c for c in clusters if c.count == 1]
|
| 240 |
+
if not multi or not singles: return clusters
|
| 241 |
+
|
| 242 |
+
# For each singleton, find nearest multi-hit cluster
|
| 243 |
+
merged = 0
|
| 244 |
+
for sc in singles:
|
| 245 |
+
si = sc.hits[0].index # hit index in original list
|
| 246 |
+
best_dist, best_cluster = float('inf'), None
|
| 247 |
+
for mc in multi:
|
| 248 |
+
dists = [1.0 - sim_matrix[si, h.index] for h in mc.hits]
|
| 249 |
+
avg_dist = np.mean(dists)
|
| 250 |
+
# Cluster internal radius = mean pairwise distance
|
| 251 |
+
if len(mc.hits) >= 2:
|
| 252 |
+
internal = np.mean([1.0 - sim_matrix[mc.hits[a].index, mc.hits[b].index]
|
| 253 |
+
for a in range(len(mc.hits)) for b in range(a+1,len(mc.hits))])
|
| 254 |
+
else:
|
| 255 |
+
internal = 0.3 # default
|
| 256 |
+
if avg_dist < internal * merge_ratio and avg_dist < best_dist:
|
| 257 |
+
best_dist, best_cluster = avg_dist, mc
|
| 258 |
+
if best_cluster is not None:
|
| 259 |
+
best_cluster.hits.append(sc.hits[0])
|
| 260 |
+
merged += 1
|
| 261 |
+
else:
|
| 262 |
+
multi.append(sc) # keep as separate cluster
|
| 263 |
+
|
| 264 |
+
if merged > 0: print(f" Merged {merged} singletons")
|
| 265 |
+
# Re-sort and re-index
|
| 266 |
+
multi.sort(key=lambda c: c.count, reverse=True)
|
| 267 |
+
for i,c in enumerate(multi): c.cluster_id = i
|
| 268 |
+
return multi
|
| 269 |
+
|
| 270 |
+
def cluster_hits(hits, audio=None, sr=44100, ncc_threshold=0.80, attack_ms=25.0,
|
| 271 |
+
mel_threshold=0.75, target_min=0, target_max=0,
|
| 272 |
+
linkage='average', merge_singletons=True):
|
| 273 |
+
"""Two-stage clustering: mel pre-filter → transient NCC → agglomerative."""
|
| 274 |
from sklearn.cluster import AgglomerativeClustering as AC
|
| 275 |
if not hits: return []
|
| 276 |
+
N=len(hits)
|
| 277 |
if N==1: return [Cluster(cluster_id=0,label=f"{hits[0].label}_0",hits=[hits[0]])]
|
| 278 |
+
|
| 279 |
+
# Use the source audio for transient extraction if available
|
| 280 |
+
if audio is None:
|
| 281 |
+
# Fallback: concatenate hit audio (less accurate)
|
| 282 |
+
audio = np.concatenate([h.audio for h in hits])
|
| 283 |
+
|
| 284 |
+
print(f"[Cluster] {N} hits, attack={attack_ms}ms, mel_thresh={mel_threshold}")
|
| 285 |
+
sim = build_similarity_matrix(hits, sr, audio, attack_ms, mel_threshold)
|
| 286 |
+
D = np.clip(1.0 - sim, 0, 2).astype(np.float32) # distance matrix
|
| 287 |
+
|
| 288 |
+
use_t = target_min>0 and target_max>0 and target_max>=target_min
|
| 289 |
+
tmin,tmax = max(1,min(target_min or 1,N)), max(max(1,target_min or 1),min(target_max or N,N))
|
| 290 |
+
|
| 291 |
if use_t:
|
| 292 |
print(f" Target: {tmin}–{tmax}")
|
| 293 |
+
lo,hi=0.001,1.5; bl,bn=None,-1
|
| 294 |
for _ in range(30):
|
| 295 |
+
mid=(lo+hi)/2
|
| 296 |
+
lb=AC(n_clusters=None,distance_threshold=max(0.001,mid),metric='precomputed',linkage=linkage).fit_predict(D)
|
| 297 |
n=len(set(lb))
|
| 298 |
+
if tmin<=n<=tmax: bl,bn=lb,n; break
|
| 299 |
elif n>tmax: lo=mid
|
| 300 |
else: hi=mid
|
| 301 |
+
if bl is None or abs(n-(tmin+tmax)/2)<abs(bn-(tmin+tmax)/2): bl,bn=lb,n
|
| 302 |
if bn<tmin or bn>tmax:
|
| 303 |
+
tm=min((tmin+tmax)//2,N-1)
|
| 304 |
try: bl=AC(n_clusters=tm,metric='precomputed',linkage=linkage).fit_predict(D); bn=tm
|
| 305 |
except: pass
|
| 306 |
+
labels=bl; print(f" → {bn} clusters")
|
| 307 |
else:
|
| 308 |
+
dt=max(0.001,1.0-ncc_threshold)
|
| 309 |
labels=AC(n_clusters=None,distance_threshold=dt,metric='precomputed',linkage=linkage).fit_predict(D)
|
| 310 |
+
|
| 311 |
print(f" ✓ {len(set(labels))} clusters")
|
| 312 |
+
clusters = _labels_to_clusters(labels, hits)
|
| 313 |
+
|
| 314 |
+
if merge_singletons:
|
| 315 |
+
clusters = _merge_singletons(clusters, sim, hits)
|
| 316 |
+
|
| 317 |
+
for c in clusters: print(f" {c.label}: {c.count}")
|
| 318 |
+
return clusters
|
| 319 |
|
| 320 |
+
# ─── Stage 5: Quality scoring ────────────────────────────────────────────────
|
| 321 |
def sample_quality_score(y,sr,label="other"):
|
| 322 |
import scipy.stats
|
| 323 |
re=librosa.feature.rms(y=y,frame_length=512,hop_length=128)[0]
|
| 324 |
if len(re)>=10:
|
| 325 |
pk=np.argmax(re); po=re[pk:]
|
| 326 |
c1=max(0,1.0-np.mean(po[-max(3,len(po)//5):])/( re[pk]+1e-8)*5)
|
| 327 |
+
c2=(max(0,scipy.stats.linregress(np.arange(len(po)),np.log(po+1e-8))[2]**2)
|
| 328 |
+
if len(po)>=5 and scipy.stats.linregress(np.arange(len(po)),np.log(po+1e-8))[0]<0 else 0.0)
|
| 329 |
else: c1,c2=0.5,0.0
|
| 330 |
+
comp=c1*0.6+c2*0.4
|
| 331 |
+
snr=10*np.log10(np.percentile(y**2,99)/(np.percentile(y**2,10)+1e-12))
|
| 332 |
+
ns=np.clip((snr-10)/40,0,1)
|
| 333 |
+
ons=librosa.onset.onset_detect(y=y,sr=sr,units='samples',backtrack=True)
|
| 334 |
+
np2 = 0.5
|
| 335 |
if len(ons)>0:
|
| 336 |
o=int(ons[0]); pre=y[max(0,o-int(sr*.02)):o]; sig=y[o:o+int(sr*.1)]
|
| 337 |
+
if len(pre)>10 and len(sig)>10:
|
| 338 |
+
np2=np.clip((-10*np.log10(np.mean(pre**2+1e-12)/np.mean(sig**2+1e-12))-5)/30,0,1)
|
| 339 |
+
cl=ns*0.5+np2*0.5
|
| 340 |
+
oe=librosa.onset.onset_strength(y=y,sr=sr)
|
| 341 |
+
oq=float(np.clip((float(np.max(oe)/(np.mean(oe)+1e-8))-1.0)/5.0,0,1)) if len(oe)>1 else 0.0
|
| 342 |
return {'total':float((comp*0.30+cl*0.40+oq*0.20+0.5*0.10)*100),'completeness':float(comp),'cleanness':float(cl),'onset_quality':float(oq)}
|
| 343 |
def select_best(clusters):
|
| 344 |
+
print(f"[Select] best per cluster...")
|
| 345 |
for c in clusters:
|
| 346 |
if c.count<=1: c.best_hit_idx=0; continue
|
| 347 |
c.best_hit_idx=int(np.argmax([sample_quality_score(h.audio,h.sr,c.label.rsplit('_',1)[0])['total'] for h in c.hits]))
|
| 348 |
|
| 349 |
+
# ─── Stage 6: Synthesis ──────────────────────────────────────────────────────
|
| 350 |
def synthesize_from_cluster(cluster):
|
| 351 |
if cluster.count<2: return None
|
| 352 |
tl=int(np.median([len(h.audio) for h in cluster.hits])); al,wt=[],[]; pp=None
|
|
|
|
| 358 |
elif s<0: a=a[-s:]
|
| 359 |
a=a[:tl] if len(a)>=tl else np.pad(a,(0,tl-len(a)))
|
| 360 |
pk=np.abs(a).max()
|
| 361 |
+
if pk>0: a/=pk
|
| 362 |
al.append(a); wt.append(2.0 if i==cluster.best_hit_idx else 1.0)
|
| 363 |
+
al=np.array(al); w=np.array(wt); w/=w.sum()
|
| 364 |
+
sy=np.average(al,axis=0,weights=w); pk=np.abs(sy).max()
|
| 365 |
return (sy*0.95/pk).astype(np.float32) if pk>0 else sy.astype(np.float32)
|
| 366 |
|
| 367 |
+
# ─── Stage 7: MIDI with quantization ─────────────────────────────────────────
|
| 368 |
+
def quantize_time(t, bpm, subdivision=16):
|
| 369 |
+
"""Snap time to nearest grid position. subdivision: 4=quarter, 8=eighth, 16=sixteenth, 32=thirty-second."""
|
| 370 |
+
grid = 60.0 / bpm / (subdivision / 4)
|
| 371 |
+
return round(t / grid) * grid
|
| 372 |
+
|
| 373 |
+
def build_midi(clusters, bpm=120.0, quantize=True, subdivision=16):
|
| 374 |
+
import pretty_midi
|
| 375 |
+
pm=pretty_midi.PrettyMIDI(initial_tempo=bpm)
|
| 376 |
for i,c in enumerate(clusters): c.midi_note=min(36+i,127)
|
| 377 |
inst=pretty_midi.Instrument(program=0,is_drum=True,name='Samples'); pm.instruments.append(inst)
|
| 378 |
for c in clusters:
|
| 379 |
for h in c.hits:
|
| 380 |
+
t = quantize_time(h.onset_time, bpm, subdivision) if quantize else h.onset_time
|
| 381 |
+
v=max(1,min(127,int(h.rms_energy/0.3*127)))
|
| 382 |
+
inst.notes.append(pretty_midi.Note(velocity=v,pitch=c.midi_note,
|
| 383 |
+
start=max(0,t),end=max(0,t)+max(h.duration,0.05)))
|
| 384 |
inst.notes.sort(key=lambda n:n.start); return pm
|
| 385 |
+
def export_midi(clusters,path,bpm=120.0,quantize=True,subdivision=16):
|
| 386 |
+
pm=build_midi(clusters,bpm,quantize,subdivision); pm.write(path)
|
| 387 |
+
print(f" ✓ MIDI: {len(pm.instruments[0].notes)} notes" + (" (quantized)" if quantize else "")); return pm
|
| 388 |
def detect_bpm(y,sr):
|
| 389 |
+
ck=("bpm",_ahash(y),sr); c=cache_get(ck)
|
| 390 |
if c: return c
|
| 391 |
oe=librosa.onset.onset_strength(y=y,sr=sr,aggregate=np.median)
|
| 392 |
bpm=float(librosa.feature.tempo(onset_envelope=oe,sr=sr).item())
|
|
|
|
| 433 |
zf.writestr('rendered_reconstruction.wav',rb.getvalue())
|
| 434 |
return zp
|
| 435 |
|
| 436 |
+
# ─── Auto-tuner with locking ─────────────────────────────────────────────────
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 437 |
def _reconstruction_score(orig,rend,sr):
|
| 438 |
+
n=min(len(orig),len(rend))
|
| 439 |
+
if n<4096: return 0.0
|
| 440 |
+
eo=np.abs(librosa.stft(orig[:n],n_fft=4096,hop_length=2048)).mean(axis=1)
|
| 441 |
+
er=np.abs(librosa.stft(rend[:n],n_fft=4096,hop_length=2048)).mean(axis=1)
|
| 442 |
+
sc=float(np.corrcoef(eo,er)[0,1]) if eo.std()>1e-10 and er.std()>1e-10 else 0.0
|
| 443 |
+
ro=librosa.feature.rms(y=orig[:n],hop_length=1024)[0]
|
| 444 |
+
rr=librosa.feature.rms(y=rend[:n],hop_length=1024)[0]
|
| 445 |
+
n2=min(len(ro),len(rr)); ro,rr=ro[:n2],rr[:n2]
|
| 446 |
+
rc=float(np.corrcoef(ro,rr)[0,1]) if n2>4 and ro.std()>1e-10 and rr.std()>1e-10 else 0.0
|
| 447 |
lr=min(len(rend),len(orig))/(max(len(rend),len(orig))+1)
|
| 448 |
return max(0.0,(sc*0.5+rc*0.4+lr*0.1)*100)
|
| 449 |
|
|
|
|
| 450 |
def auto_tune(stem_audio, sr, mode="auto", locks=None, log_fn=None):
|
| 451 |
+
locks=locks or {}; log=[]
|
| 452 |
+
def _log(m): log.append(m); (log_fn(m) if log_fn else None); print(m)
|
| 453 |
+
_log(f"[Auto-tune] {len(stem_audio)/sr:.1f}s, locked={list(locks.keys()) or 'none'}")
|
| 454 |
+
base_ocs=[{"onset_delta":0.08,"energy_threshold_db":-40,"min_gap":0.02},
|
| 455 |
+
{"onset_delta":0.10,"energy_threshold_db":-35,"min_gap":0.025},
|
| 456 |
+
{"onset_delta":0.12,"energy_threshold_db":-35,"min_gap":0.03},
|
| 457 |
+
{"onset_delta":0.15,"energy_threshold_db":-30,"min_gap":0.04},
|
| 458 |
+
{"onset_delta":0.20,"energy_threshold_db":-28,"min_gap":0.05},
|
| 459 |
+
{"onset_delta":0.25,"energy_threshold_db":-25,"min_gap":0.06}]
|
| 460 |
+
seen=set(); ocs=[]
|
| 461 |
+
for oc in base_ocs:
|
| 462 |
+
for k in ['onset_delta','energy_threshold_db','min_gap']:
|
| 463 |
+
if k in locks: oc[k]=locks[k]
|
| 464 |
+
key=tuple(sorted(oc.items()))
|
| 465 |
+
if key not in seen: seen.add(key); ocs.append(oc)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 466 |
if 'target_min' in locks and 'target_max' in locks:
|
| 467 |
+
tmn,tmx=int(locks['target_min']),int(locks['target_max'])
|
| 468 |
+
cts=sorted(set([tmn,tmx,(tmn+tmx)//2,tmn+(tmx-tmn)//3,tmn+2*(tmx-tmn)//3]))
|
| 469 |
+
cts=[t for t in cts if tmn<=t<=tmx]
|
| 470 |
+
elif 'target_min' in locks: cts=[t for t in [3,5,8,10,15,20,30] if t>=int(locks['target_min'])]
|
| 471 |
+
elif 'target_max' in locks: cts=[t for t in [3,5,8,10,15,20,30] if t<=int(locks['target_max'])]
|
| 472 |
+
else: cts=[3,5,8,10,15,20,30]
|
| 473 |
+
best_score,best_params=-1,{}
|
| 474 |
+
for oi,oc in enumerate(ocs):
|
| 475 |
+
_log(f" [{oi+1}/{len(ocs)}] delta={oc['onset_delta']}, E={oc['energy_threshold_db']}dB")
|
| 476 |
+
hits=detect_onsets(stem_audio,sr,mode=mode,**oc)
|
| 477 |
+
if len(hits)<2: continue
|
| 478 |
+
hits=classify_hits(hits)
|
| 479 |
+
for nt in cts:
|
| 480 |
+
if nt>=len(hits): continue
|
| 481 |
+
cl=cluster_hits(hits,audio=stem_audio,sr=sr,target_min=nt,target_max=nt)
|
| 482 |
+
if not cl: continue
|
| 483 |
+
for c in cl:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 484 |
if c.count<=1: c.best_hit_idx=0
|
| 485 |
else: c.best_hit_idx=int(np.argmax([h.rms_energy for h in c.hits]))
|
| 486 |
+
rend=render_midi_with_samples(cl,sr=sr)
|
| 487 |
+
score=_reconstruction_score(stem_audio,rend,sr)
|
| 488 |
+
if score>best_score:
|
| 489 |
+
best_score=score; best_params={**oc,'target_min':nt,'target_max':nt,'n_clusters':len(cl)}
|
| 490 |
+
_log(f" ★ n={nt}→{len(cl)}cl, score={score:.1f} BEST")
|
| 491 |
+
else: _log(f" n={nt}→{len(cl)}cl, score={score:.1f}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 492 |
if best_params:
|
| 493 |
+
bt=best_params.get('target_min',10); foc={k:best_params[k] for k in ['onset_delta','energy_threshold_db','min_gap']}
|
| 494 |
+
_log(f" Fine-tune ±3 around {bt}...")
|
| 495 |
+
hits=detect_onsets(stem_audio,sr,mode=mode,**foc)
|
| 496 |
+
if len(hits)>=2:
|
| 497 |
+
hits=classify_hits(hits)
|
| 498 |
+
lo=max(2,int(locks.get('target_min',bt-3))); hi=min(len(hits)-1,int(locks.get('target_max',bt+3)))
|
| 499 |
+
for ft in range(lo,hi+1):
|
| 500 |
+
cl=cluster_hits(hits,audio=stem_audio,sr=sr,target_min=ft,target_max=ft)
|
| 501 |
+
if not cl: continue
|
| 502 |
+
for c in cl:
|
|
|
|
|
|
|
| 503 |
if c.count<=1: c.best_hit_idx=0
|
| 504 |
else: c.best_hit_idx=int(np.argmax([h.rms_energy for h in c.hits]))
|
| 505 |
+
rend=render_midi_with_samples(cl,sr=sr); score=_reconstruction_score(stem_audio,rend,sr)
|
| 506 |
+
if score>best_score:
|
| 507 |
+
best_score=score; best_params={**foc,'target_min':ft,'target_max':ft,'n_clusters':len(cl)}
|
| 508 |
+
_log(f" ★ n={ft}→{len(cl)}cl, score={score:.1f} BEST")
|
| 509 |
+
_log(f"\n[Auto-tune] Best: score={best_score:.1f}, {best_params}")
|
|
|
|
|
|
|
|
|
|
| 510 |
return best_params, best_score, log
|