File size: 7,477 Bytes
d507f3c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
#!/usr/bin/env python3
"""
Local testing script for omega_model server.
Tests the Docker container health and API endpoints.
"""
import requests
import time
import numpy as np
import base64
import io
import sys
from pathlib import Path

# Configuration
SERVER_URL = "http://localhost:8000"
HEALTH_ENDPOINT = f"{SERVER_URL}/api/v1/health"
V2V_ENDPOINT = f"{SERVER_URL}/api/v1/v2v"
V2T_ENDPOINT = f"{SERVER_URL}/api/v1/v2t"

# Wait times
MAX_WAIT_TIME = 300  # 5 minutes for model loading
HEALTH_CHECK_INTERVAL = 5  # Check every 5 seconds


def create_test_audio(duration_seconds=2, sample_rate=16000):
    """Create a simple test audio signal (sine wave)."""
    t = np.linspace(0, duration_seconds, int(sample_rate * duration_seconds))
    # Generate a 440 Hz sine wave (A note)
    audio = np.sin(2 * np.pi * 440 * t).astype(np.float32)
    # Reshape to (1, samples) format
    audio = audio.reshape(1, -1)
    return audio, sample_rate


def audio_to_base64(audio, sample_rate):
    """Convert numpy audio array to base64 string."""
    buf = io.BytesIO()
    np.save(buf, audio.astype(np.float32))
    return base64.b64encode(buf.getvalue()).decode()


def wait_for_server(max_wait=MAX_WAIT_TIME):
    """Wait for the server to be ready."""
    print(f"Waiting for server to be ready (max {max_wait}s)...")
    start_time = time.time()
    
    while time.time() - start_time < max_wait:
        try:
            response = requests.get(HEALTH_ENDPOINT, timeout=5)
            if response.status_code == 200:
                data = response.json()
                if data.get("status") == "healthy" and data.get("model_loaded"):
                    print("βœ… Server is ready!")
                    return True
                else:
                    print(f"⏳ Server starting... (status: {data.get('status')}, model_loaded: {data.get('model_loaded')})")
            else:
                print(f"⏳ Server responding but not ready (status code: {response.status_code})")
        except requests.exceptions.ConnectionError:
            print("⏳ Server not responding yet...")
        except Exception as e:
            print(f"⏳ Error checking server: {e}")
        
        time.sleep(HEALTH_CHECK_INTERVAL)
    
    print("❌ Server did not become ready in time!")
    return False


def test_health():
    """Test the health endpoint."""
    print("\n" + "="*60)
    print("TEST 1: Health Check")
    print("="*60)
    
    try:
        response = requests.get(HEALTH_ENDPOINT, timeout=10)
        response.raise_for_status()
        data = response.json()
        
        print(f"Status Code: {response.status_code}")
        print(f"Response: {data}")
        
        if data.get("status") == "healthy" and data.get("model_loaded"):
            print("βœ… Health check PASSED")
            return True
        else:
            print("❌ Health check FAILED")
            if data.get("error"):
                print(f"Error: {data.get('error')}")
            return False
            
    except Exception as e:
        print(f"❌ Health check FAILED: {e}")
        return False


def test_v2t():
    """Test the voice-to-text endpoint."""
    print("\n" + "="*60)
    print("TEST 2: Voice-to-Text (v2t)")
    print("="*60)
    
    try:
        # Create test audio
        audio, sample_rate = create_test_audio(duration_seconds=2)
        audio_b64 = audio_to_base64(audio, sample_rate)
        
        payload = {
            "audio_data": audio_b64,
            "sample_rate": sample_rate
        }
        
        print(f"Sending request with audio shape: {audio.shape}, sample_rate: {sample_rate}")
        print("Waiting for response (this may take 30-60 seconds)...")
        
        response = requests.post(V2T_ENDPOINT, json=payload, timeout=120)
        response.raise_for_status()
        data = response.json()
        
        print(f"Status Code: {response.status_code}")
        print(f"Transcribed Text: {data.get('text', 'N/A')}")
        
        if "text" in data:
            print("βœ… Voice-to-Text test PASSED")
            return True
        else:
            print("❌ Voice-to-Text test FAILED - no text in response")
            return False
            
    except requests.exceptions.Timeout:
        print("❌ Voice-to-Text test FAILED - Request timed out")
        return False
    except Exception as e:
        print(f"❌ Voice-to-Text test FAILED: {e}")
        import traceback
        traceback.print_exc()
        return False


def test_v2v():
    """Test the voice-to-voice endpoint."""
    print("\n" + "="*60)
    print("TEST 3: Voice-to-Voice (v2v)")
    print("="*60)
    
    try:
        # Create test audio
        audio, sample_rate = create_test_audio(duration_seconds=2)
        audio_b64 = audio_to_base64(audio, sample_rate)
        
        payload = {
            "audio_data": audio_b64,
            "sample_rate": sample_rate
        }
        
        print(f"Sending request with audio shape: {audio.shape}, sample_rate: {sample_rate}")
        print("Waiting for response (this may take 60-120 seconds)...")
        
        response = requests.post(V2V_ENDPOINT, json=payload, timeout=200)
        response.raise_for_status()
        data = response.json()
        
        print(f"Status Code: {response.status_code}")
        
        if "audio_data" in data:
            # Decode the response audio
            audio_response_b64 = data["audio_data"]
            audio_response_bytes = base64.b64decode(audio_response_b64)
            audio_response = np.load(io.BytesIO(audio_response_bytes), allow_pickle=False)
            print(f"Response audio shape: {audio_response.shape}")
            print(f"Response audio dtype: {audio_response.dtype}")
            print("βœ… Voice-to-Voice test PASSED")
            return True
        else:
            print("❌ Voice-to-Voice test FAILED - no audio_data in response")
            return False
            
    except requests.exceptions.Timeout:
        print("❌ Voice-to-Voice test FAILED - Request timed out")
        return False
    except Exception as e:
        print(f"❌ Voice-to-Voice test FAILED: {e}")
        import traceback
        traceback.print_exc()
        return False


def main():
    """Run all tests."""
    print("="*60)
    print("OMEGA MODEL LOCAL TESTING")
    print("="*60)
    print(f"Server URL: {SERVER_URL}")
    print(f"Make sure the Docker container is running on port 8010")
    print()
    
    # Wait for server to be ready
    if not wait_for_server():
        print("\n❌ Server is not ready. Please check Docker container logs.")
        sys.exit(1)
    
    # Run tests
    results = []
    
    results.append(("Health Check", test_health()))
    results.append(("Voice-to-Text", test_v2t()))
    results.append(("Voice-to-Voice", test_v2v()))
    
    # Summary
    print("\n" + "="*60)
    print("TEST SUMMARY")
    print("="*60)
    
    passed = sum(1 for _, result in results if result)
    total = len(results)
    
    for test_name, result in results:
        status = "βœ… PASSED" if result else "❌ FAILED"
        print(f"{test_name}: {status}")
    
    print(f"\nTotal: {passed}/{total} tests passed")
    
    if passed == total:
        print("\nπŸŽ‰ All tests passed! Your model is ready to upload.")
        sys.exit(0)
    else:
        print("\n⚠️  Some tests failed. Please check the errors above.")
        sys.exit(1)


if __name__ == "__main__":
    main()