import streamlit as st import json import os import datetime # Define the path to the local JSON file where conversation will be stored FILE_PATH = "/home/sapan/PycharmProjects/maargdarshak/conversation_history.json" # Function to save prompt and response to local JSON file def save_to_local(prompt, response): data = { "prompt": prompt, "response": response, "timestamp": str(datetime.datetime.now()) } # If the file exists, load existing data, handle empty or corrupt files if os.path.exists(FILE_PATH): try: with open(FILE_PATH, 'r') as file: history = json.load(file) except json.JSONDecodeError: history = [] # If the file is empty or corrupted, start with an empty list else: history = [] # Append the new conversation entry history.append(data) # Save the updated history back to the JSON file with open(FILE_PATH, 'w') as file: json.dump(history, file, indent=4) # Function to load conversation history from local JSON file def load_from_local(): if os.path.exists(FILE_PATH): try: with open(FILE_PATH, 'r') as file: return json.load(file) except json.JSONDecodeError: return [] # Return empty list if the file is empty or corrupt return [] # Initialize session state to store conversation history for the session if "conversation" not in st.session_state: st.session_state["conversation"] = [] # Streamlit App st.title("Chatbot with Local Chat History") # Text input for user prompt user_input = st.text_input("Ask the chatbot something:") # If the user submits input if user_input: # Simulated response (for now it's echoing the input) response = f"Echo: {user_input}" # Save the current prompt and response to session state for chat history st.session_state["conversation"].append({"prompt": user_input, "response": response}) # Also save the conversation to local storage (JSON file) save_to_local(user_input, response) # Display the chat history (conversation for the session) st.write("### Chat History") for convo in st.session_state["conversation"]: st.write(f"**You**: {convo['prompt']}") st.write(f"**Bot**: {convo['response']}") st.write("---") # Button to show entire history from local JSON file if st.button("Show Full Local Conversation History"): st.write("### Full Local Conversation History") # Load history from the local file and display it full_history = load_from_local() for convo in full_history: st.write(f"**You**: {convo['prompt']}") st.write(f"**Bot**: {convo['response']}") st.write(f"Timestamp: {convo['timestamp']}") st.write("---")