Spaces:
Build error
Build error
File size: 68,460 Bytes
6bf7666 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 | 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() |