ml_app / app.py
chris2002's picture
Update app.py
fe25951 verified
Raw History Blame Contribute Delete
3.45 kB
import os
from fastapi import FastAPI, File, UploadFile
from fastapi.responses import JSONResponse
from tensorflow.keras.preprocessing.image import img_to_array
from PIL import Image
import tensorflow as tf
import numpy as np
import io
import tempfile
from ultralytics import YOLO # Make sure ultralytics is installed
# Load YOLO model
yolo_model_path = 'yolo_test.pt'
if not os.path.exists(yolo_model_path):
raise FileNotFoundError(f"YOLO model file not found at {yolo_model_path}")
yolo_model = YOLO(yolo_model_path)
# Load Keras model
keras_model_path = 'Custom_layer.h5'
if not os.path.exists(keras_model_path):
raise FileNotFoundError(f"Keras model file not found at {keras_model_path}")
keras_model = tf.keras.models.load_model(
keras_model_path,
custom_objects={'Precision': tf.keras.metrics.Precision, 'Recall': tf.keras.metrics.Recall}
)
app = FastAPI(title="Leaf Disease Classifier API")
def prepare_image(image, target_size):
if image.mode != "RGB":
image = image.convert("RGB")
image = image.resize(target_size)
image = img_to_array(image)
image = np.expand_dims(image, axis=0)
image = image / 255.0 # Normalize the image
return image
@app.get("/")
async def home():
return {"message": "Welcome to the Leaf Disease Classifier API"}
@app.post("/predict")
async def predict(file: UploadFile = File(...)):
temp_file_path = None
try:
contents = await file.read()
image = Image.open(io.BytesIO(contents))
# Save to a unique temp file for YOLO
with tempfile.NamedTemporaryFile(delete=False, suffix=".jpg") as temp_file:
temp_file.write(contents)
temp_file_path = temp_file.name
except Exception as e:
return JSONResponse(content={"error": str(e)}, status_code=400)
# Run YOLO detection
try:
results = yolo_model.predict(source=temp_file_path, conf=0.4, verbose=False)
boxes = results[0].boxes
mulberry_detected = False
if boxes is not None and len(boxes) > 0:
for box in boxes:
cls_id = int(box.cls[0])
if cls_id == 0: # Assuming class 0 is 'mulberry_leaf'
mulberry_detected = True
break
if not mulberry_detected:
os.remove(temp_file_path)
return JSONResponse(content={"error": "Upload only mulberry leaf!"}, status_code=400)
except Exception as e:
if temp_file_path and os.path.exists(temp_file_path):
os.remove(temp_file_path)
return JSONResponse(content={"error": f"YOLO error: {str(e)}"}, status_code=500)
# Run Keras classifier
try:
image = prepare_image(image, target_size=(224, 224))
prediction = keras_model.predict(image)
class_idx = np.argmax(prediction)
class_names = ['Disease Free leaves', 'Leaf Rust', 'Leaf spot'] # Replace with your actual class names
predicted_class = class_names[class_idx]
confidence = round(100 * (np.max(prediction[0])), 2)
except Exception as e:
if temp_file_path and os.path.exists(temp_file_path):
os.remove(temp_file_path)
return JSONResponse(content={"error": str(e)}, status_code=500)
if temp_file_path and os.path.exists(temp_file_path):
os.remove(temp_file_path)
return {
"predicted_class": predicted_class,
"confidence": f"{confidence}%"
}