Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
270 lines (223 loc) Β· 8.96 KB
/
Copy pathmain.py
File metadata and controls
270 lines (223 loc) Β· 8.96 KB
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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
"""
Voice ID System - Main Application
A voice identification system using ChatGPT API for voice analysis and user verification.
"""
import sys
import argparse
from pathlib import Path
# Add src directory to path
sys.path.insert(0, str(Path(__file__).parent / "src"))
from src.voice_id_system import VoiceIDSystem
from src.config import Config
def print_banner():
"""Print application banner."""
print("="*60)
print("π‘οΈ VOICEGUARD")
print("Advanced Voice Authentication System Powered by AI")
print("="*60)
def print_menu():
"""Print main menu options."""
print("\nπ MENU OPTIONS:")
print("1. π Enroll new user")
print("2. π Identify user (with username hint)")
print("3. π― Identify unknown speaker")
print("4. π₯ List all users")
print("5. βΉοΈ Get user information")
print("6. π€ Test microphone")
print("7. π System statistics")
print("8. ποΈ Delete user")
print("9. β Exit")
def enroll_user(voice_system):
"""Handle user enrollment."""
print("\n=== USER ENROLLMENT ===")
username = input("Enter username: ").strip()
if not username:
print("β Username cannot be empty!")
return
full_name = input("Enter full name (optional): ").strip()
email = input("Enter email (optional): ").strip()
success = voice_system.enroll_user(username, full_name, email)
if success:
print(f"\nβ
User '{username}' enrolled successfully!")
else:
print(f"\nβ Failed to enroll user '{username}'")
def identify_user_with_hint(voice_system):
"""Handle user identification with username hint."""
print("\n=== USER VERIFICATION ===")
username = input("Enter username to verify: ").strip()
if not username:
print("β Username cannot be empty!")
return
result = voice_system.identify_user(username_hint=username)
print("\nπ IDENTIFICATION RESULTS:")
print(f"Success: {result['success']}")
print(f"Confidence: {result['confidence']:.2f}")
if result['success']:
print(f"β
User '{result['username']}' verified successfully!")
if result.get('transcript'):
print(f"Transcript: \"{result['transcript']}\"")
else:
print(f"β Verification failed: {result.get('error', 'Unknown error')}")
def identify_unknown_speaker(voice_system):
"""Handle identification of unknown speaker."""
print("\n=== SPEAKER IDENTIFICATION ===")
print("The system will attempt to identify who is speaking...")
result = voice_system.identify_user()
print("\nπ IDENTIFICATION RESULTS:")
print(f"Success: {result['success']}")
print(f"Confidence: {result['confidence']:.2f}")
if result['success']:
print(f"β
Speaker identified: {result['username']} ({result.get('full_name', '')})")
if result.get('transcript'):
print(f"Transcript: \"{result['transcript']}\"")
else:
print(f"β Could not identify speaker: {result.get('error', 'Unknown error')}")
def list_users(voice_system):
"""List all enrolled users."""
print("\n=== ENROLLED USERS ===")
users = voice_system.list_users()
if not users:
print("No users enrolled in the system.")
return
print(f"Found {len(users)} enrolled users:")
print()
for user in users:
print(f"π€ {user['username']}")
if user.get('full_name'):
print(f" Name: {user['full_name']}")
if user.get('email'):
print(f" Email: {user['email']}")
print(f" Enrolled: {user['created_at']}")
print(f" Profiles: {user['enrollment_count']}")
print()
def get_user_info(voice_system):
"""Get detailed information about a user."""
print("\n=== USER INFORMATION ===")
username = input("Enter username: ").strip()
if not username:
print("β Username cannot be empty!")
return
info = voice_system.get_user_info(username)
if not info:
print(f"β User '{username}' not found!")
return
user = info['user_info']
print(f"\nπ€ USER: {user['username']}")
if user.get('full_name'):
print(f"Name: {user['full_name']}")
if user.get('email'):
print(f"Email: {user['email']}")
print(f"User ID: {user['user_id']}")
print(f"Created: {user['created_at']}")
print(f"Last Updated: {user['last_updated']}")
print(f"Status: {'Active' if user['is_active'] else 'Inactive'}")
print(f"\nπ STATISTICS:")
print(f"Voice Profiles: {info['voice_profiles']}")
print(f"Successful Authentications: {info['recent_authentications']}")
print(f"Failed Attempts: {info['failed_attempts']}")
if info['last_authentication']:
print(f"Last Authentication: {info['last_authentication']}")
def test_microphone(voice_system):
"""Test microphone functionality."""
voice_system.test_microphone()
def show_system_stats(voice_system):
"""Show system statistics."""
print("\n=== SYSTEM STATISTICS ===")
stats = voice_system.get_system_stats()
print(f"π₯ Total Users: {stats['total_users']}")
print(f"π Total Authentications: {stats['total_authentications']}")
print(f"β
Successful Authentications: {stats['successful_authentications']}")
print(f"β Failed Authentications: {stats['failed_authentications']}")
print(f"π Success Rate: {stats['success_rate']:.1%}")
def delete_user(voice_system):
"""Delete a user from the system."""
print("\n=== DELETE USER ===")
print("β οΈ WARNING: This will deactivate the user and all their voice profiles!")
username = input("Enter username to delete: ").strip()
if not username:
print("β Username cannot be empty!")
return
confirm = input(f"Are you sure you want to delete user '{username}'? (yes/no): ").strip().lower()
if confirm not in ['yes', 'y']:
print("β Deletion cancelled.")
return
success = voice_system.delete_user(username, confirm=True)
if success:
print(f"β
User '{username}' deleted successfully!")
else:
print(f"β Failed to delete user '{username}'")
def main():
"""Main application entry point."""
parser = argparse.ArgumentParser(
description="VoiceGuard - Advanced Voice Authentication System Powered by AI"
)
parser.add_argument("--config-check", action="store_true",
help="Check configuration and exit")
args = parser.parse_args()
print_banner()
# Configuration check
if args.config_check:
print("\nπ§ CONFIGURATION CHECK:")
try:
Config.validate()
print("β
Configuration is valid!")
print(f"Database Path: {Config.DATABASE_PATH}")
print(f"Sample Rate: {Config.SAMPLE_RATE} Hz")
print(f"Channels: {Config.CHANNELS}")
print(f"Record Duration: {Config.RECORD_SECONDS} seconds")
print(f"Similarity Threshold: {Config.SIMILARITY_THRESHOLD}")
print(f"Min Confidence Score: {Config.MIN_CONFIDENCE_SCORE}")
except Exception as e:
print(f"β Configuration error: {e}")
return
# Check if API key is set
if not Config.OPENAI_API_KEY:
print("\nβ ERROR: OpenAI API key not configured!")
print("Please create a .env file based on .env.example and add your API key.")
return
# Initialize system
try:
voice_system = VoiceIDSystem()
except Exception as e:
print(f"\nβ Failed to initialize Voice ID System: {e}")
print("Please check your configuration and try again.")
return
# Main application loop
try:
while True:
print_menu()
choice = input("\nEnter your choice (1-9): ").strip()
if choice == '1':
enroll_user(voice_system)
elif choice == '2':
identify_user_with_hint(voice_system)
elif choice == '3':
identify_unknown_speaker(voice_system)
elif choice == '4':
list_users(voice_system)
elif choice == '5':
get_user_info(voice_system)
elif choice == '6':
test_microphone(voice_system)
elif choice == '7':
show_system_stats(voice_system)
elif choice == '8':
delete_user(voice_system)
elif choice == '9':
print("\nπ Goodbye!")
break
else:
print("β Invalid choice! Please select 1-9.")
input("\nPress Enter to continue...")
except KeyboardInterrupt:
print("\n\nπ Application interrupted by user. Goodbye!")
except Exception as e:
print(f"\nβ Unexpected error: {e}")
finally:
# Cleanup
try:
voice_system.cleanup()
except:
pass
if __name__ == "__main__":
main()