App Reruns upon User Input

Hi, I have a problem with my app, So its an NLP app that accepts files in pdf format, the app fits on the document the takes user input and I have to grab the text and query the Pre-trained bert model , but upon the user pressing the predict button after writing the query the app reruns all over again, here is my code

import streamlit as st
import pandas as pd
import joblib
import cdqa
import tabula
import docx2txt
from PyPDF2 import PdfFileReader
import os
import pandas as pd
from ast import literal_eval
import urllib.request
from cdqa.utils.converters import pdf_converter
from cdqa.utils.filters import filter_paragraphs
from cdqa.pipeline import QAPipeline
from cdqa.utils.download import download_model

def read_pdf(directory_path='./tempDir/'):
    df = pdf_converter(directory_path)
    return df
#def load model

def load_model():
    model = joblib.load('models/bert_qa.joblib')
    cdqa_pipeline = QAPipeline(reader=model, max_df=1.0, )
    return cdqa_pipeline

st.subheader("Home")
docx_file = st.file_uploader("Upload Document",type=["pdf"])
if st.button("Process"):

            # text = st.text_input("input your query")
    if docx_file is not None:
                #see details of the file
                
        file_details = {"filename":docx_file.name,
                                "filetype":docx_file.type,
                                "filesize":docx_file.size}
        st.json(file_details)
        with open(os.path.join("tempDir",docx_file.name),"wb") as f:
            
            f.write(docx_file.getbuffer())
        df = read_pdf()
        with st.spinner("fitting the model...."):
            pipeline = load_model()
            pipeline.fit_retriever(df=df)
            st.write(type(docx_file))
            st.success("model has been fitted")
            text = st.text_input("Query Model",placeholder="Type your query")

        if st.button("Predict"):
            if text is not None:

                prediction = pipeline.predict(text)
                res = { "Query" : text,
                "Answer": prediction[0],
                "Title" : prediction[1],
                "Paragraph":prediction[2]}
                st.write(res)
                st.json(res)
            else:
                st.warning("you have not typed your query")

Hi @Brainiac,

First, welcome to the Streamlit community! :tada: :partying_face: :star2: :tada: :tada: :partying_face:

You will need to use session state to track if the process button you have has been clicked at any time in the past.

This is a pretty simple fix for you! Here are some links to help you add state to your app:

Happy Streamlit-ing!
Marisa

Thank you @Marisa_Smith let me try it out

I think the session.states needs a better explanations with more examples

2 Likes

I couldnt agree more

1 Like

Hey @Brainiac and @Rockkley!

I agree too! The concept of session state can be difficult to wrap your head around, and we get lots of questions on the forum about it.

I’m actually working now at putting some more examples together for the session state, so if you have any suggestions or examples that you think would be helpful for you and others let me know!

Happy Streamlit-ing!
Marisa

Hi @Brainiac ,

Could you resolve this using SessionState as @Marisa_Smith suggested ?
If not, a quick fix can be using a st.checkbox() instead of st.button()

In this way you can keep your app in an active state. You can also use SessionState for the active state of your button. I have referred to this before, here’s a link to this workaround mentioned in my blog post / Youtube video, indeed it’s a very common user issue in the forum.

Best,
Avra

1 Like

Hi @AvratanuBiswas I actually tried the st.checkbox()idea and it worked thank you I also tried using using session state too and everything worked amazingly well, thank you :partying_face: :partying_face: you guys are amazing @Marisa_Smith @Rockkley I appreciate

2 Likes

Hey @Brainiac , I’m glad that it worked for you :balloon:

There is a well written twitter thread by @dataprofessor about Streamlit SessionState, do check it out incase you are interested.

Best,
Avra

1 Like

I will be sure to check it out

Session state work out for me

def is_game_active():
    if 'game_active' in st.session_state.keys() and st.session_state['game_active']:
        return True
    else:
        return False

if is_game_active():
    # TODO: implement logic to fetch random_question (and options) on each rerun
    res = st.selectbox('random_question', ['a','b','c','d'])
    if st.button('confirm'):
        st.session_state['random_question'] = res # saves answers for each random question in sesion state for future reference
        st.info('you chose option: ' + res)
        sleep(1)
        st.experimental_rerun()
else:
    if st.button('start game'):
        st.session_state['game_active'] = True
        st.experimental_rerun()
st.write(st.session_state)

This is good example that could help

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