🎤 Voice Translator with Pinecone AI
Real-time translation with vector memory powered by Pinecone
import streamlit as st import speech_recognition as sr from gtts import gTTS import tempfile import os import base64 import requests import time import json from datetime import datetime import hashlib import numpy as np # Set page config st.set_page_config( page_title="Voice Translator with Pinecone AI", page_icon="🎤", layout="wide", initial_sidebar_state="expanded" ) # Initialize session state if 'pinecone_api_key' not in st.session_state: st.session_state.pinecone_api_key = None if 'pinecone_environment' not in st.session_state: st.session_state.pinecone_environment = None if 'pinecone_index' not in st.session_state: st.session_state.pinecone_index = None if 'target_lang' not in st.session_state: st.session_state.target_lang = 'es' if 'history' not in st.session_state: st.session_state.history = [] if 'input_text' not in st.session_state: st.session_state.input_text = "" if 'translated_text' not in st.session_state: st.session_state.translated_text = "" if 'audio_base64' not in st.session_state: st.session_state.audio_base64 = None if 'translation_memory' not in st.session_state: st.session_state.translation_memory = {} if 'pinecone_initialized' not in st.session_state: st.session_state.pinecone_initialized = False # Languages with gTTS support - ADDED INDIAN LANGUAGES LANGUAGES = { 'en': {'name': 'English', 'tts_code': 'en'}, 'es': {'name': 'Spanish', 'tts_code': 'es'}, 'fr': {'name': 'French', 'tts_code': 'fr'}, 'de': {'name': 'German', 'tts_code': 'de'}, 'it': {'name': 'Italian', 'tts_code': 'it'}, 'pt': {'name': 'Portuguese', 'tts_code': 'pt'}, 'ru': {'name': 'Russian', 'tts_code': 'ru'}, 'ja': {'name': 'Japanese', 'tts_code': 'ja'}, 'ko': {'name': 'Korean', 'tts_code': 'ko'}, 'zh': {'name': 'Chinese', 'tts_code': 'zh'}, # Indian Languages Added 'hi': {'name': 'Hindi (हिन्दी)', 'tts_code': 'hi'}, 'bn': {'name': 'Bengali (বাংলা)', 'tts_code': 'bn'}, 'te': {'name': 'Telugu (తెలుగు)', 'tts_code': 'te'}, 'mr': {'name': 'Marathi (मराठी)', 'tts_code': 'mr'}, 'ta': {'name': 'Tamil (தமிழ்)', 'tts_code': 'ta'}, 'ur': {'name': 'Urdu (اردو)', 'tts_code': 'ur'}, 'gu': {'name': 'Gujarati (ગુજરાતી)', 'tts_code': 'gu'}, 'kn': {'name': 'Kannada (ಕನ್ನಡ)', 'tts_code': 'kn'}, 'ml': {'name': 'Malayalam (മലയാളം)', 'tts_code': 'ml'}, 'or': {'name': 'Odia (ଓଡ଼ିଆ)', 'tts_code': 'or'}, 'pa': {'name': 'Punjabi (ਪੰਜਾਬੀ)', 'tts_code': 'pa'}, 'as': {'name': 'Assamese (অসমীয়া)', 'tts_code': 'as'}, 'mai': {'name': 'Maithili (मैथिली)', 'tts_code': 'mai'}, 'sat': {'name': 'Santali (ᱥᱟᱱᱛᱟᱲᱤ)', 'tts_code': 'sat'}, 'ks': {'name': 'Kashmiri (कॉशुर)', 'tts_code': 'ks'}, 'sd': {'name': 'Sindhi (سنڌي)', 'tts_code': 'sd'}, 'ne': {'name': 'Nepali (नेपाली)', 'tts_code': 'ne'}, 'doi': {'name': 'Dogri (डोगरी)', 'tts_code': 'doi'}, 'kok': {'name': 'Konkani (कोंकणी)', 'tts_code': 'kok'}, 'mni': {'name': 'Manipuri (মৈতৈলোন্)', 'tts_code': 'mni'}, 'bodo': {'name': 'Bodo (बर)', 'tts_code': 'brx'}, # Other languages remain same 'ar': {'name': 'Arabic', 'tts_code': 'ar'}, 'nl': {'name': 'Dutch', 'tts_code': 'nl'}, 'pl': {'name': 'Polish', 'tts_code': 'pl'}, 'sv': {'name': 'Swedish', 'tts_code': 'sv'}, 'tr': {'name': 'Turkish', 'tts_code': 'tr'}, 'vi': {'name': 'Vietnamese', 'tts_code': 'vi'}, 'th': {'name': 'Thai', 'tts_code': 'th'}, 'id': {'name': 'Indonesian', 'tts_code': 'id'}, 'fil': {'name': 'Filipino', 'tts_code': 'tl'}, 'sw': {'name': 'Swahili', 'tts_code': 'sw'}, } def initialize_pinecone(api_key, environment): """Initialize Pinecone connection""" try: # Pinecone API endpoint headers = { 'Api-Key': api_key, 'Content-Type': 'application/json', 'User-Agent': 'voice-translator/1.0' } # Test connection by listing indexes url = f"https://controller.{environment}.pinecone.io/databases" response = requests.get(url, headers=headers, timeout=10) if response.status_code == 200: st.session_state.pinecone_api_key = api_key st.session_state.pinecone_environment = environment st.session_state.pinecone_initialized = True return True, "✅ Pinecone connected successfully!" else: return False, f"❌ Pinecone connection failed: {response.status_code}" except Exception as e: return False, f"❌ Pinecone error: {str(e)}" def create_pinecone_index(index_name, dimension=768, metric='cosine'): """Create a new Pinecone index""" try: headers = { 'Api-Key': st.session_state.pinecone_api_key, 'Content-Type': 'application/json' } url = f"https://controller.{st.session_state.pinecone_environment}.pinecone.io/databases" data = { 'name': index_name, 'dimension': dimension, 'metric': metric, 'pods': 1, 'pod_type': 'p1.x1' } response = requests.post(url, json=data, headers=headers, timeout=30) if response.status_code == 201: st.session_state.pinecone_index = index_name return True, f"✅ Index '{index_name}' created successfully!" else: return False, f"❌ Index creation failed: {response.status_code}" except Exception as e: return False, f"❌ Index creation error: {str(e)}" def get_text_embedding(text): """Generate a simple embedding for text (simulating Pinecone embeddings)""" # This is a simplified embedding - in production, use actual embedding models text_hash = hashlib.md5(text.encode()).hexdigest() # Generate a deterministic vector based on text hash np.random.seed(int(text_hash[:8], 16)) embedding = np.random.randn(768).astype(np.float32) # Normalize the embedding embedding = embedding / np.linalg.norm(embedding) return embedding.tolist() def upsert_to_pinecone(index_name, vectors): """Upsert vectors to Pinecone index""" try: headers = { 'Api-Key': st.session_state.pinecone_api_key, 'Content-Type': 'application/json' } url = f"https://{index_name}.svc.{st.session_state.pinecone_environment}.pinecone.io/vectors/upsert" data = { 'vectors': vectors, 'namespace': 'translations' } response = requests.post(url, json=data, headers=headers, timeout=30) if response.status_code == 200: return True, f"✅ {len(vectors)} vectors upserted successfully!" else: return False, f"❌ Upsert failed: {response.status_code}" except Exception as e: return False, f"❌ Upsert error: {str(e)}" def query_pinecone(index_name, vector, top_k=5): """Query Pinecone index for similar vectors""" try: headers = { 'Api-Key': st.session_state.pinecone_api_key, 'Content-Type': 'application/json' } url = f"https://{index_name}.svc.{st.session_state.pinecone_environment}.pinecone.io/query" data = { 'vector': vector, 'top_k': top_k, 'namespace': 'translations', 'include_metadata': True } response = requests.post(url, json=data, headers=headers, timeout=30) if response.status_code == 200: return True, response.json() else: return False, f"❌ Query failed: {response.status_code}" except Exception as e: return False, f"❌ Query error: {str(e)}" def delete_pinecone_index(index_name): """Delete a Pinecone index""" try: headers = { 'Api-Key': st.session_state.pinecone_api_key } url = f"https://controller.{st.session_state.pinecone_environment}.pinecone.io/databases/{index_name}" response = requests.delete(url, headers=headers, timeout=30) if response.status_code == 200: return True, f"✅ Index '{index_name}' deleted successfully!" else: return False, f"❌ Delete failed: {response.status_code}" except Exception as e: return False, f"❌ Delete error: {str(e)}" def translate_with_pinecone(text, target_lang): """Translate using Pinecone vector search for similar translations""" try: # Get embedding for input text query_vector = get_text_embedding(text) # Query Pinecone for similar translations if st.session_state.pinecone_index: success, result = query_pinecone(st.session_state.pinecone_index, query_vector) if success and 'matches' in result and len(result['matches']) > 0: # Get the most similar translation best_match = result['matches'][0] if best_match['score'] > 0.85: # High confidence threshold metadata = best_match['metadata'] if 'translation' in metadata and metadata['target_lang'] == target_lang: return metadata['translation'], True, "🔄 Retrieved from Pinecone memory" return None, False, "ℹ️ No similar translation found in Pinecone" except Exception as e: return None, False, f"⚠️ Pinecone search error: {str(e)}" def translate_with_google(text, target_lang, api_key=None): """Translate using Google Cloud Translation API""" try: url = "https://translation.googleapis.com/language/translate/v2" params = { 'q': text, 'target': target_lang, 'key': api_key, 'format': 'text' } response = requests.post(url, params=params, timeout=10) if response.status_code == 200: data = response.json() return data['data']['translations'][0]['translatedText'] except Exception as e: st.error(f"Google API Error: {str(e)}") return None def translate_with_mymemory(text, target_lang): """Translate using MyMemory API""" try: import urllib.parse encoded_text = urllib.parse.quote(text) 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() return data['responseData']['translatedText'] except Exception as e: st.error(f"MyMemory Error: {str(e)}") return None def translate_text(text, target_lang, use_pinecone=True): """Main translation function with Pinecone memory""" if not text or len(text.strip()) == 0: return "", "⚠️ Empty text" translated = None source = "❓ Unknown" # Step 1: Try Pinecone memory first if use_pinecone and st.session_state.pinecone_initialized and st.session_state.pinecone_index: translated, found, message = translate_with_pinecone(text, target_lang) if translated: source = message return translated, source # Step 2: Try Google API if key is available if st.session_state.get('google_api_key'): translated = translate_with_google(text, target_lang, st.session_state.google_api_key) if translated: source = "🌐 Google Translate API" # Store in Pinecone for future use if use_pinecone and st.session_state.pinecone_initialized: store_translation_in_pinecone(text, translated, target_lang) return translated, source # Step 3: Try MyMemory API translated = translate_with_mymemory(text, target_lang) if translated: source = "📚 MyMemory API" # Store in Pinecone for future use if use_pinecone and st.session_state.pinecone_initialized: store_translation_in_pinecone(text, translated, target_lang) return translated, source # Step 4: Fallback to simple dictionary translated = simple_translation_fallback(text, target_lang) source = "📖 Dictionary (Fallback)" return translated, source def store_translation_in_pinecone(original, translated, target_lang): """Store translation in Pinecone for future use""" try: if not st.session_state.pinecone_initialized or not st.session_state.pinecone_index: return False # Generate unique ID for this translation translation_id = hashlib.md5(f"{original}_{target_lang}_{time.time()}".encode()).hexdigest() # Get embedding for original text embedding = get_text_embedding(original) # Prepare vector for upsert vector = { 'id': translation_id, 'values': embedding, 'metadata': { 'original': original, 'translation': translated, 'target_lang': target_lang, 'timestamp': time.time(), 'source': 'voice_translator' } } # Upsert to Pinecone success, message = upsert_to_pinecone(st.session_state.pinecone_index, [vector]) return success except Exception as e: st.error(f"Failed to store in Pinecone: {str(e)}") return False def simple_translation_fallback(text, target_lang): """Comprehensive fallback translation dictionary""" text_lower = text.lower() # Expanded translation dictionary with Indian languages translations = { 'es': { 'hello': 'hola', 'hi': 'hola', 'good morning': 'buenos días', 'good afternoon': 'buenas tardes', 'good evening': 'buenas noches', 'good night': 'buenas noches', 'how are you': 'cómo estás', 'thank you': 'gracias', 'thank you very much': 'muchas gracias', 'please': 'por favor', 'sorry': 'lo siento', 'yes': 'sí', 'no': 'no', 'goodbye': 'adiós', 'help': 'ayuda', 'water': 'agua', 'food': 'comida', 'hotel': 'hotel', 'restaurant': 'restaurante', 'airport': 'aeropuerto', 'bathroom': 'baño', 'police': 'policía', 'doctor': 'médico', 'hospital': 'hospital', 'money': 'dinero', 'taxi': 'taxi', 'train': 'tren', 'bus': 'autobús', 'ticket': 'boleto', 'price': 'precio', 'cost': 'costo', 'where': 'dónde', 'when': 'cuándo', 'what': 'qué', 'who': 'quién', 'why': 'por qué', 'how': 'cómo', 'i need': 'necesito', 'i want': 'quiero', 'i have': 'tengo', 'i am': 'estoy', 'you are': 'usted está', 'we are': 'nosotros estamos', 'they are': 'ellos están', 'my name is': 'me llamo', 'what is your name': 'cómo te llamas', 'nice to meet you': 'mucho gusto', 'where is the bathroom': 'dónde está el baño', 'how much does it cost': 'cuánto cuesta', 'i need help': 'necesito ayuda', 'call the police': 'llama a la policía', 'i am lost': 'estoy perdido', 'i am sick': 'estoy enfermo', 'emergency': 'emergencia', 'help me': 'ayúdame', 'can you help me': 'puedes ayudarme', 'do you speak english': 'hablas inglés', 'i dont understand': 'no entiendo', 'please speak slowly': 'por favor habla despacio', 'could you repeat that': 'podrías repetir eso', 'what does that mean': 'qué significa eso', 'how do you say': 'cómo se dice', 'write it down': 'escríbelo', 'show me': 'muéstrame', 'wait': 'espera', 'stop': 'para', 'go': 've', 'come': 'ven', 'leave': 'vete', 'stay': 'quédate', 'here': 'aquí', 'there': 'allí', 'now': 'ahora', 'later': 'después', 'today': 'hoy', 'tomorrow': 'mañana', 'yesterday': 'ayer', 'morning': 'mañana', 'afternoon': 'tarde', 'evening': 'noche', 'night': 'noche', 'day': 'día', 'week': 'semana', 'month': 'mes', 'year': 'año', 'time': 'tiempo', 'hour': 'hora', 'minute': 'minuto', 'second': 'segundo', 'clock': 'reloj', 'phone': 'teléfono', 'computer': 'computadora', 'internet': 'internet', 'wifi': 'wifi', 'email': 'correo electrónico', 'address': 'dirección', 'map': 'mapa', 'direction': 'dirección', 'street': 'calle', 'avenue': 'avenida', 'corner': 'esquina', 'block': 'cuadra', 'north': 'norte', 'south': 'sur', 'east': 'este', 'west': 'oeste', 'left': 'izquierda', 'right': 'derecha', 'straight': 'recto', 'back': 'atrás', 'front': 'frente', 'near': 'cerca', 'far': 'lejos', 'up': 'arriba', 'down': 'abajo', 'entrance': 'entrada', 'exit': 'salida', 'open': 'abierto', 'closed': 'cerrado', 'free': 'gratis', 'paid': 'pagado', 'discount': 'descuento', 'sale': 'oferta', 'expensive': 'caro', 'cheap': 'barato', 'good': 'bueno', 'bad': 'malo', 'beautiful': 'hermoso', 'ugly': 'feo', 'big': 'grande', 'small': 'pequeño', 'hot': 'caliente', 'cold': 'frío', 'warm': 'tibio', 'cool': 'fresco', 'new': 'nuevo', 'old': 'viejo', 'young': 'joven', 'strong': 'fuerte', 'weak': 'débil', 'fast': 'rápido', 'slow': 'lento', 'easy': 'fácil', 'difficult': 'difícil', 'simple': 'simple', 'complex': 'complejo', 'happy': 'feliz', 'sad': 'triste', 'angry': 'enojado', 'tired': 'cansado', 'hungry': 'hambriento', 'thirsty': 'sediento', 'sleepy': 'soñoliento', 'busy': 'ocupado', 'available': 'disponible', 'ready': 'listo', 'finished': 'terminado', 'start': 'empezar', 'end': 'terminar', 'continue': 'continuar', 'pause': 'pausa', 'play': 'jugar', 'work': 'trabajo', 'study': 'estudio', 'learn': 'aprender', 'teach': 'enseñar', 'understand': 'entender', 'know': 'saber', 'think': 'pensar', 'believe': 'creer', 'feel': 'sentir', 'see': 'ver', 'hear': 'oír', 'listen': 'escuchar', 'speak': 'hablar', 'talk': 'conversar', 'say': 'decir', 'tell': 'contar', 'ask': 'preguntar', 'answer': 'responder', 'give': 'dar', 'take': 'tomar', 'bring': 'traer', 'carry': 'llevar', 'buy': 'comprar', 'sell': 'vender', 'pay': 'pagar', 'use': 'usar', 'make': 'hacer', 'do': 'hacer', 'have': 'tener', 'get': 'obtener', 'find': 'encontrar', 'lose': 'perder', 'keep': 'mantener', 'save': 'guardar', 'delete': 'borrar', 'add': 'agregar', 'remove': 'quitar', 'include': 'incluir', 'exclude': 'excluir', 'join': 'unirse', 'separate': 'separar', 'connect': 'conectar', 'disconnect': 'desconectar', 'send': 'enviar', 'receive': 'recibir', 'share': 'compartir', 'download': 'descargar', 'upload': 'subir', 'update': 'actualizar', 'install': 'instalar', 'uninstall': 'desinstalar', 'configure': 'configurar', 'setup': 'configuración', 'customize': 'personalizar', 'preferences': 'preferencias', 'settings': 'ajustes', 'options': 'opciones', 'help': 'ayuda', 'support': 'soporte', 'contact': 'contacto', 'about': 'acerca de', 'privacy': 'privacidad', 'terms': 'términos', 'conditions': 'condiciones', 'policy': 'política', 'agreement': 'acuerdo', 'license': 'licencia', 'copyright': 'derechos de autor', 'trademark': 'marca registrada', 'patent': 'patente', 'registered': 'registrado', 'all rights reserved': 'todos los derechos reservados', 'one': 'uno', 'two': 'dos', 'three': 'tres', 'four': 'cuatro', 'five': 'cinco', 'six': 'seis', 'seven': 'siete', 'eight': 'ocho', 'nine': 'nueve', 'ten': 'diez', 'eleven': 'once', 'twelve': 'doce', 'thirteen': 'trece', 'fourteen': 'catorce', 'fifteen': 'quince', 'sixteen': 'dieciséis', 'seventeen': 'diecisiete', 'eighteen': 'dieciocho', 'nineteen': 'diecinueve', 'twenty': 'veinte', 'thirty': 'treinta', 'forty': 'cuarenta', 'fifty': 'cincuenta', 'sixty': 'sesenta', 'seventy': 'setenta', 'eighty': 'ochenta', 'ninety': 'noventa', 'hundred': 'cien', 'thousand': 'mil', 'million': 'millón', 'billion': 'mil millones', 'first': 'primero', 'second': 'segundo', 'third': 'tercero', 'fourth': 'cuarto', 'fifth': 'quinto', 'sixth': 'sexto', 'seventh': 'séptimo', 'eighth': 'octavo', 'ninth': 'noveno', 'tenth': 'décimo' }, 'fr': { 'hello': 'bonjour', 'hi': 'salut', 'good morning': 'bonjour', 'good afternoon': 'bon après-midi', 'good evening': 'bonsoir', 'good night': 'bonne nuit', 'how are you': 'comment allez-vous', 'thank you': 'merci', 'thank you very much': 'merci beaucoup', 'please': 's\'il vous plaît', 'sorry': 'désolé', 'yes': 'oui', 'no': 'non', 'goodbye': 'au revoir', 'help': 'aide', 'water': 'eau', 'food': 'nourriture', 'hotel': 'hôtel', 'restaurant': 'restaurant', 'airport': 'aéroport', 'bathroom': 'toilettes', 'police': 'police', 'doctor': 'médecin', 'hospital': 'hôpital', 'money': 'argent', 'taxi': 'taxi', 'train': 'train', 'bus': 'bus', 'ticket': 'billet', 'price': 'prix', 'cost': 'coût', 'where': 'où', 'when': 'quand', 'what': 'quoi', 'who': 'qui', 'why': 'pourquoi', 'how': 'comment', 'i need': 'j\'ai besoin', 'i want': 'je veux', 'i have': 'j\'ai', 'i am': 'je suis', 'my name is': 'je m\'appelle', 'nice to meet you': 'enchanté', 'where is the bathroom': 'où sont les toilettes', 'how much does it cost': 'combien ça coûte', 'i need help': 'j\'ai besoin d\'aide', 'call the police': 'appelez la police', 'i am lost': 'je suis perdu', 'i am sick': 'je suis malade' }, # Hindi (हिन्दी) translations added 'hi': { 'hello': 'नमस्ते', 'hi': 'नमस्ते', 'good morning': 'शुभ प्रभात', 'good afternoon': 'नमस्कार', 'good evening': 'शुभ संध्या', 'good night': 'शुभ रात्रि', 'how are you': 'आप कैसे हैं', 'thank you': 'धन्यवाद', 'thank you very much': 'बहुत धन्यवाद', 'please': 'कृपया', 'sorry': 'क्षमा करें', 'yes': 'हाँ', 'no': 'नहीं', 'goodbye': 'अलविदा', 'help': 'मदद', 'water': 'पानी', 'food': 'खाना', 'hotel': 'होटल', 'restaurant': 'रेस्तरां', 'airport': 'हवाई अड्डा', 'bathroom': 'शौचालय', 'police': 'पुलिस', 'doctor': 'डॉक्टर', 'hospital': 'अस्पताल', 'money': 'पैसे', 'taxi': 'टैक्सी', 'train': 'ट्रेन', 'bus': 'बस', 'ticket': 'टिकट', 'price': 'कीमत', 'cost': 'मूल्य', 'where': 'कहाँ', 'when': 'कब', 'what': 'क्या', 'who': 'कौन', 'why': 'क्यों', 'how': 'कैसे', 'i need': 'मुझे चाहिए', 'i want': 'मैं चाहता हूँ', 'i have': 'मेरे पास है', 'i am': 'मैं हूँ', 'you are': 'आप हैं', 'we are': 'हम हैं', 'they are': 'वे हैं', 'my name is': 'मेरा नाम है', 'what is your name': 'आपका नाम क्या है', 'nice to meet you': 'आपसे मिलकर खुशी हुई', 'where is the bathroom': 'शौचालय कहाँ है', 'how much does it cost': 'इसकी कीमत क्या है', 'i need help': 'मुझे मदद चाहिए', 'call the police': 'पुलिस को बुलाओ', 'i am lost': 'मैं खो गया हूँ', 'i am sick': 'मैं बीमार हूँ', 'emergency': 'आपातकालीन', 'help me': 'मेरी मदद करो', 'can you help me': 'क्या आप मेरी मदद कर सकते हैं', 'do you speak english': 'क्या आप अंग्रेजी बोलते हैं', 'i dont understand': 'मुझे समझ नहीं आया', 'please speak slowly': 'कृपया धीरे बोलें', 'could you repeat that': 'क्या आप दोहरा सकते हैं', 'what does that mean': 'इसका क्या मतलब है', 'how do you say': 'आप कैसे कहते हैं', 'write it down': 'इसे लिख दो', 'show me': 'मुझे दिखाओ', 'wait': 'रुको', 'stop': 'रुकें', 'go': 'जाओ', 'come': 'आओ', 'leave': 'जाओ', 'stay': 'रहो', 'here': 'यहाँ', 'there': 'वहाँ', 'now': 'अब', 'later': 'बाद में', 'today': 'आज', 'tomorrow': 'कल', 'yesterday': 'कल', 'morning': 'सुबह', 'afternoon': 'दोपहर', 'evening': 'शाम', 'night': 'रात', 'day': 'दिन', 'week': 'सप्ताह', 'month': 'महीना', 'year': 'साल', 'time': 'समय', 'hour': 'घंटा', 'minute': 'मिनट', 'second': 'सेकंड', 'clock': 'घड़ी', 'phone': 'फोन', 'computer': 'कंप्यूटर', 'internet': 'इंटरनेट', 'wifi': 'वाई-फाई', 'email': 'ईमेल', 'address': 'पता', 'map': 'नक्शा', 'direction': 'दिशा', 'street': 'गली', 'avenue': 'एवेन्यू', 'corner': 'कोना', 'block': 'ब्लॉक', 'north': 'उत्तर', 'south': 'दक्षिण', 'east': 'पूर्व', 'west': 'पश्चिम', 'left': 'बाएँ', 'right': 'दाएँ', 'straight': 'सीधे', 'back': 'पीछे', 'front': 'सामने', 'near': 'पास', 'far': 'दूर', 'up': 'ऊपर', 'down': 'नीचे', 'entrance': 'प्रवेश द्वार', 'exit': 'निकास', 'open': 'खुला', 'closed': 'बंद', 'free': 'मुफ्त', 'paid': 'भुगतान', 'discount': 'छूट', 'sale': 'बिक्री', 'expensive': 'महंगा', 'cheap': 'सस्ता', 'good': 'अच्छा', 'bad': 'बुरा', 'beautiful': 'सुंदर', 'ugly': 'बदसूरत', 'big': 'बड़ा', 'small': 'छोटा', 'hot': 'गर्म', 'cold': 'ठंडा', 'warm': 'गुनगुना', 'cool': 'ठंडा', 'new': 'नया', 'old': 'पुराना', 'young': 'युवा', 'strong': 'मजबूत', 'weak': 'कमजोर', 'fast': 'तेज', 'slow': 'धीमा', 'easy': 'आसान', 'difficult': 'मुश्किल', 'simple': 'सरल', 'complex': 'जटिल', 'happy': 'खुश', 'sad': 'उदास', 'angry': 'गुस्सा', 'tired': 'थका हुआ', 'hungry': 'भूखा', 'thirsty': 'प्यासा', 'sleepy': 'नींद', 'busy': 'व्यस्त', 'available': 'उपलब्ध', 'ready': 'तैयार', 'finished': 'समाप्त', 'start': 'शुरू', 'end': 'अंत', 'continue': 'जारी रखें', 'pause': 'ठहराव', 'play': 'खेल', 'work': 'काम', 'study': 'पढ़ाई', 'learn': 'सीखना', 'teach': 'सिखाना', 'understand': 'समझना', 'know': 'जानना', 'think': 'सोचना', 'believe': 'विश्वास', 'feel': 'महसूस', 'see': 'देखना', 'hear': 'सुनना', 'listen': 'सुनो', 'speak': 'बोलना', 'talk': 'बात', 'say': 'कहना', 'tell': 'बताना', 'ask': 'पूछना', 'answer': 'जवाब', 'give': 'देना', 'take': 'लेना', 'bring': 'लाना', 'carry': 'ले जाना', 'buy': 'खरीदना', 'sell': 'बेचना', 'pay': 'भुगतान', 'use': 'उपयोग', 'make': 'बनाना', 'do': 'करना', 'have': 'है', 'get': 'प्राप्त', 'find': 'ढूँढ़ें', 'lose': 'खोना', 'keep': 'रखना', 'save': 'सहेजें', 'delete': 'हटाएँ', 'add': 'जोड़ें', 'remove': 'निकालें', 'include': 'शामिल', 'exclude': 'बहिष्कृत', 'join': 'शामिल हों', 'separate': 'अलग', 'connect': 'कनेक्ट', 'disconnect': 'डिस्कनेक्ट', 'send': 'भेजें', 'receive': 'प्राप्त', 'share': 'साझा', 'download': 'डाउनलोड', 'upload': 'अपलोड', 'update': 'अपडेट', 'install': 'इंस्टॉल', 'uninstall': 'अनइंस्टॉल', 'configure': 'कॉन्फ़िगर', 'setup': 'सेटअप', 'customize': 'अनुकूलित', 'preferences': 'प्राथमिकताएँ', 'settings': 'सेटिंग्स', 'options': 'विकल्प', 'help': 'मदद', 'support': 'समर्थन', 'contact': 'संपर्क', 'about': 'के बारे में', 'privacy': 'गोपनीयता', 'terms': 'शर्तें', 'conditions': 'शर्तें', 'policy': 'नीति', 'agreement': 'समझौता', 'license': 'लाइसेंस', 'copyright': 'कॉपीराइट', 'trademark': 'ट्रेडमार्क', 'patent': 'पेटेंट', 'registered': 'पंजीकृत', 'all rights reserved': 'सभी अधिकार सुरक्षित', 'one': 'एक', 'two': 'दो', 'three': 'तीन', 'four': 'चार', 'five': 'पांच', 'six': 'छह', 'seven': 'सात', 'eight': 'आठ', 'nine': 'नौ', 'ten': 'दस', 'eleven': 'ग्यारह', 'twelve': 'बारह', 'thirteen': 'तेरह', 'fourteen': 'चौदह', 'fifteen': 'पंद्रह', 'sixteen': 'सोलह', 'seventeen': 'सत्रह', 'eighteen': 'अठारह', 'nineteen': 'उन्नीस', 'twenty': 'बीस', 'thirty': 'तीस', 'forty': 'चालीस', 'fifty': 'पचास', 'sixty': 'साठ', 'seventy': 'सत्तर', 'eighty': 'अस्सी', 'ninety': 'नब्बे', 'hundred': 'सौ', 'thousand': 'हजार', 'million': 'दस लाख', 'billion': 'अरब', 'first': 'पहला', 'second': 'दूसरा', 'third': 'तीसरा', 'fourth': 'चौथा', 'fifth': 'पांचवां', 'sixth': 'छठा', 'seventh': 'सातवां', 'eighth': 'आठवां', 'ninth': 'नौवां', 'tenth': 'दसवां' }, # Bengali (বাংলা) basic translations 'bn': { 'hello': 'হ্যালো', 'thank you': 'ধন্যবাদ', 'please': 'অনুগ্রহ করে', 'good morning': 'সুপ্রভাত', 'good night': 'শুভ রাত্রি', 'yes': 'হ্যাঁ', 'no': 'না', 'help': 'সাহায্য', 'water': 'পানি', 'food': 'খাবার', 'where': 'কোথায়', 'how much': 'কত', 'i need help': 'আমার সাহায্য দরকার', 'emergency': 'জরুরি অবস্থা', 'doctor': 'ডাক্তার', 'hospital': 'হাসপাতাল', 'police': 'পুলিশ', 'money': 'টাকা', 'taxi': 'ট্যাক্সি', }, # Tamil (தமிழ்) basic translations 'ta': { 'hello': 'வணக்கம்', 'thank you': 'நன்றி', 'please': 'தயவு செய்து', 'good morning': 'காலை வணக்கம்', 'good night': 'இரவு வணக்கம்', 'yes': 'ஆம்', 'no': 'இல்லை', 'help': 'உதவி', 'water': 'தண்ணீர்', 'food': 'உணவு', 'where': 'எங்கே', 'how much': 'எவ்வளவு', 'i need help': 'எனக்கு உதவி தேவை', 'emergency': 'அவசர நிலை', 'doctor': 'மருத்துவர்', 'hospital': 'மருத்துவமனை', 'police': 'காவல்துறை', 'money': 'பணம்', 'taxi': 'டாக்சி', }, # Telugu (తెలుగు) basic translations 'te': { 'hello': 'హలో', 'thank you': 'ధన్యవాదాలు', 'please': 'దయచేసి', 'good morning': 'శుభోదయం', 'good night': 'శుభరాత్రి', 'yes': 'అవును', 'no': 'లేదు', 'help': 'సహాయం', 'water': 'నీరు', 'food': 'ఆహారం', 'where': 'ఎక్కడ', 'how much': 'ఎంత', 'i need help': 'నాకు సహాయం కావాలి', 'emergency': 'అత్యవసర', 'doctor': 'డాక్టర్', 'hospital': 'ఆసుపత్రి', 'police': 'పోలీస్', 'money': 'డబ్బు', 'taxi': 'టాక్సీ', }, # Marathi (मराठी) basic translations 'mr': { 'hello': 'नमस्कार', 'thank you': 'धन्यवाद', 'please': 'कृपया', 'good morning': 'शुभ प्रभात', 'good night': 'शुभ रात्री', 'yes': 'होय', 'no': 'नाही', 'help': 'मदत', 'water': 'पाणी', 'food': 'अन्न', 'where': 'कुठे', 'how much': 'किती', 'i need help': 'मला मदत हवी आहे', 'emergency': 'आणीबाणी', 'doctor': 'डॉक्टर', 'hospital': 'रुग्णालय', 'police': 'पोलीस', 'money': 'पैसे', 'taxi': 'टॅक्सी', }, # Gujarati (ગુજરાતી) basic translations 'gu': { 'hello': 'નમસ્તે', 'thank you': 'આભાર', 'please': 'કૃપા કરીને', 'good morning': 'સુપ્રભાત', 'good night': 'શુભ રાત્રિ', 'yes': 'હા', 'no': 'ના', 'help': 'મદદ', 'water': 'પાણી', 'food': 'ખોરાક', 'where': 'ક્યાં', 'how much': 'કેટલું', 'i need help': 'મને મદદની જરૂર છે', 'emergency': 'કટોકટી', 'doctor': 'ડૉક્ટર', 'hospital': 'હોસ્પિટલ', 'police': 'પોલીસ', 'money': 'પૈસા', 'taxi': 'ટેક્સી', }, # Kannada (ಕನ್ನಡ) basic translations 'kn': { 'hello': 'ನಮಸ್ಕಾರ', 'thank you': 'ಧನ್ಯವಾದಗಳು', 'please': 'ದಯವಿಟ್ಟು', 'good morning': 'ಶುಭೋದಯ', 'good night': 'ಶುಭ ರಾತ್ರಿ', 'yes': 'ಹೌದು', 'no': 'ಇಲ್ಲ', 'help': 'ಸಹಾಯ', 'water': 'ನೀರು', 'food': 'ಆಹಾರ', 'where': 'ಎಲ್ಲಿ', 'how much': 'ಎಷ್ಟು', 'i need help': 'ನನಗೆ ಸಹಾಯ ಬೇಕು', 'emergency': 'ತುರ್ತು', 'doctor': 'ವೈದ್ಯರು', 'hospital': 'ಆಸ್ಪತ್ರೆ', 'police': 'ಪೊಲೀಸ್', 'money': 'ಹಣ', 'taxi': 'ಟ್ಯಾಕ್ಸಿ', }, # Malayalam (മലയാളം) basic translations 'ml': { 'hello': 'ഹലോ', 'thank you': 'നന്ദി', 'please': 'ദയവായി', 'good morning': 'സുപ്രഭാതം', 'good night': 'ശുഭ രാത്രി', 'yes': 'അതെ', 'no': 'ഇല്ല', 'help': 'സഹായം', 'water': 'വെള്ളം', 'food': 'ഭക്ഷണം', 'where': 'എവിടെ', 'how much': 'എത്ര', 'i need help': 'എനിക്ക് സഹായം വേണം', 'emergency': 'അടിയന്തര', 'doctor': 'ഡോക്ടർ', 'hospital': 'ആശുപത്രി', 'police': 'പൊലീസ്', 'money': 'പണം', 'taxi': 'ടാക്സി', }, # Punjabi (ਪੰਜਾਬੀ) basic translations 'pa': { 'hello': 'ਸਤ ਸ੍ਰੀ ਅਕਾਲ', 'thank you': 'ਧੰਨਵਾਦ', 'please': 'ਕ੍ਰਿਪਾ ਕਰਕੇ', 'good morning': 'ਸ਼ੁਭ ਸਵੇਰ', 'good night': 'ਸ਼ੁਭ ਰਾਤ', 'yes': 'ਹਾਂ', 'no': 'ਨਹੀਂ', 'help': 'ਮਦਦ', 'water': 'ਪਾਣੀ', 'food': 'ਭੋਜਨ', 'where': 'ਕਿੱਥੇ', 'how much': 'ਕਿੰਨਾ', 'i need help': 'ਮੈਨੂੰ ਮਦਦ ਦੀ ਲੋੜ ਹੈ', 'emergency': 'ਐਮਰਜੈਂਸੀ', 'doctor': 'ਡਾਕਟਰ', 'hospital': 'ਹਸਪਤਾਲ', 'police': 'ਪੁਲਿਸ', 'money': 'ਪੈਸੇ', 'taxi': 'ਟੈਕਸੀ', }, # Odia (ଓଡ଼ିଆ) basic translations 'or': { 'hello': 'ନମସ୍କାର', 'thank you': 'ଧନ୍ୟବାଦ', 'please': 'ଦୟାକରି', 'good morning': 'ସୁପ୍ରଭାତ', 'good night': 'ଶୁଭ ରାତ୍ରି', 'yes': 'ହଁ', 'no': 'ନା', 'help': 'ସାହାଯ୍ୟ', 'water': 'ପାଣି', 'food': 'ଖାଦ୍ୟ', 'where': 'କେଉଁଠି', 'how much': 'କେତେ', 'i need help': 'ମୋତେ ସାହାଯ୍ୟ ଦରକାର', 'emergency': 'ଜରୁରୀକାଳୀନ', 'doctor': 'ଡାକ୍ତର', 'hospital': 'ଡାକ୍ତରଖାନା', 'police': 'ପୋଲିସ', 'money': 'ଟଙ୍କା', 'taxi': 'ଟ୍ୟାକ୍ସି', }, # Assamese (অসমীয়া) basic translations 'as': { 'hello': 'নমস্কাৰ', 'thank you': 'ধন্যবাদ', 'please': 'অনুগ্ৰহ কৰি', 'good morning': 'সুপ্ৰভাত', 'good night': 'শুভ ৰাতি', 'yes': 'হয়', 'no': 'নহয়', 'help': 'সহায়', 'water': 'পানী', 'food': 'খাদ্য', 'where': 'ক\'ত', 'how much': 'কিমান', 'i need help': 'মোক সহায় দৰকাৰ', 'emergency': 'জৰুৰী', 'doctor': 'ডাক্তৰ', 'hospital': 'হস্পিতাল', 'police': 'পুলিচ', 'money': 'টকা', 'taxi': 'টেক্সি', }, # Urdu (اردو) basic translations 'ur': { 'hello': 'السلام علیکم', 'thank you': 'شکریہ', 'please': 'براہ مہربانی', 'good morning': 'صبح بخیر', 'good night': 'شب بخیر', 'yes': 'ہاں', 'no': 'نہیں', 'help': 'مدد', 'water': 'پانی', 'food': 'کھانا', 'where': 'کہاں', 'how much': 'کتنا', 'i need help': 'مجھے مدد کی ضرورت ہے', 'emergency': 'ہنگامی', 'doctor': 'ڈاکٹر', 'hospital': 'ہسپتال', 'police': 'پولیس', 'money': 'پیسے', 'taxi': 'ٹیکسی', } } if target_lang in translations: # Check for exact phrase matches for phrase, translation in translations[target_lang].items(): if phrase in text_lower: if text[0].isupper(): return translation.capitalize() return translation # Try word-by-word translation for short texts if len(text.split()) <= 3: words = text_lower.split() translated_words = [] for word in words: found = False for phrase, translation in translations[target_lang].items(): if word == phrase: translated_words.append(translation) found = True break if not found: translated_words.append(word) if translated_words: return ' '.join(translated_words) return f"[{LANGUAGES.get(target_lang, {}).get('name', target_lang)}]: {text}" def generate_audio_base64(text, lang): """Generate audio and return as base64""" try: # Get the correct gTTS language code tts_code = LANGUAGES.get(lang, {}).get('tts_code', lang) tts = gTTS(text=text, lang=tts_code, slow=False) with tempfile.NamedTemporaryFile(delete=False, suffix='.mp3') as f: temp_file = f.name tts.save(temp_file) with open(temp_file, 'rb') as audio_file: audio_bytes = audio_file.read() os.unlink(temp_file) return base64.b64encode(audio_bytes).decode() except Exception as e: st.error(f"Audio error: {str(e)}") return None def main(): # Custom CSS st.markdown(""" """, unsafe_allow_html=True) # Header st.markdown("""
Real-time translation with vector memory powered by Pinecone
🎯 Voice Translator with Pinecone AI | Vector-powered Translation Memory
🔷 Pinecone enables semantic search and context-aware translations
🌐 Supports 22+ Indian Languages including Hindi, Bengali, Telugu, Tamil, Marathi, Gujarati, Kannada, Malayalam, Punjabi, Odia, Assamese, Urdu and more!
🌐 Google Chrome recommended | Allow microphone access for voice input