Diff of /app.py [000000] .. [32b2c5]

Switch to unified view

a b/app.py
1
import numpy as np  # dealing with arrays
2
import os  # dealing with directories
3
from random import shuffle  # mixing up or currently ordered data that might lead our network astray in training.
4
from tqdm import \
5
    tqdm  # a nice pretty percentage bar for tasks. Thanks to viewer Daniel BA1/4hler for this suggestion
6
import tflearn
7
from tflearn.layers.conv import conv_2d, max_pool_2d
8
from tflearn.layers.core import input_data, dropout, fully_connected
9
from tflearn.layers.estimator import regression
10
import tensorflow as tf
11
import matplotlib.pyplot as plt
12
from flask import Flask, render_template, url_for, request
13
import sqlite3
14
import cv2
15
import shutil
16
17
18
app = Flask(__name__)
19
20
@app.route('/')
21
def index():
22
    return render_template('home.html')
23
24
@app.route('/userlog', methods=['GET', 'POST'])
25
def userlog():
26
    if request.method == 'POST':
27
28
        connection = sqlite3.connect('user_data.db')
29
        cursor = connection.cursor()
30
31
        name = request.form['name']
32
        password = request.form['password']
33
34
        query = "SELECT name, password FROM user WHERE name = '"+name+"' AND password= '"+password+"'"
35
        cursor.execute(query)
36
37
        result = cursor.fetchall()
38
39
        if len(result) == 0:
40
            return render_template('index.html', msg='Sorry, Incorrect Credentials Provided,  Try Again')
41
        else:
42
            return render_template('userlog.html')
43
44
    return render_template('index.html')
45
46
47
@app.route('/userreg', methods=['GET', 'POST'])
48
def userreg():
49
    if request.method == 'POST':
50
51
        connection = sqlite3.connect('user_data.db')
52
        cursor = connection.cursor()
53
54
        name = request.form['name']
55
        password = request.form['password']
56
        mobile = request.form['phone']
57
        email = request.form['email']
58
        
59
        print(name, mobile, email, password)
60
61
        command = """CREATE TABLE IF NOT EXISTS user(name TEXT, password TEXT, mobile TEXT, email TEXT)"""
62
        cursor.execute(command)
63
64
        cursor.execute("INSERT INTO user VALUES ('"+name+"', '"+password+"', '"+mobile+"', '"+email+"')")
65
        connection.commit()
66
67
        return render_template('index.html', msg='Successfully Registered')
68
    
69
    return render_template('index.html')
70
71
@app.route('/image', methods=['GET', 'POST'])
72
def image():
73
    if request.method == 'POST':
74
        
75
                
76
        dirPath = "static/images"
77
        fileList = os.listdir(dirPath)
78
        for fileName in fileList:
79
            os.remove(dirPath + "/" + fileName)
80
        fileName=request.form['filename']
81
        dst = "static/images"
82
        
83
84
        shutil.copy("test\\"+fileName, dst)
85
        
86
        verify_dir = 'static/images'
87
        IMG_SIZE = 50
88
        LR = 1e-3
89
        MODEL_NAME = 'HEMMORRHAGE-{}-{}.model'.format(LR, '2conv-basic')
90
    ##    MODEL_NAME='keras_model.h5'
91
        def process_verify_data():
92
            verifying_data = []
93
            for img in os.listdir(verify_dir):
94
                path = os.path.join(verify_dir, img)
95
                img_num = img.split('.')[0]
96
                img = cv2.imread(path, cv2.IMREAD_COLOR)
97
                img = cv2.resize(img, (IMG_SIZE, IMG_SIZE))
98
                verifying_data.append([np.array(img), img_num])
99
                np.save('verify_data.npy', verifying_data)
100
            return verifying_data
101
102
        verify_data = process_verify_data()
103
        #verify_data = np.load('verify_data.npy')
104
105
        
106
        tf.compat.v1.reset_default_graph()
107
        #tf.reset_default_graph()
108
109
        convnet = input_data(shape=[None, IMG_SIZE, IMG_SIZE, 3], name='input')
110
111
        convnet = conv_2d(convnet, 32, 3, activation='relu')
112
        convnet = max_pool_2d(convnet, 3)
113
114
        convnet = conv_2d(convnet, 64, 3, activation='relu')
115
        convnet = max_pool_2d(convnet, 3)
116
117
        convnet = conv_2d(convnet, 128, 3, activation='relu')
118
        convnet = max_pool_2d(convnet, 3)
119
120
        convnet = conv_2d(convnet, 32, 3, activation='relu')
121
        convnet = max_pool_2d(convnet, 3)
122
123
        convnet = conv_2d(convnet, 64, 3, activation='relu')
124
        convnet = max_pool_2d(convnet, 3)
125
126
        convnet = fully_connected(convnet, 1024, activation='relu')
127
        convnet = dropout(convnet, 0.8)
128
129
        convnet = fully_connected(convnet, 2, activation='softmax')
130
        convnet = regression(convnet, optimizer='adam', learning_rate=LR, loss='categorical_crossentropy', name='targets')
131
132
        model = tflearn.DNN(convnet, tensorboard_dir='log')
133
134
        if os.path.exists('{}.meta'.format(MODEL_NAME)):
135
            model.load(MODEL_NAME)
136
            print('model loaded!')
137
138
139
        accuracy=" "
140
        str_label=" "
141
        for num, data in enumerate(verify_data):
142
143
            img_num = data[1]
144
            img_data = data[0]
145
146
            #y = fig.add_subplot(3, 4, num + 1)
147
            orig = img_data
148
            data = img_data.reshape(IMG_SIZE, IMG_SIZE, 3)
149
            # model_out = model.predict([data])[0]
150
            model_out = model.predict([data])[0]
151
            print(model_out)
152
            print('model {}'.format(np.argmax(model_out)))
153
154
            if np.argmax(model_out) == 0:
155
                str_label = 'HEMORRHAGE'
156
                print("The predicted image of the brain with hemmorrhage detected with a accuracy of {} %".format(model_out[0]*90))
157
                accuracy = "The predicted image of the brain with hemmorrhage detected  with a accuracy of {} %".format(model_out[0]*90)
158
           
159
            elif np.argmax(model_out) == 1:
160
                str_label = 'NORMAL'
161
                print("The predicted image of the brain is normal with a accuracy of {} %".format(model_out[1]*100))
162
                accuracy = "The predicted image of the brain is normal with a accuracy of {} %".format(model_out[1]*100)
163
164
           
165
166
           
167
168
        return render_template('home.html', status=str_label,accuracy=accuracy, ImageDisplay="http://127.0.0.1:5000/static/images/"+fileName)
169
    return render_template('home.html')
170
171
if __name__ == "__main__":
172
173
    app.run(debug=True, use_reloader=False)