Compare commits

...

10 Commits

3 changed files with 209 additions and 55 deletions

@ -1,4 +1,22 @@
# Steps to init # Steps to initialize the project
- just need to do this one time
`python -m venv .venv` ```sh
python -m venv .venv
```
```sh
source .venv/bin/active
```
## Steps to install dependencies
```sh
pip install -r requirements.txt
```
## Seps to run
```sh
streamlit run main.py
```
Make sure that [rust server](https://git.ssdd.dev/ssdd/hackpsuchatbot) is active before asking a prompt.

125
main.py

@ -1,80 +1,101 @@
import streamlit as st import streamlit as st
import requests import requests
import datetime
import json
import os
from streamlit_cookies_manager import CookieManager
# Initialize session state for prompt history # Initialize the Cookie Manager (no encryption)
if "history" not in st.session_state: cookies = CookieManager(prefix="ktosiek/streamlit-cookies-manager/")
st.session_state.history = [] 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 # Function to send POST request to a local server
def send_post_request(prompt): def send_post_request(prompt):
url = "http://localhost:19194/" # Update this to your actual server URL url = "http://localhost:19194/" # Update this to your actual server URL
payload = prompt.title() payload = prompt.title()
response = requests.post(url, json=payload) response = requests.post(url, json=payload)
return response.text json = response.json()
if "response" in json:
return json["response"]
else:
return json
st.title('Ask Maargdarshak')
# Custom CSS to fix the input box at the bottom of the page
st.markdown(
"""
<style>
.fixed-input-container {
position: fixed;
bottom: 0;
left: 0;
width: 100%;
background-color: #f9f9f9;
padding: 10px;
box-shadow: 0px -2px 10px rgba(0, 0, 0, 0.1);
z-index: 999;
}
.input-container input {
width: 80%;
padding: 10px;
font-size: 16px;
border-radius: 5px;
border: 1px solid #ccc;
margin-right: 10px;
}
.input-container button {
padding: 10px 20px;
font-size: 16px;
border: none;
background-color: #4CAF50;
color: white;
border-radius: 5px;
cursor: pointer;
}
.input-container button:hover {
background-color: #45a049;
}
.prompt-history {
margin-bottom: 120px; /* Space to ensure prompt history doesn't overlap input box */
}
</style>
""",
unsafe_allow_html=True
)
st.title('Ask maargdarshak')
if 'messages' not in st.session_state: if 'messages' not in st.session_state:
st.session_state.messages = [] st.session_state.messages = []
# Load chat history from session state
for message in st.session_state.messages: for message in st.session_state.messages:
st.chat_message(message['role']).markdown(message['content']) st.chat_message(message['role']).markdown(message['content'])
# Prompt input
prompt = st.chat_input("Ask your question here") prompt = st.chat_input("Ask your question here")
if prompt: if prompt:
# Display the user prompt in the chat UI
st.chat_message('user').markdown(prompt) st.chat_message('user').markdown(prompt)
st.session_state.messages.append({'role': 'user', 'content': prompt}) st.session_state.messages.append({'role': 'user', 'content': prompt})
response = send_post_request(prompt) # Get the bot's response via a POST request
print(response) 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.chat_message('bot').markdown(response)
st.session_state.messages.append({'role': 'bot', 'content': response}) st.session_state.messages.append({'role': 'bot', 'content': response})
# st.session_state.history.append((prompt, response))
# st.experimental_rerun()
# 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()

115
requirements.txt Normal file

@ -0,0 +1,115 @@
aiohappyeyeballs==2.4.3
aiohttp==3.10.10
aiosignal==1.3.1
altair==5.4.1
annotated-types==0.7.0
anyio==4.6.0
appnope==0.1.4
asttokens==2.4.1
async-timeout==4.0.3
attrs==24.2.0
backcall==0.2.0
beautifulsoup4==4.12.3
bleach==6.1.0
blinker==1.8.2
bs4==0.0.2
cachetools==5.5.0
certifi==2024.8.30
cffi==1.17.1
charset-normalizer==3.4.0
click==8.1.7
cryptography==43.0.1
decorator==5.1.1
defusedxml==0.7.1
dnspython==2.7.0
docopt==0.6.2
exceptiongroup==1.2.2
executing==2.1.0
fastjsonschema==2.20.0
frozenlist==1.4.1
gitdb==4.0.11
GitPython==3.1.43
h11==0.14.0
httpcore==1.0.6
httpx==0.27.2
idna==3.10
importlib_metadata==8.5.0
ipython==8.12.3
jedi==0.19.1
Jinja2==3.1.4
jsonpatch==1.33
jsonpointer==3.0.0
jsonschema==4.23.0
jsonschema-specifications==2024.10.1
jupyter_client==8.6.3
jupyter_core==5.7.2
jupyterlab_pygments==0.3.0
langchain==0.3.3
langchain-core==0.3.10
langchain-text-splitters==0.3.0
langsmith==0.1.134
Markdown==3.7
markdown-it-py==3.0.0
MarkupSafe==3.0.1
matplotlib-inline==0.1.7
mdurl==0.1.2
mistune==3.0.2
multidict==6.1.0
narwhals==1.9.3
nbclient==0.10.0
nbconvert==7.16.4
nbformat==5.10.4
numpy==1.26.4
orjson==3.10.7
packaging==24.1
pandas==2.2.3
pandocfilters==1.5.1
parso==0.8.4
pexpect==4.9.0
pickleshare==0.7.5
pillow==10.4.0
pipreqs==0.5.0
platformdirs==4.3.6
prompt_toolkit==3.0.48
propcache==0.2.0
protobuf==5.28.2
ptyprocess==0.7.0
pure_eval==0.2.3
pyarrow==17.0.0
pycparser==2.22
pydantic==2.9.2
pydantic_core==2.23.4
pydeck==0.9.1
Pygments==2.18.0
pymongo==4.10.1
python-dateutil==2.9.0.post0
pytz==2024.2
PyYAML==6.0.2
pyzmq==26.2.0
referencing==0.35.1
requests==2.32.3
requests-toolbelt==1.0.0
rich==13.9.2
rpds-py==0.20.0
six==1.16.0
smmap==5.0.1
sniffio==1.3.1
soupsieve==2.6
SQLAlchemy==2.0.35
stack-data==0.6.3
streamlit==1.39.0
streamlit-cookies-manager==0.2.0
tenacity==8.5.0
tinycss2==1.3.0
toml==0.10.2
tornado==6.4.1
traitlets==5.14.3
typing_extensions==4.12.2
tzdata==2024.2
urllib3==2.2.3
watchdog==5.0.3
wcwidth==0.2.13
webencodings==0.5.1
yarg==0.1.9
yarl==1.15.0
zipp==3.20.2