ebitlogix/Parler_TTS_API
0
1#!/usr/bin/env python32"""3Test TTS API with Urdu text and save audio outputs4"""5import requests6import os7from pathlib import Path8from datetime import datetime9 10# API configuration11API_URL = "https://ebitlogix-parler-tts-api.hf.space"12# For local testing, change to: API_URL = "http://localhost:7860"13 14OUTPUT_DIR = Path("tts_output")15OUTPUT_DIR.mkdir(exist_ok=True)16 17# Test cases with Urdu text18TEST_CASES = [19 {20 "text": "سلام دنیا",21 "speaker": "Divya",22 "description": "Hello World"23 },24 {25 "text": "مرحبا بك في تطبيق تحويل النص إلى كلام",26 "speaker": "Rani",27 "description": "Welcome to TTS App"28 },29 {30 "text": "یہ ایک اردو متن ہے جو آواز میں تبدیل ہوگا",31 "speaker": "Rohit",32 "description": "This is Urdu text converted to speech"33 },34 {35 "text": "کتاب پڑھنا میرا پسندیدہ کام ہے",36 "speaker": "Aman",37 "description": "Reading books is my favorite"38 },39 {40 "text": "خوشامدید، یہ ایک خوبصورت دن ہے",41 "speaker": "Generic Female",42 "description": "Welcome, it's a beautiful day"43 },44 {45 "text": "ہمیں اپنے لیے بہتر مستقبل بنانی ہے",46 "speaker": "Generic Male",47 "description": "We must build a better future"48 },49]50 51def test_health():52 """Test API health check."""53 print("\n" + "="*60)54 print("Testing API Health Check")55 print("="*60)56 57 try:58 response = requests.get(f"{API_URL}/")59 if response.status_code == 200:60 data = response.json()61 print(f"✅ API is running")62 print(f" Model: {data.get('model')}")63 print(f" Speakers: {', '.join(data.get('speakers', []))}")64 print(f" Sample Rate: {data.get('sample_rate')} Hz")65 return True66 else:67 print(f"❌ API health check failed: {response.status_code}")68 return False69 except Exception as e:70 print(f"❌ Cannot connect to API: {e}")71 return False72 73def test_tts_generation():74 """Generate TTS audio for all test cases."""75 print("\n" + "="*60)76 print("Testing TTS Generation with Urdu Text")77 print("="*60 + "\n")78 79 successful = 080 failed = 081 82 for i, test_case in enumerate(TEST_CASES, 1):83 text = test_case["text"]84 speaker = test_case["speaker"]85 description = test_case["description"]86 87 print(f"[{i}/{len(TEST_CASES)}] Testing: {description}")88 print(f" Text: {text}")89 print(f" Speaker: {speaker}")90 91 try:92 payload = {93 "text": text,94 "speaker": speaker,95 "pitch": "Moderate",96 "rate": "Moderate",97 "temperature": 0.8,98 "do_sample": True99 }100 101 response = requests.post(f"{API_URL}/tts", json=payload, timeout=60)102 103 if response.status_code != 200:104 print(f" ❌ Failed: {response.status_code} - {response.text[:100]}")105 failed += 1106 continue107 108 # Save audio file109 audio_data = response.content110 timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")111 filename = f"{timestamp}_{speaker.replace(' ', '_')}_{i}.wav"112 filepath = OUTPUT_DIR / filename113 114 with open(filepath, "wb") as f:115 f.write(audio_data)116 117 file_size_kb = len(audio_data) / 1024118 print(f" ✅ Success - Saved to: {filepath} ({file_size_kb:.1f} KB)")119 successful += 1120 121 except requests.exceptions.Timeout:122 print(f" ❌ Failed: Request timeout (60s)")123 failed += 1124 except Exception as e:125 print(f" ❌ Failed: {str(e)[:100]}")126 failed += 1127 128 print()129 130 # Summary131 print("="*60)132 print(f"Results: {successful} successful, {failed} failed")133 print(f"Audio files saved to: {OUTPUT_DIR.absolute()}")134 print("="*60)135 136 return successful, failed137 138def main():139 """Run all tests."""140 print("\n" + "█"*60)141 print("█ TTS API Test Suite - Urdu Text Generation")142 print("█"*60)143 144 # Health check145 if not test_health():146 print("\n❌ API is not available. Exiting...")147 return148 149 # TTS generation tests150 successful, failed = test_tts_generation()151 152 # Final status153 if failed == 0:154 print("\n✅ All tests passed!")155 else:156 print(f"\n⚠️ {failed} test(s) failed.")157 158 print(f"\n📁 Output folder: {OUTPUT_DIR.absolute()}")159 print(f"📊 Generated {successful} audio files\n")160 161if __name__ == "__main__":162 main()163 