Ok, so I was creating a little app in order to translate words from french to english.
The goal is quite simple : I have a dataframe with 2 columns - French & English.
The next step was to create a function to get a random french word and the expected translation in the dataframe using the index.
Afterwards, the user can type in his translation and see if he was correct or not. However (and I understand that it is streamlit way of execution), whenever I type in the correct translation, the whole app reloads and I get another word, hence, I don’t get the correct translation. The end goal would be to have a submit button which would not affect the page reload and a “generate new word” button, which would trigger a reload.
Here is a minimal reproducible example :
import streamlit as st
import pandas as pd
import numpy as np
def main():
st.title("Application de traduction français-anglais")
words = {
"French": ["Bonjour", "Chat", "Maison", "Livre", "Ordinateur"],
"English": ["Hello", "Cat", "House", "Book", "Computer"],
}
df = pd.DataFrame(words)
def get_random_word():
"""get a random word thanks to a random index in the dataframe."""
random_index = np.random.randint(len(df))
return df.iloc[random_index]["French"], df.iloc[random_index]["English"]
french_word, correct_translation = get_random_word()
st.write(f"Traduisez le mot suivant du français à l'anglais : **{french_word}**")
user_translation = st.text_input("Votre traduction en anglais :")
new_word = st.button("🆕 Nouveau mot")
if user_translation.lower() == correct_translation.lower():
st.success("Bonne traduction !")
elif user_translation != "":
st.error(
f"Mauvaise traduction. La traduction correcte était : **{correct_translation}**"
)
if __name__ == "__main__":
main()
import streamlit as st
import pandas as pd
import numpy as np
def main():
st.title("Application de traduction français-anglais")
# Check if 'words' and 'df' already exist in session state, if not, create them
if 'words' not in st.session_state or 'df' not in st.session_state:
st.session_state.words = {
"French": ["Bonjour", "Chat", "Maison", "Livre", "Ordinateur"],
"English": ["Hello", "Cat", "House", "Book", "Computer"]
}
st.session_state.df = pd.DataFrame(st.session_state.words)
# Function to get a random word
def get_random_word():
random_index = np.random.randint(len(st.session_state.df))
return st.session_state.df.iloc[random_index]["French"], st.session_state.df.iloc[random_index]["English"]
# Check if 'french_word' and 'correct_translation' already exist in session state, if not, get a random word
if 'french_word' not in st.session_state or 'correct_translation' not in st.session_state or st.session_state.new_word:
st.session_state.french_word, st.session_state.correct_translation = get_random_word()
st.session_state.new_word = False
st.write(f"Traduisez le mot suivant du français à l'anglais : **{st.session_state.french_word}**")
user_translation = st.text_input("Votre traduction en anglais :")
st.session_state.new_word = st.button("🆕 Nouveau mot")
if user_translation.lower() == st.session_state.correct_translation.lower():
st.success("Bonne traduction !")
elif user_translation != "":
st.error(f"Mauvaise traduction. La traduction correcte était : **{st.session_state.correct_translation}**")
if __name__ == "__main__":
main()
I’ve used Streamlit’s session_state to store the state of certain variables (words, df, french_word, correct_translation, and new_word) across reloads. This way, when a user submits a translation, the app doesn’t lose the current word and its correct translation. The new_word button now sets a flag in the session state, which triggers the fetching of a new word when pressed.
Below is a code improvement, as it seems the red callout was mistakenly appearing with each button in my previous code:
import streamlit as st
import pandas as pd
import numpy as np
def main():
st.title("Application de traduction français-anglais")
# Initialize session state variables if they don't exist
if 'words' not in st.session_state:
st.session_state.words = {
"French": ["Bonjour", "Chat", "Maison", "Livre", "Ordinateur"],
"English": ["Hello", "Cat", "House", "Book", "Computer"]
}
if 'df' not in st.session_state:
st.session_state.df = pd.DataFrame(st.session_state.words)
# Function to get a random word
def get_random_word():
random_index = np.random.randint(len(st.session_state.df))
return st.session_state.df.iloc[random_index]["French"], st.session_state.df.iloc[random_index]["English"]
# Initialize or update random word and translation
if 'french_word' not in st.session_state or 'correct_translation' not in st.session_state or st.button("🆕 Nouveau mot"):
st.session_state.french_word, st.session_state.correct_translation = get_random_word()
st.write(f"Traduisez le mot suivant du français à l'anglais : **{st.session_state.french_word}**")
user_translation = st.text_input("Votre traduction en anglais :").strip()
submit_button = st.button("Soumettre la traduction")
# Check if the user's translation is correct or incorrect, only when submit button is pressed
if submit_button and user_translation:
if user_translation.lower() == st.session_state.correct_translation.lower():
st.success("Bonne traduction !")
else:
st.error(f"Mauvaise traduction. La traduction correcte était : **{st.session_state.correct_translation}**")
if __name__ == "__main__":
main()
I did figure it out yesterday by using session_state. The only difference is that I use st.rerun() with my clear word button like so :
if "french_word" not in st.session_state:
(
st.session_state.french_word,
st.session_state.correct_translation,
) = get_random_word(data)
...
clear = st.form_submit_button(
label="🆕 Obtenir un nouveau mot aléatoire"
)
# Rerun when new word button is pressed by user
(
st.session_state.french_word,
st.session_state.correct_translation,
) = get_random_word(data)
st.rerun()
I suppose your answer is the prefered way of doing it ?
Thanks for stopping by! We use cookies to help us understand how you interact with our website.
By clicking “Accept all”, you consent to our use of cookies. For more information, please see our privacy policy.
Cookie settings
Strictly necessary cookies
These cookies are necessary for the website to function and cannot be switched off. They are usually only set in response to actions made by you which amount to a request for services, such as setting your privacy preferences, logging in or filling in forms.
Performance cookies
These cookies allow us to count visits and traffic sources so we can measure and improve the performance of our site. They help us understand how visitors move around the site and which pages are most frequently visited.
Functional cookies
These cookies are used to record your choices and settings, maintain your preferences over time and recognize you when you return to our website. These cookies help us to personalize our content for you and remember your preferences.
Targeting cookies
These cookies may be deployed to our site by our advertising partners to build a profile of your interest and provide you with content that is relevant to you, including showing you relevant ads on other websites.