Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,116 +1,51 @@
|
|
1 |
import gradio as gr
|
2 |
-
import nltk
|
3 |
-
import numpy as np
|
4 |
-
import tflearn
|
5 |
import random
|
6 |
-
import json
|
7 |
-
import pickle
|
8 |
-
import torch
|
9 |
-
from nltk.tokenize import word_tokenize
|
10 |
-
from nltk.stem.lancaster import LancasterStemmer
|
11 |
-
from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline
|
12 |
import requests
|
13 |
-
|
14 |
-
|
15 |
-
# Ensure necessary NLTK resources are downloaded
|
16 |
-
nltk.download('punkt')
|
17 |
-
|
18 |
-
# Initialize the stemmer
|
19 |
-
stemmer = LancasterStemmer()
|
20 |
-
|
21 |
-
# Load intents.json
|
22 |
-
try:
|
23 |
-
with open("intents.json") as file:
|
24 |
-
data = json.load(file)
|
25 |
-
except FileNotFoundError:
|
26 |
-
raise FileNotFoundError("Error: 'intents.json' file not found. Ensure it exists in the current directory.")
|
27 |
-
|
28 |
-
# Load preprocessed data from pickle
|
29 |
-
try:
|
30 |
-
with open("data.pickle", "rb") as f:
|
31 |
-
words, labels, training, output = pickle.load(f)
|
32 |
-
except FileNotFoundError:
|
33 |
-
raise FileNotFoundError("Error: 'data.pickle' file not found. Ensure it exists and matches the model.")
|
34 |
-
|
35 |
-
# Build the model structure
|
36 |
-
net = tflearn.input_data(shape=[None, len(training[0])])
|
37 |
-
net = tflearn.fully_connected(net, 8)
|
38 |
-
net = tflearn.fully_connected(net, 8)
|
39 |
-
net = tflearn.fully_connected(net, len(output[0]), activation="softmax")
|
40 |
-
net = tflearn.regression(net)
|
41 |
-
|
42 |
-
# Load the trained model
|
43 |
-
model = tflearn.DNN(net)
|
44 |
-
try:
|
45 |
-
model.load("MentalHealthChatBotmodel.tflearn")
|
46 |
-
except FileNotFoundError:
|
47 |
-
raise FileNotFoundError("Error: Trained model file 'MentalHealthChatBotmodel.tflearn' not found.")
|
48 |
|
49 |
-
#
|
50 |
-
|
51 |
-
bag = [0 for _ in range(len(words))]
|
52 |
-
s_words = word_tokenize(s)
|
53 |
-
s_words = [stemmer.stem(word.lower()) for word in s_words if word.lower() in words]
|
54 |
-
for se in s_words:
|
55 |
-
for i, w in enumerate(words):
|
56 |
-
if w == se:
|
57 |
-
bag[i] = 1
|
58 |
-
return np.array(bag)
|
59 |
|
60 |
-
#
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
# Predict the tag
|
66 |
-
results = model.predict([bag_of_words(message, words)])
|
67 |
-
results_index = np.argmax(results)
|
68 |
-
tag = labels[results_index]
|
69 |
-
|
70 |
-
# Match tag with intent and choose a random response
|
71 |
-
for tg in data["intents"]:
|
72 |
-
if tg['tag'] == tag:
|
73 |
-
responses = tg['responses']
|
74 |
-
response = random.choice(responses)
|
75 |
-
break
|
76 |
-
else:
|
77 |
-
response = "I'm sorry, I didn't understand that. Could you please rephrase?"
|
78 |
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
|
|
88 |
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
95 |
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
response = f"An error occurred: {str(e)}"
|
102 |
-
|
103 |
-
return history, history, state
|
104 |
-
|
105 |
-
# Load pre-trained model and tokenizer for sentiment analysis
|
106 |
-
tokenizer = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
|
107 |
-
sentiment_model = AutoModelForSequenceClassification.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
|
108 |
|
109 |
# Function for sentiment analysis
|
110 |
def analyze_sentiment(text, state):
|
111 |
-
if state is None:
|
112 |
-
state = {'step': 1}
|
113 |
-
|
114 |
inputs = tokenizer(text, return_tensors="pt")
|
115 |
with torch.no_grad():
|
116 |
outputs = sentiment_model(**inputs)
|
@@ -129,10 +64,6 @@ def analyze_sentiment(text, state):
|
|
129 |
state['step'] = 3 # Move to emotion detection and suggestions
|
130 |
return sentiment_with_emoji, state
|
131 |
|
132 |
-
# Load pre-trained model and tokenizer for emotion detection
|
133 |
-
emotion_tokenizer = AutoTokenizer.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
|
134 |
-
emotion_model = AutoModelForSequenceClassification.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
|
135 |
-
|
136 |
# Function for emotion detection and suggestions
|
137 |
def detect_emotion(text, state):
|
138 |
pipe = pipeline("text-classification", model=emotion_model, tokenizer=emotion_tokenizer)
|
@@ -194,32 +125,6 @@ def provide_suggestions(emotion):
|
|
194 |
# Ensure we return a message even if no articles/videos are found
|
195 |
return resources.get(emotion, {'message': "Stay calm. 🙂", 'articles': ["[General Wellbeing Tips](https://www.helpguide.org)"], 'videos': []})
|
196 |
|
197 |
-
# Function to fetch wellness professionals based on location
|
198 |
-
def get_wellness_professionals(location):
|
199 |
-
# Use Geocoder to get latitude/longitude from city
|
200 |
-
g = geocoder.osm(location)
|
201 |
-
if g.ok:
|
202 |
-
latitude, longitude = g.latlng
|
203 |
-
google_api_url = f"https://maps.googleapis.com/maps/api/place/nearbysearch/json?location={latitude},{longitude}&radius=5000&type=health&key=YOUR_GOOGLE_API_KEY"
|
204 |
-
|
205 |
-
response = requests.get(google_api_url)
|
206 |
-
data = response.json()
|
207 |
-
|
208 |
-
professionals = []
|
209 |
-
if 'results' in data:
|
210 |
-
for place in data['results']:
|
211 |
-
name = place['name']
|
212 |
-
address = place.get('vicinity', 'No address available')
|
213 |
-
url = place.get('website', '#')
|
214 |
-
professionals.append(f"**{name}** - {address} - [Visit Website]({url})")
|
215 |
-
|
216 |
-
if not professionals:
|
217 |
-
professionals.append("No wellness professionals found nearby.")
|
218 |
-
|
219 |
-
return "\n".join(professionals)
|
220 |
-
else:
|
221 |
-
return "Couldn't fetch your location. Please make sure you entered a valid location."
|
222 |
-
|
223 |
# Function to ask for location and provide wellness professionals
|
224 |
def search_wellness_professionals(location, state):
|
225 |
professionals = get_wellness_professionals(location)
|
@@ -246,4 +151,4 @@ def create_ui():
|
|
246 |
|
247 |
# Launch Gradio interface
|
248 |
demo = create_ui()
|
249 |
-
demo.launch(debug=True)
|
|
|
1 |
import gradio as gr
|
|
|
|
|
|
|
2 |
import random
|
|
|
|
|
|
|
|
|
|
|
|
|
3 |
import requests
|
4 |
+
from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
5 |
|
6 |
+
# Replace with your Google Maps API and Places API Key
|
7 |
+
GOOGLE_API_KEY = "GOOGLE_API_KEY"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
8 |
|
9 |
+
# Load pre-trained models for sentiment and emotion detection
|
10 |
+
tokenizer = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
|
11 |
+
sentiment_model = AutoModelForSequenceClassification.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
|
12 |
+
emotion_tokenizer = AutoTokenizer.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
|
13 |
+
emotion_model = AutoModelForSequenceClassification.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
14 |
|
15 |
+
# Function to get latitude and longitude from city using Google Maps Geocoding API
|
16 |
+
def get_lat_lng_from_city(city):
|
17 |
+
geocode_url = f"https://maps.googleapis.com/maps/api/geocode/json?address={city}&key={GOOGLE_API_KEY}"
|
18 |
+
response = requests.get(geocode_url)
|
19 |
+
data = response.json()
|
20 |
+
if data["status"] == "OK":
|
21 |
+
lat_lng = data["results"][0]["geometry"]["location"]
|
22 |
+
return lat_lng["lat"], lat_lng["lng"]
|
23 |
+
else:
|
24 |
+
return None, None
|
25 |
|
26 |
+
# Function to get wellness professionals using Google Places API
|
27 |
+
def get_wellness_professionals(location):
|
28 |
+
lat, lng = get_lat_lng_from_city(location)
|
29 |
+
if lat and lng:
|
30 |
+
places_url = f"https://maps.googleapis.com/maps/api/place/nearbysearch/json?location={lat},{lng}&radius=5000&type=health&key={GOOGLE_API_KEY}"
|
31 |
+
response = requests.get(places_url)
|
32 |
+
data = response.json()
|
33 |
+
professionals = []
|
34 |
+
if 'results' in data:
|
35 |
+
for place in data['results']:
|
36 |
+
name = place['name']
|
37 |
+
address = place.get('vicinity', 'No address available')
|
38 |
+
url = place.get('website', '#')
|
39 |
+
professionals.append(f"**{name}** - {address} - [Visit Website]({url})")
|
40 |
|
41 |
+
if not professionals:
|
42 |
+
professionals.append("No wellness professionals found nearby.")
|
43 |
+
return "\n".join(professionals)
|
44 |
+
else:
|
45 |
+
return "Couldn't fetch your location. Please make sure you entered a valid location."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
46 |
|
47 |
# Function for sentiment analysis
|
48 |
def analyze_sentiment(text, state):
|
|
|
|
|
|
|
49 |
inputs = tokenizer(text, return_tensors="pt")
|
50 |
with torch.no_grad():
|
51 |
outputs = sentiment_model(**inputs)
|
|
|
64 |
state['step'] = 3 # Move to emotion detection and suggestions
|
65 |
return sentiment_with_emoji, state
|
66 |
|
|
|
|
|
|
|
|
|
67 |
# Function for emotion detection and suggestions
|
68 |
def detect_emotion(text, state):
|
69 |
pipe = pipeline("text-classification", model=emotion_model, tokenizer=emotion_tokenizer)
|
|
|
125 |
# Ensure we return a message even if no articles/videos are found
|
126 |
return resources.get(emotion, {'message': "Stay calm. 🙂", 'articles': ["[General Wellbeing Tips](https://www.helpguide.org)"], 'videos': []})
|
127 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
128 |
# Function to ask for location and provide wellness professionals
|
129 |
def search_wellness_professionals(location, state):
|
130 |
professionals = get_wellness_professionals(location)
|
|
|
151 |
|
152 |
# Launch Gradio interface
|
153 |
demo = create_ui()
|
154 |
+
demo.launch(debug=True)
|