import gradio as gr from keras.models import load_model from PIL import Image, ImageOps import numpy as np import os # --- 1. KONFIGURASI --- MODEL_PATH = "keras_model.h5" LABELS_PATH = "labels.txt" # MAPPING PASTI: Label di txt -> File MP3 # Saya sudah sesuaikan dengan daftar label & file yang kamu kasih DAFTAR_SUARA = { "tempe": "tempe.mp3", "hidup": "hidup.mp3", "hidup_jokowi": "hidup_jokowi.mp3", "dsh": "dsh.mp3", "bakso": "bakso.mp3" } # Suara default (kalau ada error/label ga dikenal) SUARA_DEFAULT = "dsh.mp3" # --- 2. LOAD MODEL --- # Load model sekali saja di awal model = load_model(MODEL_PATH, compile=False) class_names = [line.strip() for line in open(LABELS_PATH, "r").readlines()] # --- 3. FUNGSI DETEKSI (PASTI/MUTLAK) --- def deteksi_pasti(image): if image is None: return "⚠️ WADUH! Gambarnya mana?", None # Persiapan Gambar (Standar Keras/Teachable Machine) data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32) image = Image.fromarray(image).convert("RGB") size = (224, 224) image = ImageOps.fit(image, size, Image.Resampling.LANCZOS) image_array = np.asarray(image) normalized_image_array = (image_array.astype(np.float32) / 127.5) - 1 data[0] = normalized_image_array # Prediksi prediction = model.predict(data) # AMBIL YANG PALING TINGGI (Index Max) index = np.argmax(prediction) class_name = class_names[index] # Ambil nama label bersih. # Contoh: "0 tempe" -> kita buang "0 " (2 karakter awal) -> jadi "tempe" label_bersih = class_name[2:].strip() # Cari File Suaranya if label_bersih in DAFTAR_SUARA: file_suara = DAFTAR_SUARA[label_bersih] else: # Jaga-jaga kalau ada label baru file_suara = SUARA_DEFAULT # Buat Pesan Teks teks_hasil = f"📢 HASIL: {label_bersih.upper()} !!" return teks_hasil, file_suara # --- 4. TAMPILAN ANTARMUKA (UI) --- css_custom = """ .container {text-align: center;} #judul-utama {color: #FF5733; font-size: 3em; font-weight: 900; text-align: center; margin-bottom: 0;} #sub-judul {text-align: center; font-style: italic; margin-bottom: 20px;} #kotak-hasil { font-size: 32px; font-weight: bold; text-align: center; color: white; background-color: #28B463; padding: 10px; border-radius: 10px; } """ with gr.Blocks(theme=gr.themes.Soft(), css=css_custom) as demo: gr.Markdown("# ⚡ MAGIC SOUND DETECTOR ⚡", elem_id="judul-utama") gr.Markdown("Arahkan kamera ke Bakso, Tempe, atau Foto Pak Jokowi!", elem_id="sub-judul") with gr.Row(): with gr.Column(scale=1): input_img = gr.Image( sources=["webcam", "upload"], type="numpy", label="📸 Input Kamera/Foto", height=400 ) btn = gr.Button("🔥 CEK SEKARANG 🔥", variant="primary", size="lg") with gr.Column(scale=1): # Output Teks txt_output = gr.Textbox(label="Hasil Deteksi", elem_id="kotak-hasil", interactive=False) # Output Audio audio_output = gr.Audio(label="🔊 Suara Efek", autoplay=True) # Logika Tombol btn.click(fn=deteksi_pasti, inputs=input_img, outputs=[txt_output, audio_output]) # Jalankan demo.launch()