| from pathlib import Path |
| import numpy as np |
| import pandas as pd |
| import matplotlib.pyplot as plt |
| import librosa |
| import librosa.display |
| from sklearn.metrics import roc_auc_score |
| import warnings |
| warnings.filterwarnings("ignore") |
|
|
| DATA_DIR = Path("output/voiceguard") |
| AUDIO_DIR = DATA_DIR |
| SR = 16_000 |
| DURATION = 4 |
| N_SAMPLES = SR * DURATION |
|
|
|
|
| train_df = pd.read_csv(DATA_DIR / "train.csv") |
| test_df = pd.read_csv(DATA_DIR / "test.csv") |
|
|
| print("Train shape:", train_df.shape) |
| print("Test shape:", test_df.shape) |
| print() |
| print(train_df.head()) |
|
|
|
|
| counts = train_df["label"].value_counts().sort_index() |
| print("Label counts (0=real, 1=fake):") |
| print(counts) |
| print(f"\nClass balance — real: {counts[0]}, fake: {counts[1]}, ratio: {counts[1]/counts[0]:.2f}") |
|
|
| fig, ax = plt.subplots(figsize=(5, 3)) |
| ax.bar(["real (0)", "fake (1)"], [counts[0], counts[1]], color=["steelblue", "tomato"]) |
| ax.set_ylabel("Count") |
| ax.set_title("Train set class balance") |
| plt.tight_layout() |
| plt.show() |
|
|
|
|
| def load_audio(path, sr=SR, n_samples=N_SAMPLES): |
| y, _ = librosa.load(path, sr=sr, mono=True) |
| if len(y) < n_samples: |
| y = np.pad(y, (0, n_samples - len(y))) |
| else: |
| y = y[:n_samples] |
| return y |
|
|
|
|
| def spectral_flatness_mean(path): |
| y = load_audio(path) |
| sf = librosa.feature.spectral_flatness(y=y) |
| return float(np.mean(sf)) |
|
|
| real_rows = train_df[train_df["label"] == 0].sample(min(200, (train_df["label"]==0).sum()), random_state=42) |
| fake_rows = train_df[train_df["label"] == 1].sample(min(200, (train_df["label"]==1).sum()), random_state=42) |
|
|
| print("Computing spectral flatness for real samples …") |
| real_sf = [spectral_flatness_mean(AUDIO_DIR / r["id"]) for _, r in real_rows.iterrows()] |
| print("Computing spectral flatness for fake samples …") |
| fake_sf = [spectral_flatness_mean(AUDIO_DIR / r["id"]) for _, r in fake_rows.iterrows()] |
|
|
| print(f"Real — mean: {np.mean(real_sf):.4f} std: {np.std(real_sf):.4f}") |
| print(f"Fake — mean: {np.mean(fake_sf):.4f} std: {np.std(fake_sf):.4f}") |
|
|
|
|
| fig, ax = plt.subplots(figsize=(7, 4)) |
| ax.hist(real_sf, bins=30, alpha=0.6, color="steelblue", label="real") |
| ax.hist(fake_sf, bins=30, alpha=0.6, color="tomato", label="fake") |
| ax.set_xlabel("Spectral Flatness (mean)") |
| ax.set_ylabel("Count") |
| ax.set_title("Spectral Flatness Distribution: Real vs Fake") |
| ax.legend() |
| plt.tight_layout() |
| plt.show() |
|
|
|
|
| real_path = AUDIO_DIR / real_rows.iloc[0]["id"] |
| fake_path = AUDIO_DIR / fake_rows.iloc[0]["id"] |
|
|
| y_real = load_audio(real_path) |
| y_fake = load_audio(fake_path) |
|
|
| fig, axes = plt.subplots(2, 2, figsize=(12, 6)) |
| t = np.linspace(0, DURATION, N_SAMPLES) |
|
|
| |
| axes[0, 0].plot(t, y_real, lw=0.4, color="steelblue") |
| axes[0, 0].set_title("Waveform — Real") |
| axes[0, 0].set_xlabel("Time (s)") |
|
|
| axes[0, 1].plot(t, y_fake, lw=0.4, color="tomato") |
| axes[0, 1].set_title("Waveform — Fake") |
| axes[0, 1].set_xlabel("Time (s)") |
|
|
| |
| for ax, y, label, cmap in [ |
| (axes[1, 0], y_real, "Real", "Blues"), |
| (axes[1, 1], y_fake, "Fake", "Reds"), |
| ]: |
| mel = librosa.feature.melspectrogram(y=y, sr=SR, n_mels=80, n_fft=512, hop_length=128) |
| mel_db = librosa.power_to_db(mel, ref=np.max) |
| img = librosa.display.specshow(mel_db, sr=SR, hop_length=128, x_axis="time", |
| y_axis="mel", ax=ax, cmap=cmap) |
| ax.set_title(f"Mel Spectrogram — {label}") |
| fig.colorbar(img, ax=ax, format="%+2.0f dB") |
|
|
| plt.tight_layout() |
| plt.show() |
|
|
|
|
| def hnr_autocorr(y, sr=SR, fmin=75, fmax=400): |
| """Estimate HNR via autocorrelation (PRAAT-inspired).""" |
| frame_len = int(sr * 0.04) |
| hop = int(sr * 0.01) |
| hnrs = [] |
| for start in range(0, len(y) - frame_len, hop): |
| frame = y[start : start + frame_len] |
| frame = frame * np.hanning(len(frame)) |
| r = np.correlate(frame, frame, mode="full") |
| r = r[len(r) // 2 :] |
| r0 = r[0] + 1e-8 |
| |
| min_lag = int(sr / fmax) |
| max_lag = int(sr / fmin) |
| if max_lag >= len(r): |
| continue |
| r_search = r[min_lag:max_lag] |
| if len(r_search) == 0: |
| continue |
| r_max = r_search.max() |
| hnr = 10 * np.log10(r_max / (r0 - r_max + 1e-8)) |
| hnrs.append(hnr) |
| return float(np.mean(hnrs)) if hnrs else 0.0 |
|
|
| print("Computing HNR …") |
| real_hnr = [hnr_autocorr(load_audio(AUDIO_DIR / r["id"])) for _, r in real_rows.iterrows()] |
| fake_hnr = [hnr_autocorr(load_audio(AUDIO_DIR / r["id"])) for _, r in fake_rows.iterrows()] |
|
|
| print(f"Real HNR — mean: {np.mean(real_hnr):.2f} dB std: {np.std(real_hnr):.2f}") |
| print(f"Fake HNR — mean: {np.mean(fake_hnr):.2f} dB std: {np.std(fake_hnr):.2f}") |
|
|
| fig, ax = plt.subplots(figsize=(7, 4)) |
| ax.hist(real_hnr, bins=30, alpha=0.6, color="steelblue", label="real") |
| ax.hist(fake_hnr, bins=30, alpha=0.6, color="tomato", label="fake") |
| ax.set_xlabel("HNR (dB)") |
| ax.set_ylabel("Count") |
| ax.set_title("HNR Distribution: Real vs Fake") |
| ax.legend() |
| plt.tight_layout() |
| plt.show() |
|
|
|
|
| submission = pd.DataFrame({ |
| "id": test_df["id"], |
| "score": 0.5, |
| }) |
| print(submission.head()) |
| print("\nSubmission shape:", submission.shape) |
| |
|
|
|
|