Upload handler.py with huggingface_hub
Browse files- handler.py +27 -0
handler.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
import tensorflow as tf
|
| 3 |
+
import numpy as np
|
| 4 |
+
import cv2
|
| 5 |
+
from PIL import Image
|
| 6 |
+
import io
|
| 7 |
+
|
| 8 |
+
class InferenceHandler:
|
| 9 |
+
def __init__(self):
|
| 10 |
+
self.model = tf.saved_model.load("pneumonia_cnn_saved_model")
|
| 11 |
+
self.class_names = ['PNEUMONIA', 'NORMAL']
|
| 12 |
+
self.infer = self.model.signatures['serving_default']
|
| 13 |
+
|
| 14 |
+
def preprocess(self, image):
|
| 15 |
+
img = np.array(image.convert('L')) # Grayscale
|
| 16 |
+
img = cv2.resize(img, (150, 150))
|
| 17 |
+
img = img / 255.0
|
| 18 |
+
img = img.reshape(1, 150, 150, 1).astype(np.float32)
|
| 19 |
+
return img
|
| 20 |
+
|
| 21 |
+
def __call__(self, inputs):
|
| 22 |
+
# inputs: dict with 'image' key (e.g., uploaded image)
|
| 23 |
+
image = Image.open(io.BytesIO(inputs['image']))
|
| 24 |
+
img_array = self.preprocess(image)
|
| 25 |
+
prediction = self.infer(tf.convert_to_tensor(img_array))['dense_1'].numpy()
|
| 26 |
+
class_id = (prediction > 0.5).astype("int32")[0][0]
|
| 27 |
+
return {"prediction": self.class_names[class_id], "probability": float(prediction[0][0])}
|