Apriliaaa commited on
Commit
d73f5de
·
verified ·
1 Parent(s): 56d8f10

Upload inference.py

Browse files
Files changed (1) hide show
  1. inference.py +57 -0
inference.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from tensorflow.keras.models import load_model # type: ignore
2
+ from tensorflow.keras.preprocessing import image as keras_image # type: ignore
3
+ import numpy as np
4
+ from PIL import Image
5
+ import io
6
+ import os
7
+ import gdown
8
+
9
+ # === Path model lokal ===
10
+ model_path = 'saved_model_palm_disease.keras'
11
+
12
+ # === Unduh model dari Google Drive jika belum ada ===
13
+ if not os.path.exists(model_path):
14
+ url = 'https://drive.google.com/uc?id=1g-QPUIsySVm1oBl0KXpKKlxe7x_JPe7B'
15
+ gdown.download(url, model_path, quiet=False)
16
+
17
+ # === Load model hanya sekali ===
18
+ model = load_model(model_path)
19
+
20
+ # === Label urutan class_name (dari training) ===
21
+ labels = ['Boron Excess', 'Ganoderma', 'Healthy', 'Scale insect']
22
+
23
+ # === Fungsi preprocessing gambar ===
24
+ def preprocess_image(image_bytes):
25
+ img = Image.open(io.BytesIO(image_bytes)).convert("RGB").resize((224, 224))
26
+ img_array = keras_image.img_to_array(img) / 255.0
27
+ img_array = np.expand_dims(img_array, axis=0)
28
+ return img_array
29
+
30
+ # === Fungsi prediksi utama ===
31
+ def predict_image(image_bytes):
32
+ img_array = preprocess_image(image_bytes)
33
+ predictions = model.predict(img_array)
34
+ class_index = int(np.argmax(predictions))
35
+ confidence = float(np.max(predictions))
36
+ return {
37
+ 'class': labels[class_index],
38
+ 'confidence': confidence
39
+ }
40
+
41
+ # === Fungsi handler yang dipanggil Hugging Face API ===
42
+ def handler(inputs):
43
+ try:
44
+ # Input berupa base64 atau byte dari gambar
45
+ image_bytes = inputs['inputs']
46
+
47
+ # Jika data berupa string base64, ubah ke byte
48
+ if isinstance(image_bytes, str):
49
+ import base64
50
+ image_bytes = base64.b64decode(image_bytes)
51
+
52
+ result = predict_image(image_bytes)
53
+ return result
54
+
55
+ except Exception as e:
56
+ return {"error": str(e)}
57
+