|
a |
|
b/medic_health_assistant/app.py |
|
|
1 |
from tensorflow.keras.models import load_model |
|
|
2 |
from flask import Flask, jsonify, request |
|
|
3 |
from flask_cors import CORS |
|
|
4 |
import pickle |
|
|
5 |
import numpy as np |
|
|
6 |
import nltk |
|
|
7 |
from nltk import LancasterStemmer |
|
|
8 |
import pandas as pd |
|
|
9 |
|
|
|
10 |
stemmer = LancasterStemmer() |
|
|
11 |
|
|
|
12 |
app = Flask(__name__) |
|
|
13 |
CORS(app) |
|
|
14 |
|
|
|
15 |
model = load_model("chatbot_model.hdf5") |
|
|
16 |
|
|
|
17 |
with open('labels.pkl', 'rb') as f: |
|
|
18 |
labels = pickle.load(f) |
|
|
19 |
|
|
|
20 |
with open('words.pkl', 'rb') as f: |
|
|
21 |
words = pickle.load(f) |
|
|
22 |
|
|
|
23 |
|
|
|
24 |
def clean_up_sentence(sentence): |
|
|
25 |
sentence_words = nltk.word_tokenize(sentence) |
|
|
26 |
sentence_words = [stemmer.stem(word.lower()) for word in sentence_words] |
|
|
27 |
return sentence_words |
|
|
28 |
|
|
|
29 |
def bow(sentence, words, show_details=True): |
|
|
30 |
sentence_words = clean_up_sentence(sentence) |
|
|
31 |
bag = [0]*len(words) |
|
|
32 |
for s in sentence_words: |
|
|
33 |
for i,w in enumerate(words): |
|
|
34 |
if w == s: |
|
|
35 |
bag[i] = 1 |
|
|
36 |
if show_details: |
|
|
37 |
print ("found in bag: %s" % w) |
|
|
38 |
|
|
|
39 |
return(np.array(bag)) |
|
|
40 |
|
|
|
41 |
@app.route('/') |
|
|
42 |
def home_endpoint(): |
|
|
43 |
return 'Hello there, welcome to Team Medic Minds' |
|
|
44 |
|
|
|
45 |
|
|
|
46 |
@app.route('/api/predict', methods=['GET', 'POST']) |
|
|
47 |
def classify(): |
|
|
48 |
ERROR_THRESHOLD = 0.25 |
|
|
49 |
|
|
|
50 |
sentence = request.json['sentence'] |
|
|
51 |
input_data = pd.DataFrame([bow(sentence, words)], dtype=float, index=['input']).to_numpy() |
|
|
52 |
results = model.predict([input_data])[0] |
|
|
53 |
results = [[i, r] for i, r in enumerate(results) if r > ERROR_THRESHOLD] |
|
|
54 |
results.sort(key=lambda x: x[1], reverse=True) |
|
|
55 |
return_list = [] |
|
|
56 |
for r in results: |
|
|
57 |
return_list.append({"intent": labels[r[0]], "probability": str(r[1])}) |
|
|
58 |
|
|
|
59 |
response = jsonify(return_list) |
|
|
60 |
return response |
|
|
61 |
|
|
|
62 |
if __name__ == '__main__': |
|
|
63 |
|
|
|
64 |
app.run(host='0.0.0.0', port=5000) |
|
|
65 |
|
|
|
66 |
|
|
|
67 |
''' |
|
|
68 |
def get_prediction(): |
|
|
69 |
sentence = request.json['sentence'] |
|
|
70 |
|
|
|
71 |
if flask.request.method == 'POST': |
|
|
72 |
data = flask.request.json # Get data posted as a json |
|
|
73 |
if data == None: |
|
|
74 |
data = flask.request.args |
|
|
75 |
|
|
|
76 |
input = data.get('data') |
|
|
77 |
prediction = predictStringInput(chatbot_model,input) |
|
|
78 |
|
|
|
79 |
return prediction |
|
|
80 |
|
|
|
81 |
''' |