102 lines
3.2 KiB
Python
102 lines
3.2 KiB
Python
import streamlit as st
|
|
import requests
|
|
import datetime
|
|
import json
|
|
import os
|
|
from streamlit_cookies_manager import CookieManager
|
|
|
|
# Initialize the Cookie Manager (no encryption)
|
|
cookies = CookieManager(prefix="ktosiek/streamlit-cookies-manager/")
|
|
if not cookies.ready():
|
|
st.stop()
|
|
|
|
# Define the file path for storing user data
|
|
user_data_file = "user_data.json"
|
|
|
|
# Helper function to load user data from JSON file
|
|
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
|
|
if cookies.get('user_id') is None: # Correct check for user_id in cookies
|
|
cookies['user_id'] = str(datetime.datetime.now().timestamp()) # Use timestamp as a unique ID
|
|
cookies.save()
|
|
|
|
user_id = cookies.get('user_id')
|
|
# st.write(f"Current User ID: {user_id}")
|
|
|
|
# Check if the user exists in the JSON file
|
|
if user_id not in user_data:
|
|
timestamp = str(datetime.datetime.now().isoformat()) # Unique timestamp for each user
|
|
user_data[user_id] = {
|
|
"timestamp": timestamp,
|
|
"messages": [] # Empty chat history
|
|
}
|
|
save_user_data(user_data)
|
|
st.write("New user detected! Created user entry in the JSON file.")
|
|
else:
|
|
# If user exists, load the chat history from the JSON file
|
|
st.session_state.messages = user_data[user_id]["messages"]
|
|
# st.write("Returning user detected! Loaded chat history from the JSON file.")
|
|
|
|
# Function to send POST request to a local server
|
|
def send_post_request(prompt):
|
|
url = "http://localhost:19194/" # Update this to your actual server URL
|
|
payload = prompt.title()
|
|
response = requests.post(url, json=payload)
|
|
json = response.json()
|
|
if "response" in json:
|
|
return json["response"]
|
|
else:
|
|
return json
|
|
|
|
st.title('Ask Maargdarshak')
|
|
|
|
if 'messages' not in st.session_state:
|
|
st.session_state.messages = []
|
|
|
|
# Load chat history from session state
|
|
for message in st.session_state.messages:
|
|
st.chat_message(message['role']).markdown(message['content'])
|
|
|
|
# Prompt input
|
|
prompt = st.chat_input("Ask your question here")
|
|
|
|
if prompt:
|
|
# Display the user prompt in the chat UI
|
|
st.chat_message('user').markdown(prompt)
|
|
st.session_state.messages.append({'role': 'user', 'content': prompt})
|
|
|
|
# Get the bot's response via a POST request
|
|
with st.spinner("Fetching data..."):
|
|
try:
|
|
response = send_post_request(prompt)
|
|
except Exception as e:
|
|
response = f"An error occurred: {e}"
|
|
st.success("Data fetched successfully!")
|
|
|
|
# Display the bot's response in the chat UI
|
|
st.chat_message('bot').markdown(response)
|
|
st.session_state.messages.append({'role': 'bot', 'content': response})
|
|
|
|
# Update the user's chat history in the JSON file
|
|
user_data[user_id]["messages"] = st.session_state.messages
|
|
save_user_data(user_data)
|
|
|
|
# Save updated history to cookies (optional)
|
|
cookies['history'] = st.session_state.messages
|
|
cookies.save()
|