import streamlit as st
import os
from dotenv import load_dotenv
from langchain.schema import HumanMessage, SystemMessage, AIMessage
from langchain.chat_models import AzureChatOpenAI,ChatOpenAI
from langchain.memory import ConversationBufferWindowMemory
from langchain.prompts import PromptTemplate
import warnings
import time
from sqlalchemy import create_engine, Column, Integer, String, Text, Table, MetaData
from sqlalchemy.orm import sessionmaker
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from dotenv import load_dotenv
from langchain_google_genai import ChatGoogleGenerativeAI
warnings.filterwarnings("ignore", category=DeprecationWarning)
# Load environment variables
load_dotenv()
st.set_page_config(page_title="MindMate", layout="wide", initial_sidebar_state="expanded")
api_key = "AIzaSyCYKhYSpmg9vjUVhrf3nZjEBxl07-rnWes"
# CSS styles
css = '''
'''
bot_template = '''
{session["title"]}
{session["subtitle"]}
🕒 {session["time"]}
''', unsafe_allow_html=True)
if st.button("Open", key=f"open_{session['id']}"):
open_session(session['id'])
st.experimental_rerun()
if st.button("Delete", key=f"delete_{session['id']}"):
remove_session(session['id'])
st.experimental_rerun()
st.markdown('
', unsafe_allow_html=True)
if st.session_state['current_session'] is not None:
session = next((s for s in st.session_state['sessions'] if s['id'] == st.session_state['current_session']), None)
if session:
st.subheader("Chat")
# Language selection
languages = {"English": "en", "Spanish": "es", "French": "fr", "German": "de", "Chinese": "zh","Hindi":"hi","Japanese":"JA"}
selected_language = st.selectbox("Select Language", list(languages.keys()), index=0)
language = languages[selected_language]
# Select the appropriate prompt template based on the selected therapist
selected_therapist = st.session_state.get('selected_therapist', 'Counsellor')
therapist_template = therapist_templates.get(selected_therapist, therapist_templates['Counsellor'])
CUSTOM_PROMPT = PromptTemplate.from_template(therapist_template)
# Initialize conversation memory
if 'flowmessages' not in session:
session['flowmessages'] = [
SystemMessage(content=f"Hey there! I'm {selected_therapist}, your AI mental health assistant. How are you feeling?")
]
memory = ConversationBufferWindowMemory(k=5, return_messages=True)
def get_chatmodel_response(question):
session['flowmessages'].append(HumanMessage(content=question))
memory.save_context({"input": question}, {"output": ""}) # Save the input question to memory
# Prepare the chat history for the prompt
chat_history = "\n".join([f"User: {msg.content}" if isinstance(msg, HumanMessage) else f"Bot: {msg.content}" for msg in session['flowmessages']])
# Construct the prompt using the template
prompt = CUSTOM_PROMPT.format(chat_history=chat_history, user_message=question, language=language)
# Ensure the prompt is not empty
if not prompt.strip():
raise ValueError("The constructed prompt is empty. Check the message formatting.")
# Use HumanMessage instead of SystemMessage
messages = [HumanMessage(content=prompt)]
# Get the response from the chat model
answer = st.session_state['chat'](messages) # Pass list of messages to chat
# Ensure AI response is not empty
if not answer or not answer.content.strip():
raise ValueError("The AI response is empty. Check the prompt or input.")
# Append the AI response to the session
session['flowmessages'].append(AIMessage(content=answer.content))
save_session(session) # Save the session after appending new messages
return answer.content
input = st.text_input("Input: ", key="input")
submit = st.button("Ask the question")
if submit:
response = get_chatmodel_response(input)
save_session(session)
st.experimental_rerun()
if "flowmessages" in session:
st.subheader("Chat")
for message in session['flowmessages']:
if isinstance(message, HumanMessage):
st.write(user_template.replace("{{MSG}}", message.content), unsafe_allow_html=True)
elif isinstance(message, AIMessage):
st.write(bot_template.replace("{{MSG}}", message.content), unsafe_allow_html=True)
# Session rename functionality
new_title = st.text_input("Rename session:", value=session["title"])
if st.button("Rename"):
session["title"] = new_title
save_session(session)
st.experimental_rerun()
# Save conversation to file
if st.button("Download Conversation"):
filename = f"{session['title']}.txt"
save_conversation_to_file(session['flowmessages'], filename)
with open(filename, 'rb') as file:
st.download_button(
label="Download Conversation",
data=file,
file_name=filename,
mime='text/plain'
)
# Define other tool functions here...
def breathing_exercise():
st.markdown("""
""", unsafe_allow_html=True)
breathing_container = st.empty()
total_duration = 5 * 60 # 5 minutes in seconds
phase_duration = 12 # 4 seconds for each phase: inhale, hold, exhale
phases = ["Breathe in...", "Hold...", "Breathe out..."]
for _ in range(total_duration // phase_duration):
for text in phases:
with breathing_container.container():
st.markdown('', unsafe_allow_html=True)
st.markdown(f'
', unsafe_allow_html=True)
st.markdown('
', unsafe_allow_html=True)
time.sleep(4) # Duration for each phase
with breathing_container.container():
st.markdown('', unsafe_allow_html=True)
st.markdown('
Great job! Feel relaxed and refreshed.
', unsafe_allow_html=True)
st.markdown('
', unsafe_allow_html=True)
time.sleep(3)
breathing_container.empty()
if page == "Tools":
st.subheader("Tools")
st.write("Each tool is an interactive exercise based on cognitive-behavioral therapy and enhanced by the power of AI.")
tools = [
{"title": "Mindfulness", "description": "Breathing exercise for anxiety and stress relief", "time": "5 minutes"},
{"title": "\"Perfect day\"", "description": "Discover ways to enhance your daily routine and improve the quality of life", "time": "13 minutes"},
{"title": "Goal setting", "description": "Transform your issues and shortcomings into opportunities", "time": "22 minutes"},
{"title": "Boundaries", "description": "Separate your own values and priorities from those imposed on you", "time": "23 minutes"},
{"title": "Time awareness", "description": "Learn how to spend your time on what matters most", "time": "14 minutes"},
{"title": "Descartes square", "description": "Examine hidden pros and cons to be sure you make the right decision", "time": "9 minutes"},
]
tool_columns = st.columns(3)
for index, tool in enumerate(tools):
col = tool_columns[index % 3]
with col:
st.markdown(f'''
How to use? 🚀
Welcome to the Mental Health Support Chat Bot. Here's how to navigate and make the most out of this application:
📅 Today Page:
- Overview of mental health resources.
- Cards with information on understanding mental health, finding support, and self-care tips.
🗨️ Sessions:
- View all your chat sessions.
- Start a new session, open existing ones, or delete sessions you no longer need.
- In each session, you can chat with the AI and download conversation history.
🛠️ Tools:
- Interactive exercises based on cognitive-behavioral therapy.
- Use these tools to solve problems, set goals, and more.
👥 Therapists:
- Choose an AI therapist that best suits your needs.
- Each therapist has a unique approach and style.
📊 Insights:
- Analyze your chat sessions.
- View summaries and mood analysis over time.
⚙️ Settings:
- Configure your preferences and application settings.
If you have any questions, feel free to ask!
''', unsafe_allow_html=True)
else:
st.subheader(f"{page} Page")
st.write(f"This is the {page} page.")