Final Report Major Project
Final Report Major Project
A PROJECT REPORT
Submitted by
BACHELOR OF ENGINEERING
In
MAY 2024
ANNA UNIVERSITY : CHENNAI 600 025
BONAFIDE CERTIFICATE
SIGNATURE SIGNATURE
Dr. C. AKILA Dr. J. JESU VEDHA NAYAHI
HEAD OF THE DEPARTMENT SUPERVISOR
Assistant Professor, Senior Assistant Professor,
Dept. of Computer Science Dept. of Computer Science
and Engineering, and Engineering,
Anna University Regional Anna University Regional
Campus - Tirunelveli, Campus - Tirunelveli,
Tirunelveli – 627007. Tirunelveli – 627007.
ii
ACKNOWLEDGEMENT
We wish to express our sincere gratitude to our Head of the Department and
Project coordinator Dr. C. AKILA, Assistant Professor, Department of Computer
Science and Engineering, for her motivation, inspiration and encouragement to
undertake this work.
We wish to express our special thanks and our deepest gratitude to our guide
Dr. J. JESU VEDHA NAYAHI, Senior Assistant Professor, Department of
Computer Science and Engineering, for her suggestions and supports during the
course of our project.
We are also indebted to all the teaching and non-teaching staff members of
our college for helping us directly or indirectly by all means throughout the course
of our study and project work.
ASHOK RAJARAM S
RAMAJEYAM R
VENKATESAN M
ABDUL FARIS A
iii
ABSTRACT
This project aimed to develop a mental health chatbot using Python to provide
emotional support, resources, and tools to users. The chatbot leverages Telegram's
messaging platform for user interaction and integrates various functionalities to
promote mental well-being.
The chatbot provides users with options for relaxation techniques and self-help
tools. This may include guided breathing exercises, etc. Additionally, the chatbot
offers short meditation guides to help users manage stress and improve focus.
It is built using Python and leverages several libraries for its functionalities.
Sentiment analysis is performed using the FLAIR library. Text generation and
response tailoring are achieved through a fine-tuned Large Language Model (LLM)
integrated via HuggingFace and LangChain libraries. The Telegram Bot API allows
for user interaction within the Telegram messaging platform.
iv
TABLE OF CONTENTS
ABSTRACT iv
LIST OF TABLES ix
LIST OF ABBREVIATIONS x
1 INTRODUCTION 1
1.1 OBJECTIVE 2
1.2 SCOPE 3
2 SYSTEM DESCRIPTION 6
2.1.3 Python 7
2.1.4 Python-telegram-bot 7
v
3 SYSTEM DESIGN 12
4 SYSTEM DEVELOPMENT 16
4.1 MODULES 16
5.1 IMPLEMENTATION 18
5.2 TESTING 26
vi
5.2.1.3 Response Generation and
28
Resource Management Module
6 CONCLUSION 29
APPENDIX 30
REFERENCES 40
vii
LIST OF FIGURES
viii
LIST OF TABLES
ix
LIST OF ABBREVIATIONS
AI ARTIFICIAL INTELLIGENCE
ML MACHINE LEARNING
UI USER INTERFACE
x
CHAPTER 1
INTRODUCTION
In a world where mental health support is crucial yet often inaccessible, our
chatbot serves as a beacon of hope and understanding. Powered by advanced
technology and crafted with empathy, our chat-bot is designed to provide a safe space
for you to express your thoughts, feelings, and concerns without judgment. Whether
you are struggling with anxiety, depression, stress, or simply need someone to talk to,
our chatbot is here to lend a compassionate ear 24/7. Through thoughtful
conversation and personalized guidance, it aims to empower you on your path to
mental wellness.
Statistics show that 1 in every 5 individuals suffers from some form of mental
health illness symptoms. 50% of mental health conditions begin by age 14 and 75%
of mental health conditions develop by age 24. This project contributes to the
growing field of mental health chatbots by demonstrating the potential of AI to create
accessible and user-friendly support tools. By offering emotional support, relevant
resources, and self-help techniques, the chatbot empowers users to take charge of
their mental well-being and connect with necessary resources.
1
1.1 OBJECTIVE
This project aimed to develop a mental health chatbot using Python to bridge
the gap in accessible mental health support tools. The specific objectives focused on
creating a user-friendly and informative platform that prioritizes user safety and
emotional well-being.
2
1.2 SCOPE
It will initially focus on supporting a specific mental health area with resources
and tools tailored accordingly. The chatbot is intended as a supportive tool, not a
replacement for professional help. Complex features and functionalities like
personalized therapy plans are outside the scope of this initial version.
3
[2]NLP Techniques for Sentiment Analysis in Mental Health (2019)
This literature review examines the use of Natural Language Processing (NLP)
techniques for sentiment analysis in the context of mental health. The survey provides
an overview of existing research on sentiment analysis methods applied to textual
data from individuals with mental health conditions, such as social media posts,
online forums, and electronic health records. It discusses the challenges and
opportunities of using NLP for sentiment analysis in mental health care, including
data privacy concerns, linguistic variability, and model interpretability issues.
This survey explores the landscape of machine learning algorithms used for
mood detection and emotional analysis in mental health research and applications.
The survey reviews various machine learning techniques, including supervised,
unsupervised, and deep learning approaches, employed for mood classification,
emotion recognition, and affective computing tasks. It assesses the strengths,
limitations, and computational complexities of different machine learning algorithms
in capturing and analyzing emotional states from diverse data sources, such as text,
speech, and physiological signals. The survey also discusses the implications of using
machine learning for mood detection in clinical settings and potential avenues for
future research in this field.
4
1.3 PROBLEM DEFINITION
Integrating mental health services into platforms like WhatsApp, Telegram and
Instagram offers several advantages. Firstly, it meets individuals where they are most
comfortable and active online, reducing barriers to seeking help and support.
Secondly, it enables real-time and asynchronous communication, allowing users to
access support whenever they need it, regardless of time or location. Thirdly, it
facilitates personalized and interactive experiences, leveraging the unique features of
each platform to deliver tailored interventions and engage users in meaningful ways.
5
CHAPTER 2
SYSTEM DESCRIPTION
System requirements are the configuration that a system must have in order for
a hardware or software application to run smoothly and efficiently. Failure to meet
these requirements can result in installation problems or performance problems. The
former may prevent a device or application from getting installed, whereas the latter
may cause a product to malfunction or perform below expectation or even to hang or
crash.
6
2.1.3 PYTHON
2.1.4 PYTHON-TELEGRAM-BOT
7
2.1.5 NLP AND ML LIBRARIES
Flair and Hugging Face are leading libraries in Natural Language Processing
(NLP), offering powerful tools and resources for developers. Flair, developed by
Zalando Research, provides state-of-the-art NLP models and embeddings, along with
an easy-to-use framework for training custom models. Hugging Face's Transformers
library is renowned for its vast collection of pre-trained models and APIs, enabling
seamless integration of cutting-edge NLP capabilities into applications. Langchain,
another notable project, focuses on multilingual NLP research and development,
contributing to the advancement of language understanding across diverse linguistic
contexts. PyTorch, the underlying framework for both Flair and Transformers,
provides efficient tensor computation with Graphics Processing Unit (GPU)
acceleration, making it a cornerstone of modern deep learning research and
application.
Woebot[4]
Advantages
● The text-based format limits the ability to convey empathy and nuance
compared to human interaction.
Youper[5]
Youper combines elements of CBT with techniques from positive psychology
to promote emotional well-being. It personalizes recommendations and support
strategies based on user data collected through questionnaires and interaction
patterns.
Advantages
● Youper requires user registration, which might deter users seeking complete
anonymity.
● The reliance on user data raises privacy concerns, and the effectiveness of
personalization algorithms might vary depending on the amount and quality
of data collected.
9
Wysa[6]
Wysa takes a conversational AI approach, utilizing a friendly virtual
companion persona to engage with users. It offers emotional coaching, mindfulness
exercises, and mood tracking functionalities.
Advantages:
10
2.2.2 Proposed Work
Building upon the functionalities of existing mental health chatbots and
acknowledging their limitations, this project proposes a novel mental health chatbot
designed to address limitations found in existing systems. We will focus on a specific
mental health domain (e.g., anxiety, stress) to provide more targeted support and
resources. A sentiment analysis model, trained using the FLAIR library, will
categorize user messages to understand their emotional tone. A fine-tuned Large
Language Model (LLM) from HuggingFace Transformers will generate tailored
responses that consider the sentiment tone of the user. This ensures responses are
empathetic and supportive, addressing the user's specific state.
To prioritize user privacy, conversations will be confidential and not stored.
The chatbot will be transparent about data collection practices, if any, and offer users
control over their data. Accessibility is also a priority, So, the chatbot is integrated
with the telegram platform to be accessed by anyone who has a telegram account.
11
CHAPTER 3
SYSTEM DESIGN
3.1 ARCHITECTURE DIAGRAM
Fig 3.1 shows the mental health chatbot system. Users interact via a messaging
platform (i.e., Telegram). The system analyzes messages to understand emotions,
then generates tailored responses using a large language model. An optional data
management module can store anonymized data.
DFD Level 0 is also called a Context Diagram. It’s a basic overview of the
whole system or process being analysed or modelled. It’s designed to be an
at-a-glance view, showing the system as a single high-level process.
12
Fig 3.2 DFD Level 0
Fig 3.2 shows the entire chatbot application as a single entity interacting with
two external entities: the User and the Mental Health Resources database.
DFD Level 1 provides a more detailed breakout of pieces of the Context Level
Diagram. You will highlight the main functions carried out by the system, as you
break down the high-level process of the Context Diagram into its sub processes.
13
Fig 3.3 reveals the core processes within the application. It shows how user
input interacts with the Messaging Platform API, Sentiment Analysis, Response
Generation, and optional Data Management modules. It also emphasizes the
connection to the Mental Health Resources for retrieving relevant information
DFD Level 2 then goes one step deeper into parts of Level 1. It may require
more text to reach the necessary level of detail about the system’s functioning.
14
3.3 USE CASE DIAGRAM
Fig 3.5 displays the use case diagram of the chatbot in real time scenarios.
15
CHAPTER 4
SYSTEM DEVELOPMENT
4.1 MODULES
This module provides the user with a seamless interaction point. The User
Interface (UI), integrated with messaging platform (I.e., Telegram messenger), allows
users to send text messages and receive responses from the chatbot. Usability is
prioritized, ensuring clear instructions and intuitive navigation for a user-friendly
experience. Also Telegram offers extensive customization features for resource
delivery through Telegram commands.
This module focuses on analyzing user input and preparing it for response
generation. The Natural Language Processing (NLP) module plays a crucial role here.
Sentiment analysis, powered by a trained model (FLAIR), which uses Long
Short-Term Memory(LSTM) algorithm with Recurrent Neural Network(RNN) to
identify the emotional tone (positive, negative, neutral) in user messages,
understanding the user's state of mind. Additionally, Text Preprocessing cleans and
prepares the message for further processing by removing unnecessary elements and
ensuring a structured format.
16
4.1.3 Response Generation and Resource Management Module
17
CHAPTER 5
5.1 IMPLEMENTATION
18
Fig 5.1 shows the user interface of the telegram bot after creating the bot using
Bot Father. This is the first page which shows the description of the bot.
Fig 5.2 shows the available commands the user can access to trigger various
action of the bot.(Resources, Techniques, Meditation, Quotes, Affirmation),
19
5.1.2 Processing and Understanding
Fig 5.3 shows the initialization of the bot. The bot initiates the chat by
explaining about itself and asks the user to interact with it.
20
Fig 5.4 Response generated and delivered to the user
Fig 5.4 shows the bot responding to the user. The bot detected the emotion of
the user and tailored the response to encourage and cheer the user and also provides
the meditation command to start a short meditation session.
21
5.1.3 Response Generation and Resource Management
Fig 5.5 shows the chatbot displaying a guided meditation session message
when the meditation command is clicked. The user can also access the meditation
command by typing /meditation.
22
Fig 5.6 Bot suggesting techniques and meditation
Fig 5.6 shows the bot response with techniques command which takes us to the
available techniques or coping strategies to reduce stress or depression. By clicking
each technique, It takes you to an external link which contains a detailed explanation
of the technique.
23
Fig 5.7 Bot generating random quotes
Fig 5.7 shows the bot generating a quote each time the quotes command is
started or clicked. It is to motivate the user using a motivational or inspiration quote.
24
Fig 5.8 Bot generating affirmations
Fig 5.8 shows the bot generating random affirmations each time the affirmation
command is used to boost the mood of the user and to make his day
25
5.2 TESTING
A test case is a document, which has a set of test data, preconditions, expected
results and post conditions, developed for a particular test scenario in order to verify
compliance against a specific requirement.
26
4 /techniques The chatbot sends The chatbot Pass
command a list of coping displays techniques
strategies or to support the user
techniques
5 /meditation The chatbot The chatbot Pass
command displays a displays a message
message with a with a guided
guided meditation meditation session
session
6 /quotes Generates a Generates a random Pass
command random quote to inspiration quote
motivate the user each time
7 /affirmation Generates a Generates a random Pass
command random affirmation
affirmation message each time
message to boost
the user mood
27
5.2.1.3 Response Generation and Resource Management Module
S. No Input Desired Output Obtained Output Test case result
1 User sends the The LLM The LLM generates Pass
message "I'm generates a a supportive and
feeling supportive encouraging
anxious." response response
acknowledging understanding the
the user's anxiety user’s anxiety
2 User sends the The LLM The LLM generates Pass
message "I'm generates a a cheerful and
feeling response motivating response
motivated acknowledging understanding the
today!" the user's positive user’s positive tone
mood
3 User sends the The LLM The LLM provides Pass
message "How generates a a response with the
can I cope response relevant resources
with stress?" providing on coping up with
information on stress
coping with stress
28
CHAPTER 6
CONCLUSION
The positive impact of this project extends beyond the individual user. By
offering a safe and anonymous platform for expression, it can help reduce stigma
surrounding mental health issues. Furthermore, the potential for scalability allows this
technology to reach a wider population, fostering a more open and supportive
conversation about mental well-being on a global scale.
Looking towards the future, this project presents exciting possibilities for
further development. Advanced personalization features that incorporate user context
from past interactions can be implemented to provide even more tailored support.
Additionally, exploring the integration of more advanced language models with larger
datasets could enable the chatbot to engage in deeper and more nuanced
conversations, fostering a deeper level of understanding and support for users.
29
APPENDIX
Telegram_bot.py
import torch
tokenizer = AutoTokenizer.from_pretrained(checkpoint)
base_model = AutoModelForSeq2SeqLM.from_pretrained(checkpoint,
device_map='auto',
torch_dtype=torch.float32)
30
llm = HuggingFacePipeline.from_model_id(model_id=checkpoint,
task='text2text-generation',
template = """{text}"""
def get_sentiment(text):
sentence = Sentence(text)
sentiment_model.predict(sentence)
sentiment = sentence.labels[0].value
return sentiment
resource_suggestion = ""
if sentiment == 'NEGATIVE':
return resource_suggestion
31
#start command
#help command
* Analyze your messages to understand your emotions and offer relevant advice.
* You can use keywords like "stressed," "anxious," or "low mood" to get targeted
support.
32
#resources command
message = articles.articles_list
#resources command
message = techniques.techniques_list
#meditation command
message = meditation.guide
#quotes command
<b><i>{quotes.generate_quote()}</i></b>
"""
#affirmation command
"""
#message handler
message_type = update.message.chat.type
text = update.message.text
sentiment = get_sentiment(text)
print(sentiment)
if sentiment == "NEGATIVE":
reply = chat.run("My mental health is negative" + text + ". Can you give me
some advice to motivate me")
else:
34
reply = "User emotion: " + sentiment + "\n" + reply
await update.message.reply_text(reply)
if __name__ == "__main__":
app = Application.builder().token(TOKEN).build()
# Command handlers
app.add_handler(CommandHandler("start", start_command))
app.add_handler(CommandHandler("help", help_command))
app.add_handler(CommandHandler("resources", resources_command))
app.add_handler(CommandHandler("techniques", techniques_command))
app.add_handler(CommandHandler("meditation", meditation_command))
app.add_handler(CommandHandler("quotes", quotes_command))
app.add_handler(CommandHandler("affirmation", affirmation_command))
# Message handler
app.add_handler(MessageHandler(filters.TEXT, handle_message))
# Error handler
app.add_error_handler(error)
35
# Polling
print("Bot is running...")
app.run_polling(poll_interval=3)
meditation.py
guide = """Feeling stressed? Take a moment to relax with this short mindfulness
meditation.
Mindfulness meditation helps you focus on the present moment and reduce stress.
Here's a simple exercise you can try:
1. <b>Find a comfortable position:</b> Sit or lie down in a way that allows you to
relax.
2. <b>Close your eyes gently:</b> If you prefer, you can soften your gaze instead.
3. <b>Focus on your breath:</b> Notice the sensation of your breath entering and
leaving your body. Don't try to control your breath, just observe it naturally.
4. <b>Thoughts will wander:</b> This is normal. When you notice your mind
wandering, gently bring your attention back to your breath.
5. <b>Continue for a few minutes:</b> Start with a few minutes and gradually
increase the duration as you become more comfortable.
6. <b>Notice how you feel:</b> After the meditation, take a moment to observe
how you feel. You might feel calmer and more focused.
Remember, practice makes perfect. The more you meditate, the easier it becomes to
manage stress and improve your well-being.
For longer or more detailed meditations, you can explore guided meditation apps or
online resources. eg: <a
href="https://www.headspace.com/meditation/techniques">HeadSpace</a>"""
36
techniques.py
* <a
href="https://connect.mayoclinic.org/blog/living-with-mild-cognitive-impairment-mc
i/newsfeed-post/stress-relief-is-only-a-few-breaths-away/">Deep Breathing
Exercises</a> - Inhale deeply, hold, then exhale slowly to reduce stress and promote
relaxation.
* <a
href="https://www.webmd.com/sleep-disorders/muscle-relaxation-for-stress-insomnia
">Progressive Muscle Relaxation (PMR)</a> - Tense and relax muscle groups to
release tension and induce relaxation.
* <a
href="https://www.mindful.org/meditation/mindfulness-getting-started/">Mindfulnes
s Meditation</a> - Focus on the present moment without judgment to reduce stress
and increase awareness.
* <a
href="https://www.verywellmind.com/writing-in-a-gratitude-journal-for-stress-relief-
3144887">Gratitude Journaling</a> - Write down things you're thankful for to
cultivate positivity and shift focus away from negativity.
* <a
href="https://www.verywellmind.com/what-is-cognitive-behavior-therapy-2795747"
>Cognitive Behavioral Therapy (CBT)</a> - Challenge negative thoughts and
replace them with more balanced ones to improve mood.
* <a href="https://www.healthline.com/health/grounding-techniques">Grounding
Techniques</a> - Focus on sensory experiences to stay present and reduce anxiety or
dissociation.
* <a
href="https://self-compassion.org/self-compassion-practices/">Self-Compassion
Exercises</a> - Treat yourself with kindness and understanding to build resilience
and self-acceptance.
37
* <a
href="https://adaa.org/understanding-anxiety/obsessive-compulsive-disorder/social-s
upport-strategies">Social Support Strategies</a> - Seek connections with others for
emotional support and companionship.
* <a
href="https://www.betterhealth.vic.gov.au/health/healthyliving/exercise-and-mental-h
ealth">Physical Activity</a> - Engage in exercise to improve mood, reduce stress,
and enhance overall well-being.
* <a
href="https://www.verywellmind.com/forty-healthy-coping-skills-4586742">Healthy
Coping Skills</a> - Use positive strategies like hobbies and relaxation techniques to
manage stress effectively.
* <a
href="https://www.mayoclinic.org/healthy-lifestyle/stress-management/in-depth/relax
ation-technique/art-20045368">Relaxation Techniques</a> - Practice techniques like
visualization and deep breathing to calm the body and mind and reduce stress."""
articles.py
articles_list = """Here are some useful resources for mental health support
38
* National Alliance on Mental Illness <a
href="https://www.nami.org/">(NAMI)</a> - Provides information, education,
support, and advocacy for people with mental illness.
* The Trevor Project - Provides crisis intervention and suicide prevention for
LGBTQ youth. Call their helpline at 1-866-488-7386 or visit The <a
href="https://www.thetrevorproject.org/">Trevor Project</a>
* <a
href="https://www.thelancet.com/journals/lansea/article/PIIS2772-3682(23)00160-9/f
ulltext">Mental health in India: evolving strategies, initiatives, and prospects</a> -
The Lancet Regional Health - Southeast Asia
39
REFERENCES
4. Woebot - https://woebothealth.com/
5. Youper - https://www.youper.ai/
6. Wysa - https://www.wysa.com/
LangChain Documentation -
https://python.langchain.com/docs/integrations/platforms/huggingface/
40