Spaces:
Runtime error
Runtime error
File size: 11,926 Bytes
5d53bc6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 | #!/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) |