ankit
ankit

Reputation: 347

Final file content rolled back to initial file content in streamlit

I have created a simple streamlit application to browse files and folders and written the Python code as:

import streamlit as st
import tkinter as tk
from tkinter import filedialog
import os
import pandas as pd
from pathlib import Path

uploaded_files = st.file_uploader("Upload your Python/SQL/C file", type=["py","sql","c"], accept_multiple_files=True)
    
st.session_state.file_contents = ""

root = tk.Tk()
root.withdraw()
root.wm_attributes('-topmost', 1)
st.write('Please select a folder:')
clicked = st.button('Browse Folder')
    
if clicked:
    dirname = str(filedialog.askdirectory(master=root))
    files = [file for file in os.listdir(dirname)]
    output = pd.DataFrame({"File Name": files})
    st.table(output)
    for file in files:
        st.session_state.file_contents += Path(os.path.join(dirname, file)).read_text()   
for uploaded_file in uploaded_files:
    st.session_state.file_contents += uploaded_file.read().decode('utf-8') + "\n"
print("File content initially:",st.session_state.file_contents)

Now when I select a file, say file1, after clicking on "Browse files" and select a folder which contains file2 by clicking on "Browse Folder" then st.session_state.file_contents is fetching the file content of both file1 and file2.

Until now the code is working fine. But when I write the code as:

if (uploaded_files and st.session_state.file_contents and st.session_state.messages) is not None:
    for message in st.session_state.messages:
        if message["role"] == "user":
            st.chat_message("human").markdown(message["content"])
        if message["role"] == "ai":
            st.chat_message("ai").markdown(message["content"])
    if prompt := st.chat_input("Generate test cases for the attached file(s)"):
        st.session_state.messages.append({"role": "user", "content": prompt})
        with st.chat_message("user"):
            st.markdown(prompt)
        print("File content before calling a function:",st.session_state.file_contents)

Now, st.session_state.file_contents contains only the content of file1, not file2.

So, can anyone please explain why I am not getting the content of file2, why does it disappear after calling st.chat_input()?

Any help would be appreciated.

Upvotes: 0

Views: 35

Answers (0)

Related Questions