ketir commited on
Commit
b96ba75
Β·
verified Β·
1 Parent(s): 1a33bbe

Upload 5 files

Browse files
app.py ADDED
@@ -0,0 +1,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import numpy as np
3
+ import joblib
4
+ import tensorflow as tf
5
+ import json
6
+ import os
7
+ import warnings
8
+
9
+ # Suppress sklearn version warning
10
+ warnings.filterwarnings("ignore", category=UserWarning)
11
+
12
+ # =======================
13
+ # 1. Load Model & Assets
14
+ # =======================
15
+ MODEL_PATH = "best_bilstm_model.h5"
16
+ TOKENIZER_PATH = "tokenizer_raw.pkl"
17
+ LABELENC_PATH = "label_encoder_raw.pkl"
18
+
19
+ def load_models():
20
+ """Load all required models and components"""
21
+ try:
22
+ # Load model
23
+ model = tf.keras.models.load_model(MODEL_PATH)
24
+
25
+ # Load tokenizer
26
+ tokenizer = joblib.load(TOKENIZER_PATH)
27
+
28
+ # Load label encoder
29
+ label_encoder = joblib.load(LABELENC_PATH)
30
+
31
+ # Get label list and convert numpy strings to regular strings
32
+ labels = [str(label) for label in label_encoder.classes_]
33
+
34
+ return model, tokenizer, label_encoder, labels
35
+ except Exception as e:
36
+ print(f"Error loading models: {e}")
37
+ return None, None, None, None
38
+
39
+ # Load models at startup
40
+ model, tokenizer, label_encoder, labels = load_models()
41
+
42
+ def predict_emotion(text):
43
+ """
44
+ Predict emotion from input text
45
+
46
+ Args:
47
+ text (str): Input text for emotion classification
48
+
49
+ Returns:
50
+ tuple: (predicted_emotion, confidence_score, detailed_probabilities)
51
+ """
52
+ try:
53
+ if not text.strip():
54
+ return "Error: Please enter some text", 0.0, "No input provided"
55
+
56
+ if model is None or tokenizer is None:
57
+ return "Error: Models not loaded properly", 0.0, "Model loading failed"
58
+
59
+ # 1. Preprocessing (tokenize + pad)
60
+ seq = tokenizer.texts_to_sequences([text])
61
+ padded = tf.keras.preprocessing.sequence.pad_sequences(seq, maxlen=model.input_shape[1])
62
+
63
+ # 2. Predict
64
+ probs = model.predict(padded, verbose=0)[0] # Probabilitas untuk semua kelas
65
+ top_index = np.argmax(probs) # Index label tertinggi
66
+ top_label = labels[top_index] # Nama label
67
+ top_conf = float(probs[top_index])
68
+
69
+ # 3. Create detailed probabilities
70
+ all_probs = {labels[i]: float(probs[i]) for i in range(len(labels))}
71
+
72
+ # Sort probabilities for better display
73
+ sorted_probs = dict(sorted(all_probs.items(), key=lambda x: x[1], reverse=True))
74
+
75
+ # Format detailed output
76
+ detailed_output = json.dumps(sorted_probs, indent=2)
77
+
78
+ return top_label, top_conf, detailed_output
79
+
80
+ except Exception as e:
81
+ error_msg = f"Prediction error: {str(e)}"
82
+ return error_msg, 0.0, error_msg
83
+
84
+ def find_available_port(start_port=7860, max_attempts=10):
85
+ """Find an available port starting from start_port"""
86
+ import socket
87
+
88
+ for i in range(max_attempts):
89
+ port = start_port + i
90
+ try:
91
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
92
+ s.bind(('127.0.0.1', port))
93
+ return port
94
+ except OSError:
95
+ continue
96
+ return None
97
+
98
+ # =======================
99
+ # 2. Gradio Interface
100
+ # =======================
101
+
102
+ # Custom CSS for better styling
103
+ css = """
104
+ #output-emotion {
105
+ font-size: 24px !important;
106
+ font-weight: bold !important;
107
+ text-align: center !important;
108
+ }
109
+ #output-confidence {
110
+ font-size: 18px !important;
111
+ text-align: center !important;
112
+ }
113
+ """
114
+
115
+ # Create the interface
116
+ with gr.Blocks(css=css, title="Emotion Classification") as demo:
117
+ gr.Markdown(
118
+ """
119
+ # 🎭 Emotion Classification Model
120
+
121
+ Masukkan teks dalam bahasa Indonesia untuk menganalisis emosi yang terkandung di dalamnya.
122
+ Model akan memprediksi emosi dan memberikan tingkat kepercayaan.
123
+ """
124
+ )
125
+
126
+ with gr.Row():
127
+ with gr.Column(scale=1):
128
+ # Input
129
+ text_input = gr.Textbox(
130
+ label="Masukkan Teks",
131
+ placeholder="Ketik teks yang ingin dianalisis emosinya...",
132
+ lines=3,
133
+ max_lines=10
134
+ )
135
+
136
+ # Predict button
137
+ predict_btn = gr.Button("πŸ” Analisis Emosi", variant="primary", size="lg")
138
+
139
+ # Clear button
140
+ clear_btn = gr.Button("πŸ—‘οΈ Hapus", variant="secondary")
141
+
142
+ with gr.Column(scale=1):
143
+ # Outputs
144
+ emotion_output = gr.Textbox(
145
+ label="Emosi Terdeteksi",
146
+ elem_id="output-emotion",
147
+ interactive=False
148
+ )
149
+
150
+ confidence_output = gr.Number(
151
+ label="Tingkat Kepercayaan",
152
+ elem_id="output-confidence",
153
+ precision=4
154
+ )
155
+
156
+ probabilities_output = gr.Code(
157
+ label="Detail Probabilitas Semua Emosi",
158
+ language="json",
159
+ interactive=False
160
+ )
161
+
162
+ # Examples
163
+ gr.Examples(
164
+ examples=[
165
+ ["Saya sangat bahagia hari ini!"],
166
+ ["Aku merasa sedih sekali"],
167
+ ["Mengapa ini terjadi? Aku marah!"],
168
+ ["Aku takut dengan situasi ini"],
169
+ ["Wah, aku terkejut dengan berita ini"],
170
+ ["Aku merasa biasa saja tentang hal ini"]
171
+ ],
172
+ inputs=[text_input],
173
+ outputs=[emotion_output, confidence_output, probabilities_output],
174
+ fn=predict_emotion,
175
+ cache_examples=True
176
+ )
177
+
178
+ # Event handlers
179
+ predict_btn.click(
180
+ fn=predict_emotion,
181
+ inputs=[text_input],
182
+ outputs=[emotion_output, confidence_output, probabilities_output]
183
+ )
184
+
185
+ text_input.submit(
186
+ fn=predict_emotion,
187
+ inputs=[text_input],
188
+ outputs=[emotion_output, confidence_output, probabilities_output]
189
+ )
190
+
191
+ clear_btn.click(
192
+ fn=lambda: ("", "", 0.0, ""),
193
+ outputs=[text_input, emotion_output, confidence_output, probabilities_output]
194
+ )
195
+
196
+ # Footer
197
+ gr.Markdown(
198
+ """
199
+ ---
200
+ **Catatan:** Model ini dilatih untuk mengklasifikasikan emosi dalam teks bahasa Indonesia.
201
+ Hasil prediksi menunjukkan probabilitas untuk setiap kategori emosi.
202
+ """
203
+ )
204
+
205
+ # =======================
206
+ # 3. Launch Application
207
+ # =======================
208
+ if __name__ == "__main__":
209
+ # Check if models are loaded successfully
210
+ if model is None:
211
+ print("⚠️ Warning: Models failed to load. Please check file paths.")
212
+ print("Expected files:")
213
+ print(f"- {MODEL_PATH}")
214
+ print(f"- {TOKENIZER_PATH}")
215
+ print(f"- {LABELENC_PATH}")
216
+ else:
217
+ print("βœ… Models loaded successfully!")
218
+ print(f"πŸ“Š Available emotions: {labels}")
219
+
220
+ # Find available port
221
+ available_port = find_available_port()
222
+
223
+ if available_port:
224
+ print(f"πŸš€ Starting server on port {available_port}")
225
+ # Launch the app
226
+ demo.launch(
227
+ server_name="127.0.0.1", # Localhost untuk testing lokal
228
+ server_port=available_port, # Use available port
229
+ share=False, # Set to True if you want a public link
230
+ show_error=True, # Show detailed errors
231
+ inbrowser=True # Automatically open browser
232
+ )
233
+ else:
234
+ print("❌ Could not find available port. Trying without specifying port...")
235
+ # Let Gradio find a port automatically
236
+ demo.launch(
237
+ share=False,
238
+ show_error=True,
239
+ inbrowser=True
240
+ )
best_bilstm_model.h5 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0759eab36754bef42a97024e997195a33a3dda862c8227fe8937929b36403e88
3
+ size 31027616
label_encoder_raw.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d95b0933d826cdabd2b4c3b5adcc0200d707e437480c34f44a9b506fc25d8839
3
+ size 376
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ gradio>=4.0.0
2
+ tensorflow>=2.10.0
3
+ numpy>=1.21.0
4
+ scikit-learn>=1.0.0
5
+ joblib>=1.1.0
tokenizer_raw.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:053931994df6995292c9aaa755e5a3839bb47749ac449a0162d2841b1d82372a
3
+ size 1094018