| 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 |
|
|
| |
| MODEL_PATH = "my_model_k7.pkl" |
| LABELS_PATH = "labels.json" |
|
|
| |
| model_data = joblib.load(MODEL_PATH) |
| clf = model_data["model"] |
| labels = model_data.get("labels", None) |
|
|
| |
| with open(LABELS_PATH, "r") as f: |
| labels = json.load(f) |
|
|
| |
| feature_extractor = MobileNetV2(weights="imagenet", |
| include_top=False, |
| pooling="avg") |
|
|
| def predict(img): |
| |
| img = image.img_to_array(img) |
| img = np.expand_dims(img, axis=0) |
| img = preprocess_input(img) |
|
|
| |
| features = feature_extractor.predict(img) |
|
|
| |
| pred_idx = int(clf.predict(features)[0]) |
| pred_label = labels[str(pred_idx)] if isinstance(labels, dict) else labels[pred_idx] |
|
|
| return pred_label |
|
|
| |
| 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() |
|
|