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()
The app is running locally.
Salut @CDucloux !
I fixed it for you:
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.
I hope that helps
Charly
Hello again @CDucloux ,
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()
This should now work as expected
Thanks,
Charly
Hey Charly, many thanks for your answer
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 ?
system
Closed
November 24, 2023, 10:35am
6
This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.