Spaces:
Runtime error
Runtime error
from fastapi import FastAPI, UploadFile, File | |
from fastapi.responses import JSONResponse | |
import numpy as np | |
import cv2 | |
import pickle | |
from tensorflow.keras.models import load_model | |
from tensorflow.keras.preprocessing.image import img_to_array | |
app = FastAPI() | |
print("app run") | |
# Load the model and the label binarizer | |
model = load_model('cnn_model.h5') | |
print("model loaded") | |
label_binarizer = pickle.load(open('label_transform.pkl', 'rb')) | |
print("labels loaded") | |
# Function to convert images to array | |
def convert_image_to_array(image_dir): | |
try: | |
image = cv2.imdecode(np.frombuffer(image_dir, np.uint8), cv2.IMREAD_COLOR) | |
if image is not None: | |
image = cv2.resize(image, (256, 256)) | |
return img_to_array(image) | |
else: | |
return np.array([]) | |
except Exception as e: | |
print(f"Error : {e}") | |
return None | |
async def predict(file: UploadFile = File(...)): | |
try: | |
# Read the file and convert it to an array | |
image_data = await file.read() | |
image_array = convert_image_to_array(image_data) | |
if image_array.size == 0: | |
return JSONResponse(content={"error": "Invalid image"}, status_code=400) | |
# Normalize the image | |
image_array = np.array(image_array, dtype=np.float16) / 255.0 | |
# Ensure the image_array has the correct shape (1, 256, 256, 3) | |
image_array = np.expand_dims(image_array, axis=0) | |
# Make a prediction | |
prediction = model.predict(image_array) | |
predicted_class = label_binarizer.inverse_transform(prediction)[0] | |
return {"prediction": predicted_class} | |
except Exception as e: | |
return JSONResponse(content={"error": str(e)}, status_code=500) | |
# Add a test GET endpoint to manually trigger the prediction | |
def test_predict(): | |
try: | |
image_path = 'crop_image1.jpg' | |
image = cv2.imread(image_path) | |
image_array = cv2.resize(image, (256, 256)) | |
image_array = img_to_array(image_array) | |
if image_array.size == 0: | |
return JSONResponse(content={"error": "Invalid image"}, status_code=400) | |
# Normalize the image | |
image_array = np.array(image_array, dtype=np.float16) / 255.0 | |
# Ensure the image_array has the correct shape (1, 256, 256, 3) | |
image_array = np.expand_dims(image_array, axis=0) | |
# Make a prediction | |
prediction = model.predict(image_array) | |
predicted_class = label_binarizer.inverse_transform(prediction)[0] | |
return {"prediction": predicted_class} | |
except Exception as e: | |
return JSONResponse(content={"error": str(e)}, status_code=500) | |
if __name__ == "__main__": | |
import uvicorn | |
uvicorn.run(app, host="127.0.0.1", port=8000) | |