ClarzW commited on
Commit
ff6be60
·
verified ·
1 Parent(s): c8712d5

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +266 -0
app.py ADDED
@@ -0,0 +1,266 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import time
3
+ import streamlit as st
4
+ import openai
5
+ import psycopg2
6
+
7
+
8
+ # Accessing environment variables
9
+ api_key = os.getenv('api') # OpenAI API key for generating chatbot
10
+ sql_host = os.getenv('SQL_HOST') # Host address for PostgreSQL database
11
+ db = os.getenv('DB') # Database name
12
+ user = os.getenv('USER') # Database user
13
+ password = os.getenv('PASSWORD') # Database password
14
+ chatbot_content = os.getenv('CONTENT') # Content for chatbot responses
15
+ emails = os.getenv('EMAILS') # List of authorised emails for login
16
+ login = os.getenv('LOGIN') # Predefined password for login validation
17
+
18
+
19
+ # Configuring OpenAI with API key
20
+ openai.api_key = api_key
21
+
22
+
23
+ def initialise_database():
24
+ '''
25
+ Initialise the PostgreSQL database by creating 'chatbot' table if it doesn't exist
26
+ 'chatbot' table stores the user's name, email, question and the chatbot's response
27
+ Args: None
28
+ Returns: None
29
+ '''
30
+
31
+ # Details to connect to PostgreSQL database
32
+ conn = psycopg2.connect(
33
+ host=sql_host,
34
+ database=db,
35
+ user=user,
36
+ password=password
37
+ )
38
+ cursor = conn.cursor()
39
+
40
+ # Create table if doesn't already exist
41
+ cursor.execute('''
42
+ CREATE TABLE IF NOT EXISTS cb_chat_history (
43
+ email VARCHAR (50),
44
+ question VARCHAR(500),
45
+ answer VARCHAR
46
+ );
47
+ ''')
48
+
49
+ # Commit transaction and close connection
50
+ conn.commit()
51
+ cursor.close()
52
+ conn.close()
53
+
54
+
55
+ def save_to_db(email, question, answer):
56
+ '''
57
+ Save chat history to PostgreSQL database.
58
+ Stores user's email, question and chatbot's response
59
+ Args: email, question, chatbot's reponse
60
+ Returns: none
61
+ '''
62
+
63
+ # Details to connect to PostgreSQL database
64
+ conn = psycopg2.connect(
65
+ host=sql_host,
66
+ database=db,
67
+ user=user,
68
+ password=password
69
+ )
70
+ cursor = conn.cursor()
71
+
72
+ # Insert chat history into table
73
+ cursor.execute('''
74
+ INSERT INTO cb_chat_history (email, question, answer)
75
+ VALUES (%s, %s, %s);
76
+ ''', (email, question, answer)
77
+ )
78
+
79
+ # Commit transaction and close connection
80
+ conn.commit()
81
+ cursor.close()
82
+ conn.close()
83
+
84
+
85
+ def check_login(email, password):
86
+ '''
87
+ Validate email address and password. Email must be in the emails list, password must match correct password.
88
+ Args: email (str): The email address to validate.
89
+ password (str): The password to validate.
90
+ Returns: bool: True if email matches an email in list and password matches correct password, otherwise False.
91
+ '''
92
+ allowed_emails = emails
93
+ correct_password = login
94
+ return email.lower() in allowed_emails and password == correct_password
95
+
96
+
97
+ def type_text(text, placeholder):
98
+ '''
99
+ Simulate typing effect for chatbot responses
100
+ Args: text(str): Text to display
101
+ placeholder (streamlit.delta_generator.DeltaGenerator):Streamlit placeholder for displaying the text
102
+ Returns: None
103
+ '''
104
+ paragraphs = text.split('\n') # Split text by line breaks
105
+ formatted_text = ""
106
+
107
+
108
+ for paragraph in paragraphs:
109
+ words = paragraph.split() # Split each paragraph into words
110
+ for i in range(len(words) + 1):
111
+ current_text = " ".join(words[:i])
112
+ placeholder.markdown(formatted_text + current_text + " |") # Show current progress with cursor
113
+ time.sleep(0.1) # Adjust the typing speed by word
114
+ formatted_text += current_text + "\n\n" # Add the paragraph to the formatted text with a double line break
115
+
116
+ placeholder.markdown(formatted_text.strip()) # Final display without cursor
117
+
118
+
119
+ def clean_message_content(content):
120
+ '''
121
+ Clean up new lines within message content so download file has better format
122
+ Args: content(str): Original message with potential line breaks
123
+ Returns: str: Cleaned message with line breaks removed
124
+ '''
125
+ return " ".join(content.splitlines())
126
+
127
+
128
+ def convert_chat_history_to_text():
129
+ '''
130
+ Convert chat history to a single text block for downloading
131
+ Replaces 'system' and 'assistant' with 'CityGuru'
132
+ An empty line is added between each message.
133
+ Args: None
134
+ Output: str: The chat history formatted as a single text block
135
+ '''
136
+ chat_text = "\n\n".join(
137
+ f"CityGov Guru: {clean_message_content(msg['content'])}"
138
+ if msg['role'] in ['system', 'assistant']
139
+ else f"{msg['role']}: {clean_message_content(msg['content'])}"
140
+ for msg in st.session_state.chat_history
141
+ )
142
+
143
+ return chat_text
144
+
145
+
146
+ # Initialize session state variables for login status and chat history
147
+ if "logged_in" not in st.session_state:
148
+ st.session_state.logged_in = False # Tracks if user is logged in
149
+
150
+ if "chat_history" not in st.session_state:
151
+ st.session_state.chat_history = [] # Stores the conversation history
152
+
153
+ if "chat_text" not in st.session_state:
154
+ st.session_state.chat_text = "" # Prepares chat history text for download
155
+
156
+
157
+ # Call the function to intialise the database
158
+ initialise_database()
159
+
160
+
161
+ # Set page configuration
162
+ st.set_page_config(
163
+ page_title="CityGov Guru",
164
+ layout="centered"
165
+ )
166
+
167
+
168
+ # Display login page if user is not logged in
169
+ if not st.session_state.logged_in:
170
+
171
+ st.write("")
172
+
173
+ st.image('citygov_logo.png')
174
+
175
+ st.markdown("""
176
+ ## Instructions
177
+ - Welcome! This ChatBot is used to find the data maturity of the company CityGov.
178
+ - CityGov is a municipal government organisation responsible for providing various public services, including transportation, public safety, healthcare, and community development.
179
+ The organisation aims to enhance the quality of life for its residents through efficient and transparent governance.
180
+ - There is a **Download Chat History** button to download the history for future viewing.
181
+ - **Do not refresh the page**; this will restart the session and you will lose your chat history.
182
+ - Please enter your login details below, this will be provided in the project brief.
183
+ """)
184
+
185
+ # Create login form with name and email inputs
186
+ with st.form(key='login_form'):
187
+ email = st.text_input("Email")
188
+ login_password = st.text_input("Password", type='password')
189
+ submit_button = st.form_submit_button("Login")
190
+
191
+ if submit_button:
192
+ # Check if email and password is valid
193
+ if check_login(email, login_password):
194
+ # If credentials are valid, update session state to reflect the user is logged in.
195
+ st.session_state.logged_in = True
196
+ # Initialise the chat history with a message
197
+ 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?"})
198
+ # Store user's email in session state for later use
199
+ st.session_state.user_email = email
200
+ # Rerun script to update page state
201
+ st.rerun()
202
+ else:
203
+ st.error("Invalid credentials, please try again.")
204
+
205
+
206
+
207
+ # Chat interface - displayed if the user is logged in
208
+ if st.session_state.logged_in:
209
+ openai.api_key = api_key
210
+ email = st.session_state.user_email
211
+
212
+ col1, col2 = st.columns([2, 1])
213
+
214
+ with col1:
215
+ # streamlit page title
216
+ st.title("CityGov Guru 🎩")
217
+
218
+ # Display chat history messages
219
+ for message in st.session_state.chat_history:
220
+ with st.chat_message(message["role"]):
221
+ st.markdown(message["content"])
222
+
223
+ # Input field for user to enter question
224
+ user_prompt = st.chat_input("Enter question here...")
225
+
226
+ if user_prompt:
227
+ # Add user's message to chat and display it
228
+ st.chat_message("user").markdown(user_prompt)
229
+ st.session_state.chat_history.append({"role": "user", "content": user_prompt})
230
+
231
+ # send user's message to GPT-4o-mini and get a response
232
+ response = openai.chat.completions.create(
233
+ model="gpt-4o-mini",
234
+ messages=[
235
+ {"role": "system", "content": chatbot_content},
236
+ *st.session_state.chat_history
237
+ ]
238
+ )
239
+
240
+ # Get assistant's response
241
+ assistant_response = response.choices[0].message.content
242
+ st.session_state.chat_history.append({"role": "assistant", "content": assistant_response})
243
+
244
+ # Save chat history to database
245
+ save_to_db(email, user_prompt, assistant_response)
246
+
247
+ # Display assistant response with typing effect
248
+ with st.chat_message("assistant"):
249
+ placeholder= st.empty()
250
+ type_text(assistant_response, placeholder)
251
+
252
+ # Update chat text in session state
253
+ st.session_state.chat_text = convert_chat_history_to_text()
254
+
255
+
256
+ with col2:
257
+ st.write("")
258
+ st.write("")
259
+
260
+ # Button to download chat history as text file
261
+ st.download_button(
262
+ label="Download Chat History",
263
+ data=st.session_state.chat_text,
264
+ file_name="CityGov_Guru_history.txt",
265
+ mime="text/plain"
266
+ )