File size: 5,451 Bytes
b3cdca1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/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)