Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -5,38 +5,130 @@ import numpy as np
|
|
| 5 |
from tensorflow.keras.preprocessing.sequence import pad_sequences
|
| 6 |
import re
|
| 7 |
import json
|
|
|
|
| 8 |
|
| 9 |
-
#
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
|
|
|
| 22 |
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
|
| 33 |
-
|
| 34 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
|
| 41 |
# Emotion labels
|
| 42 |
emotion_labels = ['anger', 'fear', 'happy', 'love', 'sadness']
|
|
@@ -114,7 +206,6 @@ def predict_emotion(text):
|
|
| 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}")
|
|
@@ -129,7 +220,10 @@ def predict_emotion(text):
|
|
| 129 |
}
|
| 130 |
|
| 131 |
# Pad sequences
|
| 132 |
-
max_length =
|
|
|
|
|
|
|
|
|
|
| 133 |
padded = pad_sequences(sequences, maxlen=max_length, padding='post')
|
| 134 |
|
| 135 |
print(f"π Padded shape: {padded.shape}")
|
|
@@ -201,7 +295,7 @@ def predict_emotion_gradio(text):
|
|
| 201 |
|
| 202 |
return output
|
| 203 |
|
| 204 |
-
# API endpoint function
|
| 205 |
def predict_api(text):
|
| 206 |
"""
|
| 207 |
API endpoint yang mengembalikan JSON
|
|
@@ -238,24 +332,57 @@ demo = gr.Interface(
|
|
| 238 |
theme=gr.themes.Soft()
|
| 239 |
)
|
| 240 |
|
| 241 |
-
#
|
| 242 |
-
|
| 243 |
-
def predict_endpoint(text: str):
|
| 244 |
"""
|
| 245 |
-
|
| 246 |
-
Usage: POST /predict with {"text": "your text here"}
|
| 247 |
"""
|
| 248 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 249 |
|
| 250 |
if __name__ == "__main__":
|
| 251 |
print("π Starting Emotion Classifier API...")
|
| 252 |
print("π± Gradio Interface: Available")
|
| 253 |
-
print("π API Endpoint: /predict")
|
| 254 |
|
| 255 |
-
# Launch
|
| 256 |
-
demo.launch(
|
| 257 |
server_name="0.0.0.0",
|
| 258 |
server_port=7860,
|
| 259 |
share=False,
|
| 260 |
-
show_api=
|
| 261 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
from tensorflow.keras.preprocessing.sequence import pad_sequences
|
| 6 |
import re
|
| 7 |
import json
|
| 8 |
+
import warnings
|
| 9 |
|
| 10 |
+
# Suppress TensorFlow warnings
|
| 11 |
+
warnings.filterwarnings('ignore')
|
| 12 |
+
tf.get_logger().setLevel('ERROR')
|
| 13 |
+
|
| 14 |
+
# Global variables
|
| 15 |
+
model = None
|
| 16 |
+
tokenizer = None
|
| 17 |
+
embedding_vocab_size = None
|
| 18 |
+
|
| 19 |
+
def load_model_safely():
|
| 20 |
+
"""
|
| 21 |
+
Load model dengan handling untuk berbagai versi TensorFlow
|
| 22 |
+
"""
|
| 23 |
+
global model, embedding_vocab_size
|
| 24 |
|
| 25 |
+
try:
|
| 26 |
+
# Try loading with different methods
|
| 27 |
+
try:
|
| 28 |
+
# Method 1: Standard loading
|
| 29 |
+
model = tf.keras.models.load_model("best_bilstm_model.h5")
|
| 30 |
+
except Exception as e1:
|
| 31 |
+
print(f"β οΈ Standard loading failed: {e1}")
|
| 32 |
+
try:
|
| 33 |
+
# Method 2: Load with compile=False
|
| 34 |
+
model = tf.keras.models.load_model("best_bilstm_model.h5", compile=False)
|
| 35 |
+
print("β
Model loaded with compile=False")
|
| 36 |
+
except Exception as e2:
|
| 37 |
+
print(f"β οΈ Loading with compile=False failed: {e2}")
|
| 38 |
+
try:
|
| 39 |
+
# Method 3: Load and rebuild
|
| 40 |
+
from tensorflow.keras.models import Sequential
|
| 41 |
+
from tensorflow.keras.layers import Embedding, LSTM, Dense, Dropout, Bidirectional
|
| 42 |
+
|
| 43 |
+
print("π¨ Attempting to rebuild model...")
|
| 44 |
+
# This is a fallback - you might need to adjust architecture
|
| 45 |
+
model = Sequential([
|
| 46 |
+
Embedding(input_dim=20000, output_dim=128, input_length=44),
|
| 47 |
+
Bidirectional(LSTM(64, dropout=0.2, recurrent_dropout=0.2)),
|
| 48 |
+
Dense(32, activation='relu'),
|
| 49 |
+
Dropout(0.5),
|
| 50 |
+
Dense(5, activation='softmax')
|
| 51 |
+
])
|
| 52 |
+
|
| 53 |
+
# Load weights if available
|
| 54 |
+
try:
|
| 55 |
+
model.load_weights("best_bilstm_model.h5")
|
| 56 |
+
print("β
Weights loaded successfully")
|
| 57 |
+
except:
|
| 58 |
+
print("β οΈ Could not load weights")
|
| 59 |
+
return False
|
| 60 |
+
|
| 61 |
+
except Exception as e3:
|
| 62 |
+
print(f"β All loading methods failed: {e3}")
|
| 63 |
+
return False
|
| 64 |
|
| 65 |
+
if model:
|
| 66 |
+
print("β
Model loaded successfully")
|
| 67 |
+
|
| 68 |
+
# Get embedding layer vocab size
|
| 69 |
+
try:
|
| 70 |
+
embedding_layer = None
|
| 71 |
+
for layer in model.layers:
|
| 72 |
+
if 'embedding' in layer.name.lower() or isinstance(layer, tf.keras.layers.Embedding):
|
| 73 |
+
embedding_layer = layer
|
| 74 |
+
break
|
| 75 |
+
|
| 76 |
+
if embedding_layer:
|
| 77 |
+
embedding_vocab_size = embedding_layer.input_dim
|
| 78 |
+
print(f"π Model embedding vocab size: {embedding_vocab_size}")
|
| 79 |
+
else:
|
| 80 |
+
embedding_vocab_size = 20000 # fallback
|
| 81 |
+
print("β οΈ Using fallback embedding vocab size: 20000")
|
| 82 |
+
|
| 83 |
+
except Exception as e:
|
| 84 |
+
embedding_vocab_size = 20000
|
| 85 |
+
print(f"β οΈ Error getting embedding size, using fallback: {e}")
|
| 86 |
+
|
| 87 |
+
return True
|
| 88 |
|
| 89 |
+
return False
|
| 90 |
+
|
| 91 |
+
except Exception as e:
|
| 92 |
+
print(f"β Error in load_model_safely: {e}")
|
| 93 |
+
return False
|
| 94 |
+
|
| 95 |
+
def load_tokenizer_safely():
|
| 96 |
+
"""
|
| 97 |
+
Load tokenizer dengan error handling
|
| 98 |
+
"""
|
| 99 |
+
global tokenizer
|
| 100 |
|
| 101 |
+
try:
|
| 102 |
+
tokenizer = joblib.load("tokenizer_raw.pkl")
|
| 103 |
+
print("β
Tokenizer loaded successfully")
|
| 104 |
+
print(f"π Tokenizer vocab size: {len(tokenizer.word_index)}")
|
| 105 |
+
|
| 106 |
+
# Fix vocab size mismatch if needed
|
| 107 |
+
if embedding_vocab_size and len(tokenizer.word_index) >= embedding_vocab_size:
|
| 108 |
+
print("β οΈ Vocab size mismatch detected - applying fix...")
|
| 109 |
+
|
| 110 |
+
# Filter tokenizer vocabulary to match model
|
| 111 |
+
filtered_word_index = {}
|
| 112 |
+
for word, idx in tokenizer.word_index.items():
|
| 113 |
+
if idx < embedding_vocab_size:
|
| 114 |
+
filtered_word_index[word] = idx
|
| 115 |
+
|
| 116 |
+
tokenizer.word_index = filtered_word_index
|
| 117 |
+
print(f"β
Fixed tokenizer vocab size: {len(tokenizer.word_index)}")
|
| 118 |
+
|
| 119 |
+
return True
|
| 120 |
+
|
| 121 |
+
except Exception as e:
|
| 122 |
+
print(f"β Error loading tokenizer: {e}")
|
| 123 |
+
return False
|
| 124 |
+
|
| 125 |
+
# Initialize model and tokenizer
|
| 126 |
+
print("π Initializing model and tokenizer...")
|
| 127 |
+
model_loaded = load_model_safely()
|
| 128 |
+
tokenizer_loaded = load_tokenizer_safely()
|
| 129 |
+
|
| 130 |
+
if not model_loaded or not tokenizer_loaded:
|
| 131 |
+
print("β Failed to load model or tokenizer")
|
| 132 |
|
| 133 |
# Emotion labels
|
| 134 |
emotion_labels = ['anger', 'fear', 'happy', 'love', 'sadness']
|
|
|
|
| 206 |
print(f"π Processing text: '{processed_text}'")
|
| 207 |
|
| 208 |
# Convert to sequences with safe handling
|
|
|
|
| 209 |
sequences = safe_texts_to_sequences(tokenizer, [processed_text], embedding_vocab_size)
|
| 210 |
|
| 211 |
print(f"π’ Sequences: {sequences}")
|
|
|
|
| 220 |
}
|
| 221 |
|
| 222 |
# Pad sequences
|
| 223 |
+
max_length = 44 # Default sequence length
|
| 224 |
+
if hasattr(model, 'input_shape') and model.input_shape[1]:
|
| 225 |
+
max_length = model.input_shape[1]
|
| 226 |
+
|
| 227 |
padded = pad_sequences(sequences, maxlen=max_length, padding='post')
|
| 228 |
|
| 229 |
print(f"π Padded shape: {padded.shape}")
|
|
|
|
| 295 |
|
| 296 |
return output
|
| 297 |
|
| 298 |
+
# API endpoint function (akan dihandle secara manual)
|
| 299 |
def predict_api(text):
|
| 300 |
"""
|
| 301 |
API endpoint yang mengembalikan JSON
|
|
|
|
| 332 |
theme=gr.themes.Soft()
|
| 333 |
)
|
| 334 |
|
| 335 |
+
# Manual API handling untuk compatibility dengan Gradio versi lama
|
| 336 |
+
def create_api_endpoint(app):
|
|
|
|
| 337 |
"""
|
| 338 |
+
Manually create API endpoint
|
|
|
|
| 339 |
"""
|
| 340 |
+
try:
|
| 341 |
+
from fastapi import FastAPI
|
| 342 |
+
from pydantic import BaseModel
|
| 343 |
+
|
| 344 |
+
class PredictionRequest(BaseModel):
|
| 345 |
+
text: str
|
| 346 |
+
|
| 347 |
+
class PredictionResponse(BaseModel):
|
| 348 |
+
text: str
|
| 349 |
+
emotion: str = None
|
| 350 |
+
confidence: float = 0.0
|
| 351 |
+
probabilities: dict = {}
|
| 352 |
+
error: str = None
|
| 353 |
+
|
| 354 |
+
@app.post("/predict")
|
| 355 |
+
async def predict_endpoint(request: PredictionRequest):
|
| 356 |
+
"""
|
| 357 |
+
API endpoint untuk prediksi emosi
|
| 358 |
+
"""
|
| 359 |
+
result = predict_api(request.text)
|
| 360 |
+
return PredictionResponse(**result)
|
| 361 |
+
|
| 362 |
+
print("β
API endpoint /predict created")
|
| 363 |
+
|
| 364 |
+
except Exception as e:
|
| 365 |
+
print(f"β οΈ Could not create API endpoint: {e}")
|
| 366 |
|
| 367 |
if __name__ == "__main__":
|
| 368 |
print("π Starting Emotion Classifier API...")
|
| 369 |
print("π± Gradio Interface: Available")
|
|
|
|
| 370 |
|
| 371 |
+
# Launch Gradio
|
| 372 |
+
app = demo.launch(
|
| 373 |
server_name="0.0.0.0",
|
| 374 |
server_port=7860,
|
| 375 |
share=False,
|
| 376 |
+
show_api=False, # Disable automatic API documentation
|
| 377 |
+
prevent_thread_lock=True
|
| 378 |
+
)
|
| 379 |
+
|
| 380 |
+
# Try to add custom API endpoint
|
| 381 |
+
if hasattr(app, 'app'):
|
| 382 |
+
try:
|
| 383 |
+
create_api_endpoint(app.app)
|
| 384 |
+
except Exception as e:
|
| 385 |
+
print(f"β οΈ Could not add API endpoint: {e}")
|
| 386 |
+
|
| 387 |
+
print("π Manual API endpoint available at: /predict")
|
| 388 |
+
print("β
Server started successfully!")
|