-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_openai.py
124 lines (107 loc) · 4.14 KB
/
test_openai.py
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
import openai
from pathlib import Path
import requests
# Configure the client to use your local API
client = openai.OpenAI(
base_url="http://localhost:8100/v1", # Update with your API's URL
api_key="your-api-key-here" # Replace with your API key
)
def test_health_check():
"""Test API health check endpoint"""
try:
# Use direct requests for health check since it's not part of OpenAI's standard endpoints
response = requests.get("http://localhost:8100/health")
data = response.json()
print("\nHealth check status:", data.get('status'))
return data.get('status') == "healthy"
except Exception as e:
print(f"Error checking health: {str(e)}")
return False
def test_list_available_voices():
"""Test listing available voices"""
try:
# Use direct requests for voice listing since it's not part of standard OpenAI endpoints
response = requests.get("http://localhost:8100/v1/available_voices")
data = response.json()
print("\nAvailable voices:")
for voice_data in data.get('data', []):
print(f"- {voice_data['id']} (Type: {voice_data['root']})")
return True
except Exception as e:
print(f"Error listing voices: {str(e)}")
return False
def test_text_to_speech():
"""Test text-to-speech conversion"""
try:
# Test parameters
text = "Hello, this is a test of the text to speech system."
voice = "mlx-base-female-speaker" # Using one of the voices from our config
# Create speech
response = client.audio.speech.create(
model="tts-1-hd",
voice=voice,
input=text,
response_format="mp3"
)
# Save the audio file
speech_file_path = Path("./test_speech.mp3")
response.stream_to_file(speech_file_path)
print(f"\nSpeech generated successfully: {speech_file_path}")
return True
except Exception as e:
print(f"Error generating speech: {str(e)}")
return False
def test_transcription():
"""Test audio transcription"""
try:
# Save the audio temporarily
temp_audio_path = "/Users/gokdenizgulmez/Desktop/OpenAudioAPI/OpenAudioAPI/voices/ref_audios/base_female.wav"
# Now transcribe the audio
with open(temp_audio_path, "rb") as audio_file:
transcript = client.audio.transcriptions.create(
model="tiny", # Changed to match config
file=audio_file
)
print("\nTranscription results:")
print(f"Text: {transcript.text}")
if hasattr(transcript, 'segments'):
print(f"Segments: {len(transcript.segments)}")
return True
except Exception as e:
print(f"Error in transcription test: {str(e)}")
return False
def run_all_tests():
"""Run all test cases and report results"""
tests = [
("Health Check", test_health_check),
("List Voices", test_list_available_voices),
("Text-to-Speech", test_text_to_speech),
("Transcription", test_transcription)
]
results = []
print("Starting API tests...\n")
for test_name, test_func in tests:
print(f"Running {test_name} test...")
try:
success = test_func()
results.append((test_name, success))
print(f"{test_name} test: {'✓ Passed' if success else '✗ Failed'}\n")
except Exception as e:
results.append((test_name, False))
print(f"{test_name} test: ✗ Failed - {str(e)}\n")
# Print summary
print("\nTest Summary:")
print("-" * 40)
successful_tests = sum(1 for _, success in results if success)
print(f"Total tests: {len(tests)}")
print(f"Passed: {successful_tests}")
print(f"Failed: {len(tests) - successful_tests}")
print("-" * 40)
# Print failed tests if any
failed_tests = [name for name, success in results if not success]
if failed_tests:
print("\nFailed tests:")
for test_name in failed_tests:
print(f"- {test_name}")
if __name__ == "__main__":
run_all_tests()