"""Standalone evaluation for ResCapsGuard. python evaluate.py audio.wav""" from __future__ import annotations import numpy as np import torch from _net import CapsuleNet CUT = 64600 SAMPLE_RATE = 16000 D_ARGS = {"nb_samp": 64600, "first_conv": 128, "filts": [70, [1, 32], [32, 32], [32, 64], [64, 64]]} def pad_fixed(x: np.ndarray, max_len: int = CUT) -> np.ndarray: x = np.asarray(x, dtype=np.float32).reshape(-1) n = x.shape[0] if n >= max_len: return x[:max_len] return np.tile(x, max_len // n + 1)[:max_len].astype(np.float32) def load_model(ckpt: str = "new_capsules_changed_sinc_layer.pth", device: str = "cpu") -> CapsuleNet: gpu_id = 0 if device.startswith("cuda") else -1 model = CapsuleNet(num_class=2, gpu_id=gpu_id, d_args=D_ARGS, num_capsules=30, num_iterations=2) sd = torch.load(ckpt, map_location="cpu") sd = sd.get("state_dict", sd) if isinstance(sd, dict) else sd model.load_state_dict(sd, strict=True) return model.eval().to(device) @torch.no_grad() def score(model: CapsuleNet, audio: np.ndarray, device: str = "cpu") -> float: x = torch.from_numpy(pad_fixed(audio))[None].to(device) _z, class_ = model(x, random=False, dropout=0) return float(class_[0, 1]) if __name__ == "__main__": import sys from math import gcd import soundfile as sf from scipy.signal import resample_poly audio, sr = sf.read(sys.argv[1]) if audio.ndim == 2: audio = audio.mean(axis=1) audio = audio.astype(np.float32) if sr != SAMPLE_RATE: g = gcd(int(sr), SAMPLE_RATE) audio = resample_poly(audio, SAMPLE_RATE // g, int(sr) // g).astype(np.float32) model = load_model(device="cpu") print(f"bona-fide score: {score(model, audio):.6f} (higher = more bona fide)")