-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
379 lines (285 loc) · 12.8 KB
/
app.py
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 25 09:20:13 2023
@author: piku
"""
import joblib
from flask import Flask, render_template, redirect, url_for, request
from flask_bootstrap import Bootstrap
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField
from wtforms.validators import InputRequired, Email, Length
from flask_sqlalchemy import SQLAlchemy
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user
import pandas as pd
import pickle
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
import nltk
from nltk.stem import WordNetLemmatizer
lemmatizer = WordNetLemmatizer()
from keras.models import load_model
model2 = load_model('C:\\Users\\piku\\OneDrive\\Desktop\\ROCKY_PI\\Disease Diagnosis System cloud\\Disease Diagnosis\\model.h5')
import json
import random
intents = json.loads(open('C:\\Users\\piku\\OneDrive\\Desktop\\ROCKY_PI\\Disease Diagnosis System cloud\\Disease Diagnosis\\data.json').read())
words = pickle.load(open('C:\\Users\\piku\\OneDrive\\Desktop\\ROCKY_PI\\Disease Diagnosis System cloud\\Disease Diagnosis\\texts.pkl','rb'))
classes = pickle.load(open('C:\\Users\\piku\\OneDrive\\Desktop\\ROCKY_PI\\Disease Diagnosis System cloud\\Disease Diagnosis\\labels.pkl','rb'))
###############################################################################
filename = 'diabetes-prediction-rfc-model.pkl'
classifier = pickle.load(open(filename, 'rb'))
model = pickle.load(open('model.pkl', 'rb'))
model1 = pickle.load(open('model1.pkl', 'rb'))
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///C:/Users/piku/OneDrive/Desktop/ROCKY_PI/Disease Diagnosis System cloud/Disease Diagnosis/database.db'
bootstrap = Bootstrap(app)
db = SQLAlchemy(app)
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'
class User(UserMixin, db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(15), unique=True)
email = db.Column(db.String(50), unique=True)
password = db.Column(db.String(80))
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
class LoginForm(FlaskForm):
username = StringField('Username', validators=[InputRequired(), Length(min=4, max=15)])
password = PasswordField('Password', validators=[InputRequired(), Length(min=8, max=80)])
remember = BooleanField('remember me')
class RegisterForm(FlaskForm):
email = StringField('Email', validators=[InputRequired(), Email(message='Invalid email'), Length(max=50)])
username = StringField('Username', validators=[InputRequired(), Length(min=4, max=15)])
password = PasswordField('Password', validators=[InputRequired(), Length(min=8, max=80)])
@app.route('/')
def index():
return render_template("index.html")
@app.route('/about')
def about():
return render_template("about.html")
@app.route('/help')
def help():
return render_template("help.html")
@app.route('/terms')
def terms():
return render_template("tc.html")
@app.route('/login', methods=['GET', 'POST'])
def login():
form = LoginForm()
if form.validate_on_submit():
user = User.query.filter_by(username=form.username.data).first()
if user:
if check_password_hash(user.password, form.password.data):
login_user(user, remember=form.remember.data)
return redirect(url_for('dashboard'))
return render_template("login.html", form=form)
return render_template("login.html", form=form)
@app.route('/signup', methods=['GET', 'POST'])
def signup():
form = RegisterForm()
if form.validate_on_submit():
hashed_password = generate_password_hash(form.password.data, method='sha256')
new_user = User(username=form.username.data, email=form.email.data, password=hashed_password)
db.session.add(new_user)
db.session.commit()
return redirect("/login")
return render_template('signup.html', form=form)
@app.route("/dashboard")
@login_required
def dashboard():
return render_template("dashboard.html")
@app.route("/disindex")
def disindex():
return render_template("disindex.html")
@app.route('/chatbot')
@login_required
def chatbot():
return render_template("chatbot.html")
@app.route("/get")
def get_bot_response():
userText = request.args.get('msg')
return chatbot_response(userText)
@app.route("/cancer")
@login_required
def cancer():
return render_template("cancer.html")
@app.route("/diabetes")
@login_required
def diabetes():
return render_template("diabetes.html")
@app.route("/heart")
@login_required
def heart():
return render_template("heart.html")
@app.route("/kidney")
@login_required
def kidney():
return render_template("kidney.html")
def ValuePredictor(to_predict_list, size):
to_predict = np.array(to_predict_list).reshape(1, size)
if size == 7:
loaded_model = joblib.load('kidney_model.pkl')
result = loaded_model.predict(to_predict)
return result[0]
@app.route("/predictkidney", methods=['GET', 'POST'])
def predictkidney():
if request.method == "POST":
to_predict_list = request.form.to_dict()
to_predict_list = list(to_predict_list.values())
to_predict_list = list(map(float, to_predict_list))
if len(to_predict_list) == 7:
result = ValuePredictor(to_predict_list, 7)
if(int(result) == 1):
prediction = "Patient has a high risk of Kidney Disease, please consult your doctor immediately"
else:
prediction = "Patient has a low risk of Kidney Disease"
return render_template("kidney_result.html", prediction_text=prediction)
@app.route("/liver")
@login_required
def liver():
return render_template("liver.html")
def ValuePred(to_predict_list, size):
to_predict = np.array(to_predict_list).reshape(1,size)
if(size==7):
loaded_model = joblib.load('liver_model.pkl')
result = loaded_model.predict(to_predict)
return result[0]
@app.route('/predictliver', methods=["POST"])
def predictliver():
if request.method == "POST":
to_predict_list = request.form.to_dict()
to_predict_list = list(to_predict_list.values())
to_predict_list = list(map(float, to_predict_list))
if len(to_predict_list) == 7:
result = ValuePred(to_predict_list, 7)
if int(result) == 1:
prediction = "Patient has a high risk of Liver Disease, please consult your doctor immediately"
else:
prediction = "Patient has a low risk of Kidney Disease"
return render_template("liver_result.html", prediction_text=prediction)
@app.route('/logout')
@login_required
def logout():
logout_user()
return redirect(url_for('index'))
@app.route('/predict', methods=['POST'])
def predict():
input_features = [int(x) for x in request.form.values()]
features_value = [np.array(input_features)]
features_name = ['clump_thickness', 'uniform_cell_size', 'uniform_cell_shape', 'marginal_adhesion',
'single_epithelial_size', 'bare_nuclei', 'bland_chromatin', 'normal_nucleoli', 'mitoses']
df = pd.DataFrame(features_value, columns=features_name)
output = model.predict(df)
if output == 4:
res_val = "a high risk of Breast Cancer"
else:
res_val = "a low risk of Breast Cancer"
return render_template('cancer_result.html', prediction_text='Patient has {}'.format(res_val))
##################################################################################
df1 = pd.read_csv('diabetes.csv')
# Renaming DiabetesPedigreeFunction as DPF
df1 = df1.rename(columns={'DiabetesPedigreeFunction': 'DPF'})
# Replacing the 0 values from ['Glucose','BloodPressure','SkinThickness','Insulin','BMI'] by NaN
df_copy = df1.copy(deep=True)
df_copy[['Glucose', 'BloodPressure', 'SkinThickness', 'Insulin', 'BMI']] = df_copy[['Glucose', 'BloodPressure',
'SkinThickness', 'Insulin',
'BMI']].replace(0, np.NaN)
# Replacing NaN value by mean, median depending upon distribution
df_copy['Glucose'].fillna(df_copy['Glucose'].mean(), inplace=True)
df_copy['BloodPressure'].fillna(df_copy['BloodPressure'].mean(), inplace=True)
df_copy['SkinThickness'].fillna(df_copy['SkinThickness'].median(), inplace=True)
df_copy['Insulin'].fillna(df_copy['Insulin'].median(), inplace=True)
df_copy['BMI'].fillna(df_copy['BMI'].median(), inplace=True)
# Model Building
X = df1.drop(columns='Outcome')
y = df1['Outcome']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state=0)
# Creating Random Forest Model
classifier = RandomForestClassifier(n_estimators=20)
classifier.fit(X_train, y_train)
# Creating a pickle file for the classifier
filename = 'diabetes-prediction-rfc-model.pkl'
pickle.dump(classifier, open(filename, 'wb'))
#####################################################################
@app.route('/predictt', methods=['POST'])
def predictt():
if request.method == 'POST':
preg = request.form['pregnancies']
glucose = request.form['glucose']
bp = request.form['bloodpressure']
st = request.form['skinthickness']
insulin = request.form['insulin']
bmi = request.form['bmi']
dpf = request.form['dpf']
age = request.form['age']
data = np.array([[preg, glucose, bp, st, insulin, bmi, dpf, age]])
my_prediction = classifier.predict(data)
return render_template('diab_result.html', prediction=my_prediction)
############################################################################################################
@app.route('/predictheart', methods=['POST'])
def predictheart():
input_features = [float(x) for x in request.form.values()]
features_value = [np.array(input_features)]
features_name = ["age", "trestbps", "chol", "thalach", "oldpeak", "sex_0",
" sex_1", "cp_0", "cp_1", "cp_2", "cp_3", " fbs_0",
"restecg_0", "restecg_1", "restecg_2", "exang_0", "exang_1",
"slope_0", "slope_1", "slope_2", "ca_0", "ca_1", "ca_2", "thal_1",
"thal_2", "thal_3"]
df = pd.DataFrame(features_value, columns=features_name)
output = model1.predict(df)
if output == 1:
res_val = "a high risk of Heart Disease"
else:
res_val = "a low risk of Heart Disease"
return render_template('heart_result.html', prediction_text='Patient has {}'.format(res_val))
def clean_up_sentence(sentence):
# tokenize the pattern - split words into array
sentence_words = nltk.word_tokenize(sentence)
# stem each word - create short form for word
sentence_words = [lemmatizer.lemmatize(word.lower()) for word in sentence_words]
return sentence_words
# return bag of words array: 0 or 1 for each word in the bag that exists in the sentence
def bow(sentence, words, show_details=True):
# tokenize the pattern
sentence_words = clean_up_sentence(sentence)
# bag of words - matrix of N words, vocabulary matrix
bag = [0]*len(words)
for s in sentence_words:
for i,w in enumerate(words):
if w == s:
# assign 1 if current word is in the vocabulary position
bag[i] = 1
if show_details:
print ("found in bag: %s" % w)
return(np.array(bag))
def predict_class(sentence, model2):
# filter out predictions below a threshold
p = bow(sentence, words,show_details=False)
res = model2.predict(np.array([p]))[0]
ERROR_THRESHOLD = 0.25
results = [[i,r] for i,r in enumerate(res) if r>ERROR_THRESHOLD]
# sort by strength of probability
results.sort(key=lambda x: x[1], reverse=True)
return_list = []
for r in results:
return_list.append({"intent": classes[r[0]], "probability": str(r[1])})
return return_list
def getResponse(ints, intents_json):
tag = ints[0]['intent']
list_of_intents = intents_json['intents']
for i in list_of_intents:
if(i['tag']== tag):
result = random.choice(i['responses'])
break
return result
def chatbot_response(msg):
ints = predict_class(msg, model2)
res = getResponse(ints, intents)
return res
if __name__ == "__main__":
app.run()