import gradio as gr import tensorflow as tf from PIL import Image import numpy as np import json # Load class labels with open("class_indices.json", "r") as f: class_labels = json.load(f) # Load model model = tf.keras.models.load_model("best_model.h5") def preprocess(img: Image.Image) -> np.ndarray: img = img.convert("RGB").resize((256, 256)) img = np.array(img) / 255.0 return np.expand_dims(img, axis=0) def predict_disease(image: Image.Image) -> str: try: img = preprocess(image) preds = model.predict(img) idx = np.argmax(preds) label = class_labels[str(idx)] confidence = preds[0][idx] return f"### Prediction Result\n**Disease:** {label}\n**Confidence:** {confidence:.2%}" except Exception as e: return f"Prediction error: {e}" css = """ .gradio-container { max-width: 600px; margin: auto; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; } h1, h3 { color: #2c3e50; } .gr-button { background-color: #27ae60; border-radius: 5px; border: none; color: white; font-weight: bold; } .gr-button:hover { background-color: #219150; } """ interface = gr.Interface( fn=predict_disease, inputs=gr.Image(type="pil", label="Upload a clear image of a tomato leaf"), outputs=gr.Markdown(label="Detection Result"), title="🍅 Tomato Leaf Disease Detector", description="Upload a tomato leaf image to detect diseases with confidence using a trained TensorFlow model.", allow_flagging="never", theme="default", css=css, ) if __name__ == "__main__": interface.launch() # ---------------------------------------------------------------------------------------------------------------------- # import gradio as gr # import tensorflow as tf # from PIL import Image # import numpy as np # import json # # Load class indices from the uploaded file # with open("class_indices.json", "r") as f: # class_indices = json.load(f) # # Load model from local file # model = tf.keras.models.load_model("best_model.h5") # def preprocess_image(image): # # Resize to 256x256 as your model expects # image = image.convert("RGB").resize((256, 256)) # img_array = np.array(image) # # Normalize pixel values between 0 and 1 # img_array = img_array / 255.0 # # Add batch dimension # img_array = np.expand_dims(img_array, axis=0) # return img_array # def predict(image): # try: # img = preprocess_image(image) # preds = model.predict(img) # predicted_index = np.argmax(preds) # predicted_class = class_indices[str(predicted_index)] # confidence = preds[0][predicted_index] # return f"Predicted Disease: **{predicted_class}** with confidence {confidence:.2f}" # except Exception as e: # return f"Error: {str(e)}" # iface = gr.Interface( # fn=predict, # inputs=gr.Image(type="pil", label="Upload Tomato Leaf Image"), # outputs=gr.Markdown(label="Prediction"), # title="Tomato Leaf Disease Detection", # description="Upload a tomato leaf image to detect the disease using a TensorFlow Keras model.", # ) # if __name__ == "__main__": # iface.launch()