from flask import Flask,render_template,request
from keras.models import Sequential
from keras.layers import Dense,Activation,Flatten,Dropout
from keras.layers import Conv2D,MaxPooling2D
import keras.backend as K
import numpy as np
import joblib
from matplotlib import pyplot as plt
import os

import cv2

app=Flask(__name__)

#os.remove('static/tumorImages')

def load_brain_tumor_stage_model():

	model=Sequential()

	model.add(Conv2D(256,(3,3),input_shape=(50,50,1)))
	model.add(Activation('relu'))
	model.add(MaxPooling2D(pool_size=(4,4)))
	#The first CNN layer followed by Relu and MaxPooling layers

	model.add(Conv2D(128,(3,3)))
	model.add(Activation('relu'))
	model.add(MaxPooling2D(pool_size=(4,4)))
	#The second convolution layer followed by Relu and MaxPooling layers

	model.add(Flatten())
	model.add(Dropout(0.5))
	#Flatten layer to stack the output convolutions from second convolution layer
	model.add(Dense(32,activation='relu'))
	model.add(Dropout(0.5))
	#Dense layer of 32 neurons
	model.add(Dense(4,activation='softmax'))
	#The Final layer with two outputs for two categories
	model.compile(loss='categorical_crossentropy',optimizer='adam',metrics=['accuracy'])

	model.load_weights('Stage_CNN.h5')

	return model

@app.route('/')
def index():

        results={'accuracy':"",'stage':""}
        return render_template('brain tumor stage.html',result=results)

@app.route('/brain_tumor_stage_predict',methods=['GET', 'POST'])
def brain_tumor_stage_predict():

	stage_dict={0:'Grade I', 1:'Grade Il', 2:'Grade Ill',3:'Grade lV'}

	model=load_brain_tumor_stage_model()

	file = request.files['myFile']
	file_name=file.filename
	file.save(file_name)

	img=cv2.imread(file_name)
	gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
	resized=cv2.resize(gray,(50,50))
	reshaped=resized.reshape(1,50,50,1)

	result=model.predict(reshaped)

	acc=np.max(result,axis=1)[0]
	label=np.argmax(result,axis=1)[0]

	stage=stage_dict[label]

	results={'accuracy':acc,'stage':stage}

	K.clear_session()

	return render_template('brain tumor stage.html',result=results)

@app.route('/growth')
def growth():

	return render_template('brain tumor growth prediction.html')

count=0

@app.route('/predictGrowth',methods=['GET', 'POST'])
def predictGrowth():
	global count
	file = request.files['myFile']
	file_name=file.filename
	file.save(file_name)

	frame=cv2.imread(file_name)
	model=joblib.load('reg_model.sav')

	m=model.coef_[0][0]
	c=model.intercept_[0]
	gray=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
	ret,thresh=cv2.threshold(gray,170,255,cv2.THRESH_BINARY)
	contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
	print('no. contours:',len(contours))
	brainImagePath=" "
	graphPath=" "
	for cnt in contours:
        #cv2.drawContours(frame, [cnt], 0, (0,255,255), 3)
		area=cv2.contourArea(cnt)

		if(area>500 and area<1500):
			print(area)
			x,y,w,h = cv2.boundingRect(cnt)
			img = cv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,0),2)
			cv2.drawContours(frame, [cnt], 0, (0,0,255), 1)

			brainImagePath='static/tumorImages/brain'+str(count)+'.jpg'
			cv2.imwrite(brainImagePath,frame)

			current_date=int((area-c)/m)
			future_dates=np.arange(current_date,current_date+20).reshape(-1,1)
			future_area=model.predict(future_dates)

			plt.title('Tumor Area Prediction for next 20 days')
			plt.plot(future_dates,future_area,"r-o")
			plt.xlabel('Day no.')
			plt.ylabel('Area')
			graphPath='static/tumorImages/graph'+str(count)+'.png'
			plt.savefig(graphPath)
			plt.close()
			
	count=count+1
	return render_template('brain tumor growth prediction.html',brainImagePath=brainImagePath,graphPath=graphPath)
        
app.run(debug=True)
