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_vertexai import ChatVertexAI warnings.filterwarnings("ignore", category=DeprecationWarning) # Load environment variables load_dotenv() st.set_page_config(page_title="MindMate", layout="wide", initial_sidebar_state="expanded") # CSS styles css = ''' ''' bot_template = '''
{{MSG}}
''' user_template = '''
{{MSG}}
''' # CSS st.write(css, unsafe_allow_html=True) # Initialize the database engine = create_engine('sqlite:///sessions.db') metadata = MetaData() sessions_table = Table( 'sessions', metadata, Column('id', Integer, primary_key=True), Column('title', String), Column('subtitle', String), Column('time', String), Column('messages', Text) ) metadata.create_all(engine) DBSession = sessionmaker(bind=engine) db_session = DBSession() # Sidebar navigation with model selection def sidebar(): st.sidebar.header("Navigation") pages = ["Today", "Sessions", "Tools", "Therapists", "Insights", "Settings", "How to use?"] icons = ["📅", "💬", "🛠️", "👥", "📊", "⚙️", "❓"] selected_page = st.sidebar.selectbox( "", [f"{icons[i]} {pages[i]}" for i in range(len(pages))], format_func=lambda x: x.split(" ", 1)[1] ) # API Key and Model Selection st.sidebar.subheader('Select Model') models = ['3.5 Turbo', '4.0', 'Azure', 'Gemini', 'Ollama', 'Mistral'] # Example list of models selected_model = st.sidebar.selectbox('Select Model', models) api_key = st.sidebar.text_input('Enter API Key', type='password') if selected_model == 'Azure': endpoint = st.sidebar.text_input("Enter endpoint", type="url") deployment_name = st.sidebar.text_input("Enter deployment name") if st.sidebar.button('Run Model'): st.session_state['api_key'] = api_key if selected_model == '3.5 Turbo': st.session_state['chat'] = ChatOpenAI(temperature=0, model="gpt-3.5-turbo", api_key=api_key) elif selected_model == 'Azure': st.session_state['chat'] = AzureChatOpenAI( azure_endpoint=endpoint, deployment_name=deployment_name, openai_api_version="2023-03-15-preview", api_key=api_key, openai_api_type="Azure" ) elif selected_model == '4.0': st.session_state['chat'] = ChatOpenAI(temperature=0, model="gpt-4.0", api_key=api_key) elif selected_model == 'Gemini': st.session_state['chat'] = ChatVertexAI(model="gemini-1.5-flash",api_key=api_key) elif selected_model == 'Ollama': st.session_state['chat'] = ChatOpenAI(temperature=0, model="ollama-1", api_key=api_key) elif selected_model == 'Mistral': st.session_state['chat'] = ChatOpenAI(temperature=0, model="mistral-1", api_key=api_key) else: st.error('Invalid model selection') return st.success(f'Model {selected_model} is running...') return selected_page.split(" ", 1)[1] page = sidebar() # Initialize the selected model and API key if 'api_key' not in st.session_state: st.session_state['api_key'] = None if 'chat' not in st.session_state: st.session_state['chat'] = None # Function to load sessions from the database def load_sessions(): sessions = [] for s in db_session.query(sessions_table).all(): session = { "id": s.id, "title": s.title, "subtitle": s.subtitle, "time": s.time, "messages": eval(s.messages) if s.messages else [] } print(f"Loaded session: {session}") # Debug statement sessions.append(session) return sessions # Function to save session to the database def save_session(session): print(f"Saving session: {session}") # Debug statement db_session.query(sessions_table).filter_by(id=session['id']).update({ 'title': session['title'], 'subtitle': session['subtitle'], 'time': session['time'], 'messages': str(session['messages']) }) db_session.commit() # Function to add new session to the database def add_session(session): new_session = sessions_table.insert().values( title=session['title'], subtitle=session['subtitle'], time=session['time'], messages=str(session['messages']) ) result = db_session.execute(new_session) db_session.commit() return result.inserted_primary_key[0] # Function to delete session from the database def delete_session(session_id): db_session.query(sessions_table).filter_by(id=session_id).delete() db_session.commit() # Load existing sessions from the database if 'sessions' not in st.session_state: st.session_state['sessions'] = load_sessions() if 'current_session' not in st.session_state: st.session_state['current_session'] = None if 'selected_therapist' not in st.session_state: st.session_state['selected_therapist'] = None # Therapist prompt templates therapist_templates = { "Counsellor": """ You are a compassionate and empathetic counsellor specialized in mental health support. Your primary goal is to provide emotional support, offer practical advice, and guide users to helpful resources. You are non-judgmental, understanding, and always prioritize the user's well-being. Respond in a calm and reassuring manner, ensuring that users feel heard and supported. Guidelines: 1. Always be empathetic, supportive, and non-judgmental. 2. Provide practical advice and suggest resources where appropriate. 3. Use simple and clear language to ensure understanding. 4. Encourage users to seek professional help if needed, but never give medical diagnoses. 5. Avoid overly technical language and focus on being relatable and approachable. 6. Be friendly, remember context and conversation between the user and yourself and become more engaging. 7. Use open-ended questions to encourage users to express themselves. 8. Validate the user's feelings and experiences. 9. Offer coping strategies and self-care tips. 10. Maintain confidentiality and respect the user's privacy. Translate and respond in {language}. Current conversation: {chat_history} User: {user_message} Counsellor: """, "Cognitive Behavioral Therapist": """ You are a cognitive-behavioral therapist specialized in helping individuals challenge and change unhelpful cognitive distortions and behaviors. Your role is to guide users through structured exercises and provide evidence-based techniques to improve their mental health. Guidelines: 1. Always be empathetic, supportive, and non-judgmental. 2. Provide practical advice and suggest CBT techniques where appropriate. 3. Use simple and clear language to ensure understanding. 4. Encourage users to practice the techniques regularly for better results. 5. Avoid overly technical language and focus on being relatable and approachable. 6. Provide clear explanations of cognitive-behavioral concepts. 7. Use examples and analogies to help users understand complex ideas. 8. Offer step-by-step guidance for CBT exercises. 9. Encourage users to set and work towards achievable goals. 10. Provide positive reinforcement and celebrate progress. Translate and Respond in {language}. Current conversation: {chat_history} User: {user_message} Cognitive Behavioral Therapist: """, "Student Counsellor": """ You are a student counsellor specialized in helping students with academic, social, and emotional challenges. Your role is to provide support, guidance, and practical advice to help students navigate their school or college life effectively. Guidelines: 1. Always be empathetic, supportive, and non-judgmental. 2. Provide practical advice and suggest resources where appropriate. 3. Use simple and clear language to ensure understanding. 4. Encourage students to seek professional help if needed, but never give medical diagnoses. 5. Avoid overly technical language and focus on being relatable and approachable. 6. Help students develop time management and study skills. 7. Offer guidance on dealing with peer pressure and social issues. 8. Provide tips for managing stress and anxiety. 9. Encourage students to set academic and personal goals. 10. Validate students' feelings and experiences. Translate and Respond in {language}. Current conversation: {chat_history} User: {user_message} Student Counsellor: Respond in {language}. """, "Psychologist": """ You are a clinical psychologist specialized in psychological assessment and therapy. Your role is to provide evidence-based psychological support and guide users towards better mental health. Guidelines: 1. Always be empathetic, supportive, and non-judgmental. 2. Provide practical advice and suggest evidence-based techniques where appropriate. 3. Use simple and clear language to ensure understanding. 4. Encourage users to seek professional help if needed, but never give medical diagnoses. 5. Avoid overly technical language and focus on being relatable and approachable. 6. Provide clear explanations of psychological concepts. 7. Use examples and analogies to help users understand complex ideas. 8. Offer step-by-step guidance for therapeutic exercises. 9. Encourage users to set and work towards achievable goals. 10. Provide positive reinforcement and celebrate progress. Translate and Respond in {language}. Current conversation: {chat_history} User: {user_message} Psychologist: Respond in {language}. """, "Best Friend": """ You are a supportive and understanding friend who is always here to listen and chat about anything. Your role is to provide a non-judgmental, friendly, and comforting presence. You respond with warmth, understanding, and encouragement, just like a best friend would. Guidelines: 1. Always be empathetic, supportive, and non-judgmental. 2. Actively listen and respond with comforting and understanding messages. 3. Encourage the user to express themselves and validate their feelings. 4. Use simple, friendly, and relatable language. 5. Maintain confidentiality and respect the user's privacy. 6. Offer encouragement and positive reinforcement. 7. Follow up on previously discussed topics. 8. Provide meaningful and contextually appropriate support. 9. Maintain a casual and approachable tone. 10. Share personal anecdotes and experiences to build rapport. Translate and respond in {language} Current conversation: {chat_history} User: {user_message} Best Friend: Respond in {language}. """ } therapists = [ { "name": "Counsellor", "description": "Compassionate and empathetic, specialized in emotional support.", "image": "https://cdn-icons-png.flaticon.com/512/1154/1154448.png" # Female counsellor }, { "name": "Cognitive Behavioral Therapist", "description": "Specializes in cognitive-behavioral techniques for mental health improvement.", "image": "https://cdn-icons-png.flaticon.com/512/1154/1154476.png" # Male therapist }, { "name": "Student Counsellor", "description": "Helps students with academic, social, and emotional challenges.", "image": "https://cdn-icons-png.flaticon.com/512/1154/1154494.png" # New female student counsellor }, { "name": "Psychologist", "description": "Specializes in psychological assessment and evidence-based therapy.", "image": "https://cdn-icons-png.flaticon.com/512/1154/1154480.png" # Male psychologist }, { "name": "Best Friend", "description": "Supportive and understanding friend for general concerns and casual conversations.", "image": "https://cdn-icons-png.flaticon.com/512/1154/1154462.png" # New female best friend } ] # Callback functions def open_session(session_id): st.session_state['current_session'] = session_id def remove_session(session_id): delete_session(session_id) st.session_state['sessions'] = load_sessions() if st.session_state['current_session'] == session_id: st.session_state['current_session'] = None def select_therapist(therapist_name): st.session_state['selected_therapist'] = therapist_name # Save conversation to a downloadable format def save_conversation_to_file(conversation, filename): with open(filename, 'w') as f: for message in conversation: if isinstance(message, HumanMessage): f.write(f"User: {message.content}\n")#save message.content to file elif isinstance(message, AIMessage): f.write(f"Bot: {message.content}\n") # Function to summarize the conversation using the chat model def summarize_conversation(messages): conversation_text = "\n".join([f"User: {msg.content}" if isinstance(msg, HumanMessage) else f"Bot: {msg.content}" for msg in messages]) summary_prompt = f"Summarize the following conversation:\n\n{conversation_text}" summary_response = chat([SystemMessage(content=summary_prompt)]) return summary_response.content.strip() # Generate insights for the selected session def generate_insights(session): messages = session['messages'] if not messages: return "No messages to summarize.", pd.DataFrame() conversation_summary = summarize_conversation(messages) mood_labels = ['Positive', 'Neutral', 'Negative'] mood_counts = [0, 0, 0] for message in messages: if isinstance(message, HumanMessage): content = message.content.lower() if any(word in content for word in ['happy', 'good', 'great', 'awesome']): mood_counts[0] += 1 elif any(word in content for word in ['okay', 'fine', 'alright', 'normal']): mood_counts[1] += 1 elif any(word in content for word in ['sad', 'bad', 'terrible', 'awful']): mood_counts[2] += 1 mood_data = [count if count != 0 else 0.1 for count in mood_counts] # Ensure no NaNs mood_df = pd.DataFrame({ 'Mood': mood_labels, 'Count': mood_data }) return conversation_summary, mood_df if page == "Today": # CSS Injection st.markdown(''' ''', unsafe_allow_html=True) # HTML Content st.markdown('''

Welcome to MindMate 🧠💖

Your digital wellness companion. Embark on a journey of self-discovery and growth as we guide you through the fascinating landscape of mental health and well-being.

🌟
Wellness

Understanding Mental Health

Unlock the secrets of your mind and learn how mental health shapes your daily life.

Explore Wellness
🤝
Support

Finding Support

Discover a network of care, from professional guidance to heartwarming personal connections.

Get Support
🌼
Self-care

Self-Care Tips

Nurture your mind and soul with practical strategies for everyday mental wellness.

Practice Self-Care
''', unsafe_allow_html=True) elif page == "Sessions": st.subheader("Sessions") new_session_card = '''
Start a new session
''' st.markdown(new_session_card, unsafe_allow_html=True) if st.button("Start a new session", key="start_new_session"): new_session = { "title": "Untitled Session", "subtitle": "New session", "time": time.strftime("%H:%M %p"), "messages": [] } new_session_id = add_session(new_session) new_session['id'] = new_session_id st.session_state['sessions'].append(new_session) st.session_state['current_session'] = new_session_id st.experimental_rerun() session_columns = st.columns(3) for index, session in enumerate(st.session_state['sessions']): col = session_columns[index % 3] with col: st.markdown(f'''
{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"} 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 chat_history = "\n".join([f"User: {msg.content}" if isinstance(msg, HumanMessage) else f"Bot: {msg.content}" for msg in session['flowmessages']]) prompt = CUSTOM_PROMPT.format(chat_history=chat_history, user_message=question, language=language) messages = [SystemMessage(content=prompt)] # Use st.session_state['chat'] here answer = st.session_state['chat'](messages) # Pass list of messages to chat session['flowmessages'].append(AIMessage(content=answer.content)) # Adjusted to handle response properly save_session(session) # Ensure session is saved after adding 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'

{text}

', 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'''
{tool["title"]}
{tool["description"]}
🕒 {tool["time"]}
''', unsafe_allow_html=True) if st.button(f"Let's Go {index}", key=f"button_{index}"): if tool["title"] == "Mindfulness": breathing_exercise() else: st.write(f"{tool['title']} tool is not yet implemented.") elif page == "Therapists": st.subheader("Choose Your Therapist") st.write("Select a therapist to guide you through your mental health journey !") therapist_columns = st.columns(2) for index, therapist in enumerate(therapists): col = therapist_columns[index % 2] with col: st.markdown(f'''
{therapist[
{therapist["name"]}
{therapist["description"]}
''', unsafe_allow_html=True) if st.button(f"Select {therapist['name']}", key=f"select_{therapist['name']}"): select_therapist(therapist['name']) st.experimental_rerun() elif page == "Insights": st.subheader("Insights") session_titles = [session["title"] for session in st.session_state['sessions']] selected_session_title = st.selectbox("Select a session", session_titles) if selected_session_title: selected_session = next(session for session in st.session_state['sessions'] if session["title"] == selected_session_title) print(f"Selected session for insights: {selected_session}") # Debug statement if selected_session and 'messages' in selected_session: st.write(f"Messages: {selected_session['messages']}") conversation_summary, mood_df = generate_insights(selected_session) st.markdown("### Conversation Summary") st.write(conversation_summary) if not mood_df.empty: st.markdown("### Mood Analysis") fig, ax = plt.subplots() ax.pie(mood_df['Count'], labels=mood_df['Mood'], autopct='%1.1f%%', startangle=90, colors=['#4CAF50', '#FFC107', '#F44336']) ax.axis('equal') st.pyplot(fig) st.markdown("### Mood Over Time") mood_timeline = pd.Series([msg.content.lower() for msg in selected_session['messages'] if isinstance(msg, HumanMessage)]).apply( lambda x: 1 if any(word in x for word in ['happy', 'good', 'great', 'awesome']) else ( 0 if any(word in x for word in ['okay', 'fine', 'alright', 'normal']) else -1 ) ) mood_timeline.index = pd.to_datetime(mood_timeline.index, unit='s') mood_timeline_df = mood_timeline.reset_index() mood_timeline_df.columns = ['Time', 'Mood'] st.line_chart(mood_timeline_df.set_index('Time')) else: st.write("No mood data to display.") else: st.write("No messages to summarize.") elif page == "How to use?": st.subheader("How to use?") # Embedding HTML content 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:

🗨️ Sessions:

🛠️ Tools:

👥 Therapists:

📊 Insights:

⚙️ 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.")