Spaces:
Sleeping
Sleeping
Update main.py
Browse files
main.py
CHANGED
@@ -1,230 +1,142 @@
|
|
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 |
-
<div class="regform">
|
140 |
-
<h1>Brain Tumor Detection Form</h1>
|
141 |
-
</div>
|
142 |
-
|
143 |
-
<div class="container">
|
144 |
-
<form action="resultbt" class="main-form needs-validation" method="POST" enctype="multipart/form-data" novalidate>
|
145 |
-
<div class="row">
|
146 |
-
<div class="col-md-6">
|
147 |
-
<div class="form-group">
|
148 |
-
<label for="firstname">First Name</label>
|
149 |
-
<input type="text" name="firstname" id="firstname" class="form-control" required>
|
150 |
-
</div>
|
151 |
-
</div>
|
152 |
-
<div class="col-md-6">
|
153 |
-
<div class="form-group">
|
154 |
-
<label for="lastname">Last Name</label>
|
155 |
-
<input type="text" name="lastname" id="lastname" class="form-control" required>
|
156 |
-
</div>
|
157 |
-
</div>
|
158 |
-
</div>
|
159 |
-
|
160 |
-
<div class="form-group">
|
161 |
-
<label for="phone">Phone Number</label>
|
162 |
-
<input type="tel" name="phone" id="phone" class="form-control" required>
|
163 |
-
<small class="form-text">* Include your area code</small>
|
164 |
-
</div>
|
165 |
-
|
166 |
-
<div class="form-group">
|
167 |
-
<label for="email">Email Address</label>
|
168 |
-
<input type="email" name="email" id="email" class="form-control" required>
|
169 |
-
</div>
|
170 |
-
|
171 |
-
<div class="row">
|
172 |
-
<div class="col-md-6">
|
173 |
-
<div class="form-group">
|
174 |
-
<label for="gender">Gender</label>
|
175 |
-
<select name="gender" id="gender" class="form-control" required>
|
176 |
-
<option value="male">Male</option>
|
177 |
-
<option value="female">Female</option>
|
178 |
-
</select>
|
179 |
-
</div>
|
180 |
-
</div>
|
181 |
-
<div class="col-md-6">
|
182 |
-
<div class="form-group">
|
183 |
-
<label for="age">Age</label>
|
184 |
-
<input type="number" name="age" id="age" class="form-control" required>
|
185 |
-
</div>
|
186 |
-
</div>
|
187 |
-
</div>
|
188 |
-
|
189 |
-
<div class="form-group">
|
190 |
-
<label for="file">Upload Your Brain MRI</label>
|
191 |
-
<input type="file" class="form-control" id="file" name="file" required>
|
192 |
-
</div>
|
193 |
-
|
194 |
-
<div class="text-center">
|
195 |
-
<button type="submit" class="btn-submit">Submit</button>
|
196 |
-
</div>
|
197 |
-
</form>
|
198 |
-
</div>
|
199 |
-
|
200 |
-
<div class="footer">
|
201 |
-
<p>© 2024 Brain Tumor Detection - All Rights Reserved</p>
|
202 |
-
</div>
|
203 |
-
|
204 |
-
<!-- Bootstrap Bundle with Popper -->
|
205 |
-
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
|
206 |
-
integrity="sha384-JEW9xMcG8R+pH31jmWH6WWP0WintQrMb4s7ZOdauHnUtxwoG2vI5DkLtS3qm9Ekf"
|
207 |
-
crossorigin="anonymous"></script>
|
208 |
-
|
209 |
-
<!-- Enable Bootstrap validation -->
|
210 |
-
<script>
|
211 |
-
(function () {
|
212 |
-
'use strict'
|
213 |
-
// Fetch all the forms we want to apply custom Bootstrap validation styles to
|
214 |
-
var forms = document.querySelectorAll('.needs-validation')
|
215 |
-
// Loop over them and prevent submission
|
216 |
-
Array.prototype.slice.call(forms)
|
217 |
-
.forEach(function (form) {
|
218 |
-
form.addEventListener('submit', function (event) {
|
219 |
-
if (!form.checkValidity()) {
|
220 |
-
event.preventDefault()
|
221 |
-
event.stopPropagation()
|
222 |
-
}
|
223 |
-
form.classList.add('was-validated')
|
224 |
-
}, false)
|
225 |
-
})
|
226 |
-
})()
|
227 |
-
</script>
|
228 |
-
</body>
|
229 |
-
|
230 |
-
</html>
|
|
|
1 |
+
from flask import Flask, flash, request, redirect, render_template
|
2 |
+
import os
|
3 |
+
import cv2
|
4 |
+
import imutils
|
5 |
+
import numpy as np
|
6 |
+
from tensorflow.keras.models import load_model
|
7 |
+
from werkzeug.utils import secure_filename
|
8 |
+
import tempfile
|
9 |
+
from pymongo import MongoClient
|
10 |
+
from datetime import datetime
|
11 |
+
|
12 |
+
# Load the Brain Tumor CNN Model
|
13 |
+
braintumor_model = load_model('models/braintumor.h5')
|
14 |
+
|
15 |
+
# Configuring Flask application
|
16 |
+
app = Flask(__name__)
|
17 |
+
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0 # Disable caching for images
|
18 |
+
app.secret_key = "nielitchandigarhpunjabpolice" # Secret key for session management
|
19 |
+
|
20 |
+
# Allowed image file extensions
|
21 |
+
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg'])
|
22 |
+
|
23 |
+
# Connect to MongoDB Atlas
|
24 |
+
client = MongoClient("mongodb+srv://test:test@cluster0.sxci1.mongodb.net/?retryWrites=true&w=majority")
|
25 |
+
db = client['brain_tumor_detection'] # Database name
|
26 |
+
collection = db['predictions'] # Collection name
|
27 |
+
|
28 |
+
def allowed_file(filename):
|
29 |
+
"""Check if the file is a valid image format (png, jpg, jpeg)."""
|
30 |
+
return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
|
31 |
+
|
32 |
+
def preprocess_imgs(set_name, img_size):
|
33 |
+
"""
|
34 |
+
Preprocess images by resizing them to the target size (224x224 for VGG16)
|
35 |
+
and applying appropriate resizing techniques.
|
36 |
+
"""
|
37 |
+
set_new = []
|
38 |
+
for img in set_name:
|
39 |
+
img = cv2.resize(img, dsize=img_size, interpolation=cv2.INTER_CUBIC) # Resize image
|
40 |
+
set_new.append(img)
|
41 |
+
return np.array(set_new)
|
42 |
+
|
43 |
+
def crop_imgs(set_name, add_pixels_value=0):
|
44 |
+
"""
|
45 |
+
Crop the region of interest (ROI) in the image for brain tumor detection.
|
46 |
+
"""
|
47 |
+
set_new = []
|
48 |
+
for img in set_name:
|
49 |
+
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
|
50 |
+
gray = cv2.GaussianBlur(gray, (5, 5), 0)
|
51 |
+
thresh = cv2.threshold(gray, 45, 255, cv2.THRESH_BINARY)[1]
|
52 |
+
thresh = cv2.erode(thresh, None, iterations=2)
|
53 |
+
thresh = cv2.dilate(thresh, None, iterations=2)
|
54 |
+
cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
55 |
+
cnts = imutils.grab_contours(cnts)
|
56 |
+
c = max(cnts, key=cv2.contourArea)
|
57 |
+
extLeft = tuple(c[c[:, :, 0].argmin()][0])
|
58 |
+
extRight = tuple(c[c[:, :, 0].argmax()][0])
|
59 |
+
extTop = tuple(c[c[:, :, 1].argmin()][0])
|
60 |
+
extBot = tuple(c[c[:, :, 1].argmax()][0])
|
61 |
+
ADD_PIXELS = add_pixels_value
|
62 |
+
new_img = img[extTop[1]-ADD_PIXELS:extBot[1]+ADD_PIXELS,
|
63 |
+
extLeft[0]-ADD_PIXELS:extRight[0]+ADD_PIXELS].copy()
|
64 |
+
set_new.append(new_img)
|
65 |
+
return np.array(set_new)
|
66 |
+
|
67 |
+
@app.route('/')
|
68 |
+
def brain_tumor():
|
69 |
+
"""Render the HTML form for the user to upload an image."""
|
70 |
+
return render_template('braintumor.html')
|
71 |
+
|
72 |
+
@app.route('/resultbt', methods=['POST'])
|
73 |
+
def resultbt():
|
74 |
+
"""Process the uploaded image and save prediction results to MongoDB."""
|
75 |
+
if request.method == 'POST':
|
76 |
+
firstname = request.form['firstname']
|
77 |
+
lastname = request.form['lastname']
|
78 |
+
email = request.form['email']
|
79 |
+
phone = request.form['phone']
|
80 |
+
gender = request.form['gender']
|
81 |
+
age = request.form['age']
|
82 |
+
file = request.files['file']
|
83 |
+
|
84 |
+
if file and allowed_file(file.filename):
|
85 |
+
temp_file = tempfile.NamedTemporaryFile(delete=False)
|
86 |
+
filename = secure_filename(file.filename)
|
87 |
+
file.save(temp_file.name)
|
88 |
+
|
89 |
+
flash('Image successfully uploaded and displayed below')
|
90 |
+
|
91 |
+
# Process the image
|
92 |
+
img = cv2.imread(temp_file.name)
|
93 |
+
img = crop_imgs([img])
|
94 |
+
img = img.reshape(img.shape[1:])
|
95 |
+
img = preprocess_imgs([img], (224, 224))
|
96 |
+
|
97 |
+
# Make prediction
|
98 |
+
pred = braintumor_model.predict(img)
|
99 |
+
prediction = 'Tumor Detected' if pred[0][0] >= 0.5 else 'No Tumor Detected'
|
100 |
+
confidence_score = float(pred[0][0])
|
101 |
+
|
102 |
+
# Prepare data for MongoDB
|
103 |
+
result = {
|
104 |
+
"firstname": firstname,
|
105 |
+
"lastname": lastname,
|
106 |
+
"email": email,
|
107 |
+
"phone": phone,
|
108 |
+
"gender": gender,
|
109 |
+
"age": age,
|
110 |
+
"image_name": filename,
|
111 |
+
"prediction": prediction,
|
112 |
+
"confidence_score": confidence_score,
|
113 |
+
"timestamp": datetime.utcnow()
|
114 |
}
|
115 |
|
116 |
+
# Insert data into MongoDB
|
117 |
+
collection.insert_one(result)
|
118 |
+
|
119 |
+
# Return the result to the user
|
120 |
+
return render_template('resultbt.html', filename=filename, fn=firstname, ln=lastname, age=age, r=prediction, gender=gender)
|
121 |
+
else:
|
122 |
+
flash('Allowed image types are - png, jpg, jpeg')
|
123 |
+
return redirect(request.url)
|
124 |
+
|
125 |
+
@app.route('/dbresults')
|
126 |
+
def dbresults():
|
127 |
+
"""Fetch all results from MongoDB and render them in a template."""
|
128 |
+
# Fetch all documents from the MongoDB collection
|
129 |
+
all_results = collection.find() # Returns a cursor
|
130 |
+
|
131 |
+
# Convert cursor to a list of dictionaries
|
132 |
+
results_list = []
|
133 |
+
for result in all_results:
|
134 |
+
result['_id'] = str(result['_id']) # Convert ObjectId to string for JSON serialization
|
135 |
+
results_list.append(result)
|
136 |
+
|
137 |
+
# Pass the results to the HTML template
|
138 |
+
return render_template('dbresults.html', results=results_list)
|
139 |
+
|
140 |
+
|
141 |
+
if __name__ == '__main__':
|
142 |
+
app.run(debug=True) it is saving oposite in database when user had tumor its saving no tumor and vise versa
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|