St.pages one page doesn't load the content

Hi everyone,
I’m moving my streamlit to the new st.pages multipage from the old school /pages. After revising the code, some of my pages that are quiet simple e.g. About page, work exactly as they supposed to. But some pages don’t load the contet.
I think it’s a simple issue, but I have no background in computer science, and this code was written by a programmer a while ago. I spent all day yesterday (about 8 hours) trying to fix this but coudln’t. I thought maybe it’s the Showtopinfo function that is causing it. But eventhough I removed it from the top of code, and also from the ‘main’ at the end, the problem persisted.

Here’s link to my the page that doesn’t work:

Here’s my code:

#page name is Rubric.py
import openai
from openai import OpenAI
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Paragraph
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.pdfgen import canvas
from docx import Document
from io import BytesIO
import streamlit as st
from modules.streamlit_chat import message
from modules.OpenAI.data_loader import DataHandler
from modules.GoogleSheet.googleSheetOperation import GoogleSheetHelper
import random
import time
import string
import json

client = OpenAI(api_key=st.secrets["Make_Your_Own_Chatbot"])

def get_google_sheet_helper():
    return GoogleSheetHelper('data/googleSheet/my_key.json', 'Safe')

def get_random_value():
    if 'random_value' not in st.session_state:
        characters = string.ascii_uppercase + string.ascii_lowercase + string.digits
        tag = ''.join(random.choice(characters) for _ in range(6))
        st.session_state.random_value = tag
        
    return st.session_state.random_value


def showTopInfo():
    if "page_title" not in st.session_state:
        st.session_state['page_title'] = "Rubric Builder"
    else:
        if st.session_state['page_title'] != "Rubric Builder":
            st.session_state['generated'] = []
            st.session_state['past'] = []
            st.session_state['messages'] = [
                {"role": "system", "content": ''}
            ]
            st.session_state['page_title'] = "Rubric Builder"



def load_params_from_json(filename):
    with open(filename, 'r') as file:
        data = json.load(file)
    return data

def write_params_to_json(filename, data):
    with open(filename, 'w') as file:
        json.dump(data, file, indent = 4)

def create_chat_docx(messages):
    doc = Document()
    for message in messages:
        if message['role'] != "system":  
            doc.add_paragraph(f"{message['role']}: {message['content']}")
    doc_io = BytesIO()
    doc.save(doc_io)
    doc_io.seek(0)
    return doc_io

def create_chat_pdf(messages):
    pdf_io = BytesIO()
    doc = SimpleDocTemplate(pdf_io, pagesize=letter)
    styles = getSampleStyleSheet()
    flowables = []

    for message in messages:
        if message['role'] != "system": 
            text = f"{message['role']}: {message['content']}"
            para = Paragraph(text, styles['Normal'])
            flowables.append(para)

    doc.build(flowables)
    pdf_io.seek(0)
    return pdf_io

def main():

    st.session_state["page_type"] = "Rubric_Generator_Bot"

    st.session_state["bot_key"] = ["Response", "AI"]

    if "AI_Role" not in st.session_state:
        st.session_state["AI_Role"] = ""

    if "saved" not in st.session_state:
        st.session_state["saved"] = False

    if "purged" not in st.session_state:
        st.session_state["purged"] = False

    if "edit_t" not in st.session_state:
        st.session_state["edit_t"] = True


    dh = DataHandler()

    yml_files = dh.read_dir("yml")
    

    

    full_path = ""

    data = {}
    

    st.session_state.params = load_params_from_json('data/chat_bot_2/default.json')

    if "file_created" not in st.session_state or len(st.session_state["file_created"]) != len(yml_files):

        st.session_state["file_created"] = yml_files
    else:
        st.session_state["file_created"] = yml_files


    if "file_deleted" not in st.session_state:
        st.session_state["file_deleted"] = ""
    
    if 'messages' not in st.session_state:
        st.session_state['messages'] = [
            {"role": "system", "content": ""}
        ]
    
    
    PASSWORD = "XXXXX"

    if 'password_ok' not in st.session_state:
        st.session_state.password_ok = False  # default is no

    password_input = st.sidebar.text_input("Admin login", type="password")

    if password_input:
        if password_input == PASSWORD:
            st.session_state.password_ok = True
            st.sidebar.success("Welcome admin!")
        else:
            st.sidebar.error("Wrong pass!")


    clear_button = st.sidebar.button("Clear Conversation", key="clear")
    if clear_button:
                st.session_state['generated'] = []
                st.session_state['past'] = []
                st.session_state['messages'] = [
                    {"role": "system", "content": ''}
                ]
    
    if st.sidebar.button('Download chat'):
        st.session_state['show_download_buttons'] = True

    if st.session_state.get('show_download_buttons', False):
        chat_docx_io = create_chat_docx(st.session_state['messages'])
        st.sidebar.download_button(label="Word",
                                data=chat_docx_io,
                                file_name="chat_conversations.docx",
                                mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document")

        chat_pdf_io = create_chat_pdf(st.session_state['messages'])
        st.sidebar.download_button(label="PDF",
                                data=chat_pdf_io,
                                file_name="chat_conversations.pdf",
                                mime="application/pdf")
    # if correct
    if st.session_state.password_ok:
    
        option = st.sidebar.selectbox(
            "Select your desired app",
            
            st.session_state["file_created"] + ["Create new file"],
        )
        print('++++++++++++++++++')
        print(option)

        
        if "previous_selection" not in st.session_state:
            st.session_state["previous_selection"] = option
        else:
            if st.session_state["previous_selection"] != option:
                st.session_state["previous_selection"] = option
                st.experimental_rerun()

        st.session_state["current_selection"] = option  
        
        

        if st.session_state["current_selection"] != option:
            st.session_state["current_selection"] = option
            if "init" in data:
                st.session_state['messages'][0]['content'] = data["init"]["intro"]

        
        
        if st.session_state["current_selection"] != "Create new file":
            
            st.session_state.current_index = st.session_state["file_created"].index(st.session_state["current_selection"])
            st.session_state.params["default_index"] = st.session_state.current_index
            write_params_to_json('data/default_setting/default.json', st.session_state.params)
  


        if option == "Create new file":
            with st.form(key='create_form'):
                
                new_file_name = st.sidebar.text_input("Enter file Name")
                create_button_clicked = st.sidebar.button("Create")
                
                if create_button_clicked and new_file_name:
                    if new_file_name + ".yml" in st.session_state["file_created"]:
                        st.markdown("Unable to create the file - A file with the same name exists")
                    else:
                        dh.file_create(new_file_name)
                        

                        st.experimental_rerun()
            
        else:
            full_path = dh.get_path("data/" + st.session_state["page_type"] + "/" + option)
            print('-------------------+++++++++++++++++++++++')
            print(full_path)
            data = dh.yml_to_object(full_path)

            

            intro = st.sidebar.text_area(label='Instruction for AI', value=data["init"]["intro"], disabled= st.session_state["edit_t"])

            


            description = st.sidebar.text_area(label='Description for user', value=data["init"]["description"],disabled=st.session_state["edit_t"])
            st.caption(description)

            col1, col2, col3 = st.sidebar.columns([1, 1, 1])

            with col1:
                if st.button("Edit", disabled=not st.session_state["edit_t"]):
                    print(st.session_state.params)
                    st.session_state["edit_t"] = False
                    st.experimental_rerun()
            with col2:
                if st.button("Save", disabled=st.session_state["edit_t"]):
                    st.session_state["edit_t"] = True
                    data["init"]["intro"] = intro
                    data["init"]["description"] = description

                    dh.file_write(data, full_path)
                    st.session_state["saved"] = True
                    st.experimental_rerun()

            with col3:
                if st.button("Purge File"):
                    st.session_state["file_deleted"] = option
                    
                    dh.file_del(full_path)
               
                    st.session_state["purged"] = True
                    
                    st.experimental_rerun()

            if st.session_state["saved"]:
                st.balloons()
                st.success("The data has been successfully saved")
                st.session_state["saved"] = False

        if 'messages' in st.session_state and "init" in data:
            if len(st.session_state['messages']) > 0:
                st.session_state['messages'][0]['content'] = data["init"]["intro"]
            else:
                st.session_state['messages'] = [{'content': data["init"]["intro"]}]

        if 'generated' not in st.session_state:
            st.session_state['generated'] = []
        if 'past' not in st.session_state:
            st.session_state['past'] = []

        if 'messages' not in st.session_state:
            st.session_state['messages'] = [
                {"role": "system", "content": ""}
            ]


        if 'model_name' not in st.session_state:
            st.session_state['model_name'] = []

        if st.session_state["current_selection"] != "Create new file":
            st.sidebar.title("Sidebar")
            model_index = 0 if  data['paras']['model_name'] == "GPT-3.5" else 1
            model_name = st.sidebar.radio("Choose a model:", ("GPT-3.5", "GPT-4"), index=model_index) 
            counter_placeholder = st.sidebar.empty()
 
            
            with st.sidebar:
                st.markdown("## Model Parameters")
                max_tokens = st.number_input('Max token',
                value = data["paras"]["max_tokens"],
                help="This parameter limits the maximum length of the model output"
                )
                temperature = st.slider(
                    "Temperature",
                    0.0,
                    2.0,
                    data["paras"]['temperature'],
                    help="Adjusts randomness of outputs, greater than 1 is random and 0 is deterministic, 0.75 is a good starting value.",
                )
                
                top_p = st.slider(
                    "Top P",
                    0.0,
                    1.0,
                    data["paras"]["top_p"],
                    help="When decoding text, samples from the top p percentage of most likely tokens; lower to ignore less likely tokens",
                )
                frequency_penalty = st.slider(
                    "frequency penalty",
                    0.0,
                    2.0,
                    data["paras"]["frequency_penalty"],
                    help="Positive values reduce the probability of tokens that occur more often in a given context, while negative values increase their probability."
                )
                presence_penalty = st.slider(
                    "presence penalty",
                    0.0,
                    2.0,
                    data["paras"]["presence_penalty"],
                    help="A positive value increases the probability that a new token will appear, while a negative value decreases it.",
                )

            new_params = {
                "file_name":st.session_state.current_selection,
                "model_name":model_name,
                "max_tokens": max_tokens,
                "temperature": temperature,
                "top_p": top_p,
                "frequency_penalty": frequency_penalty,
                "presence_penalty": presence_penalty
            }
            data['paras']['model_name'] = model_name
            data['paras']['max_tokens'] = max_tokens
            data['paras']['temperature'] = temperature
            data['paras']['top_p'] = top_p
            data['paras']['frequency_penalty'] = frequency_penalty
            data['paras']['presence_penalty'] = presence_penalty
            print('-----',data['paras']['max_tokens'])
            full_path = dh.get_path("data/" + st.session_state["page_type"] + "/" + st.session_state.current_selection)
            print('---------', full_path)
            dh.file_write(data, full_path)

            if data['paras']['model_name'] == "GPT-3.5":
                model = "gpt-3.5-turbo"
                st.session_state["openai_model"] = "gpt-3.5-turbo"
            else:
                model = "gpt-4-turbo-2024-04-09"
                st.session_state["openai_model"] = "gpt-4-turbo-2024-04-09"

                

            if data['paras']['model_name'] == "GPT-3.5":
                model_to_use = "gpt-3.5-turbo"
                st.session_state["openai_model"] = "gpt-3.5-turbo"
            else:
                model_to_use = "gpt-4-turbo-2024-04-09"
                st.session_state["openai_model"] = "gpt-4-turbo-2024-04-09"


        
    else:
        option = yml_files[st.session_state.params['default_index']]
        full_path = dh.get_path("data/" + st.session_state["page_type"] + "/" + option)

        data = dh.yml_to_object(full_path)
     

        st.caption(data["init"]["description"])


       

    if 'messages' in st.session_state and "init" in data:
        st.session_state['messages'][0]['content'] = data["init"]["intro"]

    if 'generated' not in st.session_state:
        st.session_state['generated'] = []
    if 'past' not in st.session_state:
        st.session_state['past'] = []

    if 'messages' not in st.session_state:
        st.session_state['messages'] = [
            {"role": "system", "content": ""}
        ]


    if 'model_name' not in st.session_state:
        st.session_state['model_name'] = []
    if 'cost' not in st.session_state:
        st.session_state['cost'] = []
    if 'total_tokens' not in st.session_state:
        st.session_state['total_tokens'] = []
    if 'total_cost' not in st.session_state:
        st.session_state['total_cost'] = 0.0

    if "openai_model" not in st.session_state:
        st.session_state["openai_model"] = "gpt-4-turbo-2024-04-09"


    if "messages" not in st.session_state:
        st.session_state.messages = []

    for message in st.session_state.messages:

        if message["role"] != "system":
            with st.chat_message(message["role"]):
                st.markdown(message["content"])

        

    if prompt := st.chat_input("You:"):
        st.session_state.messages.append({"role": "user", "content": prompt})
        prompt_list = [prompt]
        with st.chat_message("user"):
            st.markdown(prompt)
            
        print(st.session_state.messages)
        
        with st.chat_message("assistant"):
            message_placeholder = st.empty()
            full_response = ""
            for response in client.chat.completions.create(model=st.session_state["openai_model"],
            messages=[
                {"role": m["role"], "content": m["content"]}
                for m in st.session_state.messages
            ],
            temperature=data['paras']['temperature'],
            max_tokens=data['paras']["max_tokens"],
            top_p=data['paras']["top_p"],
            frequency_penalty=data['paras']["frequency_penalty"],
            presence_penalty=data['paras']["presence_penalty"],
            stream=True):
                full_response += response.choices[0].delta.content if response.choices[0].delta.content is not None else ""

                message_placeholder.markdown(full_response + "▌")
            message_placeholder.markdown(full_response)
        st.session_state.messages.append({"role": "assistant", "content": full_response})
        response_list = [full_response]
        upload_list = prompt_list + response_list

if __name__ == "__main__":

    showTopInfo()
    main()

Hi Armin! Try removing the if condition at the end.

Explanation: Only the script that you pass to Streamlit on the command line will have its __name__ set to "__main__", so that if condition won’t run for other files.

In other words, replace this:

if __name__ == "__main__":

    showTopInfo()
    main()

…with this:

showTopInfo()
main()

Hi Thiago,

THank you so so so much. I really appreciate it. It works :slight_smile: You’re a legend.

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