rikhoffbauer2 commited on
Commit
db5b927
Β·
verified Β·
1 Parent(s): 8240217

v4: app.py entry point

Browse files
Files changed (1) hide show
  1. app.py +149 -163
app.py CHANGED
@@ -1,15 +1,10 @@
1
  """
2
- Gradio UI β€” Sample Extractor v3.
3
-
4
- Tabs:
5
- 1. Extract β€” Upload audio, auto-detect BPM, extract samples, MIDI, rendered reconstruction, ZIP archive
6
- 2. Evaluate β€” Synthetic ground-truth comparison
7
- 3. Optimize β€” Autonomous improvement loop with Hub persistence
8
- 4. Leaderboard β€” Ranked configs from HF Hub
9
  """
10
 
11
  import gradio as gr
12
- import numpy as np, pandas as pd, json, time, sys, os, tempfile
13
  import soundfile as sf, librosa
14
  import matplotlib; matplotlib.use('Agg')
15
  import matplotlib.pyplot as plt
@@ -17,15 +12,16 @@ import matplotlib.pyplot as plt
17
  sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
18
 
19
  from sample_extractor import (
20
- extract_stem, detect_onsets, classify_and_separate,
21
- compute_embeddings, cluster_hits, select_best,
22
- synthesize_from_cluster, sample_quality_score, export_midi,
23
- detect_bpm, render_midi_with_samples, build_archive,
 
24
  )
25
  from synth_generator import generate_test_song
26
- from evaluation import evaluate_extraction, report_to_dict
27
- from config_store import PipelineConfig, list_configs, load_config, get_leaderboard
28
- from optimizer_v2 import run_optimization, OptimizerState
29
 
30
 
31
  def audio_tuple(a, sr):
@@ -37,9 +33,12 @@ def audio_tuple(a, sr):
37
 
38
  # ─── Tab 1: Extract ──────────────────────────────────────────────────────────
39
 
40
- def run_extraction(audio_in, stem_choice, onset_mode, progress=gr.Progress()):
 
 
 
41
  if audio_in is None:
42
- return [None]*8
43
 
44
  progress(0.0, desc="Loading audio...")
45
  sr_in, data = audio_in
@@ -52,125 +51,106 @@ def run_extraction(audio_in, stem_choice, onset_mode, progress=gr.Progress()):
52
  sf.write(f.name, data, sr_in); tmp = f.name
53
 
54
  try:
55
- # Stage 1: Stem extraction
56
- progress(0.05, desc=f"Extracting {stem_choice} stem...")
57
- stem_audio, stem_sr = extract_stem(tmp, stem=stem_choice, device="cpu")
 
 
58
 
59
- # Auto BPM detection
60
  progress(0.15, desc="Detecting BPM...")
61
  bpm = detect_bpm(stem_audio, stem_sr)
62
 
63
  progress(0.25, desc="Detecting onsets...")
64
- hits = detect_onsets(stem_audio, stem_sr, mode=onset_mode)
 
 
 
 
65
  if not hits:
66
- return (audio_tuple(stem_audio, stem_sr), f"**Detected BPM: {bpm}**\n\nNo hits found.",
67
- None, None, None, None, None, pd.DataFrame())
 
68
 
69
- progress(0.4, desc="Classifying & separating...")
70
- hits = classify_and_separate(hits)
71
 
72
- progress(0.5, desc="Clustering...")
73
- embs = compute_embeddings(hits)
74
- clusters = cluster_hits(hits, embs)
75
 
76
- progress(0.6, desc="Scoring & selecting best...")
77
  select_best(clusters)
78
 
79
- progress(0.7, desc="Synthesizing...")
80
- for c in clusters:
81
- if c.count >= 2:
82
- c.synthesized = synthesize_from_cluster(c)
83
 
84
- # MIDI
85
  progress(0.75, desc="Building MIDI...")
86
  midi_path = tempfile.mktemp(suffix='.mid')
87
  export_midi(clusters, midi_path, bpm=bpm)
88
 
89
- # Render MIDI with extracted samples
90
- progress(0.8, desc="Rendering reconstruction from samples...")
91
  rendered = render_midi_with_samples(clusters, sr=stem_sr)
92
- rendered_out = audio_tuple(rendered, stem_sr)
93
 
94
- # Build sample WAV files for download
95
- progress(0.85, desc="Packaging samples...")
96
  sample_dir = tempfile.mkdtemp()
97
  sample_paths = []
98
  for c in sorted(clusters, key=lambda x: x.count, reverse=True):
99
  sp = os.path.join(sample_dir, f"{c.label}.wav")
100
- c.best_hit.save(sp)
101
- sample_paths.append(sp)
102
 
103
- # Build ZIP archive
104
- progress(0.9, desc="Building archive...")
105
  zip_path = build_archive(clusters, bpm, stem_sr,
106
  midi_path=midi_path, rendered_audio=rendered)
107
 
108
- # Metrics table
109
  rows = []
110
  for c in sorted(clusters, key=lambda x: x.count, reverse=True):
111
  best = c.best_hit
112
  sc = sample_quality_score(best.audio, best.sr, c.label.rsplit('_',1)[0])
113
- onset_times = sorted([h.onset_time for h in c.hits])
114
  rows.append({
115
- 'Sample': c.label,
116
- 'Hits': c.count,
117
- 'MIDI': c.midi_note,
118
  'Score': f"{sc['total']:.1f}",
119
  'Clean': f"{sc['cleanness']:.2f}",
120
  'Complete': f"{sc['completeness']:.2f}",
121
  'Dur (ms)': f"{best.duration*1000:.0f}",
122
- 'First @': f"{onset_times[0]:.2f}s",
123
  })
124
- metrics_df = pd.DataFrame(rows)
125
 
126
- # Summary markdown
127
- summary = f"**Detected BPM: {bpm}** Β· "
128
- summary += f"**{len(clusters)} unique samples** from {len(hits)} total hits\n\n"
129
- summary += "The MIDI file maps each sample to a unique note. "
130
- summary += "Load in your DAW and assign the WAV samples to hear the reconstruction.\n\n"
131
  summary += "| Sample | Hits | MIDI Note |\n|---|---|---|\n"
132
  for c in sorted(clusters, key=lambda x: x.count, reverse=True):
133
  summary += f"| {c.label} | {c.count} | {c.midi_note} |\n"
134
 
135
  progress(1.0, desc="Done!")
136
- return (
137
- audio_tuple(stem_audio, stem_sr), # stem
138
- summary, # summary markdown
139
- rendered_out, # rendered reconstruction
140
- sample_paths, # individual WAVs
141
- midi_path, # MIDI file
142
- zip_path, # ZIP archive
143
- "", # status (hidden)
144
- metrics_df, # metrics table
145
- )
146
-
147
  finally:
148
  os.unlink(tmp)
149
 
150
 
151
  # ─── Tab 2: Evaluate ─────────────────────────────────────────────────────────
152
 
153
- def run_eval(pattern, bpm, bars, progress=gr.Progress()):
154
  progress(0.0, desc="Generating synthetic song...")
155
  song = generate_test_song(pattern_name=pattern, bars=int(bars),
156
  bpm=float(bpm), variation='medium', seed=42)
157
 
158
- progress(0.1, desc="Detecting BPM...")
159
  detected_bpm = detect_bpm(song.drums_only, song.sr)
160
 
161
  progress(0.2, desc="Extracting...")
162
  hits = detect_onsets(song.drums_only, song.sr)
163
- if not hits:
164
- return None, None, None, None, None, None
165
 
166
- hits = classify_and_separate(hits)
167
- embs = compute_embeddings(hits)
168
- clusters = cluster_hits(hits, embs)
169
  select_best(clusters)
170
  for c in clusters:
171
  if c.count >= 2: c.synthesized = synthesize_from_cluster(c)
172
 
173
- progress(0.5, desc="Rendering reconstruction...")
174
  rendered = render_midi_with_samples(clusters, sr=song.sr)
175
 
176
  progress(0.6, desc="Evaluating...")
@@ -179,26 +159,21 @@ def run_eval(pattern, bpm, bars, progress=gr.Progress()):
179
  for h in song.hits]
180
  report = evaluate_extraction(clusters, gt, gt_hits, song.sr, hits)
181
 
182
- progress(0.8, desc="Building report...")
183
  mix_out = audio_tuple(song.mix, song.sr)
184
  rendered_out = audio_tuple(rendered, song.sr)
185
 
186
  summary = [
187
  {'Metric': 'Detected BPM', 'Value': f"{detected_bpm}", 'Target': f"{song.bpm}"},
188
- {'Metric': 'Overall Score', 'Value': f"{report.overall_score:.1f}/100", 'Target': '> 70'},
189
- {'Metric': 'SI-SDR', 'Value': f"{report.mean_si_sdr:.1f} dB", 'Target': '> 10 dB'},
190
- {'Metric': 'Sample Score', 'Value': f"{report.mean_sample_score:.1f}/100", 'Target': '> 60'},
191
  {'Metric': 'Env Corr', 'Value': f"{report.mean_env_corr:.3f}", 'Target': '> 0.9'},
192
- {'Metric': 'Onset Error', 'Value': f"{report.mean_onset_error_ms:.1f} ms", 'Target': '< 10'},
193
- {'Metric': 'Hit Accuracy', 'Value': f"{report.hit_count_accuracy:.2f}", 'Target': '> 0.9'},
194
- {'Metric': 'Coverage', 'Value': f"{len(report.matches)}/{len(gt)}", 'Target': 'All'},
195
  ]
196
  if report.unmatched_gt:
197
  summary.append({'Metric': '⚠ Unmatched', 'Value': ', '.join(report.unmatched_gt), 'Target': 'None'})
198
 
199
  matches = [{'Cluster': m.cluster_label, 'GT': m.gt_name, 'SI-SDR': f"{m.si_sdr:.1f}",
200
- 'Env Corr': f"{m.envelope_corr:.3f}", 'Score': f"{m.sample_score:.1f}",
201
- 'Onset (ms)': f"{m.onset_precision_ms:.1f}"} for m in report.matches]
202
 
203
  progress(1.0)
204
  return (mix_out, rendered_out, pd.DataFrame(summary),
@@ -209,34 +184,20 @@ def run_eval(pattern, bpm, bars, progress=gr.Progress()):
209
 
210
  def run_optimize(n_iters, config_name, author, save_hub, progress=gr.Progress()):
211
  logs = []
212
- def log_fn(msg): logs.append(msg)
213
  progress(0.0, desc="Starting optimization...")
214
-
215
- state = run_optimization(
216
- n_iterations=int(n_iters), config_name=config_name or "optimized",
217
- author=author or "anonymous", save_to_hub=bool(save_hub),
218
- log_fn=log_fn,
219
- )
220
-
221
  progress(1.0)
222
-
223
  hist = [{'Iter': r.iteration, 'Score': f"{r.avg_score:.1f}",
224
- 'Time': f"{r.duration_s:.1f}s",
225
- 'Changes': '; '.join(r.changes[:2])} for r in state.history]
226
-
227
  if state.history:
228
- iters = [r.iteration for r in state.history]
229
- scores = [r.avg_score for r in state.history]
230
  fig, ax = plt.subplots(figsize=(10, 4))
231
- ax.plot(iters, scores, 'b-o', linewidth=2)
232
- best_i = np.argmax(scores)
233
- ax.scatter([iters[best_i]], [scores[best_i]], color='red', s=100, zorder=5,
234
- label=f'Best: {scores[best_i]:.1f}')
235
- ax.set_xlabel('Iteration'); ax.set_ylabel('Score'); ax.set_title('Optimization Progress')
236
- ax.legend(); ax.grid(True, alpha=0.3); plt.tight_layout()
237
  else:
238
  fig, ax = plt.subplots(); ax.text(0.5, 0.5, "No data")
239
-
240
  return '\n'.join(logs), pd.DataFrame(hist), fig, json.dumps(state.best_config, indent=2)
241
 
242
 
@@ -245,92 +206,119 @@ def run_optimize(n_iters, config_name, author, save_hub, progress=gr.Progress())
245
  def refresh_leaderboard():
246
  try:
247
  lb = get_leaderboard()
248
- if lb:
249
- return pd.DataFrame(lb), ""
250
- return pd.DataFrame(), "No configs found yet. Run the optimizer to create one!"
251
  except Exception as e:
252
- return pd.DataFrame(), f"Could not load leaderboard: {e}"
 
253
 
 
254
 
255
- # ─── App ──────────────────────────────────────────────────────────────────────
 
 
256
 
257
  def build_app():
258
  with gr.Blocks(title="🎡 Sample Extractor", theme=gr.themes.Soft(),
259
- css=".gradio-container{max-width:1200px!important}") as app:
260
- gr.Markdown("""
261
- # 🎡 Sample Extractor
262
- Extract **any distinct sound** β€” drum hits, vocal stabs, guitar plucks, SFX β€” from audio.
263
- Auto-detects BPM, clusters identical occurrences, picks the best representative,
264
- reconstructs the song as MIDI, and renders it back to audio using extracted samples.
265
- """)
266
 
267
  with gr.Tabs():
268
  # ── Extract ──
269
  with gr.Tab("🎡 Extract"):
270
- with gr.Row():
271
- audio_in = gr.Audio(sources=['upload'], type='numpy', label='Upload Audio')
272
- with gr.Row():
273
- stem_dd = gr.Dropdown(['drums','bass','vocals','other','all'], value='all',
274
- label='Stem to extract')
275
- onset_dd = gr.Dropdown(['auto','percussive','harmonic','broadband'], value='auto',
276
- label='Onset detection mode')
277
- extract_btn = gr.Button("πŸ”¬ Extract Samples", variant="primary", size="lg")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
278
 
279
- # Results
280
- summary_md = gr.Markdown("*Upload audio and click Extract to begin*")
281
 
 
282
  with gr.Row():
283
- stem_out = gr.Audio(type='numpy', label='Extracted Stem', interactive=False)
284
- rendered_out = gr.Audio(type='numpy', label='πŸ”Š Rendered Reconstruction',
285
- interactive=False)
286
 
287
  gr.Markdown("### Downloads")
288
  with gr.Row():
289
- archive_file = gr.File(label="πŸ“¦ Full Archive (ZIP β€” all samples + MIDI + rendered + index)",
290
- interactive=False)
291
- midi_file = gr.File(label="🎹 MIDI File", interactive=False)
292
-
293
- gr.Markdown("### Individual Samples")
294
- sample_files = gr.File(label="WAV files (all clusters)", file_count="multiple",
295
  interactive=False)
296
-
297
- gr.Markdown("### Quality Metrics")
298
- metrics_tbl = gr.Dataframe(label="All Extracted Samples")
299
  status_txt = gr.Textbox(visible=False)
300
 
 
 
 
 
 
301
  extract_btn.click(
302
- run_extraction, [audio_in, stem_dd, onset_dd],
 
 
 
303
  [stem_out, summary_md, rendered_out, sample_files,
304
- midi_file, archive_file, status_txt, metrics_tbl],
305
- )
306
 
307
  # ── Evaluate ──
308
  with gr.Tab("πŸ“Š Evaluate"):
309
- gr.Markdown("Generate a synthetic song with known samples, extract, and compare. "
310
- "Includes auto BPM detection and rendered reconstruction.")
311
  with gr.Row():
312
  ev_pat = gr.Dropdown(['rock','funk','halftime'], value='rock', label='Pattern')
313
  ev_bpm = gr.Slider(80, 200, value=120, step=2, label='BPM')
314
  ev_bars = gr.Slider(2, 8, value=4, step=1, label='Bars')
 
315
  ev_btn = gr.Button("πŸ§ͺ Evaluate", variant="primary", size="lg")
316
  with gr.Row():
317
- ev_mix = gr.Audio(type='numpy', label='Original Mix', interactive=False)
318
- ev_rendered = gr.Audio(type='numpy', label='Rendered Reconstruction',
319
- interactive=False)
320
  ev_summary = gr.Dataframe(label="Summary")
321
  ev_matches = gr.Dataframe(label="Matches")
322
- ev_status = gr.Textbox(visible=False)
323
- ev_status2 = gr.Textbox(visible=False)
324
- ev_btn.click(run_eval, [ev_pat, ev_bpm, ev_bars],
325
- [ev_mix, ev_rendered, ev_summary, ev_matches, ev_status, ev_status2])
326
 
327
  # ── Optimize ──
328
  with gr.Tab("πŸ”„ Optimize"):
329
- gr.Markdown("""
330
- ### Autonomous Optimization
331
- Tests each config across **6 diverse synthetic songs** (rock/funk/halftime at various BPMs).
332
- Best config is saved to HuggingFace Hub and appears on the leaderboard.
333
- """)
334
  with gr.Row():
335
  opt_n = gr.Slider(2, 30, value=5, step=1, label='Iterations')
336
  opt_name = gr.Textbox(value="optimized", label='Config name')
@@ -340,20 +328,18 @@ def build_app():
340
  opt_log = gr.Textbox(label="Log", lines=20, max_lines=40)
341
  opt_hist = gr.Dataframe(label="History")
342
  opt_plot = gr.Plot(label="Progress")
343
- opt_params = gr.Code(label="Best Config (JSON)", language="json")
344
  opt_btn.click(run_optimize, [opt_n, opt_name, opt_author, opt_save],
345
  [opt_log, opt_hist, opt_plot, opt_params])
346
 
347
  # ── Leaderboard ──
348
  with gr.Tab("πŸ† Leaderboard"):
349
- gr.Markdown("### Config Leaderboard\nRanked by average score across test songs.")
350
- lb_btn = gr.Button("πŸ”„ Refresh", variant="secondary")
351
- lb_tbl = gr.Dataframe(label="Leaderboard")
352
- lb_status = gr.Textbox(visible=False)
353
- lb_btn.click(refresh_leaderboard, [], [lb_tbl, lb_status])
354
 
355
  return app
356
 
357
-
358
  if __name__ == "__main__":
359
  build_app().launch(server_name="0.0.0.0", server_port=7860)
 
1
  """
2
+ Gradio UI β€” Sample Extractor v4.
3
+ NCC clustering, full parameter control, Demucs model selection.
 
 
 
 
 
4
  """
5
 
6
  import gradio as gr
7
+ import numpy as np, pandas as pd, json, sys, os, tempfile
8
  import soundfile as sf, librosa
9
  import matplotlib; matplotlib.use('Agg')
10
  import matplotlib.pyplot as plt
 
12
  sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
13
 
14
  from sample_extractor import (
15
+ extract_stem, detect_onsets, classify_hits,
16
+ cluster_hits, select_best, synthesize_from_cluster,
17
+ sample_quality_score, export_midi, detect_bpm,
18
+ render_midi_with_samples, build_archive,
19
+ DEMUCS_MODELS, DEMUCS_STEMS,
20
  )
21
  from synth_generator import generate_test_song
22
+ from evaluation import evaluate_extraction
23
+ from config_store import PipelineConfig, get_leaderboard
24
+ from optimizer_v2 import run_optimization
25
 
26
 
27
  def audio_tuple(a, sr):
 
33
 
34
  # ─── Tab 1: Extract ──────────────────────────────────────────────────────────
35
 
36
+ def run_extraction(audio_in, stem_choice, demucs_model, demucs_shifts, demucs_overlap,
37
+ onset_mode, onset_delta, energy_db, pre_pad, min_dur, max_dur, min_gap,
38
+ ncc_threshold, ncc_compare_ms,
39
+ do_synthesize, progress=gr.Progress()):
40
  if audio_in is None:
41
+ return [None] * 8
42
 
43
  progress(0.0, desc="Loading audio...")
44
  sr_in, data = audio_in
 
51
  sf.write(f.name, data, sr_in); tmp = f.name
52
 
53
  try:
54
+ progress(0.05, desc=f"Extracting {stem_choice} stem ({demucs_model})...")
55
+ stem_audio, stem_sr = extract_stem(
56
+ tmp, stem=stem_choice, device="cpu",
57
+ model_name=demucs_model, shifts=int(demucs_shifts),
58
+ overlap=float(demucs_overlap))
59
 
 
60
  progress(0.15, desc="Detecting BPM...")
61
  bpm = detect_bpm(stem_audio, stem_sr)
62
 
63
  progress(0.25, desc="Detecting onsets...")
64
+ hits = detect_onsets(stem_audio, stem_sr, mode=onset_mode,
65
+ onset_delta=float(onset_delta),
66
+ energy_threshold_db=float(energy_db),
67
+ pre_pad=float(pre_pad), min_dur=float(min_dur),
68
+ max_dur=float(max_dur), min_gap=float(min_gap))
69
  if not hits:
70
+ return (audio_tuple(stem_audio, stem_sr),
71
+ f"**Detected BPM: {bpm}**\n\nNo hits found β€” try lowering energy threshold.",
72
+ None, None, None, None, "", pd.DataFrame())
73
 
74
+ progress(0.35, desc="Classifying...")
75
+ hits = classify_hits(hits)
76
 
77
+ progress(0.45, desc=f"NCC clustering (threshold={ncc_threshold})...")
78
+ clusters = cluster_hits(hits, ncc_threshold=float(ncc_threshold),
79
+ max_compare_ms=float(ncc_compare_ms))
80
 
81
+ progress(0.65, desc="Scoring & selecting best...")
82
  select_best(clusters)
83
 
84
+ if do_synthesize:
85
+ progress(0.7, desc="Synthesizing...")
86
+ for c in clusters:
87
+ if c.count >= 2: c.synthesized = synthesize_from_cluster(c)
88
 
 
89
  progress(0.75, desc="Building MIDI...")
90
  midi_path = tempfile.mktemp(suffix='.mid')
91
  export_midi(clusters, midi_path, bpm=bpm)
92
 
93
+ progress(0.8, desc="Rendering reconstruction...")
 
94
  rendered = render_midi_with_samples(clusters, sr=stem_sr)
 
95
 
96
+ progress(0.85, desc="Packaging...")
 
97
  sample_dir = tempfile.mkdtemp()
98
  sample_paths = []
99
  for c in sorted(clusters, key=lambda x: x.count, reverse=True):
100
  sp = os.path.join(sample_dir, f"{c.label}.wav")
101
+ c.best_hit.save(sp); sample_paths.append(sp)
 
102
 
 
 
103
  zip_path = build_archive(clusters, bpm, stem_sr,
104
  midi_path=midi_path, rendered_audio=rendered)
105
 
106
+ # Metrics
107
  rows = []
108
  for c in sorted(clusters, key=lambda x: x.count, reverse=True):
109
  best = c.best_hit
110
  sc = sample_quality_score(best.audio, best.sr, c.label.rsplit('_',1)[0])
 
111
  rows.append({
112
+ 'Sample': c.label, 'Hits': c.count, 'MIDI': c.midi_note,
 
 
113
  'Score': f"{sc['total']:.1f}",
114
  'Clean': f"{sc['cleanness']:.2f}",
115
  'Complete': f"{sc['completeness']:.2f}",
116
  'Dur (ms)': f"{best.duration*1000:.0f}",
117
+ 'First @': f"{sorted(h.onset_time for h in c.hits)[0]:.2f}s",
118
  })
 
119
 
120
+ summary = f"**Detected BPM: {bpm}** Β· **{len(clusters)} unique samples** from {len(hits)} hits\n\n"
121
+ summary += f"Model: `{demucs_model}` Β· NCC threshold: `{ncc_threshold}` Β· Onset delta: `{onset_delta}`\n\n"
 
 
 
122
  summary += "| Sample | Hits | MIDI Note |\n|---|---|---|\n"
123
  for c in sorted(clusters, key=lambda x: x.count, reverse=True):
124
  summary += f"| {c.label} | {c.count} | {c.midi_note} |\n"
125
 
126
  progress(1.0, desc="Done!")
127
+ return (audio_tuple(stem_audio, stem_sr), summary,
128
+ audio_tuple(rendered, stem_sr), sample_paths,
129
+ midi_path, zip_path, "", pd.DataFrame(rows))
 
 
 
 
 
 
 
 
130
  finally:
131
  os.unlink(tmp)
132
 
133
 
134
  # ─── Tab 2: Evaluate ─────────────────────────────────────────────────────────
135
 
136
+ def run_eval(pattern, bpm, bars, ncc_threshold, progress=gr.Progress()):
137
  progress(0.0, desc="Generating synthetic song...")
138
  song = generate_test_song(pattern_name=pattern, bars=int(bars),
139
  bpm=float(bpm), variation='medium', seed=42)
140
 
 
141
  detected_bpm = detect_bpm(song.drums_only, song.sr)
142
 
143
  progress(0.2, desc="Extracting...")
144
  hits = detect_onsets(song.drums_only, song.sr)
145
+ if not hits: return None, None, None, None, "", ""
 
146
 
147
+ hits = classify_hits(hits)
148
+ clusters = cluster_hits(hits, ncc_threshold=float(ncc_threshold))
 
149
  select_best(clusters)
150
  for c in clusters:
151
  if c.count >= 2: c.synthesized = synthesize_from_cluster(c)
152
 
153
+ progress(0.5, desc="Rendering...")
154
  rendered = render_midi_with_samples(clusters, sr=song.sr)
155
 
156
  progress(0.6, desc="Evaluating...")
 
159
  for h in song.hits]
160
  report = evaluate_extraction(clusters, gt, gt_hits, song.sr, hits)
161
 
 
162
  mix_out = audio_tuple(song.mix, song.sr)
163
  rendered_out = audio_tuple(rendered, song.sr)
164
 
165
  summary = [
166
  {'Metric': 'Detected BPM', 'Value': f"{detected_bpm}", 'Target': f"{song.bpm}"},
167
+ {'Metric': 'Clusters', 'Value': str(len(clusters)), 'Target': str(len(gt))},
168
+ {'Metric': 'Overall', 'Value': f"{report.overall_score:.1f}/100", 'Target': '> 70'},
169
+ {'Metric': 'SI-SDR', 'Value': f"{report.mean_si_sdr:.1f} dB", 'Target': '> 10'},
170
  {'Metric': 'Env Corr', 'Value': f"{report.mean_env_corr:.3f}", 'Target': '> 0.9'},
 
 
 
171
  ]
172
  if report.unmatched_gt:
173
  summary.append({'Metric': '⚠ Unmatched', 'Value': ', '.join(report.unmatched_gt), 'Target': 'None'})
174
 
175
  matches = [{'Cluster': m.cluster_label, 'GT': m.gt_name, 'SI-SDR': f"{m.si_sdr:.1f}",
176
+ 'Score': f"{m.sample_score:.1f}"} for m in report.matches]
 
177
 
178
  progress(1.0)
179
  return (mix_out, rendered_out, pd.DataFrame(summary),
 
184
 
185
  def run_optimize(n_iters, config_name, author, save_hub, progress=gr.Progress()):
186
  logs = []
 
187
  progress(0.0, desc="Starting optimization...")
188
+ state = run_optimization(n_iterations=int(n_iters),
189
+ config_name=config_name or "optimized",
190
+ author=author or "anonymous",
191
+ save_to_hub=bool(save_hub), log_fn=lambda m: logs.append(m))
 
 
 
192
  progress(1.0)
 
193
  hist = [{'Iter': r.iteration, 'Score': f"{r.avg_score:.1f}",
194
+ 'Time': f"{r.duration_s:.1f}s"} for r in state.history]
 
 
195
  if state.history:
 
 
196
  fig, ax = plt.subplots(figsize=(10, 4))
197
+ ax.plot([r.iteration for r in state.history], [r.avg_score for r in state.history], 'b-o')
198
+ ax.set_xlabel('Iteration'); ax.set_ylabel('Score'); ax.grid(True, alpha=0.3); plt.tight_layout()
 
 
 
 
199
  else:
200
  fig, ax = plt.subplots(); ax.text(0.5, 0.5, "No data")
 
201
  return '\n'.join(logs), pd.DataFrame(hist), fig, json.dumps(state.best_config, indent=2)
202
 
203
 
 
206
  def refresh_leaderboard():
207
  try:
208
  lb = get_leaderboard()
209
+ return pd.DataFrame(lb) if lb else pd.DataFrame(), ""
 
 
210
  except Exception as e:
211
+ return pd.DataFrame(), str(e)
212
+
213
 
214
+ # ─── Build App ────────────────────────────────────────────────────────────────
215
 
216
+ def get_stems_for_model(model_name):
217
+ stems = DEMUCS_STEMS.get(model_name, ["drums", "bass", "other", "vocals"])
218
+ return gr.update(choices=stems + ["all"], value=stems[0])
219
 
220
  def build_app():
221
  with gr.Blocks(title="🎡 Sample Extractor", theme=gr.themes.Soft(),
222
+ css=".gradio-container{max-width:1300px!important}") as app:
223
+ gr.Markdown("# 🎡 Sample Extractor v4\n"
224
+ "Extract distinct sounds from audio using **NCC waveform matching** β€” "
225
+ "correctly groups identical samples regardless of velocity.\n"
226
+ "Full control over Demucs model, onset detection, and clustering parameters.")
 
 
227
 
228
  with gr.Tabs():
229
  # ── Extract ──
230
  with gr.Tab("🎡 Extract"):
231
+ audio_in = gr.Audio(sources=['upload'], type='numpy', label='Upload Audio')
232
+
233
+ with gr.Accordion("πŸ”§ Stem Separation", open=False):
234
+ with gr.Row():
235
+ demucs_model = gr.Dropdown(DEMUCS_MODELS, value="htdemucs_ft",
236
+ label="Demucs Model")
237
+ stem_dd = gr.Dropdown(['drums','bass','other','vocals','all'],
238
+ value='drums', label='Stem')
239
+ demucs_shifts = gr.Slider(0, 5, value=1, step=1,
240
+ label='Shifts (TTA, 0=fastest)')
241
+ demucs_overlap = gr.Slider(0.0, 0.5, value=0.25, step=0.05,
242
+ label='Overlap')
243
+
244
+ with gr.Accordion("🎯 Onset Detection", open=False):
245
+ with gr.Row():
246
+ onset_mode = gr.Dropdown(['auto','percussive','harmonic','broadband'],
247
+ value='auto', label='Mode')
248
+ onset_delta = gr.Slider(0.01, 0.5, value=0.07, step=0.01,
249
+ label='Delta (sensitivity)')
250
+ energy_db = gr.Slider(-70, -10, value=-45, step=1,
251
+ label='Energy threshold (dB)')
252
+ with gr.Row():
253
+ pre_pad = gr.Slider(0.0, 0.05, value=0.005, step=0.001,
254
+ label='Pre-pad (s)')
255
+ min_dur = gr.Slider(0.005, 0.2, value=0.02, step=0.005,
256
+ label='Min duration (s)')
257
+ max_dur = gr.Slider(0.1, 5.0, value=1.5, step=0.1,
258
+ label='Max duration (s)')
259
+ min_gap = gr.Slider(0.005, 0.2, value=0.015, step=0.005,
260
+ label='Min gap (s)')
261
+
262
+ with gr.Accordion("πŸ”— Clustering", open=False):
263
+ with gr.Row():
264
+ ncc_thresh = gr.Slider(0.5, 0.99, value=0.80, step=0.01,
265
+ label='NCC threshold (higher = stricter matching)')
266
+ ncc_ms = gr.Slider(50, 1000, value=200, step=50,
267
+ label='Compare window (ms)')
268
+
269
+ with gr.Accordion("βš™οΈ Post-processing", open=False):
270
+ do_synth = gr.Checkbox(value=True, label='Synthesize optimal samples from clusters')
271
 
272
+ extract_btn = gr.Button("πŸ”¬ Extract Samples", variant="primary", size="lg")
 
273
 
274
+ summary_md = gr.Markdown("*Upload audio and click Extract*")
275
  with gr.Row():
276
+ stem_out = gr.Audio(type='numpy', label='Stem', interactive=False)
277
+ rendered_out = gr.Audio(type='numpy', label='πŸ”Š Reconstruction', interactive=False)
 
278
 
279
  gr.Markdown("### Downloads")
280
  with gr.Row():
281
+ archive_file = gr.File(label="πŸ“¦ ZIP Archive", interactive=False)
282
+ midi_file = gr.File(label="🎹 MIDI", interactive=False)
283
+ sample_files = gr.File(label="Individual WAV samples", file_count="multiple",
 
 
 
284
  interactive=False)
285
+ metrics_tbl = gr.Dataframe(label="Extracted Samples")
 
 
286
  status_txt = gr.Textbox(visible=False)
287
 
288
+ # Update available stems when model changes
289
+ demucs_model.change(
290
+ fn=lambda m: gr.update(choices=DEMUCS_STEMS.get(m, ["drums","bass","other","vocals"]) + ["all"]),
291
+ inputs=[demucs_model], outputs=[stem_dd])
292
+
293
  extract_btn.click(
294
+ run_extraction,
295
+ [audio_in, stem_dd, demucs_model, demucs_shifts, demucs_overlap,
296
+ onset_mode, onset_delta, energy_db, pre_pad, min_dur, max_dur, min_gap,
297
+ ncc_thresh, ncc_ms, do_synth],
298
  [stem_out, summary_md, rendered_out, sample_files,
299
+ midi_file, archive_file, status_txt, metrics_tbl])
 
300
 
301
  # ── Evaluate ──
302
  with gr.Tab("πŸ“Š Evaluate"):
303
+ gr.Markdown("Generate synthetic song β†’ extract β†’ compare to ground truth.")
 
304
  with gr.Row():
305
  ev_pat = gr.Dropdown(['rock','funk','halftime'], value='rock', label='Pattern')
306
  ev_bpm = gr.Slider(80, 200, value=120, step=2, label='BPM')
307
  ev_bars = gr.Slider(2, 8, value=4, step=1, label='Bars')
308
+ ev_ncc = gr.Slider(0.5, 0.99, value=0.80, step=0.01, label='NCC threshold')
309
  ev_btn = gr.Button("πŸ§ͺ Evaluate", variant="primary", size="lg")
310
  with gr.Row():
311
+ ev_mix = gr.Audio(type='numpy', label='Original', interactive=False)
312
+ ev_rendered = gr.Audio(type='numpy', label='Reconstruction', interactive=False)
 
313
  ev_summary = gr.Dataframe(label="Summary")
314
  ev_matches = gr.Dataframe(label="Matches")
315
+ ev_s1 = gr.Textbox(visible=False); ev_s2 = gr.Textbox(visible=False)
316
+ ev_btn.click(run_eval, [ev_pat, ev_bpm, ev_bars, ev_ncc],
317
+ [ev_mix, ev_rendered, ev_summary, ev_matches, ev_s1, ev_s2])
 
318
 
319
  # ── Optimize ──
320
  with gr.Tab("πŸ”„ Optimize"):
321
+ gr.Markdown("### Autonomous Optimization\nTests across 6 diverse songs, saves best config to Hub.")
 
 
 
 
322
  with gr.Row():
323
  opt_n = gr.Slider(2, 30, value=5, step=1, label='Iterations')
324
  opt_name = gr.Textbox(value="optimized", label='Config name')
 
328
  opt_log = gr.Textbox(label="Log", lines=20, max_lines=40)
329
  opt_hist = gr.Dataframe(label="History")
330
  opt_plot = gr.Plot(label="Progress")
331
+ opt_params = gr.Code(label="Best Config", language="json")
332
  opt_btn.click(run_optimize, [opt_n, opt_name, opt_author, opt_save],
333
  [opt_log, opt_hist, opt_plot, opt_params])
334
 
335
  # ── Leaderboard ──
336
  with gr.Tab("πŸ† Leaderboard"):
337
+ gr.Markdown("### Config Leaderboard")
338
+ lb_btn = gr.Button("πŸ”„ Refresh"); lb_tbl = gr.Dataframe()
339
+ lb_s = gr.Textbox(visible=False)
340
+ lb_btn.click(refresh_leaderboard, [], [lb_tbl, lb_s])
 
341
 
342
  return app
343
 
 
344
  if __name__ == "__main__":
345
  build_app().launch(server_name="0.0.0.0", server_port=7860)