add app file
Browse files12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576import numpy as npimport torchimport librosaimport gradio as grfrom transformers import AutoFeatureExtractor, Wav2Vec2ForSequenceClassification
# 1. Load Model & Feature Extractor (Use direct HF loading or your exported ONNX model)model_id = "Bgeorge/deepfake-audio-detector-wav2vec2"print("📥 Loading deepfake detector for live streaming...")
feature_extractor = AutoFeatureExtractor.from_pretrained(model_id)model = Wav2Vec2ForSequenceClassification.from_pretrained(model_id)model.eval()
# Global buffer to store the rolling window of audio (e.g., up to 3 seconds at 16kHz = 48,000 samples)AUDIO_BUFFER_SIZE = 16000 * 3 audio_buffer = np.array([], dtype=np.float32)
def predict_stream(stream_chunk): global audio_buffer if stream_chunk is None: return "Listening..." # Gradio streaming provides a tuple: (sample_rate, numpy_array) sr, y = stream_chunk # Ensure audio is mono and float32 if y.ndim > 1: y = np.mean(y, axis=1) y = y.astype(np.float32) # Resample to 16kHz if the mic stream is a different sample rate (e.g., 44.1kHz or 48kHz) if sr != 16000: y = librosa.resample(y, orig_sr=sr, target_sr=16000) # Append new chunk to the rolling buffer audio_buffer = np.concatenate([audio_buffer, y]) # Keep only the latest N samples (sliding window) if len(audio_buffer) > AUDIO_BUFFER_SIZE: audio_buffer = audio_buffer[-AUDIO_BUFFER_SIZE:] # Wait until we have at least 1 second of audio before running inference if len(audio_buffer) < 16000: return "🎙️ Gathering audio context..." # Extract features and run inference inputs = feature_extractor(audio_buffer, sampling_rate=16000, return_tensors="pt", padding=True) with torch.no_grad(): outputs = model(**inputs) logits = outputs.logits probabilities = torch.softmax(logits, dim=-1).squeeze().tolist() # Assuming index 1 is Fake / Spoof, index 0 is Real fake_prob = probabilities[1] if len(probabilities) > 1 else probabilities[0] real_prob = probabilities[0] if len(probabilities) > 1 else (1 - probabilities[0]) if fake_prob > 0.5: return f"🚨 ALERT: Suspicious Speech Detected!\nConfidence (Fake): {fake_prob * 100:.1f}%" else: return f"✅ Status: Clean / Real Voice\nConfidence (Real): {real_prob * 100:.1f}%"
# 2. Build Gradio Live Interfacedemo = gr.Interface( fn=predict_stream, inputs=gr.Audio(sources=["microphone"], streaming=True, type="numpy", label="Live Microphone Stream"), outputs=gr.Textbox(label="Live Fraud Detection Feed", lines=3), live=True, title="Real-Time Voice Deepfake Detector", description="Speak into your microphone to simulate a live call stream. The model analyzes rolling audio chunks to flag synthetic speech.")
if __name__ == "__main__": demo.launch()app.pyAdded+76