48 75 Dsa Report

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 11

MENTAL HEALTH CHATBOT

A MINI PROJECT REPORT

NAAN MUDHALVAN – CHATGPT

Submitted by

ADITYA TARUN S (2020506007)

ASHWIN A (2020506016)

SAI SHARAN L (2020506075)

DEPARTMENT OF INFORMATION TECHNOLOGY

MADRAS INSTITUTE OF TECHNOLOGY CAMPUS

ANNA UNIVERSITY : CHENNAI 600 044

1|Page
MENTAL HEALTH CHATBOT

AIM:
To create a Chatbot that deals and gives solutions to mental health of
human beings.

PROJECT DESCRIPTION:

Our Mental Health Chatbot project aims to provide accessible and


confidential mental health support through an intelligent conversational
agent. Leveraging natural language processing and deep learning
technologies, the chatbot can understand and respond to user input, offering
empathetic and informative guidance. Trained on a diverse dataset, the bot
recognizes various user intents related to mental health concerns, such as
stress, anxiety, and loneliness. Users can interact with the chatbot via a user-
friendly web interface, allowing for real-time conversation and support. The
model's predictions are based on a pre-trained neural network, while
responses are drawn from a curated set of therapeutic and informative
content. With a focus on user privacy, the chatbot provides a safe space for
individuals to discuss their feelings, receive valuable resources, and access
suggestions for coping strategies, fostering mental well-being in a
technologically driven and accessible manner.

2|Page
Motivation:
The motivation behind our Mental Health Chatbot project stems from
the critical need for accessible and immediate mental health support. Mental
health challenges are widespread, and many individuals hesitate to seek help
due to stigma, lack of resources, or concerns about privacy. This chatbot
serves as a proactive solution, providing a discreet and non-judgmental
platform for users to express their feelings and receive timely assistance.

By integrating natural language processing and deep learning, our chatbot can
understand and respond empathetically to a variety of mental health concerns.
The goal is to bridge the gap between individuals in need and professional
support by offering informative content, coping strategies, and resources. The
user-friendly web interface ensures easy accessibility, catering to a diverse
audience.

Ultimately, our project is motivated by a commitment to destigmatize mental


health conversations, increase awareness, and provide immediate support to
those who may be struggling, contributing to a more compassionate and
technologically enhanced approach to mental well-being.

SYSTEM REQUIREMENTS:

To deploy and run the Mental Health Chatbot project, you need to ensure that
your system meets the following requirements:

1. Hardware:
 A computer with sufficient processing power to handle the chatbot's
inference tasks.
 Recommended: A machine with a GPU (Graphics Processing Unit) for
faster deep learning model inference.

2. Software:
 Python: Ensure that you have Python installed (version 3.x).
3|Page
 Dependencies: Install the required Python libraries by running:
“pip install nltk keras flask”

 NLTK Data: Download NLTK data packages by running the following


code once:
“import nltk
nltk.download('popular')”

3. Project Files:
 Obtain the pre-trained model file (`model.h5`), word data (`texts.pkl`),
label data (`labels.pkl`), and intents data (`intents.json`).
 Ensure the availability of the HTML template (`index.html`) for the
web interface.

4. Web Server:
 Install Flask for the web server:
“pip install Flask”

5. Internet Connection:
 A stable internet connection is required to download NLTK data
packages and for the Flask application to run.

6. GPU Support (Optional):


 If you have a GPU, consider installing GPU-supported versions of
libraries like TensorFlow to accelerate deep learning model inference.

7. Operating System:
 The code is platform-independent, and it should work on major
operating systems such as Windows, macOS, and Linux.

Ensure that you have fulfilled these system requirements before attempting to
run the Mental Health Chatbot project. Additionally, if you plan to deploy the
chatbot as a web application, make sure that the required ports are accessible.
ALGORITHMS USED:
4|Page
The chatbot is integrated into a Flask web application to provide a user
interface. Here's a breakdown of the code:

1. Libraries:

 nltk: Natural Language Toolkit for natural language processing.


 WordNetLemmatizer: Used for lemmatization.
 pickle: Used for serializing and deserializing Python objects.
 numpy: Library for numerical operations.
 keras.models: Used for loading the neural network model.
 json: Used for working with JSON data.
 random: Used for generating random responses.
 Flask: Web framework for building the application.

2. Loading Model and Data:

 The Keras model (model.h5) is loaded using load_model.


 The intents, words, and classes are loaded from JSON and pickle files.

3. Text Processing Functions:

 clean_up_sentence: Tokenizes and lemmatizes input sentences.


 bow: Converts a sentence into a bag of words representation.
 predict_class: Predicts the intent of a sentence using the loaded model.

4. Response Handling Functions:

 getResponse: Retrieves a random response for a given intent.


5|Page
 chatbot_response: Combines the prediction and response functions to
provide a response for user input.

5. Run the Application:

 The Flask app is run when the script is executed.


 Make sure you have the required dependencies installed (nltk, numpy,
keras, Flask) before running the code. Also, ensure that the necessary
model and data files (model.h5, intents.json, texts.pkl, labels.pkl) are
available in the correct locations.

SOURCE CODE:

import nltk
nltk.download('popular')
from nltk.stem import WordNetLemmatizer
lemmatizer = WordNetLemmatizer()
import pickle
import numpy as np
from keras.models import load_model
model = load_model('model.h5')
import json
import random
intents = json.loads(open('intents.json').read())
words = pickle.load(open('texts.pkl','rb'))
classes = pickle.load(open('labels.pkl','rb'))
def clean_up_sentence(sentence):
# tokenize the pattern - split words into array
sentence_words = nltk.word_tokenize(sentence)
# stem each word - create short form for word
sentence_words = [lemmatizer.lemmatize(word.lower()) for word in
sentence_words]
return sentence_words
6|Page
# return bag of words array: 0 or 1 for each word in the bag that exists in the
sentence
def bow(sentence, words, show_details=True):
# tokenize the pattern
sentence_words = clean_up_sentence(sentence)
# bag of words - matrix of N words, vocabulary matrix
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'])
break
return result
7|Page
def chatbot_response(msg):
ints = predict_class(msg, model)
res = getResponse(ints, intents)
return res
from flask import Flask, render_template, request
app = Flask(__name__)
app.static_folder = 'static'
@app.route("/")
def home():
return render_template("index.html")
@app.route("/get")
def get_bot_response():
userText = request.args.get('msg')
return chatbot_response(userText)
if __name__ == "__main__":
app.run()

OUTPUTS(Screenshots):

8|Page
FUTURE WORKS:

The Mental Health Chatbot project lays the foundation for future
enhancements and expansions to further improve its impact and capabilities.
Some potential future works include:

1. Enhanced Natural Language Processing (NLP):


- Continuously improve the chatbot's understanding of nuanced language
and context by integrating state-of-the-art NLP models and techniques.

2. Personalization and User Profiles:


- Implement user profiles to enable the chatbot to provide more personalized
support based on historical interactions and individual preferences.

3. Integration with Mental Health Professionals:


- Explore partnerships with mental health professionals to integrate the
chatbot into therapeutic interventions, allowing for a more comprehensive and
collaborative approach to mental health care.

9|Page
4. Multi-modal Interaction:
- Expand the chatbot's capabilities to process and respond to multi-modal
inputs, including images and voice, to enhance user engagement and
understanding.

5. Continuous Learning and Feedback:


- Implement a feedback loop to enable users to provide feedback on the
chatbot's responses, facilitating continuous learning and improvement.

6. Expansion of Mental Health Topics:


- Incorporate a broader range of mental health topics, interventions, and
resources to address a more comprehensive spectrum of mental health
challenges.

7. Integration with Wearable Devices:


- Connect the chatbot to wearable devices to gather additional user data for a
more holistic understanding of the user's well-being.

8. Language Support:
- Extend language support to make the chatbot accessible to a more diverse
user base by incorporating additional languages.

9. Research Collaboration:
- Collaborate with mental health researchers to validate and enhance the
effectiveness of the chatbot in supporting mental health and well-being.

10. Ethical Considerations:


- Conduct ongoing assessments of ethical considerations, privacy concerns,
and potential biases to ensure responsible and inclusive use of the chatbot in
diverse communities.

By focusing on these future works, the Mental Health Chatbot can evolve into
a more advanced and impactful tool, contributing to the well-being of users
and the advancement of technology-driven mental health support.

10 | P a g e
CONCLUSION:

In conclusion, the Mental Health Chatbot project represents a proactive


and innovative step towards addressing the growing need for accessible mental
health support. By leveraging natural language processing and deep learning
technologies, the chatbot offers a confidential and empathetic space for users to
express their concerns, receive informative content, and access coping strategies.

The project's potential positive outcomes include increased accessibility to mental


health resources, de-stigmatization of mental health conversations, and positive
user engagement. The integration of user-friendly web interfaces and continuous
learning mechanisms positions the chatbot as a dynamic tool for fostering mental
well-being.

As we look to the future, ongoing improvements in natural language understanding,


personalization, and collaboration with mental health professionals hold the
promise of making the chatbot an even more effective and impactful resource. By
addressing ethical considerations and staying attuned to user feedback, the Mental
Health Chatbot project has the potential to contribute significantly to the broader
conversation surrounding mental health and technology-driven support systems.

11 | P a g e

You might also like