import json import pickle import random import nltk import numpy as np import tflearn import gradio as gr import requests import torch import pandas as pd import folium from bs4 import BeautifulSoup from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline from nltk.tokenize import word_tokenize from nltk.stem.lancaster import LancasterStemmer import os # Ensure necessary NLTK resources are downloaded nltk.download('punkt') # Initialize the stemmer stemmer = LancasterStemmer() # Load intents.json try: with open("intents.json") as file: data = json.load(file) except FileNotFoundError: raise FileNotFoundError("Error: 'intents.json' file not found. Ensure it exists in the current directory.") # Load preprocessed data from pickle try: with open("data.pickle", "rb") as f: words, labels, training, output = pickle.load(f) except FileNotFoundError: raise FileNotFoundError("Error: 'data.pickle' file not found. Ensure it exists and matches the model.") # 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) try: model.load("MentalHealthChatBotmodel.tflearn") except FileNotFoundError: raise FileNotFoundError("Error: Trained model file 'MentalHealthChatBotmodel.tflearn' not found.") # 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): 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" def get_lat_lon(location, api_key): params = { "address": location, "key": api_key } response = requests.get(geocode_url, params=params) if response.status_code == 200: result = response.json() if result['status'] == 'OK': # Return the first result's latitude and longitude location = result['results'][0]['geometry']['location'] return location['lat'], location['lng'] return None, 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 # Get the latitude and longitude from the location input 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( location=[lat, lon], popup=f"{name}
{address}", icon=folium.Icon(color='blue', icon='info-sign') ).add_to(m) # Save map as an HTML file map_file = "wellness_map.html" m.save(map_file) # Return the HTML file path to be embedded in Gradio return map_file # Gradio interface setup for user interaction def user_interface(message, location, history, api_key): history, history = chat(message, history) # Sentiment analysis inputs = tokenizer_sentiment(message, return_tensors="pt") outputs = model_sentiment(**inputs) sentiment = ["Negative", "Neutral", "Positive"][torch.argmax(outputs.logits, dim=1).item()] # Emotion detection emotion, resources, video_link = detect_emotion(message) # Get wellness professionals wellness_data = get_wellness_professionals(location, api_key) # Generate the map map_file = generate_map(wellness_data) # Create a DataFrame for the suggestions suggestions_df = pd.DataFrame(resources, columns=["Subject", "Article URL"]) suggestions_df["Video URL"] = video_link # Add video URL column return history, history, sentiment, emotion, resources, video_link, map_file, suggestions_df.to_html(escape=False) # Gradio chatbot interface chatbot = gr.Chatbot(label="Mental Health Chatbot") location_input = gr.Textbox(label="Enter your location (latitude,longitude)", placeholder="e.g., 21.3,-157.8") # Gradio interface definition demo = gr.Interface( user_interface, [gr.Textbox(label="Message"), location_input, "state", "text"], [chatbot, "state", "text", "text", "json", "text", "html", "html"], # Added additional output for the map allow_flagging="never", title="Mental Health & Well-being Assistant" ) # Launch Gradio interface if __name__ == "__main__": demo.launch()