Spaces:
Sleeping
Sleeping
Rename brain.py to app.py
Browse files- brain.py → app.py +130 -120
brain.py → app.py
RENAMED
|
@@ -1,120 +1,130 @@
|
|
| 1 |
-
from
|
| 2 |
-
|
| 3 |
-
from
|
| 4 |
-
from
|
| 5 |
-
import
|
| 6 |
-
import
|
| 7 |
-
import
|
| 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 |
-
return
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
if
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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})
|