Changing language using streamlit

I’m trying to add a feature to my site that allows me to change the language of my site to another language! I’ve tried a lot of things, I’ve searched on some kind of document but with no satisfactory result. I don’t know if anyone has already done this or has an idea to give me. I’d be delighted to learn from you !
What I’ve done so far is to create txt files with the translations of the texts on my website.
the problem is that for the moment I have a simple technique to change the language but the problem is that I have to choose 2 times in the selectbox menu the same language to change it.

type or paste code here # read url querry parameters
    url_querry_params = st.experimental_get_query_params()
    try:
        lang_from_url = url_querry_params.get('lang', ['en'])[0]
        st.session_state['language'] = lang_from_url
        print('The given language is: ', url_querry_params['lang'])
    except Exception as e:
        print(f'Exception catched {e}')

    if 'language' not in st.session_state:
        if url_querry_params['lang'] == ['en']:
            st.session_state['language'] = 'en'  # 'fr','nl', 'en'
        elif url_querry_params['lang'] == ['nl']:
            st.session_state['language'] = 'nl'
        elif url_querry_params['lang'] == ['fr']:
            st.session_state['language'] = 'fr'
        elif url_querry_params['lang'] == ['es']:
            st.session_state['language'] = 'es'
        else:
            st.session_state['language'] = 'en'

    languages = {
        'English': 'en',
        'Spanish': 'es',
        'French': 'fr',
        'Dutch': 'nl'
    }

    ### Load language variables
    config = configparser.ConfigParser()
    language_path = os.path.join(current_path, 'web_app')
    language_path = os.path.join(language_path, 'language_data')
    if st.session_state['language'] == 'en':
        config.read(os.path.join(language_path, 'language_en.txt'), encoding='utf-8')
    elif st.session_state['language'] == 'nl':
        config.read(os.path.join(language_path, 'language_nl.txt'), encoding='utf-8')
    elif st.session_state['language'] == 'fr':
        config.read(os.path.join(language_path, 'language_fr.txt'), encoding='utf-8')
    elif st.session_state['language'] == 'es':
        config.read(os.path.join(language_path, 'language_es.txt'), encoding='utf-8')
    else:
        config.read(os.path.join(language_path, 'language_en.txt'), encoding='utf-8')

    title = config.get("myvars", "title")
    question = config.get("myvars", "question")
    ref_doc = config.get("myvars", "ref_doc")
    log_in = config.get("myvars", "log_in")
    login_fail = config.get("myvars", "login_fail")
    close_pdf = config.get("myvars", "close_pdf")
    language = config.get("myvars", "language")
    email = config.get("myvars", "email")
    password = config.get("myvars", "password")
    references = config.get("myvars", "references")
    pages = config.get("myvars", "pages")
        with st.sidebar:

            st.markdown("# Language")
            selected_language = st.selectbox('Select your language and press Enter:', list(languages.keys()))
            if selected_language != st.session_state['language']:
                st.session_state['language'] = languages[selected_language]
                st.experimental_set_query_params(lang=languages[selected_language])

Hi there @yahia_hbenchekroun ,

Two things you can try separately:

  • Place what you have in the sidebar (the st.selectbox and the logic to set the query params) before the rest of the script. Keep in mind that Streamlit runs the script from top to bottom upon every user interaction.

OR

  • Add st.experimental_rerun() after setting the query params.

Hope this helps!

You can have a combination of Callback Function, Session State and Query Parameters to achieve that. Here is a simple snippet that might lead you into that direction. Hope it helps!

import streamlit as st

languages = {"English": "en", "Spanish": "es", "French": "fr", "Dutch": "nl"}

query_parameters = st.experimental_get_query_params()
if "lang" not in query_parameters:
    st.experimental_set_query_params(lang="en")
    st.experimental_rerun()


def set_language() -> None:
    if "selected_language" in st.session_state:
        st.experimental_set_query_params(
            lang=languages.get(st.session_state["selected_language"])
        )


sel_lang = st.radio(
    "Language",
    options=languages,
    horizontal=True,
    on_change=set_language,
    key="selected_language",
)

st.markdown(f"Selected Language: {sel_lang}")
st.markdown(f"""Language Code: {query_parameters.get("lang")[0]}""")

Screen-Recording-2023-09-19-at-9

5 Likes

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.