File size: 9,066 Bytes
334ba26
 
7684892
334ba26
 
 
 
7684892
334ba26
ebca5ff
5e7f7ee
334ba26
 
5e7f7ee
ff908a7
e859494
fa97be4
 
 
 
7684892
334ba26
 
ae282f5
334ba26
 
 
 
ff908a7
 
 
334ba26
 
ff908a7
 
 
334ba26
 
ff908a7
 
 
 
 
 
 
334ba26
 
ff908a7
 
 
 
334ba26
 
 
 
 
 
 
 
 
 
 
 
 
ff908a7
334ba26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48a4b0f
334ba26
ebca5ff
 
334ba26
 
 
 
 
 
 
 
 
 
 
 
ebca5ff
e6396eb
 
 
 
 
ebca5ff
 
 
 
e6396eb
ebca5ff
 
 
 
e6396eb
ebca5ff
e6396eb
ebca5ff
 
 
 
e6396eb
ebca5ff
e6396eb
ebca5ff
 
 
 
e6396eb
ebca5ff
e6396eb
ebca5ff
 
 
e6396eb
ebca5ff
e6396eb
ebca5ff
 
 
e6396eb
ebca5ff
674b44a
ebca5ff
674b44a
 
 
 
ff908a7
674b44a
 
 
 
 
ff908a7
 
 
674b44a
 
 
 
ff908a7
 
 
 
 
674b44a
d7c7798
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ebca5ff
674b44a
ebca5ff
 
 
674b44a
 
ebca5ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fa97be4
ebca5ff
fa97be4
e6396eb
fa97be4
 
 
ff908a7
fa97be4
 
 
ebca5ff
d7c7798
fa97be4
 
 
 
 
613b05f
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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
import json
import pickle
import random
import nltk
import numpy as np
import tflearn
import gradio as gr
import requests
import torch
import folium
from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline
from nltk.tokenize import word_tokenize
from nltk.stem.lancaster import LancasterStemmer
import os
from functools import lru_cache
import pandas as pd
import tensorflow as tf  # Added to enable resource variables

# Enable resource variables in TensorFlow to avoid deprecated warnings
tf.compat.v1.enable_resource_variables()

# Ensure necessary NLTK resources are downloaded
nltk.download('punkt')

# Initialize the stemmer
stemmer = LancasterStemmer()

# Load intents.json
def load_intents(file_path):
    with open(file_path) as file:
        return json.load(file)

# Load preprocessed data from pickle
def load_preprocessed_data(file_path):
    with open(file_path, "rb") as f:
        return pickle.load(f)

# Build the model structure
def build_model(words, labels, training, output):
    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)
    return tflearn.DNN(net)

# Load the trained model
def load_model(model_path, net):
    model = tflearn.DNN(net)
    model.load(model_path)
    return model

# 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 = 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)

# Chat function
def chat(message, history, words, labels, model):
    history = history or []
    message = message.lower()
    
    try:
        # Predict the tag
        results = model.predict([bag_of_words(message, words)])
        results_index = np.argmax(results)
        tag = labels[results_index]

        # Match tag with intent and choose a random response
        for tg in data["intents"]:
            if tg['tag'] == tag:
                responses = tg['responses']
                response = random.choice(responses)
                break
        else:
            response = "I'm sorry, I didn't understand that. Could you please rephrase?"

    except Exception as e:
        response = f"An error occurred: {str(e)}"
    
    history.append((message, response))
    return history, history

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

# Emotion detection setup
def load_emotion_model():
    tokenizer = AutoTokenizer.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
    model = AutoModelForSequenceClassification.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
    return tokenizer, model

tokenizer_emotion, model_emotion = load_emotion_model()

# Emotion detection function with suggestions
def detect_emotion(user_input):
    pipe = pipeline("text-classification", model=model_emotion, tokenizer=tokenizer_emotion)
    result = pipe(user_input)
    emotion = result[0]['label']
    
    suggestions = []
    video_link = ""
    
    # Provide suggestions based on the detected emotion
    if emotion == 'joy':
        suggestions = [
            ("Relaxation Techniques", "https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation"),
            ("Dealing with Stress", "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"),
            ("Emotional Wellness Toolkit", "https://www.nih.gov/health-information/emotional-wellness-toolkit")
        ]
        video_link = "Watch on YouTube: https://youtu.be/m1vaUGtyo-A"
    elif emotion == 'anger':
        suggestions = [
            ("Emotional Wellness Toolkit", "https://www.nih.gov/health-information/emotional-wellness-toolkit"),
            ("Stress Management Tips", "https://www.health.harvard.edu/health-a-to-z"),
            ("Dealing with Anger", "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety")
        ]
        video_link = "Watch on YouTube: https://youtu.be/MIc299Flibs"
    elif emotion == 'fear':
        suggestions = [
            ("Mindfulness Practices", "https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation"),
            ("Coping with Anxiety", "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"),
            ("Emotional Wellness Toolkit", "https://www.nih.gov/health-information/emotional-wellness-toolkit")
        ]
        video_link = "Watch on YouTube: https://youtu.be/yGKKz185M5o"
    elif emotion == 'sadness':
        suggestions = [
            ("Emotional Wellness Toolkit", "https://www.nih.gov/health-information/emotional-wellness-toolkit"),
            ("Dealing with Anxiety", "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety")
        ]
        video_link = "Watch on YouTube: https://youtu.be/-e-4Kx5px_I"
    elif emotion == 'surprise':
        suggestions = [
            ("Managing Stress", "https://www.health.harvard.edu/health-a-to-z"),
            ("Coping Strategies", "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety")
        ]
        video_link = "Watch on YouTube: https://youtu.be/m1vaUGtyo-A"
    
    return emotion, suggestions, video_link

# Google Geocoding API setup to convert city name to latitude/longitude
geocode_url = "https://maps.googleapis.com/maps/api/geocode/json"

@lru_cache(maxsize=128)
def get_lat_lon(location, api_key):
    params = {
        "address": location,
        "key": api_key
    }
    try:
        response = requests.get(geocode_url, params=params)
        response.raise_for_status()
        result = response.json()
        if result['status'] == 'OK':
            location = result['results'][0]['geometry']['location']
            return location['lat'], location['lng']
        else:
            return None, None
    except requests.RequestException as e:
        print(f"Error fetching coordinates: {e}")
        return None, None

# Function to fetch places data using Google Places API
def get_places_data(query, location, radius, api_key):
    places_url = "https://maps.googleapis.com/maps/api/place/textsearch/json"
    params = {
        "query": query,
        "location": location,
        "radius": radius,
        "key": api_key
    }
    try:
        response = requests.get(places_url, params=params)
        response.raise_for_status()
        return response.json()
    except requests.RequestException as e:
        print(f"Error fetching places data: {e}")
        return None

# Get wellness professionals
def get_wellness_professionals(location, api_key):
    query = "therapist OR counselor OR mental health professional OR marriage and family therapist OR psychotherapist OR psychiatrist OR psychologist OR nutritionist OR wellness doctor OR holistic practitioner OR integrative medicine OR chiropractor OR naturopath"
    radius = 50000  # 50 km radius

    lat, lon = get_lat_lon(location, api_key)
    
    if lat is None or lon is None:
        return "Unable to find coordinates for the given location."

    # Using Google Places API to fetch wellness professionals
    data = get_places_data(query, f"{lat},{lon}", radius, api_key)

    if data:
        results = data.get('results', [])
        wellness_data = []
        for place in results:
            name = place.get("name")
            address = place.get("formatted_address")
            latitude = place.get("geometry", {}).get("location", {}).get("lat")
            longitude = place.get("geometry", {}).get("location", {}).get("lng")
            wellness_data.append([name, address, latitude, longitude])
        return wellness_data

    return []

# Function to generate a map with wellness professionals
def generate_map(wellness_data):
    map_center = [23.685, 90.3563]  # Default center for Bangladesh (you can adjust this)
    m = folium.Map(location=map_center, zoom_start=12)

    for place in wellness_data:
        name, address, lat, lon = place
        folium.Marker([lat, lon], popup=f"{name}\n{address}").add_to(m)

    return m

# Initialize the necessary files
data = load_intents("intents.json")
words, labels, training, output = load_preprocessed_data("data.pickle")

# Build the model
model = build_model(words, labels, training, output)
model = load_model("model.tflearn", model)

# Gradio interface
def chatbot_interface(message, history):
    return chat(message, history, words, labels, model)

# Example usage with Gradio UI
gr.Interface(fn=chatbot_interface, inputs=["text", "state"], outputs=["chatbot", "state"]).launch()