import json
import numpy as np
import tensorflow as tf
from tensorflow.keras.applications.mobilenet_v2 import preprocess_input
from PIL import Image

class ImageClassifier:
    def __init__(self, model_path='model/model.keras', class_names_path='model/class_names.json'):
        self.model = tf.keras.models.load_model(model_path)
        with open(class_names_path, 'r') as f:
            self.class_names = json.load(f)

    def predict(self, image_path, top_k=3):
        img = Image.open(image_path).convert('RGB').resize((224, 224))
        arr = np.array(img, dtype=np.float32)
        arr = preprocess_input(arr)
        arr = np.expand_dims(arr, axis=0)

        probs = self.model.predict(arr, verbose=0)[0]
        top_indices = np.argsort(probs)[::-1][:top_k]

        return [
            {'class': self.class_names[i], 'confidence': round(float(probs[i]), 3)}
            for i in top_indices
        ]