""" Test client demonstrating both OpenAI Python SDK and direct requests to Kokoro TTS server. """ import os import requests API_BASE_URL = os.getenv("API_BASE_URL", "http://localhost:7860/v1") API_KEY = os.getenv("API_KEY", "not-needed") SAMPLE_TEXT = """ Kokoro is an open-weight TTS model with 82 million parameters. Despite its lightweight architecture, it delivers comparable quality to larger models while being significantly faster and more cost-efficient. """ def test_with_requests(): print("\n--- 1. Testing with direct HTTP POST (requests) ---") url = f"{API_BASE_URL}/audio/speech" headers = { "Content-Type": "application/json", "Authorization": f"Bearer {API_KEY}", } payload = { "model": "kokoro", "input": SAMPLE_TEXT.strip(), "voice": "af_heart", "response_format": "mp3", "speed": 1.0, } print(f"Sending request to {url}...") response = requests.post(url, json=payload, headers=headers) if response.status_code == 200: output_file = "output_requests.mp3" with open(output_file, "wb") as f: f.write(response.content) print(f"Success! Saved {len(response.content)} bytes to '{output_file}'.") else: print(f"Failed ({response.status_code}): {response.text}") def test_with_openai_sdk(): print("\n--- 2. Testing with Official OpenAI Python SDK ---") try: from openai import OpenAI except ImportError: print("OpenAI Python SDK not installed. Run: pip install openai") return client = OpenAI( base_url=API_BASE_URL, api_key=API_KEY, ) print("Requesting speech with client.audio.speech.create (voice='alloy')...") response = client.audio.speech.create( model="kokoro", voice="alloy", # mapped automatically to af_alloy / af_bella input=SAMPLE_TEXT.strip(), response_format="wav", speed=1.0, ) output_file = "output_openai_sdk.wav" response.stream_to_file(output_file) print(f"Success! Saved audio to '{output_file}'.") def test_voice_listing(): print("\n--- 3. Listing available voices ---") url = f"{API_BASE_URL}/audio/voices" response = requests.get(url) if response.status_code == 200: data = response.json() print(f"Total available voices: {len(data.get('voices', []))}") print("Sample voices:") for v in data.get("voices", [])[:5]: print(f" - {v['id']} ({v['name']}, {v['gender']}, {v['language']})") print(f"OpenAI Mappings: {data.get('openai_mapping')}") else: print(f"Failed to fetch voices: {response.status_code}") if __name__ == "__main__": print("Testing Kokoro TTS OpenAI Server...") test_voice_listing() test_with_requests() test_with_openai_sdk()