File size: 8,286 Bytes
124020a |
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 236 237 238 239 240 241 242 243 244 245 246 247 |
#!/usr/bin/env python3
"""
Test script for the optimized server to verify model loading and functionality.
"""
import requests
import json
import numpy as np
import base64
import io
import soundfile as sf
import tempfile
import os
def create_test_audio(duration=2.0, sample_rate=16000):
"""Create a simple test audio signal."""
t = np.linspace(0, duration, int(sample_rate * duration), False)
# Generate a simple sine wave
frequency = 440 # A4 note
audio = 0.3 * np.sin(2 * np.pi * frequency * t)
return audio.astype(np.float32)
def audio_to_base64(audio, sample_rate):
"""Convert audio array to base64 string."""
buf = io.BytesIO()
np.save(buf, audio.astype(np.float32))
return base64.b64encode(buf.getvalue()).decode()
def test_health_check():
"""Test the health check endpoint."""
try:
response = requests.get("http://localhost:8000/api/v1/health")
if response.status_code == 200:
data = response.json()
print(f"โ Health check passed: {data}")
# Show device information if available
if "language_model_device" in data:
print(f" ๐ฑ Language Model Device: {data['language_model_device']}")
print(f" ๐ข Model Dtype: {data['language_model_dtype']}")
if data.get("cuda_available"):
print(f" ๐ฎ CUDA Device: {data.get('cuda_device_name', 'Unknown')}")
print(f" ๐พ Memory Allocated: {data.get('cuda_memory_allocated', 'Unknown')}")
print(f" ๐พ Memory Reserved: {data.get('cuda_memory_reserved', 'Unknown')}")
else:
print(" โ CUDA not available - running on CPU")
return data.get("model_loaded", False)
else:
print(f"โ Health check failed: {response.status_code}")
return False
except Exception as e:
print(f"โ Health check error: {e}")
return False
def test_v2t_endpoint():
"""Test the voice-to-text endpoint."""
try:
# Create test audio
audio = create_test_audio()
audio_b64 = audio_to_base64(audio, 16000)
payload = {
"audio_data": audio_b64,
"sample_rate": 16000
}
response = requests.post(
"http://localhost:8000/api/v1/v2t",
json=payload,
headers={"Content-Type": "application/json"}
)
if response.status_code == 200:
data = response.json()
print(f"โ V2T endpoint working: {data.get('text', 'No text')[:100]}...")
return True
else:
print(f"โ V2T endpoint failed: {response.status_code} - {response.text}")
return False
except Exception as e:
print(f"โ V2T endpoint error: {e}")
return False
def test_error_scenarios():
"""Test error scenarios to ensure proper responses."""
print("\n4. Testing error scenarios...")
# Test with invalid audio data
try:
payload = {
"audio_data": "invalid_base64_data",
"sample_rate": 16000
}
response = requests.post(
"http://localhost:8000/api/v1/v2t",
json=payload,
headers={"Content-Type": "application/json"}
)
if response.status_code == 200:
data = response.json()
print(f"โ Error handling working: {data.get('text', 'No text')[:100]}...")
else:
print(f"โ Error handling failed: {response.status_code} - {response.text}")
except Exception as e:
print(f"โ Error scenario test failed: {e}")
# Test with missing fields
try:
payload = {
"audio_data": "",
"sample_rate": 16000
}
response = requests.post(
"http://localhost:8000/api/v1/v2t",
json=payload,
headers={"Content-Type": "application/json"}
)
if response.status_code == 200:
data = response.json()
print(f"โ Empty input handling working: {data.get('text', 'No text')[:100]}...")
else:
print(f"โ Empty input handling failed: {response.status_code} - {response.text}")
except Exception as e:
print(f"โ Empty input test failed: {e}")
return True
def test_authentication():
"""Test authentication functionality."""
print("\n5. Testing authentication...")
# Test with valid audio data (should work if auth passes)
try:
audio = create_test_audio()
audio_b64 = audio_to_base64(audio, 16000)
payload = {
"audio_data": audio_b64,
"sample_rate": 16000
}
response = requests.post(
"http://localhost:8000/api/v1/v2t",
json=payload,
headers={"Content-Type": "application/json"}
)
if response.status_code == 200:
data = response.json()
text = data.get('text', '')
if "Authentication failed" in text:
print(f"โ Authentication check working: {text}")
else:
print(f"โ Authentication passed: {text[:100]}...")
return True
else:
print(f"โ Authentication test failed: {response.status_code} - {response.text}")
return False
except Exception as e:
print(f"โ Authentication test error: {e}")
return False
def test_inference_endpoint():
"""Test the inference endpoint (if INTERFACE is available)."""
try:
# Create test audio
audio = create_test_audio()
audio_b64 = audio_to_base64(audio, 16000)
payload = {
"audio_data": audio_b64,
"sample_rate": 16000
}
response = requests.post(
"http://localhost:8000/api/v1/inference",
json=payload,
headers={"Content-Type": "application/json"}
)
if response.status_code == 200:
data = response.json()
print(f"โ Inference endpoint working: Audio data length {len(data.get('audio_data', ''))}")
return True
elif response.status_code == 503:
print(f"โ Inference endpoint not available (expected if outetts models not loaded): {response.text}")
return True # This is expected if outetts models are not available
else:
print(f"โ Inference endpoint failed: {response.status_code} - {response.text}")
return False
except Exception as e:
print(f"โ Inference endpoint error: {e}")
return False
def main():
"""Run all tests."""
print("Testing optimized server...")
print("=" * 50)
# Test health check
print("\n1. Testing health check...")
models_loaded = test_health_check()
if not models_loaded:
print("โ Models not loaded. Some tests may fail.")
# Test V2T endpoint
print("\n2. Testing voice-to-text endpoint...")
v2t_success = test_v2t_endpoint()
# Test inference endpoint
print("\n3. Testing inference endpoint...")
inference_success = test_inference_endpoint()
# Test error scenarios
error_success = test_error_scenarios()
# Test authentication
auth_success = test_authentication()
# Summary
print("\n" + "=" * 50)
print("Test Summary:")
print(f"Health Check: {'โ' if models_loaded else 'โ'}")
print(f"V2T Endpoint: {'โ' if v2t_success else 'โ'}")
print(f"Inference Endpoint: {'โ' if inference_success else 'โ'}")
print(f"Error Handling: {'โ' if error_success else 'โ'}")
print(f"Authentication: {'โ' if auth_success else 'โ'}")
if models_loaded and v2t_success and error_success and auth_success:
print("\n๐ Server is working correctly with authentication and error handling!")
else:
print("\nโ Some issues detected. Check the logs above.")
if __name__ == "__main__":
main()
|