Spaces:
Sleeping
Sleeping
Download app.py from Swapnilbpatil/brain: direct link, hf CLI and curl.
- Browser
- Download file 5.31 kB
-
https://huggingface.co/spaces/Swapnilbpatil/brain/resolve/main/app.py
- Command line
-
hf download hf://spaces/Swapnilbpatil/brain/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Swapnilbpatil/brain/resolve/main/app.py
5.31 kB
| from fastapi import FastAPI, File, UploadFile, Request, HTTPException | |
| from fastapi.responses import HTMLResponse | |
| from fastapi.staticfiles import StaticFiles | |
| from fastapi.templating import Jinja2Templates | |
| import tensorflow as tf | |
| from tensorflow.keras.models import load_model | |
| from tensorflow.keras.preprocessing.image import img_to_array | |
| import numpy as np | |
| import os | |
| import base64 | |
| from io import BytesIO | |
| from PIL import Image | |
| import uuid | |
| app = FastAPI(title="Brain Tumor MRI Detection") | |
| # Configure upload folder | |
| UPLOAD_FOLDER = 'uploads' | |
| os.makedirs(UPLOAD_FOLDER, exist_ok=True) | |
| # Load templates | |
| templates = Jinja2Templates(directory="templates") | |
| # Model and prediction globals | |
| model = None | |
| def load_tumor_model(): | |
| global model | |
| try: | |
| model = load_model("brain_tumor_final2.h5") | |
| print("Model loaded successfully!") | |
| return True | |
| except Exception as e: | |
| print(f"Error loading model: {e}") | |
| return False | |
| # Define class names based on dataset | |
| class_names = ['Glioma', 'Meningioma', 'No tumor', 'Pituitary'] | |
| # Class descriptions for better user understanding | |
| class_descriptions = { | |
| '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.', | |
| '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.', | |
| 'No tumor': 'No tumor detected in the brain MRI scan.', | |
| '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.' | |
| } | |
| def preprocess_image(image_data): | |
| """Process image from bytes data instead of file path""" | |
| try: | |
| img = Image.open(BytesIO(image_data)) | |
| img = img.resize((299, 299)) | |
| img = img.convert('RGB') # Ensure 3 channels | |
| img_array = np.array(img) | |
| img_array = np.expand_dims(img_array, axis=0) | |
| img_array = img_array / 255.0 | |
| return img_array | |
| except Exception as e: | |
| print(f"Error preprocessing image: {e}") | |
| raise | |
| def get_prediction(image_data): | |
| """Get prediction using image byte data directly""" | |
| try: | |
| processed_image = preprocess_image(image_data) | |
| predictions = model.predict(processed_image) | |
| predicted_class = np.argmax(predictions, axis=1)[0] | |
| confidence = float(predictions[0][predicted_class]) * 100 | |
| result = { | |
| 'class_name': class_names[predicted_class], | |
| 'confidence': confidence, | |
| 'description': class_descriptions[class_names[predicted_class]], | |
| 'probabilities': {class_names[i]: float(predictions[0][i]) * 100 for i in range(len(class_names))} | |
| } | |
| return result | |
| except Exception as e: | |
| print(f"Error during prediction: {e}") | |
| raise | |
| def image_to_base64(image_data): | |
| """Convert image bytes to base64 string""" | |
| try: | |
| img = Image.open(BytesIO(image_data)) | |
| # Resize the image to be displayed | |
| img.thumbnail((400, 400)) | |
| buffered = BytesIO() | |
| img.save(buffered, format="JPEG") | |
| img_str = base64.b64encode(buffered.getvalue()).decode() | |
| return img_str | |
| except Exception as e: | |
| print(f"Error converting image to base64: {e}") | |
| raise | |
| async def startup_event(): | |
| """Load model on startup""" | |
| load_tumor_model() | |
| async def index(request: Request): | |
| # Check if model is loaded | |
| global model | |
| if model is None: | |
| load_status = load_tumor_model() | |
| if not load_status: | |
| return templates.TemplateResponse("error.html", {"request": request, "message": "Failed to load brain tumor model."}) | |
| return templates.TemplateResponse("index.html", {"request": request}) | |
| async def upload(file: UploadFile = File(...)): | |
| """Process uploaded file and return prediction""" | |
| print(f"Received file: {file.filename}") | |
| if not file: | |
| raise HTTPException(status_code=400, detail="No file part in the request") | |
| if file.filename == "": | |
| raise HTTPException(status_code=400, detail="No file selected") | |
| try: | |
| # Read file content | |
| contents = await file.read() | |
| if not contents: | |
| raise HTTPException(status_code=400, detail="Empty file") | |
| # Get prediction directly from content | |
| result = get_prediction(contents) | |
| if not result: | |
| raise HTTPException(status_code=500, detail="Prediction failed") | |
| # Convert image to base64 for display | |
| img_base64 = image_to_base64(contents) | |
| result['image'] = img_base64 | |
| return result | |
| except Exception as e: | |
| print(f"Upload error: {str(e)}") | |
| raise HTTPException(status_code=500, detail=f"Processing error: {str(e)}") | |
| async def about(request: Request): | |
| return templates.TemplateResponse("about.html", {"request": request}) |