Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,101 +1,59 @@
|
|
| 1 |
import nltk
|
| 2 |
import numpy as np
|
|
|
|
|
|
|
| 3 |
import random
|
| 4 |
import json
|
| 5 |
import pickle
|
| 6 |
import gradio as gr
|
| 7 |
-
import requests
|
| 8 |
-
import folium
|
| 9 |
-
import pandas as pd
|
| 10 |
from nltk.tokenize import word_tokenize
|
| 11 |
from nltk.stem.lancaster import LancasterStemmer
|
| 12 |
from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline
|
| 13 |
import torch
|
| 14 |
-
import
|
| 15 |
-
import
|
| 16 |
-
|
| 17 |
from bs4 import BeautifulSoup
|
| 18 |
-
|
|
|
|
|
|
|
|
|
|
| 19 |
|
| 20 |
-
#
|
| 21 |
-
url = "https://maps.googleapis.com/maps/api/place/textsearch/json"
|
| 22 |
-
places_details_url = "https://maps.googleapis.com/maps/api/place/details/json"
|
| 23 |
-
|
| 24 |
-
# Initialize necessary libraries for chatbot and NLP
|
| 25 |
nltk.download('punkt')
|
|
|
|
|
|
|
| 26 |
stemmer = LancasterStemmer()
|
| 27 |
|
| 28 |
-
# Load
|
| 29 |
-
|
| 30 |
-
|
|
|
|
|
|
|
|
|
|
| 31 |
|
| 32 |
# Load preprocessed data from pickle
|
| 33 |
-
|
| 34 |
-
|
|
|
|
|
|
|
|
|
|
| 35 |
|
| 36 |
-
# Build the
|
| 37 |
net = tflearn.input_data(shape=[None, len(training[0])])
|
| 38 |
net = tflearn.fully_connected(net, 8)
|
| 39 |
net = tflearn.fully_connected(net, 8)
|
| 40 |
net = tflearn.fully_connected(net, len(output[0]), activation="softmax")
|
| 41 |
net = tflearn.regression(net)
|
| 42 |
-
model = tflearn.DNN(net)
|
| 43 |
-
model.load("MentalHealthChatBotmodel.tflearn")
|
| 44 |
-
|
| 45 |
-
# Emotion and sentiment analysis model
|
| 46 |
-
def load_model():
|
| 47 |
-
tokenizer = AutoTokenizer.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
|
| 48 |
-
model = AutoModelForSequenceClassification.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
|
| 49 |
-
return tokenizer, model
|
| 50 |
-
|
| 51 |
-
tokenizer, emotion_model = load_model()
|
| 52 |
-
|
| 53 |
-
# Google Places API query function
|
| 54 |
-
def get_places_data(query, location, radius=5000, api_key="GOOGLE_API_KEY"):
|
| 55 |
-
# Use geopy to convert location name to coordinates
|
| 56 |
-
geolocator = Nominatim(user_agent="place_search")
|
| 57 |
-
location_obj = geolocator.geocode(location)
|
| 58 |
-
if location_obj is None:
|
| 59 |
-
return []
|
| 60 |
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
}
|
| 68 |
-
try:
|
| 69 |
-
response = requests.get(url, params=params)
|
| 70 |
-
response.raise_for_status()
|
| 71 |
-
data = response.json()
|
| 72 |
-
return data.get('results', [])
|
| 73 |
-
except requests.exceptions.RequestException as e:
|
| 74 |
-
print(f"Error fetching places data: {e}")
|
| 75 |
-
return []
|
| 76 |
-
|
| 77 |
-
# Map generation function
|
| 78 |
-
def create_map(locations):
|
| 79 |
-
m = folium.Map(location=[21.3, -157.8], zoom_start=12)
|
| 80 |
-
for loc in locations:
|
| 81 |
-
name = loc.get("name", "No Name")
|
| 82 |
-
lat = loc['geometry']['location']['lat']
|
| 83 |
-
lng = loc['geometry']['location']['lng']
|
| 84 |
-
folium.Marker([lat, lng], popup=name).add_to(m)
|
| 85 |
-
return m._repr_html_() # Return HTML representation
|
| 86 |
-
|
| 87 |
-
# Sentiment Analysis function
|
| 88 |
-
def analyze_sentiment(user_input):
|
| 89 |
-
tokenizer = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
|
| 90 |
-
model = AutoModelForSequenceClassification.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
|
| 91 |
-
inputs = tokenizer(user_input, return_tensors="pt")
|
| 92 |
-
with torch.no_grad():
|
| 93 |
-
outputs = model(**inputs)
|
| 94 |
-
predicted_class = torch.argmax(outputs.logits, dim=1).item()
|
| 95 |
-
sentiment = ["Negative", "Neutral", "Positive"][predicted_class]
|
| 96 |
-
return sentiment
|
| 97 |
|
| 98 |
-
#
|
| 99 |
def bag_of_words(s, words):
|
| 100 |
bag = [0 for _ in range(len(words))]
|
| 101 |
s_words = word_tokenize(s)
|
|
@@ -106,13 +64,18 @@ def bag_of_words(s, words):
|
|
| 106 |
bag[i] = 1
|
| 107 |
return np.array(bag)
|
| 108 |
|
| 109 |
-
|
|
|
|
| 110 |
history = history or []
|
| 111 |
message = message.lower()
|
|
|
|
| 112 |
try:
|
|
|
|
| 113 |
results = model.predict([bag_of_words(message, words)])
|
| 114 |
results_index = np.argmax(results)
|
| 115 |
tag = labels[results_index]
|
|
|
|
|
|
|
| 116 |
for tg in data["intents"]:
|
| 117 |
if tg['tag'] == tag:
|
| 118 |
responses = tg['responses']
|
|
@@ -122,80 +85,130 @@ def chatbot(message, history):
|
|
| 122 |
response = "I'm sorry, I didn't understand that. Could you please rephrase?"
|
| 123 |
except Exception as e:
|
| 124 |
response = f"An error occurred: {str(e)}"
|
|
|
|
| 125 |
history.append((message, response))
|
| 126 |
return history, history
|
| 127 |
|
| 128 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
def detect_emotion(user_input):
|
| 130 |
-
pipe = pipeline("text-classification", model=emotion_model, tokenizer=tokenizer)
|
| 131 |
result = pipe(user_input)
|
| 132 |
emotion = result[0]['label']
|
| 133 |
return emotion
|
| 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 |
-
if
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 168 |
else:
|
| 169 |
-
|
| 170 |
-
places_map = ""
|
| 171 |
|
| 172 |
-
|
| 173 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 174 |
|
| 175 |
-
|
|
|
|
|
|
|
|
|
|
| 176 |
|
| 177 |
# Gradio interface setup
|
| 178 |
iface = gr.Interface(
|
| 179 |
-
fn=
|
| 180 |
inputs=[
|
| 181 |
-
gr.Textbox(label="Enter your message", placeholder="How are you feeling?"),
|
| 182 |
-
"
|
| 183 |
-
|
| 184 |
-
gr.Textbox(label="Location (e.g. Lahore, Hawaii, Allama Iqbal Town)", placeholder="e.g. Lahore, Allama Iqbal Town"),
|
| 185 |
-
gr.Button("Detect Emotion"),
|
| 186 |
-
gr.Button("Search for Therapists")
|
| 187 |
],
|
| 188 |
outputs=[
|
| 189 |
-
gr.
|
| 190 |
-
gr.
|
| 191 |
-
gr.
|
| 192 |
-
gr.
|
| 193 |
-
"
|
| 194 |
],
|
| 195 |
-
|
| 196 |
-
|
|
|
|
| 197 |
)
|
| 198 |
|
| 199 |
-
# Launch Gradio
|
| 200 |
if __name__ == "__main__":
|
| 201 |
-
iface.launch(debug=True)
|
|
|
|
| 1 |
import nltk
|
| 2 |
import numpy as np
|
| 3 |
+
import tflearn
|
| 4 |
+
import tensorflow
|
| 5 |
import random
|
| 6 |
import json
|
| 7 |
import pickle
|
| 8 |
import gradio as gr
|
|
|
|
|
|
|
|
|
|
| 9 |
from nltk.tokenize import word_tokenize
|
| 10 |
from nltk.stem.lancaster import LancasterStemmer
|
| 11 |
from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline
|
| 12 |
import torch
|
| 13 |
+
import requests
|
| 14 |
+
import pandas as pd
|
| 15 |
+
import time
|
| 16 |
from bs4 import BeautifulSoup
|
| 17 |
+
from selenium import webdriver
|
| 18 |
+
from selenium.webdriver.chrome.options import Options
|
| 19 |
+
import chromedriver_autoinstaller
|
| 20 |
+
import os
|
| 21 |
|
| 22 |
+
# Ensure necessary NLTK resources are downloaded
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
nltk.download('punkt')
|
| 24 |
+
|
| 25 |
+
# Initialize the stemmer
|
| 26 |
stemmer = LancasterStemmer()
|
| 27 |
|
| 28 |
+
# Load intents.json
|
| 29 |
+
try:
|
| 30 |
+
with open("intents.json") as file:
|
| 31 |
+
data = json.load(file)
|
| 32 |
+
except FileNotFoundError:
|
| 33 |
+
raise FileNotFoundError("Error: 'intents.json' file not found. Ensure it exists in the current directory.")
|
| 34 |
|
| 35 |
# Load preprocessed data from pickle
|
| 36 |
+
try:
|
| 37 |
+
with open("data.pickle", "rb") as f:
|
| 38 |
+
words, labels, training, output = pickle.load(f)
|
| 39 |
+
except FileNotFoundError:
|
| 40 |
+
raise FileNotFoundError("Error: 'data.pickle' file not found. Ensure it exists and matches the model.")
|
| 41 |
|
| 42 |
+
# Build the model structure
|
| 43 |
net = tflearn.input_data(shape=[None, len(training[0])])
|
| 44 |
net = tflearn.fully_connected(net, 8)
|
| 45 |
net = tflearn.fully_connected(net, 8)
|
| 46 |
net = tflearn.fully_connected(net, len(output[0]), activation="softmax")
|
| 47 |
net = tflearn.regression(net)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
|
| 49 |
+
# Load the trained model
|
| 50 |
+
model = tflearn.DNN(net)
|
| 51 |
+
try:
|
| 52 |
+
model.load("MentalHealthChatBotmodel.tflearn")
|
| 53 |
+
except FileNotFoundError:
|
| 54 |
+
raise FileNotFoundError("Error: Trained model file 'MentalHealthChatBotmodel.tflearn' not found.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
|
| 56 |
+
# Function to process user input into a bag-of-words format
|
| 57 |
def bag_of_words(s, words):
|
| 58 |
bag = [0 for _ in range(len(words))]
|
| 59 |
s_words = word_tokenize(s)
|
|
|
|
| 64 |
bag[i] = 1
|
| 65 |
return np.array(bag)
|
| 66 |
|
| 67 |
+
# Chat function (Chatbot)
|
| 68 |
+
def chat(message, history):
|
| 69 |
history = history or []
|
| 70 |
message = message.lower()
|
| 71 |
+
|
| 72 |
try:
|
| 73 |
+
# Predict the tag
|
| 74 |
results = model.predict([bag_of_words(message, words)])
|
| 75 |
results_index = np.argmax(results)
|
| 76 |
tag = labels[results_index]
|
| 77 |
+
|
| 78 |
+
# Match tag with intent and choose a random response
|
| 79 |
for tg in data["intents"]:
|
| 80 |
if tg['tag'] == tag:
|
| 81 |
responses = tg['responses']
|
|
|
|
| 85 |
response = "I'm sorry, I didn't understand that. Could you please rephrase?"
|
| 86 |
except Exception as e:
|
| 87 |
response = f"An error occurred: {str(e)}"
|
| 88 |
+
|
| 89 |
history.append((message, response))
|
| 90 |
return history, history
|
| 91 |
|
| 92 |
+
# Sentiment Analysis (Code 2)
|
| 93 |
+
tokenizer_sentiment = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
|
| 94 |
+
model_sentiment = AutoModelForSequenceClassification.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
|
| 95 |
+
|
| 96 |
+
def analyze_sentiment(user_input):
|
| 97 |
+
inputs = tokenizer_sentiment(user_input, return_tensors="pt")
|
| 98 |
+
with torch.no_grad():
|
| 99 |
+
outputs = model_sentiment(**inputs)
|
| 100 |
+
predicted_class = torch.argmax(outputs.logits, dim=1).item()
|
| 101 |
+
sentiment = ["Negative", "Neutral", "Positive"][predicted_class]
|
| 102 |
+
return f"**Predicted Sentiment:** {sentiment}"
|
| 103 |
+
|
| 104 |
+
# Emotion Detection (Code 3)
|
| 105 |
+
tokenizer_emotion = AutoTokenizer.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
|
| 106 |
+
model_emotion = AutoModelForSequenceClassification.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
|
| 107 |
+
pipe = pipeline("text-classification", model=model_emotion, tokenizer=tokenizer_emotion)
|
| 108 |
+
|
| 109 |
def detect_emotion(user_input):
|
|
|
|
| 110 |
result = pipe(user_input)
|
| 111 |
emotion = result[0]['label']
|
| 112 |
return emotion
|
| 113 |
|
| 114 |
+
def provide_suggestions(emotion):
|
| 115 |
+
suggestions = ""
|
| 116 |
+
if emotion == 'joy':
|
| 117 |
+
suggestions += "You're feeling happy! Keep up the great mood!"
|
| 118 |
+
elif emotion == 'anger':
|
| 119 |
+
suggestions += "You're feeling angry. It's okay to feel this way."
|
| 120 |
+
elif emotion == 'fear':
|
| 121 |
+
suggestions += "You're feeling fearful. Take a moment to breathe."
|
| 122 |
+
elif emotion == 'sadness':
|
| 123 |
+
suggestions += "You're feeling sad. It's okay to take a break."
|
| 124 |
+
elif emotion == 'surprise':
|
| 125 |
+
suggestions += "You're feeling surprised. It's okay to feel neutral!"
|
| 126 |
+
return suggestions
|
| 127 |
+
|
| 128 |
+
# Google Places API (Code 4)
|
| 129 |
+
api_key = "YOUR_GOOGLE_API_KEY" # Replace with your API key
|
| 130 |
+
|
| 131 |
+
def get_places_data(query, location, radius, api_key, next_page_token=None):
|
| 132 |
+
url = "https://maps.googleapis.com/maps/api/place/textsearch/json"
|
| 133 |
+
params = {
|
| 134 |
+
"query": query,
|
| 135 |
+
"location": location,
|
| 136 |
+
"radius": radius,
|
| 137 |
+
"key": api_key
|
| 138 |
+
}
|
| 139 |
+
if next_page_token:
|
| 140 |
+
params["pagetoken"] = next_page_token
|
| 141 |
+
response = requests.get(url, params=params)
|
| 142 |
+
return response.json() if response.status_code == 200 else None
|
| 143 |
+
|
| 144 |
+
def get_all_places(query, location, radius, api_key):
|
| 145 |
+
all_results = []
|
| 146 |
+
next_page_token = None
|
| 147 |
+
while True:
|
| 148 |
+
data = get_places_data(query, location, radius, api_key, next_page_token)
|
| 149 |
+
if data:
|
| 150 |
+
results = data.get('results', [])
|
| 151 |
+
for place in results:
|
| 152 |
+
place_id = place.get("place_id")
|
| 153 |
+
name = place.get("name")
|
| 154 |
+
address = place.get("formatted_address")
|
| 155 |
+
website = place.get("website", "Not available")
|
| 156 |
+
all_results.append([name, address, website])
|
| 157 |
+
next_page_token = data.get('next_page_token')
|
| 158 |
+
if not next_page_token:
|
| 159 |
+
break
|
| 160 |
+
else:
|
| 161 |
+
break
|
| 162 |
+
return all_results
|
| 163 |
+
|
| 164 |
+
# Search Wellness Professionals
|
| 165 |
+
def search_wellness_professionals(location):
|
| 166 |
+
query = "therapist OR counselor OR mental health professional"
|
| 167 |
+
radius = 50000
|
| 168 |
+
google_places_data = get_all_places(query, location, radius, api_key)
|
| 169 |
+
if google_places_data:
|
| 170 |
+
df = pd.DataFrame(google_places_data, columns=["Name", "Address", "Website"])
|
| 171 |
+
return df.to_csv(index=False)
|
| 172 |
else:
|
| 173 |
+
return "No data found."
|
|
|
|
| 174 |
|
| 175 |
+
# Gradio Interface
|
| 176 |
+
def gradio_interface(message, location, history):
|
| 177 |
+
# Stage 1: Mental Health Chatbot
|
| 178 |
+
history, _ = chat(message, history)
|
| 179 |
+
|
| 180 |
+
# Stage 2: Sentiment Analysis
|
| 181 |
+
sentiment = analyze_sentiment(message)
|
| 182 |
+
|
| 183 |
+
# Stage 3: Emotion Detection and Suggestions
|
| 184 |
+
emotion = detect_emotion(message)
|
| 185 |
+
suggestions = provide_suggestions(emotion)
|
| 186 |
|
| 187 |
+
# Stage 4: Search for Wellness Professionals
|
| 188 |
+
wellness_results = search_wellness_professionals(location)
|
| 189 |
+
|
| 190 |
+
return history, sentiment, emotion, suggestions, wellness_results
|
| 191 |
|
| 192 |
# Gradio interface setup
|
| 193 |
iface = gr.Interface(
|
| 194 |
+
fn=gradio_interface,
|
| 195 |
inputs=[
|
| 196 |
+
gr.Textbox(label="Enter your message", placeholder="How are you feeling today?"),
|
| 197 |
+
gr.Textbox(label="Enter your location (e.g., Hawaii, Oahu)", placeholder="Your location"),
|
| 198 |
+
"state"
|
|
|
|
|
|
|
|
|
|
| 199 |
],
|
| 200 |
outputs=[
|
| 201 |
+
gr.Chatbot(label="Chat History"),
|
| 202 |
+
gr.Textbox(label="Sentiment Analysis"),
|
| 203 |
+
gr.Textbox(label="Detected Emotion"),
|
| 204 |
+
gr.Textbox(label="Suggestions"),
|
| 205 |
+
gr.File(label="Download Wellness Professionals CSV")
|
| 206 |
],
|
| 207 |
+
allow_flagging="never",
|
| 208 |
+
title="Mental Wellbeing App with AI Assistance",
|
| 209 |
+
description="This app provides a mental health chatbot, sentiment analysis, emotion detection, and wellness professional search functionality.",
|
| 210 |
)
|
| 211 |
|
| 212 |
+
# Launch Gradio interface
|
| 213 |
if __name__ == "__main__":
|
| 214 |
+
iface.launch(debug=True)
|