LovnishVerma commited on
Commit
ec882da
·
verified ·
1 Parent(s): e5df06f

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +140 -228
main.py CHANGED
@@ -1,230 +1,142 @@
1
- <!doctype html>
2
- <html lang="en">
3
-
4
- <head>
5
- <!-- Required meta tags -->
6
- <meta charset="utf-8">
7
- <meta name="viewport" content="width=device-width, initial-scale=1">
8
-
9
- <!-- Bootstrap CSS -->
10
- <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
11
- integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">
12
-
13
- <!-- Custom Styles -->
14
- <style type="text/css">
15
- body {
16
- background-image: url(static/bt.png);
17
- background-position: center;
18
- background-size: cover;
19
- font-family: 'Roboto', sans-serif;
20
- margin-top: 40px;
21
- color: #fff;
22
- }
23
-
24
- .navbar {
25
- background-color: #212121 !important;
26
- }
27
-
28
- .navbar-brand {
29
- font-weight: bold;
30
- font-size: 1.5rem;
31
- }
32
-
33
- .regform {
34
- background-color: rgba(0, 0, 0, 0.6);
35
- padding: 20px;
36
- text-align: center;
37
- border-radius: 15px 15px 0 0;
38
- box-shadow: 0 10px 15px rgba(0, 0, 0, 0.5);
39
- margin-top: 20px;
40
- }
41
-
42
- .regform h1 {
43
- font-size: 2rem;
44
- font-weight: bold;
45
- }
46
-
47
- .main-form {
48
- background-color: rgba(0, 0, 0, 0.7);
49
- margin: 20px auto;
50
- padding: 30px;
51
- border-radius: 10px;
52
- max-width: 900px;
53
- }
54
-
55
- .form-group label {
56
- font-size: 1rem;
57
- font-weight: 500;
58
- }
59
-
60
- .form-control {
61
- border-radius: 5px;
62
- box-shadow: none;
63
- border: 2px solid #bbb;
64
- margin-bottom: 15px;
65
- }
66
-
67
- .form-control:focus {
68
- border-color: #5cb85c;
69
- }
70
-
71
- .btn-submit {
72
- background-color: #28a745;
73
- color: white;
74
- font-size: 1.1rem;
75
- padding: 15px 30px;
76
- border-radius: 5px;
77
- border: none;
78
- transition: background-color 0.3s ease;
79
- }
80
-
81
- .btn-submit:hover {
82
- background-color: #218838;
83
- }
84
-
85
- .form-text {
86
- font-size: 0.85rem;
87
- }
88
-
89
- .col-md-6 {
90
- margin-bottom: 15px;
91
- }
92
-
93
- .col-md-6 label,
94
- .col-md-6 input,
95
- .col-md-6 select {
96
- font-size: 1rem;
97
- }
98
-
99
- .footer {
100
- text-align: center;
101
- margin-top: 30px;
102
- font-size: 0.9rem;
103
- color: #ccc;
104
- }
105
-
106
- /* Responsive design */
107
- @media (max-width: 767px) {
108
- .regform h1 {
109
- font-size: 1.6rem;
 
 
 
 
110
  }
111
 
112
- .main-form {
113
- padding: 20px;
114
- }
115
- }
116
- </style>
117
-
118
- <title>Brain Tumor Detection</title>
119
- </head>
120
-
121
- <body>
122
- <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
123
- <div class="container-fluid">
124
- <a class="navbar-brand" href="/">CNN Brain Tumor Detection</a>
125
- <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav"
126
- aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
127
- <span class="navbar-toggler-icon"></span>
128
- </button>
129
- <div class="collapse navbar-collapse" id="navbarNav">
130
- <ul class="navbar-nav ms-auto">
131
- <li class="nav-item">
132
- <a class="nav-link" href="/dbresults">View MongoDB Results</a>
133
- </li>
134
- </ul>
135
- </div>
136
- </div>
137
- </nav>
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>&copy; 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