0% found this document useful (0 votes)
43 views41 pages

Projectfile SunilKaushikAIpoweredStressDetection

informative

Uploaded by

nehatabassum4237
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)
43 views41 pages

Projectfile SunilKaushikAIpoweredStressDetection

informative

Uploaded by

nehatabassum4237
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/ 41

See discussions, stats, and author profiles for this publication at: https://www.researchgate.

net/publication/380635769

AI-powered Stress Detection

Conference Paper · December 2023

CITATIONS READS
0 20

1 author:

Sunil Kaushik
Faridabad College of Engineering, Faridabad
5 PUBLICATIONS 0 CITATIONS

SEE PROFILE

All content following this page was uploaded by Sunil Kaushik on 17 May 2024.

The user has requested enhancement of the downloaded file.


AI-powered Stress Detection

Project Report

SUBMITTED IN PARTIAL FULFILLMENT FOR THE REQUIREMENT OF THE


AWARD OF DEGREE OF

MASTER OF TECHNOLOGY
(Computer Science & Engineering)

Submitted by
SUNIL KAUSHIK
University Reg No. 2211141050
Student No. 621339

Supervised by
MR. Kishore Ajay
Designation
Head of Department, CSE

December 2023

Faridabad College of Engineering and Management, Faridabad

Affiliated to :

Page | 1
Faridabad College of Engineering and Management, Faridabad

CANDIDATE'S DECLARATION
I hereby certify that the work which is being presented in the thesis entitled “AI-powered Stress
Detection” in partial fulfillment of requirements for the award of degree of M.Tech. (Computer Science
& Engineering) submitted in the Computer Science & Engineering Department of Faridabad College of
Engineering and Management, Faridabad, is an authentic record of my own work carried out during a
period from ______ to _______ under the supervision of Mr. Kishore Ajay. The matter presented in this
thesis has not been submitted by me in any other University / Institute for the award of Degree.

Signature of the Student


(SUNIL KAUSHIK)

This is to certify that the above statement made by the candidate is correct to the best of my/our
knowledge.

Signature of the Supervisor


(Mr. Kishor Ajay)

The M.Tech. Viva –Voce Examination of (SUNIL KAUSHIK) has been held on ____________ and
accepted.

Signature of Supervisor Signature of Dy. Dean


(NAME) (NAME)

Signature of Dean of College Signature of External Examiner

Page | 2
Sr. No. Content Page No.

Front Page
1. 1
[Topic name, College name and University name]

2. Declaration 2

3. Content 3

4. Certificate of College 4

5. Acknowledgement 5

6. Abstract 6

7. Description 9

8. Algorithm 17

9. Code 18

10. Integration with Google id 33

11. Output 35

12. Application 37

13. Conclusion 39

14. References 40

Page | 3
Faridabad College of Engineering and Management, Faridabad

CERTIFICATE

This is to certify that Sunil Kaushik University Reg. No. 2211141050, Student No. 621339 has

successfully completed the requirements and submitted the project titled “AI-powered Stress

Detection” in partial fulfilment of the requirements for the degree of Master of Technology

(M.Tech) in Computer Science and Engineering.

The project work was carried out under the guidance of Mr. Kishore Ajay, Head of Department,

Computer Science and Engineering; Faridabad College of Engineering and Management

Affiliated to Maharishi Dayanand University, Rohtak(Haryana).

Date of Submission: ________

_______________________

Mr. Kishore Ajay,


Head of Department, CSE
Faridabad College of Engineering and Management
Affiliated to Maharishi Dayanand University

Page | 4
Declaration

I, Sunil Kaushik, hereby declare that the project entitled “AI-powered Stress
Detection” is a result of my original work and has not been submitted for the award
of any other degree or diploma, either in this university or any other institution.
Any sources of information, including but not limited to text, figures, or ideas, have
been duly acknowledged and referenced. Any contribution from other individuals
or sources has been appropriately credited and cited.

I take full responsibility for any infringement of copyright laws that might arise
from the use of third-party materials in this project.
This project work represents my understanding and knowledge acquired during
the course of my M. Tech program and reflects my own thoughts, except where
specifically acknowledged.

Date:

Place: Faridabad

Signature:
(Sunil Kaushik)

Page | 5
Acknowledgement

I would like to express my deepest gratitude and appreciation to Mr. Kishore Ajay,
my project supervisor and HOD of CSE for their invaluable guidance, constant
support, and insightful feedback throughout the duration of this project. Their
expertise and encouragement were instrumental in shaping this work.

I am thankful to the faculty members of the Computer Science and Engineering


for their valuable suggestions and support during the course of this project. I
extend my heartfelt thanks to my parents/family for their unwavering
encouragement, understanding, and patience during this academic pursuit.

Special thanks to all teachers and management of F.C.E.M College for their
assistance, technical support, and resources that have contributed to the
successful completion of this project.

Lastly, I am grateful to all those who, directly or indirectly, have contributed to


this project.

[Sunil Kaushik]

Page | 6
Abstract

Title: Artificial Intelligence-Based Stress Detection

This project aims to develop an innovative approach for stress detection utilizing Artificial
Intelligence (AI) techniques. Stress, a prevalent mental health concern, often goes unnoticed
due to its subjective nature. Traditional methods of assessment lack real-time monitoring and
are reliant on self-reporting, which can be unreliable.

The proposed system integrates AI algorithms with physiological and behavioral data
acquisition to accurately detect and assess stress levels. Techniques such as machine
learning, specifically neural networks and pattern recognition, are employed to analyze data
streams from various sources, including heart rate monitors, facial recognition, voice
modulation, and activity tracking devices.

Through extensive data collection and analysis, the AI model is trained to recognize patterns
and indicators of stress. The system's adaptability allows for personalized stress identification
based on individual biometric and behavioural markers.

Preliminary results demonstrate promising accuracy in stress detection, showcasing the


potential for early intervention and personalized stress management strategies. This project's
significance lies in its potential to revolutionize stress assessment and intervention through AI-
driven, real-time monitoring, thereby contributing to improved mental health outcomes. This
project aims to develop an AI-driven system for monitoring and analyzing user stress levels
using data from Google activity and other installed apps. By combining personal usage patterns
with advanced stress detection algorithms, the system will provide insights into individual stress
triggers and suggest personalized coping mechanisms.

In the world of evolution we are working with artificial intelligence; But on the other hand we
are also suffering from natural stupidity. – Sunil Kaushik

Introduction: This project is based on the fact that there are people who tends to be depressed
and overburden to avoid the tasks. This project will show the accurate stress level and mental
health which will help in:

 Performance analysis of employees


 Effective task assignment

Page | 7
 Task distribution
 Suggesting health related products for anxiety and stress
 Providing data for analysis for work-life balance
 Enhancing office/workplace environment

Data Acquisition and Processing:

 Google Data: Utilize Google Fit APIs to access sleep patterns, physical activity
levels, and location history. Analyze search queries, Gmail communication, and
calendar entries for emotional patterns and stressful events.

 App Usage Data: Integrate with popular productivity, social media, and entertainment
apps to track usage duration and patterns. Use sentiment analysis on app interactions
to identify potential stress indicators.

Stress Detection Model:

 Develop a machine learning model based on Recurrent Neural Networks (RNNs) or


Long Short-Term Memory (LSTM) networks to analyze temporal patterns in user
data. Train the model on labeled data from stress assessment surveys and
physiological sensors (optional).

 Apply Natural Language Processing (NLP) techniques to analyze text data from
Google searches, emails, and chats for stress-related keywords and sentiment.

Personalization and Feedback:

 Create user profiles based on demographics, health information, and past stress
patterns. This allows for personalized stress triggers identification and tailored coping
mechanisms.

 Implement real-time monitoring and provide early warning signals when stress levels
reach critical thresholds. Offer personalized coping suggestions including mindfulness
exercises, breathing techniques, or recommendations for relaxation activities based on
app usage patterns.

Page | 8
Potential Applications:

 Personal stress management: Empower individuals to proactively manage their stress


levels by understanding their unique triggers and developing coping strategies.

 Workplace wellness: Integrate with enterprise platforms to create anonymous stress


maps and identify high-stress teams or periods. Offer targeted interventions and
promote a healthier work environment.

 Mental health support: Provide early detection of potential mental health issues based
on chronic stress patterns and offer resources for professional help.

Ethical Considerations:

 User privacy and data security are paramount. Ensure user consent and implement
robust data anonymization and encryption techniques.

 Address potential biases in the model by using diverse training data and incorporating
fairness metrics.

 Avoid medical diagnosis or offering therapy, focus on stress management and


providing resources for professional help.

Description:

The major goal of this study is to use vivid Machine Learning and Image Processing
methods to identify stress in the human body. Our system is an upgraded version of
previous stress detection systems that did not include live detection or personal counselling,
but this system includes live detection and periodic analysis of employees, as well as
detecting physical and mental stress levels in them and providing proper stress
management remedies via a survey form. Our method is primarily focused on stress
management and creating a healthy and spontaneous work environment for workers in
order to get the most out of them during working Hours.

Keywords— Facial Expressions, KNearest Neighbor Classifier, Stress,Stress prediction,


Artificial Intelligence, Stress Detection, Machine Learning, Biometric Data, Behavioral
Analysis

Stress management systems are necessary for detecting stress levels that affect our socio-
economic situation. According to the World Health Organization, stress is a mental health

Page | 9
disorder that affects one out of every four people (WHO). Mental and financial troubles, as
well as a lack of clarity at work, bad working relationships, despair, and, in extreme
situations, death, are all symptoms of human stress. This necessitates the provision of
therapy to help stressed people manage their stress. While it is impossible to totally
eliminate stress, taking preventative measures may help you cope. Only medical and
physiological peoples can now determine whether or not someone is depressor (stressed).
A questionnaire is one of the most used methods for detect- ing stress. This technique relies
primarily on individual responses; people will be hesitant to communicate whether or not
they are worried. Automatically detecting stress lowers the likelihood of health problems
and improves society's well-being. This involves the creation of a scientific approach for
assessing stress levels in people using physiological markers. Since stress is such a signifi-
cant societal contribution, a variety of approaches for detecting it have been investigated.
It enhances people's quality of life, according to Ghaderi Tal. Stress was assessed using
data from respira- tion, heart rate (HR), face electromyography (EMG), Galvanic skin
response (GSR) foot, and GSR hand, with the finding that parameters related to the
respiratory process are critical in stress detection. Maria Viqueira et al. present a method
for anticipating mental stress that relies only on GSR as a physiological sensor and uses a
standalone stress detecting device. Electrocardiograms alone were utilized by David Liu
and colleagues to predict stress levels (ECG). The effectiveness of multimodal sensors in
detecting stress in working individuals is investigated experimentally. Sensor data from
pressure distribution, heart rate, blood volume pulse (BVP), and electro dermal activity is
used in this investigation (EDA). In addition, an eye tracker sensor is used, which analyses
eye movements in connection with stressors such as the Stroop word test and information
regarding pick-up tasks.
Nowadays, the IT industry is creating a new standard in the market by introducing new
technology and goods. Employee stress levels were also found to set the bar high in this
research. De- spite the fact that many companies pro- vide mental health benefits to their
workers, the problem remains out of control. In this study, we attempt to go further into the
topic by attempting to identify stress patterns in working em- ployees in businesses. We
plan to use image processing and machine learning methods to analyse stress patterns
and narrow down the elements that greatly influence stress levels. Machine learning
approaches such as KNN classifiers are used to categorise stress. The employee's picture
is snapped by the camera, which acts as input, and image processing is employed at the
first step for detection. Picture processing is used to improve an image or extract relevant
Page | 10
information from it by converting the image to digi- tal form and executing operations on it.
By taking a picture from video frames as input and producing an image or attributes related
with that image as output.
Image processing consists of three phases:
• Importing the image using photo capture software
• Analysing and altering the picture
• As a result of the output, a picture that has been modified or a report based on image
analysis.
Machine learning, which is an application of artificial intelligence, gives the system the
capacity to autonomously learn and develop from self-experiences without being explicitly
designed (Artificial Intelligence). Machine Learning creates computer programs that can ac-
cess data and utilize it to learn for them- selves. Explicit programming produces a
mathematical model based on "training data" to accomplish the work based on predictions
or judgments using Machine Learning. Image mining is a technique for extracting hidden
data, associating picture data, and discovering new patterns not visible in the image. This
category includes image processing, data mining, machine learning, and datasets.
According to conservative estimates in medical literature, stress is the cause of 50-80
percent of all physical diseases. Stress is regarded to be the major cause of cardiovascular
disease. Stress is associated to diabetes, ulcers, asthma, migraine headaches, skin issues,
epilepsy, and sexual dysfunction. Each of these conditions, as well as a slew of others, has
a psychosomatic basis (i.e., induced or exacerbated by mental factors like stress). There
are three impacts of stress:
• Guilt, humiliation, anxiety, anger, and frustration are some of the subjective symptoms
of stress. Individuals may also experience fatigue, tenseness, nervousness, irritability,
moodiness, or loneliness.
• Behavioural impacts of stress indicate visible changes in a person's behaviour.
Increased accidents, drug or alcohol usage, out-of-context laughing, outra- geous or
argumentative behaviour, extremely excitable moods, and/or excessive eating or drinking
are all signs of behavioural stress.
• Cognitive stress may cause a decline in mental capacity, poor judgment, impulsive
choices, forgetfulness, and/or hypersensitivity to criticism.

1.1 LITERATURE SURVEY


1. Detecting stress and anxiety in films using facial clues
Page | 11
AUTHORS: G. Giannakakis, D. Manousos, F. Chiarugi
Through video-recorded face clues, this research creates a framework for detecting and
analyzing stress/anxiety emotional states. Through a range of external and internal
stresses, a complete experimental methodology was designed to produce systematic
diversity in emotional states (neutral, calm, and stressed/anxious). In order to measure
emotion expression more objectively, the study focused mostly on non-voluntary and semi-
voluntary facial signals. Eye-related events, mouth activity, head motion characteristics,
and heart rate assessed via camera-based photo-plethysmography were also investigated.
In each experimental phase, a feature selection technique was used to pick the most robust
characteristics, followed by classification algorithms that discriminated between
stress/anxiety and neutral states with reference to a relaxed condition. In addition, a ranking
transformation based on self-reports was presented to study the relationship be- tween face
attributes and a participant's reported stress/anxiety level. Specific facial signals generated
from eye, mouth, head, and camera-based cardiac activity acquire excellent accuracy and
are acceptable as discriminative markers of stress and anxiety, according to the findings.

2. Detection of Stress Using Image Pro- cessing and Machine Learning Techniques
AUTHORS: Nisha Raichur, Nidhi Lonakadi, Priyanka Mural
Stress is an uncomfortable state of emotional arousal that individuals feel in settings such
as sitting in front of a computer for lengthy periods of time. Computers have become a way
of life; we spend so much of our time on them that we are more impacted by the ups and
downs they create. One cannot totally avoid using computers for work, but one should at
least limit his or her use if he or she is concerned about being stressed at a certain moment.
Monitoring a person's mental state while working in front of a computer for an extend- ed
period of time is critical for their safety. This research uses real-time non- intrusive movies
to assess a person's emotional state by analyzing their facial expression. Each video frame
contains a distinct feeling, and the stress level is determined in the hours after the video
recording. We use a method that enables us to train a model and compare differ- ences in
feature prediction. Theano is a Python framework aimed at speeding up the execution and
development of the linear regression model, which is employed as a deep learning
technique in this case. The results of the experiments reveal that the devised method works
effectively with a generic model of all ages.

3. Techniques for Predicting Stress in Working Employees Using Machine Learning


Page | 12
AUTHORS: U. S. Reddy, A. V. Thota and A. Dharun
Stress problems are a wide- spread problem among today's working IT professionals.
Employees are more likely to experience stress when their lifestyles and work environments
change. Despite the fact that many sectors and corporations provide mental health-related
programs and attempt to improve the office environment, the problem remains out of
Control. In this research, we will use machine learning approaches to examine stress
patterns in working people and to identify the elements that have a significant impact on
stress levels. Data from the OSMI mental health survey 2017 answers of working
professionals in the IT sector were used to help with this. After proper data cleaning and
pre-processing, we used a variety of Machine Learning approaches to train our model. The
accuracy of the models mentioned above was deter- mined and compared. Among the
models used, boosting had the best accuracy. Gender, family history, and the availability
of health benefits in the job were found as key characteristics that impact stress using
Decision Trees. With these findings, businesses may focus their efforts on reducing stress
and providing a more pleasant working environment for their workers.

4. A sternal ECG is used to classify acute stress using linear and non-linear heart
rate variability analyses.AUTHORS: Tanev, G., Saadi, D.B., Hoppe, K., Sorensen, H.B
The diagnosis of chronic stress is crucial in predicting and lowering the risk of
cardiovascular disease. This project is pilot research with the goal of establishing a
technique for identifying short-term psychophysiological alterations using HRV properties.
The goal of this pilot project is to identify and ac- quire insight into a collection of
characteristics that might be utilized to detect psychophysiological alterations associated
with chronic stress. Images, noises, mental activities, and rest were used to evoke four
distinct forms of arousal, which were then identified using linear and non-linear HRV
characteristics from electrocardiograms (ECG) obtained by the wireless wearable ePatch®
recorder. Sample entropy, detrended fluctuation analysis, and normalized high frequency
features were used to get the greatest identification rates for the neutral stage (90 percent),
acute stress stage (80 per- cent), and baseline stage (80 percent). It was discovered that
standardizing non- linear HRV variables for each partici- pant was a crucial component in
improving classification outcomes.

5. Healthy Office: Using smartphones and wearable sensors, employees may recognize
their moods at work.
Page | 13
AUTHORS: Zenonos, A., Khan, A., Kalogridis, G., Vatsikas, S., Lewis, T., Sooriyabandara
Workplace stress, anxiety, and depression are detrimental to employees' health and
productivity, and they are costly. Sensor technologies, such as smartphones and wearables
with physiological and movement sensors, have been the focus of recent research in this
field. In this paper, we look at the feasibility of deploying such gadgets for mood detection
in the workplace. Every two hours, we propose a new mood detection framework that can
recognize five intensity levels for eight distinct kinds of emotions. We also propose a
smartphone app ('Healthy Office') that is meant to promote formal self-reporting and give
data for our model. In a small- scale user research, we gather wearable sensing data in an
office setting to assess our technology. Our trials have shown encouraging results, enabling
us to accurately distinguish different types of emotions.

2. Project Description
2.1 Problem Statement
Image capturing is automated, so it collects photographs whenever a typical behavior
occurs. The detecting of sys- tem will be fooled. If the picture is dis- torted while being
captured, the system will provide incorrect findings. Contin- ued picture capture results in
massive, useless datasets. Detection will become more time demanding or incorrect as a
result of the auto collected picture datasets.
2.2 Existing System
Work on stress detection in the present system is based on digital signal pro- cessing, which
takes into account of galvanic skin reaction, blood volume, pupil dilation, and skin
temperature. Other research on this topic relies on a variety of physiological signals and
visual aspects (eye closure, head movement) to assess a person's stress levels while they
are at work. These measures, on the other hand, are obtrusive and un- comfortable in
practice. Every sensor reading is compared to a stress index, which is a number that is
used to deter- mine the amount of stress.
Disadvantages of Existing System
• Non-stationary temporal performance commonly pigeon- holes physiological signals for
analysis, and the extracted characteristics explicitly reveal the physiological signals' stress
index
• Different individuals may react or express differently under stress, therefore it is difficult
to discover a uniform pattern to characterize the stress emotion.
• The ECG signal is immediately analysed using the frequently used peak j48 technique.
Page | 14
2.3 Proposed system
To categorize stress, the suggested Sys- tem Machine Learning techniques, such as KNN
classifiers, are used. The employee's picture is provided by the browser, which acts as
input, and Image Processing is employed at the first step for detection. Picture processing
is used to improve an image or extract relevant information from it by converting the image
to digital form and executing operations on it. By taking an image as input and producing
an image or image- related qualities as output. On the rounder box, the emotions are
represent- ed. Angry, Disgusted, Fearful, and Sad are all stress indicators.
Advantages of Proposed System
• The output of image analysis is a transformed image or a report.
• By providing proactive stress management solutions, the Stress Detection System
assists workers in dealing with challenges that cause stress.
• We'll take pictures of staff at regular intervals, and then give them the traditional survey
forms.
2.4 Module Description

The following modules are used in this project:


• User
• Admin
• Data Pre-process
• Machine Learning (K-Nearest Neighbour Classification)
• Here, we will use haarcascade_frontalface_default.xml (classifier)
• User:
The first may be registered by the user. For future contact, he needed a valid user email
and cell phone number while registration. After the user has registered, the customer may
be activated by the administrator. After the customer has been activated by the admin, the
user may log into our system. The user must first provide the system with an image as
input. The image's at- tributes and relevant emotion will be extracted using the Py- thon
package. It is also feasible to recognize many faces in a same picture. The stress level will
be shown by facial expressions such as sadness, anger, and so on. After the picture pro-
cessing is complete, we will begin the live feed. We can also see the face expressions of
many people on the live broad- cast. TensorFlow live stream is more accurate and faster

Page | 15
than tensor flow live stream. After that, we'll import the dataset in order to calculate the KNN
classification accuracy precession scores.
• Admin: With his credentials, the administrator can log in. He may activate the users after
logging in. Only the activated user may access our apps. The admin may dynamically set
the project's training and testing data in the code. In a hidden frame, the admin may see all
of the users' identified results. He can discern the emotions of the photos by clicking a
hyperlink on the screen. The results of the K- nearest neighbor classification discovered
may also be seen by the admin. The spreadsheet with the data. We may extend the dataset
size based on fictitious values by allowing authorized people to do so.

• Data Pre-process: Dataset con- tains a grid view of an existing dataset with numerous
proper- ties; however, Property Extrac- tion produces a newly designed dataset with only
numerical in- put variables as a result of Prin- cipal Component Analysis fea- ture selection,
which transforms to six principal components: Condition (No stress, Time pressure,
Interruption), Stress, Physical Demand, Performance, and Frustration.
• Machine Learning: K-Nearest Neighbour (KNN) is a classifi- cation and regression
analysis algorithm. It's a supervised learning system for determining whether or not a
person need therapy. The dependent variable is classified by KNN based on how similar it
is to a comparable instance from previously col- lected data. KNN A statistical model with
a binary dependent variable is known as classifica- tion. KNN is used to estimate the
parameters of a KNN model in classification analysis. A bi- nary KNN model, mathemati-
cally, contains a dependent vari- able with two potential values, which is represented by an
indi- cator variable, with the two val- ues labelled "0" and "1".
3. Project Design and Analysis
3.1 Architecture

Page | 16
Fig.1 Architecture

Fig. 2 Data Flow Diagram (DFD)

• A bubble chart is another name for a DFD. It is a basic graphical formalism that may be
used to depict a system in terms of the data it receives, the processing it does on that
data, and the data it generates as output.

• The data flow diagram is one of the most important modelling tools (DFD). It's used to
symbolize the numerous parts of the system. These components include the sys- tem
process, the data used by the process, an external entity that interacts with the system,
and the information flows in the system.

• DFD depicts how data flows through the system and is trans- formed by a sequence of
transformations. It's a graphical representation of data flow and the changes that occur
when data goes from in- put to output.

• DFD is sometimes referred to as a bubble chart. At any level of abstraction, a DFD may
be used to depict a system. DFD may be divided into levels, each representing a
different degree of information flow and functional detail.

Algorithm:

1) Start

2) Using a camera, capture the input image/object.

3) If the image/object is clear, it may be used as input, or it can be told to be rechecked.

Page | 17
4) After the input picture has been recognized, it displays the object/stress images in the
form of emotions such as joyful, sad, furious, and so on.

5) Stop

3.2 Input Design

The information system and the users are linked via the input design. It entails defining data
preparation criteria and procedures for turning transaction data into a format that may be used.
Processing may be done in one of two ways: by scanning a computer for data from a written
or printed document, or by having individuals manually enter the data into the system. The
goals of input design are to decrease the quantity of data needed, control mistakes, reduce
delays, remove superfluous steps, and simplify the process. The input is meant to give security
and convenience while maintaining confidentiality. The following aspects were considered by
Input Design:

• What data should be given as input?

• How should the data be organized or coded?

• A conversation to assist operational people in offering feed- back.

• How to prepare input validations and what to do if a mistake occurs.

Objectives of input Design

• The process of translating a user-oriented description of an input into a computer-based


system is known as input design. This design is critical for avoiding data entry mistakes
and directing management in the right way for collecting accurate information from the
computerized system.

• It is accomplished by designing user-friendly data input panels that can manage enormous
amounts of data. The purpose of input design is to make data entering simpler and error-
free. The data entering panel is set up in such a manner that you may execute all of the
data manipulations. It also allows you to see your records.

• It will validate the data after it has been input. Screens may be used as v input information.
Appropriate messages are sent when required, ensuring that the user is never caught off
guard. As a result, the goal of input de- sign is to produce an easy-to- follow input layout.

Page | 18
3.3 Output Design

A quality output is one that satisfies the end user's needs and shows information clearly. Any
system's processing results are conveyed to users and other systems through outputs. In
output design, it's decided how information will be dis- placed for immediate use, as well as the
format. Hard copy output. It is the most important and direct source information to a user. The
system's relationship with the user is improved via efficient and intelligent output design.

• Computer output should be built in an orderly, well-thought-out manner; the proper


output must be generated while ensuring that each output part is designed in such a way that
users will find the system easy to use. They should identify the exact output that is required
to satisfy the criteria while analysing and de- signing computer output.

• Decide on how you'll deliver the data.

• Create a paper, report or other document that includes the information from the
system.

An information system's output form should achieve one or more of the fol- lowing goals.

• Disseminate information regarding previous actions, present status, or future


estimates.

• Alert people to significant events, opportunities, challenges, or warnings.

• Initiate a reaction.

• Verify a decision.

4. CONCLUSION

The Tension Detection System monitors collected photographs of authorized users to forecast
stress in workers, making the system safe. When the authenticated user logs in, the picture
capture is done automatically depending on a time period. Based on certain common
conversion and image processing processes, the acquired pictures are utilized to determine
the user's stress. The system will then use Machine Learning algorithms to analyze the stress
levels, resulting in more efficient outcomes.

5. Future Enhancement

In the health-care industry, biomedical wearable sensors combined with Internet of Things
technologies have shown to be a winning combo. The advantages of employing such
Page | 19
gadgets have had a favorable influence on both patients and clinicians. Early detection of
medical issues, quicker medical aid through Re- mote Monitoring and Telecommunication, an
emergency alarm system to in- form the caregiver and personal physician, and so on are only
a few of its benefits. By continuously monitoring and delivering frequent feedback on stress
levels, the suggested work on constructing a multimodal IoT system ensures to be a better
health aid for a person. In the future, it would be interesting to expand on this work by
integrating additional physiological characteristics, such as an activity identification system,
and using machine learning approaches to the construction of a stress detection model.

Stress, anxiety, and depression are threatening the mental health of people. Every person has
a reason for having a stressful life. People often share their feelings on social media platforms
like on Instagram in the form of posts and stories, and on Reddit in the form of asking for
suggestions about their life on subreddits. In the past few years, many content creators have
come forward to create content to help people with their mental health. Many organizations
can use stress detection to find which social media users are stressed to help them quickly. So
if you want to learn how to use machine learning to detect stress on social media posts, this
article is for you. In this article, I will take you through the task of stress detection with machine
learning using Python.

Stress Detection with Machine Learning

Stress detection is a challenging task, as there are so many words that can be used by people
on their posts that can show whether a person is having psychological stress or not. While
looking for datasets that I can use to train a machine learning model for stress detection, I
found a dataset on Kaggle with 116 columns. We only need to use the text and label column
for this task.

The dataset I am using for this task contains data posted on subreddits related to mental health.
This dataset contains various mental health problems shared by people about their life.
Fortunately, this dataset is labelled as 0 and 1, where 0 indicates no stress and 1 indicates
stress. So in the section below, I will take you through the task of stress detection in social
media posts using Python.

Stress Detection using Python

Page | 20
Now let’s start the task of stress detection with machine learning. I will start this task by
importing the necessary Python libraries and the dataset that we need for this task:

1
import pandas as pd

2
import numpy as np

3
data = pd.read_csv("stress.csv")

4
print(data.head())

subreddit post_id ... syntax_fk_grade sentiment


0 ptsd 8601tu ... 3.253573 -0.002742
1 assistance 8lbrx9 ... 8.828316 0.292857
2 ptsd 9ch1zh ... 7.841667 0.011894
3 relationships 7rorpp ... 4.104027 0.141671
4 survivorsofabuse 9p2gbc ... 7.910952 -0.204167

[5 rows x 116 columns]

Let’s have a look at whether this dataset contains any null values or not:

1
print(data.isnull().sum())

subreddit 0
post_id 0
sentence_range 0
text 0

Page | 21
id 0
..
lex_dal_avg_pleasantness 0
social_upvote_ratio 0
social_num_comments 0
syntax_fk_grade 0
sentiment 0
Length: 116, dtype: int64

So this dataset does not have any null values. Now let’s prepare the text column of this
dataset to clean the text column with stopwords, links, special symbols and language errors:

1
import nltk

2
import re

3
nltk.download('stopwords')

4
stemmer = nltk.SnowballStemmer("english")

5
from nltk.corpus import stopwords

6
import string

7
stopword=set(stopwords.words('english'))

8
def clean(text):

10

Page | 22
text = str(text).lower()

11
text = re.sub('\[.*?\]', '', text)

12
text = re.sub('https?://\S+|www\.\S+', '', text)

13
text = re.sub('<.*?>+', '', text)

14
text = re.sub('[%s]' % re.escape(string.punctuation), '', text)

15
text = re.sub('\n', '', text)

16
text = re.sub('\w*\d\w*', '', text)

17
text = [word for word in text.split(' ') if word not in stopword]

18
text=" ".join(text)

19
text = [stemmer.stem(word) for word in text.split(' ')]

20
text=" ".join(text)

21
return text

22
data["text"] = data["text"].apply(clean)

Now let’s have a look at the most used words by the people sharing about their life problems
on social media by visualizing a word cloud of the text column:

Page | 23
1
import matplotlib.pyplot as plt

2
from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator

3
text = " ".join(i for i in data.text)

4
stopwords = set(STOPWORDS)

5
wordcloud = WordCloud(stopwords=stopwords,

6
background_color="white").generate(text)

7
plt.figure( figsize=(15,10))

8
plt.imshow(wordcloud, interpolation='bilinear')

9
plt.axis("off")

10
plt.show()

Page | 24
Stress Detection Model

The label column in this dataset contains labels as 0 and 1. 0 means no stress, and 1 means
stress. I will use Stress and No stress labels instead of 1 and 0. So let’s prepare this column
accordingly and select the text and label columns for the process of training a machine
learning model:

1
data["label"] = data["label"].map({0: "No Stress", 1: "Stress"})

2
data = data[["text", "label"]]

3
print(data.head())

text label
0 said felt way sugget go rest trigger ahead you... Stress
1 hey rassist sure right place post goe im curr... No Stress
2 mom hit newspap shock would know dont like pla... Stress
3 met new boyfriend amaz kind sweet good student... Stress
4 octob domest violenc awar month domest violenc... Stress

Now I will split this dataset into training and test sets:

1
from sklearn.feature_extraction.text import CountVectorizer
2
Page | 25
from sklearn.model_selection import train_test_split
3

4
x = np.array(data["text"])
5
y = np.array(data["label"])
6

7
cv = CountVectorizer()
8
X = cv.fit_transform(x)
9
xtrain, xtest, ytrain, ytest = train_test_split(X, y,
10
test_size=0.33,
11
random_state=42)

As this task is based on the problem of binary classification, I will be using the Bernoulli
Naive Bayes algorithm, which is one of the best algorithms for binary classification problems.
So let’s train the stress detection model:

1
from sklearn.naive_bayes import BernoulliNB
2
model = BernoulliNB()
3
model.fit(xtrain, ytrain)

Now let’s test the performance of our model on some random sentences based on mental
health:

Page | 26
1
user = input("Enter a Text: ")
2
data = cv.transform([user]).toarray()
3
output = model.predict(data)
4
print(output)

Enter a Text: People need to take care of their mental health


['No Stress']

1
user = input("Enter a Text: ")
2
data = cv.transform([user]).toarray()
output = model.predict(data)
print(output)

Enter a Text: Sometime I feel like I need some help


['Stress']
So as you can see, we can see good results from our machine learning model. This is how
you can train a stress detection model to detect stress from social media posts. This machine
learning model can be improved by feeding it with more data.

Page | 27
The dataset I’m utilizing for this errand contains information presented on subreddits related
on emotional wellness. This dataset contains different emotional well-being issues shared by

individuals about their life. Luckily, this dataset is named as 0 and 1, where 0 shows no
pressure and 1 demonstrates pressure. So, in the part underneath, I will take you through the

undertaking of pressure discovery in online entertainment posts utilizing Python.

Presently how about we start the undertaking of pressure recognition with AI. I will begin this
assignment by bringing in the essential Python libraries and the dataset that we want for this

errand:

You can download the dataset from the link of given below:

http://tinyurl.com/datasetforstressdetection

Page | 28
Let’s look at the description of our data.

Page | 29
Let’s check if our data set contains null values or not.

So, this dataset does not have any null values. Now we will prepare the text column of this
dataset to clean the text column with stopwords, links, special symbols and language errors:

Presently we should view the most utilized words by individuals sharing about their life issues
via online entertainment by picturing a word cloud of the text column:

Page | 30
The label column in this dataset contains labels as 0 and 1. 0 means no stress, and 1 means
stress. I will use Stress and No stress labels instead of 1 and 0. So let’s prepare this column
accordingly and select the text and label columns for the process of training a machine
learning model:

Now we will split the dataset into training and test sets:

Page | 31
As this task is based on the problem of binary classification, I will be using the Bernoulli
Naive Bayes algorithm, which is one of the best algorithms for binary classification problems.

Now let’s test the performance of our model on some random sentences based on mental
health:

Page | 32
So, as you can see, we have got good results from our machine learning model. This is how
you can train a stress detection model to detect stress from social media posts. This machine
learning model can be improved by feeding it with more data.

Integrating with Google Mail Id (Gmail id)

Here is a simplified example of using the Gmail API in Python to search for emails containing
specific keywords:

Code :

from googleapiclient.discovery import build

from google_auth_oauthlib.flow import InstalledAppFlow

from google.auth.transport.requests import Request

import os

import base64

# Define the SCOPES and credentials

SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']

creds = None

# Check if credentials file exists, otherwise authenticate the user

if os.path.exists('token.json'):

creds = Credentials.from_authorized_user_file('token.json')

if not creds or not creds.valid:

if creds and creds.expired and creds.refresh_token:

creds.refresh(Request())

else:

flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES)

creds = flow.run_local_server(port=0)

Page | 33
# Connect to Gmail API

service = build('gmail', 'v1', credentials=creds)

# Function to search for emails containing specific keywords

def search_emails(query):

try:

result = service.users().messages().list(userId='me', q=query).execute()

messages = []

if 'messages' in result:

messages.extend(result['messages'])

for message in messages:

msg = service.users().messages().get(userId='me', id=message['id']).execute()

message_data =
base64.urlsafe_b64decode(msg['payload']['body']['data'].encode('UTF-8'))

print(message_data) # Process or analyze the email data here

except Exception as e:

print(f"An error occurred: {e}")

# Example: Search for emails containing the word 'stress'

search_emails('subject:stress')

Here we have to use credentials from Google's Developer Console and the credentials.json
file, which contains client information to access the Gmail API.

This code provides a basic structure to connect to Gmail, search for emails containing
specific keywords (in this case, 'stress' in the subject), and retrieve the email content.
However, interpreting and detecting stress based solely on email search data would require
advanced natural language processing and machine learning models to analyze the content
effectively.

Page | 34
Examples of Output
According to the analysis of data from various inputs there are some indicators defined in the
dataset for some situations and related keywords:

Almost homeless
Anxiety
Assistance
Domestic violence
Food pantry
Homeless
PTSD- Post-traumatic stress disorder (PTSD)
Relationships
Stress
Survivors of abuse

Detecting stress involves analyzing various indicators, considering its multidimensional


nature. Some indicators commonly used for stress detection include:

Physiological Indicators:
Heart Rate Variability (HRV): Fluctuations in the time intervals between heartbeats.
Skin Conductance: Changes in skin moisture levels due to sweating, indicating arousal or
stress.
Cortisol Levels: The hormone cortisol increases during stress and can be measured in saliva
or blood.

Body Temperature: Stress can lead to changes in body temperature due to altered blood
flow.

Behavioural Indicators:
Sleep Patterns: Disturbed sleep or changes in sleep duration.
Physical Activity: Sudden changes in activity levels or restlessness.
Eating Habits: Alterations in appetite or sudden dietary changes.
Social Withdrawal: Avoidance of social interactions or increased isolation.

Page | 35
Emotional Indicators:
Self-Reported Stress: Questionnaires or surveys assessing perceived stress levels.
Voice Analysis: Changes in tone, pitch, or speech patterns.
Facial Expressions: Facial recognition software detecting signs of distress or negative
emotions.

Cognitive Indicators:
Memory and Concentration: Difficulty concentrating or memory lapses.
Decision-Making Ability: Impaired judgment or indecisiveness.
Reaction Time: Slower response times in tasks.

Environmental Indicators:
Workload: Overwhelming tasks or deadlines.
Noise Levels: High noise environments can contribute to stress.
Ambient Lighting: Harsh lighting or lack of natural light affecting stress levels.
Combining multiple indicators using machine learning or AI algorithms can provide a more
comprehensive understanding of an individual's stress levels. However, it's essential to
consider that stress manifests differently for each person, and a holistic approach to analyzing
these indicators is crucial for accurate stress detection.

Page | 36
Applications of Stress Detection

Stress detection has numerous applications in various facets of life, contributing to both
personal well-being and professional efficiency. Some practical applications include:

Healthcare and Mental Well-being: Stress detection technology can assist in early
identification of stress levels, enabling timely interventions and personalized mental health
support. It can aid therapists, counselors, and healthcare professionals in offering tailored
interventions for individuals experiencing high stress.

Workplace Productivity: In professional settings, stress detection can be used to monitor


employee well-being. Employers can implement stress detection tools to identify high-stress
periods or situations, allowing for the implementation of strategies to reduce workplace stress
and enhance productivity.

Education: In educational institutions, stress detection can help educators and


administrators understand students' stress levels. This insight can lead to the development of
targeted support programs, adapting teaching methods, and scheduling to reduce student
stress and improve learning outcomes.

Wearable Technology: Wearable devices equipped with stress detection capabilities can
provide real-time monitoring of stress levels. These devices can offer personalized feedback
to users, helping them manage stress through breathing exercises, mindfulness practices, or
suggesting breaks during high-stress periods.

Automotive Safety: Stress detection systems integrated into vehicles can monitor drivers'
stress levels. This technology could prompt alerts or suggest breaks to prevent accidents
caused by stressed or fatigued drivers.

Smart Homes: Stress detection integrated into smart home systems could create
environments that adapt to occupants' stress levels. This could involve adjusting lighting,
music, or other environmental factors to promote relaxation and reduce stress.

Page | 37
Public Safety and Security: Stress detection technology might aid in identifying high-stress
situations in public places, such as airports or crowded events. This could help security
personnel respond more effectively to potentially volatile situations.

In essence, stress detection technology has far-reaching applications that span healthcare,
education, workplace management, and various other domains. Its potential to improve
personal well-being and enhance efficiency in different aspects of life makes it a valuable
area of development and research.

Page | 38
Conclusion

So, this is how you can train a machine learning model to detect stress from social media posts.
People often share their feelings on social media platforms. Many organizations can use stress
detection to find which social media users are stressed to help them quickly.

In conclusion, this project embarked on a significant exploration of stress detection leveraging


the power of Artificial Intelligence in Python. Through the integration of advanced machine
learning algorithms, signal processing techniques, and data analysis methodologies, we aimed
to develop a robust stress detection system.

The utilization of diverse physiological, behavioural, and contextual indicators provided a


comprehensive approach to understanding stress patterns. The AI model exhibited promising
capabilities in recognizing stress-related patterns, demonstrating its potential to accurately
identify stress levels from various data sources.This project's strength lies in its adaptability
and potential for real-time monitoring, offering personalized stress assessment and
intervention strategies. The model's ability to detect stress cues in physiological responses,
behavioral changes, and contextual triggers showcases its versatility and effectiveness in
diverse scenarios.

Despite the advancements made, challenges persist in refining the model's accuracy across
different demographics, contexts, and individual variations in stress responses. Ethical
considerations surrounding data privacy, user consent, and interpretability remain paramount
in the implementation of such AI-powered systems.

Moving forward, continued research and refinement of this stress detection system hold
promise for enhancing mental health support, workplace productivity, and overall well-being.
Collaborations with healthcare professionals, psychologists, and individuals from various
domains can further enrich the model's capabilities and applicability.

In essence, this project serves as a stepping stone towards harnessing AI's potential in
revolutionizing stress detection, paving the way for proactive interventions and personalized
stress management strategies in our increasingly digitized world.

Page | 39
References

1. Dharan, "Machine Learning Techniques for Stress Prediction in Working Employees,"


Madurai, 2018 IEEE International Conference on Computational Intelligence and
Computing Research (ICCIC), Madurai, India, 2018, pp. 1-4
2. Bhattacharyya, R., & Basu, S. (2018). Retrieved from ‘The Economic Times’.
3. "Detection of Stress Using Image Processing and Machine Learning Techniques," by
Nisha Raichur, Nidhi Lonakadi, and Priyanka Mural, vol.9, no. 3S, July 2017.
4. "Stress and anxiety detection using facial cues from videos," Biomedical Signal Pro-
cessing and Control, vol. 31, pp. 89-101, January 2017. G. Giannakakis, D.
Manousos, F.Chiarugi
5. Zenonos, A., Khan, A., Ka- logridis, G., Vatsikas, S., Lewis, T., Sooriyabandara, M.
6. Healthy office: Using smartphones and wearable sensors, employees may rec- ognize
their moods at work. In: Pervasive Computing and Communication Workshops
(PerCom Workshops), 2016 IEEE International Conference on. IEEE; 2016, p. 1–6.
7. OSMI Mental Health in Tech Survey Dataset, 2017.
8. Ghaderi, A., Frounchi, J., Farnam, A. Machine learning based signal processing using
physiological signals for stress detection. In: 2015 22nd Iranian Conference on
Biomedical Engineering (ICBME). 2015, p. 93–98.
9. Liu, D., Ulrich, M. Listen to your heart: Stress prediction using consumer heart rate
sensors 2015;
10. Nakashima, Y., Kim, J., Flutura, S., Seiderer, A., Andre, E., Stress recognition in daily
work. In: ´ International Symposium on Pervasive Computing Paradigms for Mental
Health. Springer; 2015, p. 23–33.

Page | 40

View publication stats

You might also like