|
from tensorflow.keras.models import load_model
|
|
from tensorflow.keras.preprocessing import image as keras_image
|
|
import numpy as np
|
|
from PIL import Image
|
|
import io
|
|
import os
|
|
import gdown
|
|
|
|
|
|
model_path = 'saved_model_palm_disease.keras'
|
|
|
|
|
|
if not os.path.exists(model_path):
|
|
url = 'https://drive.google.com/uc?id=1g-QPUIsySVm1oBl0KXpKKlxe7x_JPe7B'
|
|
gdown.download(url, model_path, quiet=False)
|
|
|
|
|
|
model = load_model(model_path)
|
|
|
|
|
|
labels = ['Boron Excess', 'Ganoderma', 'Healthy', 'Scale insect']
|
|
|
|
|
|
def preprocess_image(image_bytes):
|
|
img = Image.open(io.BytesIO(image_bytes)).convert("RGB").resize((224, 224))
|
|
img_array = keras_image.img_to_array(img) / 255.0
|
|
img_array = np.expand_dims(img_array, axis=0)
|
|
return img_array
|
|
|
|
|
|
def predict_image(image_bytes):
|
|
img_array = preprocess_image(image_bytes)
|
|
predictions = model.predict(img_array)
|
|
class_index = int(np.argmax(predictions))
|
|
confidence = float(np.max(predictions))
|
|
return {
|
|
'class': labels[class_index],
|
|
'confidence': confidence
|
|
}
|
|
|
|
|
|
def handler(inputs):
|
|
try:
|
|
|
|
image_bytes = inputs['inputs']
|
|
|
|
|
|
if isinstance(image_bytes, str):
|
|
import base64
|
|
image_bytes = base64.b64decode(image_bytes)
|
|
|
|
result = predict_image(image_bytes)
|
|
return result
|
|
|
|
except Exception as e:
|
|
return {"error": str(e)}
|
|
|
|
|