CoolFace
Apppublic

ebitlogix/Parler_TTS_API

sourceHugging Faceupdated 5mo agoView on Hugging Face
0likes
test_api.py159 linesDownload Raw Back to root
1import requests2import io3import soundfile as sf4import numpy as np5from pathlib import Path6import json7 8# Test configuration9BASE_URL = "http://localhost:7860"10TEST_OUTPUT_DIR = Path("test_outputs")11 12# Create output directory for test audio files13TEST_OUTPUT_DIR.mkdir(exist_ok=True)14 15def test_health_check():16    """Test the health check endpoint."""17    response = requests.get(f"{BASE_URL}/")18    assert response.status_code == 20019    data = response.json()20    assert data["status"] == "ok"21    assert "model" in data22    assert "speakers" in data23    print("✓ Health check passed")24    print(f"  Available speakers: {data['speakers']}")25    print(f"  Sample rate: {data['sample_rate']} Hz")26    return data27 28def test_speakers_endpoint():29    """Test the speakers endpoint."""30    response = requests.get(f"{BASE_URL}/speakers")31    assert response.status_code == 20032    data = response.json()33    assert "speakers" in data34    assert len(data["speakers"]) > 035    print(f"✓ Speakers endpoint passed")36    print(f"  Speakers: {data['speakers']}")37    return data["speakers"]38 39def test_tts_generation(text, speaker="Divya", pitch="Moderate", rate="Moderate"):40    """Test TTS generation and validate audio output."""41    payload = {42        "text": text,43        "speaker": speaker,44        "pitch": pitch,45        "rate": rate,46        "temperature": 0.8,47        "do_sample": True48    }49 50    response = requests.post(f"{BASE_URL}/tts", json=payload)51 52    if response.status_code != 200:53        print(f"✗ TTS generation failed: {response.status_code}")54        print(f"  Response: {response.text}")55        return False56 57    # Validate that we got audio data58    audio_data = response.content59    assert len(audio_data) > 0, "Audio data is empty"60 61    # Try to read the audio to validate it's valid WAV62    try:63        audio_buffer = io.BytesIO(audio_data)64        audio, sample_rate = sf.read(audio_buffer)65 66        # Validate audio properties67        assert isinstance(audio, np.ndarray), "Audio is not a numpy array"68        assert len(audio) > 0, "Audio array is empty"69        assert sample_rate > 0, "Invalid sample rate"70 71        # Calculate audio duration72        duration = len(audio) / sample_rate73 74        print(f"✓ TTS generation successful")75        print(f"  Text: {text}")76        print(f"  Speaker: {speaker}")77        print(f"  Audio shape: {audio.shape}")78        print(f"  Sample rate: {sample_rate} Hz")79        print(f"  Duration: {duration:.2f} seconds")80        print(f"  Audio size: {len(audio_data) / 1024:.2f} KB")81 82        # Save test audio file83        test_file = TEST_OUTPUT_DIR / f"test_{speaker}_{len(text)}_chars.wav"84        with open(test_file, "wb") as f:85            f.write(audio_data)86        print(f"  Saved to: {test_file}")87 88        return True89 90    except Exception as e:91        print(f"✗ Failed to read audio: {e}")92        return False93 94def test_empty_text():95    """Test handling of empty text."""96    payload = {"text": "", "speaker": "Divya"}97    response = requests.post(f"{BASE_URL}/tts", json=payload)98    assert response.status_code == 400, "Should return 400 for empty text"99    print("✓ Empty text validation passed")100 101def test_invalid_speaker():102    """Test handling of invalid speaker."""103    payload = {"text": "Hello world", "speaker": "InvalidSpeaker"}104    response = requests.post(f"{BASE_URL}/tts", json=payload)105    assert response.status_code == 400, "Should return 400 for invalid speaker"106    print("✓ Invalid speaker validation passed")107 108def run_all_tests():109    """Run all tests."""110    print("\n" + "="*60)111    print("TTS API Test Suite")112    print("="*60 + "\n")113 114    try:115        # Basic endpoint tests116        print("1. Testing health check...")117        health_data = test_health_check()118        print()119 120        print("2. Testing speakers endpoint...")121        speakers = test_speakers_endpoint()122        print()123 124        # Validation tests125        print("3. Testing input validation...")126        test_empty_text()127        test_invalid_speaker()128        print()129 130        # TTS generation tests with different speakers and text131        print("4. Testing TTS generation with different speakers...")132 133        test_cases = [134            ("سلام دنیا", "Divya"),  # Urdu text135            ("ہیلو ورلڈ", "Rani"),136            ("مرحبا العالم", "Generic Female"),137        ]138 139        for text, speaker in test_cases:140            success = test_tts_generation(text, speaker=speaker)141            if not success:142                print(f"  WARNING: Test failed for {speaker}")143            print()144 145        print("="*60)146        print(f"All tests completed! Test outputs saved to: {TEST_OUTPUT_DIR}")147        print("="*60 + "\n")148 149    except requests.exceptions.ConnectionError:150        print(f"✗ Cannot connect to server at {BASE_URL}")151        print("  Make sure the API is running: python api.py")152    except Exception as e:153        print(f"✗ Test suite failed with error: {e}")154        import traceback155        traceback.print_exc()156 157if __name__ == "__main__":158    run_all_tests()159