File size: 4,773 Bytes
45a0e83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Test script for the new IPA assessment API
"""

import requests
import json
import os

# API endpoint
API_BASE = "http://localhost:8000"
ENDPOINT = f"{API_BASE}/speaking/assess-ipa"

def test_ipa_assessment():
    """Test the new IPA assessment endpoint"""
    
    # Create a test audio file (mock)
    test_audio_path = "test_audio.wav"
    
    # Create a minimal WAV file for testing
    with open(test_audio_path, "wb") as f:
        # Write minimal WAV header (44 bytes)
        f.write(b'RIFF')
        f.write((36).to_bytes(4, 'little'))  # file size - 8
        f.write(b'WAVE')
        f.write(b'fmt ')
        f.write((16).to_bytes(4, 'little'))  # fmt chunk size
        f.write((1).to_bytes(2, 'little'))   # audio format (PCM)
        f.write((1).to_bytes(2, 'little'))   # num channels
        f.write((44100).to_bytes(4, 'little'))  # sample rate
        f.write((88200).to_bytes(4, 'little'))  # byte rate
        f.write((2).to_bytes(2, 'little'))   # block align
        f.write((16).to_bytes(2, 'little'))  # bits per sample
        f.write(b'data')
        f.write((0).to_bytes(4, 'little'))   # data size
    
    try:
        # Test data
        test_cases = [
            {
                "target_word": "bed",
                "target_ipa": "/bɛd/",
                "focus_phonemes": "ɛ,b,d"
            },
            {
                "target_word": "cat", 
                "target_ipa": "/kæt/",
                "focus_phonemes": "æ"
            },
            {
                "target_word": "think",
                "target_ipa": "/θɪŋk/", 
                "focus_phonemes": "θ"
            }
        ]
        
        for i, test_case in enumerate(test_cases, 1):
            print(f"\n{'='*50}")
            print(f"Test Case {i}: {test_case['target_word']}")
            print(f"{'='*50}")
            
            # Prepare the request
            files = {
                'audio_file': ('test.wav', open(test_audio_path, 'rb'), 'audio/wav')
            }
            
            data = {
                'target_word': test_case['target_word'],
                'target_ipa': test_case['target_ipa'],
                'focus_phonemes': test_case['focus_phonemes']
            }
            
            print(f"Request data: {data}")
            
            # Make the request
            response = requests.post(ENDPOINT, files=files, data=data)
            
            # Close the file
            files['audio_file'][1].close()
            
            print(f"Response status: {response.status_code}")
            
            if response.status_code == 200:
                result = response.json()
                print("✅ Success!")
                print(f"Overall Score: {result.get('overall_score', 0) * 100:.1f}%")
                print(f"Character Analysis: {len(result.get('character_analysis', []))} characters")
                print(f"Phoneme Scores: {len(result.get('phoneme_scores', []))} phonemes")
                print(f"Focus Phonemes: {len(result.get('focus_phonemes_analysis', []))} analyzed")
                print(f"Vietnamese Tips: {len(result.get('vietnamese_tips', []))} tips")
                print(f"Recommendations: {len(result.get('practice_recommendations', []))} recommendations")
                
                # Print sample character analysis
                if result.get('character_analysis'):
                    print("\nCharacter Analysis Sample:")
                    for char_analysis in result['character_analysis'][:3]:
                        print(f"  '{char_analysis['character']}' -> /{char_analysis['phoneme']}/ ({char_analysis['score']*100:.1f}%)")
                
                # Print focus phonemes
                if result.get('focus_phonemes_analysis'):
                    print("\nFocus Phonemes Analysis:")
                    for phoneme_analysis in result['focus_phonemes_analysis']:
                        print(f"  /{phoneme_analysis['phoneme']}/ - {phoneme_analysis['score']*100:.1f}% ({phoneme_analysis['status']})")
                        print(f"    Tip: {phoneme_analysis['vietnamese_tip']}")
                
            else:
                print(f"❌ Failed: {response.text}")
    
    except requests.exceptions.ConnectionError:
        print("❌ Connection Error: Make sure the API server is running on port 8000")
        print("Start the server with: uvicorn app:app --host 0.0.0.0 --port 8000")
    
    except Exception as e:
        print(f"❌ Error: {e}")
    
    finally:
        # Clean up test file
        if os.path.exists(test_audio_path):
            os.remove(test_audio_path)

if __name__ == "__main__":
    print("Testing New IPA Assessment API")
    print("=" * 50)
    test_ipa_assessment()