Spaces:
Runtime error
Runtime error
| #!/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) |