0% found this document useful (0 votes)
8 views61 pages

54A10 Final

The project report details the development of an AI-powered mental health therapist chatbot designed to provide personalized mental health support using Natural Language Processing and therapeutic techniques like CBT and DBT. It aims to enhance accessibility by supporting multiple languages and offering 24/7 interaction through text and speech, ensuring a confidential and non-judgmental environment. The chatbot promotes self-management strategies, reduces stigma around seeking help, and is deployed using Streamlit for user-friendly access.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views61 pages

54A10 Final

The project report details the development of an AI-powered mental health therapist chatbot designed to provide personalized mental health support using Natural Language Processing and therapeutic techniques like CBT and DBT. It aims to enhance accessibility by supporting multiple languages and offering 24/7 interaction through text and speech, ensuring a confidential and non-judgmental environment. The chatbot promotes self-management strategies, reduces stigma around seeking help, and is deployed using Streamlit for user-friendly access.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 61

A Project Report

On

AI-POWERED MENTAL HEALTH THERAPIST


CHATBOT
Submitted by

Ms. MD. DULDHANA FARHEEN 21ME1A5439


Mr. SUDHEER KUMAR BALABOINA 22ME5A5401
Mr. ABDUL KAUSAR 21ME1A5401
Mr. TEJA BANDARU 21ME1A5403

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

Department of ARTIFICIAL INTELLIGENCE & DATA SCIENCE


RAMACHANDRA COLLEGE OF ENGINEERING
(AUTONOMOUS)
(Approved by AICTE, PermanantlyAffiliated to JNTUK, Kakinada)
Accredited by NBA and NAAC (A+)

NH-16 Bypass, Vatluru (V), ELURU-534007, Eluru Dist., A.P.

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

Department of Artificial Intelligence & Data Science

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.

PROJECT GUIDE HEAD OF THE DEPARTMENT


Mrs. T. RAJYA LAKSHMI Dr. K. VENKATESH. M. Tech., Ph. D.
Assistant Professor Professor

Internal Examiner External Examiner

II
DECLARATION

We, MD. DULDHANA FARHEEN (21ME1A5439), SUDHEER KUMAR


BALABOINA (22ME5A5401), ABDUL KAUSAR (21ME1A5401), and TEJA
BANDARU (21ME1A5403) hereby declare that the project report titled “AI-POWERED
MENTAL HEALTH THERAPIST CHATBOT” has been completed under the supervision of
Mrs. T. Rajya Lakshmi, Assistant Professor, Department of Artificial Intelligence &
Data Science. This report is submitted in partial fulfillment of the requirements for the award
of the degree of BACHELOR OF TECHNOLOGY in ARTIFICIAL INTELLIGENCE
& DATA SCIENCE.
This is a record of work carried out by us, and the results presented in this project have
not been reproduced or copied from any source. Furthermore, the results embodied in this
project report have not been submitted to any other University or Institute for the award of
any other degree or diploma.

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.

We are deeply indebted to Dr. K. Venkatesh, Head of the Department, Artificial


Intelligence & Data Science, for his continuous encouragement, guidance, and support in all
aspects of this research endeavor.

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 extend our profound gratitude to the Management of Ramachandra College of


Engineering, Eluru, for their unwavering support, encouragement, and for providing the
necessary facilities to successfully carry out this project.

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.

Ms. MD. DULDHANA FARHEEN 21ME1A5439


Mr. SUDHEER KUMAR BALABOINA 22ME5A5401
Mr. ABDUL KAUSAR 21ME1A5401
Mr. TEJA BANDARU 21ME1A5403

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

Overview of the AI- Powered mental therapist chatbot

 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

The scope of the project includes:


1. User Interaction and Input Processing:
o Accepting user inputs through text and speech in Telugu, Hindi, and English.
o Analyzing user emotions and concerns using Natural Language Processing (NLP).
2. AI-Driven Therapy Support:
o Implementing CBT and DBT techniques for personalized mental health support.
o Providing AI-generated responses based on user sentiment and emotional state.
3. Multimodal Communication:
o Supporting text-based and voice-based interactions to enhance accessibility.
o Enabling smooth transitions between different input modes for user
convenience.
4. Real-Time Emotional Analysis and Response Generation:
o Understanding user sentiment through AI-powered language models.

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.

1.5 Expected Outcome

The expected outcomes of the project include:


1. AI-Powered Mental Health Chatbot:
o A fully functional chatbot capable of providing real-time therapeutic support.
o AI-driven analysis of user emotions to offer relevant and supportive responses.
2. Multilingual and Speech-Enabled Interaction:
o Support for Telugu, Hindi, and English to enhance accessibility.
o Seamless speech-to-text and text-to-speech functionality for interactive
engagement.
3. Personalized and Confidential Mental Health Assistance:
o Tailored self-help strategies based on CBT and DBT techniques.
o Secure and non-judgmental support to help users express their emotions

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.

Mental Health Therapist Chatbot: Concepts and Techniques


An AI-driven mental health chatbot incorporates various advanced techniques to understand user
emotions and provide personalized therapy recommendations. The key concepts and techniques include:
 Natural Language Processing (NLP): Analyzing user input to detect sentiment, intent, and
emotional tone.
 Emotion Recognition & Sentiment Analysis: Identifying distress signals and mood
variations to offer appropriate support.
 Conversational AI: Implementing AI-driven dialogue systems using Gemini API to provide
human-like interactions.
 Therapeutic Model Integration: Applying CBT and DBT frameworks to guide users with
structured mental health exercises.
 Speech and Text Processing: Supporting both voice and text-based interactions for
accessibility and ease of communication.
 Real-Time Adaptability: Modifying responses dynamically based on user engagement
and emotional state.

Aspects of AI-Powered Mental Health Therapist Chatbot:


1. AI-Powered Therapy Guidance: Provides personalized therapy
recommendations based on user input and mental health techniques.

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.

Methodologies for AI-Powered Mental Health Therapist Chatbot

1. User Input Processing:


o Accepting text and voice-based inputs in multiple languages.
o Analyzing user sentiment and emotional state using NLP models.
2. AI-Based Emotional Analysis:
o Using sentiment analysis algorithms to detect mood variations.
o Identifying stress, anxiety, or depression indicators based on user
conversations.
3. Therapeutic Response Generation:
o Implementing CBT and DBT techniques for structured therapy suggestions.
o Offering self-help exercises, meditation techniques, and coping strategies.
4. Multimodal Communication Support:
o Enabling voice-based and text-based interaction for seamless
communication.
o Enhancing accessibility for individuals with reading/writing difficulties.
5. Interactive User Experience:
o Deploying a Streamlit-based web platform for user-friendly chatbot interaction.
o Allowing users to view, modify, and track their emotional progress.
6. Continuous System Learning & Refinement:
oImproving AI response accuracy based on historical interactions and user feedback.
o Adapting AI models to provide more effective mental health
recommendations.
7. Real-Time Updates & Adaptive Learning:
o Modifying responses dynamically based on new user interactions.
o Enhancing chatbot intelligence using continuous learning models.

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

3.1 Existing System

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.

1. AI-Based Interactive Therapy Support:


o Uses NLP and AI models to provide intelligent and empathetic responses.
o Offers personalized mental health suggestions based on user conversations.

2. Real-Time Emotional Analysis and Support:


o Detects user emotions through sentiment analysis to assess mental well- being.
o Provides instant mental health support, including relaxation techniques and guided
interventions.

3. 24/7 Availability and Crisis Assistance:


o Ensures round-the-clock availability, allowing users to seek help anytime.
o Offers immediate guidance and connects users to professional support when necessary.

4. Personalized Recommendations and Progress Tracking:


o Adapts responses based on user history and engagement patterns.
o Tracks emotional well-being over time and suggests mental wellness exercises.

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

4.1 Feasibility Study


4.1.1 Operational Feasibility
Description: Operational feasibility evaluates whether the proposed AI-powered mental health chatbot
can be effectively implemented and meets user needs.
Evaluation:
 Integration: The chatbot integrates seamlessly with existing mental health platforms, ensuring
smooth interaction and user engagement.
 User Acceptance: Surveys and feedback indicate strong demand for an AI-based mental health
assistant that provides instant support.
 Alignment with Goals: The chatbot aligns with mental health objectives by offering real-time
emotional support, reducing response time, and increasing accessibility to mental health
resources.
Conclusion: The proposed system is operationally feasible as it enhances mental health support
accessibility and meets user needs effectively.

4.1.2 Economic Feasibility


Description: Economic feasibility assesses whether the benefits of implementing the mental health
chatbot justify the costs associated with development, deployment, and maintenance.
Evaluation:
 Development Costs: The investment in AI models, NLP processing, and cloud- based hosting
remains within budget constraints.
 Deployment Costs: The chatbot can be deployed on cloud-based or mobile platforms,
ensuring cost-effective implementation.
 Maintenance Costs: Regular updates, AI model improvements, and user feedback integration
are manageable, providing long-term benefits through automated mental

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

4.2.1 Hardware Requirements


Minimum Hardware Requirements:
1. CPU: Intel Core i5 or AMD Ryzen 5 processor.
2. RAM: 8GB DDR4 RAM.
3. Storage: 256GB SSD.
4. Internet: Stable connection with 5 Mbps bandwidth.
5. Development: Basic workstation with Python installed.
6. Testing: Any device with a modern web browser to test the timetable generation system.
7. Power: Standard power supply for continuous operation.

4.2.2 Software Requirements

1. Programming language: Python


2. Development Environment: Visual Studio
3. Libraries: NumPy, pandas
4. Tools: LLM’s
5. API: Gemini AI [API]
6. Output interface: Streamlit

13
CHAPTER-5
PROJECT ARCHITECTURE

5.1 System Architecture

14
5.2 Design and Diagrams

5.2.1 Use case Diagram

15
5.2.2 Class Diagram

16
5.2.3 Sequence Diagram
5.2.3.1 Sequence Diagram for Mood & Sentiment Analysis

5.2.3.2 Sequence Diagram for Mental Health Assessment

17
5.2.3.3 Sequence Diagram for Therapeutic Suggestions &
Recommendations

5.2.3.4 Sequence Diagram for User Interaction with Chatbot

18
5.2.4 Collaboration Diagram

19
CHAPTER-6
METHODOLOGY

6.1 Data Dictionary


The Data Dictionary provides a structured overview of the data used in the Mental Health Therapist
Chatbot. It includes details about the types of data, their sources, and their relevance to the system.

Data Type Description Source


User Input Data Messages, voice inputs, or User interactions via chatbot
text queries from users (Streamlit interface).
related to mental health
concerns.
Sentiment Analysis Data Emotional tone detected Sentiment analysis module
from user messages, using AI-based emotion
including stress, anxiety, detection.
and mood
states
Therapeutic Response Data Predefined therapy Gemini API, Mental Health
responses and Dataset, Psychological
dynamically generated AI- Research Data.
driven suggestions based
on user inputs.
Mental Health Resources Cognitive Behavioral SQL Database storing past
Therapy (CBT) exercises, chatbot conversations.
mindfulness techniques,
self-
help guides, and crisis
helplines.
Session History Data Logs of previous User input via web-based
interactions, responses form
provided, and user feedback.

6.2 Data Collection


The data collection process involves gathering relevant data from various sources to build a robust and
efficient Mental Health Therapist Chatbot.

1. User Input Data:


o User messages, voice inputs, and text queries related to mental health concerns are
collected.

o Inputs are captured through the Streamlit-based chatbot interface and stored for further
processing.

2. Sentiment Analysis Data:


o User interactions are analyzed to detect emotional tone, stress levels, and mood states.

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.

3. Therapeutic Response Data:


o Responses generated using Gemini API, which provides AI-driven mental health
guidance.

o Predefined therapy responses, cognitive behavioral therapy (CBT) exercises, and


mindfulness techniques are collected from verified psychological sources.

4. User Profile Data (Optional):


o Users may choose to provide demographic details (age, gender) and mental health
preferences.

o Stored securely in an SQL database to enhance personalized recommendations.

5. Chat History & Progress Tracking:

o The chatbot stores past conversations to track progress in user mental health journeys.

o Based on previous conversations, the chatbot can suggest recurring exercises or


relaxation techniques tailored to the user's mental state.

6.3 Preprocessing Techniques


The preprocessing ensures that collected data is cleaned, structured, and optimized for delivering
personalized therapeutic responses.

1. User Input Data:


o Text preprocessing techniques (tokenization, stopword removal, and lemmatization) are
applied to extract meaningful insights.

o Speech-to-text conversion is applied for voice-based inputs using AI- powered speech
recognition tools.

2. Sentiment Analysis Data:


o Machine learning models are trained on mental health-related datasets to classify
emotions accurately.

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.

4. User Profile Data (Optional):


o Missing values are handled using default profile settings to ensure
uninterrupted chatbot responses.

o Sensitive information is encrypted and stored securely.

5. Chat History & Progress Tracking:


o Past conversation logs are stored securely for context-aware responses in future
interactions.

o Users receive periodic mental health insights based on their interaction history.

6.4 Prepared Data


The final dataset is structured and optimized to deliver real-time, AI-powered mental health
assistance while ensuring privacy and security.
1. User Input Data:
o Cleaned and formatted text inputs ready for analysis and therapeutic response
generation.
2. Sentiment Analysis Data:
o Labelled emotional states stored for future improvement in chatbot
interactions.
3. Therapeutic Response Data:
o Predefined responses and dynamically generated AI-based therapy
suggestions are stored in a structured format.
4. User Profile Data (Optional):
o Securely stored optional demographic and preference data used for
personalized recommendations.
5. Chat History & Progress Tracking:
o Analyzed conversation history is stored securely for long-term mental health
support.
o Recurring mood patterns and progress reports are used to provide insights on
emotional well-being.

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:

1. User Input Processing:


o The chatbot receives user queries and processes them for analysis.

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.

4. Response Optimization & Formatting:


o The response is structured using pandas to ensure clarity and proper formatting.
5. Response Delivery via Streamlit Interface:
o The chatbot presents the response in an interactive format using Streamlit.

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

Software Description for our AI-Powered Mental Health Therapist chatbot:

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

9.1 Literature on Testing


System testing ensures that the timetable generator functions correctly, meets user requirements,
and maintains reliability. The following types of testing were conducted:

9.1.1 Unit Testing


Objective: To test individual components of the chatbot in isolation.
Scope:
 Validating text input processing using Pandas.
 Ensuring the chatbot correctly interacts with the Gemini AI API.
 Testing response generation logic for accuracy and relevance.
 Verifying the sentiment analysis mechanism.
Tools:
 Python's unittest framework.
Outcome:
 Confirmed that each module performs as expected before integration.

9.1.2 Integration Testing

Objective: To test the interaction between different modules of the chatbot.


Scope:
 Verifying the connection between the user input interface (Streamlit) and the Gemini AI
API.
 Ensuring smooth data transfer between chatbot logic and response generation.
 Validating sentiment detection and AI-generated responses.
Tools:
 Manual testing and API response validation.
Outcome:
 Ensured that all modules work together without errors.

9.1.3 Acceptance 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.

9.2 Test cases on Project

Test Case 1: Chatbot Response Generation

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.

Test Case 2: Sentiment Detection Accuracy

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.

Test Case 3: Gemini AI API Response Handling

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

Purpose: To ensure that the chatbot interface is intuitive and responsive.


Steps:
1. Test the chatbot input field by entering different queries.
2. Verify that the interface responds without lag.
3. Check responsiveness on different screen sizes.
Expected Result:
 The chatbot interface should function smoothly and be user-friendly on all devices.

Test Case 5: Error Handling and User Input Validation Purpose: To

confirm that the chatbot properly handles invalid or ambiguous inputs.


Steps:
1. Enter empty messages or random characters.
2. Enter extremely long or nonsensical queries.
3. Check if the chatbot provides meaningful responses or prompts users to rephrase their query.
Expected Result:
 The chatbot should either generate a relevant response or ask for clarification without
crashing.

31
CHAPTER-10
CODING

# Import the required libraries import os


import streamlit as st
import google.generativeai as genai
from deep_translator import GoogleTranslator from gtts
import gTTS
from io import BytesIO import
base64
import requests
from PIL import Image
import speech_recognition as sr
from streamlit_option_menu import option_menu
from dotenv import load_dotenv # Import the dotenv library

# Load environment variables from .env file load_dotenv()

# Page icon
icon = Image.open(r"Logo.png")

# Page configuration st.set_page_config(


page_title="🤖 AI-Powered Mental Health Therapist Chatbot",
page_icon=icon,
layout="wide",
initial_sidebar_state="expanded",
)

st.markdown("<h2 style='text-align: center; color: #000080;'>Ramachandra College of


Engineering</h2>", unsafe_allow_html=True)
st.markdown("<h2 style='text-align: center; color: #BDB76B;'>Department of Artificial Intelligence &
Data Science</h2>", unsafe_allow_html=True)
st.text("")
st.text("")

# Page Styling st.markdown(


"""
<style>

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

# Configure Google Generative AI


genai.configure(api_key=GOOGLE_API_KEY)

# Function to autoplay audio in Streamlit def


autoplay_audio(audio_data):
b64 = base64.b64encode(audio_data).decode() md =
f"""
<audio controls autoplay>
<source src="data:audio/mp3;base64,{b64}" type="audio/mp3">
</audio> """
st.markdown(md, unsafe_allow_html=True)

# Function to translate text based on selected language def


translate_text(text, target_lang):
if target_lang == "English": return
text
elif target_lang == "Telugu":
return GoogleTranslator(source='en', target='te').translate(text) elif
target_lang == "Hindi":
return GoogleTranslator(source='en', target='hi').translate(text)

# Function to display chat messages in a modern chat interface def


display_chat_message(role, message):
if role == "bot": st.markdown(
f'<div class="chat-bubble bot">'
f'<b>🤖 Bot:</b> {message}'
'</div>', unsafe_allow_html=True
)
else:
st.markdown(
f'<div class="chat-bubble user">'
f'<b>👤 You:</b> {message}'
'</div>', unsafe_allow_html=True
)

# 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

# Function to generate YouTube video links using the API def


generate_youtube_links(query):
base_url = "https://www.googleapis.com/youtube/v3/search" params = {
"part": "snippet",
"q": query, "type":
"video",
"maxResults": 5, # Number of videos to fetch "key":
YOUTUBE_API_KEY
}

response = requests.get(base_url, params=params) if


response.status_code == 200:
videos = response.json().get("items", [])
video_links = []
for video in videos:
video_id = video["id"]["videoId"] video_title
= video["snippet"]["title"]
video_links.append((video_title,
f"https://www.youtube.com/watch?v={video_id}")) return
video_links
else:
return ["Failed to fetch videos. Please try again later."]

# Function to generate images based on user's reason and feelings def


generate_images(reason, feelings):
search_query = f"{reason} {feelings}" try:
response = requests.get(f"https://source.unsplash.com/400x300/?{search_query}")
if response.status_code == 200:
return Image.open(BytesIO(response.content)) else:
return None except
Exception as e:
st.error(f"Error fetching image: {e}") return None

# Function to convert text to speech using gTTS def


text_to_speech(text, language):

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

# Function to convert speech to text using speech_recognition def


speech_to_text():
recognizer = sr.Recognizer() with
sr.Microphone() as source:
st.write("🎤 Speak now...") audio =
recognizer.listen(source) try:
text = recognizer.recognize_google(audio) return text
except sr.UnknownValueError:
st.error("Sorry, I could not understand the audio.") return None
except sr.RequestError:
st.error("Sorry, there was an issue with the speech recognition service.") return None

# Initialize session state for storing conversation and response parts if


'conversation' not in st.session_state:
st.session_state.conversation = []
if 'response_parts' not in st.session_state: st.session_state.response_parts
= {}
if 'step' not in st.session_state:
st.session_state.step = 1

# Input language selection moved to Settings page if


'input_language' not in st.session_state:
st.session_state.input_language = "English"

# Start the conversation


if not st.session_state.conversation:
# Translate initial bot message based on selected language initial_message =
translate_text("Hi! How are you feeling today?",
st.session_state.input_language)
st.session_state.conversation.append({"role": "bot", "message": initial_message})

37
st.session_state.step = 1

# Display the conversation within a container box


st.markdown('<div class="chat-container">', unsafe_allow_html=True) for msg in
st.session_state.conversation:
display_chat_message(msg["role"], msg["message"])
st.markdown('</div>', unsafe_allow_html=True)

# Step 1: Ask how the user is feeling if


st.session_state.step == 1:
feelings_placeholder = {
"English": "e.g., feeling anxious about my upcoming presentation", "Telugu":
"e.g., నా రాబోయే ప్రెజెంటేషన్ గురెంచి ఆెందోళన
చెందుతునాా ను",
"Hindi": "e.g., अपनी आगामी प्रस्तु ति के बारे में ि तాాतितా महसूस कर रहा हूँ "
}

# Translate the text area label based on selected language feelings_label =


translate_text("How are you feeling right now?",
st.session_state.input_language)

# Create a container for the text area and submit button


col1, col2 = st.columns([4, 1]) # Adjust column widths as needed

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()

# Step 2: Ask for the reason behind the problem if


st.session_state.step == 2:
# Translate the question based on selected language
reason_question = translate_text("Can you tell me more about why you're feeling this way?",
st.session_state.input_language)
display_chat_message("bot", reason_question)

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., मे री कल एक बडी प्रस्तुति है, और मु झे डर है िक मैं इसे खराब कर दू तాాगा"
}

# Translate the text area label based on selected language


reason_label = translate_text("Can you tell me more about why you're feeling this way?",
st.session_state.input_language)

# Create a container for the text area and submit button


col1, col2 = st.columns([4, 1]) # Adjust column widths as needed

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()

# Step 3: Ask for detailed situation if


st.session_state.step == 3:
# Translate the question based on selected language
detailed_question = translate_text("Can you explain your situation in more detail?
This will help me provide better suggestions.", st.session_state.input_language)
display_chat_message("bot", detailed_question)

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., मु झे बहुतా काम का दबाव है , और मैं अपने समय को प्रतबतितా करने के िलएదतसघर्ष
करదरहाదहूँ ।"
}

# Translate the text area label based on selected language


detailed_label = translate_text("Can you explain your situation in more detail?",
st.session_state.input_language)

# Create a container for the text area and submit button


col1, col2 = st.columns([4, 1]) # Adjust column widths as needed

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()

# Step 4: Provide detailed CBT and DBT-based solutions (Final Step)


if st.session_state.step == 4 and 'response' not in st.session_state.response_parts: progress_bar =
st.progress(0)
status_text = st.empty()

# Retrieve user input from session state feelings =


st.session_state.get('feelings', '') reason =
st.session_state.get('reason', '')
detailed_situation = st.session_state.get('detailed_situation', '')

# Translate input to English if not already in English if


st.session_state.input_language == "Telugu":
status_text.text("Translating from Telugu...")
progress_bar.progress(20)

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)

status_text.text("Analyzing your feelings and reason...")


progress_bar.progress(40)

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}")

# Display the response only once


if st.session_state.step == 4 and 'response' in st.session_state.response_parts: st.write("### ✅
Suggested Solutions:")
display_chat_message("bot", st.session_state.response_parts['response'])

# Generate YouTube links and images based on user's reason and feelings feelings =
st.session_state.get('feelings', '')
reason = st.session_state.get('reason', '')

if feelings and reason:


# Generate YouTube link
query = f"{reason} {feelings} mental health tips" video_links =
generate_youtube_links(query)

st.write("### 🎥 Recommended Videos:") for title,


link in video_links:
st.markdown(f"- [{title}]({link})")

# 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 Details Section


elif selected == "Project Details": #
Header
st.markdown("<h2 style='text-align: center; color: SlateGray;'>Project Details</h2>",
unsafe_allow_html=True)
st.write("") # Add some space

# 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

# About the Project


st.markdown("<h3 style='color: #000080;'>About the Project:</h3>", unsafe_allow_html=True)
st.write("""
The **AI-Powered Mental Health Therapist Chatbot** is an innovative application designed to
provide mental health support and therapeutic guidance using advanced artificial intelligence (AI)
technologies.
The chatbot leverages **Cognitive Behavioral Therapy (CBT)** and **Dialectical Behavior Therapy
(DBT)** techniques to offer personalized, empathetic, and actionable solutions to users experiencing
mental health challenges.
""")
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)

for i, member in enumerate(team_members): with


locals()[f"col{i+1}"]:

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("")

# Language selection st.session_state.input_language =


st.selectbox(
"🌍 Select your preferred language:", ["English",
"Telugu", "Hindi"],
index=["English", "Telugu", "Hindi"].index(st.session_state.input_language)
)
st.write(f"Selected Language: {st.session_state.input_language}")

47
CHAPTER-11
RESULTS
11.1 Screenshots

Interface of Our Project:

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..

11.3 Future Scope

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.

 Introduce sentiment-based response refinement to provide more personalized and empathetic


answers.

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.

3. Real-Time Crisis Intervention


 Implement an emergency response feature that connects users to mental health professionals
or crisis helplines in urgent situations.

 Develop an AI-driven alert system that detects distress signals and provides immediate
support options.

4. Personalization & Memory Retention


 Allow users to create optional profiles where the chatbot remembers past interactions
for better long-term assistance.

 Provide personalized self-care recommendations based on previous conversations and mood


patterns.

5. Integration with Mental Health Resources


 Offer seamless integration with online therapy platforms, self-help articles, and guided
meditation tools.

 Sync with wearable health devices (e.g., smartwatches) to monitor stress levels and suggest
relaxation techniques.

6. Mobile Application Development


 Create a mobile-friendly version for users to access the chatbot anytime, anywhere.

 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.

8. Ethical AI & Privacy Enhancements


 Strengthen data encryption and privacy policies to ensure user confidentiality.

 Develop AI fairness mechanisms to eliminate biases in mental health advice and responses.

53
CHAPTER-12
REFERENCES & BIBLIOGRAPHY

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

You might also like