Spaces:
Sleeping
Sleeping
Download app.py from ClarzW/CityGov_ChatBot: direct link, hf CLI and curl.
- Browser
- Download file 9.05 kB
-
https://huggingface.co/spaces/ClarzW/CityGov_ChatBot/resolve/main/app.py
- Command line
-
hf download hf://spaces/ClarzW/CityGov_ChatBot/app.py
-
curl -L -o app.py https://huggingface.co/spaces/ClarzW/CityGov_ChatBot/resolve/main/app.py
9.05 kB
| 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" | |
| ) |