-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathapp.py
More file actions
73 lines (57 loc) · 2.12 KB
/
Copy pathapp.py
File metadata and controls
73 lines (57 loc) · 2.12 KB
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
import json
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.preprocessing import LabelEncoder
from tensorflow.keras.models import load_model
from flask import Flask, render_template, request
# Load intents from JSON file
file_path = 'C:/Users/Randhir kumar/OneDrive/Desktop/chatbot project/intents.json'
try:
with open(file_path, 'r') as file:
intents_data = json.load(file)
except FileNotFoundError:
print("File not found. Please check the file path.")
except json.JSONDecodeError:
print("Error decoding JSON. Check if the file is properly formatted.")
# Extract patterns and tags
patterns = []
tags = []
for intent in intents_data['intents']:
tag = intent['tag']
for pattern in intent['patterns']:
tags.append(tag)
patterns.append(pattern)
# Tokenize patterns (convert text into a bag-of-words representation)
vectorizer = CountVectorizer()
X = vectorizer.fit_transform(patterns)
# Prepare labels
label_encoder = LabelEncoder()
y = label_encoder.fit_transform(tags)
# Load the trained model
model = load_model('new_chatbot_model.h5')
def predict_tag(message):
# Tokenize user input to match the format used for training
user_input = vectorizer.transform([message])
prediction = model.predict(user_input)
predicted_tag = label_encoder.inverse_transform([np.argmax(prediction)])
return predicted_tag[0]
def get_response(predicted_tag):
for intent in intents_data['intents']:
if intent['tag'] == predicted_tag:
responses = intent['responses']
return np.random.choice(responses)
app = Flask(__name__)
app.static_folder = 'static'
# Define the home route
@app.route("/")
def home():
return render_template("index.html") # This renders your HTML file
# Define the route to get responses from the bot
@app.route("/get")
def get_bot_response():
userText = request.args.get('msg')
predicted_tag = predict_tag(userText)
response = get_response(predicted_tag)
return response
if __name__ == "__main__":
app.run()