Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from fastapi import FastAPI, UploadFile, File
|
2 |
+
from keras.models import load_model
|
3 |
+
from PIL import Image
|
4 |
+
import numpy as np
|
5 |
+
import cv2
|
6 |
+
|
7 |
+
app = FastAPI()
|
8 |
+
|
9 |
+
# Load the model
|
10 |
+
model = load_model('model1.h5')
|
11 |
+
|
12 |
+
# Define the target size for the images
|
13 |
+
target_size = (256, 256)
|
14 |
+
|
15 |
+
# Define a function to preprocess the uploaded image
|
16 |
+
def preprocess_image(image):
|
17 |
+
# Convert the image to RGB
|
18 |
+
image = image.convert('RGB')
|
19 |
+
# Resize the image
|
20 |
+
img = np.array(image)
|
21 |
+
resized_img = cv2.resize(img, target_size)
|
22 |
+
resized_img = resized_img / 255.0
|
23 |
+
return np.expand_dims(resized_img, axis=0)
|
24 |
+
|
25 |
+
# Define the class names (adjust based on your model's classes)
|
26 |
+
class_names = ['Blight', 'Healthy', 'Gray Leaf Spot', 'Common Rust']
|
27 |
+
|
28 |
+
@app.post("/predict/")
|
29 |
+
async def predict(file: UploadFile = File(...)):
|
30 |
+
# Read the image
|
31 |
+
image = Image.open(file.file)
|
32 |
+
|
33 |
+
# Preprocess the image
|
34 |
+
processed_image = preprocess_image(image)
|
35 |
+
|
36 |
+
# Make predictions
|
37 |
+
predictions = model.predict(processed_image)[0]
|
38 |
+
|
39 |
+
# Interpret the predictions
|
40 |
+
predicted_class = class_names[np.argmax(predictions)]
|
41 |
+
confidence = np.max(predictions)
|
42 |
+
|
43 |
+
return {
|
44 |
+
"prediction": predicted_class,
|
45 |
+
"confidence": confidence,
|
46 |
+
"raw_predictions": {class_name: float(predictions[i]) for i, class_name in enumerate(class_names)}
|
47 |
+
}
|