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)