Spaces:
Sleeping
Sleeping
File size: 5,636 Bytes
6b1f3f6 1d5f3a7 6b1f3f6 1d5f3a7 6b1f3f6 1d5f3a7 6b1f3f6 1d5f3a7 6b1f3f6 1d5f3a7 6b1f3f6 1d5f3a7 6b1f3f6 1d5f3a7 6b1f3f6 1d5f3a7 6b1f3f6 1d5f3a7 6b1f3f6 1d5f3a7 6b1f3f6 1d5f3a7 6b1f3f6 1d5f3a7 6b1f3f6 1d5f3a7 6b1f3f6 1d5f3a7 6b1f3f6 1d5f3a7 6b1f3f6 1d5f3a7 6b1f3f6 1d5f3a7 6b1f3f6 1d5f3a7 6b1f3f6 | 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 | import gradio as gr
import torch
import torch.nn as nn
import librosa
import numpy as np
import whisper
import pandas as pd
from datasets import load_dataset
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.utils import resample
device = torch.device("cpu")
# ================= LOAD DATASET =================
data1 = pd.read_csv("spam_dataset.csv")
data2 = load_dataset("ucirvine/sms_spam")
data2 = data2["train"].to_pandas()
data2 = data2.rename(columns={"sms": "text", "label": "label"})
data = pd.concat([data1, data2], ignore_index=True)
# ================= FIX LABELS =================
# Ensure labels are 0 (ham) and 1 (spam)
data["label"] = data["label"].astype(int)
# ================= BALANCE DATASET =================
ham = data[data.label == 0]
spam = data[data.label == 1]
min_size = min(len(ham), len(spam))
ham_bal = resample(ham, replace=False, n_samples=min_size, random_state=42)
spam_bal = resample(spam, replace=False, n_samples=min_size, random_state=42)
data = pd.concat([ham_bal, spam_bal])
texts = data["text"]
labels = data["label"]
# ================= ML TRAINING =================
vectorizer = TfidfVectorizer(stop_words="english")
X = vectorizer.fit_transform(texts)
ml_model = LogisticRegression(max_iter=200)
ml_model.fit(X, labels)
# ================= CNN MODEL =================
class ScamAudioCNN(nn.Module):
def __init__(self):
super(ScamAudioCNN, self).__init__()
self.conv1 = nn.Conv2d(1, 16, 3, padding=1)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(16, 32, 3, padding=1)
self.fc1 = nn.Linear(32 * 10 * 25, 128)
self.fc2 = nn.Linear(128, 2)
def forward(self, x):
x = self.pool(torch.relu(self.conv1(x)))
x = self.pool(torch.relu(self.conv2(x)))
x = x.view(x.size(0), -1)
x = torch.relu(self.fc1(x))
x = self.fc2(x)
return x
cnn_model = ScamAudioCNN().to(device)
# ================= LOAD CNN =================
try:
cnn_model.load_state_dict(torch.load("scam_audio_model.pth", map_location=device))
cnn_model.eval()
cnn_loaded = True
except:
cnn_loaded = False
print("⚠️ CNN model not found, skipping CNN contribution")
# ================= WHISPER =================
whisper_model = whisper.load_model("tiny", device="cpu")
# ================= MFCC =================
def extract_features(file_path, max_len=100):
y, sr = librosa.load(file_path, sr=16000)
mfcc = librosa.feature.mfcc(y=y, sr=sr, n_mfcc=40)
if mfcc.shape[1] < max_len:
mfcc = np.pad(mfcc, ((0,0),(0,max_len-mfcc.shape[1])))
else:
mfcc = mfcc[:, :max_len]
mfcc = mfcc[np.newaxis, np.newaxis, :, :]
return torch.tensor(mfcc, dtype=torch.float32)
# ================= TRANSCRIPTION =================
def transcribe_audio(file_path):
result = whisper_model.transcribe(file_path)
return result["text"].lower()
# ================= KEYWORDS =================
scam_keywords = [
"otp","bank","account","verify","urgent","blocked","suspend",
"credit card","loan","refund","investment","crypto","kyc",
"password","security","congratulations","won","winner","prize",
"claim","fee","pay","offer","lottery","jackpot","gift","free"
]
def keyword_score(text):
found = [w for w in scam_keywords if w in text]
score = 0 if len(found) == 0 else min(len(found)/3, 1.0)
return score, found
# ================= ML PREDICTION =================
def ml_predict(text):
X_test = vectorizer.transform([text])
prob = ml_model.predict_proba(X_test)[0][1]
return prob
# ================= MAIN =================
def analyze_audio(audio):
if audio is None:
return "No audio detected."
try:
# TRANSCRIBE
transcript = transcribe_audio(audio)
# KEYWORD
k_score, words = keyword_score(transcript)
# ML
ml_score = ml_predict(transcript)
# CNN (optional)
cnn_score = 0
if cnn_loaded:
features = extract_features(audio).to(device)
with torch.no_grad():
out = cnn_model(features)
probs = torch.softmax(out, dim=1)
cnn_score = probs[0][1].item()
# DEBUG PRINTS
print("Transcript:", transcript)
print("Keyword Score:", k_score)
print("ML Score:", ml_score)
print("CNN Score:", cnn_score)
# FINAL SCORE (balanced weights)
final_score = (0.2 * k_score) + (0.5 * ml_score) + (0.3 * cnn_score)
# THRESHOLD FIXED
if final_score < 0.40:
risk = "Low Risk"
result = "NOT SPAM"
elif final_score < 0.65:
risk = "Medium Risk"
result = "SPAM"
else:
risk = "High Scam Risk"
result = "SPAM"
return f"""
Transcript: {transcript}
Spam Words Found: {', '.join(words) if words else 'None'}
Scores:
Keyword: {k_score:.2f}
ML: {ml_score:.2f}
CNN: {cnn_score:.2f}
Final Probability: {final_score*100:.2f}%
Risk Level: {risk}
Final Result: {result}
"""
except Exception as e:
return f"Error: {str(e)}"
# ================= UI =================
with gr.Blocks() as demo:
gr.Markdown("# 🎙️ Hybrid Voice Scam Detection System")
gr.Markdown("Speech + AI + Keyword Detection")
audio_input = gr.Audio(sources=["microphone", "upload"], type="filepath")
output = gr.Textbox(lines=12)
gr.Button("Analyze").click(
analyze_audio,
inputs=audio_input,
outputs=output
)
demo.launch() |