-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.py
More file actions
89 lines (63 loc) · 2.09 KB
/
Copy pathapi.py
File metadata and controls
89 lines (63 loc) · 2.09 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import random
import json
import torch
from chatbot_util.model import NeuralNetwork
from chatbot_util.nltk_wrapper import bag_of_words, tokenise
from flask import Flask
from flask import jsonify
from flask_ngrok import run_with_ngrok
import requests
app = Flask(__name__)
run_with_ngrok(app)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
with open('chatbot_util/train.json', 'r') as json_data:
intents = json.load(json_data)
FILE = "chatbot_util/data.pth"
data = torch.load(FILE)
input_size = data["input_size"]
hidden_size = data["hidden_size"]
output_size = data["output_size"]
all_words = data['all_words']
tags = data['tags']
model_state = data["model_state"]
model = NeuralNetwork(input_size, hidden_size, output_size).to(device)
model.load_state_dict(model_state)
model.eval()
@app.route('/')
def greet():
return 'Hoi!'
@app.route('/chatbot/<input_message>')
def index(input_message):
input_message = tokenise(input_message)
X = bag_of_words(input_message, all_words)
X = X.reshape(1, X.shape[0])
X = torch.from_numpy(X).to(device)
output = model(X)
_, predicted = torch.max(output, dim=1)
tag = tags[predicted.item()]
probs = torch.softmax(output, dim=1)
prob = probs[0][predicted.item()]
output_message = ""
if prob.item() > 0.75:
for intent in intents['classes']:
if tag == intent["tag"]:
output_message = random.choice(intent['responses'])
else:
output_message = "Sorry, write in simple words pls"
json_output = dict()
json_output['reply'] = output_message
if output_message == "MEME":
nsfw = True
is_gif = True
url = ""
while nsfw or is_gif:
response = requests.get("https://meme-api.herokuapp.com/gimme")
print(response.json())
nsfw = response.json()['nsfw']
url = response.json()['url']
if url.split('.')[-1] != 'gif':
is_gif = False
json_output['reply'] = str('m:' + url)
return jsonify(json_output)
if __name__ == "__main__":
app.run()