Spaces:
Build error
Build error
Download app.py from Gajanand1/Language_Translation: direct link, hf CLI and curl.
- Browser
- Download file 68.5 kB
-
https://huggingface.co/spaces/Gajanand1/Language_Translation/resolve/main/app.py
- Command line
-
hf download hf://spaces/Gajanand1/Language_Translation/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Gajanand1/Language_Translation/resolve/main/app.py
68.5 kB
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("""
<style>
.main-header {
text-align: center;
padding: 1.5rem;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
border-radius: 10px;
margin-bottom: 2rem;
}
.pinecone-badge {
background-color: #00A36C;
color: white;
padding: 0.2rem 0.5rem;
border-radius: 5px;
font-size: 0.8rem;
display: inline-block;
}
.translation-box {
padding: 1.5rem;
border-radius: 10px;
background: #f8f9fa;
margin: 1rem 0;
border-left: 4px solid #667eea;
}
.source-badge {
font-size: 0.8rem;
color: #666;
margin-top: 0.5rem;
}
</style>
""", unsafe_allow_html=True)
# Header
st.markdown("""
<div class="main-header">
<h1>🎤 Voice Translator with Pinecone AI</h1>
<p>Real-time translation with vector memory powered by Pinecone</p>
</div>
""", unsafe_allow_html=True)
# Sidebar
with st.sidebar:
st.header("⚙️ Settings")
# Pinecone Configuration
with st.expander("🔷 Pinecone AI Configuration", expanded=True):
st.markdown('<span class="pinecone-badge">Vector Database</span>', unsafe_allow_html=True)
pinecone_api_key = st.text_input(
"pcsk_5uRGLA_UgyP8R7QNdz4m7hL4i4G3f7iCQGLPKSU4haMo2zcY8F2ZMSvSzcmBj8iz7FG2rA",
type="password",
help="Get your API key from app.pinecone.io",
value=st.session_state.pinecone_api_key if st.session_state.pinecone_api_key else ""
)
pinecone_env = st.text_input(
"Pinecone Environment",
help="e.g., us-west1-gcp, us-east-1-aws",
value=st.session_state.pinecone_environment if st.session_state.pinecone_environment else ""
)
pinecone_index = st.text_input(
"Index Name",
value="voice-translator" if not st.session_state.pinecone_index else st.session_state.pinecone_index,
help="Name of the index to store translations"
)
col1, col2 = st.columns(2)
with col1:
if st.button("🔌 Connect", use_container_width=True):
if pinecone_api_key and pinecone_env:
success, message = initialize_pinecone(pinecone_api_key, pinecone_env)
if success:
st.session_state.pinecone_index = pinecone_index
st.success(message)
else:
st.error(message)
else:
st.warning("Please enter API key and environment")
with col2:
if st.button("📁 Create Index", use_container_width=True):
if st.session_state.pinecone_initialized:
success, message = create_pinecone_index(pinecone_index)
if success:
st.success(message)
else:
st.error(message)
else:
st.warning("Connect to Pinecone first")
if st.session_state.pinecone_initialized:
st.success("✅ Pinecone connected")
if st.button("🗑️ Delete Index", use_container_width=True):
if st.session_state.pinecone_index:
success, message = delete_pinecone_index(st.session_state.pinecone_index)
if success:
st.success(message)
st.session_state.pinecone_index = None
else:
st.error(message)
# Google API (Optional)
with st.expander("🌐 Google API (Optional)"):
google_api_key = st.text_input(
"AIzaSyAG-qx8FgW8gGzxZpuh9LlgFojsX3d7hmU",
type="password",
help="Get from Google Cloud Console",
value=st.session_state.get('google_api_key', '')
)
if st.button("Save Google API"):
st.session_state.google_api_key = google_api_key if google_api_key else None
st.success("Google API saved!" if google_api_key else "Google API disabled")
# Language selection - INDIAN LANGUAGES NOW AVAILABLE
st.session_state.target_lang = st.selectbox(
"🌍 Translate to:",
options=list(LANGUAGES.keys()),
format_func=lambda x: LANGUAGES[x]['name'],
index=list(LANGUAGES.keys()).index('hi') # Default to Hindi now
)
# Pinecone settings
use_pinecone = st.checkbox("🔷 Use Pinecone Memory", value=True, help="Use vector search for faster, context-aware translations")
# Quick phrases
st.header("💡 Quick Phrases")
phrases = [
"Hello, how are you?",
"Thank you very much",
"Where is the bathroom?",
"I need help",
"How much does it cost?",
"Good morning",
"Nice to meet you",
"What is your name?",
"Can you help me?",
"I am lost",
"Call the police",
"Emergency"
]
cols = st.columns(2)
for i, phrase in enumerate(phrases):
with cols[i % 2]:
if st.button(phrase[:20] + "...", key=f"quick_{i}"):
st.session_state.input_text = phrase
# History
if st.session_state.history:
st.header("📜 Translation Memory")
for entry in reversed(st.session_state.history[-5:]):
with st.expander(f"{entry['time']} - {entry['lang']}"):
st.write(f"**Original:** {entry['original']}")
st.write(f"**Translated:** {entry['translated']}")
st.write(f"*Source: {entry.get('source', 'Translation API')}*")
# Clear history button
if st.button("🧹 Clear History", use_container_width=True):
st.session_state.history = []
st.rerun()
# Main content
col1, col2 = st.columns(2)
with col1:
st.header("🎤 Input")
input_method = st.radio(
"Input method:",
["Text", "Voice"],
horizontal=True
)
if input_method == "Text":
input_text = st.text_area(
"Enter text:",
height=300,
value=st.session_state.get('input_text', ''),
placeholder="Type or paste text here..."
)
else:
input_text = ""
if st.button("🎤 Start Recording", use_container_width=True, type="primary"):
with st.spinner("Listening... Speak now!"):
try:
recognizer = sr.Recognizer()
with sr.Microphone() as source:
recognizer.adjust_for_ambient_noise(source, duration=0.5)
audio = recognizer.listen(source, timeout=5, phrase_time_limit=10)
input_text = recognizer.recognize_google(audio)
st.success("✅ Recording successful!")
except sr.UnknownValueError:
st.error("❌ Could not understand audio")
except sr.RequestError as e:
st.error(f"❌ Speech recognition error: {e}")
except Exception as e:
st.error(f"❌ Error: {str(e)}")
if input_text:
st.session_state.input_text = input_text
with col2:
st.header("🌐 Translation")
if st.button("🚀 Translate", use_container_width=True, type="primary"):
if 'input_text' in st.session_state and st.session_state.input_text:
with st.spinner("Translating..."):
# Translate with Pinecone memory
translated, source = translate_text(
st.session_state.input_text,
st.session_state.target_lang,
use_pinecone=use_pinecone
)
st.session_state.translated_text = translated
st.session_state.translation_source = source
# Generate audio
audio_base64 = generate_audio_base64(
translated,
st.session_state.target_lang
)
if audio_base64:
st.session_state.audio_base64 = audio_base64
# Save to history
entry = {
'time': datetime.now().strftime("%H:%M:%S"),
'lang': LANGUAGES[st.session_state.target_lang]['name'],
'original': st.session_state.input_text,
'translated': translated,
'source': source
}
st.session_state.history.append(entry)
# Store in Pinecone for future use
if use_pinecone and st.session_state.pinecone_initialized:
if 'Google' in source or 'MyMemory' in source or 'Dictionary' in source:
store_translation_in_pinecone(
st.session_state.input_text,
translated,
st.session_state.target_lang
)
else:
st.warning("Please enter some text first")
# Display translation
if 'translated_text' in st.session_state and st.session_state.translated_text:
st.markdown('<div class="translation-box">', unsafe_allow_html=True)
st.subheader(f"📝 {LANGUAGES[st.session_state.target_lang]['name']}")
st.success(st.session_state.translated_text)
# Show translation source
if 'translation_source' in st.session_state:
st.markdown(f'<div class="source-badge">{st.session_state.translation_source}</div>', unsafe_allow_html=True)
st.markdown('</div>', unsafe_allow_html=True)
# Audio player
if 'audio_base64' in st.session_state and st.session_state.audio_base64:
st.subheader("🔊 Audio")
audio_html = f"""
<audio controls autoplay style="width: 100%; margin: 10px 0;">
<source src="data:audio/mp3;base64,{st.session_state.audio_base64}" type="audio/mp3">
Your browser does not support the audio element.
</audio>
"""
st.markdown(audio_html, unsafe_allow_html=True)
# Download button
audio_bytes = base64.b64decode(st.session_state.audio_base64)
st.download_button(
"📥 Download Audio",
audio_bytes,
f"translation_{int(time.time())}.mp3",
"audio/mp3",
use_container_width=True
)
# Language guide - UPDATED WITH INDIAN LANGUAGES
st.markdown("---")
st.header("📚 Common Phrases")
lang_guide = st.selectbox(
"Select language guide:",
['hi', 'bn', 'te', 'ta', 'mr', 'gu', 'kn', 'ml', 'pa', 'or', 'as', 'ur', 'es', 'fr', 'de', 'it', 'pt'],
format_func=lambda x: LANGUAGES[x]['name']
)
guides = {
'es': [
("Hola", "Hello"),
("Gracias", "Thank you"),
("Por favor", "Please"),
("¿Dónde está...?", "Where is...?"),
("Necesito ayuda", "I need help"),
("¿Cuánto cuesta?", "How much?"),
("La cuenta, por favor", "The bill, please"),
("¿Habla inglés?", "Do you speak English?"),
],
'fr': [
("Bonjour", "Hello"),
("Merci", "Thank you"),
("S'il vous plaît", "Please"),
("Où est...?", "Where is...?"),
("J'ai besoin d'aide", "I need help"),
("Combien ça coûte?", "How much?"),
("L'addition, s'il vous plaît", "The bill, please"),
("Parlez-vous anglais?", "Do you speak English?"),
],
'de': [
("Hallo", "Hello"),
("Danke", "Thank you"),
("Bitte", "Please"),
("Wo ist...?", "Where is...?"),
("Ich brauche Hilfe", "I need help"),
("Wie viel kostet das?", "How much?"),
("Die Rechnung, bitte", "The bill, please"),
("Sprechen Sie Englisch?", "Do you speak English?"),
],
'it': [
("Ciao", "Hello"),
("Grazie", "Thank you"),
("Per favore", "Please"),
("Dov'è...?", "Where is...?"),
("Ho bisogno di aiuto", "I need help"),
("Quanto costa?", "How much?"),
("Il conto, per favore", "The bill, please"),
("Parla inglese?", "Do you speak English?"),
],
'pt': [
("Olá", "Hello"),
("Obrigado", "Thank you"),
("Por favor", "Please"),
("Onde está...?", "Where is...?"),
("Preciso de ajuda", "I need help"),
("Quanto custa?", "How much?"),
("A conta, por favor", "The bill, please"),
("Fala inglês?", "Do you speak English?"),
],
# INDIAN LANGUAGE GUIDES ADDED
'hi': [
("नमस्ते", "Hello"),
("धन्यवाद", "Thank you"),
("कृपया", "Please"),
("कहाँ है...?", "Where is...?"),
("मुझे मदद चाहिए", "I need help"),
("कितने का है?", "How much?"),
("बिल दीजिए", "The bill, please"),
("क्या आप अंग्रेज़ी बोलते हैं?", "Do you speak English?"),
("मेरा नाम है", "My name is"),
("आपका नाम क्या है?", "What is your name?"),
("मैं खो गया हूँ", "I am lost"),
("पुलिस को बुलाओ", "Call the police"),
],
'bn': [
("হ্যালো", "Hello"),
("ধন্যবাদ", "Thank you"),
("অনুগ্রহ করে", "Please"),
("কোথায়...?", "Where is...?"),
("আমার সাহায্য দরকার", "I need help"),
("কত দাম?", "How much?"),
("বিল দিন", "The bill, please"),
("আপনি কি ইংরেজি বলেন?", "Do you speak English?"),
("আমার নাম", "My name is"),
("আপনার নাম কী?", "What is your name?"),
("আমি হারিয়ে গেছি", "I am lost"),
("পুলিশ ডাকুন", "Call the police"),
],
'te': [
("హలో", "Hello"),
("ధన్యవాదాలు", "Thank you"),
("దయచేసి", "Please"),
("ఎక్కడ ఉంది...?", "Where is...?"),
("నాకు సహాయం కావాలి", "I need help"),
("ఎంత ఖర్చు అవుతుంది?", "How much?"),
("బిల్లు ఇవ్వండి", "The bill, please"),
("మీరు ఇంగ్లీష్ మాట్లాడతారా?", "Do you speak English?"),
("నా పేరు", "My name is"),
("మీ పేరు ఏమిటి?", "What is your name?"),
("నేను దారి తప్పాను", "I am lost"),
("పోలీసులకు కాల్ చేయండి", "Call the police"),
],
'ta': [
("வணக்கம்", "Hello"),
("நன்றி", "Thank you"),
("தயவு செய்து", "Please"),
("எங்கே உள்ளது...?", "Where is...?"),
("எனக்கு உதவி தேவை", "I need help"),
("எவ்வளவு செலவாகும்?", "How much?"),
("பில் கொடுங்கள்", "The bill, please"),
("நீங்கள் ஆங்கிலம் பேசுவீர்களா?", "Do you speak English?"),
("என் பெயர்", "My name is"),
("உங்கள் பெயர் என்ன?", "What is your name?"),
("நான் தொலைந்து விட்டேன்", "I am lost"),
("போலீஸை அழைக்கவும்", "Call the police"),
],
'mr': [
("नमस्कार", "Hello"),
("धन्यवाद", "Thank you"),
("कृपया", "Please"),
("कुठे आहे...?", "Where is...?"),
("मला मदत हवी आहे", "I need help"),
("किती पैसे लागतील?", "How much?"),
("बिल द्या", "The bill, please"),
("तुम्ही इंग्रजी बोलता का?", "Do you speak English?"),
("माझे नाव", "My name is"),
("तुमचे नाव काय आहे?", "What is your name?"),
("मी हरवलो आहे", "I am lost"),
("पोलिसांना बोलवा", "Call the police"),
],
'gu': [
("નમસ્તે", "Hello"),
("આભાર", "Thank you"),
("કૃપા કરીને", "Please"),
("ક્યાં છે...?", "Where is...?"),
("મને મદદની જરૂર છે", "I need help"),
("કેટલા પૈસા થાય?", "How much?"),
("બિલ આપો", "The bill, please"),
("તમે અંગ્રેજી બોલો છો?", "Do you speak English?"),
("મારું નામ", "My name is"),
("તમારું નામ શું છે?", "What is your name?"),
("હું ખોવાઈ ગયો છું", "I am lost"),
("પોલીસને બોલાવો", "Call the police"),
],
'kn': [
("ನಮಸ್ಕಾರ", "Hello"),
("ಧನ್ಯವಾದಗಳು", "Thank you"),
("ದಯವಿಟ್ಟು", "Please"),
("ಎಲ್ಲಿ ಇದೆ...?", "Where is...?"),
("ನನಗೆ ಸಹಾಯ ಬೇಕು", "I need help"),
("ಎಷ್ಟು ವೆಚ್ಚವಾಗುತ್ತದೆ?", "How much?"),
("ಬಿಲ್ ಕೊಡಿ", "The bill, please"),
("ನೀವು ಇಂಗ್ಲಿಷ್ ಮಾತನಾಡುತ್ತೀರಾ?", "Do you speak English?"),
("ನನ್ನ ಹೆಸರು", "My name is"),
("ನಿಮ್ಮ ಹೆಸರೇನು?", "What is your name?"),
("ನಾನು ದಾರಿ ತಪ್ಪಿದ್ದೇನೆ", "I am lost"),
("ಪೊಲೀಸರನ್ನು ಕರೆ ಮಾಡಿ", "Call the police"),
],
'ml': [
("ഹലോ", "Hello"),
("നന്ദി", "Thank you"),
("ദയവായി", "Please"),
("എവിടെയാണ്...?", "Where is...?"),
("എനിക്ക് സഹായം വേണം", "I need help"),
("എത്ര വിലയാകും?", "How much?"),
("ബിൽ തരൂ", "The bill, please"),
("നിങ്ങൾ ഇംഗ്ലീഷ് സംസാരിക്കുമോ?", "Do you speak English?"),
("എന്റെ പേര്", "My name is"),
("താങ്കളുടെ പേരെന്താണ്?", "What is your name?"),
("ഞാൻ വഴിതെറ്റി", "I am lost"),
("പോലീസിനെ വിളിക്കൂ", "Call the police"),
],
'pa': [
("ਸਤ ਸ੍ਰੀ ਅਕਾਲ", "Hello"),
("ਧੰਨਵਾਦ", "Thank you"),
("ਕ੍ਰਿਪਾ ਕਰਕੇ", "Please"),
("ਕਿੱਥੇ ਹੈ...?", "Where is...?"),
("ਮੈਨੂੰ ਮਦਦ ਦੀ ਲੋੜ ਹੈ", "I need help"),
("ਕਿੰਨਾ ਮੁੱਲ ਹੈ?", "How much?"),
("ਬਿਲ ਦਿਓ", "The bill, please"),
("ਕੀ ਤੁਸੀਂ ਅੰਗਰੇਜ਼ੀ ਬੋਲਦੇ ਹੋ?", "Do you speak English?"),
("ਮੇਰਾ ਨਾਮ", "My name is"),
("ਤੁਹਾਡਾ ਨਾਮ ਕੀ ਹੈ?", "What is your name?"),
("ਮੈਂ ਗੁੰਮ ਗਿਆ ਹਾਂ", "I am lost"),
("ਪੁਲਿਸ ਨੂੰ ਬੁਲਾਓ", "Call the police"),
],
'or': [
("ନମସ୍କାର", "Hello"),
("ଧନ୍ୟବାଦ", "Thank you"),
("ଦୟାକରି", "Please"),
("କେଉଁଠି ଅଛି...?", "Where is...?"),
("ମୋତେ ସାହାଯ୍ୟ ଦରକାର", "I need help"),
("କେତେ ଟଙ୍କା ହେବ?", "How much?"),
("ବିଲ୍ ଦିଅନ୍ତୁ", "The bill, please"),
("ଆପଣ ଇଂରାଜୀ କହନ୍ତି କି?", "Do you speak English?"),
("ମୋର ନାମ", "My name is"),
("ଆପଣଙ୍କ ନାମ କଣ?", "What is your name?"),
("ମୁଁ ହଜି ଯାଇଛି", "I am lost"),
("ପୋଲିସ ଡାକନ୍ତୁ", "Call the police"),
],
'as': [
("নমস্কাৰ", "Hello"),
("ধন্যবাদ", "Thank you"),
("অনুগ্ৰহ কৰি", "Please"),
("ক\'ত আছে...?", "Where is...?"),
("মোক সহায় দৰকাৰ", "I need help"),
("কিমান দাম?", "How much?"),
("বিল দিয়ক", "The bill, please"),
("আপুনি ইংৰাজী কয় নে?", "Do you speak English?"),
("মোৰ নাম", "My name is"),
("আপোনাৰ নাম কি?", "What is your name?"),
("মই হেৰাই গৈছো", "I am lost"),
("পুলিচ মাতক", "Call the police"),
],
'ur': [
("السلام علیکم", "Hello"),
("شکریہ", "Thank you"),
("براہ مہربانی", "Please"),
("کہاں ہے...؟", "Where is...?"),
("مجھے مدد کی ضرورت ہے", "I need help"),
("کتنا ہے؟", "How much?"),
("بل دیں", "The bill, please"),
("کیا آپ انگریزی بولتے ہیں؟", "Do you speak English?"),
("میرا نام", "My name is"),
("آپ کا نام کیا ہے؟", "What is your name?"),
("میں کھو گیا ہوں", "I am lost"),
("پولیس کو بلاؤ", "Call the police"),
],
}
if lang_guide in guides:
cols = st.columns(2)
for i, (foreign, english) in enumerate(guides[lang_guide]):
with cols[i % 2]:
st.markdown(f"""
<div style="padding: 0.5rem; margin: 0.2rem 0; background: #f0f2f6; border-radius: 5px;">
<strong>{foreign}</strong><br>
<small>{english}</small>
</div>
""", unsafe_allow_html=True)
# Footer
st.markdown("---")
st.markdown("""
<div style='text-align: center; padding: 1rem;'>
<p>🎯 <b>Voice Translator with Pinecone AI</b> | Vector-powered Translation Memory</p>
<p style='font-size: 0.8rem; color: #666;'>
🔷 Pinecone enables semantic search and context-aware translations<br>
🌐 Supports 22+ Indian Languages including Hindi, Bengali, Telugu, Tamil, Marathi, Gujarati, Kannada, Malayalam, Punjabi, Odia, Assamese, Urdu and more!<br>
🌐 Google Chrome recommended | Allow microphone access for voice input
</p>
</div>
""", unsafe_allow_html=True)
if __name__ == "__main__":
main()
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'