From 84d92007752e6d80d8ced01bb3c352ff7c0b8d33 Mon Sep 17 00:00:00 2001 From: rahulpscraftech360 Date: Tue, 19 Aug 2025 15:30:24 +0530 Subject: [PATCH] clean test files --- download_gigaspeech_manual.py | 98 ----------------------- test_concurrent_clients.py | 141 ---------------------------------- test_english_asr.py | 72 ----------------- test_fallback_tts.py | 101 ------------------------ test_gigaspeech_download.py | 79 ------------------- test_whisper_model.py | 59 -------------- 6 files changed, 550 deletions(-) delete mode 100644 download_gigaspeech_manual.py delete mode 100644 test_concurrent_clients.py delete mode 100644 test_english_asr.py delete mode 100644 test_fallback_tts.py delete mode 100644 test_gigaspeech_download.py delete mode 100644 test_whisper_model.py diff --git a/download_gigaspeech_manual.py b/download_gigaspeech_manual.py deleted file mode 100644 index b0ba12cd7..000000000 --- a/download_gigaspeech_manual.py +++ /dev/null @@ -1,98 +0,0 @@ -#!/usr/bin/env python3 -""" -Manual download script for Gigaspeech model -Use this if the automatic download fails -""" - -import os -import urllib.request -import tarfile - -def download_gigaspeech_manual(): - """Manually download and extract Gigaspeech model""" - - url = "https://github.com/k2-fsa/sherpa-onnx/releases/download/asr-models/sherpa-onnx-zipformer-gigaspeech-2023-12-12.tar.bz2" - model_dir = "models/sherpa-onnx-zipformer-gigaspeech-2023-12-12" - - print("šŸ”½ Manual Gigaspeech Model Download") - print("=" * 50) - - # Check if already exists - expected_files = [ - "encoder-epoch-30-avg-9.onnx", - "decoder-epoch-30-avg-9.onnx", - "joiner-epoch-30-avg-9.onnx", - "tokens.txt" - ] - - if all(os.path.exists(os.path.join(model_dir, f)) for f in expected_files): - print("āœ… Model already exists!") - return True - - try: - # Create models directory - os.makedirs("models", exist_ok=True) - - # Download file - tar_filename = "models/gigaspeech_temp.tar.bz2" - print(f"šŸ“„ Downloading from: {url}") - print("ā³ This may take a few minutes (~120MB)...") - - def progress_hook(block_num, block_size, total_size): - if total_size > 0: - percent = min(100, (block_num * block_size * 100) // total_size) - print(f"\ršŸ“Š Progress: {percent}%", end="", flush=True) - - urllib.request.urlretrieve(url, tar_filename, progress_hook) - print("\nāœ… Download completed!") - - # Extract - print("šŸ“‚ Extracting files...") - with tarfile.open(tar_filename, 'r:bz2') as tar: - tar.extractall("models") - - # Clean up - os.remove(tar_filename) - - # Verify - if all(os.path.exists(os.path.join(model_dir, f)) for f in expected_files): - print("āœ… Extraction successful!") - print("\nšŸ“ Model files:") - for f in expected_files: - file_path = os.path.join(model_dir, f) - size = os.path.getsize(file_path) / (1024*1024) # MB - print(f" āœ“ {f}: {size:.1f} MB") - - print(f"\nšŸŽ‰ Gigaspeech model ready!") - print(f"šŸ“ Location: {os.path.abspath(model_dir)}") - print("\nšŸš€ You can now start your server with:") - print(" python app.py") - - return True - else: - print("āŒ Some files are missing after extraction") - return False - - except Exception as e: - print(f"āŒ Download failed: {e}") - return False - -if __name__ == "__main__": - print("Manual Gigaspeech Model Downloader") - print("Use this if automatic download fails") - print() - - success = download_gigaspeech_manual() - - if success: - print("\nšŸŽÆ SUCCESS! Your English-only ASR model is ready!") - print("āœ… 100% English-only") - print("āœ… Large vocabulary (GigaSpeech)") - print("āœ… Perfect for multiple kids") - print("āœ… Fast Zipformer architecture") - else: - print("\nāš ļø Manual download failed.") - print("You can try:") - print("1. Check your internet connection") - print("2. Run the script again") - print("3. Use a different ASR model (SherpaWhisperTinyEN)") \ No newline at end of file diff --git a/test_concurrent_clients.py b/test_concurrent_clients.py deleted file mode 100644 index 26ed66c73..000000000 --- a/test_concurrent_clients.py +++ /dev/null @@ -1,141 +0,0 @@ -#!/usr/bin/env python3 -""" -Test script for concurrent client connections to Zipformer Streaming English ASR -Usage: python test_concurrent_clients.py -""" - -import asyncio -import websockets -import json -import time -import threading -from concurrent.futures import ThreadPoolExecutor - -class ConcurrentASRTester: - def __init__(self, server_url="ws://localhost:8000/xiaozhi/v1/"): - self.server_url = server_url - self.results = [] - self.lock = threading.Lock() - - async def single_client_test(self, client_id, test_duration=10): - """Simulate a single client connection""" - try: - async with websockets.connect(self.server_url) as websocket: - start_time = time.time() - requests_sent = 0 - responses_received = 0 - - print(f"Client {client_id}: Connected") - - # Send test messages for specified duration - while time.time() - start_time < test_duration: - # Send a test audio message (mock) - test_message = { - "type": "audio", - "data": "test_audio_data", - "session_id": f"client_{client_id}_{requests_sent}" - } - - await websocket.send(json.dumps(test_message)) - requests_sent += 1 - - # Wait for response - try: - response = await asyncio.wait_for(websocket.recv(), timeout=5.0) - responses_received += 1 - except asyncio.TimeoutError: - print(f"Client {client_id}: Timeout waiting for response") - - await asyncio.sleep(0.5) # Simulate natural speech pauses - - with self.lock: - self.results.append({ - 'client_id': client_id, - 'requests_sent': requests_sent, - 'responses_received': responses_received, - 'success_rate': responses_received / requests_sent if requests_sent > 0 else 0, - 'duration': time.time() - start_time - }) - - print(f"Client {client_id}: Completed - {requests_sent} requests, {responses_received} responses") - - except Exception as e: - print(f"Client {client_id}: Error - {e}") - with self.lock: - self.results.append({ - 'client_id': client_id, - 'error': str(e) - }) - - async def run_concurrent_test(self, num_clients=5, test_duration=10): - """Run concurrent client tests""" - print(f"Starting concurrent test with {num_clients} clients for {test_duration} seconds each") - - # Create tasks for all clients - tasks = [] - for i in range(num_clients): - task = asyncio.create_task(self.single_client_test(i + 1, test_duration)) - tasks.append(task) - - # Wait for all clients to complete - await asyncio.gather(*tasks, return_exceptions=True) - - # Print results - self.print_results() - - def print_results(self): - """Print test results""" - print("\n" + "="*60) - print("CONCURRENT CLIENT TEST RESULTS") - print("="*60) - - successful_clients = [r for r in self.results if 'error' not in r] - failed_clients = [r for r in self.results if 'error' in r] - - if successful_clients: - total_requests = sum(r['requests_sent'] for r in successful_clients) - total_responses = sum(r['responses_received'] for r in successful_clients) - avg_success_rate = sum(r['success_rate'] for r in successful_clients) / len(successful_clients) - - print(f"Successful Clients: {len(successful_clients)}") - print(f"Failed Clients: {len(failed_clients)}") - print(f"Total Requests Sent: {total_requests}") - print(f"Total Responses Received: {total_responses}") - print(f"Overall Success Rate: {total_responses/total_requests*100:.1f}%") - print(f"Average Client Success Rate: {avg_success_rate*100:.1f}%") - - print("\nPer-Client Results:") - for result in successful_clients: - print(f" Client {result['client_id']}: {result['success_rate']*100:.1f}% success rate") - - if failed_clients: - print(f"\nFailed Clients: {len(failed_clients)}") - for result in failed_clients: - print(f" Client {result['client_id']}: {result['error']}") - -def main(): - """Main test function""" - tester = ConcurrentASRTester() - - print("Testing Zipformer Streaming English ASR with multiple concurrent clients") - print("Make sure your server is running with SherpaZipformerStreamingEN selected") - - # Test different client loads - test_scenarios = [ - (2, 10), # 2 clients for 10 seconds - (5, 10), # 5 clients for 10 seconds - (10, 10), # 10 clients for 10 seconds - ] - - for num_clients, duration in test_scenarios: - print(f"\n{'='*60}") - print(f"TESTING: {num_clients} concurrent clients") - print(f"{'='*60}") - - asyncio.run(tester.run_concurrent_test(num_clients, duration)) - tester.results.clear() # Clear results for next test - - input("Press Enter to continue to next test...") - -if __name__ == "__main__": - main() \ No newline at end of file diff --git a/test_english_asr.py b/test_english_asr.py deleted file mode 100644 index d6268bf36..000000000 --- a/test_english_asr.py +++ /dev/null @@ -1,72 +0,0 @@ -#!/usr/bin/env python3 -""" -Test script for English-only Sherpa-ONNX ASR models -Usage: python test_english_asr.py -""" - -import sys -import os -sys.path.append('main/xiaozhi-server') - -from core.providers.asr.sherpa_onnx_local import ASRProvider - -def test_english_models(): - """Test different English-only Sherpa-ONNX models""" - - models_to_test = [ - { - "name": "Whisper Tiny English (Smallest)", - "config": { - "model_dir": "models/sherpa-onnx-whisper-tiny.en", - "model_type": "whisper", - "output_dir": "tmp/" - } - }, - { - "name": "Whisper Base English (Good Balance)", - "config": { - "model_dir": "models/sherpa-onnx-whisper-base.en", - "model_type": "whisper", - "output_dir": "tmp/" - } - }, - { - "name": "Zipformer English (RECOMMENDED - Verified Working)", - "config": { - "model_dir": "models/sherpa-onnx-zipformer-en-2023-04-01", - "model_type": "zipformer", - "output_dir": "tmp/" - } - }, - { - "name": "Zipformer Gigaspeech English (Large Vocabulary)", - "config": { - "model_dir": "models/sherpa-onnx-zipformer-gigaspeech-2023-12-12", - "model_type": "zipformer", - "output_dir": "tmp/" - } - }, - { - "name": "Paraformer English (Alternative Architecture)", - "config": { - "model_dir": "models/sherpa-onnx-paraformer-en-2023-10-24", - "model_type": "paraformer", - "output_dir": "tmp/" - } - } - ] - - for model_info in models_to_test: - print(f"\n=== Testing {model_info['name']} ===") - try: - asr = ASRProvider(model_info['config'], delete_audio_file=False) - print(f"āœ… {model_info['name']} initialized successfully") - print(f" Model directory: {model_info['config']['model_dir']}") - print(f" Model type: {model_info['config']['model_type']}") - except Exception as e: - print(f"āŒ {model_info['name']} failed to initialize: {e}") - -if __name__ == "__main__": - print("Testing English-only Sherpa-ONNX ASR models...") - test_english_models() - print("\nTest completed!") \ No newline at end of file diff --git a/test_fallback_tts.py b/test_fallback_tts.py deleted file mode 100644 index ed9c4d668..000000000 --- a/test_fallback_tts.py +++ /dev/null @@ -1,101 +0,0 @@ -#!/usr/bin/env python3 -""" -Test script for SiliconFlow TTS with ElevenLabs fallback -""" - -import sys -import os -import asyncio -import yaml - -# Add the main directory to Python path -sys.path.append(os.path.join(os.path.dirname(__file__), 'main', 'xiaozhi-server')) - -from core.providers.tts.siliconflow import TTSProvider - -def load_config(): - """Load configuration from .config.yaml""" - config_path = os.path.join(os.path.dirname(__file__), 'main', 'xiaozhi-server', 'data', '.config.yaml') - try: - with open(config_path, 'r', encoding='utf-8') as f: - config = yaml.safe_load(f) - return config.get('TTS', {}).get('siliconflow', {}) - except Exception as e: - print(f"Warning: Could not load config from {config_path}: {e}") - return {} - -async def test_fallback_functionality(): - """Test SiliconFlow TTS with ElevenLabs fallback""" - - # Load configuration from .config.yaml - config = load_config() - - if not config: - print("āŒ Could not load SiliconFlow configuration") - return - - print("āœ… Loaded SiliconFlow configuration with fallback") - print(f"Primary: SiliconFlow CosyVoice ({config.get('model', 'N/A')})") - print(f"Fallback: {'Enabled' if config.get('fallback', {}).get('enabled') else 'Disabled'}") - - try: - # Initialize TTS provider with fallback - tts_provider = TTSProvider(config, delete_audio_file=False) - - # Test text - test_text = "Testing SiliconFlow with ElevenLabs fallback functionality." - - print(f"\nšŸ”„ Testing with text: {test_text}") - print(f"Primary voice: {tts_provider.voice}") - print(f"Fallback available: {'Yes' if tts_provider.fallback_provider else 'No'}") - - # Generate speech (this will try SiliconFlow first, then ElevenLabs if it fails) - output_file = "test_fallback_tts.mp3" - - print(f"\nšŸŽÆ Attempting TTS generation...") - await tts_provider.text_to_speak(test_text, output_file) - - if os.path.exists(output_file): - print(f"āœ… Success! Audio file generated: {output_file}") - print(f"File size: {os.path.getsize(output_file)} bytes") - else: - print("āŒ Failed to generate audio file") - - except Exception as e: - print(f"āŒ Error: {e}") - -async def test_forced_fallback(): - """Test fallback by using invalid SiliconFlow token""" - - config = load_config() - if not config: - return - - # Force fallback by using invalid token - config['access_token'] = 'invalid_token_to_force_fallback' - - print(f"\nšŸ”„ Testing forced fallback (invalid SiliconFlow token)...") - - try: - tts_provider = TTSProvider(config, delete_audio_file=False) - - test_text = "This should use ElevenLabs fallback due to invalid SiliconFlow token." - output_file = "test_forced_fallback.mp3" - - await tts_provider.text_to_speak(test_text, output_file) - - if os.path.exists(output_file): - print(f"āœ… Fallback successful! Audio file generated: {output_file}") - print(f"File size: {os.path.getsize(output_file)} bytes") - else: - print("āŒ Fallback failed") - - except Exception as e: - print(f"āŒ Both providers failed: {e}") - -if __name__ == "__main__": - print("Testing SiliconFlow TTS with ElevenLabs Fallback...") - print("=" * 60) - - asyncio.run(test_fallback_functionality()) - asyncio.run(test_forced_fallback()) \ No newline at end of file diff --git a/test_gigaspeech_download.py b/test_gigaspeech_download.py deleted file mode 100644 index 1c8a39ec2..000000000 --- a/test_gigaspeech_download.py +++ /dev/null @@ -1,79 +0,0 @@ -#!/usr/bin/env python3 -""" -Test script to verify Gigaspeech model download from GitHub -""" - -import os -import sys -import urllib.request -import tarfile - -def test_gigaspeech_download(): - """Test downloading Gigaspeech model from GitHub""" - - model_dir = "models/sherpa-onnx-zipformer-gigaspeech-2023-12-12" - url = "https://github.com/k2-fsa/sherpa-onnx/releases/download/asr-models/sherpa-onnx-zipformer-gigaspeech-2023-12-12.tar.bz2" - - print("šŸ” Testing Gigaspeech model download from GitHub...") - print(f"URL: {url}") - print(f"Target directory: {model_dir}") - - # Check if model already exists - expected_files = [ - "encoder-epoch-30-avg-9.onnx", - "decoder-epoch-30-avg-9.onnx", - "joiner-epoch-30-avg-9.onnx", - "tokens.txt" - ] - - all_exist = all(os.path.exists(os.path.join(model_dir, f)) for f in expected_files) - - if all_exist: - print("āœ… All model files already exist!") - for f in expected_files: - file_path = os.path.join(model_dir, f) - size = os.path.getsize(file_path) / (1024*1024) # MB - print(f" {f}: {size:.1f} MB") - return True - - print("šŸ“„ Model files not found, testing download...") - - try: - # Create directory - os.makedirs(model_dir, exist_ok=True) - - # Test URL accessibility - print("🌐 Testing URL accessibility...") - response = urllib.request.urlopen(url) - content_length = response.headers.get('Content-Length') - if content_length: - size_mb = int(content_length) / (1024*1024) - print(f"āœ… URL accessible, file size: {size_mb:.1f} MB") - else: - print("āœ… URL accessible") - response.close() - - print("āœ… GitHub download test successful!") - print("\nšŸŽ‰ The Gigaspeech model can be downloaded from GitHub!") - print("Your server should be able to download it automatically.") - - return True - - except Exception as e: - print(f"āŒ Download test failed: {e}") - return False - -if __name__ == "__main__": - print("Testing Gigaspeech model availability...") - success = test_gigaspeech_download() - - if success: - print("\nšŸŽÆ CONFIRMED: Gigaspeech model is available!") - print("āœ… English-only model") - print("āœ… Large vocabulary (GigaSpeech dataset)") - print("āœ… Perfect for multiple kids") - print("āœ… GitHub download working") - print("\nYour server should start successfully now!") - else: - print("\nāš ļø There might be a network issue.") - print("Try running your server - it will attempt the download.") \ No newline at end of file diff --git a/test_whisper_model.py b/test_whisper_model.py deleted file mode 100644 index 57452ee56..000000000 --- a/test_whisper_model.py +++ /dev/null @@ -1,59 +0,0 @@ -#!/usr/bin/env python3 -""" -Test script to verify Whisper model initialization -""" - -import sys -import os -sys.path.append('main/xiaozhi-server') - -def test_whisper_initialization(): - """Test Whisper model initialization with correct parameters""" - try: - import sherpa_onnx - - # Test the exact parameters we're using - model_dir = "models/sherpa-onnx-whisper-tiny.en" - - # Check if model files exist - encoder_path = os.path.join(model_dir, "tiny.en-encoder.onnx") - decoder_path = os.path.join(model_dir, "tiny.en-decoder.onnx") - tokens_path = os.path.join(model_dir, "tiny.en-tokens.txt") - - print("Checking model files...") - print(f"Encoder exists: {os.path.exists(encoder_path)}") - print(f"Decoder exists: {os.path.exists(decoder_path)}") - print(f"Tokens exists: {os.path.exists(tokens_path)}") - - if all(os.path.exists(p) for p in [encoder_path, decoder_path, tokens_path]): - print("\nāœ… All model files found!") - - print("Testing Whisper model initialization...") - model = sherpa_onnx.OfflineRecognizer.from_whisper( - encoder=encoder_path, - decoder=decoder_path, - tokens=tokens_path, - num_threads=2, - decoding_method="greedy_search", - debug=False, - ) - print("āœ… Whisper model initialized successfully!") - return True - else: - print("āŒ Model files not found. Please run the server first to download them.") - return False - - except Exception as e: - print(f"āŒ Error: {e}") - return False - -if __name__ == "__main__": - print("Testing Whisper Tiny English model initialization...") - success = test_whisper_initialization() - - if success: - print("\nšŸŽ‰ Your Whisper model is ready!") - print("The server should start successfully now.") - else: - print("\nāš ļø There might be an issue with the model setup.") - print("Try running the server to download the model files first.") \ No newline at end of file