agent_decoder / test_script.py
Aziz3's picture
Initial commit: English Accent Detection Tool with Streamlit and tests
b3cdca1
#!/usr/bin/env python3
"""
Test script for accent detection functionality
Run this to validate the core components work correctly
"""
import sys
import os
from pathlib import Path
# Add the current directory to Python path
sys.path.insert(0, str(Path(__file__).parent))
def test_accent_patterns():
"""Test the accent pattern analysis"""
print("πŸ§ͺ Testing accent pattern analysis...")
# Import the detector (assuming the main script is available)
try:
from streamlit_app import AccentDetector
detector = AccentDetector()
except ImportError:
print("❌ Could not import AccentDetector")
return False
# Test cases
test_cases = [
{
'text': "I'm gonna grab some cookies and head to the elevator",
'expected': 'American',
'description': 'American English patterns'
},
{
'text': "That's brilliant mate, quite lovely indeed, fancy a biscuit",
'expected': 'British',
'description': 'British English patterns'
},
{
'text': "G'day mate, fair dinkum ripper of a day for a barbie",
'expected': 'Australian',
'description': 'Australian English patterns'
},
{
'text': "Sorry eh, gonna grab a double double and toque from the parkade",
'expected': 'Canadian',
'description': 'Canadian English patterns'
}
]
results = []
for test in test_cases:
scores = detector.analyze_patterns(test['text'])
accent, confidence, explanation = detector.classify_accent(scores)
success = accent == test['expected']
results.append(success)
status = "βœ…" if success else "❌"
print(f"{status} {test['description']}")
print(f" Text: '{test['text']}'")
print(f" Expected: {test['expected']}, Got: {accent} ({confidence}%)")
print(f" Explanation: {explanation}")
print()
success_rate = sum(results) / len(results) * 100
print(f"πŸ“Š Pattern Analysis Success Rate: {success_rate:.1f}%")
return success_rate > 50
def test_dependencies():
"""Test that all required dependencies are available"""
print("πŸ” Testing dependencies...")
dependencies = [
('streamlit', 'Streamlit framework'),
('requests', 'HTTP requests'),
('speech_recognition', 'Speech recognition'),
('pydub', 'Audio processing'),
('numpy', 'Numerical computing')
]
missing = []
for dep, description in dependencies:
try:
__import__(dep)
print(f"βœ… {dep} - {description}")
except ImportError:
print(f"❌ {dep} - {description} (MISSING)")
missing.append(dep)
if missing:
print(f"\n⚠️ Missing dependencies: {', '.join(missing)}")
print("Install with: pip install " + " ".join(missing))
return False
return True
def test_audio_processing():
"""Test audio processing capabilities"""
print("🎡 Testing audio processing...")
try:
from pydub import AudioSegment
from pydub.generators import Sine
# Generate a test tone
tone = Sine(440).to_audio_segment(duration=1000) # 1 second
# Test basic operations
tone = tone.set_frame_rate(16000)
tone = tone.set_channels(1)
print("βœ… Audio processing functionality works")
return True
except Exception as e:
print(f"❌ Audio processing failed: {e}")
return False
def test_speech_recognition():
"""Test speech recognition setup"""
print("🎀 Testing speech recognition...")
try:
import speech_recognition as sr
r = sr.Recognizer()
print("βœ… Speech recognition initialized")
return True
except Exception as e:
print(f"❌ Speech recognition failed: {e}")
return False
def main():
"""Run all tests"""
print("πŸš€ Running Accent Detection Tests\n")
tests = [
("Dependencies", test_dependencies),
("Audio Processing", test_audio_processing),
("Speech Recognition", test_speech_recognition),
("Accent Patterns", test_accent_patterns)
]
results = []
for test_name, test_func in tests:
print(f"=" * 50)
print(f"Testing: {test_name}")
print("=" * 50)
try:
result = test_func()
results.append((test_name, result))
except Exception as e:
print(f"❌ {test_name} failed with error: {e}")
results.append((test_name, False))
print()
# Summary
print("=" * 50)
print("TEST SUMMARY")
print("=" * 50)
passed = 0
for test_name, result in results:
status = "βœ… PASS" if result else "❌ FAIL"
print(f"{status} - {test_name}")
if result:
passed += 1
print(f"\nπŸ“Š Overall: {passed}/{len(results)} tests passed")
if passed == len(results):
print("πŸŽ‰ All tests passed! The accent detector is ready to use.")
return True
else:
print("⚠️ Some tests failed. Check the issues above.")
return False
if __name__ == "__main__":
success = main()
sys.exit(0 if success else 1)