AdityaK007 commited on
Commit
8990170
Β·
verified Β·
1 Parent(s): 6de0f6b

Update app_reallyworks.py

Browse files
Files changed (1) hide show
  1. app_reallyworks.py +408 -0
app_reallyworks.py CHANGED
@@ -0,0 +1,408 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import librosa
3
+ import numpy as np
4
+ import pandas as pd
5
+ from sklearn.cluster import KMeans, AgglomerativeClustering, DBSCAN
6
+ from sklearn.preprocessing import StandardScaler
7
+ from sklearn.metrics.pairwise import cosine_similarity
8
+ from scipy import signal
9
+ from scipy.signal import get_window as scipy_get_window
10
+ from scipy.stats import pearsonr
11
+ import plotly.express as px
12
+ 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
64
+ n_fft = min(2048, frames.shape[0])
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"]}
71
+ for j in range(n_mfcc): feat[f"mfcc_{j+1}"] = 0.0
72
+ feat["spectrum"] = np.zeros((n_fft // 2 + 1, 1))
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
105
+ feat["spectrum"] = np.zeros((n_fft // 2 + 1, 1))
106
+
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
124
+
125
+ if "Euclidean Distance" in metrics:
126
+ results["euclidean_dist"] = np.linalg.norm(near_vec - far_vec, axis=1).tolist()
127
+
128
+ if "Cosine Similarity" in metrics:
129
+ cos_vals = []
130
+ for i in range(min_len):
131
+ a, b = near_vec[i].reshape(1, -1), far_vec[i].reshape(1, -1)
132
+ if np.all(a == 0) or np.all(b == 0): cos_vals.append(0.0)
133
+ else: cos_vals.append(float(cosine_similarity(a, b)[0][0]))
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)
153
+ if "cosine_similarity" in results: score += (results["cosine_similarity"][i] * 0.5)
154
+ combined.append(score)
155
+ results["combined_match_score"] = combined
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
+
168
+ X_near = np.nan_to_num(near_df[valid_features].values)
169
+ X_far = np.nan_to_num(far_df[valid_features].values)
170
+
171
+ scaler = StandardScaler()
172
+ X_near_scaled = scaler.fit_transform(X_near)
173
+ X_far_scaled = scaler.transform(X_far)
174
+
175
+ if algo == "KMeans":
176
+ model = KMeans(n_clusters=min(n_clusters, len(X_near)), random_state=42, n_init=10)
177
+ near_labels = model.fit_predict(X_near_scaled)
178
+ far_labels = model.predict(X_far_scaled)
179
+ elif algo == "Agglomerative":
180
+ model = AgglomerativeClustering(n_clusters=min(n_clusters, len(X_near)))
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()