Aziz3/agent_decoder
0
1#!/usr/bin/env python32"""3Test script for accent detection functionality4Run this to validate the core components work correctly5"""6 7import sys8import os9from pathlib import Path10 11# Add the current directory to Python path12sys.path.insert(0, str(Path(__file__).parent))13 14def test_accent_patterns():15 """Test the accent pattern analysis"""16 print("๐งช Testing accent pattern analysis...")17 18 # Import the detector (assuming the main script is available)19 try:20 from streamlit_app import AccentDetector21 detector = AccentDetector()22 except ImportError:23 print("โ Could not import AccentDetector")24 return False25 26 # Test cases27 test_cases = [28 {29 'text': "I'm gonna grab some cookies and head to the elevator",30 'expected': 'American',31 'description': 'American English patterns'32 },33 {34 'text': "That's brilliant mate, quite lovely indeed, fancy a biscuit",35 'expected': 'British', 36 'description': 'British English patterns'37 },38 {39 'text': "G'day mate, fair dinkum ripper of a day for a barbie",40 'expected': 'Australian',41 'description': 'Australian English patterns'42 },43 {44 'text': "Sorry eh, gonna grab a double double and toque from the parkade",45 'expected': 'Canadian',46 'description': 'Canadian English patterns'47 }48 ]49 50 results = []51 for test in test_cases:52 scores = detector.analyze_patterns(test['text'])53 accent, confidence, explanation = detector.classify_accent(scores)54 55 success = accent == test['expected']56 results.append(success)57 58 status = "โ
" if success else "โ"59 print(f"{status} {test['description']}")60 print(f" Text: '{test['text']}'")61 print(f" Expected: {test['expected']}, Got: {accent} ({confidence}%)")62 print(f" Explanation: {explanation}")63 print()64 65 success_rate = sum(results) / len(results) * 10066 print(f"๐ Pattern Analysis Success Rate: {success_rate:.1f}%")67 return success_rate > 5068 69def test_dependencies():70 """Test that all required dependencies are available"""71 print("๐ Testing dependencies...")72 73 dependencies = [74 ('streamlit', 'Streamlit framework'),75 ('requests', 'HTTP requests'),76 ('speech_recognition', 'Speech recognition'),77 ('pydub', 'Audio processing'),78 ('numpy', 'Numerical computing')79 ]80 81 missing = []82 for dep, description in dependencies:83 try:84 __import__(dep)85 print(f"โ
{dep} - {description}")86 except ImportError:87 print(f"โ {dep} - {description} (MISSING)")88 missing.append(dep)89 90 if missing:91 print(f"\nโ ๏ธ Missing dependencies: {', '.join(missing)}")92 print("Install with: pip install " + " ".join(missing))93 return False94 95 return True96 97def test_audio_processing():98 """Test audio processing capabilities"""99 print("๐ต Testing audio processing...")100 101 try:102 from pydub import AudioSegment103 from pydub.generators import Sine104 105 # Generate a test tone106 tone = Sine(440).to_audio_segment(duration=1000) # 1 second107 108 # Test basic operations109 tone = tone.set_frame_rate(16000)110 tone = tone.set_channels(1)111 112 print("โ
Audio processing functionality works")113 return True114 except Exception as e:115 print(f"โ Audio processing failed: {e}")116 return False117 118def test_speech_recognition():119 """Test speech recognition setup"""120 print("๐ค Testing speech recognition...")121 122 try:123 import speech_recognition as sr124 r = sr.Recognizer()125 print("โ
Speech recognition initialized")126 return True127 except Exception as e:128 print(f"โ Speech recognition failed: {e}")129 return False130 131def main():132 """Run all tests"""133 print("๐ Running Accent Detection Tests\n")134 135 tests = [136 ("Dependencies", test_dependencies),137 ("Audio Processing", test_audio_processing), 138 ("Speech Recognition", test_speech_recognition),139 ("Accent Patterns", test_accent_patterns)140 ]141 142 results = []143 for test_name, test_func in tests:144 print(f"=" * 50)145 print(f"Testing: {test_name}")146 print("=" * 50)147 148 try:149 result = test_func()150 results.append((test_name, result))151 except Exception as e:152 print(f"โ {test_name} failed with error: {e}")153 results.append((test_name, False))154 155 print()156 157 # Summary158 print("=" * 50)159 print("TEST SUMMARY")160 print("=" * 50)161 162 passed = 0163 for test_name, result in results:164 status = "โ
PASS" if result else "โ FAIL"165 print(f"{status} - {test_name}")166 if result:167 passed += 1168 169 print(f"\n๐ Overall: {passed}/{len(results)} tests passed")170 171 if passed == len(results):172 print("๐ All tests passed! The accent detector is ready to use.")173 return True174 else:175 print("โ ๏ธ Some tests failed. Check the issues above.")176 return False177 178if __name__ == "__main__":179 success = main()180 sys.exit(0 if success else 1)