File size: 5,904 Bytes
a394d8b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 | # =========================================================
# IMPORT
# =========================================================
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchaudio
# =========================================================
# CONFIG (GIỐNG TRAIN + OFFLINE TEST)
# =========================================================
SR = 16000
N_MELS = 80
N_FFT = 1024
HOP = 256
MAX_LEN_CONF = 160
CROP_SEC = 2.5
NUM_CROPS = 5 # 🔥 GIỐNG OFFLINE
TH_CONF = 0.5 # 🔥 GIỐNG OFFLINE
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# =========================================================
# MEL
# =========================================================
mel_extractor = torchaudio.transforms.MelSpectrogram(
sample_rate=SR,
n_fft=N_FFT,
hop_length=HOP,
n_mels=N_MELS,
power=2.0
).to(DEVICE)
db_transform = torchaudio.transforms.AmplitudeToDB(stype="power")
# =========================================================
# MODEL
# =========================================================
class ConvSubsampling(nn.Module):
def __init__(self):
super().__init__()
self.conv = nn.Sequential(
nn.Conv2d(1, 64, 3, stride=2, padding=1),
nn.ReLU(),
nn.Conv2d(64, 64, 3, stride=2, padding=1),
nn.ReLU(),
)
def forward(self, x):
x = self.conv(x.unsqueeze(1))
b, c, f, t = x.shape
return x.view(b, c * f, t).transpose(1, 2)
class ConformerBlock(nn.Module):
def __init__(self, dim, heads=4, dropout=0.3):
super().__init__()
self.ff1 = nn.Sequential(
nn.LayerNorm(dim),
nn.Linear(dim, dim * 4),
nn.GELU(),
nn.Dropout(dropout),
nn.Linear(dim * 4, dim),
)
self.attn = nn.MultiheadAttention(
dim, heads, dropout=dropout, batch_first=True
)
self.norm_attn = nn.LayerNorm(dim)
self.conv = nn.Sequential(
nn.Conv1d(dim, dim, 3, padding=1, groups=dim),
nn.BatchNorm1d(dim),
nn.GELU(),
nn.Conv1d(dim, dim, 1),
)
self.norm_conv = nn.LayerNorm(dim)
self.ff2 = nn.Sequential(
nn.LayerNorm(dim),
nn.Linear(dim, dim * 4),
nn.GELU(),
nn.Dropout(dropout),
nn.Linear(dim * 4, dim),
)
self.norm_out = nn.LayerNorm(dim)
def forward(self, x):
x = x + 0.5 * self.ff1(x)
attn, _ = self.attn(x, x, x)
x = self.norm_attn(x + attn)
conv = self.conv(x.transpose(1, 2)).transpose(1, 2)
x = self.norm_conv(x + conv)
x = x + 0.5 * self.ff2(x)
return self.norm_out(x)
class AttentivePooling(nn.Module):
def __init__(self, dim):
super().__init__()
self.att = nn.Linear(dim, 1)
def forward(self, x):
w = torch.softmax(self.att(x), dim=1)
return (x * w).sum(dim=1)
ENC_DIM = 64 * (N_MELS // 4)
class AntiDeepfakeConformer(nn.Module):
def __init__(self):
super().__init__()
self.subsample = ConvSubsampling()
self.encoder = nn.Sequential(
ConformerBlock(ENC_DIM),
ConformerBlock(ENC_DIM),
ConformerBlock(ENC_DIM),
)
self.pool = AttentivePooling(ENC_DIM)
self.fc = nn.Sequential(
nn.Linear(ENC_DIM, 128),
nn.ReLU(),
nn.Dropout(0.3),
nn.Linear(128, 1)
)
def forward(self, x):
x = self.subsample(x)
x = self.encoder(x)
x = self.pool(x)
return self.fc(x).squeeze(1)
# =========================================================
# LOAD MODEL
# =========================================================
conformer_model = AntiDeepfakeConformer().to(DEVICE)
conformer_model.load_state_dict(
torch.load("anti_ai_conformer_best.pt", map_location=DEVICE)
)
conformer_model.eval()
# =========================================================
# UTILS (GIỐNG OFFLINE)
# =========================================================
def normalize_soft(audio, target_rms=0.08):
rms = np.sqrt(np.mean(audio ** 2) + 1e-9)
scale = min(target_rms / rms, 3.0)
return audio * scale
def split_crops(audio, sr=SR, crop_sec=CROP_SEC, num_crops=NUM_CROPS):
crop_len = int(sr * crop_sec)
if len(audio) <= crop_len:
return [audio]
step = max((len(audio) - crop_len) // (num_crops - 1), 1)
crops = []
for i in range(num_crops):
start = i * step
seg = audio[start:start + crop_len]
if len(seg) == crop_len:
crops.append(seg)
return crops
# =========================================================
# PREDICT (CHUẨN – GIỐNG OFFLINE)
# =========================================================
def predict_conformer(audio: np.ndarray):
audio = normalize_soft(audio)
crops = split_crops(audio)
if len(crops) == 0:
return 0.0, "UNKNOWN"
probs = []
with torch.no_grad():
for seg in crops:
seg = torch.tensor(seg, dtype=torch.float32).to(DEVICE)
mel = db_transform(mel_extractor(seg))
if mel.shape[1] < MAX_LEN_CONF:
mel = F.pad(mel, (0, MAX_LEN_CONF - mel.shape[1]))
else:
mel = mel[:, :MAX_LEN_CONF]
mel = mel.unsqueeze(0)
prob = torch.sigmoid(conformer_model(mel)).item()
probs.append(prob)
final_score = float(np.mean(probs))
label = "AI" if final_score >= TH_CONF else "HUMAN"
return final_score, label
|