| from pathlib import Path |
| import numpy as np |
| import pandas as pd |
| import librosa |
| from sklearn.ensemble import ExtraTreesClassifier |
| from sklearn.preprocessing import StandardScaler |
| from sklearn.model_selection import train_test_split |
| from sklearn.metrics import roc_auc_score, confusion_matrix, ConfusionMatrixDisplay |
| import matplotlib |
| matplotlib.use("Agg") |
| import matplotlib.pyplot as plt |
| 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") |
| train_df["label"] = (train_df["label"] == "fake").astype(int) |
| test_df = pd.read_csv(DATA_DIR / "test.csv") |
| print("Train:", train_df.shape, " Test:", test_df.shape) |
|
|
|
|
| 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))) |
| return y[:n_samples] |
|
|
|
|
| def hnr_autocorr(y, sr=SR, fmin=75, fmax=400): |
| 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] * np.hanning(frame_len) |
| r = np.correlate(frame, frame, mode="full") |
| r = r[len(r) // 2:] |
| r0 = r[0] + 1e-8 |
| min_lag, max_lag = int(sr / fmax), int(sr / fmin) |
| if max_lag >= len(r): |
| continue |
| r_max = r[min_lag:max_lag].max() |
| hnrs.append(10 * np.log10(r_max / (r0 - r_max + 1e-8))) |
| return float(np.mean(hnrs)) if hnrs else 0.0 |
|
|
|
|
| def jitter_shimmer_approx(y, sr=SR): |
| """Approximate jitter (F0 variation) and shimmer (amplitude variation).""" |
| |
| try: |
| f0 = librosa.yin(y, fmin=75, fmax=400, sr=sr, |
| frame_length=int(sr * 0.04), |
| hop_length=int(sr * 0.01)) |
| f0_voiced = f0[(f0 > 75) & (f0 < 400)] |
| except Exception: |
| f0_voiced = np.array([]) |
|
|
| jitter = float(np.std(np.diff(f0_voiced))) if len(f0_voiced) > 1 else 0.0 |
|
|
| |
| hop = int(sr * 0.01) |
| frame_len = int(sr * 0.04) |
| amps = [] |
| for start in range(0, len(y) - frame_len, hop): |
| amps.append(float(np.sqrt(np.mean(y[start: start + frame_len] ** 2)))) |
| amps = np.array(amps) |
| if len(amps) > 1 and amps.mean() > 1e-8: |
| shimmer = float(np.std(np.diff(amps)) / amps.mean()) |
| else: |
| shimmer = 0.0 |
| return jitter, shimmer |
|
|
|
|
| def extract_features(path): |
| y = load_audio(path) |
| n_fft = 512 |
|
|
| sf = librosa.feature.spectral_flatness(y=y)[0] |
| mfcc = librosa.feature.mfcc(y=y, sr=SR, n_mfcc=20) |
| mfcc_delta = librosa.feature.delta(mfcc) |
| zcr = librosa.feature.zero_crossing_rate(y)[0] |
| rms = librosa.feature.rms(y=y)[0] |
|
|
| chroma = librosa.feature.chroma_stft(y=y, sr=SR, n_fft=n_fft) |
|
|
| cent = librosa.feature.spectral_centroid(y=y, sr=SR, n_fft=n_fft)[0] |
| bw = librosa.feature.spectral_bandwidth(y=y, sr=SR, n_fft=n_fft)[0] |
| roll = librosa.feature.spectral_rolloff(y=y, sr=SR, n_fft=n_fft)[0] |
|
|
| S = np.abs(librosa.stft(y, n_fft=n_fft)) ** 2 |
| freqs = librosa.fft_frequencies(sr=SR, n_fft=n_fft) |
| hfe = float(S[freqs >= 4000].sum() / (S.sum() + 1e-8)) |
|
|
| jitter, shimmer = jitter_shimmer_approx(y) |
| hnr = hnr_autocorr(y) |
|
|
| feat = np.concatenate([ |
| [np.mean(sf), np.std(sf)], |
| [hfe], |
| np.mean(mfcc, axis=1), |
| np.std(mfcc, axis=1), |
| np.mean(mfcc_delta, axis=1), |
| [np.mean(zcr), np.std(zcr)], |
| [np.mean(rms), np.std(rms)], |
| np.mean(chroma, axis=1), |
| [np.mean(cent), np.std(cent)], |
| [np.mean(bw), np.std(bw)], |
| [np.mean(roll), np.std(roll)], |
| [jitter, shimmer, hnr], |
| ]) |
| return feat |
|
|
|
|
| from joblib import Parallel, delayed |
| from tqdm import tqdm |
| Path("cache").mkdir(exist_ok=True) |
|
|
| def _ex(row_id): |
| return extract_features(AUDIO_DIR / row_id) |
|
|
| def cached_extract(df, cache_name): |
| cp = Path("cache") / cache_name |
| if cp.exists(): |
| print(f"[cache] Loading {cache_name}"); return np.load(cp) |
| feats = np.array(Parallel(n_jobs=-1, prefer="threads")( |
| delayed(_ex)(r["id"]) for _, r in tqdm(df.iterrows(), total=len(df)))) |
| np.save(cp, feats); print(f"[cache] Saved {cache_name}"); return feats |
|
|
| print("Extracting train features …") |
| X_train_raw = np.nan_to_num(cached_extract(train_df, "vg_02_train.npy"), nan=0.0, posinf=0.0, neginf=0.0) |
| y_train = train_df["label"].to_numpy() |
| print("Done. Shape:", X_train_raw.shape) |
|
|
| print("Extracting test features …") |
| X_test_raw = np.nan_to_num(cached_extract(test_df, "vg_02_test.npy"), nan=0.0, posinf=0.0, neginf=0.0) |
| print("Done. Shape:", X_test_raw.shape) |
|
|
|
|
| X_tr, X_val, y_tr, y_val = train_test_split( |
| X_train_raw, y_train, test_size=0.2, random_state=42, stratify=y_train |
| ) |
| scaler = StandardScaler() |
| X_tr_s = scaler.fit_transform(X_tr) |
| X_val_s = scaler.transform(X_val) |
| X_test_s = scaler.transform(X_test_raw) |
|
|
|
|
| clf = ExtraTreesClassifier(n_estimators=300, random_state=42, n_jobs=-1) |
| clf.fit(X_tr_s, y_tr) |
|
|
| val_probs = clf.predict_proba(X_val_s)[:, 1] |
| val_preds = (val_probs >= 0.5).astype(int) |
| auroc = roc_auc_score(y_val, val_probs) |
| print(f"Validation AUROC: {auroc:.4f}") |
|
|
|
|
| importances = clf.feature_importances_ |
| top_idx = np.argsort(importances)[::-1][:20] |
| fig, ax = plt.subplots(figsize=(9, 4)) |
| ax.bar(range(20), importances[top_idx]) |
| ax.set_xticks(range(20)) |
| ax.set_xticklabels([f"f{i}" for i in top_idx], rotation=45) |
| ax.set_ylabel("Importance") |
| ax.set_title("Top-20 Feature Importances") |
| plt.tight_layout() |
| plt.savefig("/dev/null") |
|
|
|
|
| cm = confusion_matrix(y_val, val_preds) |
| disp = ConfusionMatrixDisplay(cm, display_labels=["real", "fake"]) |
| fig, ax = plt.subplots(figsize=(4, 4)) |
| disp.plot(ax=ax, colorbar=False) |
| ax.set_title(f"Confusion Matrix AUROC={auroc:.3f}") |
| plt.tight_layout() |
| plt.savefig("/dev/null") |
|
|
|
|
| test_probs = clf.predict_proba(X_test_s)[:, 1] |
| np.save("probs_rf.npy", test_probs) |
|
|
| submission = pd.DataFrame({"id": test_df["id"], "score": test_probs}) |
| submission.to_csv("submission_rf.csv", index=False) |
| print(submission.head()) |
| print("Saved submission_rf.csv | probs_rf.npy") |
|
|
|
|