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