AN AUTOMATED CONVERSATION FOR
MENTAL HEALTH CHATBOT USING
ARTIFICIAL
INTELLIGENCE
PROJECT REPORT
Submitted by
CHAPTER 1
INTRODUCTION
1.1 INTRODUCTION TO PROJECT
A Mental Health health care chatbot is a piece of software that conducts a
conversation with users via auditory or textual methods. A health care chatbot
facilitates the job of a MENTAL HEALTH provider and helps improve their
performance by interacting with users in a human-like way. These bots can also
play a critical role in making relevant MENTAL HEALTH information
accessible to the right stakeholders, at the right time. The system application
uses the question and answer protocol in the form of a chatbot to answer user
queries. This system is developed to reduce the MENTAL HEALTH cost and
time of the users, as it is not possible for the users to visit the doctors or experts
when immediately needed. The response to the question will be replied based
on the user query and knowledge base. The significant keywords are fetched
from the sentence and answer to those sentences. If the match is discovered or
the significant, answer will be given or similar answers will be displayed. The
input sentence of the chat pattern is stored in an python. The chatbot would
coordinate the input sentence from the user question with the knowledge base.
Each query is compared with the knowledge database of the chatbot. The
important keywords are extracted from the given input sentence and the
sentence similarity is found. The keyword ranking and sentence similarity are
found using the N-gram, TF-IDF, and cosine similarity. The interfaces are
standalone built using the Python programming language.
1.2 OBJECTIVE OF THE WORK
Provide health information
Offering personalized health
advice Facilitating appointment
Providing emotional support
Offering medication remedies
Enhancing user engagemen
1
1.2 MACHINE LEARNING
Machine Learning is the field of study that gives computers the capability
to learn without being explicitly programmed. ML is one of the most exciting
technologies that one would have ever come across. As it is evident from the
name, it gives the computer that makes it more similar to humans: The ability to
learn.
Machine learning is actively being used today, perhaps in many more
places than one would expect.
Fig:1.3 Machine learning architecture
FEATURES
Machine learning is data driven technology. Large amount of data
generated by organizations on daily bases. So, by notable
relationships in data, organizations makes better decisions.
Machine can learn itself from past data and automatically improve.
From the given dataset it detects various patterns on data.
For the big organizations branding is important and it will become
more easy to target relatable customer base.
It is similar to data mining because it is also deals with the huge
amount of data.
2
1.2.1.1. MACHINE LEARNING METHODS
Some of the methods of Artificial Intelligence are categorized as
1.2.1.2. Supervised machine learning
Supervised learning, also known as supervised machine learning, is
defined by its use of labeled datasets to train algorithms to classify data or
predict outcomes accurately. As input data is fed into the model, the model
adjusts its weights until it has been fitted appropriately. This occurs as part of
the cross validation process to ensure that the model avoid overfitting or
underfitting. Supervised learning helps organizations solve a variety of
real-world problems at scale, such as classifying spam in a separate folder from
your inbox. Some methods used in supervised learning include neural networks,
naïve bayes, linear regression, logistic regression, random forest, and support
vector machine (SVM).
1.2.1.3. Unsupervised machine learning
Unsupervised learning, also known as unsupervised machine learning,
uses machine learning algorithms to analyze and cluster unlabeled datasets.
These algorithms discover hidden patterns or data groupings without the need
for human intervention. This method’s ability to discover similarities and
differences in information make it ideal for exploratory data analysis,
cross-selling strategies, customer segmentation, and image and pattern
recognition. It’s also used to reduce the number of features in a model through
the process of dimensionality reduction. Principal component analysis (PCA)
and singular value decomposition (SVD) are two common approaches for this.
Other algorithms used in unsupervised learning include neural networks,
k-means clustering, and probabilistic clustering methods.
1.2.1.4. Semi-supervised learning
Semi-supervised learning offers a happy medium between supervised and
unsupervised learning. During training, it uses a smaller labeled data set to
guide classification and feature extraction from a larger, unlabeled data set.
Semi- supervised learning can solve the problem of not having enough labeled
data for a supervised learning algorithm. It also helps if it’s too costly to label
enough data.
1.3 APPLICATIONS OF MACHINE LEARNING
• Personalized Shopping
• AI-powered Assistants
• Fraud Prevention
• Voice Assistance
• Personalized Learning
3
1.3.1 Advantages
• AI drives down the time taken to perform a task.
• AI enables the execution of hitherto complex tasks
without significant cost outlays.
• AI operates 24*7 without interruption or breaks and has no downtime.
• AI augments the capability of differently abled individual
• Increased Accuracy: AI systems can perform tasks with a
high level of precision and accuracy, reducing errors
compared to human counterparts.
• Scalability: AI systems can easily scale up to handle large
volumes of tasks or data without significant increase in cost
or resources.
• Consistency: AI systems can consistently perform
tasks without variations or deviations, ensuring
uniformity in output.
• Data Analysis: AI can analyze large datasets quickly and
efficiently, extracting valuable insights and patterns that
may not be apparent to humans.
• Personalization: AI algorithms can personalize user
experiences by analyzing user preferences and behavior,
leading to customized recommendations and services.
• Automation of Repetitive Tasks: AI can automate
repetitive and mundane tasks, freeing up human resources to
focus on more creative and strategic activities.
• Improved Decision Making: AI systems can process vast
amounts of data and provide insights to support decision
making, leading to more informed and timely decisions.
• Risk Reduction: AI can be used to simulate and predict
outcomes, helping to identify potential risks and mitigate
them proactively.
• Innovation: AI enables the development of innovative
products and services by pushing the boundaries of what
is possible through automation and intelligent systems.
4
CHAPTER 2
LITERATURE SURVEY
2.1 Harnessing NLP Advancements for Enhanced Chatbot Interventions
in Mental Health (2016-2019)
Abstract
Between 2016 and 2019, advancements in natural language processing
(NLP) techniques sparked a wave of innovation in various domains,
including mental health support through chatbots. Researchers and
developers seized the potential of NLP algorithms, sentiment analysis, and
linguistic modeling to revolutionize the capabilities and efficacy of
chatbots in providing mental health assistance.Machine learning
algorithms formed the backbone of these advancements. These
algorithms enabled chatbots to learn from vast amounts of data,
continually improving their understanding of human language nuances,
emotions, and context. As a result, chatbots became more adept at
interpreting user inputs, discerning emotional cues, and providing
appropriate responses. Sentiment analysis played a crucial role in
enhancing chatbots' ability to gauge users' emotional states. By analyzing
the sentiment conveyed in users' messages, chatbots could identify signs
of distress, anxiety, or depression, allowing them to offer tailored support
and intervention strategies. This capability significantly augmented the
empathetic and responsive nature of chatbots, fostering a sense of
connection and understanding for users seeking mental health assistance.
2.2 Enhancing Access to Mental Health Support(2018-
2021) Abstract
From 2018 to 2021, the integration of chatbots with mobile platforms
marked a significant advancement in the accessibility of mental health
support services. This period saw a surge in research and development
aimed at exploring the synergies between chatbots and various mobile
technologies, including smartphone apps and social media platforms. The
goal was to create integrated solutions that could provide real-time
support and personalized interventions to individuals seeking mental
health assistance.One of the key advantages of integrating chatbots with
mobile platforms was the ability to reach a broader audience, particularly
younger demographics who are often more comfortable using mobile
devices for seeking help and support. By leveraging the widespread
adoption of smartphones and the ubiquity of messaging apps and social
media platforms, mental health chat bots could meet users where they
were already spending much of their time online.
5
2.3 Ethical Challenges and Considerations in the Deployment
of Mental Health Chatbots (2020-2023)
Abstract
The years spanning 2020 to 2023 marked a significant period of
introspection and analysis regarding the ethical implications surrounding the
utilization of chatbots in the realm of mental health. This period witnessed a
surge in discussions among researchers, practitioners, and policymakers
regarding the multifaceted challenges and ethical dilemmas inherent in the
integration of chatbot technology into mental health care provision. Key areas
of concern included privacy protection, confidentiality maintenance, data
security, algorithmic bias mitigation, human oversight necessity, cultural
sensitivity incorporation, and the potential for unintended harm arising from
inaccurate or inappropriate responses. These deliberations underscored the
pressing necessity for the establishment of comprehensive ethical guidelines
and regulatory frameworks aimed at fostering the responsible development
and deployment of chatbots within mental health contexts.The proliferation of
digital technologies, coupled with the growing demand for accessible mental
health support, has led to the increasing adoption of chatbots as a means of
delivering mental health interventions. Chatbots, equipped with artificial
intelligence (AI) algorithms, offer users the convenience of immediate, round-
the-clock assistance for various mental health concerns, ranging from stress
and anxiety to depression and beyond. However, this rapid expansion in the
utilization of chatbots has prompted a critical examination of the ethical
implications associated with their implementation in mental health settings.
The years from 2020 to 2023 were characterized by heightened scrutiny and
discourse surrounding the ethical challenges inherent in the utilization of
chatbots for mental health support.
2.4The Future Trajectory of Chatbots in Mental Health
Abstract
As technology continues to advance at a rapid pace, the landscape of
mental health interventions, particularly in the realm of chatbots, is poised for
significant evolution. This abstract provides an overview of the anticipated
future directions in the field of chatbots for mental health, focusing on the
development of more sophisticated models, integration with emerging
technologies, and the expansion of intervention scope to address diverse
populations and mental health conditions. Chatbots have emerged as
promising tools for providing mental health support, offering users a
convenient and accessible means of accessing resources and assistance.
However, as the field progresses, there is a growing recognition of the need for
further refinement and innovation to maximize their effectiveness and impact.
6
CHAPTER 3
SYSTEM
ANALYSIS
3.1 PROBLEM SPECIFICATION
A medical chatbot is a computer program that imitates human activity in
a chat, maintains a dialogue with a user (a medical worker or a patient)
selecting answers from databases and responding to specific sets of commands.
The chatbot technology in MENTAL HEALTH aims to save time and avoid
human errors. The peculiarity of the technology is that it either learns itself on
the basis of conversations with real people or pulls replies from a database of
pre- programmed answers. Therefore we have 2 types of chatbots: simple
chatbots and MENTAL HEALTH chatbots with artificial intelligence. In the
case with simple medical chatbots, we just have to provide as many probable
scenarios as possible for what a person can ask. With all possible scripts, a
chatbot is capable of recognizing the request and making an appointment to see
a physician, for example. If the patient has not used any of the registered
keywords, then the chatbot will answer "Sorry, I did not understand".
The second approach to MENTAL HEALTH chatbot development is based on
learning. Smarter chatbots can analyze patient responses and ask clarifying
questions based on them. Such AI chatbots in MENTAL HEALTH help speed
up the collection of medical history by a doctor and even establish a preliminary
diagnosis based on the patient's initial complaint, thereby increasing the quality
and speed of medical care. However, artificial intelligence in a chatbot is
optional, as bots are engaged in the automation of routine actions.
3.2 EXISTING SYSTEM
For every MENTAL HEALTH problem, there is a need of doctor to
consult. Most of the existing system consist of SVM Algorithm. But it analysis
and predicts the given input in a slower manner. In AI, the MENTAL HEALTH
chatbot needs ever better algorithm to predict the queries. It will give
sometimes a wrong results for the patients. Because of this drawbacks people
will not use MENTAL HEALTH chatbot
• Chatbot for Psychiartic counseling: gives adivces for patients to
keep their mental health in stable.
• Voice chatbot: interaction between humans.
• MENTAL HEALTH chatbot: gives health related advices to the
every patients using it.
7
3.2.1. Disadvantages
• Certain chatbots are poor in processing and takes time to filter
the results. This anonys the users.
• Different chatbot require different installation procedures
and hence increases initial installation cost unlike human
beings
• Like other chatbots, this algorithm takes its process as slow
and giving the irrelevant result to the users.
3.3 PROPOSED SYSTEM
At first, chatbot is created which can help the users to get the
symptoms of their diseases. The chatbots are conversational virtual
assistants which automate interactions with the patients. The proposed idea
is to make a MENTAL HEALTH chatbot using Artificial Intelligence which
will diagnose the disease and give a basic knowledge about the disease
before consulting a doctor. To reduce the MENTAL HEALTH costs and
improve accessibility to medical knowledge the MENTAL HEALTH
chatbot is made. Here JSON is used for handling the database. The proposed
idea is to make a medical chatbot using artificial intelligence which will
diagnose the disease and supply basic details about the disease before
consulting a doctor. To reduce the MENTAL HEALTH costs and improve
accessibility to medical knowledge the medical chatbot is made. The
chatbots are conversational virtual assistants which automate interactions
with the users.
3.3.1 Advantage of Proposed System
• Naive bayes algorithm predicts the tag of text and
calculate the probability of prediction.
• It particularly works well with NLP problems.
• There is an easy and efficient approach for creating a closed domain.
• The result of prediction and level of accuracy is high when
compared to other algorithms in AI.
• It reduced the cost of users and it also easily schedule appointment.
8
CHAPTER 4
SYSTEM SPECIFICATION
4.1 SOFTWARE SPECIFICATION
Front end :HTML & CSS AND JAVASCRIPT
Algorithm used : Naïve Bayes Algorithm
Software:: Python
Back end : JSON
4.2 SOFTWARE DESCRIPTION
4.2.1 Introduction to HTML and CSS
HTML, or Hypertext Markup Language, is the standard markup language for
creating web pages and web applications. It provides the structure and content
of a webpage by using various tags and elements. When a web browser reads an
HTML file, it interprets the tags and displays the content accordingly.
Here are some key concepts and elements in HTML:
Tags: HTML tags are used to define different elements in a webpage. They are
enclosed in angle brackets (<>) and usually come in pairs, with an opening tag
and a closing tag. For example, the <p> tag is used to define a paragraph, and it
is closed with the </p> tag.
Elements: HTML elements consist of a tag and the content within it. For
instance, the <h1> element defines a heading and the text placed within it
becomes the heading text.
Attributes: HTML attributes provide additional information about an element.
They are placed within the opening tag of an element and are comprised of a
name and a value. For example, the "src" attribute in an <img> tag specifies the
source (URL) of an image.
Structure: HTML documents have a specific structure. The root element is
<html>, and within it, you have the <head> and <body> elements. The <head>
element contains meta-information about the document, such as the page title,
character encoding, or linked stylesheets. The <body> element holds the visible
content of the webpage.
9
Text Formatting: HTML provides various tags for text formatting, such as
headings (<h1> to <h6>), paragraphs (<p>), emphasis (<em> or <strong>), lists
(<ul>, <ol>, <li>), and more.
Links: The <a> tag is used to create hyperlinks. It requires an "href" attribute
that specifies the target URL.
Images: The <img> tag is used to embed images in a webpage. It requires the
"src" attribute to specify the image source (URL) and the "alt" attribute to
provide alternative text for accessibility.
Tables: HTML tables are created using the <table>, <tr>, and <td> tags to
define rows, columns, and table cells, respectively.
Forms: HTML forms are used to collect user input. The <form> tag wraps form
elements like input fields, checkboxes, radio buttons, dropdowns, and submit
buttons. User input is typically submitted to a server-side script for processing.
These are just some of the basic concepts and elements in HTML. HTML can
be combined with CSS (Cascading Style Sheets) for styling and JavaScript for
interactivity to create dynamic and visually appealing web pages.
CSS:
When multiple CSS rules target the same element, the specificity of selectors
determines which styles take precedence. Specificity is based on the
combination of selectors used and their order of appearance. More specific
selectors override less specific ones.
Box Model: The CSS box model describes how elements are rendered in terms
of content, padding, borders, and margins. Each element is considered a
rectangular box, and CSS properties like width, height, padding, and margins
control its dimensions and spacing.
Responsive Design: CSS offers features for creating responsive web designs
that adapt to different screen sizes and devices. Media queries allow you to
apply specific styles based on the characteristics of the device, such as screen
width or orientation.
CSS Frameworks: CSS frameworks, such as Bootstrap and Foundation, provide
pre-designed styles, components, and responsive layouts that can be easily
integrated into web projects, saving development time and effort.
CSS is a powerful tool for controlling the presentation of web content and plays
a crucial role in creating visually appealing and user-friendly websites. It works
10
hand in hand with HTML and JavaScript to build dynamic and interactive web
experiences.
4.2.2. Introduction to Python
Python is a very simple programming language developed by Guido van
Rossum in 1989. Even if you are new to programming, you can learn python
without facing any issues. Python support both Object Oriented and Procedural
Programming language as it is a high level programming language designed for
general purpose programming. Python are multiparadigm, you can write
programs or libraries that are largely procedural, object-oriented, or functional
in all of these languages. It depends on what you mean by functional. Python
does have some features of a functional language. Simple Python was designed
to be easy for the Professional programmer to learn and to use effectively. If
you are an experienced C++ Programmer. Learning Python will oriented
features of C++. Most of the confusing concepts from C++ are either left out of
Java or implemented in a cleaner, more approachable manner. In Java there are
a small number of clearly defined ways to accomplish a given task. Object
oriented Python was not designed to be source-code compatible with any other
language. This allowed the Python team the freedom to design with a blank
state. One outcome of this was a 10 clean, usable, pragmatic approach to
objects. The object model in Python is simple and easy to extend, while simple
types, such as integers, are kept as high-performance non-objects. Robust The
multi-platform environment of the web places extraordinary demands on a
program, because the program must execute reliably in a variety of systems.
The ability to create robust programs. Was given a high priority in the design of
Python. Python is strictly typed language; it checks your code at compile time
and runtime. Python virtually eliminates the problems of memory management
and deal location, which is completely automatic. In a well-written Python
program, all run-time errors can and should be managed by your program.
Fig:4.2 Python architecture
Languages influenced by Python Python's design and philosophy have
influenced many other programming languages:
11
• Boo uses indentation, a similar syntax, and a similar object model.
• Cobra uses indentation and a similar syntax, and its
Acknowledgements document lists Python first among languages
that influenced it.
• Coffee Script, a programming language that cross-compiles
to JavaScript, has Pythoninspired syntax.
• ECMAScript /JavaScript borrowed iterators and generators from Python.
• GD Script, a scripting language very similar to Python, built-in
to the Godot game engine.
• Go is designed for the "speed of working in a dynamic
language like Python"and shares the same syntax for slicing
arrays.
• Groovy was motivated by the desire to bring the
Python design philosophy to Java.
• Julia was designed to be "as usable for general programming as Python".
• Nim uses indentation and similar syntax.
• Ruby's creator, Yukihiro Matsumoto, has said: "I wanted a scripting
language that was more powerful than Perl, and more object-oriented
than Python. That's why I decided to design my own language.
• Swift, a programming language developed by Apple, has some Python-
inspired syntax. Python's development practices have also been emulated
by other languages. For example, the practice of requiring a document
describing the rationale for, and issues surrounding, a change to the
language (in Python, a PEP) is also used in Tcl, Erlang and Swift.
4.2.3. Introduction to JSON:
JSON (JavaScript Object Notation) is a lightweight data interchange format that
is easy for humans to read and write and easy for machines to parse and
generate. It is a popular format for representing structured data, particularly in
web-based applications.
JSON is often used to transmit data between a server and a web application as
an alternative to XML. It is based on a subset of the JavaScript Programming
Language, Standard ECMA-262 3rd Edition - December 1999. JSON is
language-independent and can be used with many programming languages,
including JavaScript, Python, Java, C#, and more.
JSON data is represented using key-value pairs. A JSON object is enclosed in
curly braces {} and consists of one or more key-value pairs. The keys are
strings, and the values can be of various types, including strings, numbers,
booleans, arrays, or other JSON objects
12
4.3 NAIVE BAYES ALGORITHM
In statistics, naive Bayes classifiers are a family of simple "probabilistic
classifiers" based on applying Bayes' theorem with strong (naive) independence
assumptions between the features (see Bayes classifier). They are among the
simplest Bayesian network models, but coupled with kernel density estimation,
they can achieve high accuracy levels. Naive Bayes classifiers are highly
scalable, requiring a number of parameters linear in the number of variables
(features/predictors) in a learning problem. Maximum-likelihood training can
be done by evaluating a closed-form expression,: 718 which takes linear time,
rather than by expensive iterative approximation as used for many other types
of classifiers. In the statistics literature, naive Bayes models are known under a
variety of names, including simple Bayes and independence Bayes. All these
names reference the use of Bayes' theorem in the classifier's decision rule, but
naive Bayes is not (necessarily) a Bayesian method.
4.3.1. Advantages of Naive Bayes Algorithm:
●It is simple and easy to implement
●It doesn’t require as much training data
●It handles both continuous and discrete data
●It is highly scalable with the number of predictors and data points
●It is fast and can be used to make real-time predictions
●It is not sensitive to irrelevant feature
13
CHAPTER 5
SYSTEM DESIGN
5.1 INTRODUCTION
Technology is increasingly becoming a massive part of today's MENTAL
HEALTH scenario. Technology has changed the way how patients
communicate with doctors and not only that, but also how MENTAL HEALTH
is administered. Artificial intelligence and Chatbots are two ground breaking
technologies that have changed how patients and doctors perceive MENTAL
HEALTH. To make MENTAL HEALTH system more interactive a diagnostic
Chatbot is designed and developed using latest algorithms in machine learning,
decision tree algorithm to help the user to form a diagnosis of their condition
based on their symptoms. The system will be fed with information pertaining to
various diseases and using NLP, it will be able to understand the user query and
give a suitable response. The system can be used for effective information
retrieval in a similar manner like siri, alexa etc but the scope will be limited to
disease diagnosis.
5.2 SYSTEM ARCHITECTURE
An Mental Health chatbot is designed to provide personalized information and
recommendations based on the principles and practices of Mental Health, an
ancient holistic healing system from India. Here's an explanation of the
architecture typically used for an Mental Health chatbot.
User Interface: The chatbot interacts with users through a user interface, which
can be a web-based chat interface, a mobile app, or a messaging platform. Users
can input their queries, symptoms, or concerns related to their health or well-
being.
Natural Language Processing (NLP): The chatbot utilizes NLP techniques to
understand and interpret user queries. It employs algorithms to process the text
input, extract relevant keywords, and identify the intent behind the user's
message. NLP helps the chatbot comprehend user requests and generate
appropriate responses.
Knowledge Base: The Mental Health chatbot relies on a comprehensive
knowledge base of Mental Health principles, remedies, herbs, and treatments.
This knowledge base is created and maintained by Mental Health experts and
practitioners. It contains information about various health conditions, their
causes, symptoms, and Mental Health recommendations for treatment.
14
Recommendation Engine: Based on the user's input and the information
available in the knowledge base, the chatbot uses a recommendation engine to
generate personalized suggestions. The recommendation engine takes into
account the user's specific health concerns, body type (dosha), and other
relevant factors to provide tailored advice and remedies.
Rule-based System: Mental Health follows certain rules and guidelines for
treatment. The chatbot incorporates a rule-based system that applies these
principles to analyze the user's symptoms and health profile. It uses predefined
rules and logic to determine the appropriate course of action or remedies for the
user.
Machine Learning and AI: To enhance the chatbot's capabilities, machine
learning and AI techniques can be employed. The chatbot can be trained on a
large dataset of Mental Health texts, research papers, and clinical studies to
improve its understanding of user queries and provide more accurate
recommendations. Machine learning models can also be used to continuously
update and refine the knowledge base of the chatbot.
Integration with External Systems: The Mental Health chatbot can integrate
with external systems to provide a more comprehensive user experience. For
example, it can connect with electronic health record (EHR) systems to access
the user's medical history or link to an online Mental Health store to
recommend specific products or herbal formulations.
Privacy and Security: As with any MENTAL HEALTH-related application,
privacy and security are critical considerations. The chatbot architecture should
incorporate robust security measures to protect user data and ensure compliance
with relevant privacy regulations.
Overall, the architecture of an Mental Health chatbot combines NLP techniques,
a knowledge base of Mental Health principles, a recommendation engine,
rule-based systems, and machine learning/AI to provide personalized advice
and remedies based on Mental Health principles. It aims to enhance the user's
understanding of Mental Health and provide practical solutions for their health
concerns.
15
Fig.5.2 Chatbot architecture
5.2.1. Input
The patients ask his/her queries by text format to the chatbot.
5.2.2 Output
The Mental Health chatbot analyze the queries and separates the related
keywords and find the patient's MENTAL HEALTH conditions. Then respond
to patients queries.
5.3. MODULE DESCRIPTION
The mental health chatbot initiates the conversation by introducing itself and warmly
greeting the user. User Registration: If needed, the chatbot guides the user through a
registration process to collect essential details such as name, age, gender, and
relevant medical history. Symptom Assessment: The chatbot prompts the user to
describe their current mental health symptoms in detail, allowing them to articulate
their concerns. Diagnosis: Utilizing either rule-based logic or machine learning
algorithms, the chatbot evaluates the user's symptoms to provide an initial diagnosis
or potential mental health conditions. Treatment Recommendations: Drawing from
evidence-based practices, the chatbot suggests personalized mental health
interventions, including therapy techniques, coping strategies, and lifestyle
adjustments. Dosha Evaluation: If applicable, the chatbot assists the user in
understanding their mental constitution (dosha) through questions about their
emotional state, behaviors, and preferences. It then offers insights into balancing
these aspects and recommends tailored practices or interventions. Psychoeducation:
The chatbot shares information about mental health conditions, treatment options,
and self-care practices to enhance the user's understanding of mental well-being.
Meditation and Mindfulness: Offering guidance on mindfulness exercises and
16
meditation practices, the chatbot helps users cultivate emotional resilience and
manage stress effectively. Lifestyle and Wellness Tips: Providing personalized
advice on lifestyle modifications, the chatbot suggests routines, dietary changes, and
relaxation techniques to support mental wellness. General Mental Health
Knowledge: The chatbot imparts knowledge about mental health principles,
psychological concepts, and holistic approaches to mental well-being. Safety
Information: The chatbot emphasizes the importance of seeking professional help for
mental health concerns and provides resources for accessing emergency assistance if
needed. FAQs and Common Queries: Addressing frequently asked questions, the
chatbot offers guidance on accessing mental health support, managing crises, and
understanding treatment options. Referral and Support: If necessary, the chatbot
directs users to mental health professionals or support services for further evaluation
and assistance. Conclusion: As the conversation concludes, the chatbot expresses
gratitude to the user for engaging and offers any additional support or resources as
needed.
17
5.4. DATA FLOW DIAGRAM:
Fig.5.4. Data flow diagram
5.5. DATABASE DETAILS:
JSON (JavaScript Object Notation) is a lightweight data-interchange
format that is easy for humans to read and write and easy for machines to parse
and generate. It is commonly used for transmitting data between a server and a
web application as an alternative to XML.
Here are some key points to understand about JSON:
Syntax: JSON consists of key-value pairs enclosed in curly braces {}. Each key
is followed by a colon :, and the values can be strings, numbers, booleans,
arrays, or nested JSON objects. Multiple key-value pairs are separated by
commas.
18
EXAMPLE
19
Data Types: JSON supports the following data types:
Strings: Enclosed in double quotes.
Numbers: Integer or floating-point values.
Booleans: True or false.
Arrays: Ordered list of values enclosed in square brackets [].
Objects: Nested JSON objects, represented by key-value pairs enclosed in curly
braces {}.
Nesting: JSON allows nesting objects within objects and arrays within arrays to
represent complex data structures. For example:
Usage: JSON is widely used in web development to exchange data between a
client and a server. It is often used in APIs (Application Programming
Interfaces) to send and receive data in a standardized format.
20
Parsing and Generation: Most programming languages provide built-in
functions or libraries to parse JSON strings into data structures and generate
JSON strings from data structures.
JSON's simplicity and readability make it a popular choice for data interchange,
especially in web-based applications. It's widely supported and easy to work
with in various programming languages, making it an effective means of
transmitting and storing structured data.
5.6. CODE
DESIGN: HTML
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Chatbot</title>
<link rel="stylesheet" href="style.css"> <!-- CSS file link -->
</head>
<body>
<div id="chat-container">
<div id="chat-box"></div>
<input type="text" id="user-input" placeholder="Type here...">
<button id="send-btn">Send</button>
</div>
<script src="javascript.js"></script> <!-- JavaScript file link -->
</body>
</html>
21
STYLE.CSS
/* styles.css */
#chat-container {
width: 600px;
position:
relative; margin:
auto; padding:
20px;
border: 1px solid
#ccc; border-radius:
5px;
}
#chat-box {
background:(mh\ pic.jpeg) ;
height: 200px;
overflow-y: scroll;
border: 1px solid
#ddd; margin-bottom:
10px; padding: 10px;
}
#user-input {
width: calc(100% -
70px); margin-right:
10px; padding: 5px;
border-radius: 3px;
border: 1px solid
#ddd;
}
#send-btn {
padding: 5px 10px;
border: none;
border-radius:
3px;
background-color: #007bff;
color: #fff;
cursor: pointer;
}
22
JAVASCRIPT
// script.js
document.addEventListener('DOMContentLoaded', function() {
const chatBox = document.getElementById('chat-box');
const userInput = document.getElementById('user-input');
const sendBtn = document.getElementById('send-btn');
// Function to display message in chat box
function showMessage(message) {
const messageDiv = document.createElement('div');
messageDiv.textContent = message;
chatBox.appendChild(messageDiv);
}
// Function to fetch responses from JSON file
async function fetchResponses() {
try {
const response = await fetch('responses.json');
const data = await response.json();
return data.responses;
} catch (error) {
console.error('Error loading JSON file:', error);
return {};
}
}
// Event listener for send button click
sendBtn.addEventListener('click', async function() {
const userMessage = userInput.value;
showMessage('You: ' + userMessage); // Display user message
userInput.value = ''; // Clear user input field
const responses = await fetchResponses(); // Fetch responses from JSON
file
let botResponse = responses[userMessage] || responses['']; // Get bot
response
showMessage('Bot: ' + botResponse); // Display bot response
});
});
23
# Create model - 3 layers. First layer 128 neurons, second layer 64 neurons and
3rd output layer contains number of neurons
# equal to number of intents to predict output intent with softmax
model = Sequential()
model.add(Dense(128, input_shape=(len(train_x[0]),), activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(64, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(len(train_y[0]),
activation='softmax'))
# Compile model. Stochastic gradient descent with Nesterov accelerated
gradient gives good results for this model
sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='categorical_crossentropy',
optimizer=sgd, metrics=['accuracy'])
# fitting and saving the model
hist = model.fit(np.array(train_x), np.array(train_y),
epochs=200, batch_size=5, verbose=1)
model.save('model.h5', hist)
print("Yup! The model is created")
app.py
24
def bow(sentence, words, show_details=True):
# tokenize the pattern
sentence_words = clean_up_sentence(sentence)
# bag of words - matrix of N words, vocabulary rix
bag = [0]*len(words)
for s in sentence_words:
for i, w in enumerate(words):
if w == s:
# assign 1 if current word is in the vocabulary position
bag[i] = 1
if show_details:
print("found in bag: %s" % w)
return(np.array(bag))
def predict_class(sentence, model):
# filter out predictions below a threshold
p = bow(sentence, words, show_details=False)
res = model.predict(np.array([p]))[0]
ERROR_THRESHOLD = 0.25
results = [[i, r] for i, r in enumerate(res) if r > ERROR_THRESHOLD]
# sort by strength of probability
results.sort(key=lambda x: x[1], reverse=True)
return_list = []
for r in results:
return_list.append({"intent": classes[r[0]], "probability":
str(r[1])}) return return_list
def getResponse(ints, intents_json):
tag = ints[0]['intent']
list_of_intents = intents_json['intents']
for i in list_of_intents:
if(i['tag'] == tag):
result = random.choice(i['responses'])
breadef chatbot_response(msg):
ints = predict_class(msg, model)
res = getResponse(ints, intents)
26
CHAPTER-6
SYSTEM IMPLEMENTATION
● Mental HealthBot is an intelligent chatbot designed to
provide personalized recommendations on Mental Health
wellness practices.
● With Mental HealthBot, you can access the benefits of
Mental Health from the comfort of your own home, 24/7.
● It is built using cutting-edge technologies such as Flask,
NLTK, Keras, Python, and others.
● Mental HealthBot uses natural language processing (NLP) to
understand and interpret user input, allowing it to provide
customized guidance to users.
● Mental HealthBot's user-friendly interface makes it easy to
interact with user experience.
● Technologies used - Flask, NLTK, Keras, and Python
6.1. About Chatbot
In my Python web-based project, I have created a Mental HealthBot(chatbot)
that employs advanced deep learning and Flask techniques. The Mental
HealthBot(chatbot) is trained on a comprehensive dataset comprising categories
(intents), patterns, and corresponding responses. To classify the user's message
into the appropriate category, I have implemented a sophisticated artificial
neural network (ANN). Once the message is categorized, the Mental
HealthBot(chatbot) selects a random response from the list of possible
responses for that category. This approach ensures that the Mental
HealthBot(chatbot) can effectively engage with users and respond appropriately
to their queries.
6.2. THE DATASET
The dataset that I have utilize in my Mental HealthBot(chatbot) is stored
in a JSON file named 'data.json'. This JSON file contains a comprehensive list
of patterns that the chatbot will identify, and their corresponding responses that
will be returned to the user. By leveraging the data stored in 'data.json', our
chatbot will be able to engage with users effectively and provide relevant
responses based on their queries.
6.2.1 Prerequisites:
To undertake this project, it is essential to possess a solid understanding
of Python programming, Keras deep learning framework, and Natural
Language Processing (NLP) concepts. Additionally, I have employed several
helper
27
modules, which can be downloaded using the python-pip command. To install
these dependencies, execute the following commands:
pip install
tensorflow
pip install
keras
pip install pickle
pip install nltk
pip install
flask
These modules are crucial to the chatbot's functionality and enable us to
streamline the development process, achieve optimal performance, and create a
highly responsive and effective chatbot that can interact with users seamlessly.
6.3 DEMONSTRATION OF MY PROJECT
Building the model
- I have developed a deep neural network consisting of three layers using the
Keras sequential API. After training the model for 200 epochs, it has achieved
an outstanding accuracy rate of 100%. The model has been saved as 'model.h5'
for future use, allowing the Mental HealthBot(chatbot) to accurately classify
user messages and provide relevant responses, resulting in a highly responsive
and effective user engagement solution.
The training of the Mental Healthchatbot is captured and figured out as below:
28
Fig.6.3.1.Training data
29
Fig.6.3.2.Training data
Fig.6.3.3.Training data
29
CHAPTER-7
SYSTEM TESTNG
System testing is an important phase in the development process of an
Mental Health chatbot. It involves testing the overall functionality,
performance, and reliability of the chatbot to ensure that it meets the desired
requirements. Here are some key aspects to consider during the system testing
of an Mental Health chatbot:
Functional Testing:
Test the chatbot's basic functionalities such as greeting, user registration,
symptom analysis, diagnosis, treatment recommendations, dosha assessment,
herbal medicine information, yoga and meditation guidance, lifestyle and
dietary advice, etc.
Verify that the chatbot provides accurate and relevant responses based on the
user's inputs and the provided information.
Test different scenarios and edge cases to ensure the chatbot handles various
user inputs and scenarios correctly.
Validate the chatbot's ability to handle interruptions, errors, and unexpected
inputs gracefully.
Performance Testing:
Evaluate the chatbot's response time and ensure that it provides quick and
efficient responses to user queries.
Test the chatbot's ability to handle multiple user interactions simultaneously
without experiencing significant delays or performance issues.
Validate the chatbot's performance under peak load conditions to ensure it can
handle a high volume of user interactions without degradation.
30
Fig.7.1.1 Testing
modulo Language and Input Testing:
Test the chatbot's language processing capabilities to ensure it can understand
and interpret user inputs accurately, especially when dealing with different
dialects, accents, or variations in language usage.
Verify that the chatbot can handle various types of input formats, including
text, voice, and multimedia inputs.
Compatibility Testing:
Test the chatbot's compatibility with different web browsers, devices, and
operating systems to ensure a consistent user experience across various
platforms. Verify that the chatbot's user interface is responsive, intuitive, and
compatible with different screen sizes and resolutions.
31
Fig.7.1.2.Testing modulo
Security and Privacy Testing:
Validate the chatbot's security measures to protect user data, ensuring that
sensitive information is handled securely and is not accessible to unauthorized
individuals.
Test the chatbot's compliance with privacy regulations and standards, such as
GDPR or HIPAA, depending on the jurisdiction and purpose of the chatbot.
Error Handling and Recovery Testing:
Test the chatbot's ability to handle and recover from errors, such as incorrect
inputs or system failures, providing meaningful error messages and appropriate
guidance to the user.
Integration Testing:
If the chatbot integrates with external systems or APIs to fetch data or provide
additional functionalities, test the integration points to ensure seamless
communication and proper functioning.
User Acceptance Testing:
Involve a group of end-users or representatives to perform user acceptance
testing, gathering feedback and insights to evaluate the chatbot's usability,
effectiveness, and user satisfaction.
32
Documentation and Training:
Ensure that the chatbot's documentation, user guides, and training materials
are accurate, comprehensive, and easily accessible to users and administrators.
By conducting thorough system testing, you can identify and address any issues
or deficiencies in the Mental Health chatbot, ensuring a robust and reliable user
experience.
Frontend testing:
33
app.py
34
Chapter- 8
RESULT
Fig.8.1.Mental Health bot
Fig.8.2.Mental Health bot remedies
35
Fig.8.3.Mental Health bot greetings
Fig.8.4.Mental Health bot remedies
36
Fig.8.5.Mental Health bot remedies
37
CHAPTER-9
CONCLUSION AND FUTURE WORK
9.1 CONCLUSION
A Chatbot is a great tool for conversation. Here the application is developed to
provide quality of answers in a short period of time. It removes the burden from
the answer provider by directly delivering the answer to the user using an expert
system. The project is developed for the user to save the user their time in
consulting the doctors or experts for the MENTAL HEALTH solution. Here we
developed the application using the N-gram, TF- IDF for extracting the
keyword from the user query. Each keyword is weighed down to obtain the
proper answer for the query. The Web interface is developed for the users, to
the input query. The application is improved with the security and effectiveness
upgrades by ensuring user protection and characters and retrieving answers
consequently for the questions.
9.2. FUTURE WORK:
In the future, there are several potential areas of improvement and
development for an Mental Health chatbot. Here are some suggestions for
future work:
Enhanced Personalization: Mental Health is highly individualized, considering
a person's unique constitution (dosha) and specific health concerns. An
advanced chatbot can be designed to collect and analyze user data to provide
more personalized recommendations and treatment plans.
Integration with Wearable Devices: With the increasing popularity of wearable
health devices, such as fitness trackers and smartwatches, an Mental Health
chatbot could integrate with these devices to gather real-time data on a user's
health parameters. This data can be utilized to offer tailored advice and track
progress.
Herbal and Medicinal Recommendations: Mental Health relies heavily on
herbal remedies and medicinal plants. A chatbot can provide information about
various herbs, their benefits, and usage instructions. It can also suggest specific
herbal remedies based on the user's symptoms or health conditions.
Lifestyle and Dietary Guidance: Mental Health emphasizes the importance of a
balanced lifestyle, including diet, exercise, and daily routines. A chatbot can
38
offer personalized lifestyle and dietary recommendations based on a user's
dosha, health goals, and preferences. It can suggest suitable Mental Health
recipes, meal plans, and exercise routines.
Mental Health Support: Mental Health recognizes the mind-body connection
and addresses mental well-being. An Mental Health chatbot can provide
guidance and support for managing stress, anxiety, and other mental health
issues. It can offer meditation techniques, breathing exercises, and lifestyle
modifications to promote mental wellness.
Natural Remedies for Common Ailments: Mental Health offers natural
remedies for a wide range of common ailments. The chatbot can provide
information on Mental Health treatments for conditions like cold and flu,
digestive disorders, skin problems, and allergies. It can suggest home remedies,
herbal formulations, and self-care practices.
Integration with Telemedicine: Integrating the Mental Health chatbot with
telemedicine platforms can allow users to consult with Mental Health
practitioners remotely. The chatbot can assist in gathering relevant information,
scheduling appointments, and providing follow-up care recommendations.
39
REFERENCES
[1] Oh,D.Lee.B.KoandH.Choi, "A chatbot for Psychiatric Counseling in
Mental MENTAL HEALTH Service Based on Emotional Dialogue Analysis
and Sentence Generation,“ 201718th IEEE International Conference on Mobile
Data Management(MDM), Daejeon,2017,pp.371-375.
doi:10.1109/MDM.2017.64
[2]Du Preez.S.J. & Lall, Manoj & Sinha, S. (2009). An intelligent web-based
voice chatbot.386- 391.10.1109/
[3]Bayu Seti6.aji, Ferry Wahyu Wibowo, "Chatbot Using a Knowledge in
Database: Human- toMachine Conversation Modeling", Intelligent Systems
Modelling and Simulation (ISMS) 2016 7th International Conference on,pp.72-
77,2016
[4]Dahiya.Menal.(2017).A Tool of Conversation:Chatbot. INTERNATIONAL
JOURNAL OF COMPUTER SCIENCES AND ENGINEERING.5.158-
161.2017.
[5] C.P. Shabariram, V. Srinath, C.S. Indhuja, Vidhya (2017).
Ratatta:Chatbot Application Using Expert System, International Journal of
Advanced Research in Computer Science and Software Engineering,2017
[6] Mrs Rashmi Dharwadkar1, Dr.Mrs. Neeta A.
Deshpande, A Medical ChatBot, International Journal of
Computer Trends and Technology (IJCTT) – Volume 60 Issue
1- June 2018
[7] Farheen Naaz, Farheen Siddiqui, modified n-gram based model for
identifying and filtering near-duplicate documents detection, International
Journal of Advanced Computational Engineering and Networking, ISSN: 2320-
2106, Volume-5, Issue-10, Oct.-2017
[8] N-gram Accuracy Analysis in the Method of Chatbot
Response,International Journal of Engineering & Technology. (2018)
[9] Shukla, V.K, Verma, A, "Enhancing LMS Experience through AIML
Base and Retrieval Base Chatbot using R Language", 2019 International
Conference on Automation, Computational and Technology Management
(ICACTM)
[10] Al`es, Z., Duplessis, G.D., S¸erban, O., Pauchet, A.: A methodology to
design human-like embodied conversational agents. In: International Workshop
on Human-Agent Interaction Design and Models (HAIDM 12). Valencia,
Spain(2012)
40
[11] Anderson, J.R., Boyle, C.F., Reiser, B.J.: Intelligent tutoringsystems.
Science228(4698),456–462(1985).
[12] Angeli, A.D., Johnson, G.I., Coventry, L.: The unfriendlyuser: Exploring
social reactions to chatterbots. In Proceedings of International Conference on
AffectiveHuman Factor Design. pp. 467–474. Asean Academic Press (2001).
[13] Dutta, D.: Developing an intelligent chat-bot tool to assist high school
students forlearning general knowledge subjects.Tech. rep., Georgia Institute of
Technology (2017).
[14] Goel, A.K., Polepeddi, L.: Jill Watson: A Virtual Teaching Assistant for
Online Education. Tech. rep., Georgia Institute of Technology (2016).
[15] M. J. Pereira, L. Coheur, P. Fialho, and R. Ribeiro, “Chatbots’ greeting to
human-computer communication,”arXiv preprint arXiv:1609.06479,2016.
[16] O. Deryugina, “Chatterbots,” Scientific and Technical Information
Processing, vol. 37, no. 2, pp. 143–147, 2010.
[17] J. S. Malik, P. Goyal, and A. K. Sharma, “A comprehensive approach
towards data preprocessing techniques & association rules,” in Proceedings of
The4th National Conference, 2010.
[18] B. A. Shawar and E. Atwell, “Chatbots: are they reallyuseful?” in
LDVForum, vol. 22, no. 1, 2007, pp. 29–49.
[19]. A. Bordes, S. Chopra, and J. Weston, “Question answering with subgraph
embeddings,” arXiv preprint arXiv:1406.3676.
[20] Jason Williams, Antoine Raux,Deepak Ramachandran, and Alan
Black. The dialog state tracking challenge. In SIGDIAL’13, pages 404–413,
2014
41
PUBLICATION
42
PUBLICATION
43