-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi_dep.py
More file actions
55 lines (41 loc) · 1.7 KB
/
api_dep.py
File metadata and controls
55 lines (41 loc) · 1.7 KB
1
2
3
4
5
6
7
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
import numpy as np
from fastapi import FastAPI, File, UploadFile, HTTPException
from pydantic import BaseModel
from tensorflow.keras.models import load_model
from tensorflow.keras.utils import img_to_array
from PIL import Image
from io import BytesIO
# Load the saved model
model_save_path = r'C:\Users\victor.tablas\OneDrive - United Nations Development Programme\Documents\cnn_pneumonia_model_VGG16.keras'
try:
loaded_model = load_model(model_save_path)
except Exception as e:
print(f"Error loading the model: {e}")
loaded_model = None # Fallback if model fails to load
# Initialize FastAPI app
app = FastAPI()
# Define response model
class PredictionResult(BaseModel):
prediction: float
class_label: str
@app.get("/")
async def read_root():
return {"message": "Pneumonia Detection API"}
@app.post("/predict/", response_model=PredictionResult)
async def predict_image(file: UploadFile = File(...)):
if loaded_model is None:
raise HTTPException(status_code=500, detail="Model not loaded")
try:
contents = await file.read()
image = Image.open(BytesIO(contents)).convert("RGB")
# Preprocess the image
image = image.resize((224, 224))
img_array = img_to_array(image)
img_array = np.expand_dims(img_array, axis=0)
img_array /= 255.0
# Predict
prediction = loaded_model.predict(img_array)[0][0]
class_label = "Pneumonia" if prediction > 0.5 else "Normal"
return PredictionResult(prediction=float(prediction), class_label=class_label)
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error processing image: {e}")