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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import torch
|
| 3 |
+
import torchaudio
|
| 4 |
+
import numpy as np
|
| 5 |
+
import json
|
| 6 |
+
import os
|
| 7 |
+
from datetime import datetime
|
| 8 |
+
import matplotlib.pyplot as plt
|
| 9 |
+
import seaborn as sns
|
| 10 |
+
from sklearn.preprocessing import LabelEncoder
|
| 11 |
+
import warnings
|
| 12 |
+
warnings.filterwarnings('ignore')
|
| 13 |
+
|
| 14 |
+
# Import your existing classes and functions
|
| 15 |
+
from torch import nn
|
| 16 |
+
import torchvision
|
| 17 |
+
|
| 18 |
+
class AudioPreprocessor:
|
| 19 |
+
"""Enhanced audio preprocessing for voice security."""
|
| 20 |
+
|
| 21 |
+
def __init__(self, sample_rate=16000, n_mels=128, n_fft=2048, hop_length=512):
|
| 22 |
+
self.sample_rate = sample_rate
|
| 23 |
+
self.n_mels = n_mels
|
| 24 |
+
self.n_fft = n_fft
|
| 25 |
+
self.hop_length = hop_length
|
| 26 |
+
self.mel_spectrogram = torchaudio.transforms.MelSpectrogram(
|
| 27 |
+
sample_rate=sample_rate,
|
| 28 |
+
n_mels=n_mels,
|
| 29 |
+
n_fft=n_fft,
|
| 30 |
+
hop_length=hop_length
|
| 31 |
+
)
|
| 32 |
+
self.amplitude_to_db = torchaudio.transforms.AmplitudeToDB()
|
| 33 |
+
|
| 34 |
+
def audio_to_melspectrogram(self, audio_path):
|
| 35 |
+
"""Convert audio file to mel-spectrogram."""
|
| 36 |
+
try:
|
| 37 |
+
# Load audio file
|
| 38 |
+
waveform, sr = torchaudio.load(audio_path)
|
| 39 |
+
|
| 40 |
+
# Resample if necessary
|
| 41 |
+
if sr != self.sample_rate:
|
| 42 |
+
resampler = torchaudio.transforms.Resample(sr, self.sample_rate)
|
| 43 |
+
waveform = resampler(waveform)
|
| 44 |
+
|
| 45 |
+
# Convert to mono if stereo
|
| 46 |
+
if waveform.shape[0] > 1:
|
| 47 |
+
waveform = torch.mean(waveform, dim=0, keepdim=True)
|
| 48 |
+
|
| 49 |
+
# Pad or truncate to fixed length (3 seconds)
|
| 50 |
+
target_length = self.sample_rate * 3
|
| 51 |
+
if waveform.shape[1] > target_length:
|
| 52 |
+
waveform = waveform[:, :target_length]
|
| 53 |
+
else:
|
| 54 |
+
padding = target_length - waveform.shape[1]
|
| 55 |
+
waveform = torch.nn.functional.pad(waveform, (0, padding))
|
| 56 |
+
|
| 57 |
+
# Convert to mel-spectrogram
|
| 58 |
+
mel_spec = self.mel_spectrogram(waveform)
|
| 59 |
+
mel_spec_db = self.amplitude_to_db(mel_spec)
|
| 60 |
+
|
| 61 |
+
# Normalize
|
| 62 |
+
mel_spec_db = (mel_spec_db - mel_spec_db.mean()) / (mel_spec_db.std() + 1e-8)
|
| 63 |
+
|
| 64 |
+
# Convert to 3-channel image (RGB) for pretrained models
|
| 65 |
+
mel_spec_rgb = mel_spec_db.repeat(3, 1, 1)
|
| 66 |
+
|
| 67 |
+
return mel_spec_rgb, waveform.numpy()
|
| 68 |
+
|
| 69 |
+
except Exception as e:
|
| 70 |
+
print(f"Error processing audio: {e}")
|
| 71 |
+
return None, None
|
| 72 |
+
|
| 73 |
+
# Model Classes (same as your original code)
|
| 74 |
+
class ResNet18Model(nn.Module):
|
| 75 |
+
def __init__(self, num_classes):
|
| 76 |
+
super(ResNet18Model, self).__init__()
|
| 77 |
+
self.backbone = torchvision.models.resnet18(pretrained=False)
|
| 78 |
+
self.backbone.fc = nn.Sequential(
|
| 79 |
+
nn.Dropout(0.5),
|
| 80 |
+
nn.Linear(self.backbone.fc.in_features, 256),
|
| 81 |
+
nn.ReLU(),
|
| 82 |
+
nn.Dropout(0.3),
|
| 83 |
+
nn.Linear(256, num_classes)
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
def forward(self, x):
|
| 87 |
+
return self.backbone(x)
|
| 88 |
+
|
| 89 |
+
class ResNet50Model(nn.Module):
|
| 90 |
+
def __init__(self, num_classes):
|
| 91 |
+
super(ResNet50Model, self).__init__()
|
| 92 |
+
self.backbone = torchvision.models.resnet50(pretrained=False)
|
| 93 |
+
num_ftrs = self.backbone.fc.in_features
|
| 94 |
+
self.backbone.fc = nn.Sequential(
|
| 95 |
+
nn.BatchNorm1d(num_ftrs),
|
| 96 |
+
nn.Dropout(0.4),
|
| 97 |
+
nn.Linear(num_ftrs, 512),
|
| 98 |
+
nn.ReLU(),
|
| 99 |
+
nn.BatchNorm1d(512),
|
| 100 |
+
nn.Dropout(0.3),
|
| 101 |
+
nn.Linear(512, num_classes)
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
def forward(self, x):
|
| 105 |
+
return self.backbone(x)
|
| 106 |
+
|
| 107 |
+
class EfficientNetB0Model(nn.Module):
|
| 108 |
+
def __init__(self, num_classes):
|
| 109 |
+
super(EfficientNetB0Model, self).__init__()
|
| 110 |
+
self.backbone = torchvision.models.efficientnet_b0(pretrained=False)
|
| 111 |
+
self.backbone.classifier = nn.Sequential(
|
| 112 |
+
nn.Dropout(p=0.3, inplace=True),
|
| 113 |
+
nn.Linear(in_features=1280, out_features=512),
|
| 114 |
+
nn.ReLU(),
|
| 115 |
+
nn.Dropout(0.4),
|
| 116 |
+
nn.Linear(512, num_classes)
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
def forward(self, x):
|
| 120 |
+
return self.backbone(x)
|
| 121 |
+
|
| 122 |
+
class MobileNetV2Model(nn.Module):
|
| 123 |
+
def __init__(self, num_classes):
|
| 124 |
+
super(MobileNetV2Model, self).__init__()
|
| 125 |
+
self.backbone = torchvision.models.mobilenet_v2(pretrained=False)
|
| 126 |
+
self.backbone.classifier = nn.Sequential(
|
| 127 |
+
nn.Dropout(0.2),
|
| 128 |
+
nn.Linear(self.backbone.last_channel, 512),
|
| 129 |
+
nn.ReLU(),
|
| 130 |
+
nn.Dropout(0.3),
|
| 131 |
+
nn.Linear(512, num_classes)
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
def forward(self, x):
|
| 135 |
+
return self.backbone(x)
|
| 136 |
+
|
| 137 |
+
class VoiceSecuritySystem:
|
| 138 |
+
def __init__(self):
|
| 139 |
+
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 140 |
+
self.preprocessor = AudioPreprocessor()
|
| 141 |
+
self.models = {}
|
| 142 |
+
self.label_encoder = LabelEncoder()
|
| 143 |
+
self.model_info = {
|
| 144 |
+
"resnet18": {"name": "ResNet-18", "description": "Fast and efficient for real-time applications"},
|
| 145 |
+
"resnet50": {"name": "ResNet-50", "description": "Balanced performance and accuracy"},
|
| 146 |
+
"efficientnet_b0": {"name": "EfficientNet-B0", "description": "Optimized for mobile deployment"},
|
| 147 |
+
"mobilenet_v2": {"name": "MobileNet-V2", "description": "Lightweight with good accuracy"}
|
| 148 |
+
}
|
| 149 |
+
self.load_models()
|
| 150 |
+
|
| 151 |
+
def load_models(self):
|
| 152 |
+
"""Load all pre-trained models"""
|
| 153 |
+
# This would load your actual trained models
|
| 154 |
+
# For demo purposes, we'll create placeholder models
|
| 155 |
+
num_classes = 10 # Adjust based on your actual number of users
|
| 156 |
+
|
| 157 |
+
# Initialize label encoder with dummy classes
|
| 158 |
+
dummy_classes = [f"user_{i+1}" for i in range(num_classes)]
|
| 159 |
+
self.label_encoder.fit(dummy_classes)
|
| 160 |
+
|
| 161 |
+
model_classes = {
|
| 162 |
+
"resnet18": ResNet18Model,
|
| 163 |
+
"resnet50": ResNet50Model,
|
| 164 |
+
"efficientnet_b0": EfficientNetB0Model,
|
| 165 |
+
"mobilenet_v2": MobileNetV2Model
|
| 166 |
+
}
|
| 167 |
+
|
| 168 |
+
for model_name, model_class in model_classes.items():
|
| 169 |
+
try:
|
| 170 |
+
model = model_class(num_classes).to(self.device)
|
| 171 |
+
# In actual deployment, you would load the trained weights:
|
| 172 |
+
# model.load_state_dict(torch.load(f"models/{model_name}.pth", map_location=self.device))
|
| 173 |
+
model.eval()
|
| 174 |
+
self.models[model_name] = model
|
| 175 |
+
print(f"Loaded {model_name} successfully")
|
| 176 |
+
except Exception as e:
|
| 177 |
+
print(f"Error loading {model_name}: {e}")
|
| 178 |
+
|
| 179 |
+
def predict_voice(self, audio_file, model_name, confidence_threshold):
|
| 180 |
+
"""Predict voice access using selected model"""
|
| 181 |
+
if audio_file is None:
|
| 182 |
+
return "β Error", "No audio file provided", 0.0, self.create_empty_plot(), "Please upload an audio file"
|
| 183 |
+
|
| 184 |
+
try:
|
| 185 |
+
# Process audio
|
| 186 |
+
features, waveform = self.preprocessor.audio_to_melspectrogram(audio_file)
|
| 187 |
+
if features is None:
|
| 188 |
+
return "β Error", "Failed to process audio", 0.0, self.create_empty_plot(), "Audio processing failed"
|
| 189 |
+
|
| 190 |
+
# Get selected model
|
| 191 |
+
model = self.models.get(model_name)
|
| 192 |
+
if model is None:
|
| 193 |
+
return "β Error", "Model not found", 0.0, self.create_empty_plot(), "Selected model is not available"
|
| 194 |
+
|
| 195 |
+
# Make prediction
|
| 196 |
+
features = features.unsqueeze(0).to(self.device)
|
| 197 |
+
|
| 198 |
+
with torch.no_grad():
|
| 199 |
+
output = model(features)
|
| 200 |
+
probabilities = torch.softmax(output, dim=1)
|
| 201 |
+
confidence, predicted = torch.max(probabilities, 1)
|
| 202 |
+
|
| 203 |
+
predicted_class = self.label_encoder.inverse_transform([predicted.item()])[0]
|
| 204 |
+
confidence_score = confidence.item()
|
| 205 |
+
|
| 206 |
+
# Create visualization
|
| 207 |
+
viz_plot = self.create_prediction_visualization(probabilities.cpu().numpy()[0],
|
| 208 |
+
predicted_class, confidence_score)
|
| 209 |
+
|
| 210 |
+
# Determine access decision
|
| 211 |
+
if confidence_score >= confidence_threshold:
|
| 212 |
+
status = "π’ ACCESS GRANTED"
|
| 213 |
+
message = f"Welcome, {predicted_class}!"
|
| 214 |
+
security_status = f"β
AUTHORIZED USER DETECTED"
|
| 215 |
+
else:
|
| 216 |
+
status = "π΄ ACCESS DENIED"
|
| 217 |
+
message = f"Access denied - Low confidence"
|
| 218 |
+
security_status = f"β οΈ UNAUTHORIZED ACCESS ATTEMPT"
|
| 219 |
+
|
| 220 |
+
detailed_info = f"""
|
| 221 |
+
**Model Used:** {self.model_info[model_name]['name']}
|
| 222 |
+
**Predicted User:** {predicted_class}
|
| 223 |
+
**Confidence Score:** {confidence_score:.3f}
|
| 224 |
+
**Threshold:** {confidence_threshold}
|
| 225 |
+
**Decision:** {'GRANT' if confidence_score >= confidence_threshold else 'DENY'}
|
| 226 |
+
"""
|
| 227 |
+
|
| 228 |
+
return status, message, confidence_score, viz_plot, detailed_info
|
| 229 |
+
|
| 230 |
+
except Exception as e:
|
| 231 |
+
return "β Error", f"Prediction failed: {str(e)}", 0.0, self.create_empty_plot(), "An error occurred during prediction"
|
| 232 |
+
|
| 233 |
+
def create_prediction_visualization(self, probabilities, predicted_class, confidence):
|
| 234 |
+
"""Create visualization of prediction results"""
|
| 235 |
+
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))
|
| 236 |
+
|
| 237 |
+
# Color scheme without blue
|
| 238 |
+
colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#F7DC6F', '#BB8FCE', '#85C1E9', '#F8C471', '#82E0AA', '#F1948A']
|
| 239 |
+
|
| 240 |
+
# Plot 1: Top 5 predictions
|
| 241 |
+
top_5_indices = np.argsort(probabilities)[-5:][::-1]
|
| 242 |
+
top_5_probs = probabilities[top_5_indices]
|
| 243 |
+
top_5_labels = [self.label_encoder.inverse_transform([i])[0] for i in top_5_indices]
|
| 244 |
+
|
| 245 |
+
bars = ax1.barh(range(len(top_5_labels)), top_5_probs, color=colors[:len(top_5_labels)])
|
| 246 |
+
ax1.set_yticks(range(len(top_5_labels)))
|
| 247 |
+
ax1.set_yticklabels(top_5_labels)
|
| 248 |
+
ax1.set_xlabel('Confidence Score')
|
| 249 |
+
ax1.set_title('Top 5 Predictions')
|
| 250 |
+
ax1.set_xlim(0, 1)
|
| 251 |
+
|
| 252 |
+
# Highlight the top prediction
|
| 253 |
+
bars[0].set_color('#FFD93D')
|
| 254 |
+
bars[0].set_edgecolor('#FF8C00')
|
| 255 |
+
bars[0].set_linewidth(2)
|
| 256 |
+
|
| 257 |
+
# Add value labels
|
| 258 |
+
for i, (bar, prob) in enumerate(zip(bars, top_5_probs)):
|
| 259 |
+
ax1.text(prob + 0.01, bar.get_y() + bar.get_height()/2,
|
| 260 |
+
f'{prob:.3f}', va='center', fontweight='bold')
|
| 261 |
+
|
| 262 |
+
# Plot 2: Confidence gauge
|
| 263 |
+
theta = np.linspace(0, np.pi, 100)
|
| 264 |
+
r = np.ones_like(theta)
|
| 265 |
+
|
| 266 |
+
ax2 = plt.subplot(122, projection='polar')
|
| 267 |
+
ax2.set_theta_zero_location('S')
|
| 268 |
+
ax2.set_theta_direction(1)
|
| 269 |
+
ax2.set_ylim(0, 1)
|
| 270 |
+
|
| 271 |
+
# Color segments based on confidence levels
|
| 272 |
+
if confidence < 0.3:
|
| 273 |
+
color = '#FF6B6B' # Red
|
| 274 |
+
status_text = 'LOW'
|
| 275 |
+
elif confidence < 0.7:
|
| 276 |
+
color = '#F7DC6F' # Yellow
|
| 277 |
+
status_text = 'MEDIUM'
|
| 278 |
+
else:
|
| 279 |
+
color = '#58D68D' # Green
|
| 280 |
+
status_text = 'HIGH'
|
| 281 |
+
|
| 282 |
+
# Draw gauge
|
| 283 |
+
ax2.fill_between(theta, 0, r, alpha=0.3, color='lightgray')
|
| 284 |
+
confidence_theta = theta[int(confidence * len(theta))]
|
| 285 |
+
ax2.plot([confidence_theta, confidence_theta], [0, 1], color=color, linewidth=8)
|
| 286 |
+
ax2.fill_between(theta[:int(confidence * len(theta))], 0, r[:int(confidence * len(theta))],
|
| 287 |
+
alpha=0.7, color=color)
|
| 288 |
+
|
| 289 |
+
ax2.set_title(f'Confidence: {confidence:.3f}\nLevel: {status_text}', pad=20)
|
| 290 |
+
ax2.set_ylim(0, 1)
|
| 291 |
+
ax2.set_yticklabels([])
|
| 292 |
+
ax2.set_xticklabels(['Low', '', '', 'Medium', '', '', 'High'])
|
| 293 |
+
|
| 294 |
+
plt.tight_layout()
|
| 295 |
+
return fig
|
| 296 |
+
|
| 297 |
+
def create_empty_plot(self):
|
| 298 |
+
"""Create empty plot for error cases"""
|
| 299 |
+
fig, ax = plt.subplots(figsize=(8, 6))
|
| 300 |
+
ax.text(0.5, 0.5, 'No Data Available', ha='center', va='center',
|
| 301 |
+
fontsize=20, color='gray')
|
| 302 |
+
ax.set_xlim(0, 1)
|
| 303 |
+
ax.set_ylim(0, 1)
|
| 304 |
+
ax.axis('off')
|
| 305 |
+
return fig
|
| 306 |
+
|
| 307 |
+
def get_model_comparison(self):
|
| 308 |
+
"""Return model comparison information"""
|
| 309 |
+
comparison_data = []
|
| 310 |
+
for model_key, info in self.model_info.items():
|
| 311 |
+
# In actual deployment, you would load real metrics
|
| 312 |
+
comparison_data.append([
|
| 313 |
+
info['name'],
|
| 314 |
+
info['description'],
|
| 315 |
+
f"{np.random.uniform(0.85, 0.95):.3f}", # Mock accuracy
|
| 316 |
+
f"{np.random.uniform(0.01, 0.05):.3f}", # Mock FAR
|
| 317 |
+
f"{np.random.uniform(0.02, 0.08):.3f}" # Mock FRR
|
| 318 |
+
])
|
| 319 |
+
return comparison_data
|
| 320 |
+
|
| 321 |
+
# Initialize the system
|
| 322 |
+
voice_system = VoiceSecuritySystem()
|
| 323 |
+
|
| 324 |
+
def process_voice(audio_file, model_name, confidence_threshold):
|
| 325 |
+
"""Main processing function for Gradio interface"""
|
| 326 |
+
return voice_system.predict_voice(audio_file, model_name, confidence_threshold)
|
| 327 |
+
|
| 328 |
+
def get_model_info(model_name):
|
| 329 |
+
"""Get information about selected model"""
|
| 330 |
+
if model_name in voice_system.model_info:
|
| 331 |
+
info = voice_system.model_info[model_name]
|
| 332 |
+
return f"**{info['name']}**\n\n{info['description']}"
|
| 333 |
+
return "Model information not available"
|
| 334 |
+
|
| 335 |
+
# Custom CSS for styling (no blue colors)
|
| 336 |
+
custom_css = """
|
| 337 |
+
.gradio-container {
|
| 338 |
+
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
|
| 339 |
+
}
|
| 340 |
+
|
| 341 |
+
.gr-button-primary {
|
| 342 |
+
background: linear-gradient(45deg, #FF6B6B, #FF8E53) !important;
|
| 343 |
+
border: none !important;
|
| 344 |
+
}
|
| 345 |
+
|
| 346 |
+
.gr-button-secondary {
|
| 347 |
+
background: linear-gradient(45deg, #4ECDC4, #44A08D) !important;
|
| 348 |
+
border: none !important;
|
| 349 |
+
}
|
| 350 |
+
|
| 351 |
+
.gr-panel {
|
| 352 |
+
background: rgba(255, 255, 255, 0.95) !important;
|
| 353 |
+
backdrop-filter: blur(10px) !important;
|
| 354 |
+
border-radius: 15px !important;
|
| 355 |
+
border: 1px solid rgba(255, 255, 255, 0.2) !important;
|
| 356 |
+
}
|
| 357 |
+
|
| 358 |
+
.gr-form {
|
| 359 |
+
background: transparent !important;
|
| 360 |
+
}
|
| 361 |
+
|
| 362 |
+
.gr-box {
|
| 363 |
+
border-radius: 10px !important;
|
| 364 |
+
border: 1px solid #E0E0E0 !important;
|
| 365 |
+
}
|
| 366 |
+
|
| 367 |
+
h1, h2, h3 {
|
| 368 |
+
color: #2C3E50 !important;
|
| 369 |
+
text-shadow: 1px 1px 2px rgba(0,0,0,0.1) !important;
|
| 370 |
+
}
|
| 371 |
+
|
| 372 |
+
.security-status {
|
| 373 |
+
padding: 10px;
|
| 374 |
+
border-radius: 8px;
|
| 375 |
+
margin: 10px 0;
|
| 376 |
+
font-weight: bold;
|
| 377 |
+
}
|
| 378 |
+
|
| 379 |
+
.access-granted {
|
| 380 |
+
background-color: #D5F4E6;
|
| 381 |
+
color: #27AE60;
|
| 382 |
+
border-left: 4px solid #27AE60;
|
| 383 |
+
}
|
| 384 |
+
|
| 385 |
+
.access-denied {
|
| 386 |
+
background-color: #FADBD8;
|
| 387 |
+
color: #E74C3C;
|
| 388 |
+
border-left: 4px solid #E74C3C;
|
| 389 |
+
}
|
| 390 |
+
"""
|
| 391 |
+
|
| 392 |
+
# Create Gradio interface
|
| 393 |
+
with gr.Blocks(css=custom_css, title="π Voice Recognition Security System") as app:
|
| 394 |
+
gr.HTML("""
|
| 395 |
+
<div style="text-align: center; padding: 20px; background: linear-gradient(45deg, #667eea, #764ba2); color: white; border-radius: 15px; margin-bottom: 20px;">
|
| 396 |
+
<h1 style="margin: 0; font-size: 2.5em; text-shadow: 2px 2px 4px rgba(0,0,0,0.3);">π Voice Recognition Security System</h1>
|
| 397 |
+
<p style="margin: 10px 0 0 0; font-size: 1.2em; opacity: 0.9;">Advanced AI-powered voice authentication with multiple deep learning models</p>
|
| 398 |
+
</div>
|
| 399 |
+
""")
|
| 400 |
+
|
| 401 |
+
with gr.Row():
|
| 402 |
+
with gr.Column(scale=1):
|
| 403 |
+
gr.HTML("<h2>π― Authentication Panel</h2>")
|
| 404 |
+
|
| 405 |
+
# Audio input
|
| 406 |
+
audio_input = gr.Audio(
|
| 407 |
+
label="π€ Upload Voice Sample",
|
| 408 |
+
type="filepath",
|
| 409 |
+
elem_id="audio_input"
|
| 410 |
+
)
|
| 411 |
+
|
| 412 |
+
# Model selection
|
| 413 |
+
model_selector = gr.Dropdown(
|
| 414 |
+
choices=[
|
| 415 |
+
("ResNet-18 (Fast & Efficient)", "resnet18"),
|
| 416 |
+
("ResNet-50 (Balanced Performance)", "resnet50"),
|
| 417 |
+
("EfficientNet-B0 (Mobile Optimized)", "efficientnet_b0"),
|
| 418 |
+
("MobileNet-V2 (Lightweight)", "mobilenet_v2")
|
| 419 |
+
],
|
| 420 |
+
value="resnet18",
|
| 421 |
+
label="π€ Select AI Model",
|
| 422 |
+
info="Choose the deep learning model for voice recognition"
|
| 423 |
+
)
|
| 424 |
+
|
| 425 |
+
# Confidence threshold
|
| 426 |
+
confidence_slider = gr.Slider(
|
| 427 |
+
minimum=0.1,
|
| 428 |
+
maximum=1.0,
|
| 429 |
+
value=0.7,
|
| 430 |
+
step=0.05,
|
| 431 |
+
label="ποΈ Security Threshold",
|
| 432 |
+
info="Higher values = More secure but stricter"
|
| 433 |
+
)
|
| 434 |
+
|
| 435 |
+
# Process button
|
| 436 |
+
process_btn = gr.Button(
|
| 437 |
+
"π Authenticate Voice",
|
| 438 |
+
variant="primary",
|
| 439 |
+
size="lg"
|
| 440 |
+
)
|
| 441 |
+
|
| 442 |
+
# Model info display
|
| 443 |
+
model_info_display = gr.Markdown(
|
| 444 |
+
get_model_info("resnet18"),
|
| 445 |
+
label="π Model Information"
|
| 446 |
+
)
|
| 447 |
+
|
| 448 |
+
with gr.Column(scale=2):
|
| 449 |
+
gr.HTML("<h2>π Authentication Results</h2>")
|
| 450 |
+
|
| 451 |
+
with gr.Row():
|
| 452 |
+
with gr.Column():
|
| 453 |
+
# Status display
|
| 454 |
+
status_output = gr.Textbox(
|
| 455 |
+
label="π¦ Access Status",
|
| 456 |
+
interactive=False,
|
| 457 |
+
elem_id="status_output"
|
| 458 |
+
)
|
| 459 |
+
|
| 460 |
+
# Message display
|
| 461 |
+
message_output = gr.Textbox(
|
| 462 |
+
label="π¬ System Message",
|
| 463 |
+
interactive=False
|
| 464 |
+
)
|
| 465 |
+
|
| 466 |
+
# Confidence display
|
| 467 |
+
confidence_output = gr.Number(
|
| 468 |
+
label="π Confidence Score",
|
| 469 |
+
interactive=False,
|
| 470 |
+
precision=3
|
| 471 |
+
)
|
| 472 |
+
|
| 473 |
+
with gr.Column():
|
| 474 |
+
# Detailed information
|
| 475 |
+
detailed_info = gr.Markdown(
|
| 476 |
+
label="π Detailed Analysis"
|
| 477 |
+
)
|
| 478 |
+
|
| 479 |
+
# Visualization plot
|
| 480 |
+
plot_output = gr.Plot(
|
| 481 |
+
label="π Prediction Visualization",
|
| 482 |
+
elem_id="plot_output"
|
| 483 |
+
)
|
| 484 |
+
|
| 485 |
+
# Model comparison section
|
| 486 |
+
with gr.Row():
|
| 487 |
+
gr.HTML("<h2>βοΈ Model Comparison</h2>")
|
| 488 |
+
|
| 489 |
+
with gr.Row():
|
| 490 |
+
comparison_table = gr.Dataframe(
|
| 491 |
+
headers=["Model", "Description", "Accuracy", "FAR (False Accept)", "FRR (False Reject)"],
|
| 492 |
+
value=voice_system.get_model_comparison(),
|
| 493 |
+
label="π Performance Metrics",
|
| 494 |
+
interactive=False
|
| 495 |
+
)
|
| 496 |
+
|
| 497 |
+
# Information section
|
| 498 |
+
with gr.Row():
|
| 499 |
+
with gr.Column():
|
| 500 |
+
gr.HTML("""
|
| 501 |
+
<div style="background: linear-gradient(45deg, #FFF3E0, #FFE0B2); padding: 20px; border-radius: 10px; border-left: 4px solid #FF9800;">
|
| 502 |
+
<h3>π‘οΈ Security Features</h3>
|
| 503 |
+
<ul>
|
| 504 |
+
<li><strong>Multi-Model Architecture:</strong> Choose from 4 state-of-the-art models</li>
|
| 505 |
+
<li><strong>Confidence-Based Authentication:</strong> Adjustable security thresholds</li>
|
| 506 |
+
<li><strong>Real-Time Processing:</strong> Fast voice recognition and analysis</li>
|
| 507 |
+
<li><strong>Detailed Analytics:</strong> Comprehensive prediction visualization</li>
|
| 508 |
+
</ul>
|
| 509 |
+
</div>
|
| 510 |
+
""")
|
| 511 |
+
|
| 512 |
+
with gr.Column():
|
| 513 |
+
gr.HTML("""
|
| 514 |
+
<div style="background: linear-gradient(45deg, #E8F5E8, #C8E6C9); padding: 20px; border-radius: 10px; border-left: 4px solid #4CAF50;">
|
| 515 |
+
<h3>π How to Use</h3>
|
| 516 |
+
<ol>
|
| 517 |
+
<li><strong>Upload Audio:</strong> Record or upload a voice sample (3 seconds recommended)</li>
|
| 518 |
+
<li><strong>Select Model:</strong> Choose the AI model based on your needs</li>
|
| 519 |
+
<li><strong>Set Threshold:</strong> Adjust security level (0.7 recommended for balanced security)</li>
|
| 520 |
+
<li><strong>Authenticate:</strong> Click the button to process your voice</li>
|
| 521 |
+
<li><strong>Review Results:</strong> Check the detailed analysis and visualization</li>
|
| 522 |
+
</ol>
|
| 523 |
+
</div>
|
| 524 |
+
""")
|
| 525 |
+
|
| 526 |
+
# Event handlers
|
| 527 |
+
model_selector.change(
|
| 528 |
+
fn=get_model_info,
|
| 529 |
+
inputs=[model_selector],
|
| 530 |
+
outputs=[model_info_display]
|
| 531 |
+
)
|
| 532 |
+
|
| 533 |
+
process_btn.click(
|
| 534 |
+
fn=process_voice,
|
| 535 |
+
inputs=[audio_input, model_selector, confidence_slider],
|
| 536 |
+
outputs=[status_output, message_output, confidence_output, plot_output, detailed_info]
|
| 537 |
+
)
|
| 538 |
+
|
| 539 |
+
# Footer
|
| 540 |
+
gr.HTML("""
|
| 541 |
+
<div style="text-align: center; padding: 20px; margin-top: 30px; background: linear-gradient(45deg, #37474F, #455A64); color: white; border-radius: 10px;">
|
| 542 |
+
<p style="margin: 0; opacity: 0.8;">π Advanced Voice Recognition Security System | Powered by Deep Learning & Transfer Learning</p>
|
| 543 |
+
<p style="margin: 5px 0 0 0; font-size: 0.9em; opacity: 0.6;">Supported formats: WAV, MP3, FLAC, M4A, OGG | Optimized for 16kHz sample rate</p>
|
| 544 |
+
</div>
|
| 545 |
+
""")
|
| 546 |
+
|
| 547 |
+
# Launch configuration
|
| 548 |
+
if __name__ == "__main__":
|
| 549 |
+
app.launch(
|
| 550 |
+
share=True,
|
| 551 |
+
server_name="0.0.0.0",
|
| 552 |
+
server_port=7860,
|
| 553 |
+
show_error=True,
|
| 554 |
+
show_tips=True,
|
| 555 |
+
enable_queue=True,
|
| 556 |
+
max_threads=10
|
| 557 |
+
)
|