Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import tensorflow as tf
|
| 3 |
+
import numpy as np
|
| 4 |
+
import json
|
| 5 |
+
from tensorflow.keras.applications.efficientnet import preprocess_input
|
| 6 |
+
from tensorflow.keras.preprocessing import image as keras_image
|
| 7 |
+
|
| 8 |
+
# Load Model & Class Indices
|
| 9 |
+
MODEL_PATH = "latest_model%2520%25281%2529.keras"
|
| 10 |
+
CLASS_INDICES_PATH = "class_indices%2525252520%252525252811%2525252529 (1).json"
|
| 11 |
+
FLOWER_INFO_PATH = "flower_info%2525252520%25252525281%2525252529[1].json"
|
| 12 |
+
|
| 13 |
+
def load_model():
|
| 14 |
+
return tf.keras.models.load_model(MODEL_PATH)
|
| 15 |
+
|
| 16 |
+
def load_class_indices():
|
| 17 |
+
with open(CLASS_INDICES_PATH, "r") as f:
|
| 18 |
+
return json.load(f)
|
| 19 |
+
|
| 20 |
+
def load_flower_info():
|
| 21 |
+
with open(FLOWER_INFO_PATH, "r", encoding="utf-8") as f:
|
| 22 |
+
return json.load(f)
|
| 23 |
+
|
| 24 |
+
model = load_model()
|
| 25 |
+
class_indices = load_class_indices()
|
| 26 |
+
flower_info = load_flower_info()
|
| 27 |
+
class_names = list(class_indices.keys())
|
| 28 |
+
|
| 29 |
+
def preprocess_image(pil_image):
|
| 30 |
+
# Convert PIL image to numpy array and preprocess
|
| 31 |
+
img_array = keras_image.img_to_array(pil_image.resize((224, 224)))
|
| 32 |
+
img_array = np.expand_dims(img_array, axis=0)
|
| 33 |
+
return preprocess_input(img_array)
|
| 34 |
+
|
| 35 |
+
def predict_image(pil_image):
|
| 36 |
+
img_array = preprocess_image(pil_image)
|
| 37 |
+
predictions = model.predict(img_array)
|
| 38 |
+
predicted_class = class_names[np.argmax(predictions[0])]
|
| 39 |
+
|
| 40 |
+
info = flower_info.get(predicted_class, "No additional information available.")
|
| 41 |
+
|
| 42 |
+
return f"Identified as: {predicted_class}", info
|
| 43 |
+
|
| 44 |
+
def predict(pil_image):
|
| 45 |
+
return predict_image(pil_image)
|
| 46 |
+
|
| 47 |
+
interface = gr.Interface(
|
| 48 |
+
fn=predict,
|
| 49 |
+
inputs=gr.Image(type="pil"), # Receive image as a PIL object
|
| 50 |
+
outputs=[gr.Textbox(label="Prediction"), gr.Textbox(label="Flower Information")],
|
| 51 |
+
title="Flower Identification App",
|
| 52 |
+
description="Upload an image of a flower to identify it and get care information."
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
if __name__ == "__main__":
|
| 56 |
+
interface.launch()
|