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="Kidney Disease 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_kidney_model(): global model try: model = load_model("KIDNEY-Diseases.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 = ['Cyst', 'Normal', 'Stone', 'Tumor'] # Class descriptions for better user understanding class_descriptions = { 'Cyst': 'Kidney cysts are fluid-filled sacs that form in the kidneys. Most simple kidney cysts are benign and do not cause symptoms or harm kidney function.', 'Normal': 'No kidney disease detected in the scan.', 'Stone': 'Kidney stones are hard deposits made of minerals and salts that form inside your kidneys. They can cause severe pain, urinary tract infections, and blockages.', 'Tumor': 'Kidney tumors are abnormal growths in the kidney. They can be benign (non-cancerous) or malignant (cancerous) and may affect kidney function.' } def preprocess_image(image_data): """Process image from bytes data instead of file path""" try: img = Image.open(BytesIO(image_data)) img = img.resize((244, 244)) 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 @app.on_event("startup") async def startup_event(): """Load model on startup""" load_kidney_model() @app.get("/", response_class=HTMLResponse) async def index(request: Request): # Check if model is loaded global model if model is None: load_status = load_kidney_model() if not load_status: return templates.TemplateResponse("error.html", {"request": request, "message": "Failed to load kidney disease model."}) return templates.TemplateResponse("index.html", {"request": request}) @app.post("/upload") 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)}") @app.get("/about", response_class=HTMLResponse) async def about(request: Request): return templates.TemplateResponse("about.html", {"request": request}) @app.get("/health") async def health_check(): """Health check endpoint""" return {"status": "healthy", "model_loaded": model is not None}