Spaces:
Sleeping
Sleeping
Download app.py from Galih18/DataMiningUAs: direct link, hf CLI and curl.
- Browser
- Download file 2.47 kB
-
https://huggingface.co/spaces/Galih18/DataMiningUAs/resolve/main/app.py
- Command line
-
hf download hf://spaces/Galih18/DataMiningUAs/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Galih18/DataMiningUAs/resolve/main/app.py
2.47 kB
| 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() |