File size: 7,397 Bytes
1aa6549
936af04
 
 
 
e623c13
936af04
2ae19d7
936af04
2ae19d7
fd60b30
936af04
fa97be4
936af04
334ba26
dacc7c0
e623c13
334ba26
 
e623c13
936af04
 
334ba26
e623c13
936af04
 
0e313c1
c69efb6
 
 
 
 
 
 
 
 
936af04
c69efb6
 
d5331b4
 
c69efb6
d5331b4
c69efb6
 
 
 
97f0957
936af04
 
 
 
 
 
 
 
 
 
4525308
936af04
3218176
 
 
936af04
 
 
3218176
 
 
936af04
 
 
3218176
936af04
3218176
 
 
936af04
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e623c13
936af04
 
 
3218176
936af04
 
 
3218176
936af04
 
 
e623c13
936af04
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
import gradio as gr
from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline
import json
import pickle
import random
import pandas as pd
import requests
import nltk
from nltk.stem import LancasterStemmer
import numpy as np
import tensorflow as tf
from bs4 import BeautifulSoup

# Download necessary NLTK resources
nltk.download('punkt')

# Initialize the stemmer
stemmer = LancasterStemmer()

# Load intents.json
with open("intents.json") as file:
    data = json.load(file)

# Load preprocessed data from pickle
with open("data.pickle", "rb") as f:
    words, labels, training, output = pickle.load(f)

# Build the model structure
net = tflearn.input_data(shape=[None, len(training[0])])
net = tflearn.fully_connected(net, 8)
net = tflearn.fully_connected(net, 8)
net = tflearn.fully_connected(net, len(output[0]), activation="softmax")
net = tflearn.regression(net)

# Load the trained model
model = tflearn.DNN(net)
model.load("MentalHealthChatBotmodel.tflearn")

# Sentiment analysis
tokenizer_sentiment = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
model_sentiment = AutoModelForSequenceClassification.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
sentiment_pipeline = pipeline("sentiment-analysis")

# Emotion detection
tokenizer_emotion = AutoTokenizer.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
model_emotion = AutoModelForSequenceClassification.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
emotion_pipeline = pipeline("text-classification", model=model_emotion, tokenizer=tokenizer_emotion)

# Function to process user input into a bag-of-words format
def bag_of_words(s, words):
    bag = [0 for _ in range(len(words))]
    s_words = nltk.word_tokenize(s)
    s_words = [stemmer.stem(word.lower()) for word in s_words if word.lower() in words]
    for se in s_words:
        for i, w in enumerate(words):
            if w == se:
                bag[i] = 1
    return np.array(bag)

# Function to generate recommendations based on emotion
def generate_recommendations(emotion):
    if emotion == 'joy':
        return [
            {"title": "Mindful Breathing Meditation", "link": "https://www.example.com/joy"},
            {"title": "Dealing with Stress", "link": "https://www.example.com/stress"},
            {"title": "Emotional Wellness Toolkit", "link": "https://www.example.com/wellness"}
        ]
    elif emotion == 'anger':
        return [
            {"title": "Anger Management Techniques", "link": "https://www.example.com/anger"},
            {"title": "Stress Management Tips", "link": "https://www.example.com/stress"},
            {"title": "Dealing with Anger", "link": "https://www.example.com/dealing_with_anger"}
        ]
    # Add more cases for other emotions
    else:
        return []

# Function to fetch nearby health professionals
def fetch_nearby_health_professionals(location):
    # Placeholder for fetching nearby health professionals
    # Actual implementation depends on the API used and should replace the placeholder data
    return pd.DataFrame([
        {'Name': 'Dr. Jane Smith', 'Address': '123 Wellness St.', 'Phone': '555-1234'},
        {'Name': 'Dr. John Doe', 'Address': '456 Health Rd.', 'Phone': '555-5678'}
    ])

# Function to detect emotion and provide suggestions
def detect_emotion_and_suggest(text):
    pipe = pipeline("text-classification", model=model_emotion, tokenizer=tokenizer_emotion)
    result = pipe(text)
    emotion = result[0]['label']

    # Prepare suggestions based on the detected emotion
    suggestions = ""
    relaxation_videos = ""
    if emotion == 'joy':
        suggestions = "You're feeling happy! Keep up the great mood!\n\nUseful Resources:\n- Relaxation Techniques: [Link](https://www.example.com/joy)\n- Dealing with Stress: [Link](https://www.example.com/stress)\n- Emotional Wellness Toolkit: [Link](https://www.example.com/wellness)"
        relaxation_videos = "Relaxation Videos:\n- Watch on YouTube: [Link](https://youtu.be/m1vaUGtyo-A)"

    elif emotion == 'anger':
        suggestions = "You're feeling angry. It's okay to feel this way. Let's try to calm down.\n\nUseful Resources:\n- Emotional Wellness Toolkit: [Link](https://www.example.com/anger)\n- Stress Management Tips: [Link](https://www.example.com/stress)\n- Dealing with Anger: [Link](https://www.example.com/dealing_with_anger)"
        relaxation_videos = "Relaxation Videos:\n- Watch on YouTube: [Link](https://youtu.be/MIc299Flibs)"

    elif emotion == 'fear':
        suggestions = "You're feeling fearful. Take a moment to breathe and relax.\n\nUseful Resources:\n- Mindfulness Practices: [Link](https://www.example.com/fear)\n- Coping with Anxiety: [Link](https://www.example.com/anxiety)\n- Emotional Wellness Toolkit: [Link](https://www.example.com/wellness)"
        relaxation_videos = "Relaxation Videos:\n- Watch on YouTube: [Link](https://youtu.be/yGKKz185M5o)"

    elif emotion == 'sadness':
        suggestions = "You're feeling sad. It's okay to take a break.\n\nUseful Resources:\n- Emotional Wellness Toolkit: [Link](https://www.example.com/sadness)\n- Dealing with Anxiety: [Link](https://www.example.com/anxiety)"
        relaxation_videos = "Relaxation Videos:\n- Watch on YouTube: [Link](https://youtu.be/-e-4Kx5px_I)"

    elif emotion == 'surprise':
        suggestions = "You're feeling surprised. It's okay to feel neutral!\n\nUseful Resources:\n- Managing Stress: [Link](https://www.example.com/surprise)\n- Coping Strategies: [Link](https://www.example.com/coping)"
        relaxation_videos = "Relaxation Videos:\n- Watch on YouTube: [Link](https://youtu.be/m1vaUGtyo-A)"

    return emotion, suggestions, relaxation_videos

# Gradio interface for emotion detection and suggestions
iface = gr.Interface(
    fn=detect_emotion_and_suggest,
    inputs="text",
    outputs=[
        "text",  # For displaying detected emotion
        "markdown",  # For displaying suggestions
        "markdown",  # For displaying relaxation videos
    ],
    title="Emotion Detection and Well-Being Suggestions",
    description="Enter your thoughts below to detect your current emotion and receive personalized well-being suggestions.",
)

# Function to show a summary of the detected emotion and suggestions
def show_summary(emotion, suggestions):
    return f"**Emotion Detected:** {emotion}\n{suggestions}"

# Gradio interface for showing summary
summary_iface = gr.Interface(
    fn=show_summary,
    inputs=[
        "text",  # For detected emotion
        "text",  # For suggestions
    ],
    outputs="markdown",
    title="Summary of Emotion and Suggestions",
    description="Click the button to see a summary of your detected emotion and the suggested well-being resources.",
)

# Function to fetch and display nearby health professionals
def fetch_and_display_health_professionals(location):
    df = fetch_nearby_health_professionals(location)
    return df

# Gradio interface for fetching nearby health professionals
health_professionals_iface = gr.Interface(
    fn=fetch_and_display_health_professionals,
    inputs="text",
    outputs="dataframe",
    title="Find Nearby Health Professionals",
    description="Enter your location to find nearby health professionals.",
)

# Launch the Gradio interfaces
iface.launch()
summary_iface.launch()
health_professionals_iface.launch()