File size: 3,446 Bytes
093251c fe25951 093251c ec08773 093251c ec08773 093251c 72c8da2 093251c fe25951 093251c fe25951 093251c ec08773 093251c fe25951 ec08773 fe25951 ec08773 fe25951 ec08773 093251c ec08773 093251c fe25951 093251c fe25951 093251c | 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 86 87 88 89 90 91 92 93 | 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}%"
} |