Spaces:
Sleeping
Sleeping
File size: 6,435 Bytes
1be2c8e b048fbe 1be2c8e 7898e7d 1be2c8e b048fbe 1be2c8e b048fbe 1be2c8e b048fbe 1be2c8e b048fbe 1be2c8e b048fbe 1be2c8e b048fbe 1be2c8e b048fbe 1be2c8e b048fbe |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 |
import os
import pickle
from pathlib import Path
import streamlit as st
import streamlit_authenticator as stauth
from streamlit_feedback import streamlit_feedback
import traceback
import uuid
from dataset_loader import load_dataset
from dotenv import load_dotenv
load_dotenv()
if not os.path.isdir("spsetia_chatbot_data"):
load_dataset()
from spsetia_chatbot_data.utils import (
run_conversation,
record_db,
hashed_passwords,
greeting,
save_feedback
)
st.set_page_config(page_title="S P Setia Chatbot", page_icon=":robot:", layout="wide")
# --- USER AUTHENTICATION ---
names = ["S P Setia Admin"]
usernames = ["spsetia_admin"]
authenticator = stauth.Authenticate(
names,
usernames,
hashed_passwords,
"spsetia_chatbot",
"eqiddnksadjw",
cookie_expiry_days=30,
)
name, authentication_status, username = authenticator.login("Login", "main")
if authentication_status == False:
st.error("Username/password is incorrect")
if authentication_status == None:
st.warning("Please enter your username and password")
if authentication_status:
st.sidebar.title(f"S P Setia Chatbot")
st.sidebar.header(f"Welcome {name}")
authenticator.logout("Logout", "sidebar")
if st.sidebar.button("Refresh Chat"):
st.session_state.messages = [
{
"role": "assistant",
"content": greeting,
}
]
if "messages" not in st.session_state:
st.session_state.messages = [
{
"role": "assistant",
"content": greeting,
}
]
if "chat_history" not in st.session_state:
st.session_state.chat_history = []
if "fbk" not in st.session_state:
st.session_state.fbk = str(uuid.uuid4())
def display_answer():
for message in st.session_state.messages:
with st.chat_message(message["role"]):
st.write(message["content"])
def create_answer(prompt):
st.session_state.messages.append({"role": "user", "content": prompt})
with st.chat_message("user"):
st.write(prompt)
if st.session_state.messages[-1]["role"] != "assistant":
try:
with st.chat_message("assistant"):
with st.spinner("Thinking..."):
response = run_conversation(
st.session_state.messages, prompt, username
)
qa_id = response[4]
prompt_tokens = response[5]
completion_tokens = response[6]
if response[3]:
if isinstance(response[0], list):
answer = ""
for item in response[0]:
answer += f"""{item[0]}\n"""
st.text(item[0])
for image in item[1]:
if image:
st.image(image)
reference = f""" \n\nReference \nfolder: {response[2]["folder"]} \nfile: {response[2]["file"]}"""
st.text(reference)
answer += reference
record_db(
content=answer,
qa_id=qa_id,
msg_mode=1,
recipient_id=username,
prompt_tokens=prompt_tokens,
completion_tokens=completion_tokens,
)
else:
answer = response[0]
reference = f""" \n\nReference \nfolder: {response[2]["folder"]} \nfile: {response[2]["file"]}"""
answer += reference
st.text(answer)
record_db(
content=answer,
qa_id=qa_id,
msg_mode=1,
recipient_id=username,
prompt_tokens=prompt_tokens,
completion_tokens=completion_tokens,
)
else:
answer = response[0]
st.text(answer)
if images := response[1]:
if isinstance(images, list):
for image in images:
st.image(image)
record_db(
content=answer,
qa_id=qa_id,
msg_mode=1,
recipient_id=username,
prompt_tokens=prompt_tokens,
completion_tokens=completion_tokens,
)
message = {"role": "assistant", "content": answer}
st.session_state.messages.append(message)
st.session_state.chat_history.append(
{
"question": prompt,
"answer": answer,
}
)
except:
st.error("An error occurred. Please try again.")
traceback.print_exc()
display_answer()
if prompt := st.chat_input():
create_answer(prompt)
def fbcb(response):
data = st.session_state.chat_history[-1]
question = data["question"]
answer = data["answer"]
print(question, answer, response)
save_feedback(question, answer, response)
st.success("Thank you for your feedback!")
st.session_state.fbk = str(uuid.uuid4())
streamlit_feedback(
feedback_type="thumbs",
optional_text_label="[Optional]",
align="flex-start",
key=st.session_state.fbk,
on_submit=fbcb,
)
# {'type': 'thumbs', 'score': 'π', 'text': 'bad'}
# {'type': 'thumbs', 'score': 'π', 'text': 'good'}
|