Spaces:
Build error
Build error
Create voice_translation_simple.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349import speech_recognition as srfrom gtts import gTTSimport osimport tempfileimport timeimport urllib.parseimport requestsimport json
class SimpleVoiceTranslator: def __init__(self, target_lang='es'): """ Simple Voice Translation Agent Args: target_lang: Target language code (default: Spanish) """ self.recognizer = sr.Recognizer() self.target_lang = target_lang # Common languages mapping self.languages = { 'en': 'English', 'es': 'Spanish', 'fr': 'French', 'de': 'German', 'it': 'Italian', 'pt': 'Portuguese', 'ru': 'Russian', 'ja': 'Japanese', 'ko': 'Korean', 'zh': 'Chinese', 'hi': 'Hindi', 'ar': 'Arabic', } print(f"\n{'='*50}") print("๐ค SIMPLE VOICE TRANSLATION AGENT") print(f"{'='*50}") print(f"Target Language: {self.languages.get(target_lang, target_lang)}") print("Will auto-detect source language") print(f"{'='*50}\n") def record_speech(self): """Record and convert speech to text""" try: with sr.Microphone() as source: print("Adjusting for ambient noise...") self.recognizer.adjust_for_ambient_noise(source, duration=1) print("๐ค Listening... Speak now!") print("(You have 10 seconds to speak)") try: audio = self.recognizer.listen(source, timeout=10, phrase_time_limit=10) text = self.recognizer.recognize_google(audio) print(f"โ Recognized: {text}") return text except sr.WaitTimeoutError: print("โ No speech detected within 10 seconds") return None except Exception as e: print(f"โ Microphone error: {e}") print("\n๐ก Troubleshooting tips:") print("1. Check if microphone is connected") print("2. Grant microphone permissions") print("3. Try using text input instead") return None def translate_text(self, text, target_lang='es'): """ Translate text using free MyMemory API Works without any special libraries """ if not text or len(text.strip()) == 0: return "" try: # Encode the text for URL encoded_text = urllib.parse.quote(text) # MyMemory Translation API (free) url = f"https://api.mymemory.translated.net/get?q={encoded_text}&langpair=en|{target_lang}" response = requests.get(url, timeout=10) if response.status_code == 200: data = response.json() translated = data['responseData']['translatedText'] # Clean up translation if translated: return translated else: return self.simple_translation_fallback(text, target_lang) else: print(f"Translation API error: {response.status_code}") return self.simple_translation_fallback(text, target_lang) except Exception as e: print(f"Translation error: {e}") return self.simple_translation_fallback(text, target_lang) def simple_translation_fallback(self, text, target_lang): """Simple fallback translation using dictionary""" text_lower = text.lower() # Common phrases dictionary translations = { 'es': { # Spanish 'hello': 'hola', 'hi': 'hola', 'how are you': 'cรณmo estรกs', 'good morning': 'buenos dรญas', 'good afternoon': 'buenas tardes', 'good evening': 'buenas noches', 'thank you': 'gracias', 'please': 'por favor', 'sorry': 'lo siento', 'yes': 'sรญ', 'no': 'no', 'goodbye': 'adiรณs', 'what is your name': 'cรณmo te llamas', 'my name is': 'me llamo', 'where is': 'dรณnde estรก', 'i need help': 'necesito ayuda', 'i love you': 'te quiero', 'how much': 'cuรกnto', 'water': 'agua', 'food': 'comida', 'help': 'ayuda', 'doctor': 'mรฉdico', 'police': 'policรญa', 'hello my name is': 'hola me llamo', 'nice to meet you': 'mucho gusto', 'you are welcome': 'de nada' }, 'fr': { # French 'hello': 'bonjour', 'hi': 'salut', 'how are you': 'comment allez-vous', 'good morning': 'bonjour', 'good afternoon': 'bon aprรจs-midi', 'good evening': 'bonsoir', 'thank you': 'merci', 'please': 's\'il vous plaรฎt', 'sorry': 'dรฉsolรฉ', 'yes': 'oui', 'no': 'non', 'goodbye': 'au revoir', 'what is your name': 'comment vous appelez-vous', 'my name is': 'je m\'appelle', 'where is': 'oรน est', 'i need help': 'j\'ai besoin d\'aide' }, 'de': { # German 'hello': 'hallo', 'hi': 'hallo', 'how are you': 'wie geht es dir', 'good morning': 'guten morgen', 'good afternoon': 'guten nachmittag', 'good evening': 'guten abend', 'thank you': 'danke', 'please': 'bitte', 'sorry': 'entschuldigung', 'yes': 'ja', 'no': 'nein', 'goodbye': 'auf wiedersehen', 'what is your name': 'wie heiรt du', 'my name is': 'ich heiรe', 'where is': 'wo ist', 'i need help': 'ich brauche hilfe' } } if target_lang in translations: # Check for exact phrase matches first for phrase, translation in translations[target_lang].items(): if phrase in text_lower: # Preserve capitalization if text[0].isupper(): return translation.capitalize() return translation # If no phrase match, try word by word words = text_lower.split() translated_words = [] for word in words: # Simple word mapping (very basic) word_map = { 'hello': {'es': 'hola', 'fr': 'bonjour', 'de': 'hallo'}, 'hi': {'es': 'hola', 'fr': 'salut', 'de': 'hallo'}, 'thank': {'es': 'gracias', 'fr': 'merci', 'de': 'danke'}, 'please': {'es': 'por favor', 'fr': 's\'il vous plaรฎt', 'de': 'bitte'}, 'yes': {'es': 'sรญ', 'fr': 'oui', 'de': 'ja'}, 'no': {'es': 'no', 'fr': 'non', 'de': 'nein'}, } if word in word_map and target_lang in word_map[word]: translated_words.append(word_map[word][target_lang]) else: translated_words.append(f"[{word}]") return ' '.join(translated_words) return f"[Translated to {target_lang}]: {text}" def text_to_speech(self, text, lang='es'): """Convert text to speech using gTTS""" try: print(f"Generating speech in {self.languages.get(lang, lang)}...") # Clean language code if lang == 'zh-cn': lang = 'zh' # Create gTTS object tts = gTTS(text=text, lang=lang, slow=False) # Save to temporary file timestamp = int(time.time()) temp_file = f"translation_{timestamp}.mp3" tts.save(temp_file) # Play the audio (platform-specific) print("Playing audio...") # For Windows if os.name == 'nt': os.system(f'start {temp_file}') # For macOS elif os.name == 'posix' and sys.platform == 'darwin': os.system(f'afplay {temp_file}') # For Linux else: os.system(f'mpg123 {temp_file} 2>/dev/null || mplayer {temp_file} 2>/dev/null || echo "Install mpg123 or mplayer to play audio"') print(f"Audio saved as: {temp_file}") print("You can play it with any media player") except Exception as e: print(f"Speech generation error: {e}") print(f"Text was: {text}") print("You can copy this text to any translation app") def run(self): """Main conversation loop""" conversation_count = 0 while True: print(f"\n{'โ'*50}") print("Options:") print("1. Speak and translate") print("2. Type text to translate") print("3. Change target language") print("4. Show supported languages") print("5. Exit") print(f"{'โ'*50}") choice = input("Choose (1-5): ").strip() if choice == '1': # Speech input original_text = self.record_speech() if original_text: conversation_count += 1 print(f"\n๐ฌ Conversation #{conversation_count}") print(f"๐ฃ๏ธ You said: {original_text}") # Translate translated_text = self.translate_text(original_text, self.target_lang) print(f"๐ Translation: {translated_text}") # Speak translation self.text_to_speech(translated_text, self.target_lang) elif choice == '2': # Text input original_text = input("\nEnter text to translate: ").strip() if original_text: conversation_count += 1 print(f"\n๐ฌ Conversation #{conversation_count}") print(f"๐ You entered: {original_text}") # Translate translated_text = self.translate_text(original_text, self.target_lang) print(f"๐ Translation: {translated_text}") # Ask if user wants to hear it hear = input("\nDo you want to hear the translation? (y/n): ").strip().lower() if hear == 'y': self.text_to_speech(translated_text, self.target_lang) elif choice == '3': # Change language print("\n๐ Supported languages:") for code, name in self.languages.items(): print(f" {code}: {name}") new_lang = input("\nEnter language code: ").strip().lower() if new_lang in self.languages: self.target_lang = new_lang print(f"โ Target language changed to {self.languages[new_lang]}") else: print(f"โ Invalid language code. Current: {self.target_lang}") elif choice == '4': print("\n๐ Supported languages:") for code, name in self.languages.items(): print(f" {code}: {name}") print(f"\nCurrent target: {self.target_lang} ({self.languages.get(self.target_lang, 'Unknown')})") elif choice == '5': print("\n๐ Goodbye! Thanks for using Voice Translation!") break else: print("โ Invalid choice. Please enter 1-5")
def main(): """Main function""" print("\n" + "="*60) print("๐ SIMPLE VOICE TRANSLATION AGENT") print("="*60) print("This version uses minimal dependencies and should work!") print("="*60) # Check for required packages try: import speech_recognition import gtts print("โ Required packages are installed") except ImportError as e: print(f"โ Missing package: {e}") print("\nPlease install with:") print("pip install SpeechRecognition gTTS") return # Start translator translator = SimpleVoiceTranslator(target_lang='es') translator.run()
if __name__ == "__main__": main()voice_translation_simple.pyAdded+349