File size: 10,767 Bytes
0943038
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""

Usage examples for Translation AI Agent

"""

import os
import time
from hf_translation_ai_agent.app_old import TranslationAIAgent
from utils import AudioProcessor, LanguageDetector, MetricsTracker
from config import config

def example_text_translation():
    """Example: Text translation"""
    print("🔤 Text Translation Example")
    print("=" * 40)
    
    agent = TranslationAIAgent()
    
    # Example texts in different languages
    examples = [
        ("Hello, how are you today?", "en", "es"),
        ("Bonjour, comment allez-vous?", "fr", "en"),
        ("Hola, ¿cómo estás hoy?", "es", "vi"),
        ("こんにちは、元気ですか?", "ja", "en"),
        ("Xin chào, bạn khỏe không?", "vi", "en")
    ]
    
    for text, src_lang, tgt_lang in examples:
        print(f"\n📝 Original ({src_lang}): {text}")
        
        start_time = time.time()
        translated = agent.translate_text(text, src_lang, tgt_lang)
        processing_time = time.time() - start_time
        
        print(f"🔄 Translated ({tgt_lang}): {translated}")
        print(f"⏱️  Processing time: {processing_time:.2f}s")

def example_audio_processing():
    """Example: Audio processing (mock)"""
    print("\n🎵 Audio Processing Example")
    print("=" * 40)
    
    agent = TranslationAIAgent()
    processor = AudioProcessor()
    
    # Create mock audio file
    import numpy as np
    import soundfile as sf
    
    # Generate test audio (sine wave)
    duration = 3.0  # seconds
    sample_rate = 16000
    frequency = 440  # Hz
    
    t = np.linspace(0, duration, int(sample_rate * duration), False)
    audio_data = 0.3 * np.sin(2 * np.pi * frequency * t)
    
    # Save to temporary file
    temp_audio_path = "/tmp/test_audio.wav"
    sf.write(temp_audio_path, audio_data, sample_rate)
    
    print(f"📁 Created test audio: {temp_audio_path}")
    print(f"⏱️  Duration: {processor.get_audio_duration(temp_audio_path):.2f}s")
    
    # Test speech recognition
    print("\n🎤 Speech Recognition:")
    transcribed = agent.speech_to_text(temp_audio_path, "en")
    print(f"📝 Transcribed: {transcribed}")
    
    # Test complete audio translation
    print("\n🔄 Complete Audio Translation:")
    source_lang, target_lang = "en", "es"
    
    start_time = time.time()
    transcribed, translated, audio_output = agent.process_audio_translation(
        temp_audio_path, source_lang, target_lang
    )
    processing_time = time.time() - start_time
    
    print(f"📝 Transcribed: {transcribed}")
    print(f"🔄 Translated: {translated}")
    print(f"🔊 Audio output: {audio_output}")
    print(f"⏱️  Total processing time: {processing_time:.2f}s")
    
    # Cleanup
    if os.path.exists(temp_audio_path):
        os.remove(temp_audio_path)

def example_language_detection():
    """Example: Language detection"""
    print("\n🔍 Language Detection Example")
    print("=" * 40)
    
    detector = LanguageDetector(config.LANGUAGE_KEYWORDS)
    
    test_texts = [
        "Hello, this is a test in English",
        "Hola, esto es una prueba en español", 
        "Bonjour, ceci est un test en français",
        "Hallo, das ist ein Test auf Deutsch",
        "Xin chào, đây là một bài kiểm tra bằng tiếng Việt"
    ]
    
    for text in test_texts:
        detected_lang = detector.detect(text)
        confidence = detector.get_confidence(text, detected_lang)
        lang_name = config.get_language_name(detected_lang)
        
        print(f"📝 Text: {text}")
        print(f"🔍 Detected: {detected_lang} ({lang_name})")
        print(f"📊 Confidence: {confidence:.2f}")
        print()

def example_batch_translation():
    """Example: Batch translation"""
    print("\n📦 Batch Translation Example")
    print("=" * 40)
    
    agent = TranslationAIAgent()
    
    # Sample documents in different languages
    documents = [
        {
            "id": "doc1",
            "text": "Welcome to our AI translation service. We support multiple languages.",
            "source_lang": "en"
        },
        {
            "id": "doc2", 
            "text": "La inteligencia artificial está transformando el mundo.",
            "source_lang": "es"
        },
        {
            "id": "doc3",
            "text": "L'intelligence artificielle change notre façon de travailler.",
            "source_lang": "fr"
        }
    ]
    
    target_languages = ["vi", "ja", "de"]
    
    print(f"📄 Translating {len(documents)} documents to {len(target_languages)} languages...")
    
    results = []
    total_start_time = time.time()
    
    for doc in documents:
        doc_results = {"id": doc["id"], "original": doc["text"], "translations": {}}
        
        for target_lang in target_languages:
            if doc["source_lang"] != target_lang:
                start_time = time.time()
                translated = agent.translate_text(
                    doc["text"], 
                    doc["source_lang"], 
                    target_lang
                )
                processing_time = time.time() - start_time
                
                doc_results["translations"][target_lang] = {
                    "text": translated,
                    "processing_time": processing_time
                }
        
        results.append(doc_results)
    
    total_time = time.time() - total_start_time
    
    # Display results
    for result in results:
        print(f"\n📄 Document {result['id']}:")
        print(f"   Original: {result['original']}")
        
        for lang, translation in result["translations"].items():
            lang_name = config.get_language_name(lang)
            print(f"   {lang} ({lang_name}): {translation['text']}")
            print(f"   Processing time: {translation['processing_time']:.2f}s")
    
    print(f"\n⏱️  Total processing time: {total_time:.2f}s")
    print(f"📊 Average per translation: {total_time / (len(documents) * len(target_languages)):.2f}s")

def example_performance_monitoring():
    """Example: Performance monitoring"""
    print("\n📊 Performance Monitoring Example")
    print("=" * 40)
    
    agent = TranslationAIAgent()
    tracker = MetricsTracker()
    
    # Simulate various operations
    operations = [
        ("translation", "Hello world", "en", "es"),
        ("translation", "How are you?", "en", "fr"),
        ("translation", "Good morning", "en", "de"),
    ]
    
    for operation_type, text, src_lang, tgt_lang in operations:
        start_time = time.time()
        
        if operation_type == "translation":
            result = agent.translate_text(text, src_lang, tgt_lang)
            processing_time = time.time() - start_time
            tracker.record_translation(processing_time)
            
            print(f"✅ Translation: {text}{result} ({processing_time:.2f}s)")
    
    # Display performance stats
    stats = tracker.get_stats()
    print(f"\n📈 Performance Statistics:")
    print(f"   Translations: {stats['translations']}")
    print(f"   Speech recognitions: {stats['speech_recognitions']}")
    print(f"   Text-to-speech: {stats['text_to_speech']}")
    print(f"   Total processing time: {stats['total_processing_time']:.2f}s")
    print(f"   Average processing time: {stats['average_processing_time']:.2f}s")
    print(f"   Operations per minute: {stats['operations_per_minute']:.1f}")
    print(f"   Uptime: {stats['uptime_seconds']:.1f}s")
    print(f"   Errors: {stats['errors']}")

def example_api_usage():
    """Example: API usage patterns"""
    print("\n🔌 API Usage Examples")
    print("=" * 40)
    
    # Example 1: Simple translation
    print("1️⃣ Simple Translation:")
    agent = TranslationAIAgent()
    result = agent.translate_text("Hello", "en", "es")
    print(f"   Input: 'Hello' (en)")
    print(f"   Output: '{result}' (es)")
    
    # Example 2: Language detection + translation
    print("\n2️⃣ Auto-detect + Translation:")
    detector = LanguageDetector(config.LANGUAGE_KEYWORDS)
    text = "Bonjour le monde"
    detected_lang = detector.detect(text)
    translated = agent.translate_text(text, detected_lang, "en")
    print(f"   Input: '{text}'")
    print(f"   Detected: {detected_lang}")
    print(f"   Translated: '{translated}'")
    
    # Example 3: Translation history
    print("\n3️⃣ Translation History:")
    history = agent.get_translation_history()
    print(f"   Recent translations: {len(history)}")
    for i, entry in enumerate(history[-3:], 1):  # Show last 3
        print(f"   {i}. {entry['original']}{entry['translated']}")
        print(f"      ({entry['source_lang']}{entry['target_lang']})")

def example_error_handling():
    """Example: Error handling"""
    print("\n❌ Error Handling Examples")
    print("=" * 40)
    
    agent = TranslationAIAgent()
    
    # Test with empty input
    print("1️⃣ Empty input:")
    result = agent.translate_text("", "en", "es")
    print(f"   Result: '{result}'")
    
    # Test with very long input
    print("\n2️⃣ Long input:")
    long_text = "This is a very long text. " * 100
    result = agent.translate_text(long_text[:100] + "...", "en", "es")
    print(f"   Result: {result[:50]}...")
    
    # Test with invalid language codes
    print("\n3️⃣ Invalid language:")
    result = agent.translate_text("Hello", "xx", "yy")  # Invalid codes
    print(f"   Result: '{result}'")
    
    # Test with non-existent audio file
    print("\n4️⃣ Invalid audio file:")
    result = agent.speech_to_text("nonexistent.wav", "en")
    print(f"   Result: '{result}'")

def run_all_examples():
    """Run all examples"""
    print("🚀 Translation AI Agent - Examples")
    print("=" * 50)
    
    try:
        example_text_translation()
        example_language_detection()
        example_batch_translation() 
        example_performance_monitoring()
        example_api_usage()
        example_error_handling()
        
        # Skip audio example if running in environment without audio support
        try:
            example_audio_processing()
        except Exception as e:
            print(f"\n⚠️  Skipped audio example: {e}")
        
        print("\n✅ All examples completed successfully!")
        
    except Exception as e:
        print(f"\n❌ Error running examples: {e}")

if __name__ == "__main__":
    run_all_examples()