ketir commited on
Commit
f758016
·
verified ·
1 Parent(s): 925332b

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -259
app.py DELETED
@@ -1,259 +0,0 @@
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
- )