Compare commits

..

No commits in common. "2c15c026c849966b9f9b0c4f1e129f6f3a7472b0" and "1b842ff917b1f64f56c7b929f2d94756fa5cc684" have entirely different histories.

63
main.py

@ -1,8 +1,7 @@
import streamlit as st import streamlit as st
import requests import requests
import datetime import datetime
import json from pymongo import MongoClient
import os
from streamlit_cookies_manager import CookieManager from streamlit_cookies_manager import CookieManager
# Inject the scroll control HTML/JS # Inject the scroll control HTML/JS
@ -15,47 +14,35 @@ cookies = CookieManager(prefix="ktosiek/streamlit-cookies-manager/")
if not cookies.ready(): if not cookies.ready():
st.stop() st.stop()
# Define the file path for storing user data # Connect to MongoDB
user_data_file = "user_data.json" client = MongoClient("mongodb://localhost:27017/") # Adjust your MongoDB connection URI
db = client["chatbot_db"] # Database name
# Helper function to load user data from JSON file users_collection = db["users"] # Collection to store user data
def load_user_data():
if os.path.exists(user_data_file):
with open(user_data_file, 'r') as file:
return json.load(file)
else:
save_user_data({})
return {}
# Helper function to save user data to JSON file
def save_user_data(data):
with open(user_data_file, 'w') as file:
json.dump(data, file, indent=4)
# Load existing user data
user_data = load_user_data()
# Generate a user ID and store it in cookies if not already set # Generate a user ID and store it in cookies if not already set
if cookies.get('user_id') is None: # Correct check for user_id in cookies if 'user_id' not in cookies:
cookies['user_id'] = str(datetime.datetime.now().timestamp()) # Use timestamp as a unique ID cookies['user_id'] = str(datetime.datetime.now().timestamp()) # Use timestamp as a unique ID
cookies.save() cookies.save()
user_id = cookies.get('user_id') user_id = cookies.get('user_id')
# st.write(f"Current User ID: {user_id}") # st.write(f"Current User ID: {user_id}")
# Check if the user exists in the JSON file # Check if the user exists in the database
if user_id not in user_data: user_data = users_collection.find_one({"user_id": user_id})
# If user doesn't exist, create a new entry with the current timestamp and empty chat history
if not user_data:
timestamp = str(datetime.datetime.now().isoformat()) # Unique timestamp for each user timestamp = str(datetime.datetime.now().isoformat()) # Unique timestamp for each user
user_data[user_id] = { users_collection.insert_one({
"user_id": user_id,
"timestamp": timestamp, "timestamp": timestamp,
"messages": [] # Empty chat history "messages": [] # Empty chat history
} })
save_user_data(user_data) st.write("New user detected! Created user entry in the database.")
st.write("New user detected! Created user entry in the JSON file.")
else: else:
# If user exists, load the chat history from the JSON file # If user exists, load the chat history from the database
st.session_state.messages = user_data[user_id]["messages"] st.session_state.messages = user_data["messages"]
# st.write("Returning user detected! Loaded chat history from the JSON file.") # st.write("Returning user detected! Loaded chat history from the database.")
# Function to send POST request to a local server # Function to send POST request to a local server
def send_post_request(prompt): def send_post_request(prompt):
@ -134,10 +121,16 @@ if prompt:
st.chat_message('bot').markdown(response) st.chat_message('bot').markdown(response)
st.session_state.messages.append({'role': 'bot', 'content': response}) st.session_state.messages.append({'role': 'bot', 'content': response})
# Update the user's chat history in the JSON file # Update the user's chat history in the database
user_data[user_id]["messages"] = st.session_state.messages users_collection.update_one(
save_user_data(user_data) {"user_id": user_id},
{"$push": {"messages": {'role': 'user', 'content': prompt}}},
)
users_collection.update_one(
{"user_id": user_id},
{"$push": {"messages": {'role': 'bot', 'content': response}}},
)
# Save updated history to cookies (optional) # Save updated history to cookies (optional, MongoDB handles persistence)
cookies['history'] = st.session_state.messages cookies['history'] = st.session_state.messages
cookies.save() cookies.save()