Spaces:
Sleeping
Sleeping
| import numpy as np | |
| import gradio as gr | |
| import tensorflow as tf # version 2.13.0 | |
| from keras.models import load_model # version matching your TensorFlow | |
| import cv2 | |
| import json | |
| def analyse(img, plant_type): | |
| # Load label_disease.json | |
| with open('data/label_disease.json', 'r') as f: | |
| label_disease = json.load(f) | |
| # Load plant_label_disease.json | |
| with open('data/plant_label_disease.json', 'r') as f: | |
| plant_label_disease = json.load(f) | |
| HEIGHT = 256 | |
| WIDTH = 256 | |
| modelArchitecturePath = 'model/model_architecture.h5' | |
| modelWeightsPath = 'model/model_weights.h5' | |
| # Load the model | |
| dnn_model = load_model(modelArchitecturePath, compile=False) | |
| dnn_model.load_weights(modelWeightsPath) | |
| # Preprocess the image | |
| process_img = cv2.resize(img, (HEIGHT, WIDTH), interpolation=cv2.INTER_LINEAR) | |
| process_img = process_img / 255.0 | |
| process_img = np.expand_dims(process_img, axis=0) | |
| # Predict using the model | |
| y_pred = dnn_model.predict(process_img) | |
| y_pred = y_pred[0] | |
| # Identify predictions | |
| p_id = plant_label_disease[plant_type.lower()][0] | |
| for disease in plant_label_disease[plant_type.lower()]: | |
| if y_pred[disease] > y_pred[p_id]: | |
| p_id = disease | |
| overall_predicted_id = np.argmax(y_pred) | |
| overall_predicted_name = label_disease[str(overall_predicted_id)] | |
| overall_predicted_acc = y_pred[overall_predicted_id] | |
| plant_predicted_id = p_id | |
| plant_predicted_name = label_disease[str(plant_predicted_id)] | |
| plant_predicted_acc = y_pred[plant_predicted_id] | |
| # Return results as a JSON object | |
| result = { | |
| "plant_predicted_id": int(plant_predicted_id), | |
| "plant_predicted_name": plant_predicted_name, | |
| "plant_predicted_accuracy": float(plant_predicted_acc), | |
| "overall_predicted_id": int(overall_predicted_id), | |
| "overall_predicted_name": overall_predicted_name, | |
| "overall_predicted_accuracy": float(overall_predicted_acc), | |
| } | |
| return result | |
| # Gradio interface | |
| demo = gr.Interface( | |
| fn=analyse, | |
| inputs=[ | |
| gr.Image(type="numpy"), | |
| gr.Radio(["Apple", "Blueberry", "Cherry", "Corn", "Grape", "Orange", "Peach", | |
| "Pepper", "Potato", "Raspberry", "Soybean", "Squash", "Strawberry", "Tomato"]) | |
| ], | |
| outputs=gr.JSON() | |
| ) | |
| demo.launch(share=True, show_error=True) | |