routes

parent fb82b3cc
from flask import render_template, request
from app import app
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import os
import cv2
from pathlib import Path
import pickle
import tensorflow as tf
import sklearn
from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing import image
#### Home Page ####
@app.route('/')
@app.route('/home')
def home():
return render_template('home.html')
#### Lung Cancer Disease ####
@app.route('/lungcancer')
def lungcancer():
return render_template('lungCancer.html')
@app.route('/lungpradict')
def lungpradict():
return render_template('lung_cancer_detection.html')
@app.route('/predictLungCancer', methods=['POST'])
def predictLungCancer():
GENDER = request.form['GENDER']
AGE = request.form['AGE']
SMOKING = request.form['SMOKING']
YELLOW_FINGERS = request.form['YELLOW_FINGERS']
ANXIETY = request.form['ANXIETY']
PEER_PRESSURE = request.form['PEER_PRESSURE']
CHRONICDISEASE = request.form['CHRONICDISEASE']
FATIGUE = request.form['FATIGUE']
ALLERGY = request.form['ALLERGY']
WHEEZING = request.form['WHEEZING']
ALCOHOL = request.form['ALCOHOL']
COUGHING = request.form['COUGHING']
SHORTBREATH = request.form['SHORTBREATH']
SWALLOW = request.form['SWALLOW']
CHESTPAIN = request.form['CHESTPAIN']
with open('models/finalized_model_lung_classification_LR.sav', 'rb') as f:
model = pickle.load(f)
input_data = (GENDER, AGE, SMOKING, YELLOW_FINGERS, ANXIETY, PEER_PRESSURE, CHRONICDISEASE,
FATIGUE, ALLERGY, WHEEZING, ALCOHOL, COUGHING, SHORTBREATH, SWALLOW, CHESTPAIN)
input_data3 = np.array(input_data).astype(int)
input_data_as_numpy_array = np.asarray(input_data3)
input_data_reshaped = input_data_as_numpy_array.reshape(1, -1)
prediction = model.predict(input_data_reshaped)
if (prediction == 1):
result = "You have a lung disease"
disease = 'lung'
return docRec(disease, result, value="lung")
else:
result = "You don't have a lung disease"
return render_template('results.html', result=result)
@app.route('/lungcancerlevel')
def lungcancerlevel():
return render_template('lung_cancer_level_detection.html')
@app.route('/predictLungCancerLevel', methods=['POST'])
def predictLungCancerLevel():
GENDER = request.form['GENDER']
AGE = request.form['AGE']
SMOKING = request.form['SMOKING']
FATIGUE = request.form['FATIGUE']
ALLERGY = request.form['ALLERGY']
WHEEZING = request.form['WHEEZING']
ALCOHOL = request.form['ALCOHOL']
COUGHING = request.form['COUGHING']
SHORTBREATH = request.form['SHORTBREATH']
SWALLOW = request.form['SWALLOW']
CHESTPAIN = request.form['CHESTPAIN']
GENETICRISK = request.form['GENETICRISK']
COUGHINGBLOOD = request.form['COUGHINGBLOOD']
with open('models/finalized_model_lung_cancer_LR_new_level.sav', 'rb') as f:
model = pickle.load(f)
input_data = (AGE, GENDER, ALCOHOL, ALLERGY, GENETICRISK, SMOKING, CHESTPAIN,
COUGHINGBLOOD, FATIGUE, SHORTBREATH, WHEEZING, SWALLOW, COUGHING)
# input_data2 = (1, 69, 0, 1, 0, 1, 1, 1, 1, 1)
# change input data to numpy array
input_data_as_numpy_array = np.asarray(input_data)
# reshape the numpy array as we are predicting for only on instance
input_data_reshaped = input_data_as_numpy_array.reshape(1, -1)
prediction = model.predict(input_data_reshaped)
if (prediction == ['1']):
result = "Your risk is low"
elif (prediction == ['2']):
result = "Your risk is medium"
else:
result = "Your risk is high"
disease = 'lung'
return docRec(disease, result)
@app.route('/lungxray')
def lungxray():
return render_template('lungXray.html')
def predictxray(img):
model = tf.keras.models.load_model('models/lung_disease_model.h5')
pic = []
img = cv2.resize(img, (224, 224))
if img.shape[2] == 1:
img = np.dstack([img, img, img])
img = np.array(img)
img = img/255
# label = to_categorical(0, num_classes=2)
pic.append(img)
# pic_labels.append(pneu)
pic1 = np.array(pic)
a = model.predict(pic1)
print(a.argmax())
predicts = a.argmax()
predicts
if predicts == 0:
return "Anatomia Normal"
elif predicts == 1:
return "Inflammatory processes (pneumonia)"
elif predicts == 2:
return "Higher density (pleural effusion, atelectatic consolidation, hydrothorax, empyema)"
elif predicts == 3:
return "Lower density (pneumotorax, pneumomediastinum, pneumoperitoneum)"
elif predicts == 4:
return "Obstructive pulmonary diseases (emphysema, bronchopneumonia, bronchiectasis, embolism)"
elif predicts == 5:
return "Degenerative infectious diseases (tuberculosis , sarcoidosis, proteinosis, fibrosis)"
elif predicts == 6:
return "Encapsulated lesions (abscesses, nodules, cysts, tumor masses, metastases)"
elif predicts == 7:
return "Mediastinal changes (pericarditis, arteriovenous malformations, lymph node enlargement)"
else:
return "Chest changes (atelectasis, malformations, agenesis, hypoplasia)"
@app.route('/process_image_lung', methods=['POST'])
def process_image_lung():
if request.method == 'POST':
file = request.files['file']
img_bytes = file.read() # Read image data as bytes
# Convert bytes to OpenCV image
img = cv2.imdecode(np.frombuffer(img_bytes, np.uint8), -1)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # Convert BGR to RGB
result = predictxray(img) # Make prediction using img
disease = 'lung'
return docRec(disease, result)
return 'File uploaded successfully!'
######################### Kidney Disease #########################################
@app.route('/predictKidneypage')
def predictKidneypage():
return render_template('kidney_prediction.html')
@app.route('/kidney')
def kidney():
return render_template('kidney.html')
@app.route('/predictKidney', methods=['POST'])
def predictKidney():
Bp = request.form['bp']
Sg = request.form['sg']
Rbc = request.form['rbc']
Bu = request.form['bu']
Sc = request.form['sc']
Sod = request.form['sod']
Pot = request.form['pot']
Hemo = request.form['hemo']
Wbcc = request.form['wbcc']
Rbcc = request.form['rbcc']
Htn = request.form['htn']
with open('models/finalized_model_kidney_prediction_RF.sav', 'rb') as f:
model = pickle.load(f)
input_data = (Bp, Sg, Rbc, Bu, Sc, Sod, Pot, Hemo, Wbcc, Rbcc, Htn)
# input_data3 = np.array(input_data).astype(int)
input_data_as_numpy_array = np.asarray(input_data)
input_data_reshaped = input_data_as_numpy_array.reshape(1, -1)
prediction = model.predict(input_data_reshaped)
print(input_data)
if (prediction == 1):
disease = "kidney"
result = "You have a chronic kidney disease"
return docRec(disease, result, value="kidney")
else:
result = "You don't have a chronic kidney disease"
return render_template('results.html', result=result)
@app.route('/kidneyDisease')
def kidneyDisease():
return render_template('kidney_detection.html')
def predict(img):
model = tf.keras.models.load_model('models/kidney_detect_model.h5')
pic = []
img = cv2.resize(img, (28, 28))
if img.shape[2] == 1:
img = np.dstack([img, img, img])
img = np.array(img)
img = img/255
# label = to_categorical(0, num_classes=2)
pic.append(img)
# pic_labels.append(pneu)
pic1 = np.array(pic)
a = model.predict(pic1)
print(a.argmax())
predicts = a.argmax()
predicts
if predicts == 0:
return "There is a cyst in the uploaded picture. You are not well"
elif predicts == 1:
return "There is nothing unnatural in the uploaded image. you are fine"
elif predicts == 2:
return "There is a stone in the uploaded picture. You are not well"
else:
return "There is a Tumor in the uploaded picture. You are not well"
@app.route('/process_image_kidney', methods=['POST'])
def process_image_kidney():
if request.method == 'POST':
file = request.files['file']
img_bytes = file.read() # Read image data as bytes
# Convert bytes to OpenCV image
img = cv2.imdecode(np.frombuffer(img_bytes, np.uint8), -1)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # Convert BGR to RGB
prediction = predict(img) # Make prediction using img
disease = "kidney"
return docRec(disease, result=prediction, value="kidney")
return 'File uploaded successfully!'
################################ Skin Cancer ##########################################
@app.route('/skinCancerPage')
def skinCancerPage():
return render_template('skinCancerPage.html')
@app.route('/skincancer')
def skincancer():
return render_template('skincancer.html')
def predict2(img):
model = tf.keras.models.load_model('models/skinmodel.h5')
pic = []
img = cv2.resize(img, (224, 224))
if img.shape[2] == 1:
img = np.dstack([img, img, img])
img = np.array(img)
img = img/255
# label = to_categorical(0, num_classes=2)
pic.append(img)
# pic_labels.append(pneu)
pic1 = np.array(pic)
a = model.predict(pic1)
print(a.argmax())
predicts = a.argmax()
predicts
if predicts == 0:
return "Melanocytic nevi"
elif predicts == 1:
return "Melanoma"
elif predicts == 2:
return "Benign keratosis-like lesions"
elif predicts == 3:
return "Basal cell carcinoma"
elif predicts == 4:
return "Actinic keratoses"
elif predicts == 5:
return "Vascular lesions"
else:
return "Dermatofibroma"
@app.route('/process_image_skin', methods=['POST'])
def process_image_skin():
if request.method == 'POST':
file = request.files['file']
img_bytes = file.read() # Read image data as bytes
# Convert bytes to OpenCV image
img = cv2.imdecode(np.frombuffer(img_bytes, np.uint8), -1)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # Convert BGR to RGB
result = predict2(img) # Make prediction using img
disease = 'skin'
return docRec(disease, result, value="skin")
return 'File uploaded successfully!'
@app.route('/skinTumor')
def skinTumor():
return render_template('skinTumor.html')
@app.route('/tumor', methods=['POST'])
def tumor():
mass_npea = request.form['mass_npea']
size_npear = request.form['size_npear']
malign_ratio = request.form['malign_ratio']
damage_size = request.form['damage_size']
exposed_area = request.form['exposed_area']
std_dev_malign = request.form['std_dev_malign']
err_malign = request.form['err_malign']
malign_penalty = request.form['malign_penalty']
damage_ratio = request.form['damage_ratio']
with open('models/finalized_model_skinT_prediction_RF.sav', 'rb') as f:
model = pickle.load(f)
input_data = (mass_npea, size_npear, malign_ratio, damage_size, exposed_area, std_dev_malign, err_malign,
malign_penalty, damage_ratio)
# nput_data3 = np.array(input_data).astype(int)
input_data_as_numpy_array = np.asarray(input_data)
input_data_reshaped = input_data_as_numpy_array.reshape(1, -1)
result = model.predict(input_data_reshaped)
# convert to string with comma-separated values
# convert the numpy array to a string
result = str(result)
# remove the brackets from the string
result = result.replace('[', '').replace(']', '')
result = "Tumor size is "+result+"mm"
# result = ("Predicted result is"+result+"(mm)")
disease = 'skin'
return docRec(disease, result, value="skin")
######################## Stroke ############################
@app.route('/stroke')
def stroke():
return render_template('strokePage.html')
@app.route('/predictStrokepage')
def predictStrokepage():
return render_template('stroke_predict.html')
# predict stroke
@app.route('/predictStroke', methods=['POST'])
def predictStroke():
gender = request.form['gender']
age = request.form['age']
hypertension = request.form['hypertension']
heart_disease = request.form['heart_disease']
ever_married = request.form['ever_married']
work_type = request.form['work_type']
Residence_type = request.form['Residence_type']
avg_glucose_level = request.form['avg_glucose_level']
bmi = request.form['bmi']
smoking_status = request.form['smoking_status']
with open('models/finalized_model_stroke_prediction_RF.sav', 'rb') as f:
model = pickle.load(f)
input_data = (gender, age, hypertension, heart_disease, ever_married,
work_type, Residence_type, avg_glucose_level, bmi, smoking_status)
# input_data3 = np.array(input_data).astype(int)
input_data_as_numpy_array = np.asarray(input_data)
input_data_reshaped = input_data_as_numpy_array.reshape(1, -1)
prediction = model.predict(input_data_reshaped)
print(input_data)
if (prediction == 1):
result = "You are at risk of having a stroke"
else:
result = "You are not at risk of having a stroke"
return render_template('results.html', result=result)
# CT image detection
@app.route('/predictStrokeCt')
def predictStrokeCt():
return render_template('stroke_detection_CT.html')
def predict4(img):
model = tf.keras.models.load_model('models/finalized_model_strokeCT.h5')
# model = load_model('finalized_model_strokeCT.h5')
model = load_model('models/finalized_model_strokeCT.h5')
pic = []
img = cv2.resize(img, (224, 224))
# Convert the image to a numpy array and preprocess it
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x /= 255
# Make a prediction using the model
prediction = model.predict(x)
# Print the predicted class (0 = non-stroke, 1 = stroke)
if prediction < 0.5:
return ('Non-stroke')
else:
return ('Stroke')
@app.route('/process_image_stroke', methods=['POST'])
def process_image_stroke():
if request.method == 'POST':
file = request.files['file']
img_bytes = file.read() # Read image data as bytes
# Convert bytes to OpenCV image
img = cv2.imdecode(np.frombuffer(img_bytes, np.uint8), -1)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # Convert BGR to RGB
prediction = predict4(img) # Make prediction using img
return render_template('results.html', result=prediction)
return 'File uploaded successfully!'
def docRec(disease, result, value):
df = pd.read_excel('docs\RELEVANTDOCTORS.xlsx')
# find rows that contain a keyword in a specific column
keyword = str(disease)
column_name = 'Disease'
rec = df[df[column_name].str.contains(keyword)]
rec = rec.iloc[:, 1:]
table_classes = 'table table-striped table-bordered table-hover'
if value == "lung":
show_button = True
# render the output in a table format
return render_template('results.html', rec=rec.to_html(index=False, classes=table_classes), result=result, show_button=show_button)
else:
show_button = False
return render_template('results.html', rec=rec.to_html(index=False, classes=table_classes), result=result, show_button=show_button)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment