AdityaK007 commited on
Commit
a60d710
·
verified ·
1 Parent(s): 8990170

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +241 -229
app.py CHANGED
@@ -13,51 +13,34 @@ import plotly.graph_objects as go
13
  import os
14
  import tempfile
15
 
16
- # ----------------------------
17
- # 1. Signal Alignment & Preprocessing
18
- # ----------------------------
19
  def align_signals(ref, target):
20
  """Aligns target signal to reference signal using Cross-Correlation."""
21
  ref_norm = librosa.util.normalize(ref)
22
  target_norm = librosa.util.normalize(target)
23
 
 
24
  correlation = signal.fftconvolve(target_norm, ref_norm[::-1], mode='full')
25
  lags = signal.correlation_lags(len(target_norm), len(ref_norm), mode='full')
26
  lag = lags[np.argmax(correlation)]
27
 
28
  if lag > 0:
29
- aligned_target = target[lag:]
30
- aligned_ref = ref
31
  else:
32
- aligned_target = target
33
- aligned_ref = ref[abs(lag):]
34
 
35
- min_len = min(len(aligned_ref), len(aligned_target))
36
- return aligned_ref[:min_len], aligned_target[:min_len]
37
-
38
- # ----------------------------
39
- # 2. Segment Audio
40
- # ----------------------------
41
  def segment_audio(y, sr, frame_length_ms, hop_length_ms, window_type="hann"):
42
  frame_length = int(frame_length_ms * sr / 1000)
43
  hop_length = int(hop_length_ms * sr / 1000)
44
  window = scipy_get_window(window_type if window_type != "rectangular" else "boxcar", frame_length)
45
- frames = []
46
- y_padded = np.pad(y, (0, frame_length), mode='constant')
47
 
48
- for i in range(0, len(y) - frame_length + 1, hop_length):
49
- frame = y[i:i + frame_length] * window
50
- frames.append(frame)
51
-
52
- if frames:
53
- frames = np.array(frames).T
54
- else:
55
- frames = np.zeros((frame_length, 1))
56
- return frames, frame_length
57
 
58
- # ----------------------------
59
- # 3. Feature Extraction
60
- # ----------------------------
61
  def extract_features_with_spectrum(frames, sr):
62
  features = []
63
  n_mfcc = 13
@@ -65,6 +48,9 @@ def extract_features_with_spectrum(frames, sr):
65
 
66
  for i in range(frames.shape[1]):
67
  frame = frames[:, i]
 
 
 
68
  if len(frame) < n_fft or np.max(np.abs(frame)) < 1e-10:
69
  feat = {k: 0.0 for k in ["rms", "spectral_centroid", "zcr", "spectral_flatness",
70
  "low_freq_energy", "mid_freq_energy", "high_freq_energy"]}
@@ -73,32 +59,32 @@ def extract_features_with_spectrum(frames, sr):
73
  features.append(feat)
74
  continue
75
 
76
- feat = {}
77
  feat["rms"] = float(np.mean(librosa.feature.rms(y=frame)[0]))
78
  feat["zcr"] = float(np.mean(librosa.feature.zero_crossing_rate(frame)[0]))
79
 
 
80
  try: feat["spectral_centroid"] = float(np.mean(librosa.feature.spectral_centroid(y=frame, sr=sr)[0]))
81
  except: feat["spectral_centroid"] = 0.0
82
-
83
  try: feat["spectral_flatness"] = float(np.mean(librosa.feature.spectral_flatness(y=frame)[0]))
84
  except: feat["spectral_flatness"] = 0.0
85
 
 
86
  try:
87
  mfccs = librosa.feature.mfcc(y=frame, sr=sr, n_mfcc=n_mfcc, n_fft=n_fft)
88
  for j in range(n_mfcc): feat[f"mfcc_{j+1}"] = float(np.mean(mfccs[j]))
89
  except:
90
  for j in range(n_mfcc): feat[f"mfcc_{j+1}"] = 0.0
91
 
 
92
  try:
93
  S = np.abs(librosa.stft(frame, n_fft=n_fft))
94
  S_db = librosa.amplitude_to_db(S, ref=np.max)
95
  freqs = librosa.fft_frequencies(sr=sr, n_fft=n_fft)
96
- low_mask = freqs <= 2000
97
- mid_mask = (freqs > 2000) & (freqs <= 4000)
98
- high_mask = freqs > 4000
99
- feat["low_freq_energy"] = float(np.mean(S_db[low_mask])) if np.any(low_mask) else -80.0
100
- feat["mid_freq_energy"] = float(np.mean(S_db[mid_mask])) if np.any(mid_mask) else -80.0
101
- feat["high_freq_energy"] = float(np.mean(S_db[high_mask])) if np.any(high_mask) else -80.0
102
  feat["spectrum"] = S_db
103
  except:
104
  feat["low_freq_energy"] = feat["mid_freq_energy"] = feat["high_freq_energy"] = -80.0
@@ -107,17 +93,18 @@ def extract_features_with_spectrum(frames, sr):
107
  features.append(feat)
108
  return features
109
 
110
- # ----------------------------
111
- # 4. Frame Comparison
112
- # ----------------------------
113
  def compare_frames_enhanced(near_feats, far_feats, metrics):
114
  min_len = min(len(near_feats), len(far_feats))
115
- if min_len == 0: return pd.DataFrame({"frame_index": []})
116
 
117
  results = {"frame_index": list(range(min_len))}
118
  near_df = pd.DataFrame(near_feats[:min_len])
119
  far_df = pd.DataFrame(far_feats[:min_len])
120
 
 
121
  drop_cols = ["spectrum"]
122
  near_vec = near_df.drop(columns=drop_cols, errors="ignore").select_dtypes(include=[np.number]).values
123
  far_vec = far_df.drop(columns=drop_cols, errors="ignore").select_dtypes(include=[np.number]).values
@@ -134,19 +121,18 @@ def compare_frames_enhanced(near_feats, far_feats, metrics):
134
  results["cosine_similarity"] = cos_vals
135
 
136
  if "High-Freq Loss Ratio" in metrics:
137
- loss_ratios = []
138
- for i in range(min_len):
139
- loss_ratios.append(float(near_feats[i]["high_freq_energy"] - far_feats[i]["high_freq_energy"]))
140
- results["high_freq_loss_db"] = loss_ratios
141
 
 
142
  overlap_scores = []
143
  for i in range(min_len):
144
- near_spec = near_feats[i]["spectrum"].flatten()
145
- far_spec = far_feats[i]["spectrum"].flatten()
146
- if np.all(near_spec == 0) or np.all(far_spec == 0): overlap_scores.append(0.0)
147
- else: overlap_scores.append(float(cosine_similarity(near_spec.reshape(1, -1), far_spec.reshape(1, -1))[0][0]))
148
  results["spectral_overlap"] = overlap_scores
149
 
 
150
  combined = []
151
  for i in range(min_len):
152
  score = (results["spectral_overlap"][i] * 0.5)
@@ -156,12 +142,8 @@ def compare_frames_enhanced(near_feats, far_feats, metrics):
156
 
157
  return pd.DataFrame(results)
158
 
159
- # ----------------------------
160
- # 5. Dual Clustering & Feature Relation (NEW)
161
- # ----------------------------
162
  def perform_dual_clustering(near_df, far_df, cluster_features, algo, n_clusters, eps):
163
  if not cluster_features: return near_df, far_df
164
-
165
  valid_features = [f for f in cluster_features if f in near_df.columns]
166
  if not valid_features: return near_df, far_df
167
 
@@ -181,228 +163,258 @@ def perform_dual_clustering(near_df, far_df, cluster_features, algo, n_clusters,
181
  near_labels = model.fit_predict(X_near_scaled)
182
  far_model = AgglomerativeClustering(n_clusters=min(n_clusters, len(X_far)))
183
  far_labels = far_model.fit_predict(X_far_scaled)
184
- elif algo == "DBSCAN":
185
  model = DBSCAN(eps=eps, min_samples=3)
186
  near_labels = model.fit_predict(X_near_scaled)
187
  far_labels = model.fit_predict(X_far_scaled)
188
- else:
189
- near_labels = np.zeros(len(X_near))
190
- far_labels = np.zeros(len(X_far))
191
 
192
  near_df = near_df.copy(); near_df["cluster"] = near_labels.astype(str)
193
  far_df = far_df.copy(); far_df["cluster"] = far_labels.astype(str)
194
-
195
  return near_df, far_df
196
 
197
  def compute_feature_correlations(near_df, far_df, quality_scores):
198
- """
199
- Calculates the correlation between Near Features and Far Features
200
- weighted by the Match Quality.
201
- Returns a correlation matrix dataframe for plotting.
202
- """
203
- # Filter numeric columns only
204
  near_num = near_df.select_dtypes(include=[np.number])
205
  far_num = far_df.select_dtypes(include=[np.number])
206
 
207
- # We want to see: For a high quality frame, how does Near Feature X relate to Far Feature X?
208
- # Simple approach: Calculate Pearson Correlation of (Near_Col, Far_Col) across all frames.
209
-
210
  correlations = {}
211
-
212
  common_cols = [c for c in near_num.columns if c in far_num.columns]
213
 
214
  for col in common_cols:
215
- if col == "cluster": continue
216
  try:
217
- # Basic Correlation: Do Near and Far move together?
218
  corr, _ = pearsonr(near_num[col], far_num[col])
219
  correlations[col] = corr
220
- except:
221
- correlations[col] = 0.0
222
 
223
- # Also calculate correlation with Quality
224
  quality_corr = {}
225
  for col in common_cols:
226
- if col == "cluster": continue
227
  try:
228
- # Does this feature predict high quality?
229
- # e.g., Does high 'rms' usually mean better match score?
230
  corr, _ = pearsonr(near_num[col], quality_scores)
231
  quality_corr[col] = corr
232
- except:
233
- quality_corr[col] = 0.0
234
 
235
  return pd.DataFrame({"Near-Far Correlation": correlations, "Correlation with Quality": quality_corr})
236
 
237
- # ----------------------------
238
- # 6. Plotting Helpers
239
- # ----------------------------
240
- def generate_cluster_plot(df, x_attr, y_attr, title_suffix):
241
- if len(df) == 0 or x_attr not in df.columns or y_attr not in df.columns:
242
- return px.scatter(title="No Data")
243
- fig = px.scatter(
244
- df, x=x_attr, y=y_attr, color="cluster",
245
- title=f"Clustering Analysis ({title_suffix}): {x_attr} vs {y_attr}",
246
- color_discrete_sequence=px.colors.qualitative.Bold
247
- )
248
- return fig
249
-
250
- def update_cluster_view(view_mode, near_df, far_df, cluster_features):
251
- if near_df is None or far_df is None: return px.scatter(title="Run Analysis First")
252
- if len(cluster_features) < 2: return px.scatter(title="Select at least 2 features")
253
- x_attr, y_attr = cluster_features[0], cluster_features[1]
254
- if view_mode == "Near Field": return generate_cluster_plot(near_df, x_attr, y_attr, "Near Field")
255
- else: return generate_cluster_plot(far_df, x_attr, y_attr, "Far Field")
256
-
257
- # ----------------------------
258
- # 7. Main Analysis
259
- # ----------------------------
260
- def analyze_audio_pair(
261
- near_file, far_file,
262
- frame_length_ms, hop_length_ms, window_type,
263
- comparison_metrics, cluster_features, clustering_algo, n_clusters, dbscan_eps
264
- ):
265
- if not near_file or not far_file: raise gr.Error("Upload both files.")
266
-
267
- # Load & Align
268
- y_near, sr = librosa.load(near_file.name, sr=None)
269
- y_far, _ = librosa.load(far_file.name, sr=sr)
270
- y_near = librosa.util.normalize(y_near)
271
- y_far = librosa.util.normalize(y_far)
272
- y_near, y_far = align_signals(y_near, y_far)
273
-
274
- # Process
275
- frames_near, _ = segment_audio(y_near, sr, frame_length_ms, hop_length_ms, window_type)
276
- frames_far, _ = segment_audio(y_far, sr, frame_length_ms, hop_length_ms, window_type)
277
- near_feats = extract_features_with_spectrum(frames_near, sr)
278
- far_feats = extract_features_with_spectrum(frames_far, sr)
279
 
280
- # Compare & Cluster
281
- comparison_df = compare_frames_enhanced(near_feats, far_feats, comparison_metrics)
282
- near_df_raw = pd.DataFrame(near_feats).drop(columns=["spectrum"], errors="ignore")
283
- far_df_raw = pd.DataFrame(far_feats).drop(columns=["spectrum"], errors="ignore")
284
- near_clustered, far_clustered = perform_dual_clustering(
285
- near_df_raw, far_df_raw, cluster_features, clustering_algo, n_clusters, dbscan_eps
286
- )
 
 
287
 
288
- # 1. Comparison Plot
289
- plot_comparison = go.Figure()
 
290
  for col in ["cosine_similarity", "spectral_overlap", "combined_match_score"]:
291
- if col in comparison_df.columns:
292
- plot_comparison.add_trace(go.Scatter(x=comparison_df["frame_index"], y=comparison_df[col], name=col, yaxis="y1"))
293
- if "high_freq_loss_db" in comparison_df.columns:
294
- plot_comparison.add_trace(go.Scatter(x=comparison_df["frame_index"], y=comparison_df["high_freq_loss_db"],
295
- name="High Freq Loss (dB)", line=dict(color="red", width=1), yaxis="y2"))
296
- plot_comparison.update_layout(
297
- title="Comparison Metrics", yaxis=dict(title="Similarity"), yaxis2=dict(title="dB Loss", overlaying="y", side="right")
298
- )
299
-
300
- # 2. Cluster Plot
301
- init_cluster_plot = update_cluster_view("Near Field", near_clustered, far_clustered, cluster_features)
 
 
 
 
 
 
 
 
 
302
 
303
- # 3. Spectral Heatmap
304
- safe_idx = int(len(near_feats)/2)
305
- diff = near_feats[safe_idx]["spectrum"] - far_feats[safe_idx]["spectrum"]
306
- spec_heatmap = go.Figure(data=go.Heatmap(z=diff, colorscale='RdBu', zmid=0))
307
- spec_heatmap.update_layout(title=f"Spectral Diff (Frame {safe_idx})", height=350)
308
-
309
- # 4. Overlay Plot
310
- near_clustered["match_quality"] = comparison_df["combined_match_score"]
311
- if len(cluster_features) > 0:
312
- overlay_fig = px.scatter(near_clustered, x=cluster_features[0], y="match_quality", color="cluster",
313
- title="Cluster vs Quality (Near Field)")
314
  else:
315
- overlay_fig = px.scatter(title="No features")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
316
 
317
- # 5. NEW: Feature Relation Heatmap
318
- corr_df = compute_feature_correlations(near_clustered, far_clustered, comparison_df["combined_match_score"])
319
- corr_fig = px.imshow(corr_df.T, text_auto=True, aspect="auto", color_continuous_scale="RdBu", zmin=-1, zmax=1,
320
- title="Feature Correlation Analysis")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
321
 
322
- # 6. Scatter Matrix (Inter-feature)
323
- # Pick top 3 features and Quality
324
- top_cols = cluster_features[:3] + ["match_quality"]
325
- scatter_matrix_fig = px.scatter_matrix(near_clustered, dimensions=top_cols, color="cluster",
326
- title="Inter-Feature Scatter Matrix (Near Field)")
327
-
328
- return (plot_comparison, comparison_df,
329
- init_cluster_plot, near_clustered,
330
- spec_heatmap, overlay_fig,
331
- corr_fig, scatter_matrix_fig,
332
- near_clustered, far_clustered)
333
-
334
- def export_results(comparison_df, near_df, far_df):
335
- temp_dir = tempfile.mkdtemp()
336
- p1 = os.path.join(temp_dir, "comparison.csv")
337
- p2 = os.path.join(temp_dir, "near_clusters.csv")
338
- p3 = os.path.join(temp_dir, "far_clusters.csv")
339
- comparison_df.to_csv(p1, index=False)
340
- near_df.to_csv(p2, index=False)
341
- far_df.to_csv(p3, index=False)
342
- return [p1, p2, p3]
343
-
344
- # ----------------------------
345
- # 8. Gradio UI
346
- # ----------------------------
347
  feature_list = ["rms", "spectral_centroid", "zcr", "spectral_flatness",
348
  "low_freq_energy", "mid_freq_energy", "high_freq_energy"] + [f"mfcc_{i}" for i in range(1, 14)]
 
349
 
350
- with gr.Blocks(title="Audio Field Analyzer", theme=gr.themes.Soft()) as demo:
351
- state_near_df = gr.State()
352
- state_far_df = gr.State()
353
-
354
- gr.Markdown("# 🎙️ Near vs Far Field Analyzer (Dual-Clustering)")
 
 
 
355
 
356
  with gr.Row():
357
- near_file = gr.File(label="Near-Field (Ref)", file_types=[".wav"])
358
- far_file = gr.File(label="Far-Field (Target)", file_types=[".wav"])
359
-
360
- with gr.Accordion("⚙️ Settings", open=False):
361
- frame_length_ms = gr.Slider(10, 200, value=30, label="Frame Length (ms)")
362
- hop_length_ms = gr.Slider(5, 100, value=15, label="Hop Length (ms)")
363
- window_type = gr.Dropdown(["hann", "hamming"], value="hann", label="Window")
364
- comparison_metrics = gr.CheckboxGroup(["Cosine Similarity", "High-Freq Loss Ratio"], value=["Cosine Similarity", "High-Freq Loss Ratio"], label="Metrics")
365
- cluster_features = gr.CheckboxGroup(feature_list, value=["spectral_centroid", "spectral_flatness", "rms"], label="Clustering Features")
366
- clustering_algo = gr.Dropdown(["KMeans", "Agglomerative"], value="KMeans", label="Algorithm")
367
- n_clusters = gr.Slider(2, 10, value=4, step=1, label="Clusters")
368
- dbscan_eps = gr.Slider(0.1, 5.0, value=0.5, visible=False)
369
-
370
- btn = gr.Button("🚀 Analyze", variant="primary")
 
 
 
 
 
 
 
371
 
372
  with gr.Tabs():
373
- with gr.Tab("📈 Comparison"):
374
- comp_plot = gr.Plot()
375
- comp_table = gr.Dataframe()
376
- with gr.Tab("🧩 Phoneme Clustering"):
377
- view_toggle = gr.Radio(["Near Field", "Far Field"], value="Near Field", label="View Mode")
378
- cluster_plot = gr.Plot()
379
- cluster_table = gr.Dataframe()
380
- with gr.Tab("🔍 Spectral"):
381
- spec_heatmap = gr.Plot()
382
- with gr.Tab("🧭 Overlay"):
383
- overlay_plot = gr.Plot()
384
- with gr.Tab("🔗 Feature Relations"):
385
- gr.Markdown("### Correlation Heatmap & Scatter Matrix")
386
- corr_plot = gr.Plot(label="Correlation Heatmap")
387
- scatter_matrix_plot = gr.Plot(label="Scatter Matrix")
388
-
389
- with gr.Tab("📤 Export"):
390
- export_btn = gr.Button("Download CSVs")
391
- export_files = gr.Files()
392
-
393
- btn.click(
394
- fn=analyze_audio_pair,
395
- inputs=[near_file, far_file, frame_length_ms, hop_length_ms, window_type,
396
- comparison_metrics, cluster_features, clustering_algo, n_clusters, dbscan_eps],
397
- outputs=[comp_plot, comp_table,
398
- cluster_plot, cluster_table,
399
- spec_heatmap, overlay_plot,
400
- corr_plot, scatter_matrix_plot,
401
- state_near_df, state_far_df]
402
  )
403
 
404
- view_toggle.change(fn=update_cluster_view, inputs=[view_toggle, state_near_df, state_far_df, cluster_features], outputs=[cluster_plot])
405
- export_btn.click(fn=export_results, inputs=[comp_table, state_near_df, state_far_df], outputs=export_files)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
406
 
407
  if __name__ == "__main__":
408
  demo.launch()
 
13
  import os
14
  import tempfile
15
 
16
+ # ==========================================
17
+ # 1. CORE SIGNAL PROCESSING & ALIGNMENT
18
+ # ==========================================
19
  def align_signals(ref, target):
20
  """Aligns target signal to reference signal using Cross-Correlation."""
21
  ref_norm = librosa.util.normalize(ref)
22
  target_norm = librosa.util.normalize(target)
23
 
24
+ # FFT based correlation is faster for long audio
25
  correlation = signal.fftconvolve(target_norm, ref_norm[::-1], mode='full')
26
  lags = signal.correlation_lags(len(target_norm), len(ref_norm), mode='full')
27
  lag = lags[np.argmax(correlation)]
28
 
29
  if lag > 0:
30
+ return ref, target[lag:][:len(ref)]
 
31
  else:
32
+ return ref[abs(lag):][:len(target)], target
 
33
 
 
 
 
 
 
 
34
  def segment_audio(y, sr, frame_length_ms, hop_length_ms, window_type="hann"):
35
  frame_length = int(frame_length_ms * sr / 1000)
36
  hop_length = int(hop_length_ms * sr / 1000)
37
  window = scipy_get_window(window_type if window_type != "rectangular" else "boxcar", frame_length)
 
 
38
 
39
+ # Efficient framing
40
+ frames = librosa.util.frame(y, frame_length=frame_length, hop_length=hop_length).T
41
+ frames = frames * window
42
+ return frames.T, frame_length
 
 
 
 
 
43
 
 
 
 
44
  def extract_features_with_spectrum(frames, sr):
45
  features = []
46
  n_mfcc = 13
 
48
 
49
  for i in range(frames.shape[1]):
50
  frame = frames[:, i]
51
+ feat = {}
52
+
53
+ # Guard against silence/empty frames
54
  if len(frame) < n_fft or np.max(np.abs(frame)) < 1e-10:
55
  feat = {k: 0.0 for k in ["rms", "spectral_centroid", "zcr", "spectral_flatness",
56
  "low_freq_energy", "mid_freq_energy", "high_freq_energy"]}
 
59
  features.append(feat)
60
  continue
61
 
62
+ # Time Domain
63
  feat["rms"] = float(np.mean(librosa.feature.rms(y=frame)[0]))
64
  feat["zcr"] = float(np.mean(librosa.feature.zero_crossing_rate(frame)[0]))
65
 
66
+ # Spectral Domain
67
  try: feat["spectral_centroid"] = float(np.mean(librosa.feature.spectral_centroid(y=frame, sr=sr)[0]))
68
  except: feat["spectral_centroid"] = 0.0
 
69
  try: feat["spectral_flatness"] = float(np.mean(librosa.feature.spectral_flatness(y=frame)[0]))
70
  except: feat["spectral_flatness"] = 0.0
71
 
72
+ # MFCCs
73
  try:
74
  mfccs = librosa.feature.mfcc(y=frame, sr=sr, n_mfcc=n_mfcc, n_fft=n_fft)
75
  for j in range(n_mfcc): feat[f"mfcc_{j+1}"] = float(np.mean(mfccs[j]))
76
  except:
77
  for j in range(n_mfcc): feat[f"mfcc_{j+1}"] = 0.0
78
 
79
+ # Frequency Bands
80
  try:
81
  S = np.abs(librosa.stft(frame, n_fft=n_fft))
82
  S_db = librosa.amplitude_to_db(S, ref=np.max)
83
  freqs = librosa.fft_frequencies(sr=sr, n_fft=n_fft)
84
+
85
+ feat["low_freq_energy"] = float(np.mean(S_db[freqs <= 2000])) if np.any(freqs <= 2000) else -80.0
86
+ feat["mid_freq_energy"] = float(np.mean(S_db[(freqs > 2000) & (freqs <= 4000)])) if np.any((freqs > 2000) & (freqs <= 4000)) else -80.0
87
+ feat["high_freq_energy"] = float(np.mean(S_db[freqs > 4000])) if np.any(freqs > 4000) else -80.0
 
 
88
  feat["spectrum"] = S_db
89
  except:
90
  feat["low_freq_energy"] = feat["mid_freq_energy"] = feat["high_freq_energy"] = -80.0
 
93
  features.append(feat)
94
  return features
95
 
96
+ # ==========================================
97
+ # 2. COMPARISON & CLUSTERING LOGIC
98
+ # ==========================================
99
  def compare_frames_enhanced(near_feats, far_feats, metrics):
100
  min_len = min(len(near_feats), len(far_feats))
101
+ if min_len == 0: return pd.DataFrame()
102
 
103
  results = {"frame_index": list(range(min_len))}
104
  near_df = pd.DataFrame(near_feats[:min_len])
105
  far_df = pd.DataFrame(far_feats[:min_len])
106
 
107
+ # Vector preparation
108
  drop_cols = ["spectrum"]
109
  near_vec = near_df.drop(columns=drop_cols, errors="ignore").select_dtypes(include=[np.number]).values
110
  far_vec = far_df.drop(columns=drop_cols, errors="ignore").select_dtypes(include=[np.number]).values
 
121
  results["cosine_similarity"] = cos_vals
122
 
123
  if "High-Freq Loss Ratio" in metrics:
124
+ results["high_freq_loss_db"] = [float(near_feats[i]["high_freq_energy"] - far_feats[i]["high_freq_energy"]) for i in range(min_len)]
 
 
 
125
 
126
+ # Spectral Overlap
127
  overlap_scores = []
128
  for i in range(min_len):
129
+ n_s = near_feats[i]["spectrum"].flatten()
130
+ f_s = far_feats[i]["spectrum"].flatten()
131
+ if np.all(n_s == 0) or np.all(f_s == 0): overlap_scores.append(0.0)
132
+ else: overlap_scores.append(float(cosine_similarity(n_s.reshape(1, -1), f_s.reshape(1, -1))[0][0]))
133
  results["spectral_overlap"] = overlap_scores
134
 
135
+ # Combined Match Score
136
  combined = []
137
  for i in range(min_len):
138
  score = (results["spectral_overlap"][i] * 0.5)
 
142
 
143
  return pd.DataFrame(results)
144
 
 
 
 
145
  def perform_dual_clustering(near_df, far_df, cluster_features, algo, n_clusters, eps):
146
  if not cluster_features: return near_df, far_df
 
147
  valid_features = [f for f in cluster_features if f in near_df.columns]
148
  if not valid_features: return near_df, far_df
149
 
 
163
  near_labels = model.fit_predict(X_near_scaled)
164
  far_model = AgglomerativeClustering(n_clusters=min(n_clusters, len(X_far)))
165
  far_labels = far_model.fit_predict(X_far_scaled)
166
+ else: # DBSCAN
167
  model = DBSCAN(eps=eps, min_samples=3)
168
  near_labels = model.fit_predict(X_near_scaled)
169
  far_labels = model.fit_predict(X_far_scaled)
 
 
 
170
 
171
  near_df = near_df.copy(); near_df["cluster"] = near_labels.astype(str)
172
  far_df = far_df.copy(); far_df["cluster"] = far_labels.astype(str)
 
173
  return near_df, far_df
174
 
175
  def compute_feature_correlations(near_df, far_df, quality_scores):
176
+ """Calculates Pearson correlation between Near/Far features."""
177
+ if len(near_df) < 2: return pd.DataFrame()
178
+
 
 
 
179
  near_num = near_df.select_dtypes(include=[np.number])
180
  far_num = far_df.select_dtypes(include=[np.number])
181
 
 
 
 
182
  correlations = {}
 
183
  common_cols = [c for c in near_num.columns if c in far_num.columns]
184
 
185
  for col in common_cols:
 
186
  try:
 
187
  corr, _ = pearsonr(near_num[col], far_num[col])
188
  correlations[col] = corr
189
+ except: correlations[col] = 0.0
 
190
 
 
191
  quality_corr = {}
192
  for col in common_cols:
 
193
  try:
 
 
194
  corr, _ = pearsonr(near_num[col], quality_scores)
195
  quality_corr[col] = corr
196
+ except: quality_corr[col] = 0.0
 
197
 
198
  return pd.DataFrame({"Near-Far Correlation": correlations, "Correlation with Quality": quality_corr})
199
 
200
+ # ==========================================
201
+ # 3. FILTERING & VISUALIZATION ENGINE
202
+ # ==========================================
203
+ def update_visuals(near_df, far_df, comparison_df,
204
+ fil_col, fil_op, fil_val,
205
+ cluster_features, view_mode):
206
+ """
207
+ Master function that takes Full Data -> Applies Filter -> Generates ALL Plots
208
+ """
209
+ if near_df is None: return [None] * 6 # Return empty if no data
210
+
211
+ # 1. APPLY FILTER
212
+ # Merge for easier filtering
213
+ near_merged = near_df.copy()
214
+ far_merged = far_df.copy()
215
+ for c in comparison_df.columns:
216
+ if c != "frame_index":
217
+ near_merged[c] = comparison_df[c]
218
+ far_merged[c] = comparison_df[c]
219
+
220
+ mask = None
221
+ if fil_col != "None" and fil_op != "None":
222
+ if fil_col in near_merged.columns:
223
+ if fil_op == "<": mask = near_merged[fil_col] < fil_val
224
+ elif fil_op == ">": mask = near_merged[fil_col] > fil_val
225
+ elif fil_op == "=": mask = near_merged[fil_col] == fil_val
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
226
 
227
+ if mask is None:
228
+ f_near, f_far, f_comp = near_merged, far_merged, comparison_df
229
+ title_prefix = "Full Data"
230
+ else:
231
+ f_near, f_far, f_comp = near_merged[mask], far_merged[mask], comparison_df[mask]
232
+ title_prefix = f"Filtered ({fil_col} {fil_op} {fil_val})"
233
+
234
+ if len(f_near) == 0:
235
+ return [px.scatter(title="No data matches filter")] * 5 + [pd.DataFrame()]
236
 
237
+ # 2. GENERATE COMPARISON PLOT
238
+ fig_comp = go.Figure()
239
+ # Plot Similarity Metrics
240
  for col in ["cosine_similarity", "spectral_overlap", "combined_match_score"]:
241
+ if col in f_comp.columns:
242
+ mode = 'markers+lines' if len(f_comp) < 100 else 'lines'
243
+ fig_comp.add_trace(go.Scatter(x=f_comp["frame_index"], y=f_comp[col], name=col, mode=mode, yaxis="y1"))
244
+ # Plot dB Loss (Dual Axis)
245
+ if "high_freq_loss_db" in f_comp.columns:
246
+ mode = 'markers+lines' if len(f_comp) < 100 else 'lines'
247
+ fig_comp.add_trace(go.Scatter(x=f_comp["frame_index"], y=f_comp["high_freq_loss_db"],
248
+ name="dB Loss", mode=mode, line=dict(color="red"), yaxis="y2"))
249
+ fig_comp.update_layout(title=f"{title_prefix}: Comparison",
250
+ yaxis=dict(title="Similarity (0-1)", range=[0, 1.1]),
251
+ yaxis2=dict(title="dB Loss", overlaying="y", side="right"))
252
+
253
+ # 3. GENERATE CLUSTER PLOT
254
+ target_df = f_near if view_mode == "Near Field" else f_far
255
+ if len(cluster_features) >= 2:
256
+ fig_clust = px.scatter(target_df, x=cluster_features[0], y=cluster_features[1], color="cluster",
257
+ title=f"{title_prefix}: Clustering ({view_mode})",
258
+ color_discrete_sequence=px.colors.qualitative.Bold)
259
+ else:
260
+ fig_clust = px.scatter(title="Select 2+ features")
261
 
262
+ # 4. GENERATE OVERLAY PLOT
263
+ if len(cluster_features) > 0 and "combined_match_score" in f_near.columns:
264
+ fig_over = px.scatter(f_near, x=cluster_features[0], y="combined_match_score", color="cluster",
265
+ title=f"{title_prefix}: Quality Overlay")
 
 
 
 
 
 
 
266
  else:
267
+ fig_over = px.scatter(title="No Match Score")
268
+
269
+ # 5. GENERATE CORRELATION HEATMAP
270
+ # Note: We calculate correlation on the FILTERED set. This allows seeing how relations change in failure modes.
271
+ corr_df = compute_feature_correlations(f_near, f_far, f_comp["combined_match_score"])
272
+ if not corr_df.empty:
273
+ fig_corr = px.imshow(corr_df.T, text_auto=True, aspect="auto", color_continuous_scale="RdBu", zmin=-1, zmax=1,
274
+ title=f"{title_prefix}: Feature Correlations")
275
+ else:
276
+ fig_corr = px.scatter(title="Not enough data for correlation")
277
+
278
+ # 6. GENERATE SCATTER MATRIX
279
+ top_cols = cluster_features[:3] + ["combined_match_score"] if "combined_match_score" in f_near.columns else cluster_features[:3]
280
+ fig_matrix = px.scatter_matrix(f_near, dimensions=top_cols, color="cluster",
281
+ title=f"{title_prefix}: Scatter Matrix")
282
 
283
+ return fig_comp, fig_clust, fig_over, fig_corr, fig_matrix, f_near
284
+
285
+ # ==========================================
286
+ # 4. MAIN ANALYZER WRAPPER
287
+ # ==========================================
288
+ def run_full_analysis(near, far, fl, hl, wt, cm, cf, ca, nc, eps):
289
+ if not near or not far: raise gr.Error("Upload files")
290
+
291
+ # Process
292
+ y_n, sr = librosa.load(near.name, sr=None)
293
+ y_f, _ = librosa.load(far.name, sr=sr)
294
+ y_n, y_f = align_signals(y_n, y_f) # Align
295
+ y_n, y_f = librosa.util.normalize(y_n), librosa.util.normalize(y_f) # Normalize
296
+
297
+ frames_n, _ = segment_audio(y_n, sr, fl, hl, wt)
298
+ frames_f, _ = segment_audio(y_f, sr, fl, hl, wt)
299
+
300
+ feat_n = extract_features_with_spectrum(frames_n, sr)
301
+ feat_f = extract_features_with_spectrum(frames_f, sr)
302
+
303
+ comp_df = compare_frames_enhanced(feat_n, feat_f, cm)
304
+
305
+ df_n = pd.DataFrame(feat_n).drop(columns=["spectrum"], errors="ignore")
306
+ df_f = pd.DataFrame(feat_f).drop(columns=["spectrum"], errors="ignore")
307
+
308
+ # Cluster
309
+ df_n, df_f = perform_dual_clustering(df_n, df_f, cf, ca, nc, eps)
310
+
311
+ # Generate Plots (No Filter initially)
312
+ plots = update_visuals(df_n, df_f, comp_df, "None", "None", 0, cf, "Near Field")
313
+
314
+ # Static Spectral Heatmap
315
+ idx = int(len(feat_n)/2)
316
+ diff = feat_n[idx]["spectrum"] - feat_f[idx]["spectrum"]
317
+ fig_spec = go.Figure(data=go.Heatmap(z=diff, colorscale='RdBu', zmid=0))
318
+ fig_spec.update_layout(title=f"Spectral Diff (Frame {idx})")
319
 
320
+ # Return: Plots, Tables, Heatmap, StateVars
321
+ return (plots[0], comp_df, plots[1], df_n, plots[2], plots[3], plots[4], fig_spec,
322
+ df_n, df_f, comp_df) # State
323
+
324
+ # ==========================================
325
+ # 5. GRADIO UI
326
+ # ==========================================
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
327
  feature_list = ["rms", "spectral_centroid", "zcr", "spectral_flatness",
328
  "low_freq_energy", "mid_freq_energy", "high_freq_energy"] + [f"mfcc_{i}" for i in range(1, 14)]
329
+ filter_opts = ["combined_match_score", "rms", "high_freq_loss_db", "spectral_flatness"] + feature_list
330
 
331
+ with gr.Blocks(title="Ultimate Audio Analyzer", theme=gr.themes.Soft()) as demo:
332
+ # State Storage
333
+ s_near = gr.State()
334
+ s_far = gr.State()
335
+ s_comp = gr.State()
336
+
337
+ gr.Markdown("# 🎙️ Ultimate Near/Far Field Analyzer")
338
+ gr.Markdown("Includes: Alignment, Dual Clustering, Feature Correlation, and Conditional Filtering.")
339
 
340
  with gr.Row():
341
+ f1 = gr.File(label="Near Field (Ref)")
342
+ f2 = gr.File(label="Far Field (Target)")
343
+ run_btn = gr.Button("🚀 Run Analysis", variant="primary")
344
+
345
+ with gr.Accordion("⚙️ Configuration", open=False):
346
+ fl = gr.Slider(10, 100, 30, label="Frame Length (ms)")
347
+ hl = gr.Slider(10, 50, 15, label="Hop Length (ms)")
348
+ wt = gr.Dropdown(["hann", "boxcar"], value="hann")
349
+ cm = gr.CheckboxGroup(["Cosine Similarity", "High-Freq Loss Ratio"], value=["Cosine Similarity"], label="Metrics")
350
+ cf = gr.CheckboxGroup(feature_list, value=["spectral_centroid", "rms", "mfcc_1"], label="Clustering Feats")
351
+ ca = gr.Dropdown(["KMeans", "DBSCAN"], value="KMeans")
352
+ nc = gr.Slider(2, 8, 4, label="Clusters")
353
+ eps = gr.Slider(0.1, 2.0, 0.5)
354
+
355
+ gr.Markdown("### 🔎 Frame Filtering (Updates ALL plots)")
356
+ with gr.Row(variant="panel"):
357
+ fil_col = gr.Dropdown(filter_opts, value="combined_match_score", label="Filter Column")
358
+ fil_op = gr.Dropdown(["<", ">"], value="<", label="Operator")
359
+ fil_val = gr.Number(value=0.8, label="Value")
360
+ apply_btn = gr.Button("Apply Filter")
361
+ reset_btn = gr.Button("Reset")
362
 
363
  with gr.Tabs():
364
+ with gr.Tab("Comparison"):
365
+ p_comp = gr.Plot()
366
+ t_comp = gr.Dataframe(height=200)
367
+ with gr.Tab("Clustering"):
368
+ view_mode = gr.Radio(["Near Field", "Far Field"], value="Near Field", label="View Mode")
369
+ p_clust = gr.Plot()
370
+ t_clust = gr.Dataframe(height=200)
371
+ with gr.Tab("Overlay"):
372
+ p_over = gr.Plot()
373
+ with gr.Tab("Relations (Correlation)"):
374
+ p_corr = gr.Plot(label="Correlation Heatmap")
375
+ p_matrix = gr.Plot(label="Scatter Matrix")
376
+ with gr.Tab("Spectral"):
377
+ p_spec = gr.Plot()
378
+
379
+ with gr.Tab("Export"):
380
+ exp_btn = gr.Button("Download Results")
381
+ exp_file = gr.Files()
382
+
383
+ # Callbacks
384
+ run_btn.click(
385
+ run_full_analysis,
386
+ inputs=[f1, f2, fl, hl, wt, cm, cf, ca, nc, eps],
387
+ outputs=[p_comp, t_comp, p_clust, t_clust, p_over, p_corr, p_matrix, p_spec, s_near, s_far, s_comp]
 
 
 
 
 
388
  )
389
 
390
+ # Filter Logic
391
+ apply_btn.click(
392
+ update_visuals,
393
+ inputs=[s_near, s_far, s_comp, fil_col, fil_op, fil_val, cf, view_mode],
394
+ outputs=[p_comp, p_clust, p_over, p_corr, p_matrix, t_clust]
395
+ )
396
+
397
+ reset_btn.click(
398
+ lambda n, f, c, feat, v: update_visuals(n, f, c, "None", "None", 0, feat, v),
399
+ inputs=[s_near, s_far, s_comp, cf, view_mode],
400
+ outputs=[p_comp, p_clust, p_over, p_corr, p_matrix, t_clust]
401
+ )
402
+
403
+ # View Mode Logic
404
+ view_mode.change(
405
+ update_visuals,
406
+ inputs=[s_near, s_far, s_comp, fil_col, fil_op, fil_val, cf, view_mode],
407
+ outputs=[p_comp, p_clust, p_over, p_corr, p_matrix, t_clust]
408
+ )
409
+
410
+ # Export Logic
411
+ def export(c, n, f):
412
+ d = tempfile.mkdtemp()
413
+ p1, p2, p3 = os.path.join(d, "comp.csv"), os.path.join(d, "near.csv"), os.path.join(d, "far.csv")
414
+ c.to_csv(p1, index=False); n.to_csv(p2, index=False); f.to_csv(p3, index=False)
415
+ return [p1, p2, p3]
416
+
417
+ exp_btn.click(export, inputs=[s_comp, s_near, s_far], outputs=[exp_file])
418
 
419
  if __name__ == "__main__":
420
  demo.launch()