File size: 6,188 Bytes
3135113
 
1059c3e
3135113
 
 
 
 
 
 
 
 
 
1059c3e
3135113
1059c3e
3135113
 
 
 
 
 
 
 
 
 
be42ab9
 
1059c3e
 
3135113
 
 
 
be42ab9
 
1059c3e
3135113
 
 
 
 
 
 
 
 
 
 
 
 
1059c3e
3135113
1059c3e
3135113
 
 
 
1059c3e
3135113
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1059c3e
3135113
1059c3e
3135113
 
 
 
1059c3e
3135113
 
 
 
 
 
 
 
 
 
 
 
 
 
1059c3e
3135113
 
 
 
1059c3e
3135113
 
 
 
 
 
 
 
 
1059c3e
 
 
be42ab9
1059c3e
 
 
 
 
be42ab9
1059c3e
 
 
 
 
 
 
 
 
 
 
 
 
be42ab9
1059c3e
 
be42ab9
3135113
 
 
 
1059c3e
3135113
 
 
 
 
 
 
 
 
1059c3e
3135113
 
 
 
 
 
 
1059c3e
 
 
3135113
 
 
 
 
1059c3e
3135113
 
 
be42ab9
1059c3e
be42ab9
1059c3e
be42ab9
3135113
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Simple test script for the Coqui TTS API
Run this to test the API locally
"""

import requests
import time
import os

# Configuration
API_BASE_URL = "http://localhost:7860"
TEST_TEXTS = [
    "Hello world, this is a test of the Coqui TTS API using the VITS model.",
    "The quick brown fox jumps over the lazy dog.",
    "Welcome to our minimal text-to-speech service!"
]

def test_health_check():
    """Test the health check endpoints"""
    print("πŸ” Testing health check endpoints...")
    
    try:
        # Test root endpoint
        response = requests.get(f"{API_BASE_URL}/")
        print(f"GET / - Status: {response.status_code}")
        if response.status_code == 200:
            data = response.json()
            print(f"Model: {data.get('model')}")
            print(f"Engine: {data.get('engine')}")
        
        # Test health endpoint
        response = requests.get(f"{API_BASE_URL}/health")
        print(f"GET /health - Status: {response.status_code}")
        if response.status_code == 200:
            data = response.json()
            print(f"Model loaded: {data.get('model_loaded')}")
        
    except requests.exceptions.ConnectionError:
        print("❌ Could not connect to the API. Make sure it's running on localhost:7860")
        return False
    
    return True

def test_get_endpoint():
    """Test the GET TTS endpoint"""
    print("\n🎀 Testing GET TTS endpoint...")
    
    for i, text in enumerate(TEST_TEXTS):
        try:
            params = {"text": text}
            
            print(f"Testing text {i+1}: '{text[:50]}...'")
            response = requests.get(f"{API_BASE_URL}/tts", params=params)
            
            if response.status_code == 200:
                # Save the audio file
                filename = f"test_output_get_{i+1}.wav"
                with open(filename, "wb") as f:
                    f.write(response.content)
                print(f"βœ… Audio saved as {filename} ({len(response.content)} bytes)")
            else:
                print(f"❌ Error: {response.status_code} - {response.text}")
                
        except Exception as e:
            print(f"❌ Exception: {str(e)}")

def test_post_endpoint():
    """Test the POST TTS endpoint"""
    print("\n🎡 Testing POST TTS endpoint...")
    
    for i, text in enumerate(TEST_TEXTS):
        try:
            data = {"text": text}
            
            print(f"Testing text {i+1}: '{text[:50]}...'")
            response = requests.post(f"{API_BASE_URL}/tts", json=data)
            
            if response.status_code == 200:
                # Save the audio file
                filename = f"test_output_post_{i+1}.wav"
                with open(filename, "wb") as f:
                    f.write(response.content)
                print(f"βœ… Audio saved as {filename} ({len(response.content)} bytes)")
            else:
                print(f"❌ Error: {response.status_code} - {response.text}")
                
        except Exception as e:
            print(f"❌ Exception: {str(e)}")

def test_form_endpoint():
    """Test the POST TTS endpoint with form data"""
    print("\nπŸ“‹ Testing POST TTS endpoint with form data...")
    
    try:
        data = {"text": "This is a test using form data submission with Coqui TTS VITS model."}
        
        response = requests.post(f"{API_BASE_URL}/tts", data=data)
        
        if response.status_code == 200:
            filename = "test_output_form_vits.wav"
            with open(filename, "wb") as f:
                f.write(response.content)
            print(f"βœ… Audio saved as {filename} ({len(response.content)} bytes)")
        else:
            print(f"❌ Error: {response.status_code} - {response.text}")
            
    except Exception as e:
        print(f"❌ Exception: {str(e)}")

def test_long_text():
    """Test with longer text"""
    print("\nπŸ“– Testing with longer text...")
    
    long_text = """
    This is a longer text passage to test the VITS model's ability to handle 
    extended speech synthesis. The model should maintain good quality and 
    natural prosody throughout this longer utterance.
    """
    
    try:
        data = {"text": long_text.strip()}
        
        print("Testing with longer text passage...")
        response = requests.post(f"{API_BASE_URL}/tts", json=data)
        
        if response.status_code == 200:
            filename = "test_output_long_text.wav"
            with open(filename, "wb") as f:
                f.write(response.content)
            print(f"βœ… Long text audio saved as {filename} ({len(response.content)} bytes)")
        else:
            print(f"❌ Error: {response.status_code} - {response.text}")
            
    except Exception as e:
        print(f"❌ Exception: {str(e)}")

def cleanup_test_files():
    """Clean up generated test files"""
    print("\n🧹 Cleaning up test files...")
    
    test_files = [f for f in os.listdir(".") if f.startswith("test_output_") and f.endswith(".wav")]
    
    for file in test_files:
        try:
            os.remove(file)
            print(f"Removed {file}")
        except Exception as e:
            print(f"Could not remove {file}: {str(e)}")

if __name__ == "__main__":
    print("πŸš€ Starting Coqui TTS VITS API Test Suite")
    print("=" * 50)
    
    # Test health check first
    if not test_health_check():
        print("\n❌ Health check failed. Exiting.")
        exit(1)
    
    # Wait for model to load
    print("\n⏳ Waiting for VITS model to load...")
    time.sleep(5)
    
    # Run tests
    test_get_endpoint()
    test_post_endpoint()
    test_form_endpoint()
    test_long_text()
    
    print("\n" + "=" * 50)
    print("βœ… Test suite completed!")
    print("\nGenerated files demonstrate:")
    print("- VITS model voice quality")
    print("- Various input methods (GET, POST JSON, POST form)")
    print("- Short and long text handling")
    
    print("\nTo clean up test files, run:")
    print("python test_api.py --cleanup")
    
    # Check if cleanup flag is provided
    import sys
    if "--cleanup" in sys.argv:
        cleanup_test_files()