Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -2,6 +2,7 @@ import gradio as gr
|
|
| 2 |
import os
|
| 3 |
import numpy as np
|
| 4 |
import warnings
|
|
|
|
| 5 |
|
| 6 |
# Suppress warnings
|
| 7 |
warnings.filterwarnings('ignore')
|
|
@@ -9,161 +10,188 @@ warnings.filterwarnings('ignore')
|
|
| 9 |
# Check if we're running on Hugging Face Spaces
|
| 10 |
ON_SPACES = os.environ.get('SPACE_ID') is not None
|
| 11 |
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
missing_files = []
|
| 16 |
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
-
return missing_files
|
| 22 |
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
|
| 29 |
-
def
|
| 30 |
-
"""Load model and
|
| 31 |
-
global model, tokenizer,
|
|
|
|
|
|
|
| 32 |
|
| 33 |
-
missing_files = check_files()
|
| 34 |
if missing_files:
|
| 35 |
-
print(f"β Missing
|
| 36 |
-
print("π Required files for this app:")
|
| 37 |
-
print(" - best_bilstm_model.h5 (your trained BiLSTM model)")
|
| 38 |
-
print(" - tokenizer_raw.pkl (your fitted tokenizer)")
|
| 39 |
return False
|
| 40 |
|
| 41 |
try:
|
| 42 |
-
# Try to load TensorFlow and required libraries
|
| 43 |
import tensorflow as tf
|
| 44 |
import joblib
|
|
|
|
| 45 |
from tensorflow.keras.preprocessing.sequence import pad_sequences
|
| 46 |
|
| 47 |
# Suppress TensorFlow warnings
|
| 48 |
tf.get_logger().setLevel('ERROR')
|
| 49 |
|
| 50 |
-
|
|
|
|
|
|
|
| 51 |
try:
|
| 52 |
-
model =
|
| 53 |
print("β
Model loaded successfully")
|
| 54 |
except Exception as e:
|
| 55 |
try:
|
| 56 |
-
model =
|
| 57 |
print("β
Model loaded with compile=False")
|
| 58 |
except Exception as e2:
|
| 59 |
print(f"β Failed to load model: {e2}")
|
| 60 |
return False
|
| 61 |
|
| 62 |
-
#
|
| 63 |
try:
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
return False
|
| 69 |
|
| 70 |
-
#
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
|
| 81 |
return True
|
| 82 |
|
| 83 |
except ImportError as e:
|
| 84 |
-
print(f"β Missing
|
| 85 |
return False
|
| 86 |
except Exception as e:
|
| 87 |
print(f"β Unexpected error: {e}")
|
| 88 |
return False
|
| 89 |
|
| 90 |
-
def
|
| 91 |
-
"""
|
| 92 |
-
import re
|
| 93 |
-
|
| 94 |
-
if not text or not isinstance(text, str):
|
| 95 |
-
return ""
|
| 96 |
-
|
| 97 |
-
text = text.lower()
|
| 98 |
-
text = re.sub(r'\s+', ' ', text).strip()
|
| 99 |
-
text = re.sub(r'[^\w\s]', '', text)
|
| 100 |
-
|
| 101 |
-
return text
|
| 102 |
-
|
| 103 |
-
def predict_emotion_demo(text):
|
| 104 |
-
"""Demo function when model is not available"""
|
| 105 |
-
if not text or not text.strip():
|
| 106 |
-
return "β Error: Teks tidak boleh kosong"
|
| 107 |
-
|
| 108 |
-
# Simulate prediction based on keywords for demo
|
| 109 |
-
text_lower = text.lower()
|
| 110 |
-
|
| 111 |
-
demo_predictions = {
|
| 112 |
-
'happy': ['bahagia', 'senang', 'gembira', 'suka', 'cinta', 'love'],
|
| 113 |
-
'sadness': ['sedih', 'kecewa', 'galau', 'patah hati', 'duka'],
|
| 114 |
-
'anger': ['marah', 'kesal', 'benci', 'jengkel', 'dongkol'],
|
| 115 |
-
'fear': ['takut', 'cemas', 'khawatir', 'panik', 'gelisah'],
|
| 116 |
-
'love': ['cinta', 'sayang', 'kasih', 'rindu', 'romantic']
|
| 117 |
-
}
|
| 118 |
-
|
| 119 |
-
scores = {emotion: 0 for emotion in emotion_labels}
|
| 120 |
-
|
| 121 |
-
for emotion, keywords in demo_predictions.items():
|
| 122 |
-
for keyword in keywords:
|
| 123 |
-
if keyword in text_lower:
|
| 124 |
-
scores[emotion] += 1
|
| 125 |
-
|
| 126 |
-
# If no keywords found, assign random emotion for demo
|
| 127 |
-
if sum(scores.values()) == 0:
|
| 128 |
-
import random
|
| 129 |
-
random_emotion = random.choice(emotion_labels)
|
| 130 |
-
scores[random_emotion] = 1
|
| 131 |
-
|
| 132 |
-
# Normalize scores
|
| 133 |
-
total_score = sum(scores.values())
|
| 134 |
-
if total_score > 0:
|
| 135 |
-
for emotion in scores:
|
| 136 |
-
scores[emotion] = scores[emotion] / total_score
|
| 137 |
-
|
| 138 |
-
# Get predicted emotion
|
| 139 |
-
predicted_emotion = max(scores, key=scores.get)
|
| 140 |
-
confidence = scores[predicted_emotion] * 100
|
| 141 |
-
|
| 142 |
-
# Format output
|
| 143 |
-
output = f"π Text: {text}\n\n"
|
| 144 |
-
output += f"π Predicted Emotion: {predicted_emotion.upper()}\n"
|
| 145 |
-
output += f"π― Confidence: {confidence:.1f}%\n\n"
|
| 146 |
-
output += "π All Probabilities:\n"
|
| 147 |
-
|
| 148 |
-
sorted_emotions = sorted(scores.items(), key=lambda x: x[1], reverse=True)
|
| 149 |
-
|
| 150 |
-
for emotion, prob in sorted_emotions:
|
| 151 |
-
percentage = prob * 100
|
| 152 |
-
bar_length = int(prob * 20)
|
| 153 |
-
bar = 'β' * bar_length + 'β' * (20 - bar_length)
|
| 154 |
-
output += f"{emotion.ljust(8)} | {bar} | {percentage:.1f}%\n"
|
| 155 |
-
|
| 156 |
-
output += "\nβ οΈ Note: This is a DEMO version using keyword matching.\n"
|
| 157 |
-
output += "Please upload your model files to enable full functionality."
|
| 158 |
-
|
| 159 |
-
return output
|
| 160 |
-
|
| 161 |
-
def predict_emotion_real(text):
|
| 162 |
-
"""Real prediction function when model is available"""
|
| 163 |
try:
|
| 164 |
import tensorflow as tf
|
| 165 |
from tensorflow.keras.preprocessing.sequence import pad_sequences
|
| 166 |
-
import re
|
| 167 |
|
| 168 |
if not text or not text.strip():
|
| 169 |
return "β Error: Teks tidak boleh kosong"
|
|
@@ -171,110 +199,220 @@ def predict_emotion_real(text):
|
|
| 171 |
if model is None or tokenizer is None:
|
| 172 |
return "β Error: Model atau tokenizer tidak dapat dimuat"
|
| 173 |
|
| 174 |
-
|
| 175 |
-
|
|
|
|
|
|
|
|
|
|
| 176 |
|
| 177 |
-
if not
|
| 178 |
-
return "β Error: Text
|
| 179 |
|
| 180 |
# Convert to sequences
|
| 181 |
-
sequences = tokenizer.texts_to_sequences([
|
|
|
|
| 182 |
|
| 183 |
if not sequences or not sequences[0]:
|
| 184 |
-
return "β Error: Tidak dapat
|
| 185 |
|
| 186 |
# Pad sequences
|
| 187 |
-
max_length = 44 # Default sequence length
|
| 188 |
padded = pad_sequences(sequences, maxlen=max_length, padding='post')
|
|
|
|
| 189 |
|
| 190 |
# Make prediction
|
| 191 |
-
|
| 192 |
-
predicted_probs =
|
|
|
|
|
|
|
| 193 |
|
| 194 |
# Get predicted emotion
|
| 195 |
predicted_idx = np.argmax(predicted_probs)
|
| 196 |
predicted_emotion = emotion_labels[predicted_idx]
|
| 197 |
-
confidence = float(predicted_probs[predicted_idx])
|
| 198 |
|
| 199 |
# Format output
|
| 200 |
-
output = f"
|
| 201 |
-
output += f"
|
| 202 |
-
output += f"
|
|
|
|
|
|
|
| 203 |
output += "π All Probabilities:\n"
|
| 204 |
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
reverse=True
|
| 209 |
-
)
|
| 210 |
|
| 211 |
-
for
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
output += f"{emotion_name.ljust(8)} | {bar} | {percentage:.1f}%\n"
|
| 216 |
|
| 217 |
return output
|
| 218 |
|
| 219 |
except Exception as e:
|
|
|
|
| 220 |
return f"β Error dalam prediksi: {str(e)}"
|
| 221 |
|
| 222 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 223 |
print("π Initializing Indonesian Emotion Classifier...")
|
| 224 |
|
| 225 |
-
|
| 226 |
-
model_loaded = load_model_and_tokenizer()
|
| 227 |
|
| 228 |
-
if
|
| 229 |
-
print("
|
| 230 |
-
predict_function =
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
β
Model fully loaded and ready!
|
| 236 |
-
"""
|
| 237 |
-
else:
|
| 238 |
-
print("β οΈ Running in DEMO mode")
|
| 239 |
-
predict_function = predict_emotion_demo
|
| 240 |
-
app_description = """
|
| 241 |
-
π¨ DEMO MODE: Model files not found!
|
| 242 |
|
| 243 |
-
|
|
|
|
| 244 |
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
|
| 249 |
-
|
| 250 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 251 |
|
| 252 |
-
# Create
|
| 253 |
demo = gr.Interface(
|
| 254 |
fn=predict_function,
|
| 255 |
inputs=[
|
| 256 |
gr.Textbox(
|
| 257 |
-
label="Input Text (
|
| 258 |
placeholder="Masukkan kalimat dalam bahasa Indonesia...",
|
| 259 |
-
lines=3
|
|
|
|
| 260 |
)
|
| 261 |
],
|
| 262 |
outputs=[
|
| 263 |
gr.Textbox(
|
| 264 |
label="Emotion Analysis Result",
|
| 265 |
-
lines=12
|
|
|
|
|
|
|
| 266 |
)
|
| 267 |
],
|
| 268 |
-
title=
|
| 269 |
description=app_description,
|
| 270 |
examples=[
|
|
|
|
| 271 |
["Saya sangat bahagia hari ini"],
|
| 272 |
-
["Saya marah sekali dengan kejadian ini"],
|
| 273 |
["Saya takut dengan situasi ini"],
|
| 274 |
["Saya cinta kamu selamanya"],
|
| 275 |
["Saya sedih banget hari ini"],
|
| 276 |
["Hari ini cuaca sangat cerah dan indah"],
|
| 277 |
["Kenapa hidup ini begitu sulit?"],
|
|
|
|
|
|
|
|
|
|
|
|
|
| 278 |
],
|
| 279 |
cache_examples=False,
|
| 280 |
theme=gr.themes.Soft(),
|
|
@@ -284,14 +422,13 @@ demo = gr.Interface(
|
|
| 284 |
if __name__ == "__main__":
|
| 285 |
print("π Starting Indonesian Emotion Classifier...")
|
| 286 |
|
| 287 |
-
# Launch with appropriate settings for Spaces
|
| 288 |
if ON_SPACES:
|
| 289 |
demo.launch()
|
| 290 |
else:
|
| 291 |
demo.launch(
|
| 292 |
-
server_name="0.0.0.0",
|
| 293 |
server_port=7860,
|
| 294 |
share=False
|
| 295 |
)
|
| 296 |
|
| 297 |
-
print("β
App
|
|
|
|
| 2 |
import os
|
| 3 |
import numpy as np
|
| 4 |
import warnings
|
| 5 |
+
import re
|
| 6 |
|
| 7 |
# Suppress warnings
|
| 8 |
warnings.filterwarnings('ignore')
|
|
|
|
| 10 |
# Check if we're running on Hugging Face Spaces
|
| 11 |
ON_SPACES = os.environ.get('SPACE_ID') is not None
|
| 12 |
|
| 13 |
+
# Global variables
|
| 14 |
+
model = None
|
| 15 |
+
tokenizer = None
|
| 16 |
+
emotion_labels = ['anger', 'fear', 'happy', 'love', 'sadness'] # Default order
|
| 17 |
+
max_length = 44 # Default max length
|
| 18 |
+
|
| 19 |
+
def check_available_files():
|
| 20 |
+
"""Check what files are available and return info"""
|
| 21 |
+
available_files = []
|
| 22 |
missing_files = []
|
| 23 |
|
| 24 |
+
# Check for model file
|
| 25 |
+
if os.path.exists('best_bilstm_model.h5'):
|
| 26 |
+
available_files.append('best_bilstm_model.h5')
|
| 27 |
+
else:
|
| 28 |
+
missing_files.append('best_bilstm_model.h5')
|
| 29 |
+
|
| 30 |
+
# Check for tokenizer files (various possible names)
|
| 31 |
+
tokenizer_files = [
|
| 32 |
+
'tokenizer_raw.pkl',
|
| 33 |
+
'tokenizer.pkl',
|
| 34 |
+
'datasets.pkl',
|
| 35 |
+
'preprocessor.pkl'
|
| 36 |
+
]
|
| 37 |
+
|
| 38 |
+
tokenizer_found = None
|
| 39 |
+
for tfile in tokenizer_files:
|
| 40 |
+
if os.path.exists(tfile):
|
| 41 |
+
available_files.append(tfile)
|
| 42 |
+
tokenizer_found = tfile
|
| 43 |
+
break
|
| 44 |
+
|
| 45 |
+
if tokenizer_found is None:
|
| 46 |
+
missing_files.extend(['tokenizer file (.pkl)'])
|
| 47 |
|
| 48 |
+
return available_files, missing_files, tokenizer_found
|
| 49 |
|
| 50 |
+
def clean_text_comprehensive(text):
|
| 51 |
+
"""
|
| 52 |
+
Comprehensive text cleaning function based on typical preprocessing
|
| 53 |
+
"""
|
| 54 |
+
if not text or not isinstance(text, str):
|
| 55 |
+
return ""
|
| 56 |
+
|
| 57 |
+
# Convert to lowercase
|
| 58 |
+
text = text.lower()
|
| 59 |
+
|
| 60 |
+
# Replace URLs, mentions, hashtags (common in social media)
|
| 61 |
+
text = re.sub(r'http[s]?://\S+|www\.\S+', '<url>', text)
|
| 62 |
+
text = re.sub(r'@\w+', '<user>', text)
|
| 63 |
+
text = re.sub(r'#(\w+)', r'\1', text)
|
| 64 |
+
|
| 65 |
+
# Replace numbers
|
| 66 |
+
text = re.sub(r'\d+', '<number>', text)
|
| 67 |
+
|
| 68 |
+
# Fix repeated punctuation
|
| 69 |
+
text = re.sub(r'([!?.]){2,}', r'\1', text)
|
| 70 |
+
|
| 71 |
+
# Fix repeated characters (like "hellooooo" -> "helloo")
|
| 72 |
+
text = re.sub(r'([a-zA-Z])\1{2,}', r'\1\1', text)
|
| 73 |
+
|
| 74 |
+
# Clean multiple spaces
|
| 75 |
+
text = ' '.join(text.split())
|
| 76 |
+
|
| 77 |
+
# Remove special characters but keep Indonesian characters and basic punctuation
|
| 78 |
+
text = re.sub(r'[^\w\s!?.,]', '', text)
|
| 79 |
+
|
| 80 |
+
return text.strip()
|
| 81 |
|
| 82 |
+
def load_model_and_components():
|
| 83 |
+
"""Load model and available components with fallback strategies"""
|
| 84 |
+
global model, tokenizer, emotion_labels, max_length
|
| 85 |
+
|
| 86 |
+
available_files, missing_files, tokenizer_file = check_available_files()
|
| 87 |
|
|
|
|
| 88 |
if missing_files:
|
| 89 |
+
print(f"β Missing files: {missing_files}")
|
|
|
|
|
|
|
|
|
|
| 90 |
return False
|
| 91 |
|
| 92 |
try:
|
|
|
|
| 93 |
import tensorflow as tf
|
| 94 |
import joblib
|
| 95 |
+
from tensorflow.keras.models import load_model
|
| 96 |
from tensorflow.keras.preprocessing.sequence import pad_sequences
|
| 97 |
|
| 98 |
# Suppress TensorFlow warnings
|
| 99 |
tf.get_logger().setLevel('ERROR')
|
| 100 |
|
| 101 |
+
print(f"π Available files: {available_files}")
|
| 102 |
+
|
| 103 |
+
# 1. Load TensorFlow model
|
| 104 |
try:
|
| 105 |
+
model = load_model('best_bilstm_model.h5')
|
| 106 |
print("β
Model loaded successfully")
|
| 107 |
except Exception as e:
|
| 108 |
try:
|
| 109 |
+
model = load_model('best_bilstm_model.h5', compile=False)
|
| 110 |
print("β
Model loaded with compile=False")
|
| 111 |
except Exception as e2:
|
| 112 |
print(f"β Failed to load model: {e2}")
|
| 113 |
return False
|
| 114 |
|
| 115 |
+
# Get model info
|
| 116 |
try:
|
| 117 |
+
# Try to get max_length from model input shape
|
| 118 |
+
if hasattr(model, 'input_shape') and model.input_shape[1]:
|
| 119 |
+
max_length = model.input_shape[1]
|
| 120 |
+
print(f"π Max length from model: {max_length}")
|
| 121 |
+
else:
|
| 122 |
+
print(f"π Using default max length: {max_length}")
|
| 123 |
+
except:
|
| 124 |
+
print(f"π Using default max length: {max_length}")
|
| 125 |
+
|
| 126 |
+
# 2. Load tokenizer with multiple strategies
|
| 127 |
+
tokenizer_loaded = False
|
| 128 |
+
|
| 129 |
+
# Strategy 1: Try loading complete datasets object
|
| 130 |
+
if tokenizer_file == 'datasets.pkl':
|
| 131 |
+
try:
|
| 132 |
+
datasets = joblib.load('datasets.pkl')
|
| 133 |
+
if 'preprocessor' in datasets:
|
| 134 |
+
tokenizer = datasets['preprocessor'].tokenizer
|
| 135 |
+
if hasattr(datasets['preprocessor'], 'label_encoder'):
|
| 136 |
+
emotion_labels = list(datasets['preprocessor'].label_encoder.classes_)
|
| 137 |
+
if 'config' in datasets and 'max_sequence_length' in datasets['config']:
|
| 138 |
+
max_length = datasets['config']['max_sequence_length']
|
| 139 |
+
print("β
Complete datasets loaded")
|
| 140 |
+
tokenizer_loaded = True
|
| 141 |
+
except Exception as e:
|
| 142 |
+
print(f"β οΈ Failed to load complete datasets: {e}")
|
| 143 |
+
|
| 144 |
+
# Strategy 2: Try loading preprocessor object
|
| 145 |
+
elif tokenizer_file == 'preprocessor.pkl':
|
| 146 |
+
try:
|
| 147 |
+
preprocessor = joblib.load('preprocessor.pkl')
|
| 148 |
+
if hasattr(preprocessor, 'tokenizer'):
|
| 149 |
+
tokenizer = preprocessor.tokenizer
|
| 150 |
+
if hasattr(preprocessor, 'label_encoder'):
|
| 151 |
+
emotion_labels = list(preprocessor.label_encoder.classes_)
|
| 152 |
+
print("β
Preprocessor object loaded")
|
| 153 |
+
tokenizer_loaded = True
|
| 154 |
+
except Exception as e:
|
| 155 |
+
print(f"β οΈ Failed to load preprocessor: {e}")
|
| 156 |
+
|
| 157 |
+
# Strategy 3: Load raw tokenizer
|
| 158 |
+
else:
|
| 159 |
+
try:
|
| 160 |
+
tokenizer = joblib.load(tokenizer_file)
|
| 161 |
+
print(f"β
Tokenizer loaded from {tokenizer_file}")
|
| 162 |
+
tokenizer_loaded = True
|
| 163 |
+
except Exception as e:
|
| 164 |
+
print(f"β οΈ Failed to load tokenizer: {e}")
|
| 165 |
+
|
| 166 |
+
if not tokenizer_loaded:
|
| 167 |
+
print("β No tokenizer could be loaded")
|
| 168 |
return False
|
| 169 |
|
| 170 |
+
# Verify tokenizer
|
| 171 |
+
if not hasattr(tokenizer, 'word_index'):
|
| 172 |
+
print("β Invalid tokenizer object")
|
| 173 |
+
return False
|
| 174 |
+
|
| 175 |
+
vocab_size = len(tokenizer.word_index)
|
| 176 |
+
print(f"β
Tokenizer verified:")
|
| 177 |
+
print(f" β’ Vocab size: {vocab_size:,}")
|
| 178 |
+
print(f" β’ Max length: {max_length}")
|
| 179 |
+
print(f" β’ Emotion labels: {emotion_labels}")
|
| 180 |
|
| 181 |
return True
|
| 182 |
|
| 183 |
except ImportError as e:
|
| 184 |
+
print(f"β Missing packages: {e}")
|
| 185 |
return False
|
| 186 |
except Exception as e:
|
| 187 |
print(f"β Unexpected error: {e}")
|
| 188 |
return False
|
| 189 |
|
| 190 |
+
def predict_emotion_with_loaded_model(text):
|
| 191 |
+
"""Predict emotion using loaded model and tokenizer"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 192 |
try:
|
| 193 |
import tensorflow as tf
|
| 194 |
from tensorflow.keras.preprocessing.sequence import pad_sequences
|
|
|
|
| 195 |
|
| 196 |
if not text or not text.strip():
|
| 197 |
return "β Error: Teks tidak boleh kosong"
|
|
|
|
| 199 |
if model is None or tokenizer is None:
|
| 200 |
return "β Error: Model atau tokenizer tidak dapat dimuat"
|
| 201 |
|
| 202 |
+
print(f"π Processing: '{text}'")
|
| 203 |
+
|
| 204 |
+
# Clean text
|
| 205 |
+
cleaned_text = clean_text_comprehensive(text)
|
| 206 |
+
print(f"π§Ή Cleaned: '{cleaned_text}'")
|
| 207 |
|
| 208 |
+
if not cleaned_text:
|
| 209 |
+
return "β Error: Text kosong setelah preprocessing"
|
| 210 |
|
| 211 |
# Convert to sequences
|
| 212 |
+
sequences = tokenizer.texts_to_sequences([cleaned_text])
|
| 213 |
+
print(f"π’ Sequences: {sequences}")
|
| 214 |
|
| 215 |
if not sequences or not sequences[0]:
|
| 216 |
+
return "β Error: Tidak dapat mengkonversi text ke sequences"
|
| 217 |
|
| 218 |
# Pad sequences
|
|
|
|
| 219 |
padded = pad_sequences(sequences, maxlen=max_length, padding='post')
|
| 220 |
+
print(f"π Padded shape: {padded.shape}")
|
| 221 |
|
| 222 |
# Make prediction
|
| 223 |
+
predictions = model.predict(padded, verbose=0)
|
| 224 |
+
predicted_probs = predictions[0]
|
| 225 |
+
|
| 226 |
+
print(f"π― Raw predictions: {predicted_probs}")
|
| 227 |
|
| 228 |
# Get predicted emotion
|
| 229 |
predicted_idx = np.argmax(predicted_probs)
|
| 230 |
predicted_emotion = emotion_labels[predicted_idx]
|
| 231 |
+
confidence = float(predicted_probs[predicted_idx])
|
| 232 |
|
| 233 |
# Format output
|
| 234 |
+
output = f"π Result:\n"
|
| 235 |
+
output += f"π Original Text: {text}\n"
|
| 236 |
+
output += f"π§Ή Cleaned Text: {cleaned_text}\n"
|
| 237 |
+
output += f"π Emotion: {predicted_emotion.upper()}\n"
|
| 238 |
+
output += f"π― Confidence: {confidence:.3f} ({confidence*100:.1f}%)\n\n"
|
| 239 |
output += "π All Probabilities:\n"
|
| 240 |
|
| 241 |
+
# Create probability pairs and sort
|
| 242 |
+
prob_pairs = [(emotion_labels[i], predicted_probs[i]) for i in range(len(emotion_labels))]
|
| 243 |
+
prob_pairs.sort(key=lambda x: x[1], reverse=True)
|
|
|
|
|
|
|
| 244 |
|
| 245 |
+
for emotion, prob in prob_pairs:
|
| 246 |
+
bar_length = int(prob * 30)
|
| 247 |
+
bar = "β" * bar_length
|
| 248 |
+
output += f" {emotion:8} | {bar:<30} | {prob:.3f} ({prob*100:.1f}%)\n"
|
|
|
|
| 249 |
|
| 250 |
return output
|
| 251 |
|
| 252 |
except Exception as e:
|
| 253 |
+
print(f"β Prediction error: {e}")
|
| 254 |
return f"β Error dalam prediksi: {str(e)}"
|
| 255 |
|
| 256 |
+
def predict_demo_mode(text):
|
| 257 |
+
"""Demo prediction using keyword matching"""
|
| 258 |
+
if not text or not text.strip():
|
| 259 |
+
return "β Error: Teks tidak boleh kosong"
|
| 260 |
+
|
| 261 |
+
# Enhanced Indonesian keyword matching
|
| 262 |
+
emotion_keywords = {
|
| 263 |
+
'happy': [
|
| 264 |
+
'bahagia', 'senang', 'gembira', 'ceria', 'riang', 'sukses', 'bangga',
|
| 265 |
+
'puas', 'suka', 'tertawa', 'tersenyum', 'beruntung', 'lega', 'syukur'
|
| 266 |
+
],
|
| 267 |
+
'sadness': [
|
| 268 |
+
'sedih', 'kecewa', 'galau', 'duka', 'terpuruk', 'hancur', 'patah hati',
|
| 269 |
+
'kehilangan', 'menyesal', 'putus asa', 'lemah', 'kosong', 'hampa'
|
| 270 |
+
],
|
| 271 |
+
'anger': [
|
| 272 |
+
'marah', 'kesal', 'benci', 'jengkel', 'dongkol', 'murka', 'geram',
|
| 273 |
+
'sebal', 'sebel', 'berang', 'gusar', 'emosi', 'panas'
|
| 274 |
+
],
|
| 275 |
+
'fear': [
|
| 276 |
+
'takut', 'cemas', 'khawatir', 'panik', 'gelisah', 'was-was',
|
| 277 |
+
'nervous', 'tegang', 'deg-degan', 'grogi', 'resah'
|
| 278 |
+
],
|
| 279 |
+
'love': [
|
| 280 |
+
'cinta', 'sayang', 'kasih', 'rindu', 'romantis', 'mesra', 'setia',
|
| 281 |
+
'mencintai', 'menyayangi', 'kangen', 'vermissen'
|
| 282 |
+
]
|
| 283 |
+
}
|
| 284 |
+
|
| 285 |
+
# Clean and analyze text
|
| 286 |
+
cleaned_text = clean_text_comprehensive(text)
|
| 287 |
+
text_words = cleaned_text.lower().split()
|
| 288 |
+
|
| 289 |
+
# Calculate scores
|
| 290 |
+
scores = {emotion: 0 for emotion in emotion_keywords.keys()}
|
| 291 |
+
|
| 292 |
+
for emotion, keywords in emotion_keywords.items():
|
| 293 |
+
for keyword in keywords:
|
| 294 |
+
# Exact match
|
| 295 |
+
if keyword in cleaned_text.lower():
|
| 296 |
+
scores[emotion] += 1
|
| 297 |
+
# Word-level match
|
| 298 |
+
if keyword in text_words:
|
| 299 |
+
scores[emotion] += 0.5
|
| 300 |
+
|
| 301 |
+
# If no matches, assign neutral positive
|
| 302 |
+
if sum(scores.values()) == 0:
|
| 303 |
+
scores['happy'] = 1
|
| 304 |
+
|
| 305 |
+
# Normalize scores
|
| 306 |
+
total_score = sum(scores.values())
|
| 307 |
+
for emotion in scores:
|
| 308 |
+
scores[emotion] = scores[emotion] / total_score if total_score > 0 else 0
|
| 309 |
+
|
| 310 |
+
# Get prediction
|
| 311 |
+
predicted_emotion = max(scores, key=scores.get)
|
| 312 |
+
confidence = scores[predicted_emotion]
|
| 313 |
+
|
| 314 |
+
# Format output
|
| 315 |
+
output = f"π DEMO Result:\n"
|
| 316 |
+
output += f"π Original Text: {text}\n"
|
| 317 |
+
output += f"π§Ή Cleaned Text: {cleaned_text}\n"
|
| 318 |
+
output += f"π Emotion: {predicted_emotion.upper()}\n"
|
| 319 |
+
output += f"π― Confidence: {confidence:.3f} ({confidence*100:.1f}%)\n\n"
|
| 320 |
+
output += "π All Probabilities:\n"
|
| 321 |
+
|
| 322 |
+
# Sort and display
|
| 323 |
+
sorted_emotions = sorted(scores.items(), key=lambda x: x[1], reverse=True)
|
| 324 |
+
for emotion, prob in sorted_emotions:
|
| 325 |
+
bar_length = int(prob * 30)
|
| 326 |
+
bar = "β" * bar_length
|
| 327 |
+
output += f" {emotion:8} | {bar:<30} | {prob:.3f} ({prob*100:.1f}%)\n"
|
| 328 |
+
|
| 329 |
+
output += "\nβ οΈ DEMO MODE: Menggunakan keyword matching.\n"
|
| 330 |
+
output += "Upload file model untuk hasil akurat."
|
| 331 |
+
|
| 332 |
+
return output
|
| 333 |
+
|
| 334 |
+
# Initialize system
|
| 335 |
print("π Initializing Indonesian Emotion Classifier...")
|
| 336 |
|
| 337 |
+
available_files, missing_files, tokenizer_file = check_available_files()
|
|
|
|
| 338 |
|
| 339 |
+
if missing_files:
|
| 340 |
+
print(f"β Missing files: {missing_files}")
|
| 341 |
+
predict_function = predict_demo_mode
|
| 342 |
+
app_title = "π Indonesian Emotion Classifier (DEMO)"
|
| 343 |
+
app_description = f"""
|
| 344 |
+
π¨ **DEMO MODE**: Beberapa file tidak ditemukan!
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 345 |
|
| 346 |
+
**File yang ada:** {available_files if available_files else 'Tidak ada'}
|
| 347 |
+
**File yang hilang:** {missing_files}
|
| 348 |
|
| 349 |
+
**Untuk mode penuh, upload file berikut:**
|
| 350 |
+
- `best_bilstm_model.h5` (model yang dilatih)
|
| 351 |
+
- File tokenizer: `tokenizer_raw.pkl` ATAU `datasets.pkl` ATAU `preprocessor.pkl`
|
| 352 |
|
| 353 |
+
Saat ini menggunakan keyword matching sederhana.
|
| 354 |
"""
|
| 355 |
+
else:
|
| 356 |
+
# Try to load model system
|
| 357 |
+
model_loaded = load_model_and_components()
|
| 358 |
+
|
| 359 |
+
if model_loaded:
|
| 360 |
+
print("β
Model system loaded successfully!")
|
| 361 |
+
predict_function = predict_emotion_with_loaded_model
|
| 362 |
+
app_title = "π Indonesian Emotion Classifier"
|
| 363 |
+
app_description = """
|
| 364 |
+
**Klasifikasi emosi untuk teks bahasa Indonesia menggunakan BiLSTM.**
|
| 365 |
+
|
| 366 |
+
β
**Model fully loaded dan siap digunakan!**
|
| 367 |
+
|
| 368 |
+
**Emotions:** anger, fear, happy, love, sadness
|
| 369 |
+
|
| 370 |
+
Model menggunakan arsitektur BiLSTM dengan preprocessing yang dioptimalkan untuk bahasa Indonesia.
|
| 371 |
+
"""
|
| 372 |
+
else:
|
| 373 |
+
print("β οΈ Model loading failed, using demo mode")
|
| 374 |
+
predict_function = predict_demo_mode
|
| 375 |
+
app_title = "π Indonesian Emotion Classifier (DEMO)"
|
| 376 |
+
app_description = """
|
| 377 |
+
π¨ **DEMO MODE**: File ditemukan tapi gagal dimuat!
|
| 378 |
+
|
| 379 |
+
Kemungkinan ada masalah kompatibilitas. Menggunakan keyword matching.
|
| 380 |
+
"""
|
| 381 |
|
| 382 |
+
# Create interface
|
| 383 |
demo = gr.Interface(
|
| 384 |
fn=predict_function,
|
| 385 |
inputs=[
|
| 386 |
gr.Textbox(
|
| 387 |
+
label="Input Text (Bahasa Indonesia)",
|
| 388 |
placeholder="Masukkan kalimat dalam bahasa Indonesia...",
|
| 389 |
+
lines=3,
|
| 390 |
+
max_lines=5
|
| 391 |
)
|
| 392 |
],
|
| 393 |
outputs=[
|
| 394 |
gr.Textbox(
|
| 395 |
label="Emotion Analysis Result",
|
| 396 |
+
lines=12,
|
| 397 |
+
max_lines=20,
|
| 398 |
+
show_copy_button=True
|
| 399 |
)
|
| 400 |
],
|
| 401 |
+
title=app_title,
|
| 402 |
description=app_description,
|
| 403 |
examples=[
|
| 404 |
+
["aku senang tahun ini"],
|
| 405 |
["Saya sangat bahagia hari ini"],
|
| 406 |
+
["Saya marah sekali dengan kejadian ini"],
|
| 407 |
["Saya takut dengan situasi ini"],
|
| 408 |
["Saya cinta kamu selamanya"],
|
| 409 |
["Saya sedih banget hari ini"],
|
| 410 |
["Hari ini cuaca sangat cerah dan indah"],
|
| 411 |
["Kenapa hidup ini begitu sulit?"],
|
| 412 |
+
["Terima kasih atas semua bantuan kalian"],
|
| 413 |
+
["Aku khawatir dengan masa depan"],
|
| 414 |
+
["Wah, hasil ujianku bagus banget!"],
|
| 415 |
+
["Dia sudah pergi dan tidak akan kembali"],
|
| 416 |
],
|
| 417 |
cache_examples=False,
|
| 418 |
theme=gr.themes.Soft(),
|
|
|
|
| 422 |
if __name__ == "__main__":
|
| 423 |
print("π Starting Indonesian Emotion Classifier...")
|
| 424 |
|
|
|
|
| 425 |
if ON_SPACES:
|
| 426 |
demo.launch()
|
| 427 |
else:
|
| 428 |
demo.launch(
|
| 429 |
+
server_name="0.0.0.0",
|
| 430 |
server_port=7860,
|
| 431 |
share=False
|
| 432 |
)
|
| 433 |
|
| 434 |
+
print("β
App launched successfully!")
|