| | import os |
| | import numpy as np |
| | import tensorflow as tf |
| | from PIL import Image |
| | from io import BytesIO |
| | import base64 |
| |
|
| | |
| | model = tf.keras.models.load_model("MobileNet_model.h5") |
| |
|
| | |
| | class_labels = { |
| | 0: "Fake", |
| | 1: "Low", |
| | 2: "Medium", |
| | 3: "High" |
| | } |
| |
|
| | def preprocess_image(image): |
| | """Preprocess the image for model prediction""" |
| | |
| | image = image.resize((128, 128)) |
| | |
| | |
| | img_array = np.array(image) / 255.0 |
| | |
| | |
| | img_array = np.expand_dims(img_array, axis=0) |
| | return img_array |
| |
|
| | def predict_image(image): |
| | """Make prediction on a single image""" |
| | img_array = preprocess_image(image) |
| | predictions = model.predict(img_array) |
| | predicted_class_idx = np.argmax(predictions) |
| | predicted_class = class_labels[predicted_class_idx] |
| | confidence = float(np.max(predictions)) |
| | |
| | return { |
| | "predicted_class": predicted_class, |
| | "confidence": confidence, |
| | "class_probabilities": {class_labels[i]: float(prob) for i, prob in enumerate(predictions[0])} |
| | } |
| |
|
| | def inference(data): |
| | """ |
| | Inference function for Hugging Face API |
| | |
| | data can be: |
| | - File path (string) |
| | - URL string |
| | - Base64 encoded image |
| | - Raw image bytes |
| | - Dict with image key containing any of the above |
| | """ |
| | |
| | if isinstance(data, dict) and "image" in data: |
| | data = data["image"] |
| | |
| | |
| | if isinstance(data, str) and os.path.isfile(data): |
| | image = Image.open(data) |
| | |
| | |
| | elif isinstance(data, str) and (data.startswith("http://") or data.startswith("https://")): |
| | from urllib.request import urlopen |
| | with urlopen(data) as response: |
| | image_bytes = response.read() |
| | image = Image.open(BytesIO(image_bytes)) |
| | |
| | |
| | elif isinstance(data, str) and data.startswith("data:image"): |
| | base64_data = data.split(",")[1] |
| | image_bytes = base64.b64decode(base64_data) |
| | image = Image.open(BytesIO(image_bytes)) |
| | |
| | |
| | elif isinstance(data, bytes): |
| | image = Image.open(BytesIO(data)) |
| | |
| | |
| | if image.mode == "RGBA": |
| | image = image.convert("RGB") |
| | |
| | |
| | return predict_image(image) |
| |
|
| | |
| | if __name__ == "__main__": |
| | |
| | test_image_path = "path/to/test/image.jpg" |
| | if os.path.exists(test_image_path): |
| | result = inference(test_image_path) |
| | print(f"Predicted class: {result['predicted_class']}") |
| | print(f"Confidence: {result['confidence']:.4f}") |