Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, File, UploadFile, HTTPException
|
| 2 |
+
from fastapi.responses import JSONResponse
|
| 3 |
+
from PIL import Image
|
| 4 |
+
import numpy as np
|
| 5 |
+
import cv2
|
| 6 |
+
import tensorflow as tf # Assuming you're using TensorFlow for loading your model
|
| 7 |
+
|
| 8 |
+
app = FastAPI()
|
| 9 |
+
|
| 10 |
+
# Load your model
|
| 11 |
+
model = tf.keras.models.load_model("Brain_tumor_pred_large.h5")
|
| 12 |
+
|
| 13 |
+
def predict_tumor(image: Image.Image):
|
| 14 |
+
# Convert the PIL image to OpenCV format
|
| 15 |
+
opencv_image = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
|
| 16 |
+
img = cv2.resize(opencv_image, (128, 128))
|
| 17 |
+
img = img.reshape(1, 128, 128, 3)
|
| 18 |
+
|
| 19 |
+
# Predict using the model
|
| 20 |
+
predictions = model.predict(img)[0] # Get probabilities for each class
|
| 21 |
+
predicted_class = np.argmax(predictions) # Index of the predicted class
|
| 22 |
+
confidence = predictions[predicted_class] # Confidence of the predicted class
|
| 23 |
+
|
| 24 |
+
# Determine if a tumor is present
|
| 25 |
+
if confidence < 0.20:
|
| 26 |
+
if confidence < 0.10:
|
| 27 |
+
result = "No Tumor"
|
| 28 |
+
confidence = 1.0
|
| 29 |
+
else:
|
| 30 |
+
result = "Uncertain"
|
| 31 |
+
else:
|
| 32 |
+
result = "No Tumor" if predicted_class == 1 else "Tumor Detected"
|
| 33 |
+
|
| 34 |
+
return {"result": result, "confidence": f"{confidence:.2%}"}
|
| 35 |
+
|
| 36 |
+
@app.post("/predict")
|
| 37 |
+
async def predict(upload: UploadFile = File(...)):
|
| 38 |
+
try:
|
| 39 |
+
# Open and process the uploaded image file
|
| 40 |
+
image = Image.open(upload.file)
|
| 41 |
+
result = predict_tumor(image)
|
| 42 |
+
return JSONResponse(content=result)
|
| 43 |
+
except Exception as e:
|
| 44 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 45 |
+
|
| 46 |
+
# To run the FastAPI app, use the following command:
|
| 47 |
+
# uvicorn app:app --reload
|