File size: 2,805 Bytes
6425b49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3c00005
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
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

@app.post("/predict")
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
@app.get("/test-predict")
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)