Test_Voice / test_local.py
ducnguyen1978's picture
Upload test_local.py
5d53bc6 verified
#!/usr/bin/env python3
"""
Local testing script for Translation AI Agent
Test functionality before deploying to HuggingFace Spaces
"""
import os
import sys
import time
import tempfile
import numpy as np
import soundfile as sf
from pathlib import Path
# Add current directory to path
sys.path.insert(0, os.path.dirname(__file__))
def test_imports():
"""Test if all required packages can be imported"""
print("๐Ÿ” Testing imports...")
packages = [
"gradio", "torch", "transformers", "librosa",
"soundfile", "numpy", "scipy"
]
missing_packages = []
for package in packages:
try:
__import__(package)
print(f" โœ… {package}")
except ImportError:
print(f" โŒ {package}")
missing_packages.append(package)
if missing_packages:
print(f"\nโš ๏ธ Missing packages: {', '.join(missing_packages)}")
print("Install with: pip install -r requirements.txt")
return False
print("โœ… All imports successful!")
return True
def test_config():
"""Test configuration loading"""
print("\nโš™๏ธ Testing configuration...")
try:
from config import config
print(f" โœ… Supported languages: {len(config.SUPPORTED_LANGUAGES)}")
print(f" โœ… Translation model: {config.TRANSLATION_MODEL}")
print(f" โœ… Speech model: {config.SPEECH_RECOGNITION_MODEL}")
print(f" โœ… TTS model: {config.TEXT_TO_SPEECH_MODEL}")
# Test language validation
assert config.validate_language("en")
assert config.validate_language("es")
assert not config.validate_language("xyz")
print("โœ… Configuration test passed!")
return True
except Exception as e:
print(f"โŒ Configuration test failed: {e}")
return False
def test_utils():
"""Test utility functions"""
print("\n๐Ÿ› ๏ธ Testing utilities...")
try:
from utils import AudioProcessor, LanguageDetector, FileManager
from config import config
# Test audio processor
processor = AudioProcessor()
# Create test audio
duration = 1.0
sample_rate = 16000
audio_data = 0.3 * np.sin(2 * np.pi * 440 * np.linspace(0, duration, int(sample_rate * duration), False))
temp_file = tempfile.NamedTemporaryFile(suffix='.wav', delete=False)
sf.write(temp_file.name, audio_data, sample_rate)
temp_file.close()
# Test loading audio
loaded_audio, sr = processor.load_audio(temp_file.name)
assert len(loaded_audio) > 0
assert sr == 16000
# Test duration
duration_calculated = processor.get_audio_duration(temp_file.name)
assert abs(duration_calculated - duration) < 0.1
# Test validation
assert processor.validate_audio_file(temp_file.name)
# Cleanup
os.unlink(temp_file.name)
# Test language detector
detector = LanguageDetector(config.LANGUAGE_KEYWORDS)
detected = detector.detect("Hello world how are you")
assert detected == "en"
detected = detector.detect("Hola mundo como estas")
assert detected == "es"
print("โœ… Utilities test passed!")
return True
except Exception as e:
print(f"โŒ Utilities test failed: {e}")
return False
def test_ai_agent():
"""Test AI Agent functionality"""
print("\n๐Ÿค– Testing AI Agent...")
try:
from hf_translation_ai_agent.app_old import TranslationAIAgent
agent = TranslationAIAgent()
# Test text translation (will be mock if models not loaded)
print(" Testing text translation...")
result = agent.translate_text("Hello world", "en", "es")
assert result is not None
assert len(result) > 0
print(f" โœ… Translation: 'Hello world' โ†’ '{result}'")
# Test language detection
print(" Testing language detection...")
detected = agent.detect_language("Hello how are you today")
assert detected in agent.supported_languages
print(f" โœ… Language detection: 'Hello...' โ†’ '{detected}'")
# Test audio processing (mock)
print(" Testing audio processing...")
# Create test audio file
duration = 2.0
sample_rate = 16000
audio_data = 0.1 * np.sin(2 * np.pi * 440 * np.linspace(0, duration, int(sample_rate * duration), False))
temp_file = tempfile.NamedTemporaryFile(suffix='.wav', delete=False)
sf.write(temp_file.name, audio_data, sample_rate)
temp_file.close()
# Test speech to text
transcription = agent.speech_to_text(temp_file.name, "en")
assert transcription is not None
print(f" โœ… Speech-to-text: '{transcription[:50]}...'")
# Test text to speech
tts_path = agent.text_to_speech("Hello world", "en")
if tts_path:
assert os.path.exists(tts_path)
print(f" โœ… Text-to-speech: generated {tts_path}")
# Cleanup TTS output
os.unlink(tts_path)
# Cleanup test audio
os.unlink(temp_file.name)
# Test translation history
history = agent.get_translation_history()
assert isinstance(history, list)
print(f" โœ… Translation history: {len(history)} entries")
print("โœ… AI Agent test passed!")
return True
except Exception as e:
print(f"โŒ AI Agent test failed: {e}")
import traceback
traceback.print_exc()
return False
def test_gradio_app():
"""Test Gradio app creation"""
print("\n๐Ÿ–ฅ๏ธ Testing Gradio app...")
try:
import gradio as gr
# Test basic Gradio functionality
def dummy_function(text):
return f"Processed: {text}"
# Create simple interface
interface = gr.Interface(
fn=dummy_function,
inputs=gr.Textbox(label="Input"),
outputs=gr.Textbox(label="Output"),
title="Test Interface"
)
assert interface is not None
print(" โœ… Basic Gradio interface created")
# Test our app import (without launching)
try:
# Import app but don't run it
import hf_translation_ai_agent.app_old as app_old
print(" โœ… Main app imported successfully")
except Exception as e:
print(f" โš ๏ธ App import warning: {e}")
print("โœ… Gradio app test passed!")
return True
except Exception as e:
print(f"โŒ Gradio app test failed: {e}")
return False
def test_deployment_readiness():
"""Test deployment readiness"""
print("\n๐Ÿš€ Testing deployment readiness...")
required_files = [
"app.py",
"requirements.txt",
"config.py",
"utils.py",
"README.md",
"Dockerfile"
]
missing_files = []
for file in required_files:
if not os.path.exists(file):
missing_files.append(file)
else:
print(f" โœ… {file}")
if missing_files:
print(f" โŒ Missing files: {', '.join(missing_files)}")
return False
# Check requirements.txt format
try:
with open("requirements.txt", "r") as f:
requirements = f.read()
assert "gradio" in requirements
assert "torch" in requirements
assert "transformers" in requirements
print(" โœ… requirements.txt format valid")
except Exception as e:
print(f" โŒ requirements.txt issue: {e}")
return False
# Check app.py has main execution
try:
with open("app.py", "r") as f:
content = f.read()
assert "if __name__ == \"__main__\":" in content
assert "demo.launch" in content
print(" โœ… app.py has proper launch code")
except Exception as e:
print(f" โŒ app.py issue: {e}")
return False
print("โœ… Deployment readiness test passed!")
return True
def run_all_tests():
"""Run all tests"""
print("๐Ÿงช Translation AI Agent - Local Testing")
print("=" * 60)
tests = [
("Imports", test_imports),
("Configuration", test_config),
("Utilities", test_utils),
("AI Agent", test_ai_agent),
("Gradio App", test_gradio_app),
("Deployment Readiness", test_deployment_readiness)
]
results = {}
for test_name, test_func in tests:
try:
results[test_name] = test_func()
except Exception as e:
print(f"โŒ {test_name} test crashed: {e}")
results[test_name] = False
# Summary
print("\n" + "=" * 60)
print("๐Ÿ“Š TEST SUMMARY")
print("=" * 60)
passed = sum(results.values())
total = len(results)
for test_name, result in results.items():
status = "โœ… PASS" if result else "โŒ FAIL"
print(f" {status} {test_name}")
print(f"\n๐Ÿ“ˆ Results: {passed}/{total} tests passed")
if passed == total:
print("๐ŸŽ‰ All tests passed! Ready for deployment!")
print("\n๐Ÿš€ Next steps:")
print(" 1. Create HuggingFace account")
print(" 2. Create new Space with Gradio SDK")
print(" 3. Upload files: app.py, requirements.txt, README.md")
print(" 4. Set Hardware to GPU Basic (recommended)")
print(" 5. Make Space public and enjoy!")
else:
print("โš ๏ธ Some tests failed. Please fix issues before deployment.")
return False
return True
def show_system_info():
"""Show system information"""
print("๐Ÿ’ป System Information")
print("=" * 30)
# Python version
print(f"๐Ÿ Python: {sys.version.split()[0]}")
# Platform
import platform
print(f"๐Ÿ’ป Platform: {platform.system()} {platform.release()}")
# Memory info (if available)
try:
import psutil
memory = psutil.virtual_memory()
print(f"๐Ÿ’พ RAM: {memory.total // (1024**3)}GB total, {memory.available // (1024**3)}GB available")
except ImportError:
print("๐Ÿ’พ RAM: psutil not available")
# GPU info
try:
import torch
if torch.cuda.is_available():
gpu_count = torch.cuda.device_count()
print(f"๐ŸŽฎ GPU: {gpu_count} CUDA device(s) available")
for i in range(gpu_count):
gpu_name = torch.cuda.get_device_name(i)
memory_gb = torch.cuda.get_device_properties(i).total_memory // (1024**3)
print(f" Device {i}: {gpu_name} ({memory_gb}GB)")
else:
print("๐ŸŽฎ GPU: No CUDA devices available")
except ImportError:
print("๐ŸŽฎ GPU: PyTorch not available")
print()
if __name__ == "__main__":
show_system_info()
success = run_all_tests()
if success:
print("\n๐Ÿค” Want to run examples? Execute:")
print(" python examples.py")
print("\n๐Ÿš€ Ready to launch locally? Execute:")
print(" python app.py")
sys.exit(0 if success else 1)