File size: 4,871 Bytes
1be2c8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce4cdbe
1be2c8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e5935ce
1be2c8e
 
 
e5935ce
1be2c8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import pickle
from pathlib import Path
import streamlit as st
import streamlit_authenticator as stauth
import traceback
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
)


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}
        ]

    for message in st.session_state.messages:
        with st.chat_message(message["role"]):
            st.write(message["content"])

    if prompt := st.chat_input():
        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)
        except:
            st.error("An error occurred. Please try again.")
            traceback.print_exc()