Spaces:
Sleeping
Sleeping
Upload 4 files
Browse files- app.py +466 -251
- config.json +7 -0
- model.py +157 -0
- requirements.txt +2 -5
app.py
CHANGED
|
@@ -1,296 +1,467 @@
|
|
| 1 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
import os
|
| 3 |
-
import io
|
| 4 |
import time
|
| 5 |
-
import
|
| 6 |
-
import random
|
| 7 |
-
import threading
|
| 8 |
import shutil
|
| 9 |
-
import
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
import gradio as gr
|
| 11 |
-
from
|
| 12 |
-
|
| 13 |
-
import
|
| 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 |
if classification == "AI_GENERATED":
|
| 54 |
if confidence >= 0.99:
|
| 55 |
return (
|
| 56 |
-
"The
|
| 57 |
-
"no natural micro-variations. These characteristics are definitive indicators of "
|
| 58 |
"AI-generated speech."
|
| 59 |
)
|
| 60 |
-
elif confidence >= 0.
|
| 61 |
return (
|
| 62 |
-
"
|
| 63 |
-
"
|
| 64 |
)
|
| 65 |
elif confidence >= 0.75:
|
| 66 |
return (
|
| 67 |
-
"
|
| 68 |
-
"
|
| 69 |
)
|
| 70 |
-
elif confidence >= 0.
|
| 71 |
return (
|
| 72 |
-
"
|
| 73 |
-
"human-like variations. Classification confidence is moderate."
|
| 74 |
)
|
| 75 |
else:
|
| 76 |
return (
|
| 77 |
-
"
|
| 78 |
-
"
|
| 79 |
)
|
| 80 |
-
|
|
|
|
| 81 |
if confidence >= 0.99:
|
| 82 |
return (
|
| 83 |
-
"The
|
| 84 |
-
"
|
| 85 |
)
|
| 86 |
-
elif confidence >= 0.
|
| 87 |
return (
|
| 88 |
-
"
|
| 89 |
-
"
|
| 90 |
)
|
| 91 |
elif confidence >= 0.75:
|
| 92 |
return (
|
| 93 |
-
"The
|
| 94 |
-
"effects may be present."
|
| 95 |
)
|
| 96 |
-
elif confidence >= 0.
|
| 97 |
return (
|
| 98 |
-
"The
|
| 99 |
-
"confidence is moderate."
|
| 100 |
)
|
| 101 |
else:
|
| 102 |
return (
|
| 103 |
-
"The
|
| 104 |
-
"
|
| 105 |
)
|
| 106 |
|
| 107 |
-
# ================= SENDER LOGIC =================
|
| 108 |
-
def run_sender_pipeline(file_path: str, filename: str) -> dict:
|
| 109 |
-
print("\n" + "="*50)
|
| 110 |
-
print("AI VOICE DETECTOR")
|
| 111 |
-
print("=================")
|
| 112 |
-
print("\nInitializing audio analysis pipeline...")
|
| 113 |
-
time.sleep(0.5)
|
| 114 |
-
print("Device: cuda")
|
| 115 |
-
time.sleep(0.3)
|
| 116 |
-
print("Loading audio processing pipeline...")
|
| 117 |
-
time.sleep(0.6)
|
| 118 |
-
print(f"Audio received: {filename}")
|
| 119 |
-
print("Preparing audio...")
|
| 120 |
-
time.sleep(0.4)
|
| 121 |
-
print("Decoding audio...")
|
| 122 |
-
time.sleep(0.5)
|
| 123 |
-
print("Sampling rate: 16000 Hz")
|
| 124 |
-
|
| 125 |
-
fake_duration = round(random.uniform(2.5, 8.5), 2)
|
| 126 |
-
print(f"Audio duration: {fake_duration} seconds")
|
| 127 |
-
|
| 128 |
-
time.sleep(0.7)
|
| 129 |
-
print("Extracting acoustic features...")
|
| 130 |
-
time.sleep(0.8)
|
| 131 |
-
print("Analyzing speech characteristics...")
|
| 132 |
-
print("Evaluating spectral patterns...")
|
| 133 |
-
time.sleep(0.5)
|
| 134 |
-
print("Evaluating temporal characteristics...")
|
| 135 |
-
time.sleep(0.6)
|
| 136 |
-
print("Running classification pipeline...")
|
| 137 |
-
time.sleep(0.4)
|
| 138 |
-
print("Calculating confidence...")
|
| 139 |
-
time.sleep(0.3)
|
| 140 |
-
print("Classification complete.\n")
|
| 141 |
-
|
| 142 |
-
is_ai = check_filename_for_prime(filename)
|
| 143 |
-
classification = "AI_GENERATED" if is_ai else "HUMAN"
|
| 144 |
-
confidence = round(random.uniform(0.75, 1.0), 3)
|
| 145 |
-
|
| 146 |
-
if confidence >= 0.999:
|
| 147 |
-
confidence = 0.999
|
| 148 |
-
|
| 149 |
-
explanation = generate_explanation(classification, confidence)
|
| 150 |
-
|
| 151 |
-
print("Result:")
|
| 152 |
-
print(f"Classification : {classification}")
|
| 153 |
-
print(f"Confidence : {confidence}")
|
| 154 |
-
print(f"Status : success\n")
|
| 155 |
-
print("Preparing response...")
|
| 156 |
-
time.sleep(0.2)
|
| 157 |
-
print("Response sent successfully.")
|
| 158 |
-
print("===========================\n")
|
| 159 |
-
|
| 160 |
-
result = {
|
| 161 |
-
"status": "success",
|
| 162 |
-
"classification": classification,
|
| 163 |
-
"confidenceScore": confidence,
|
| 164 |
-
"explanation": explanation,
|
| 165 |
-
"available": True
|
| 166 |
-
}
|
| 167 |
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
state["classification"] = classification
|
| 172 |
-
state["confidence"] = confidence
|
| 173 |
-
state["explanation"] = explanation
|
| 174 |
|
| 175 |
-
|
|
|
|
|
|
|
| 176 |
|
| 177 |
-
|
| 178 |
-
app = FastAPI()
|
| 179 |
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
result = run_sender_pipeline(file_path, filename)
|
| 192 |
-
return JSONResponse(content=result)
|
| 193 |
-
|
| 194 |
-
@app.get("/receiver")
|
| 195 |
-
async def receiver_endpoint(background_tasks: BackgroundTasks):
|
| 196 |
-
print("\n---")
|
| 197 |
-
print("\nRECEIVER\n")
|
| 198 |
-
print("Polling detection service...")
|
| 199 |
-
print("Checking /receiver...")
|
| 200 |
-
|
| 201 |
-
with state_lock:
|
| 202 |
-
is_available = state["available"]
|
| 203 |
-
|
| 204 |
-
if not is_available:
|
| 205 |
-
print("Audio availability: false")
|
| 206 |
-
print("Waiting for audio...\n---")
|
| 207 |
-
return JSONResponse(content={"available": False})
|
| 208 |
-
|
| 209 |
-
print("Audio availability: true")
|
| 210 |
-
print("Audio detected.")
|
| 211 |
-
print("Receiving audio stream...")
|
| 212 |
-
print("Receiving classification metadata...")
|
| 213 |
-
|
| 214 |
-
classification = state["classification"]
|
| 215 |
-
confidence = state["confidence"]
|
| 216 |
-
audio_path = state["audio_path"]
|
| 217 |
-
|
| 218 |
-
print(f"Audio Type : {classification}")
|
| 219 |
-
print(f"Confidence : {confidence}")
|
| 220 |
-
print("Saving received audio...")
|
| 221 |
-
time.sleep(0.5)
|
| 222 |
-
print("Audio received successfully.")
|
| 223 |
-
print("Processing complete.")
|
| 224 |
-
print("Waiting for next audio...")
|
| 225 |
-
print("-------------------------\n")
|
| 226 |
-
|
| 227 |
-
state["available"] = False
|
| 228 |
-
state["audio_path"] = None
|
| 229 |
-
state["classification"] = None
|
| 230 |
-
state["confidence"] = None
|
| 231 |
-
state["explanation"] = None
|
| 232 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 233 |
try:
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
except Exception
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
"
|
| 252 |
-
"
|
| 253 |
-
"
|
| 254 |
})
|
| 255 |
|
| 256 |
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 260 |
if not audio_path:
|
| 261 |
-
raise gr.Error("No audio uploaded")
|
| 262 |
|
| 263 |
try:
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
result =
|
| 269 |
-
|
| 270 |
-
return
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 286 |
with gr.Row():
|
|
|
|
| 287 |
with gr.Column():
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 291 |
with gr.Column():
|
| 292 |
-
|
| 293 |
-
|
|
|
|
|
|
|
|
|
|
| 294 |
analyze_btn.click(
|
| 295 |
fn=predict_gradio,
|
| 296 |
inputs=audio_input,
|
|
@@ -298,11 +469,55 @@ with gr.Blocks(title="AI Voice Detector") as demo:
|
|
| 298 |
api_name="detect_voice"
|
| 299 |
)
|
| 300 |
|
| 301 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 302 |
|
| 303 |
if __name__ == "__main__":
|
| 304 |
-
|
| 305 |
-
#
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
AI Voice / Speech Deepfake Detector
|
| 3 |
+
-----------------------------------
|
| 4 |
+
|
| 5 |
+
Runs:
|
| 6 |
+
Flask API -> http://127.0.0.1:7860
|
| 7 |
+
Gradio UI -> http://127.0.0.1:7861
|
| 8 |
+
|
| 9 |
+
API:
|
| 10 |
+
POST /api/detect
|
| 11 |
+
multipart/form-data
|
| 12 |
+
field: audio
|
| 13 |
+
|
| 14 |
+
Compatibility:
|
| 15 |
+
POST /sender
|
| 16 |
+
Same as /api/detect
|
| 17 |
+
|
| 18 |
+
Health:
|
| 19 |
+
GET /health
|
| 20 |
+
|
| 21 |
+
The model is loaded ONCE at application startup and reused for all requests.
|
| 22 |
+
|
| 23 |
+
Expected local files:
|
| 24 |
+
model.py
|
| 25 |
+
checkpoint_epoch_5.safetensors
|
| 26 |
+
config.json
|
| 27 |
+
|
| 28 |
+
The model's WavLM backbone is loaded from Hugging Face on the first run
|
| 29 |
+
unless it is already present in the local Hugging Face cache.
|
| 30 |
+
"""
|
| 31 |
+
|
| 32 |
import os
|
|
|
|
| 33 |
import time
|
| 34 |
+
import uuid
|
|
|
|
|
|
|
| 35 |
import shutil
|
| 36 |
+
import threading
|
| 37 |
+
import traceback
|
| 38 |
+
from pathlib import Path
|
| 39 |
+
|
| 40 |
+
import torch
|
| 41 |
+
import torchaudio
|
| 42 |
+
import torch.nn.functional as F
|
| 43 |
+
from flask import Flask, jsonify, request
|
| 44 |
import gradio as gr
|
| 45 |
+
from safetensors.torch import load_file
|
| 46 |
+
|
| 47 |
+
from model import DeepfakeDetector
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
# ============================================================
|
| 51 |
+
# CONFIG
|
| 52 |
+
# ============================================================
|
| 53 |
+
|
| 54 |
+
BASE_DIR = Path(__file__).resolve().parent
|
| 55 |
+
TEMP_DIR = BASE_DIR / "temp_audio"
|
| 56 |
+
TEMP_DIR.mkdir(exist_ok=True)
|
| 57 |
+
|
| 58 |
+
CHECKPOINT = BASE_DIR / "checkpoint_epoch_5.safetensors"
|
| 59 |
+
|
| 60 |
+
TARGET_SR = 16000
|
| 61 |
+
TARGET_SECONDS = 5.0
|
| 62 |
+
|
| 63 |
+
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 64 |
+
|
| 65 |
+
# Model decision threshold from the supplied inference.py
|
| 66 |
+
FAKE_THRESHOLD = 0.5
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
# ============================================================
|
| 70 |
+
# GLOBAL MODEL
|
| 71 |
+
# ============================================================
|
| 72 |
+
|
| 73 |
+
MODEL = None
|
| 74 |
+
MODEL_LOCK = threading.Lock()
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
# ============================================================
|
| 78 |
+
# AUDIO
|
| 79 |
+
# ============================================================
|
| 80 |
+
|
| 81 |
+
def load_audio(path, sr=TARGET_SR, seconds=TARGET_SECONDS):
|
| 82 |
+
"""
|
| 83 |
+
Load audio, convert to mono / 16 kHz and trim/pad to 5 seconds.
|
| 84 |
+
"""
|
| 85 |
+
|
| 86 |
+
wav, orig_sr = torchaudio.load(str(path))
|
| 87 |
+
|
| 88 |
+
# Stereo -> mono
|
| 89 |
+
if wav.shape[0] > 1:
|
| 90 |
+
wav = wav.mean(0, keepdim=True)
|
| 91 |
+
|
| 92 |
+
wav = wav.squeeze(0)
|
| 93 |
+
|
| 94 |
+
# Resample
|
| 95 |
+
if orig_sr != sr:
|
| 96 |
+
wav = torchaudio.functional.resample(
|
| 97 |
+
wav,
|
| 98 |
+
orig_sr,
|
| 99 |
+
sr
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
# Normalize
|
| 103 |
+
wav = wav / (wav.abs().max() + 1e-8)
|
| 104 |
+
|
| 105 |
+
# Exactly 5 seconds
|
| 106 |
+
n = int(seconds * sr)
|
| 107 |
+
cur = wav.shape[0]
|
| 108 |
+
|
| 109 |
+
if cur < n:
|
| 110 |
+
# Preserve the supplied inference.py behavior:
|
| 111 |
+
# repeat the audio until 5 seconds.
|
| 112 |
+
if cur == 0:
|
| 113 |
+
raise ValueError("Audio file contains no samples.")
|
| 114 |
+
|
| 115 |
+
wav = wav.repeat((n + cur - 1) // cur)[:n]
|
| 116 |
+
|
| 117 |
+
elif cur > n:
|
| 118 |
+
# Center crop
|
| 119 |
+
start = (cur - n) // 2
|
| 120 |
+
wav = wav[start:start + n]
|
| 121 |
+
|
| 122 |
+
return wav
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
# ============================================================
|
| 126 |
+
# MODEL
|
| 127 |
+
# ============================================================
|
| 128 |
+
|
| 129 |
+
def load_model():
|
| 130 |
+
global MODEL
|
| 131 |
+
|
| 132 |
+
print("=" * 60)
|
| 133 |
+
print("AI VOICE DETECTOR")
|
| 134 |
+
print("=" * 60)
|
| 135 |
+
|
| 136 |
+
print(f"Device: {DEVICE}")
|
| 137 |
+
|
| 138 |
+
if not CHECKPOINT.exists():
|
| 139 |
+
raise FileNotFoundError(
|
| 140 |
+
f"Checkpoint not found:\n{CHECKPOINT}"
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
print("Loading WavLM + AASIST model...")
|
| 144 |
+
print("This may download microsoft/wavlm-large on first run.")
|
| 145 |
+
|
| 146 |
+
model = DeepfakeDetector()
|
| 147 |
+
|
| 148 |
+
print(f"Loading checkpoint: {CHECKPOINT.name}")
|
| 149 |
+
|
| 150 |
+
state_dict = load_file(
|
| 151 |
+
str(CHECKPOINT),
|
| 152 |
+
device="cpu"
|
| 153 |
+
)
|
| 154 |
+
|
| 155 |
+
# Match the supplied inference.py behavior.
|
| 156 |
+
missing, unexpected = model.load_state_dict(
|
| 157 |
+
state_dict,
|
| 158 |
+
strict=False
|
| 159 |
+
)
|
| 160 |
+
|
| 161 |
+
if missing:
|
| 162 |
+
print("\nWARNING: Missing checkpoint keys:")
|
| 163 |
+
for key in missing:
|
| 164 |
+
print(f" - {key}")
|
| 165 |
+
|
| 166 |
+
if unexpected:
|
| 167 |
+
print("\nWARNING: Unexpected checkpoint keys:")
|
| 168 |
+
for key in unexpected:
|
| 169 |
+
print(f" - {key}")
|
| 170 |
+
|
| 171 |
+
model.to(DEVICE)
|
| 172 |
+
model.eval()
|
| 173 |
+
|
| 174 |
+
MODEL = model
|
| 175 |
+
|
| 176 |
+
print("\nModel loaded successfully.")
|
| 177 |
+
print("=" * 60)
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
# ============================================================
|
| 181 |
+
# INFERENCE
|
| 182 |
+
# ============================================================
|
| 183 |
+
|
| 184 |
+
@torch.inference_mode()
|
| 185 |
+
def detect_audio(audio_path):
|
| 186 |
+
if MODEL is None:
|
| 187 |
+
raise RuntimeError("Model has not been loaded.")
|
| 188 |
+
|
| 189 |
+
wav = load_audio(audio_path)
|
| 190 |
+
|
| 191 |
+
# (T) -> (1, T)
|
| 192 |
+
waveform = wav.unsqueeze(0).to(DEVICE)
|
| 193 |
+
|
| 194 |
+
# Serialize inference to avoid GPU memory races when multiple
|
| 195 |
+
# HTTP/Gradio requests arrive simultaneously.
|
| 196 |
+
with MODEL_LOCK:
|
| 197 |
+
logit = MODEL(waveform).float()
|
| 198 |
+
|
| 199 |
+
bonafide = torch.sigmoid(logit).item()
|
| 200 |
+
fake = 1.0 - bonafide
|
| 201 |
+
|
| 202 |
+
classification = (
|
| 203 |
+
"AI_GENERATED"
|
| 204 |
+
if fake >= FAKE_THRESHOLD
|
| 205 |
+
else "HUMAN"
|
| 206 |
+
)
|
| 207 |
+
|
| 208 |
+
# Confidence means confidence of the selected class.
|
| 209 |
+
confidence = (
|
| 210 |
+
fake
|
| 211 |
+
if classification == "AI_GENERATED"
|
| 212 |
+
else bonafide
|
| 213 |
+
)
|
| 214 |
+
|
| 215 |
+
explanation = generate_explanation(
|
| 216 |
+
classification,
|
| 217 |
+
confidence
|
| 218 |
+
)
|
| 219 |
+
|
| 220 |
+
return {
|
| 221 |
+
"status": "success",
|
| 222 |
+
"classification": classification,
|
| 223 |
+
"confidenceScore": round(confidence, 4),
|
| 224 |
+
"fake_probability": round(fake, 4),
|
| 225 |
+
"bonafide_score": round(bonafide, 4),
|
| 226 |
+
"verdict": "FAKE" if fake >= FAKE_THRESHOLD else "REAL",
|
| 227 |
+
"threshold": FAKE_THRESHOLD,
|
| 228 |
+
"device": str(DEVICE),
|
| 229 |
+
"sample_rate": TARGET_SR,
|
| 230 |
+
"analysis_duration_seconds": TARGET_SECONDS,
|
| 231 |
+
"explanation": explanation,
|
| 232 |
+
"available": True
|
| 233 |
+
}
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
# ============================================================
|
| 237 |
+
# EXPLANATION
|
| 238 |
+
# ============================================================
|
| 239 |
+
|
| 240 |
+
def generate_explanation(classification, confidence):
|
| 241 |
+
"""
|
| 242 |
+
This is deliberately framed as an interpretation of the model
|
| 243 |
+
result rather than claiming individual acoustic properties were
|
| 244 |
+
explicitly measured by the classifier.
|
| 245 |
+
"""
|
| 246 |
+
|
| 247 |
if classification == "AI_GENERATED":
|
| 248 |
if confidence >= 0.99:
|
| 249 |
return (
|
| 250 |
+
"The classifier assigned a very high probability to "
|
|
|
|
| 251 |
"AI-generated speech."
|
| 252 |
)
|
| 253 |
+
elif confidence >= 0.90:
|
| 254 |
return (
|
| 255 |
+
"The classifier found strong evidence consistent with "
|
| 256 |
+
"AI-generated speech."
|
| 257 |
)
|
| 258 |
elif confidence >= 0.75:
|
| 259 |
return (
|
| 260 |
+
"The classifier found multiple signals consistent with "
|
| 261 |
+
"AI-generated speech."
|
| 262 |
)
|
| 263 |
+
elif confidence >= 0.60:
|
| 264 |
return (
|
| 265 |
+
"The classifier moderately favors AI-generated speech."
|
|
|
|
| 266 |
)
|
| 267 |
else:
|
| 268 |
return (
|
| 269 |
+
"The classifier weakly favors AI-generated speech; "
|
| 270 |
+
"the result should be treated cautiously."
|
| 271 |
)
|
| 272 |
+
|
| 273 |
+
else:
|
| 274 |
if confidence >= 0.99:
|
| 275 |
return (
|
| 276 |
+
"The classifier assigned a very high probability to "
|
| 277 |
+
"human speech."
|
| 278 |
)
|
| 279 |
+
elif confidence >= 0.90:
|
| 280 |
return (
|
| 281 |
+
"The classifier found strong evidence consistent with "
|
| 282 |
+
"human speech."
|
| 283 |
)
|
| 284 |
elif confidence >= 0.75:
|
| 285 |
return (
|
| 286 |
+
"The classifier largely favors human speech."
|
|
|
|
| 287 |
)
|
| 288 |
+
elif confidence >= 0.60:
|
| 289 |
return (
|
| 290 |
+
"The classifier moderately favors human speech."
|
|
|
|
| 291 |
)
|
| 292 |
else:
|
| 293 |
return (
|
| 294 |
+
"The classifier weakly favors human speech; "
|
| 295 |
+
"the result should be treated cautiously."
|
| 296 |
)
|
| 297 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 298 |
|
| 299 |
+
# ============================================================
|
| 300 |
+
# FILE HANDLING
|
| 301 |
+
# ============================================================
|
|
|
|
|
|
|
|
|
|
| 302 |
|
| 303 |
+
def save_uploaded_file(file_storage):
|
| 304 |
+
if file_storage is None:
|
| 305 |
+
raise ValueError("No audio file provided.")
|
| 306 |
|
| 307 |
+
original_name = file_storage.filename or "audio.wav"
|
|
|
|
| 308 |
|
| 309 |
+
# Do not trust the original filename as a filesystem path.
|
| 310 |
+
safe_name = Path(original_name).name
|
| 311 |
+
|
| 312 |
+
unique_name = (
|
| 313 |
+
f"{int(time.time())}_{uuid.uuid4().hex}_{safe_name}"
|
| 314 |
+
)
|
| 315 |
+
|
| 316 |
+
output_path = TEMP_DIR / unique_name
|
| 317 |
+
|
| 318 |
+
file_storage.save(str(output_path))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 319 |
|
| 320 |
+
return output_path, safe_name
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
def cleanup_file(path):
|
| 324 |
try:
|
| 325 |
+
path = Path(path)
|
| 326 |
+
if path.exists():
|
| 327 |
+
path.unlink()
|
| 328 |
+
except Exception:
|
| 329 |
+
pass
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
# ============================================================
|
| 333 |
+
# FLASK
|
| 334 |
+
# ============================================================
|
| 335 |
+
|
| 336 |
+
app = Flask(__name__)
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
@app.get("/health")
|
| 340 |
+
def health():
|
| 341 |
+
return jsonify({
|
| 342 |
+
"status": "ok",
|
| 343 |
+
"model_loaded": MODEL is not None,
|
| 344 |
+
"device": str(DEVICE)
|
| 345 |
})
|
| 346 |
|
| 347 |
|
| 348 |
+
@app.post("/api/detect")
|
| 349 |
+
def api_detect():
|
| 350 |
+
"""
|
| 351 |
+
Main JSON API.
|
| 352 |
+
|
| 353 |
+
Request:
|
| 354 |
+
POST /api/detect
|
| 355 |
+
Content-Type: multipart/form-data
|
| 356 |
+
field: audio
|
| 357 |
+
|
| 358 |
+
Response:
|
| 359 |
+
JSON classification result.
|
| 360 |
+
"""
|
| 361 |
+
|
| 362 |
+
audio = request.files.get("audio")
|
| 363 |
+
|
| 364 |
+
if audio is None:
|
| 365 |
+
return jsonify({
|
| 366 |
+
"status": "error",
|
| 367 |
+
"error": "Missing 'audio' file field."
|
| 368 |
+
}), 400
|
| 369 |
+
|
| 370 |
+
file_path = None
|
| 371 |
+
|
| 372 |
+
try:
|
| 373 |
+
file_path, filename = save_uploaded_file(audio)
|
| 374 |
+
|
| 375 |
+
print(f"\nAPI request: {filename}")
|
| 376 |
+
|
| 377 |
+
result = detect_audio(file_path)
|
| 378 |
+
|
| 379 |
+
# Useful for debugging/integration.
|
| 380 |
+
result["filename"] = filename
|
| 381 |
+
|
| 382 |
+
return jsonify(result)
|
| 383 |
+
|
| 384 |
+
except Exception as exc:
|
| 385 |
+
traceback.print_exc()
|
| 386 |
+
|
| 387 |
+
return jsonify({
|
| 388 |
+
"status": "error",
|
| 389 |
+
"error": str(exc)
|
| 390 |
+
}), 500
|
| 391 |
+
|
| 392 |
+
finally:
|
| 393 |
+
if file_path:
|
| 394 |
+
cleanup_file(file_path)
|
| 395 |
+
|
| 396 |
+
|
| 397 |
+
@app.post("/sender")
|
| 398 |
+
def sender():
|
| 399 |
+
"""
|
| 400 |
+
Backward-compatible endpoint matching the previous application.
|
| 401 |
+
"""
|
| 402 |
+
|
| 403 |
+
return api_detect()
|
| 404 |
+
|
| 405 |
+
|
| 406 |
+
# ============================================================
|
| 407 |
+
# GRADIO
|
| 408 |
+
# ============================================================
|
| 409 |
+
|
| 410 |
+
def predict_gradio(audio_path):
|
| 411 |
+
"""
|
| 412 |
+
Gradio -> model -> JSON-compatible dictionary.
|
| 413 |
+
"""
|
| 414 |
+
|
| 415 |
if not audio_path:
|
| 416 |
+
raise gr.Error("No audio uploaded.")
|
| 417 |
|
| 418 |
try:
|
| 419 |
+
audio_path = Path(audio_path)
|
| 420 |
+
|
| 421 |
+
result = detect_audio(audio_path)
|
| 422 |
+
|
| 423 |
+
result["filename"] = audio_path.name
|
| 424 |
+
|
| 425 |
+
return result
|
| 426 |
+
|
| 427 |
+
except Exception as exc:
|
| 428 |
+
traceback.print_exc()
|
| 429 |
+
raise gr.Error(f"Detection failed: {exc}")
|
| 430 |
+
|
| 431 |
+
|
| 432 |
+
with gr.Blocks(
|
| 433 |
+
title="AI Voice Detector"
|
| 434 |
+
) as demo:
|
| 435 |
+
|
| 436 |
+
gr.Markdown(
|
| 437 |
+
"""
|
| 438 |
+
# AI Voice Detector
|
| 439 |
+
|
| 440 |
+
Upload an audio recording to classify it as **human** or
|
| 441 |
+
**AI-generated** using the WavLM + AASIST speech deepfake detector.
|
| 442 |
+
"""
|
| 443 |
+
)
|
| 444 |
+
|
| 445 |
with gr.Row():
|
| 446 |
+
|
| 447 |
with gr.Column():
|
| 448 |
+
|
| 449 |
+
audio_input = gr.Audio(
|
| 450 |
+
type="filepath",
|
| 451 |
+
label="Upload Audio"
|
| 452 |
+
)
|
| 453 |
+
|
| 454 |
+
analyze_btn = gr.Button(
|
| 455 |
+
"Analyze",
|
| 456 |
+
variant="primary"
|
| 457 |
+
)
|
| 458 |
+
|
| 459 |
with gr.Column():
|
| 460 |
+
|
| 461 |
+
result_json = gr.JSON(
|
| 462 |
+
label="Detection Result"
|
| 463 |
+
)
|
| 464 |
+
|
| 465 |
analyze_btn.click(
|
| 466 |
fn=predict_gradio,
|
| 467 |
inputs=audio_input,
|
|
|
|
| 469 |
api_name="detect_voice"
|
| 470 |
)
|
| 471 |
|
| 472 |
+
|
| 473 |
+
# ============================================================
|
| 474 |
+
# SERVER STARTUP
|
| 475 |
+
# ============================================================
|
| 476 |
+
|
| 477 |
+
def start_gradio():
|
| 478 |
+
"""
|
| 479 |
+
Run Gradio independently from Flask.
|
| 480 |
+
|
| 481 |
+
Flask stays on port 7860.
|
| 482 |
+
Gradio stays on port 7861.
|
| 483 |
+
"""
|
| 484 |
+
|
| 485 |
+
demo.queue().launch(
|
| 486 |
+
server_name="0.0.0.0",
|
| 487 |
+
server_port=7861,
|
| 488 |
+
show_error=True,
|
| 489 |
+
prevent_thread_lock=True
|
| 490 |
+
)
|
| 491 |
+
|
| 492 |
|
| 493 |
if __name__ == "__main__":
|
| 494 |
+
|
| 495 |
+
# Load model exactly once.
|
| 496 |
+
load_model()
|
| 497 |
+
|
| 498 |
+
# Run Gradio in the background.
|
| 499 |
+
gradio_thread = threading.Thread(
|
| 500 |
+
target=start_gradio,
|
| 501 |
+
daemon=True
|
| 502 |
+
)
|
| 503 |
+
|
| 504 |
+
gradio_thread.start()
|
| 505 |
+
|
| 506 |
+
print("\n")
|
| 507 |
+
print("=" * 60)
|
| 508 |
+
print("SERVERS")
|
| 509 |
+
print("=" * 60)
|
| 510 |
+
print("Flask API : http://127.0.0.1:7860")
|
| 511 |
+
print("Gradio UI : http://127.0.0.1:7861")
|
| 512 |
+
print()
|
| 513 |
+
print("API endpoint:")
|
| 514 |
+
print("POST http://127.0.0.1:7860/api/detect")
|
| 515 |
+
print("Field: audio")
|
| 516 |
+
print("=" * 60)
|
| 517 |
+
|
| 518 |
+
# Flask API
|
| 519 |
+
app.run(
|
| 520 |
+
host="0.0.0.0",
|
| 521 |
+
port=7860,
|
| 522 |
+
threaded=True
|
| 523 |
+
)
|
config.json
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": ["DeepfakeDetector"],
|
| 3 |
+
"model_type": "wavlm-aasist-deepfake-detector",
|
| 4 |
+
"backbone": "microsoft/wavlm-large",
|
| 5 |
+
"pooling": "aasist",
|
| 6 |
+
"task": "audio-classification"
|
| 7 |
+
}
|
model.py
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""WavLM-large + AASIST speech deepfake detector (inference only)."""
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
from transformers import WavLMModel
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class _GraphAttentionLayer(nn.Module):
|
| 9 |
+
def __init__(self, in_dim, out_dim, temperature):
|
| 10 |
+
super().__init__()
|
| 11 |
+
self.att_proj = nn.Linear(in_dim, out_dim)
|
| 12 |
+
self.att_weight = nn.Parameter(torch.empty(out_dim, 1))
|
| 13 |
+
self.proj_with_att = nn.Linear(in_dim, out_dim)
|
| 14 |
+
self.proj_without_att = nn.Linear(in_dim, out_dim)
|
| 15 |
+
self.bn = nn.BatchNorm1d(out_dim)
|
| 16 |
+
self.temp = temperature
|
| 17 |
+
|
| 18 |
+
def forward(self, x):
|
| 19 |
+
N = x.size(1)
|
| 20 |
+
x_i = x.unsqueeze(2).expand(-1, -1, N, -1)
|
| 21 |
+
att = torch.matmul(torch.tanh(self.att_proj(x_i * x_i.transpose(1, 2))), self.att_weight) / self.temp
|
| 22 |
+
att = F.softmax(att, dim=-2)
|
| 23 |
+
out = self.proj_with_att(torch.matmul(att.squeeze(-1), x)) + self.proj_without_att(x)
|
| 24 |
+
s = out.shape
|
| 25 |
+
return F.selu(self.bn(out.reshape(-1, s[-1])).reshape(s))
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class _HtrgGraphAttentionLayer(nn.Module):
|
| 29 |
+
def __init__(self, in_dim, out_dim, temperature):
|
| 30 |
+
super().__init__()
|
| 31 |
+
self.proj_type1 = nn.Linear(in_dim, in_dim)
|
| 32 |
+
self.proj_type2 = nn.Linear(in_dim, in_dim)
|
| 33 |
+
self.att_proj = nn.Linear(in_dim, out_dim)
|
| 34 |
+
self.att_projM = nn.Linear(in_dim, out_dim)
|
| 35 |
+
self.att_weight11 = nn.Parameter(torch.empty(out_dim, 1))
|
| 36 |
+
self.att_weight22 = nn.Parameter(torch.empty(out_dim, 1))
|
| 37 |
+
self.att_weight12 = nn.Parameter(torch.empty(out_dim, 1))
|
| 38 |
+
self.att_weightM = nn.Parameter(torch.empty(out_dim, 1))
|
| 39 |
+
self.proj_with_att = nn.Linear(in_dim, out_dim)
|
| 40 |
+
self.proj_without_att = nn.Linear(in_dim, out_dim)
|
| 41 |
+
self.proj_with_attM = nn.Linear(in_dim, out_dim)
|
| 42 |
+
self.proj_without_attM = nn.Linear(in_dim, out_dim)
|
| 43 |
+
self.bn = nn.BatchNorm1d(out_dim)
|
| 44 |
+
self.temp = temperature
|
| 45 |
+
|
| 46 |
+
def forward(self, x1, x2, master):
|
| 47 |
+
n1 = x1.size(1)
|
| 48 |
+
x = torch.cat([self.proj_type1(x1), self.proj_type2(x2)], dim=1)
|
| 49 |
+
N = x.size(1)
|
| 50 |
+
x_i = x.unsqueeze(2).expand(-1, -1, N, -1)
|
| 51 |
+
att_map = torch.tanh(self.att_proj(x_i * x_i.transpose(1, 2)))
|
| 52 |
+
board = torch.zeros_like(att_map[:, :, :, 0]).unsqueeze(-1)
|
| 53 |
+
board[:, :n1, :n1] = torch.matmul(att_map[:, :n1, :n1], self.att_weight11)
|
| 54 |
+
board[:, n1:, n1:] = torch.matmul(att_map[:, n1:, n1:], self.att_weight22)
|
| 55 |
+
board[:, :n1, n1:] = torch.matmul(att_map[:, :n1, n1:], self.att_weight12)
|
| 56 |
+
board[:, n1:, :n1] = torch.matmul(att_map[:, n1:, :n1], self.att_weight12)
|
| 57 |
+
board = F.softmax(board / self.temp, dim=-2)
|
| 58 |
+
out = self.proj_with_att(torch.matmul(board.squeeze(-1), x)) + self.proj_without_att(x)
|
| 59 |
+
s = out.shape
|
| 60 |
+
out = F.selu(self.bn(out.reshape(-1, s[-1])).reshape(s))
|
| 61 |
+
att_m = F.softmax(torch.matmul(torch.tanh(self.att_projM(x * master)), self.att_weightM) / self.temp, dim=-2)
|
| 62 |
+
master = self.proj_with_attM(torch.matmul(att_m.squeeze(-1).unsqueeze(1), x)) + self.proj_without_attM(master)
|
| 63 |
+
return out.narrow(1, 0, n1), out.narrow(1, n1, N - n1), master
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
class _GraphPool(nn.Module):
|
| 67 |
+
def __init__(self, k, in_dim):
|
| 68 |
+
super().__init__()
|
| 69 |
+
self.k = k
|
| 70 |
+
self.proj = nn.Linear(in_dim, 1)
|
| 71 |
+
|
| 72 |
+
def forward(self, h):
|
| 73 |
+
scores = torch.sigmoid(self.proj(h))
|
| 74 |
+
n_keep = max(int(h.size(1) * self.k), 1)
|
| 75 |
+
idx = torch.topk(scores, n_keep, dim=1)[1].expand(-1, -1, h.size(-1))
|
| 76 |
+
return torch.gather(h * scores, 1, idx)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
class AASISTPool(nn.Module):
|
| 80 |
+
def __init__(self, feat_dim, num_layers, gat_dims=(128, 64),
|
| 81 |
+
pool_ratios=(0.5, 0.7, 0.5, 0.5), temps=(2.0, 2.0, 100.0, 100.0)):
|
| 82 |
+
super().__init__()
|
| 83 |
+
g = list(gat_dims)
|
| 84 |
+
self.proj = nn.Linear(feat_dim, g[0])
|
| 85 |
+
self.pos_S = nn.Parameter(torch.randn(1, num_layers, g[0]))
|
| 86 |
+
self.master1 = nn.Parameter(torch.randn(1, 1, g[0]))
|
| 87 |
+
self.master2 = nn.Parameter(torch.randn(1, 1, g[0]))
|
| 88 |
+
self.GAT_S = _GraphAttentionLayer(g[0], g[0], temps[0])
|
| 89 |
+
self.GAT_T = _GraphAttentionLayer(g[0], g[0], temps[1])
|
| 90 |
+
self.HtrgGAT_11 = _HtrgGraphAttentionLayer(g[0], g[1], temps[2])
|
| 91 |
+
self.HtrgGAT_12 = _HtrgGraphAttentionLayer(g[1], g[1], temps[3])
|
| 92 |
+
self.HtrgGAT_21 = _HtrgGraphAttentionLayer(g[0], g[1], temps[2])
|
| 93 |
+
self.HtrgGAT_22 = _HtrgGraphAttentionLayer(g[1], g[1], temps[3])
|
| 94 |
+
self.pool_S = _GraphPool(pool_ratios[0], g[0])
|
| 95 |
+
self.pool_T = _GraphPool(pool_ratios[1], g[0])
|
| 96 |
+
self.pool_hS1 = _GraphPool(pool_ratios[2], g[1])
|
| 97 |
+
self.pool_hT1 = _GraphPool(pool_ratios[2], g[1])
|
| 98 |
+
self.pool_hS2 = _GraphPool(pool_ratios[2], g[1])
|
| 99 |
+
self.pool_hT2 = _GraphPool(pool_ratios[2], g[1])
|
| 100 |
+
self.output_dim = 5 * g[1]
|
| 101 |
+
|
| 102 |
+
def forward(self, hidden_states):
|
| 103 |
+
projected = self.proj(torch.stack(hidden_states, dim=1))
|
| 104 |
+
e_S = torch.max(torch.abs(projected), dim=2)[0] + self.pos_S
|
| 105 |
+
e_T = torch.max(torch.abs(projected), dim=1)[0]
|
| 106 |
+
out_S = self.pool_S(self.GAT_S(e_S))
|
| 107 |
+
out_T = self.pool_T(self.GAT_T(e_T))
|
| 108 |
+
out_T1, out_S1, m1 = self.HtrgGAT_11(out_T, out_S, self.master1)
|
| 109 |
+
out_S1, out_T1 = self.pool_hS1(out_S1), self.pool_hT1(out_T1)
|
| 110 |
+
a_T, a_S, a_m = self.HtrgGAT_12(out_T1, out_S1, m1)
|
| 111 |
+
out_T1, out_S1, m1 = out_T1 + a_T, out_S1 + a_S, m1 + a_m
|
| 112 |
+
out_T2, out_S2, m2 = self.HtrgGAT_21(out_T, out_S, self.master2)
|
| 113 |
+
out_S2, out_T2 = self.pool_hS2(out_S2), self.pool_hT2(out_T2)
|
| 114 |
+
a_T, a_S, a_m = self.HtrgGAT_22(out_T2, out_S2, m2)
|
| 115 |
+
out_T2, out_S2, m2 = out_T2 + a_T, out_S2 + a_S, m2 + a_m
|
| 116 |
+
out_T, out_S, master = torch.max(out_T1, out_T2), torch.max(out_S1, out_S2), torch.max(m1, m2)
|
| 117 |
+
return torch.cat([torch.max(torch.abs(out_T), 1)[0], out_T.mean(1),
|
| 118 |
+
torch.max(torch.abs(out_S), 1)[0], out_S.mean(1), master.squeeze(1)], dim=1)
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
class MLPBlock(nn.Module):
|
| 122 |
+
def __init__(self, dim):
|
| 123 |
+
super().__init__()
|
| 124 |
+
self.net = nn.Sequential(nn.Linear(dim, dim * 2), nn.GELU(), nn.Dropout(0.1),
|
| 125 |
+
nn.Linear(dim * 2, dim), nn.GELU(), nn.Dropout(0.1))
|
| 126 |
+
|
| 127 |
+
def forward(self, x):
|
| 128 |
+
return self.net(x)
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
class Classifier(nn.Module):
|
| 132 |
+
def __init__(self, input_dim, hidden_dim, num_layers, num_labels=1):
|
| 133 |
+
super().__init__()
|
| 134 |
+
self.input_proj = nn.Linear(input_dim, hidden_dim) if input_dim != hidden_dim else nn.Identity()
|
| 135 |
+
self.mlp_blocks = nn.ModuleList([MLPBlock(hidden_dim) for _ in range(num_layers)])
|
| 136 |
+
self.layer_norms = nn.ModuleList([nn.LayerNorm(hidden_dim) for _ in range(num_layers)])
|
| 137 |
+
self.output_head = nn.Sequential(nn.Linear(hidden_dim, hidden_dim), nn.GELU(),
|
| 138 |
+
nn.Dropout(0.1), nn.Linear(hidden_dim, num_labels))
|
| 139 |
+
|
| 140 |
+
def forward(self, x):
|
| 141 |
+
x = self.input_proj(x)
|
| 142 |
+
for mlp, ln in zip(self.mlp_blocks, self.layer_norms):
|
| 143 |
+
x = x + mlp(ln(x))
|
| 144 |
+
return self.output_head(x)
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
class DeepfakeDetector(nn.Module):
|
| 148 |
+
def __init__(self, hidden_dim=320, classifier_layers=3, aasist_gat_dims=(128, 64)):
|
| 149 |
+
super().__init__()
|
| 150 |
+
self.wavlm = WavLMModel.from_pretrained("microsoft/wavlm-large")
|
| 151 |
+
self.pool = AASISTPool(self.wavlm.config.hidden_size, self.wavlm.config.num_hidden_layers, aasist_gat_dims)
|
| 152 |
+
self.classifier = Classifier(self.pool.output_dim, hidden_dim, classifier_layers)
|
| 153 |
+
|
| 154 |
+
@torch.no_grad()
|
| 155 |
+
def forward(self, waveform): # (B, T) 16 kHz -> logit (B,); sigmoid(logit)=P(real)
|
| 156 |
+
hs = list(self.wavlm(waveform, output_hidden_states=True).hidden_states[1:])
|
| 157 |
+
return self.classifier(self.pool(hs)).squeeze(-1)
|
requirements.txt
CHANGED
|
@@ -1,7 +1,4 @@
|
|
| 1 |
-
spaces==0.51.1
|
| 2 |
-
huggingface_hub>=0.28.1
|
| 3 |
torch
|
|
|
|
| 4 |
transformers
|
| 5 |
-
|
| 6 |
-
numpy
|
| 7 |
-
soundfile
|
|
|
|
|
|
|
|
|
|
| 1 |
torch
|
| 2 |
+
torchaudio
|
| 3 |
transformers
|
| 4 |
+
safetensors
|
|
|
|
|
|