File size: 1,216 Bytes
582bf6b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# utils/translator.py
"""Translation utility for TriviaVerse"""

import streamlit as st
from googletrans import Translator
from config.languages import SUPPORTED_LANGUAGES
from config.localization import UI_TEXT

@st.cache_data(ttl=3600)
def get_translated_texts(dest_lang="en"):
    """

    Translates all UI texts to the destination language in a single batch

    and caches the result.

    """
    if dest_lang == "en":
        return UI_TEXT

    try:
        translator = Translator()
        # Get all the values from the UI_TEXT dictionary
        original_texts = list(UI_TEXT.values())
        
        # Translate them in a single batch
        translated_texts = translator.translate(original_texts, dest=dest_lang)
        
        # Create a new dictionary with the same keys but translated values
        translated_dict = dict(zip(UI_TEXT.keys(), [t.text for t in translated_texts]))
        
        return translated_dict
    except Exception as e:
        st.error(f"Translation service failed: {e}. Falling back to English.")
        return UI_TEXT

def get_supported_languages():
    """Returns the list of supported languages."""
    return SUPPORTED_LANGUAGES