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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +258 -239
app.py CHANGED
@@ -1,240 +1,259 @@
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
  )
 
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) with OOV handling
60
+ seq = tokenizer.texts_to_sequences([text])
61
+
62
+ # Check for out-of-vocabulary issues
63
+ max_vocab_index = len(tokenizer.word_index)
64
+ print(f"Max vocab index: {max_vocab_index}")
65
+ print(f"Sequence before filtering: {seq}")
66
+
67
+ # Filter out OOV tokens that exceed vocabulary size
68
+ filtered_seq = []
69
+ for sequence in seq:
70
+ filtered_sequence = [idx for idx in sequence if idx < max_vocab_index]
71
+ filtered_seq.append(filtered_sequence)
72
+
73
+ print(f"Sequence after filtering: {filtered_seq}")
74
+
75
+ # If sequence is empty after filtering, handle gracefully
76
+ if not filtered_seq[0]:
77
+ return "Warning: Text contains only unknown words", 0.5, "Text tidak dapat diproses - mengandung kata yang tidak dikenal"
78
+
79
+ padded = tf.keras.preprocessing.sequence.pad_sequences(filtered_seq, maxlen=model.input_shape[1])
80
+
81
+ # 2. Predict
82
+ probs = model.predict(padded, verbose=0)[0] # Probabilitas untuk semua kelas
83
+ top_index = np.argmax(probs) # Index label tertinggi
84
+ top_label = labels[top_index] # Nama label
85
+ top_conf = float(probs[top_index])
86
+
87
+ # 3. Create detailed probabilities
88
+ all_probs = {labels[i]: float(probs[i]) for i in range(len(labels))}
89
+
90
+ # Sort probabilities for better display
91
+ sorted_probs = dict(sorted(all_probs.items(), key=lambda x: x[1], reverse=True))
92
+
93
+ # Format detailed output
94
+ detailed_output = json.dumps(sorted_probs, indent=2)
95
+
96
+ return top_label, top_conf, detailed_output
97
+
98
+ except Exception as e:
99
+ error_msg = f"Prediction error: {str(e)}"
100
+ print(f"Error details: {e}")
101
+ return error_msg, 0.0, error_msg
102
+
103
+ def find_available_port(start_port=7860, max_attempts=10):
104
+ """Find an available port starting from start_port"""
105
+ import socket
106
+
107
+ for i in range(max_attempts):
108
+ port = start_port + i
109
+ try:
110
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
111
+ s.bind(('127.0.0.1', port))
112
+ return port
113
+ except OSError:
114
+ continue
115
+ return None
116
+
117
+ # =======================
118
+ # 2. Gradio Interface
119
+ # =======================
120
+
121
+ # Custom CSS for better styling
122
+ css = """
123
+ #output-emotion {
124
+ font-size: 24px !important;
125
+ font-weight: bold !important;
126
+ text-align: center !important;
127
+ }
128
+ #output-confidence {
129
+ font-size: 18px !important;
130
+ text-align: center !important;
131
+ }
132
+ """
133
+
134
+ # Create the interface
135
+ with gr.Blocks(css=css, title="Emotion Classification") as demo:
136
+ gr.Markdown(
137
+ """
138
+ # 🎭 Emotion Classification Model
139
+
140
+ Masukkan teks dalam bahasa Indonesia untuk menganalisis emosi yang terkandung di dalamnya.
141
+ Model akan memprediksi emosi dan memberikan tingkat kepercayaan.
142
+ """
143
+ )
144
+
145
+ with gr.Row():
146
+ with gr.Column(scale=1):
147
+ # Input
148
+ text_input = gr.Textbox(
149
+ label="Masukkan Teks",
150
+ placeholder="Ketik teks yang ingin dianalisis emosinya...",
151
+ lines=3,
152
+ max_lines=10
153
+ )
154
+
155
+ # Predict button
156
+ predict_btn = gr.Button("πŸ” Analisis Emosi", variant="primary", size="lg")
157
+
158
+ # Clear button
159
+ clear_btn = gr.Button("πŸ—‘οΈ Hapus", variant="secondary")
160
+
161
+ with gr.Column(scale=1):
162
+ # Outputs
163
+ emotion_output = gr.Textbox(
164
+ label="Emosi Terdeteksi",
165
+ elem_id="output-emotion",
166
+ interactive=False
167
+ )
168
+
169
+ confidence_output = gr.Number(
170
+ label="Tingkat Kepercayaan",
171
+ elem_id="output-confidence",
172
+ precision=4
173
+ )
174
+
175
+ probabilities_output = gr.Code(
176
+ label="Detail Probabilitas Semua Emosi",
177
+ language="json",
178
+ interactive=False
179
+ )
180
+
181
+ # Examples
182
+ gr.Examples(
183
+ examples=[
184
+ ["Saya sangat bahagia hari ini!"],
185
+ ["Aku merasa sedih sekali"],
186
+ ["Mengapa ini terjadi? Aku marah!"],
187
+ ["Aku takut dengan situasi ini"],
188
+ ["Wah, aku terkejut dengan berita ini"],
189
+ ["Aku merasa biasa saja tentang hal ini"]
190
+ ],
191
+ inputs=[text_input],
192
+ outputs=[emotion_output, confidence_output, probabilities_output],
193
+ fn=predict_emotion,
194
+ cache_examples=True
195
+ )
196
+
197
+ # Event handlers
198
+ predict_btn.click(
199
+ fn=predict_emotion,
200
+ inputs=[text_input],
201
+ outputs=[emotion_output, confidence_output, probabilities_output]
202
+ )
203
+
204
+ text_input.submit(
205
+ fn=predict_emotion,
206
+ inputs=[text_input],
207
+ outputs=[emotion_output, confidence_output, probabilities_output]
208
+ )
209
+
210
+ clear_btn.click(
211
+ fn=lambda: ("", "", 0.0, ""),
212
+ outputs=[text_input, emotion_output, confidence_output, probabilities_output]
213
+ )
214
+
215
+ # Footer
216
+ gr.Markdown(
217
+ """
218
+ ---
219
+ **Catatan:** Model ini dilatih untuk mengklasifikasikan emosi dalam teks bahasa Indonesia.
220
+ Hasil prediksi menunjukkan probabilitas untuk setiap kategori emosi.
221
+ """
222
+ )
223
+
224
+ # =======================
225
+ # 3. Launch Application
226
+ # =======================
227
+ if __name__ == "__main__":
228
+ # Check if models are loaded successfully
229
+ if model is None:
230
+ print("⚠️ Warning: Models failed to load. Please check file paths.")
231
+ print("Expected files:")
232
+ print(f"- {MODEL_PATH}")
233
+ print(f"- {TOKENIZER_PATH}")
234
+ print(f"- {LABELENC_PATH}")
235
+ else:
236
+ print("βœ… Models loaded successfully!")
237
+ print(f"πŸ“Š Available emotions: {labels}")
238
+
239
+ # Find available port
240
+ available_port = find_available_port()
241
+
242
+ if available_port:
243
+ print(f"πŸš€ Starting server on port {available_port}")
244
+ # Launch the app
245
+ demo.launch(
246
+ server_name="127.0.0.1", # Localhost untuk testing lokal
247
+ server_port=available_port, # Use available port
248
+ share=False, # Set to True if you want a public link
249
+ show_error=True, # Show detailed errors
250
+ inbrowser=True # Automatically open browser
251
+ )
252
+ else:
253
+ print("❌ Could not find available port. Trying without specifying port...")
254
+ # Let Gradio find a port automatically
255
+ demo.launch(
256
+ share=False,
257
+ show_error=True,
258
+ inbrowser=True
259
  )