ketir commited on
Commit
b025efa
Β·
verified Β·
1 Parent(s): a7a8f0c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +222 -220
app.py CHANGED
@@ -1,259 +1,261 @@
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
- )
 
1
  import gradio as gr
 
2
  import joblib
3
  import tensorflow as tf
4
+ import numpy as np
5
+ from tensorflow.keras.preprocessing.sequence import pad_sequences
6
+ import re
7
  import json
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
+ # Load model and tokenizer with error handling
10
+ try:
11
+ model = tf.keras.models.load_model("best_bilstm_model.h5")
12
+ print("βœ… Model loaded successfully")
13
+
14
+ tokenizer = joblib.load("tokenizer_raw.pkl")
15
+ print("βœ… Tokenizer loaded successfully")
16
+ print(f"πŸ“Š Tokenizer vocab size: {len(tokenizer.word_index)}")
17
+
18
+ # Get embedding layer vocab size
19
+ embedding_layer = model.layers[1] # Assuming embedding is second layer
20
+ embedding_vocab_size = embedding_layer.input_dim
21
+ print(f"πŸ“Š Model embedding vocab size: {embedding_vocab_size}")
22
+
23
+ # Check if there's a mismatch
24
+ if len(tokenizer.word_index) >= embedding_vocab_size:
25
+ print("⚠️ Vocab size mismatch detected - applying fix...")
26
 
27
+ # Filter tokenizer vocabulary to match model
28
+ filtered_word_index = {}
29
+ for word, idx in tokenizer.word_index.items():
30
+ if idx < embedding_vocab_size:
31
+ filtered_word_index[word] = idx
32
 
33
+ tokenizer.word_index = filtered_word_index
34
+ print(f"βœ… Fixed tokenizer vocab size: {len(tokenizer.word_index)}")
35
+
36
+ except Exception as e:
37
+ print(f"❌ Error loading model/tokenizer: {e}")
38
+ model = None
39
+ tokenizer = None
40
+
41
+ # Emotion labels
42
+ emotion_labels = ['anger', 'fear', 'happy', 'love', 'sadness']
43
 
44
+ def safe_texts_to_sequences(tokenizer, texts, max_vocab_size=None):
45
+ """
46
+ Safe version of texts_to_sequences yang menghindari OOV error
47
+ """
48
+ if max_vocab_size is None:
49
+ max_vocab_size = len(tokenizer.word_index) + 1
50
+
51
+ sequences = tokenizer.texts_to_sequences(texts)
52
+
53
+ # Filter out indices that exceed vocabulary
54
+ filtered_sequences = []
55
+ for seq in sequences:
56
+ filtered_seq = [idx for idx in seq if idx < max_vocab_size and idx > 0]
57
+ filtered_sequences.append(filtered_seq)
58
+
59
+ return filtered_sequences
60
+
61
+ def preprocess_text(text):
62
+ """
63
+ Preprocess text for emotion classification
64
+ """
65
+ if not text or not isinstance(text, str):
66
+ return ""
67
+
68
+ # Convert to lowercase
69
+ text = text.lower()
70
+
71
+ # Remove extra whitespaces
72
+ text = re.sub(r'\s+', ' ', text).strip()
73
+
74
+ # Remove special characters but keep Indonesian characters
75
+ text = re.sub(r'[^\w\s]', '', text)
76
+
77
+ return text
78
 
79
  def predict_emotion(text):
80
  """
81
  Predict emotion from input text
 
 
 
 
 
 
82
  """
83
  try:
84
+ if not text or not text.strip():
85
+ return {
86
+ "error": "Text tidak boleh kosong",
87
+ "text": text,
88
+ "emotion": None,
89
+ "confidence": 0,
90
+ "probabilities": {}
91
+ }
92
 
93
  if model is None or tokenizer is None:
94
+ return {
95
+ "error": "Model atau tokenizer tidak dapat dimuat",
96
+ "text": text,
97
+ "emotion": None,
98
+ "confidence": 0,
99
+ "probabilities": {}
100
+ }
101
+
102
+ # Preprocess text
103
+ processed_text = preprocess_text(text)
104
 
105
+ if not processed_text:
106
+ return {
107
+ "error": "Text tidak valid setelah preprocessing",
108
+ "text": text,
109
+ "emotion": None,
110
+ "confidence": 0,
111
+ "probabilities": {}
112
+ }
113
 
114
+ print(f"πŸ” Processing text: '{processed_text}'")
 
 
 
115
 
116
+ # Convert to sequences with safe handling
117
+ embedding_vocab_size = model.layers[1].input_dim
118
+ sequences = safe_texts_to_sequences(tokenizer, [processed_text], embedding_vocab_size)
 
 
119
 
120
+ print(f"πŸ”’ Sequences: {sequences}")
121
 
122
+ if not sequences or not sequences[0]:
123
+ return {
124
+ "error": "Tidak dapat mengonversi text ke sequences. Text mungkin tidak dikenal oleh model.",
125
+ "text": text,
126
+ "emotion": None,
127
+ "confidence": 0,
128
+ "probabilities": {}
129
+ }
130
 
131
+ # Pad sequences
132
+ max_length = model.input_shape[1]
133
+ padded = pad_sequences(sequences, maxlen=max_length, padding='post')
134
 
135
+ print(f"πŸ“ Padded shape: {padded.shape}")
136
+ print(f"πŸ“ Max sequence value: {np.max(padded) if padded.size > 0 else 'empty'}")
 
 
 
137
 
138
+ # Make prediction
139
+ prediction = model.predict(padded, verbose=0)
140
+ predicted_probs = prediction[0]
141
 
142
+ print(f"🎯 Raw predictions: {predicted_probs}")
 
143
 
144
+ # Get predicted emotion
145
+ predicted_idx = np.argmax(predicted_probs)
146
+ predicted_emotion = emotion_labels[predicted_idx]
147
+ confidence = float(predicted_probs[predicted_idx])
148
 
149
+ # Create probabilities dictionary
150
+ probabilities = {
151
+ emotion_labels[i]: float(predicted_probs[i])
152
+ for i in range(len(emotion_labels))
153
+ }
154
+
155
+ result = {
156
+ "text": text,
157
+ "emotion": predicted_emotion,
158
+ "confidence": confidence,
159
+ "probabilities": probabilities
160
+ }
161
+
162
+ print(f"βœ… Prediction result: {result}")
163
+ return result
164
 
165
  except Exception as e:
166
+ print(f"❌ Prediction error: {str(e)}")
167
+ return {
168
+ "error": f"Error dalam prediksi: {str(e)}",
169
+ "text": text,
170
+ "emotion": None,
171
+ "confidence": 0,
172
+ "probabilities": {}
173
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
174
 
175
+ def predict_emotion_gradio(text):
176
+ """
177
+ Gradio interface function
178
+ """
179
+ result = predict_emotion(text)
 
 
 
 
 
180
 
181
+ if "error" in result:
182
+ return f"❌ Error: {result['error']}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
183
 
184
+ # Format output for Gradio
185
+ emotion = result['emotion'].upper()
186
+ confidence = result['confidence'] * 100
 
 
 
 
 
 
 
 
 
 
 
 
187
 
188
+ output = f"πŸ“ Text: {result['text']}\n\n"
189
+ output += f"🎭 Emotion: {emotion}\n"
190
+ output += f"🎯 Confidence: {confidence:.1f}%\n\n"
191
+ output += "πŸ“Š All Probabilities:\n"
 
 
192
 
193
+ # Sort probabilities
194
+ sorted_probs = sorted(result['probabilities'].items(), key=lambda x: x[1], reverse=True)
 
 
 
195
 
196
+ for emotion_name, prob in sorted_probs:
197
+ percentage = prob * 100
198
+ bar_length = int(prob * 20)
199
+ bar = 'β–ˆ' * bar_length + 'β–‘' * (20 - bar_length)
200
+ output += f"{emotion_name.ljust(8)} | {bar} | {percentage:.1f}%\n"
201
 
202
+ return output
203
+
204
+ # API endpoint function
205
+ def predict_api(text):
206
+ """
207
+ API endpoint yang mengembalikan JSON
208
+ """
209
+ result = predict_emotion(text)
210
+ return result
211
+
212
+ # Create Gradio interface
213
+ demo = gr.Interface(
214
+ fn=predict_emotion_gradio,
215
+ inputs=[
216
+ gr.Textbox(
217
+ label="Input Text",
218
+ placeholder="Masukkan kalimat dalam bahasa Indonesia...",
219
+ lines=3
220
+ )
221
+ ],
222
+ outputs=[
223
+ gr.Textbox(
224
+ label="Emotion Analysis Result",
225
+ lines=10
226
+ )
227
+ ],
228
+ title="🎭 Indonesian Emotion Classifier",
229
+ description="Klasifikasi emosi dalam teks bahasa Indonesia menggunakan BiLSTM model. Mendukung emosi: anger, fear, happy, love, sadness.",
230
+ examples=[
231
+ ["Saya sangat bahagia hari ini"],
232
+ ["Saya marah sekali dengan kejadian ini"],
233
+ ["Saya takut dengan situasi ini"],
234
+ ["Saya cinta kamu selamanya"],
235
+ ["Saya sedih banget hari ini"]
236
+ ],
237
+ cache_examples=False,
238
+ theme=gr.themes.Soft()
239
+ )
240
+
241
+ # Add API endpoint
242
+ @demo.api
243
+ def predict_endpoint(text: str):
244
+ """
245
+ API endpoint untuk prediksi emosi
246
+ Usage: POST /predict with {"text": "your text here"}
247
+ """
248
+ return predict_api(text)
249
 
 
 
 
250
  if __name__ == "__main__":
251
+ print("πŸš€ Starting Emotion Classifier API...")
252
+ print("πŸ“± Gradio Interface: Available")
253
+ print("πŸ”— API Endpoint: /predict")
 
 
 
 
 
 
 
 
 
 
254
 
255
+ # Launch with API enabled
256
+ demo.launch(
257
+ server_name="0.0.0.0",
258
+ server_port=7860,
259
+ share=False,
260
+ show_api=True
261
+ )