Swapnilbpatil commited on
Commit
360d140
·
verified ·
1 Parent(s): 68e896c

Rename brain.py to app.py

Browse files
Files changed (1) hide show
  1. brain.py → app.py +130 -120
brain.py → app.py RENAMED
@@ -1,120 +1,130 @@
1
- from flask import Flask, render_template, request, jsonify
2
- import tensorflow as tf
3
- from tensorflow.keras.models import load_model
4
- from tensorflow.keras.preprocessing.image import img_to_array, load_img
5
- import numpy as np
6
- import os
7
- import base64
8
- from io import BytesIO
9
- from PIL import Image
10
-
11
- app = Flask(__name__)
12
-
13
- # Configure upload folder
14
- UPLOAD_FOLDER = 'uploads'
15
- os.makedirs(UPLOAD_FOLDER, exist_ok=True)
16
- app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
17
-
18
- # Load model
19
- model = None
20
-
21
- def load_tumor_model():
22
- global model
23
- try:
24
- model = load_model("brain_tumor_final2.h5")
25
- print("Model loaded successfully!")
26
- return True
27
- except Exception as e:
28
- print(f"Error loading model: {e}")
29
- return False
30
-
31
- # Define class names based on dataset
32
- class_names = ['Glioma', 'Meningioma', 'No tumor', 'Pituitary']
33
-
34
- # Class descriptions for better user understanding
35
- class_descriptions = {
36
- 'Glioma': 'Glioma is a type of tumor that originates in the glial cells of the brain or the spine. Glial cells support nerve cells with energy and nutrients and help maintain the blood-brain barrier.',
37
- 'Meningioma': 'Meningioma is a tumor that forms on membranes that cover the brain and spinal cord just inside the skull. Most meningiomas are benign, though they can cause serious problems.',
38
- 'No tumor': 'No tumor detected in the brain MRI scan.',
39
- 'Pituitary': 'Pituitary tumors are abnormal growths that develop in the pituitary gland. Most are benign (not cancer) and are called pituitary adenomas. They usually don\'t spread to other parts of the body.'
40
- }
41
-
42
- def preprocess_image(image_path):
43
- img = load_img(image_path, target_size=(299, 299))
44
- img_array = img_to_array(img)
45
- img_array = np.expand_dims(img_array, axis=0)
46
- img_array = img_array / 255.0
47
- return img_array
48
-
49
- def get_prediction(image_path):
50
- try:
51
- processed_image = preprocess_image(image_path)
52
- predictions = model.predict(processed_image)
53
- predicted_class = np.argmax(predictions, axis=1)[0]
54
- confidence = float(predictions[0][predicted_class]) * 100
55
-
56
- result = {
57
- 'class_name': class_names[predicted_class],
58
- 'confidence': confidence,
59
- 'description': class_descriptions[class_names[predicted_class]],
60
- 'probabilities': {class_names[i]: float(predictions[0][i]) * 100 for i in range(len(class_names))}
61
- }
62
- return result
63
- except Exception as e:
64
- print(f"Error during prediction: {e}")
65
- return None
66
-
67
- def image_to_base64(image_path):
68
- with Image.open(image_path) as img:
69
- # Resize the image to be displayed
70
- img.thumbnail((400, 400))
71
- buffered = BytesIO()
72
- img.save(buffered, format="JPEG")
73
- img_str = base64.b64encode(buffered.getvalue()).decode()
74
- return img_str
75
-
76
- @app.route('/')
77
- def index():
78
- # Check if model is loaded
79
- global model
80
- if model is None:
81
- load_status = load_tumor_model()
82
- if not load_status:
83
- return render_template('error.html', message="Failed to load brain tumor model.")
84
-
85
- return render_template('index.html')
86
-
87
- @app.route('/upload', methods=['POST'])
88
- def upload():
89
- if 'file' not in request.files:
90
- return jsonify({'error': 'No file part in the request'}), 400
91
-
92
- file = request.files['file']
93
-
94
- if file.filename == '':
95
- return jsonify({'error': 'No file selected'}), 400
96
-
97
- if file:
98
- # Save the file
99
- file_path = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
100
- file.save(file_path)
101
-
102
- # Get prediction
103
- result = get_prediction(file_path)
104
-
105
- if result:
106
- # Convert image to base64 for display
107
- img_base64 = image_to_base64(file_path)
108
- result['image'] = img_base64
109
- return jsonify(result)
110
- else:
111
- return jsonify({'error': 'Prediction failed'}), 500
112
-
113
- @app.route('/about')
114
- def about():
115
- return render_template('about.html')
116
-
117
- if __name__ == '__main__':
118
- # Load model on startup
119
- load_tumor_model()
120
- app.run(debug=True)
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, File, UploadFile, Request, HTTPException
2
+ from fastapi.responses import HTMLResponse
3
+ from fastapi.staticfiles import StaticFiles
4
+ from fastapi.templating import Jinja2Templates
5
+ import tensorflow as tf
6
+ from tensorflow.keras.models import load_model
7
+ from tensorflow.keras.preprocessing.image import img_to_array, load_img
8
+ import numpy as np
9
+ import os
10
+ import base64
11
+ from io import BytesIO
12
+ from PIL import Image
13
+ import shutil
14
+
15
+ app = FastAPI(title="Brain Tumor MRI Detection")
16
+
17
+ # Configure upload folder
18
+ UPLOAD_FOLDER = 'uploads'
19
+ os.makedirs(UPLOAD_FOLDER, exist_ok=True)
20
+
21
+ # Load templates
22
+ templates = Jinja2Templates(directory="templates")
23
+
24
+ # Mount static files directory if needed
25
+ # app.mount("/static", StaticFiles(directory="static"), name="static")
26
+
27
+ # Model and prediction globals
28
+ model = None
29
+
30
+ def load_tumor_model():
31
+ global model
32
+ try:
33
+ model = load_model("brain_tumor_final2.h5")
34
+ print("Model loaded successfully!")
35
+ return True
36
+ except Exception as e:
37
+ print(f"Error loading model: {e}")
38
+ return False
39
+
40
+ # Define class names based on dataset
41
+ class_names = ['Glioma', 'Meningioma', 'No tumor', 'Pituitary']
42
+
43
+ # Class descriptions for better user understanding
44
+ class_descriptions = {
45
+ 'Glioma': 'Glioma is a type of tumor that originates in the glial cells of the brain or the spine. Glial cells support nerve cells with energy and nutrients and help maintain the blood-brain barrier.',
46
+ 'Meningioma': 'Meningioma is a tumor that forms on membranes that cover the brain and spinal cord just inside the skull. Most meningiomas are benign, though they can cause serious problems.',
47
+ 'No tumor': 'No tumor detected in the brain MRI scan.',
48
+ 'Pituitary': 'Pituitary tumors are abnormal growths that develop in the pituitary gland. Most are benign (not cancer) and are called pituitary adenomas. They usually don\'t spread to other parts of the body.'
49
+ }
50
+
51
+ def preprocess_image(image_path):
52
+ img = load_img(image_path, target_size=(299, 299))
53
+ img_array = img_to_array(img)
54
+ img_array = np.expand_dims(img_array, axis=0)
55
+ img_array = img_array / 255.0
56
+ return img_array
57
+
58
+ def get_prediction(image_path):
59
+ try:
60
+ processed_image = preprocess_image(image_path)
61
+ predictions = model.predict(processed_image)
62
+ predicted_class = np.argmax(predictions, axis=1)[0]
63
+ confidence = float(predictions[0][predicted_class]) * 100
64
+
65
+ result = {
66
+ 'class_name': class_names[predicted_class],
67
+ 'confidence': confidence,
68
+ 'description': class_descriptions[class_names[predicted_class]],
69
+ 'probabilities': {class_names[i]: float(predictions[0][i]) * 100 for i in range(len(class_names))}
70
+ }
71
+ return result
72
+ except Exception as e:
73
+ print(f"Error during prediction: {e}")
74
+ return None
75
+
76
+ def image_to_base64(image_path):
77
+ with Image.open(image_path) as img:
78
+ # Resize the image to be displayed
79
+ img.thumbnail((400, 400))
80
+ buffered = BytesIO()
81
+ img.save(buffered, format="JPEG")
82
+ img_str = base64.b64encode(buffered.getvalue()).decode()
83
+ return img_str
84
+
85
+ @app.on_event("startup")
86
+ async def startup_event():
87
+ """Load model on startup"""
88
+ load_tumor_model()
89
+
90
+ @app.get("/", response_class=HTMLResponse)
91
+ async def index(request: Request):
92
+ # Check if model is loaded
93
+ global model
94
+ if model is None:
95
+ load_status = load_tumor_model()
96
+ if not load_status:
97
+ return templates.TemplateResponse("error.html", {"request": request, "message": "Failed to load brain tumor model."})
98
+
99
+ return templates.TemplateResponse("index.html", {"request": request})
100
+
101
+ @app.post("/upload")
102
+ async def upload(file: UploadFile = File(...)):
103
+ if not file:
104
+ raise HTTPException(status_code=400, detail="No file part in the request")
105
+
106
+ if file.filename == "":
107
+ raise HTTPException(status_code=400, detail="No file selected")
108
+
109
+ try:
110
+ # Save the file
111
+ file_path = os.path.join(UPLOAD_FOLDER, file.filename)
112
+ with open(file_path, "wb") as buffer:
113
+ shutil.copyfileobj(file.file, buffer)
114
+
115
+ # Get prediction
116
+ result = get_prediction(file_path)
117
+
118
+ if result:
119
+ # Convert image to base64 for display
120
+ img_base64 = image_to_base64(file_path)
121
+ result['image'] = img_base64
122
+ return result
123
+ else:
124
+ raise HTTPException(status_code=500, detail="Prediction failed")
125
+ except Exception as e:
126
+ raise HTTPException(status_code=500, detail=str(e))
127
+
128
+ @app.get("/about", response_class=HTMLResponse)
129
+ async def about(request: Request):
130
+ return templates.TemplateResponse("about.html", {"request": request})