tahirsher's picture
Update app.py
f9f5c08 verified
raw
history blame
2.85 kB
import nltk
import numpy as np
import tflearn
import tensorflow
import random
import json
import pickle
import gradio as gr
from nltk.tokenize import word_tokenize
from nltk.stem.lancaster import LancasterStemmer
# 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
# Gradio interface
chatbot = gr.Chatbot(label="Chat")
demo = gr.Interface(
chat,
[gr.Textbox(lines=1, label="Message"), "state"],
[chatbot, "state"],
allow_flagging="never",
title="Wellbeing for All, ** I am your Best Friend **",
)
# Launch Gradio interface
if __name__ == "__main__":
demo.launch()