Spaces:
Sleeping
Sleeping
File size: 9,051 Bytes
ff6be60 fda8b41 ff6be60 | 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 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 | import os
import time
import streamlit as st
import openai
import psycopg2
# Accessing environment variables
api_key = os.getenv('API') # OpenAI API key for generating chatbot
sql_host = os.getenv('SQL_HOST') # Host address for PostgreSQL database
db = os.getenv('DB') # Database name
user = os.getenv('USER') # Database user
password = os.getenv('PASSWORD') # Database password
chatbot_content = os.getenv('CONTENT') # Content for chatbot responses
emails = os.getenv('EMAILS') # List of authorised emails for login
login = os.getenv('LOGIN') # Predefined password for login validation
# Configuring OpenAI with API key
openai.api_key = api_key
def initialise_database():
'''
Initialise the PostgreSQL database by creating 'chatbot' table if it doesn't exist
'chatbot' table stores the user's name, email, question and the chatbot's response
Args: None
Returns: None
'''
# Details to connect to PostgreSQL database
conn = psycopg2.connect(
host=sql_host,
database=db,
user=user,
password=password
)
cursor = conn.cursor()
# Create table if doesn't already exist
cursor.execute('''
CREATE TABLE IF NOT EXISTS cb_chat_history (
email VARCHAR (50),
question VARCHAR(500),
answer VARCHAR
);
''')
# Commit transaction and close connection
conn.commit()
cursor.close()
conn.close()
def save_to_db(email, question, answer):
'''
Save chat history to PostgreSQL database.
Stores user's email, question and chatbot's response
Args: email, question, chatbot's reponse
Returns: none
'''
# Details to connect to PostgreSQL database
conn = psycopg2.connect(
host=sql_host,
database=db,
user=user,
password=password
)
cursor = conn.cursor()
# Insert chat history into table
cursor.execute('''
INSERT INTO cb_chat_history (email, question, answer)
VALUES (%s, %s, %s);
''', (email, question, answer)
)
# Commit transaction and close connection
conn.commit()
cursor.close()
conn.close()
def check_login(email, password):
'''
Validate email address and password. Email must be in the emails list, password must match correct password.
Args: email (str): The email address to validate.
password (str): The password to validate.
Returns: bool: True if email matches an email in list and password matches correct password, otherwise False.
'''
allowed_emails = emails
correct_password = login
return email.lower() in allowed_emails and password == correct_password
def type_text(text, placeholder):
'''
Simulate typing effect for chatbot responses
Args: text(str): Text to display
placeholder (streamlit.delta_generator.DeltaGenerator):Streamlit placeholder for displaying the text
Returns: None
'''
paragraphs = text.split('\n') # Split text by line breaks
formatted_text = ""
for paragraph in paragraphs:
words = paragraph.split() # Split each paragraph into words
for i in range(len(words) + 1):
current_text = " ".join(words[:i])
placeholder.markdown(formatted_text + current_text + " |") # Show current progress with cursor
time.sleep(0.1) # Adjust the typing speed by word
formatted_text += current_text + "\n\n" # Add the paragraph to the formatted text with a double line break
placeholder.markdown(formatted_text.strip()) # Final display without cursor
def clean_message_content(content):
'''
Clean up new lines within message content so download file has better format
Args: content(str): Original message with potential line breaks
Returns: str: Cleaned message with line breaks removed
'''
return " ".join(content.splitlines())
def convert_chat_history_to_text():
'''
Convert chat history to a single text block for downloading
Replaces 'system' and 'assistant' with 'CityGuru'
An empty line is added between each message.
Args: None
Output: str: The chat history formatted as a single text block
'''
chat_text = "\n\n".join(
f"CityGov Guru: {clean_message_content(msg['content'])}"
if msg['role'] in ['system', 'assistant']
else f"{msg['role']}: {clean_message_content(msg['content'])}"
for msg in st.session_state.chat_history
)
return chat_text
# Initialize session state variables for login status and chat history
if "logged_in" not in st.session_state:
st.session_state.logged_in = False # Tracks if user is logged in
if "chat_history" not in st.session_state:
st.session_state.chat_history = [] # Stores the conversation history
if "chat_text" not in st.session_state:
st.session_state.chat_text = "" # Prepares chat history text for download
# Call the function to intialise the database
initialise_database()
# Set page configuration
st.set_page_config(
page_title="CityGov Guru",
layout="centered"
)
# Display login page if user is not logged in
if not st.session_state.logged_in:
st.write("")
st.image('citygov_logo.png')
st.markdown("""
## Instructions
- Welcome! This ChatBot is used to find the data maturity of the company CityGov.
- CityGov is a municipal government organisation responsible for providing various public services, including transportation, public safety, healthcare, and community development.
The organisation aims to enhance the quality of life for its residents through efficient and transparent governance.
- There is a **Download Chat History** button to download the history for future viewing.
- **Do not refresh the page**; this will restart the session and you will lose your chat history.
- Please enter your login details below, this will be provided in the project brief.
""")
# Create login form with name and email inputs
with st.form(key='login_form'):
email = st.text_input("Email")
login_password = st.text_input("Password", type='password')
submit_button = st.form_submit_button("Login")
if submit_button:
# Check if email and password is valid
if check_login(email, login_password):
# If credentials are valid, update session state to reflect the user is logged in.
st.session_state.logged_in = True
# Initialise the chat history with a message
st.session_state.chat_history.append({"role": "assistant", "content": "I'm CityGov Guru, here to help you navigate the world of data at CityGov. How may I assist you on your journey today?"})
# Store user's email in session state for later use
st.session_state.user_email = email
# Rerun script to update page state
st.rerun()
else:
st.error("Invalid credentials, please try again.")
# Chat interface - displayed if the user is logged in
if st.session_state.logged_in:
openai.api_key = api_key
email = st.session_state.user_email
col1, col2 = st.columns([2, 1])
with col1:
# streamlit page title
st.title("CityGov Guru 🎩")
# Display chat history messages
for message in st.session_state.chat_history:
with st.chat_message(message["role"]):
st.markdown(message["content"])
# Input field for user to enter question
user_prompt = st.chat_input("Enter question here...")
if user_prompt:
# Add user's message to chat and display it
st.chat_message("user").markdown(user_prompt)
st.session_state.chat_history.append({"role": "user", "content": user_prompt})
# send user's message to GPT-4o-mini and get a response
response = openai.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": chatbot_content},
*st.session_state.chat_history
]
)
# Get assistant's response
assistant_response = response.choices[0].message.content
st.session_state.chat_history.append({"role": "assistant", "content": assistant_response})
# Save chat history to database
save_to_db(email, user_prompt, assistant_response)
# Display assistant response with typing effect
with st.chat_message("assistant"):
placeholder= st.empty()
type_text(assistant_response, placeholder)
# Update chat text in session state
st.session_state.chat_text = convert_chat_history_to_text()
with col2:
st.write("")
st.write("")
# Button to download chat history as text file
st.download_button(
label="Download Chat History",
data=st.session_state.chat_text,
file_name="CityGov_Guru_history.txt",
mime="text/plain"
) |