|
|
1 năm trước cách đây | |
|---|---|---|
| .. | ||
| IMPLEMENTATION_SUMMARY.md | 1 năm trước cách đây | |
| README.md | 1 năm trước cách đây | |
| __init__.py | 1 năm trước cách đây | |
| audio_features.py | 1 năm trước cách đây | |
| config.py | 1 năm trước cách đây | |
| detector.py | 1 năm trước cách đây | |
| examples.py | 1 năm trước cách đây | |
| integration.py | 1 năm trước cách đây | |
| model_architectures.py | 1 năm trước cách đây | |
| model_loader.py | 1 năm trước cách đây | |
| optimization.py | 1 năm trước cách đây | |
| recognition_engine.py | 1 năm trước cách đây | |
| speaker_embeddings.py | 1 năm trước cách đây | |
| speaker_manager.py | 1 năm trước cách đây | |
| vad.py | 1 năm trước cách đây | |
| validate_system.py | 1 năm trước cách đây | |
A comprehensive voice recognition system for the Trixy voice assistant client, providing real-time speaker identification and verification capabilities with production-ready performance optimization.
┌─────────────────────────────────────────────────────────────┐
│ Voice Recognition System │
├─────────────────────────────────────────────────────────────┤
│ VoiceRecognitionDetector (Main Interface) │
│ ├── Audio Features (Log-Mel/MFCC) │
│ ├── VAD (WebRTC/Energy-based) │
│ ├── Model Architectures (ECAPA-TDNN/TitaNet-S/SpeakerNet) │
│ ├── Speaker Embeddings & Comparison │
│ ├── Speaker Manager (Dynamic Add/Remove) │
│ ├── Recognition Engine (Confidence Scoring) │
│ └── Performance Optimization │
├─────────────────────────────────────────────────────────────┤
│ Integration Layer │
│ ├── Event System Integration │
│ ├── Wakeword Enhancement │
│ └── Continuous Recognition │
└─────────────────────────────────────────────────────────────┘
# Core dependencies
pip install torch torchaudio numpy scipy scikit-learn
# Audio processing
pip install webrtcvad librosa
# Security (for encrypted models)
pip install cryptography
# Performance monitoring
pip install psutil
# Optional: for visualization
pip install matplotlib seaborn
from trixy_core.ml.voice_recognition import setup_complete_voice_recognition_system
# Create complete system
integration = setup_complete_voice_recognition_system(
model_path="/path/to/trained_model.pth",
model_password="your_secret_password",
event_handler=event_handler # Optional
)
# Start the system
integration.start()
from trixy_core.ml.voice_recognition import (
create_default_config,
VoiceRecognitionDetector
)
import numpy as np
# Create configuration
config = create_default_config(
model_path="/path/to/model.pth",
model_password="secret123"
)
# Initialize detector
detector = VoiceRecognitionDetector(config)
detector.start()
# Process audio (16kHz, 16-bit PCM)
audio_data = np.random.randn(48000).astype(np.float32) # 3 seconds
result = detector.identify_speaker(audio_data)
print(f"Speaker: {result.speaker_name}")
print(f"Confidence: {result.confidence:.3f}")
print(f"Processing time: {result.processing_time_ms:.1f}ms")
# Verify specific speaker
verification_result = detector.verify_speaker(audio_data, "expected_speaker_id")
print(f"Verification: {verification_result.verification_success}")
print(f"Expected: {verification_result.expected_speaker_id}")
print(f"Actual: {verification_result.speaker_id}")
print(f"Confidence: {verification_result.confidence:.3f}")
# Add new speaker with multiple audio samples
audio_samples = [
np.random.randn(48000).astype(np.float32) for _ in range(5)
]
success = detector.add_speaker("New Speaker", audio_samples)
print(f"Enrollment success: {success}")
# List all speakers
speakers = detector.get_speaker_list()
for speaker in speakers:
print(f"{speaker.speaker_name}: {speaker.embedding_count} embeddings")
# Remove speaker
removed = detector.remove_speaker("speaker_id_to_remove")
print(f"Removal success: {removed}")
from trixy_core.ml.voice_recognition import create_voice_recognition_integration
from trixy_core.events import create_default_event_handler
# Create event handler
event_handler = create_default_event_handler()
# Create integration
integration = create_voice_recognition_integration(
voice_detector=detector,
event_handler=event_handler,
enable_wakeword_enhancement=True
)
# Start integration
integration.start()
# Process wakeword detection with enhancement
enhanced_info = integration.process_wakeword_detection(
audio_data=wakeword_audio,
wakeword_id="hey_trixy"
)
print(f"Enhanced speaker info: {enhanced_info}")
from trixy_core.ml.voice_recognition import create_vr_performance_monitor
# Create performance monitor
monitor = create_vr_performance_monitor(
window_size=100,
enable_profiling=True
)
# Start monitoring
monitor.start_monitoring()
# Record inference performance
monitor.record_inference(
inference_time_ms=25.3,
confidence=0.85,
success=True
)
# Get performance metrics
metrics = monitor.get_metrics()
print(f"Average inference time: {metrics.avg_inference_time_ms:.1f}ms")
print(f"Frames per second: {metrics.frames_per_second:.1f}")
print(f"Memory usage: {metrics.memory_usage_mb:.1f}MB")
# Enable continuous recognition mode
integration = create_voice_recognition_integration(
voice_detector=detector,
event_handler=event_handler,
enable_continuous_recognition=True
)
integration.start()
# Process streaming audio
def audio_callback(audio_chunk):
result = integration.process_audio_stream(audio_chunk)
if result and result.speaker_id:
print(f"Continuous recognition: {result.speaker_name}")
# The integration will continuously process audio and trigger callbacks
from trixy_core.ml.voice_recognition import AudioConfig, FeatureType, VADType
audio_config = AudioConfig(
sample_rate=16000,
audio_length=3.0,
feature_type=FeatureType.LOG_MEL,
n_mels=40,
n_fft=1024,
hop_length=160,
win_length=400,
use_vad=True,
vad_type=VADType.WEBRTC,
vad_aggressiveness=2
)
from trixy_core.ml.voice_recognition import ModelConfig, ModelArchitectureType
model_config = ModelConfig(
model_path="/path/to/model.pth",
model_password="secret123",
architecture_type=ModelArchitectureType.ECAPA_TDNN,
embedding_dim=192,
num_speakers=10,
device="auto" # auto-detect best device
)
from trixy_core.ml.voice_recognition import RecognitionConfig, SimilarityMetric
recognition_config = RecognitionConfig(
identification_threshold=0.7,
verification_threshold=0.8,
similarity_metric=SimilarityMetric.COSINE,
use_temporal_smoothing=True,
smoothing_window_size=5,
confidence_decay_factor=0.9
)
from trixy_core.ml.voice_recognition import PerformanceConfig
performance_config = PerformanceConfig(
device="cuda", # or "cpu", "mps", "auto"
use_half_precision=True,
use_torch_compile=True,
batch_size=1,
num_threads=4,
target_latency_ms=100
)
The system is designed to work with models trained using the ML framework. Model files should include:
model.pth (ZIP archive)
├── model.pth (PyTorch state dict)
├── metadata.json (Model metadata)
└── README.txt (Documentation)
from trixy_core.ml.voice_recognition import (
SecureVRModelLoader,
validate_vr_model_file
)
# Validate model file
validation = validate_vr_model_file(
model_path="/path/to/model.pth",
password="secret123"
)
if validation['is_valid']:
print("Model is valid")
print(f"Speakers: {len(validation['metadata']['speaker_mapping'])}")
else:
print(f"Model validation failed: {validation['errors']}")
# Load model securely
loader = SecureVRModelLoader("cuda")
model, metadata = loader.load_model(
model_path="/path/to/model.pth",
password="secret123"
)
from trixy_core.ml.voice_recognition import optimize_vr_for_deployment
# Optimize model for deployment
optimization_results = optimize_vr_for_deployment(
model=model,
target_device="cuda",
target_latency_ms=50,
enable_quantization=True
)
print(f"Model size reduced by {optimization_results['model_size_reduction']:.1f}%")
optimized_model = optimization_results['optimized_model']
from trixy_core.ml.voice_recognition import VRMemoryManager
# Create memory manager
memory_manager = VRMemoryManager(max_memory_mb=512)
# Check memory usage
if not memory_manager.check_memory_usage():
memory_manager.force_cleanup()
from trixy_core.ml.voice_recognition import VRLatencyOptimizer
# Create latency optimizer
latency_optimizer = VRLatencyOptimizer(target_latency_ms=100)
# Record latencies
latency_optimizer.record_latency(85.3) # ms
# Get optimization suggestions
suggestions = latency_optimizer.get_optimization_suggestions()
for suggestion in suggestions:
print(f"Suggestion: {suggestion}")
from trixy_core.ml.voice_recognition import VoiceRecognitionTester
# Create tester
tester = VoiceRecognitionTester(config)
# Setup test speakers
speakers = {
'alice': {'f0': 180, 'formants': [900, 1300, 2800]},
'bob': {'f0': 120, 'formants': [700, 1100, 2300]}
}
tester.setup_test_speakers(speakers)
# Run identification test
results = tester.run_identification_test(
test_speakers=['alice', 'bob'],
samples_per_speaker=10
)
print(f"Accuracy: {results['accuracy']:.2%}")
print(f"Average confidence: {results['avg_confidence']:.3f}")
# Run performance stress test
perf_results = tester.run_performance_test(
duration_minutes=5.0,
target_fps=33.3
)
print(f"Achieved FPS: {perf_results['achieved_fps']:.1f}")
print(f"Average processing time: {perf_results['avg_processing_time_ms']:.1f}ms")
# Test complete integration
from trixy_core.ml.voice_recognition import run_all_vr_examples
# Run all example scenarios
results = run_all_vr_examples()
print("All tests completed successfully!")
The system generates the following events:
voice_recognition_started - System initializationvoice_recognition_stopped - System shutdownspeaker_identified - Speaker identification completedspeaker_verified - Speaker verification completedspeaker_enrolled - New speaker addedspeaker_removed - Speaker removedwakeword_enhanced - Wakeword detection enhanced with speaker info# Speaker identification event
{
'event_type': 'speaker_identified',
'speaker_id': 'spk_001',
'speaker_name': 'Alice',
'confidence': 0.89,
'similarity_score': 0.89,
'processing_time_ms': 23.5,
'audio_quality': 0.92,
'vad_confidence': 0.95,
'timestamp': '2024-01-15T10:30:45.123Z'
}
from trixy_core.events import TrixyEvent
class VoiceRecognitionHandler:
@TrixyEvent(["speaker_identified", "speaker_enrolled"])
def handle_voice_events(self, event_name, event_data):
if event_name == "speaker_identified":
print(f"Speaker identified: {event_data.speaker_name}")
elif event_name == "speaker_enrolled":
print(f"New speaker enrolled: {event_data.speaker_name}")
# Register handler
handler = VoiceRecognitionHandler()
event_handler.register_handler_object(handler)
Model Loading Fails
Poor Recognition Accuracy
High Latency
Memory Issues
# Enable debug mode for detailed logging
config.debug_mode = True
detector = VoiceRecognitionDetector(config)
# Save debug information
detector.save_debug_info("/tmp/vr_debug.json")
For detailed API documentation, see the individual module docstrings:
VoiceRecognitionDetector - Main detection interfaceVoiceRecognitionConfig - Configuration managementSpeakerManager - Dynamic speaker managementVRPerformanceMonitor - Performance monitoringVoiceRecognitionIntegration - Event system integrationThis voice recognition system is part of the Trixy voice assistant project.