import os import json import numpy as np import tensorflow as tf import gradio as gr # --- CONFIGURATION --- ASSETS_DIR = "model_assets" # Nama folder aset # --- 1. LOAD MODEL & ASSETS --- print("--- Loading Model & Assets... ---") try: # Load Model .h5 model_path = os.path.join(ASSETS_DIR, "model_klasifikasi_aduan.h5") model = tf.keras.models.load_model(model_path) # Load Config (Max Sequence Length) with open(os.path.join(ASSETS_DIR, "config.json"), 'r') as f: config = json.load(f) MAX_SEQUENCE_LENGTH = config.get('max_sequence_length', 100) # Default 100 jika tidak ada # Load Label Map with open(os.path.join(ASSETS_DIR, "label_map.json"), 'r') as f: label_map = json.load(f) index_to_label = {v: k for k, v in label_map.items()} # Load Vocabulary with open(os.path.join(ASSETS_DIR, "vocabulary.txt"), "r") as f: vocabulary = [line.strip() for line in f.readlines()] word_to_index = {word: index for index, word in enumerate(vocabulary)} print("✅ Success: Model Loaded!") except Exception as e: print(f"❌ Error Loading Assets: {e}") print("Pastikan folder 'model_assets' berisi file .h5, config, label_map, dan vocabulary.") # --- 2. PREPROCESSING FUNCTION --- def preprocess_text(text): if not text: return None tokens = text.lower().split() # Mengubah kata ke angka (1 untuk kata yg tidak dikenal/OOV) token_indices = [word_to_index.get(token, 1) for token in tokens] # Padding sequence padded_indices = tf.keras.preprocessing.sequence.pad_sequences( [token_indices], maxlen=MAX_SEQUENCE_LENGTH, padding='post', truncating='post' ) return padded_indices # --- 3. PREDICTION FUNCTION --- def klasifikasi_aduan(text): if not text or len(text.strip()) < 3: return "⚠️ Mohon masukkan kalimat aduan yang jelas." processed_input = preprocess_text(text) prediction = model.predict(processed_input)[0] # Format output untuk Gradio (Dictionary {Label: Confidence}) results = {} for i, score in enumerate(prediction): label_name = index_to_label.get(i, f"Label {i}") results[label_name] = float(score) return results # --- 4. GRADIO INTERFACE --- # Contoh input agar user langsung paham examples = [ ["Jalan raya di kecamatan Wonosobo berlubang parah dan membahayakan pengendara motor."], ["Anak saya dipersulit saat mengurus administrasi pindah sekolah, mohon bantuannya."], ["Lampu penerangan jalan umum di desa mati total sudah satu bulan belum diperbaiki."], ["Ada pungutan liar di lokasi wisata yang tidak sesuai dengan tiket resmi."] ] demo = gr.Interface( fn=klasifikasi_aduan, inputs=gr.Textbox(lines=4, placeholder="Ketik aduan Anda di sini..."), outputs=gr.Label(num_top_classes=3, label="Hasil Analisis Model"), title="🏛️ LaporGub! Complaints Classifier", description="A Bi-LSTM deep learning model designed to classify Central Java public complaints into 14 government sectors with 87% F1-score accuracy.", examples=examples, theme="soft" ) if __name__ == "__main__": demo.launch(share=True)