SANJAYV10's picture
Update app.py
2177f90
raw
history blame
1.05 kB
import torch
import fastapi
import numpy as np
from PIL import Image
class TorchTensor(torch.Tensor):
pass
class Prediction:
prediction: TorchTensor
app = fastapi.FastAPI(docs_url="/")
# Load the pre-trained model
pre_trained_model = torch.load('best_model.pth', map_location=torch.device('cpu'))
# Define a function to preprocess the input image
def preprocess_input(input: fastapi.UploadFile):
image = Image.open(input.file)
image = image.resize((224, 224))
input = np.array(image)
input = torch.from_numpy(input).float()
input = input.unsqueeze(0)
return input
# Define an endpoint to make predictions
@app.post("/predict")
async def predict_endpoint(input:fastapi.UploadFile):
"""Make a prediction on an image uploaded by the user."""
# Preprocess the input image
input = preprocess_input(input)
# Make a prediction
prediction = model(input)
predicted_class = prediction.argmax(1).item()
# Return the predicted class in JSON format
return {"prediction": predicted_class}