54A10 Final
54A10 Final
On
Submitted in partial fulfillment of the requirement for the award of the degree of
BACHELOR OF TECHNOLOGY
in
ARTIFICIAL INTELLIGENCE & DATA SCIENCE
Under the Esteemed Guidance of
Mrs. T. Rajya Lakshmi
Assistant Professor
DEPARTMENT OF AI&DS
2024–2025
I
RAMACHANDRA COLLEGE OF ENGINEERING
(AUTONOMOUS)
(Approved by AICTE, Permanantly Affiliated to JNTUK, Kakinada)
Accredited by NBA and NAAC (A+)
NH-16 Bypass, Vatluru (V), ELURU-534007, Eluru Dist., A.P.
2024–2025
BONAFIDE CERTIFICATE
This is to certify that this project report entitled “AI-POWERED MENTAL HEALTH
THERAPIST CHATBOT” is being submitted by MD. DULDHANA FARHEEN
(21ME1A5439), SUDHEER KUMAR BALABOINA (22ME5A5401), ABDUL
KAUSAR (21ME1A5401), and TEJA BANDARU (21ME1A5403) in partial
fulfillment of BACHELOR OF TECHNOLOGY in ARTIFICIAL INTELLIGENCE &
DATA SCIENCE.
This report is a bonafide work carried out under my guidance and supervision during
the academic year 2024-2025 and it has been found worthy of acceptance as per the
requirements of the university.
II
DECLARATION
III
ACKNOWLEDGEMENT
We take this opportunity to express our sincere gratitude to all those who have contributed
to the successful completion of our research work. Their guidance, support, and
encouragement have been invaluable throughout this journey.
We extend our heartfelt thanks to our supervisor, Mr. T. Rajya Lakshmi., Assistant
Professor, Department of Artificial Intelligence & Data Science, for her invaluable
mentorship, insightful guidance, and unwavering support throughout the course of this
research. Her expertise and constructive feedback have been instrumental in shaping this
work.
Our sincere recognition also goes to Dr. M. Muralidhara Rao, Principal for his invaluable
suggestions and constructive inputs during the preparation of this research work.
We also wish to convey our sincere thanks to all the Deans for their constant
encouragement and insightful suggestions that have greatly contributed to the progress of this
research.
We would also like to express our deepest recognition to all the faculty members and staff
of the Department of Artificial Intelligence & Data Science for their valuable advice,
insightful suggestions, and continuous motivation, which have played a crucial role in the
successful completion of this research.
Finally, we extend our sincere gratitude to everyone who has directly or indirectly
contributed to the successful completion of this research work. Their support and
encouragement have been truly invaluable.
IV
INDEX
Chapter
No Title Page No
Abstract VII
1. Introduction 1-5
1.1 Introduction 1
1.2 Overview of the Project 2
1.3 Objective 2-3
1.4 Scope 3-4
1.5 Expected Outcome 5
2. Literature Survey 6-8
3. System Analysis 9-10
3.1 Existing System 9
3.2 Proposed System 10
4. System Study 11-13
4.1 Feasibility Study 11-12
4.1.1 Operational Feasibility 11
4.1.2 Economic Feasibility 11-12
4.1.3 Technical Feasibility 12
4.2 System Requirements 13
4.2.1 Hardware Requirements 13
4.2.2 Software Requirements 13
5. Project Architecture 14-19
5.1 System Architecture 14
5.2 Design and Diagrams 15-19
5.2.1 Use case Diagram 15
5.2.2 Class Diagram 16
5.2.3 Sequence Diagram 17-18
5.2.4 Collaboration Diagram 19
6. Methodology 20-22
6.1 Data Dictionary 20
6.2 Data Collection 20-21
6.3 Preprocessing Techniques 21-22
6.4 Prepared Data 22
V
Chapter Title Page No
No
7. Model 23-25
7.1 Training 23-24
7.2 Validation 24-25
8. Software Description 26-28
9. System Testing 29-31
9.1 Literature on Testing 29-30
9.1.1 Unit Testing 29
9.1.2 Integration Testing 29
9.1.3 Acceptance Testing 29-30
9.2 Test cases on Project 30-31
10. Coding 32-47
11. Results 48-53
11.1 Screenshots 48-51
11.2 Conclusion & Limitations 52
11.3 Future Scope 52-53
12. References & Bibliography 54
VI
ABSTRACT
Mental health support is a growing concern, and AI-powered solutions offer a promising approach to
addressing it. An AI-driven Mental Health Therapist Chatbot is designed to provide personalized mental
health assistance using Natural Language Processing (NLP) and therapeutic techniques such as Cognitive
Behavioral Therapy (CBT) and Dialectical Behavioral Therapy (DBT). This chatbot enables users to
express their emotions and concerns through text and speech in multiple languages, including Telugu,
Hindi, and English. By leveraging the Gemini API, the system intelligently interacts with users,
understands their concerns, and suggests tailored remedies, ensuring real-time therapeutic support. The
inclusion of speech functionality enhances accessibility, making mental health support more inclusive.
Deployed using Streamlit, this 24/7 accessible chatbot promotes self-management strategies, reduces the
stigma around seeking help, and ensures user privacy in a confidential and non-judgmental environment.
With AI- driven interactions, the system enhances mental health accessibility and encourages overall well-
being.
VII
CHAPTER-1
INTRODUCTION
1.1 Introduction
In the modern era, AI-driven solutions are transforming mental health support by providing
accessible and personalized assistance. Our project, AI-Powered Mental Health Therapist
Chatbot, is designed to offer real-time therapeutic interactions using Natural Language
Processing (NLP) along with Cognitive Behavioral Therapy (CBT) and Dialectical Behavioral
Therapy (DBT) techniques. This system enables users to communicate their emotions and
concerns through text and speech in multiple languages, including Telugu, Hindi, and English.
This project aims to enhance mental health accessibility by leveraging the Gemini API to
analyze user inputs, understand concerns, and provide tailored remedies. By incorporating AI-
driven conversational capabilities, it ensures 24/7 support, encourages self-management
strategies, and fosters a confidential and non- judgmental environment. The chatbot’s speech
functionality further enhances inclusivity, making mental health assistance available to a
broader audience. Deployed using Streamlit, this system effectively reduces the stigma around
seeking help while ensuring user privacy and well-being.
1
1.2 Overview of the Project
The main purpose of this project is to provide real-time mental health support using AI-
powered conversational techniques. By integrating Natural Language Processing (NLP)
with Cognitive Behavioral Therapy (CBT) and Dialectical Behavioral Therapy (DBT), the
chatbot helps users express their emotions and receive personalized therapeutic guidance in
multiple languages, including Telugu, Hindi, and English.
This system leverages the Gemini API to analyze user inputs, understand mental health
concerns, and provide tailored suggestions. With speech functionality and 24/7 accessibility, it
ensures inclusivity and immediate support. Deployed using Streamlit, the chatbot enhances
mental health accessibility, promotes self- management strategies, and offers a confidential,
non-judgmental space, reducing the stigma associated with seeking help.
1.3 Objective
The main objective of this project is to develop an AI-powered chatbot that provides personalized
mental health support using AI and therapeutic techniques. Specifically, the project aims to achieve
the following objectives:
2
1. AI-Driven Mental Health Assistance: Implement AI-based conversational capabilities using
the Gemini API to interact with users, understand their concerns, and provide therapeutic
guidance in real time.
2. Multilingual Support: Enable users to communicate their emotions in Telugu, Hindi, and
English, ensuring accessibility for diverse populations.
3. Speech and Text Interaction: Incorporate speech functionality alongside text input to make
mental health support more inclusive and user-friendly.
4. Personalized Therapy Recommendations: Utilize Cognitive Behavioral Therapy (CBT) and
Dialectical Behavioral Therapy (DBT) techniques to offer tailored self- help strategies and
mental health recommendations.
5. 24/7 Accessibility: Ensure continuous availability of mental health assistance, allowing
users to seek support anytime without human intervention.
6. Confidential and Non-Judgmental Environment: Provide a safe and private space for
users to share their emotions and receive support without fear of stigma.
7. User-Friendly Deployment: Deploy the chatbot using Streamlit for seamless interaction
and accessibility through a web-based platform.
8. Data Security and Privacy Protection: Ensure that user interactions remain secure and
confidential, maintaining trust and compliance with ethical standards.
9. Reduction of Mental Health Stigma: Encourage self-management strategies and early
intervention by providing accessible and stigma-free mental health support.
Overall, the objective of this project is to create an AI-powered mental health chatbot that offers real-
time, personalized, and confidential support, helping users manage their mental well-being
effectively.
1.4 Scope
3
o Generating empathetic, supportive, and context-aware therapeutic
suggestions.
5. Secure and Confidential User Experience:
o Ensuring data privacy by implementing secure handling of user
interactions.
o Maintaining a non-judgmental and anonymous space for users.
6. User-Friendly Deployment:
o Deploying the chatbot using Streamlit for a simple and interactive web- based
experience.
o Allowing users to access mental health support easily from any device.
7. Continuous Availability and Accessibility:
o Providing 24/7 support for users seeking help anytime, anywhere.
o Ensuring reliability and scalability for handling multiple users
simultaneously.
8. Dynamic Learning and Enhancements:
o Adapting AI responses based on continuous user interactions and feedback.
o Expanding functionalities with future enhancements such as personalized mental
health progress tracking.
9. Ethical AI Implementation:
o Developing a safe and responsible AI model that provides accurate and non-
harmful advice.
o Ensuring the chatbot does not replace professional medical guidance but serves as
an initial self-help tool.
10. Future Enhancements:
o Integrating emotion-based voice modulation for a more human-like
experience.
o Adding features like daily mental health check-ins, journaling support, and guided
meditation suggestions.
4
freely.
4. Real-Time and 24/7 Availability:
o Round-the-clock mental health support without requiring human
intervention.
o Ability to handle multiple user requests efficiently with AI-driven
automation.
5. User-Friendly Deployment and Accessibility:
o A Streamlit-based web application for easy access.
o Simple and intuitive interface for seamless user interaction.
6. Improved Awareness and Reduced Stigma:
o Encouraging more people to seek mental health assistance without hesitation.
o Promoting self-management strategies and mental well-being.
7. Data Privacy and Secure Communication:
o Ensuring safe and encrypted user interactions.
o Protecting sensitive mental health data from unauthorized access.
8. Scalability and Future Expansion:
o Ability to handle an increasing number of users with optimized
performance.
o Potential for integration with wearable devices and mental health
monitoring tools.
9. Enhanced Mental Health Support System:
o A structured, AI-powered approach to self-care and well-being.
o A first step toward AI-driven emotional intelligence in healthcare
applications.
Overall, the expected outcome of this project is to provide a comprehensive, AI- powered mental
health chatbot that enhances accessibility, promotes self-care, and ensures secure, real-time
therapeutic assistance for users seeking mental well-being support.
5
CHAPTER-2
LITERATURE SURVEY
Introduction
The AI-Powered Mental Health Chatbot is an intelligent conversational system designed to assist
individuals in managing their mental well-being. This project leverages Artificial Intelligence (AI),
Natural Language Processing (NLP), and Cognitive Behavioral Therapy (CBT) techniques to provide
real-time, personalized mental health support. The chatbot is designed to enhance accessibility to
mental health assistance, providing multilingual support in Telugu, Hindi, and English. It ensures a
non- judgmental, confidential, and empathetic environment for users to express their emotions and
receive tailored therapeutic guidance. The primary objective is to offer 24/7 mental health support,
reduce the stigma around mental health issues, and encourage self-care through AI-driven therapy
recommendations.
Keywords
AI Mental Health Chatbot, NLP-Based Therapy, Cognitive Behavioral Therapy, Mental Well-being,
Emotion Analysis, AI-Powered Support System.
6
2. Emotion-Based Response Generation: Uses NLP-driven sentiment analysis to tailor
responses based on user emotions and concerns.
3. Multilingual Support: Allows users to communicate in Telugu, Hindi, and English for
wider accessibility.
4. Voice & Text Interaction: Enables users to speak or type their concerns, making mental
health assistance more inclusive.
5. Confidential & Stigma-Free Environment: Ensures privacy and data security to encourage
users to seek help freely.
6. 24/7 Availability: Provides round-the-clock mental health support without the need for
human intervention.
7
Gather the user requirements for mental health chatbot through an interactive interface.
1. Collect user inputs, including preferences, language selection (Telugu, Hindi, English),
and communication mode (text/voice).
2. Identify mental health concerns such as stress, anxiety, or emotional well-being.
3. Retrieve and process mental health resources from validated sources like CBT and DBT therapy
modules.
4. Utilize historical user interactions to enhance chatbot responses.
5. Apply NLP-based sentiment analysis to detect user emotions and mood variations.
6. Identify key mental health indicators such as distress levels and conversational patterns.
7. Implement AI-driven therapy guidance with personalized recommendations.
8. Offer self-help exercises, relaxation techniques, and guided meditation
suggestions.
9. Ensure real-time adaptive responses based on user sentiment and engagement levels.
10. Provide continuous feedback loops for personalized mental health tracking.
11. Develop an interactive user interface for seamless chatbot interaction.
12. Enable users to view, modify, and track emotional progress over time.
13. Enhance data privacy and security with encryption methods.
14. Maintain a safe and stigma-free environment for mental health discussions.
15. Continuously refine chatbot responses using past interactions.
16. Implement adaptive learning models to improve therapy recommendations.
17. Ensure scalability and adaptability for long-term mental health support
Conclusion:
The AI-Powered Mental Health Chatbot provides accessible, real-time, and confidential mental
health support through AI-driven sentiment analysis and therapeutic guidance. By integrating
NLP, CBT, and DBT techniques, the chatbot ensures personalized, emotion-aware responses
while maintaining data privacy and multilingual accessibility. Continuous refinement enhances
the chatbot’s effectiveness, making it a scalable and adaptive mental health solution for
individuals seeking AI-powered therapy assistance.
8
CHAPTER-3
SYSTEM ANALYSIS
The current mental health support system relies on traditional counselling methods and generic online
resources, leading to limited accessibility and inconsistent user engagement. Below is an overview of
the existing system:
1. Manual Counselling and Therapy:
o Users must schedule in-person or online therapy sessions, which may not be available in
emergencies.
o Accessibility to professional mental health support is limited due to location,
time constraints, and financial barriers.
2. Lack of Personalized Support:
o Generalized mental health resources do not provide personalized
recommendations.
o Users often rely on self-help materials, which lack interactive and adaptive support.
3. Delayed Response and Accessibility Issues:
o Traditional mental health support systems may not provide immediate assistance.
o Helplines and counselling services have limited availability, making it difficult
for users to get real-time help.
4. Limited Integration of AI and Data Analytics:
o Mental health platforms lack AI-driven insights for analyzing user emotions and
engagement patterns.
o Existing systems do not dynamically adapt to user needs based on behavioral
patterns.
Disadvantages
Limited accessibility and availability of mental health professionals.
Lack of real-time support for individuals in distress.
Generalized resources that do not cater to individual needs.
Delays in response, reducing the effectiveness of crisis intervention.
9
3.2 Proposed System
The proposed AI-Powered Mental Health Chatbot enhances mental health support by providing
real-time, personalized, and interactive assistance through AI-driven responses and emotional
analysis.
Advantages:
AI-driven, real-time mental health support for users anytime, anywhere.
Personalized interactions based on user emotions and past engagement.
Instant access to self-help techniques and professional guidance when needed.
Scalable, adaptive system that improves mental well-being through AI-driven insights.
10
CHAPTER-4
SYSTEM STUDY
11
health assistance.
Conclusion: The system is economically feasible as the benefits of real-time mental health support,
user engagement, and reduced therapy bottlenecks outweigh the development and maintenance costs.
4.1.3 Technical Feasibility
Description: Technical feasibility assesses whether the chatbot can be developed and deployed
using available technology and resources.
Evaluation:
Technology Availability: The required AI technologies, including NLP, sentiment analysis, and
chatbot frameworks, are readily available and well-supported.
Data Accessibility: User interactions, emotional analysis, and feedback data can be securely
accessed and processed.
Scalability: The chatbot is designed to handle increasing user interactions efficiently,
ensuring scalability as demand grows.
Conclusion: The system demonstrates strong technical feasibility, as it can be developed and deployed
using available AI and cloud technologies while ensuring scalability and high-performance mental
health support.
Summary
The feasibility study confirms that the proposed AI-powered mental health chatbot is operationally,
economically, and technically viable. It improves accessibility to mental health support, reduces
response times, personalizes user interactions, and remains cost- effective while leveraging AI-driven
emotional analysis.
12
4.2 System Requirements
13
CHAPTER-5
PROJECT ARCHITECTURE
14
5.2 Design and Diagrams
15
5.2.2 Class Diagram
16
5.2.3 Sequence Diagram
5.2.3.1 Sequence Diagram for Mood & Sentiment Analysis
17
5.2.3.3 Sequence Diagram for Therapeutic Suggestions &
Recommendations
18
5.2.4 Collaboration Diagram
19
CHAPTER-6
METHODOLOGY
o Inputs are captured through the Streamlit-based chatbot interface and stored for further
processing.
o AI-based sentiment analysis techniques are used to classify emotions (e.g., happy,
anxious, stressed, or depressed).
20
o Data is collected from previous chatbot interactions and processed using machine
learning models.
o The chatbot stores past conversations to track progress in user mental health journeys.
o Speech-to-text conversion is applied for voice-based inputs using AI- powered speech
recognition tools.
o Noisy or irrelevant data (e.g., greetings, generic statements) is filtered out before
analysis.
21
3. Therapeutic Response Data:
o AI-generated responses from the Gemini API are checked for accuracy and aligned with
mental health best practices.
o Responses are categorized into CBT exercises, mindfulness practices, and self-care
strategies.
o Users receive periodic mental health insights based on their interaction history.
22
CHAPTER-7
MODEL
7.1 Training
The training process ensures that the Mental Health Therapist Chatbot provides accurate, context-
aware, and empathetic responses based on user interactions, sentiment analysis, and AI-generated
therapeutic guidance.
Model Selection
The chatbot is developed using:
Programming Language: Python
Development Environment: Visual Studio
Libraries: NumPy, pandas
Tools: SQL, Large Language Models (LLMs)
API: Gemini AI
Output Interface: Streamlit
Training Data
The chatbot processes structured mental health-related data, including:
User input text containing mental health concerns and queries.
Predefined therapy-related knowledge sourced from psychology-based datasets.
AI-generated responses using Gemini AI to ensure relevant and well-structured answers.
Response Generation Algorithm
The chatbot follows a structured approach for generating responses:
2. Sentiment Analysis:
o The chatbot evaluates the sentiment of the user’s input to determine emotional
tone (e.g., stress, anxiety, calmness).
3. LLM-Powered Response Generation:
o The chatbot requests an AI-generated response from the Gemini AI API
23
based on user input and sentiment analysis.
7.2 Validation
The validation process ensures that the chatbot generates accurate, empathetic, and relevant
responses based on user inputs.
Validation Data
The system is tested using:
User queries with different mental health topics (stress, anxiety, relaxation techniques).
Benchmark case studies to validate response accuracy.
Test datasets containing predefined queries and expected chatbot responses.
Evaluation Metrics
The chatbot is evaluated based on:
Response Accuracy: Comparing chatbot-generated responses with expected answers.
Sentiment Detection Precision: Checking if the chatbot correctly interprets user emotions.
User Engagement: Measuring response clarity and user satisfaction.
Therapeutic Effectiveness: Ensuring responses align with mental health best practices.
Testing Scenarios
User seeking general mental health tips: The chatbot provides predefined suggestions.
User asking about stress management: The chatbot retrieves therapy-based
24
responses.
User input requires a unique response: The chatbot dynamically generates a response
using Gemini AI.
Long-term interactions: Testing how well the chatbot maintains contextual awareness
over multiple queries.
Error Handling
To ensure reliability, the chatbot detects and handles errors effectively:
"I'm unable to process your request right now, please try again later." – If there’s an
issue with Gemini AI API connectivity.
Fallback responses: If an issue arises, the chatbot suggests general mental wellness tips.
User Feedback & Continuous Improvement
Users can rate responses to improve accuracy.
The chatbot refines its response generation based on new queries and interactions.
Regular fine-tuning ensures improved user experience and response effectiveness.
25
CHAPTER-8
SOFTWARE DESCRIPTION
The AI-Powered Mental Health Therapist Chatbot is a software application designed to provide users
with instant mental health support, guidance, and wellness recommendations. It assists individuals by
offering AI-driven responses to mental health concerns, ensuring privacy, accessibility, and
personalized assistance. The chatbot leverages data-driven techniques to generate empathetic, relevant,
and insightful responses.
Key Features:
AI-Powered Mental Health Assistance
Utilizes AI models to provide personalized mental health guidance.
Processes user input to generate supportive and informative responses.
Emotion and Sentiment Analysis
Identifies user emotions based on text input to offer relevant mental wellness suggestions.
Adjusts response tone and content based on detected sentiment.
Guided Mental Health Support
Provides self-help strategies for stress, anxiety, and emotional well-being.
Recommends relaxation techniques such as mindfulness and breathing exercises.
Privacy-Focused Conversations
Ensures confidentiality in user interactions.
No personally identifiable information is stored or shared.
User-Friendly Interface
Simple and interactive chatbot interface built with Streamlit.
Easy-to-use response system for smooth user experience.
Fast and Accurate Response Generation
26
AI-driven algorithms process queries efficiently, reducing response time.
Ensures logical and well-structured responses for better understanding.
Scalability
Can support increasing numbers of users and evolving mental health queries.
Designed for easy updates and improvements with AI advancements.
Benefits:
Instant Mental Health Support
Provides immediate responses to mental health concerns.
Helps users with self-care recommendations anytime, anywhere.
Improved User Engagement
Uses AI to generate personalized responses based on user input.
Encourages users to explore wellness techniques through interactive conversations.
Accessible and Non-Judgmental Assistance
Offers a supportive, AI-powered platform without bias or stigma.
Available 24/7 for users seeking mental health guidance.
Better Decision-Making for Mental Well-being
Helps users recognize stress patterns and manage emotions effectively.
Encourages healthy mental health practices through AI-driven insights.
Target Users:
Individuals Seeking Mental Health Support
Provides guidance on stress management, mindfulness, and emotional well-being.
Students and Professionals
Assists in managing academic and work-related stress.
Offers self-care strategies for balancing productivity and mental wellness.
Mental Health Enthusiasts
Helps users explore psychological well-being techniques.
Provides AI-curated tips for maintaining emotional balance.
27
Technology Stack:
Backend
Python – Core programming language for chatbot logic.
NumPy & Pandas – Used for processing and structuring mental health data.
LLMs (Large Language Models) – Powering AI-generated responses.
Gemini AI API – Provides intelligent and context-aware chatbot replies.
Frontend
Streamlit – Enables a clean, interactive user interface.
Future Enhancements
Expanded Mental Health Guidance
Incorporating more personalized response suggestions based on user history.
Adding AI-driven coping strategies for various emotional states.
Advanced Sentiment Analysis
Enhancing chatbot accuracy in detecting emotional tones for improved responses.
Integration with Mental Health Resources
Providing links to professional therapy resources and wellness articles.
Scalability Enhancements
Supporting a broader range of mental health topics and AI learning improvements.
28
CHAPTER-9
SYSTEM TESTING
Objective:
To validate the chatbot against user requirements and confirm readiness for deployment.
Scope:
Testing the chatbot’s accuracy in responding to mental health queries.
Ensuring that generated responses are empathetic, relevant, and meaningful.
Evaluating the chatbot’s user experience, including text input handling and response
clarity.
Participants:
29
Test users from different age groups and backgrounds.
Outcome:
Verified that the system meets expectations and is ready for deployment.
Purpose: To verify that the chatbot generates accurate and relevant mental health responses.
Steps:
1. Open the chatbot interface in Streamlit.
2. Enter a mental health-related query (e.g., "I feel stressed").
3. Check the chatbot’s response for relevance and clarity.
Expected Result:
The chatbot provides a meaningful, supportive, and contextually appropriate response.
Purpose: To ensure that the chatbot correctly detects user emotions based on text input.
Steps:
1. Enter different emotional statements (e.g., "I feel happy," "I am anxious," "I am struggling with
stress").
2. Check if the chatbot correctly interprets the sentiment.
3. Verify that responses align with the detected sentiment.
Expected Result:
The chatbot accurately identifies the sentiment and provides appropriate guidance.
Purpose: To validate that the chatbot correctly processes responses from the Gemini AI API.
Steps:
1. Enter various mental health queries.
2. Analyze API response times and content.
3. Ensure chatbot displays responses without errors.
Expected Result:
The chatbot successfully retrieves and displays AI-generated responses without delays or
failures.
30
Test Case 4: User Interface Functionality
31
CHAPTER-10
CODING
# Page icon
icon = Image.open(r"Logo.png")
32
body {
background-color: #f0f2f6;
}
.chat-container { background-
color: #ffffff; padding: 20px;
border-radius: 15px;
max-width: 800px; /* Adjusted width */ margin:
auto;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}
.chat-bubble {
max-width: 70%;
padding: 12px 16px;
border-radius: 15px;
margin-bottom: 10px;
position: relative;
word-wrap: break-word;
}
.chat-bubble.user {
background-color: #dcf8c6; /* Light green */
margin-left: auto;
margin-right: 0;
border-bottom-right-radius: 5px;
}
.chat-bubble.bot {
background-color: #f0f0f0; /* Light gray */
margin-left: 0;
margin-right: auto;
border-bottom-left-radius: 5px;
}
.chat-input {
display: flex;
gap: 5px; /* Reduced gap between buttons */
padding: 10px;
background-color: #ffffff;
border-radius: 15px; margin-
top: 20px;
}
.chat-input input {
flex: 1; padding:
10px;
border: 1px solid #ddd;
border-radius: 15px;
33
outline: none;
}
.chat-input button {
background-color: #25d366; /* WhatsApp green */ color:
white;
border: none; padding:
10px 15px; border-
radius: 50%; cursor:
pointer; display: flex;
align-items: center;
justify-content: center;
}
.chat-input button.mic {
background-color: #f0f2f6;
color: #333;
}
/* Adjust text area width */
.stTextArea textarea {
width: 90% !important; /* Adjusted width */
}
/* Reduce space between buttons */
.stButton button {
margin-right: 5px; /* Adjusted spacing */
}
</style> """,
unsafe_allow_html=True,
)
with st.sidebar:
st.sidebar.image(icon, use_container_width=True) selected =
option_menu(
menu_title="Main Menu",
options=["Home", "Project Details", "Contact", "Settings"],
icons=["house", "book", "envelope", "gear"], # optional
menu_icon="cast", # optional
default_index=0, # optional
)
# Home Section
if selected == "Home":
# Load API keys from .env file
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY") # Gemini API key
34
YOUTUBE_API_KEY = os.getenv("YOUTUBE_API_KEY") # YouTube API key
# Function to clean user input (remove empty lines and trim spaces) def
clean_input(text):
lines = text.splitlines() # Split into lines
35
non_empty_lines = [line.strip() for line in lines if line.strip()] # Remove empty lines and trim
spaces
return "\n".join(non_empty_lines) # Join non-empty lines
36
try:
tts = gTTS(text=text, lang=language, slow=False)
audio_bytes = BytesIO() tts.write_to_fp(audio_bytes)
audio_bytes.seek(0) return
audio_bytes.read()
except Exception as e:
st.error(f"Error generating audio: {e}") return
None
37
st.session_state.step = 1
with col1:
feelings = st.text_area(
f"{feelings_label} (in {st.session_state.input_language})",
placeholder=feelings_placeholder[st.session_state.input_language], height=100
)
with col2:
st.write("") # Add some vertical space for alignment
st.write("") # Add some vertical space for alignment if
st.button("Submit", key="submit_feelings"):
if feelings.strip():
cleaned_feelings = clean_input(feelings) # Clean user input st.session_state.feelings =
cleaned_feelings st.session_state.conversation.append({"role": "user", "message":
cleaned_feelings})
st.session_state.step = 2 st.rerun()
else:
38
st.error("Please enter how you are feeling to proceed.")
# Add the "Speak" button below the text area and submit button if
st.button("🎤 Speak"):
user_input = speech_to_text() if
user_input:
st.session_state.feelings = user_input st.session_state.conversation.append({"role": "user",
"message": user_input}) st.session_state.step = 2
st.rerun()
reason_placeholder = {
"English": "e.g., I have a big presentation tomorrow, and I'm worried I'll mess
up",
"Telugu": "e.g., నాకు రేపు ాద్ద ప్రెజెంటేషన్ ఉెంది, మరయు నేను దానిని
పాడు చేదతానని భయపడుతునాా ను",
"Hindi": "e.g., मे री कल एक बडी प्रस्तुति है, और मु झे डर है िक मैं इसे खराब कर दू तాాगा"
}
with col1:
reason = st.text_area(
f"{reason_label} (in {st.session_state.input_language})",
placeholder=reason_placeholder[st.session_state.input_language], height=100
)
with col2:
st.write("") # Add some vertical space for alignment st.write("") #
Add some vertical space for alignment
39
if st.button("Submit", key="submit_reason"): if
reason.strip():
cleaned_reason = clean_input(reason) # Clean user input st.session_state.reason =
cleaned_reason st.session_state.conversation.append({"role": "user", "message":
cleaned_reason})
st.session_state.step = 3 # Move to step 3 for detailed situation st.rerun()
else:
st.error("Please provide more details to proceed.")
# Add the "Speak" button below the text area and submit button if
st.button("🎤 Speak", key="speak_reason"):
user_input = speech_to_text() if
user_input:
st.session_state.reason = user_input st.session_state.conversation.append({"role": "user",
"message": user_input}) st.session_state.step = 3
st.rerun()
detailed_placeholder = {
"English": "e.g., I have a lot of work pressure, and I'm struggling to manage my
time.",
"Telugu": "e.g., నాకు చాలా వర్క్ ప్రెజర్ ఉెంది, మరయు నేను నా టైమ్ ని
మేనేజ్ చేయడెంలో కషటపడుతునాా ను.",
"Hindi": "e.g., मु झे बहुतా काम का दबाव है , और मैं अपने समय को प्रतबतितా करने के िलएదतसघर्ष
करదरहाదहूँ ।"
}
40
with col1:
detailed_situation = st.text_area(
f"{detailed_label} (in {st.session_state.input_language})",
placeholder=detailed_placeholder[st.session_state.input_language], height=100
)
with col2:
st.write("") # Add some vertical space for alignment
st.write("") # Add some vertical space for alignment if
st.button("Submit", key="submit_detailed"):
if detailed_situation.strip():
cleaned_situation = clean_input(detailed_situation) # Clean user input
st.session_state.detailed_situation = cleaned_situation
st.session_state.conversation.append({"role": "user", "message":
cleaned_situation})
st.session_state.step = 4 # Move to step 4 for final response st.rerun()
else:
st.error("Please provide more details to proceed.")
# Add the "Speak" button below the text area and submit button if
st.button("🎤 Speak", key="speak_detailed"):
user_input = speech_to_text() if
user_input:
st.session_state.detailed_situation = user_input st.session_state.conversation.append({"role":
"user", "message": user_input}) st.session_state.step = 4
st.rerun()
41
translated_feelings = GoogleTranslator(source='te', target='en').translate(feelings)
translated_reason = GoogleTranslator(source='te', target='en').translate(reason)
translated_situation = GoogleTranslator(source='te',
target='en').translate(detailed_situation)
elif st.session_state.input_language == "Hindi":
status_text.text("Translating from Hindi...")
progress_bar.progress(20)
translated_feelings = GoogleTranslator(source='hi', target='en').translate(feelings)
translated_reason = GoogleTranslator(source='hi', target='en').translate(reason)
translated_situation = GoogleTranslator(source='hi',
target='en').translate(detailed_situation) else:
translated_feelings = feelings translated_reason =
reason translated_situation = detailed_situation
progress_bar.progress(30)
prompt = f"""
You are a highly intelligent and empathetic AI-powered mental health therapist.
A user has described their feelings, the reason behind them, and their detailed situation as
follows:
Feelings: {translated_feelings}
Reason: {translated_reason}
Detailed Situation: {translated_situation}
Please provide:
1. A detailed step-by-step solution using CBT and DBT techniques to help the user overcome
their problem.
2. Specific exercises or activities the user can do to feel better (e.g., breathing exercises,
journaling).
3. Words of encouragement and reassurance. """
try:
model = genai.GenerativeModel('gemini-1.5-flash-002') response =
model.generate_content(prompt) progress_bar.progress(70)
full_response = response.text
42
if st.session_state.input_language != "English":
status_text.text(f"Translating response to
{st.session_state.input_language}...")
progress_bar.progress(90)
target_lang = 'te' if st.session_state.input_language == "Telugu" else 'hi'
translated_response = GoogleTranslator(source='en',
target=target_lang).translate(full_response) st.session_state.response_parts['response'] =
translated_response
else:
st.session_state.response_parts['response'] = full_response
progress_bar.progress(100)
status_text.empty() st.rerun()
except Exception as e:
st.error(f"Error generating response: {e}")
# Generate YouTube links and images based on user's reason and feelings feelings =
st.session_state.get('feelings', '')
reason = st.session_state.get('reason', '')
# Generate image
image = generate_images(reason, feelings) if
image:
st.write("### 📸 Related Image:")
st.image(image, caption="Related to your situation", use_container_width=True)
43
# Automatically generate and play audio
if 'response' in st.session_state.response_parts:
response_text = st.session_state.response_parts['response'] language_map =
{"English": "en", "Telugu": "te", "Hindi": "hi"}
# Generate audio
audio_data = text_to_speech(response_text, language_map[st.session_state.input_language])
if audio_data:
st.write("### 🔊 Listen to the response:")
autoplay_audio(audio_data)
else:
st.error("Failed to generate audio. Please try again.")
# Project Title
st.markdown("<h3 style='color: #000080;'>Title:</h3>", unsafe_allow_html=True) st.write("🤖
AI-Powered Mental Health Therapist Chatbot")
st.write("") # Add some space
# Key Features
st.markdown("<h3 style='color: #000080;'>Key Features:</h3>", unsafe_allow_html=True)
st.write("""
44
- **Multilingual Support**: Interact in English, Telugu, or Hindi.
- **Voice and Text Input**: Speak or type to communicate with the chatbot.
- **Personalized Mental Health Support**: Get tailored advice based on your feelings and situation.
- **Therapeutic Exercises**: Learn breathing exercises, journaling, and mindfulness practices.
- **Visual and Audio Support**: View related images and listen to audio responses.
- **YouTube Video Recommendations**: Access additional resources like guided meditations
and motivational talks.
""")
st.write("") # Add some space
# Technologies Used
st.markdown("<h3 style='color: #000080;'>Technologies Used:</h3>", unsafe_allow_html=True)
st.write("""
- **Streamlit**: For building the web application interface.
- **Google Generative AI (Gemini)**: For generating personalized responses.
- **Deep Translator**: For multilingual support.
- **gTTS (Google Text-to-Speech)**: For converting text responses to audio.
- **SpeechRecognition Library**: For speech-to-text functionality.
- **YouTube Data API**: For fetching relevant YouTube videos.
- **Unsplash API**: For generating related images.
- **PIL (Python Imaging Library)**: For image processing.
- **Base64**: For encoding and decoding audio files. """)
st.write("") # Add some space
# Display Logo
st.markdown("<h3 style='color: #000080;'>Project Logo:</h3>", unsafe_allow_html=True)
logo_path = r"Logo.png" # Update the path to your logo try:
logo = Image.open(logo_path)
st.image(logo, caption="AI-Powered Mental Health Therapist Chatbot", width=300,
use_container_width=True)
except Exception as e: st.error(f"Error
loading logo: {e}")
# Contact Section
elif selected == "Contact": #
Header
st.markdown("<h2 class='sider-title' style='color: SlateGray;'>Project Team</h2>",
unsafe_allow_html=True)
st.text("")
45
# Team member details team_members
=[
{
"name": "Mohammad Duldhana Farheen",
"Roll_Number": "21ME1A5439", "Phone":
"+919398911371",
"Email": "[email protected]",
"Dept": "Department of Artificial Intelligence & Data Science"
},
{
"name": "B. Sudheer Kumar", "Roll_Number":
"22ME5A5401", "Phone": "+916301371055",
"Email": "[email protected]",
"Dept": "Department of Artificial Intelligence & Data Science"
},
{
"name": "Bandaru Teja", "Roll_Number":
"21ME1A5403", "Phone": "+916304155699",
"Email": "[email protected]",
"Dept": "Department of Artificial Intelligence & Data Science"
},
{
"name": "Abdul Kausar", "Roll_Number":
"21ME1A5401", "Phone": "+918919540598",
"Email": "[email protected]",
"Dept": "Department of Artificial Intelligence & Data Science"
}
]
# Display team member details with images side by side col1, col2,
col3, col4 = st.columns(4)
46
st.write(f"Name: {member['name']}")
st.write(f"Roll Number: {member['Roll_Number']}")
st.write(f"Phone: {member['Phone']}")
st.write(f"Email: {member['Email']}") st.write(f"Department:
{member['Dept']}")
# Settings Section
elif selected == "Settings":
st.markdown("<h2 class='sider-title' style='color: SlateGray;'>Settings</h2>",
unsafe_allow_html=True)
st.text("")
47
CHAPTER-11
RESULTS
11.1 Screenshots
Sample Input:
48
Sample Output:
49
Project Details:
50
Team Details:
Multi-Language Selection:
51
11.2 Conclusion & Limitations
Conclusion
The AI-Powered Mental Health Therapist Chatbot is an intelligent and accessible solution designed to
provide emotional support and mental health assistance to users. By leveraging technologies such as
Python, Pandas, Gemini AI API, and Streamlit, the chatbot delivers real-time, empathetic, and
informative responses to mental health-related queries. The system enhances accessibility, reduces
stigma associated with seeking help, and provides users with instant guidance. With features such as
sentiment detection, personalized responses, and an intuitive interface, the chatbot serves as a valuable
tool for individuals in need of emotional support.
Limitations
Despite its effectiveness, the mental health therapist chatbot has certain limitations:
1. Context Awareness: The chatbot may not fully understand complex emotional states or long
conversational contexts, leading to generalized responses.
2. Dependency on Input Quality: The accuracy of responses depends on how well users
articulate their concerns. Vague or ambiguous queries may not yield precise answers.
3. Lack of Real-Time Crisis Intervention: The chatbot does not replace professional therapy or
emergency mental health services for users in critical situations.
4. Limited Personalization: While the chatbot can detect sentiment, it does not store user history
for long-term personalized advice.
5. Ethical Considerations: The system must ensure privacy and confidentiality while avoiding
biases in responses generated by the AI model..
The Mental Health Therapist Chatbot has vast potential for future enhancements:
1. Advanced AI Models
Implement more sophisticated Natural Language Processing (NLP) models for improved
contextual understanding.
2. Multimodal Support
Enable voice-based interaction to improve accessibility for users who prefer
52
speaking over typing.
Integrate facial emotion detection to enhance sentiment analysis for a more tailored response.
Develop an AI-driven alert system that detects distress signals and provides immediate
support options.
Sync with wearable health devices (e.g., smartwatches) to monitor stress levels and suggest
relaxation techniques.
Introduce push notifications for daily mental wellness tips and mood check-ins.
7. Multilingual Support
Expand the chatbot’s capabilities to support multiple languages, ensuring accessibility for diverse
user groups.
Implement localized mental health resources based on user region and language preferences.
Develop AI fairness mechanisms to eliminate biases in mental health advice and responses.
53
CHAPTER-12
REFERENCES & BIBLIOGRAPHY
"Woebot, a Mental-Health Chatbot, Tries Out Generative AI" – IEEE Spectrum (2023):
Discusses Woebot’s use of AI and cognitive behavioral therapy (CBT) techniques for mental
health support.
Available at: https://spectrum.ieee.org/woebot
"Response-act Guided Reinforced Dialogue Generation for Mental Health
Counseling" – arXiv (2023)
Proposes READER, a chatbot model for improving mental health counseling conversations.
Available at: https://arxiv.org/abs/2301.12729
"LLM-empowered Chatbots for Psychiatrist and Patient Simulation" – arXiv
(2023)
Explores how AI chatbots can simulate psychiatric interactions for therapy and training.
Available at: https://arxiv.org/abs/2305.13614
"Enhancing Mental Health Support through AI Chatbots" – arXiv (2024) Focuses on
secure, empathetic AI chatbots for mental health assistance. Available at:
https://arxiv.org/abs/2410.02783
"LLM-based Conversational AI Therapist for Psychotherapeutic
Interventions" – arXiv (2024)
Introduces CaiTI, an AI therapist for mental health self-care using smart devices. Available at:
https://arxiv.org/abs/2403.10779
54