Spaces:
Sleeping

File size: 2,472 Bytes
b7de40a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31e25e6
d1bc151
07c40f0
d1bc151
 
 
 
 
 
 
b7de40a
 
 
 
 
 
 
 
 
 
31e25e6
b7de40a
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import gradio as gr
import os 
os.environ["KERAS_BACKEND"] = "tensorflow"

import tensorflow as tf
from tensorflow import keras
from keras.models import load_model
import numpy as np
from PIL import Image

# --- 1. Load Model dan Labels ---
MODEL_PATH = "keras_model.h5"
LABELS_PATH = "labels.txt"

# Load model
model = load_model('keras_model.h5')

#load label
with open(LABELS_PATH, "r") as f:
        # Baca label dan hapus nomor urut (e.g., "0 pink" -> "pink")
        labels = [line.strip().split(" ", 1)[-1] for line in f.readlines()]

# --- 2. Fungsi Prediksi ---
def classify_image(input_image):
    img = np.array(input_image)
    
    # Pre-processing: Sesuaikan ukuran input model
    IMG_SIZE = (224, 224) 
    
    # Konversi ke gambar PIL, ubah ukurannya, dan konversi kembali ke NumPy
    img = Image.fromarray(img).resize(IMG_SIZE)
    img_array = np.asarray(img) / 255.0  # Normalisasi (sesuaikan dengan pelatihan model Anda)
    
    # Tambahkan dimensi batch: (H, W, C) -> (1, H, W, C)
    input_tensor = np.expand_dims(img_array, axis=0)
    
    # Lakukan prediksi
    predictions = model.predict(input_tensor)[0]
    
    # Format hasil untuk Gradio, berisi label dan probabilitasnya dalam bentuk set
    confidences = {labels[i]: float(predictions[i]) for i in range(len(labels))}
    
    # Tentukan kelas dengan probabilitas tertinggi
    predicted_class = max(confidences, key=confidences.get)
    
    # === Custom output sesuai kondisi ===
    custom_message = ""  # INISIALISASI WAJIB

    label = predicted_class.lower()
    if label == "open":
        custom_message = "kamu dalam keadaan tidak mengantuk"
    elif label in ["close", "closed"]:
        custom_message = "kamu dalam keadaan mengantuk"
    else:
        custom_message = "kondisi tidak terdeteksi"
    return custom_message, confidences


# --- 3. Bikin UI Pakai Gradio ---
# Definisikan Input dan Output
image_input = gr.Image(type="pil", label="Unggah Gambar")

# Output: Komponen Label untuk menampilkan probabilitas
label_output = gr.Label(num_top_classes=len(labels)) 
#Bisa juga ditambahkan kata-kata diatasnya
text_output = gr.Textbox(label="Apakah kamu dalam keadaan...") #kalo ga mau pake kata2, cukup gr.Textbox()


# Buat UI-nya
gr.Interface(
    fn=classify_image,
    inputs=image_input,
    outputs=[text_output, label_output],    #sesuaikan dengan urutan return di fungsi classify
    title="Klasifikasi Gambar",
    description="Unggah gambar disini").launch()