File size: 1,705 Bytes
1307a08
67e8993
2755336
67e8993
2755336
 
 
67e8993
 
 
 
2755336
 
67e8993
 
 
 
 
 
2755336
 
67e8993
 
 
 
2755336
 
 
 
 
 
 
 
67e8993
2755336
67e8993
 
 
2755336
 
 
 
67e8993
2755336
67e8993
 
2755336
67e8993
2755336
c1cad17
 
67e8993
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
import joblib
import json
import numpy as np
import gradio as gr
from tensorflow.keras.applications import MobileNetV2
from tensorflow.keras.applications.mobilenet_v2 import preprocess_input
from tensorflow.keras.preprocessing import image

# --- Paths to your model and labels ---
MODEL_PATH = "my_model_k7.pkl"
LABELS_PATH = "labels.json"

# --- Load model and labels ---
model_data = joblib.load(MODEL_PATH)      # this is a dict with model + labels
clf = model_data["model"]                 # your KNN classifier
labels = model_data.get("labels", None)   # try to load labels from inside dict

# If labels are stored separately, override
with open(LABELS_PATH, "r") as f:
    labels = json.load(f)

# --- Feature extractor (MobileNetV2 embeddings) ---
feature_extractor = MobileNetV2(weights="imagenet",
                                include_top=False,
                                pooling="avg")

def predict(img):
    # preprocess image
    img = image.img_to_array(img)
    img = np.expand_dims(img, axis=0)
    img = preprocess_input(img)

    # extract features
    features = feature_extractor.predict(img)

    # run through classifier
    pred_idx = int(clf.predict(features)[0])
    pred_label = labels[str(pred_idx)] if isinstance(labels, dict) else labels[pred_idx]

    return pred_label

# --- Gradio UI ---
iface = gr.Interface(
    fn=predict,
    inputs=gr.Image(type="pil", label="Upload plant image"),
    outputs=gr.Label(num_top_classes=1, label="Predicted class"),
    title="🌿 UAE Flora Classifier",
    description="Upload a plant photo and I’ll predict the species using a KNN classifier over MobileNetV2 embeddings."
)

if __name__ == "__main__":
    iface.launch()