Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,35 +1,39 @@
|
|
| 1 |
-
|
| 2 |
-
from fastapi import
|
| 3 |
-
from fastapi.responses import JSONResponse, HTMLResponse
|
| 4 |
from fastapi.staticfiles import StaticFiles
|
| 5 |
from fastapi.templating import Jinja2Templates
|
| 6 |
-
from fastapi.requests import Request
|
| 7 |
-
|
| 8 |
import tensorflow as tf
|
| 9 |
from tensorflow.keras.models import load_model
|
| 10 |
-
from tensorflow.keras.preprocessing.image import img_to_array
|
| 11 |
import numpy as np
|
| 12 |
import os
|
| 13 |
import base64
|
| 14 |
from io import BytesIO
|
| 15 |
from PIL import Image
|
| 16 |
-
import
|
| 17 |
-
import uvicorn
|
| 18 |
|
| 19 |
-
app = FastAPI(title="Kidney Disease Detection"
|
| 20 |
-
description="API for detecting kidney diseases from medical images")
|
| 21 |
|
| 22 |
# Configure upload folder
|
| 23 |
UPLOAD_FOLDER = 'uploads'
|
| 24 |
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
|
| 25 |
|
| 26 |
-
#
|
| 27 |
templates = Jinja2Templates(directory="templates")
|
| 28 |
|
| 29 |
-
|
| 30 |
-
# Global model variable
|
| 31 |
model = None
|
| 32 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
# Define class names based on dataset
|
| 34 |
class_names = ['Cyst', 'Normal', 'Stone', 'Tumor']
|
| 35 |
|
|
@@ -41,29 +45,24 @@ class_descriptions = {
|
|
| 41 |
'Tumor': 'Kidney tumors are abnormal growths in the kidney. They can be benign (non-cancerous) or malignant (cancerous) and may affect kidney function.'
|
| 42 |
}
|
| 43 |
|
| 44 |
-
def
|
| 45 |
-
"""
|
| 46 |
-
global model
|
| 47 |
try:
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
except Exception as e:
|
| 52 |
-
print(f"Error
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
def preprocess_image(image_path):
|
| 56 |
-
"""Preprocess the image for model prediction"""
|
| 57 |
-
img = load_img(image_path, target_size=(244, 244))
|
| 58 |
-
img_array = img_to_array(img)
|
| 59 |
-
img_array = np.expand_dims(img_array, axis=0)
|
| 60 |
-
img_array = img_array / 255.0
|
| 61 |
-
return img_array
|
| 62 |
|
| 63 |
-
def get_prediction(
|
| 64 |
-
"""Get prediction
|
| 65 |
try:
|
| 66 |
-
processed_image = preprocess_image(
|
| 67 |
predictions = model.predict(processed_image)
|
| 68 |
predicted_class = np.argmax(predictions, axis=1)[0]
|
| 69 |
confidence = float(predictions[0][predicted_class]) * 100
|
|
@@ -77,39 +76,38 @@ def get_prediction(image_path):
|
|
| 77 |
return result
|
| 78 |
except Exception as e:
|
| 79 |
print(f"Error during prediction: {e}")
|
| 80 |
-
|
| 81 |
|
| 82 |
-
def image_to_base64(
|
| 83 |
-
"""Convert image to base64
|
| 84 |
-
|
|
|
|
| 85 |
# Resize the image to be displayed
|
| 86 |
img.thumbnail((400, 400))
|
| 87 |
buffered = BytesIO()
|
| 88 |
img.save(buffered, format="JPEG")
|
| 89 |
img_str = base64.b64encode(buffered.getvalue()).decode()
|
| 90 |
return img_str
|
|
|
|
|
|
|
|
|
|
| 91 |
|
| 92 |
@app.on_event("startup")
|
| 93 |
async def startup_event():
|
| 94 |
-
"""Load model
|
| 95 |
load_kidney_model()
|
| 96 |
|
| 97 |
@app.get("/", response_class=HTMLResponse)
|
| 98 |
async def index(request: Request):
|
| 99 |
-
"""Render the main page"""
|
| 100 |
# Check if model is loaded
|
| 101 |
global model
|
| 102 |
if model is None:
|
| 103 |
load_status = load_kidney_model()
|
| 104 |
if not load_status:
|
| 105 |
-
return templates.TemplateResponse(
|
| 106 |
-
"error.html",
|
| 107 |
-
{"request": request, "message": "Failed to load kidney disease model."}
|
| 108 |
-
)
|
| 109 |
|
| 110 |
return templates.TemplateResponse("index.html", {"request": request})
|
| 111 |
|
| 112 |
-
|
| 113 |
@app.post("/upload")
|
| 114 |
async def upload(file: UploadFile = File(...)):
|
| 115 |
"""Process uploaded file and return prediction"""
|
|
@@ -145,12 +143,9 @@ async def upload(file: UploadFile = File(...)):
|
|
| 145 |
|
| 146 |
@app.get("/about", response_class=HTMLResponse)
|
| 147 |
async def about(request: Request):
|
| 148 |
-
"""Render the about page"""
|
| 149 |
return templates.TemplateResponse("about.html", {"request": request})
|
| 150 |
|
| 151 |
-
# Add health check endpoint
|
| 152 |
@app.get("/health")
|
| 153 |
async def health_check():
|
| 154 |
"""Health check endpoint"""
|
| 155 |
-
return {"status": "healthy", "model_loaded": model is not None}
|
| 156 |
-
|
|
|
|
| 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
|
| 8 |
import numpy as np
|
| 9 |
import os
|
| 10 |
import base64
|
| 11 |
from io import BytesIO
|
| 12 |
from PIL import Image
|
| 13 |
+
import uuid
|
|
|
|
| 14 |
|
| 15 |
+
app = FastAPI(title="Kidney Disease 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 |
+
# Model and prediction globals
|
|
|
|
| 25 |
model = None
|
| 26 |
|
| 27 |
+
def load_kidney_model():
|
| 28 |
+
global model
|
| 29 |
+
try:
|
| 30 |
+
model = load_model("KIDNEY-Diseases.h5")
|
| 31 |
+
print("Model loaded successfully!")
|
| 32 |
+
return True
|
| 33 |
+
except Exception as e:
|
| 34 |
+
print(f"Error loading model: {e}")
|
| 35 |
+
return False
|
| 36 |
+
|
| 37 |
# Define class names based on dataset
|
| 38 |
class_names = ['Cyst', 'Normal', 'Stone', 'Tumor']
|
| 39 |
|
|
|
|
| 45 |
'Tumor': 'Kidney tumors are abnormal growths in the kidney. They can be benign (non-cancerous) or malignant (cancerous) and may affect kidney function.'
|
| 46 |
}
|
| 47 |
|
| 48 |
+
def preprocess_image(image_data):
|
| 49 |
+
"""Process image from bytes data instead of file path"""
|
|
|
|
| 50 |
try:
|
| 51 |
+
img = Image.open(BytesIO(image_data))
|
| 52 |
+
img = img.resize((244, 244))
|
| 53 |
+
img = img.convert('RGB') # Ensure 3 channels
|
| 54 |
+
img_array = np.array(img)
|
| 55 |
+
img_array = np.expand_dims(img_array, axis=0)
|
| 56 |
+
img_array = img_array / 255.0
|
| 57 |
+
return img_array
|
| 58 |
except Exception as e:
|
| 59 |
+
print(f"Error preprocessing image: {e}")
|
| 60 |
+
raise
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
|
| 62 |
+
def get_prediction(image_data):
|
| 63 |
+
"""Get prediction using image byte data directly"""
|
| 64 |
try:
|
| 65 |
+
processed_image = preprocess_image(image_data)
|
| 66 |
predictions = model.predict(processed_image)
|
| 67 |
predicted_class = np.argmax(predictions, axis=1)[0]
|
| 68 |
confidence = float(predictions[0][predicted_class]) * 100
|
|
|
|
| 76 |
return result
|
| 77 |
except Exception as e:
|
| 78 |
print(f"Error during prediction: {e}")
|
| 79 |
+
raise
|
| 80 |
|
| 81 |
+
def image_to_base64(image_data):
|
| 82 |
+
"""Convert image bytes to base64 string"""
|
| 83 |
+
try:
|
| 84 |
+
img = Image.open(BytesIO(image_data))
|
| 85 |
# Resize the image to be displayed
|
| 86 |
img.thumbnail((400, 400))
|
| 87 |
buffered = BytesIO()
|
| 88 |
img.save(buffered, format="JPEG")
|
| 89 |
img_str = base64.b64encode(buffered.getvalue()).decode()
|
| 90 |
return img_str
|
| 91 |
+
except Exception as e:
|
| 92 |
+
print(f"Error converting image to base64: {e}")
|
| 93 |
+
raise
|
| 94 |
|
| 95 |
@app.on_event("startup")
|
| 96 |
async def startup_event():
|
| 97 |
+
"""Load model on startup"""
|
| 98 |
load_kidney_model()
|
| 99 |
|
| 100 |
@app.get("/", response_class=HTMLResponse)
|
| 101 |
async def index(request: Request):
|
|
|
|
| 102 |
# Check if model is loaded
|
| 103 |
global model
|
| 104 |
if model is None:
|
| 105 |
load_status = load_kidney_model()
|
| 106 |
if not load_status:
|
| 107 |
+
return templates.TemplateResponse("error.html", {"request": request, "message": "Failed to load kidney disease model."})
|
|
|
|
|
|
|
|
|
|
| 108 |
|
| 109 |
return templates.TemplateResponse("index.html", {"request": request})
|
| 110 |
|
|
|
|
| 111 |
@app.post("/upload")
|
| 112 |
async def upload(file: UploadFile = File(...)):
|
| 113 |
"""Process uploaded file and return prediction"""
|
|
|
|
| 143 |
|
| 144 |
@app.get("/about", response_class=HTMLResponse)
|
| 145 |
async def about(request: Request):
|
|
|
|
| 146 |
return templates.TemplateResponse("about.html", {"request": request})
|
| 147 |
|
|
|
|
| 148 |
@app.get("/health")
|
| 149 |
async def health_check():
|
| 150 |
"""Health check endpoint"""
|
| 151 |
+
return {"status": "healthy", "model_loaded": model is not None}
|
|
|