ketir's picture
Update app.py
60b118e verified
Raw History Blame Contribute Delete
23.6 kB
import gradio as gr
import os
import numpy as np
import warnings
import re
import joblib
# Suppress warnings
warnings.filterwarnings('ignore')
# Check if we're running on Hugging Face Spaces
ON_SPACES = os.environ.get('SPACE_ID') is not None
# Global variables
model = None
tokenizer = None
label_encoder = None
emotion_labels = ['anger', 'fear', 'happy', 'love', 'sadness'] # Default order
max_length = 44 # Default max length
def check_available_files():
"""Check what files are available and return info"""
available_files = []
missing_files = []
# Check for model file
if os.path.exists('best_bilstm_model.h5'):
available_files.append('best_bilstm_model.h5')
else:
missing_files.append('best_bilstm_model.h5')
# Check for tokenizer files (various possible names)
tokenizer_files = [
'tokenizer_raw.pkl',
'tokenizer.pkl',
'datasets.pkl',
'preprocessor.pkl'
]
tokenizer_found = None
for tfile in tokenizer_files:
if os.path.exists(tfile):
available_files.append(tfile)
tokenizer_found = tfile
break
if tokenizer_found is None:
missing_files.extend(['tokenizer file (.pkl)'])
return available_files, missing_files, tokenizer_found
def clean_text_comprehensive(text):
"""
Enhanced text cleaning function with better Indonesian handling
"""
if not text or not isinstance(text, str):
return ""
# Convert to lowercase first
text = text.lower()
# Handle Indonesian-specific patterns
# Replace common Indonesian slang and informal words
indonesian_replacements = {
'ga': 'tidak',
'gak': 'tidak',
'nggak': 'tidak',
'engga': 'tidak',
'banget': 'sekali',
'bgt': 'sekali',
'udah': 'sudah',
'udh': 'sudah',
'gimana': 'bagaimana',
'gmn': 'bagaimana',
'kenapa': 'mengapa',
'knp': 'mengapa',
'sama': 'dengan',
'sm': 'dengan',
'trus': 'terus',
'trs': 'terus',
'yg': 'yang',
'dgn': 'dengan',
'krn': 'karena',
'krna': 'karena',
'tp': 'tapi',
'tpi': 'tapi',
'wkwk': 'haha',
'wkwkwk': 'haha',
'hehe': 'haha',
'huhu': 'sedih',
'huhuhu': 'sedih'
}
# Apply Indonesian replacements
words = text.split()
words = [indonesian_replacements.get(word, word) for word in words]
text = ' '.join(words)
# Replace URLs, mentions, hashtags
text = re.sub(r'http[s]?://\S+|www\.\S+', '<url>', text)
text = re.sub(r'@\w+', '<user>', text)
text = re.sub(r'#(\w+)', r'\1', text)
# Replace numbers
text = re.sub(r'\d+', '<number>', text)
# Fix repeated punctuation (preserve emotional context)
text = re.sub(r'([!?.]){3,}', r'\1\1', text) # Keep max 2 repetitions
# Fix repeated characters but preserve Indonesian words
# More careful with Indonesian words that naturally have repeated chars
text = re.sub(r'([aiueo])\1{3,}', r'\1\1', text) # Vowels max 2
text = re.sub(r'([bcdfghjklmnpqrstvwxyz])\1{2,}', r'\1\1', text) # Consonants max 2
# Clean multiple spaces
text = ' '.join(text.split())
# Remove special characters but keep Indonesian characters and basic punctuation
text = re.sub(r'[^\w\s!?.,]', ' ', text)
# Remove extra spaces again
text = ' '.join(text.split())
return text.strip()
def normalize_emotion_labels(predicted_labels, model_labels, standard_labels):
"""
Normalize emotion labels to match model's expected format
"""
# Create mapping from various possible labels to standard format
label_mapping = {
# Anger variations
'marah': 'anger',
'angry': 'anger',
'kesal': 'anger',
'jengkel': 'anger',
# Fear variations
'takut': 'fear',
'scared': 'fear',
'afraid': 'fear',
'cemas': 'fear',
'khawatir': 'fear',
# Happy variations
'senang': 'happy',
'bahagia': 'happy',
'gembira': 'happy',
'joy': 'happy',
'excited': 'happy',
# Love variations
'cinta': 'love',
'sayang': 'love',
'kasih': 'love',
'romantic': 'love',
# Sadness variations
'sedih': 'sadness',
'sad': 'sadness',
'kecewa': 'sadness',
'galau': 'sadness'
}
normalized = []
for label in predicted_labels:
normalized_label = label_mapping.get(label.lower(), label.lower())
if normalized_label in standard_labels:
normalized.append(normalized_label)
else:
# Default to most similar
normalized.append(standard_labels[0])
return normalized
def load_model_and_components():
"""Load model and available components with enhanced error handling"""
global model, tokenizer, label_encoder, emotion_labels, max_length
available_files, missing_files, tokenizer_file = check_available_files()
if missing_files:
print(f"❌ Missing files: {missing_files}")
return False
try:
import tensorflow as tf
from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing.sequence import pad_sequences
# Suppress TensorFlow warnings
tf.get_logger().setLevel('ERROR')
print(f"πŸ“ Available files: {available_files}")
# 1. Load TensorFlow model
try:
model = load_model('best_bilstm_model.h5')
print("βœ… Model loaded successfully")
except Exception as e:
try:
model = load_model('best_bilstm_model.h5', compile=False)
print("βœ… Model loaded with compile=False")
except Exception as e2:
print(f"❌ Failed to load model: {e2}")
return False
# Get model info
try:
if hasattr(model, 'input_shape') and model.input_shape[1]:
max_length = model.input_shape[1]
print(f"πŸ“ Max length from model: {max_length}")
except:
print(f"πŸ“ Using default max length: {max_length}")
# 2. Load tokenizer and label encoder with multiple strategies
tokenizer_loaded = False
label_encoder_loaded = False
# Strategy 1: Try loading complete datasets object
if tokenizer_file == 'datasets.pkl':
try:
datasets = joblib.load('datasets.pkl')
if 'preprocessor' in datasets:
tokenizer = datasets['preprocessor'].tokenizer
label_encoder = datasets['preprocessor'].label_encoder
if hasattr(datasets['preprocessor'], 'label_encoder'):
emotion_labels = list(datasets['preprocessor'].label_encoder.classes_)
if 'config' in datasets and 'max_sequence_length' in datasets['config']:
max_length = datasets['config']['max_sequence_length']
print("βœ… Complete datasets loaded")
tokenizer_loaded = True
label_encoder_loaded = True
except Exception as e:
print(f"⚠️ Failed to load complete datasets: {e}")
# Strategy 2: Try loading preprocessor object
elif tokenizer_file == 'preprocessor.pkl':
try:
preprocessor = joblib.load('preprocessor.pkl')
if hasattr(preprocessor, 'tokenizer'):
tokenizer = preprocessor.tokenizer
tokenizer_loaded = True
if hasattr(preprocessor, 'label_encoder'):
label_encoder = preprocessor.label_encoder
emotion_labels = list(preprocessor.label_encoder.classes_)
label_encoder_loaded = True
print("βœ… Preprocessor object loaded")
except Exception as e:
print(f"⚠️ Failed to load preprocessor: {e}")
# Strategy 3: Load raw tokenizer
else:
try:
tokenizer = joblib.load(tokenizer_file)
print(f"βœ… Tokenizer loaded from {tokenizer_file}")
tokenizer_loaded = True
# Try to find separate label encoder
if os.path.exists('label_encoder.pkl'):
label_encoder = joblib.load('label_encoder.pkl')
emotion_labels = list(label_encoder.classes_)
label_encoder_loaded = True
except Exception as e:
print(f"⚠️ Failed to load tokenizer: {e}")
if not tokenizer_loaded:
print("❌ No tokenizer could be loaded")
return False
# Verify tokenizer
if not hasattr(tokenizer, 'word_index'):
print("❌ Invalid tokenizer object")
return False
# If no label encoder, create default mapping
if not label_encoder_loaded:
print("⚠️ No label encoder found, using default mapping")
from sklearn.preprocessing import LabelEncoder
label_encoder = LabelEncoder()
label_encoder.classes_ = np.array(emotion_labels)
vocab_size = len(tokenizer.word_index)
print(f"βœ… Components verified:")
print(f" β€’ Vocab size: {vocab_size:,}")
print(f" β€’ Max length: {max_length}")
print(f" β€’ Emotion labels: {emotion_labels}")
print(f" β€’ Label encoder: {'βœ…' if label_encoder_loaded else '⚠️ (default)'}")
return True
except ImportError as e:
print(f"❌ Missing packages: {e}")
return False
except Exception as e:
print(f"❌ Unexpected error: {e}")
return False
def predict_emotion_with_loaded_model(text):
"""Enhanced prediction with better error handling and confidence scoring"""
try:
import tensorflow as tf
from tensorflow.keras.preprocessing.sequence import pad_sequences
if not text or not text.strip():
return "❌ Error: Teks tidak boleh kosong"
if model is None or tokenizer is None:
return "❌ Error: Model atau tokenizer tidak dapat dimuat"
print(f"πŸ” Processing: '{text}'")
# Enhanced text cleaning
cleaned_text = clean_text_comprehensive(text)
print(f"🧹 Cleaned: '{cleaned_text}'")
if not cleaned_text:
return "❌ Error: Text kosong setelah preprocessing"
# Convert to sequences
sequences = tokenizer.texts_to_sequences([cleaned_text])
print(f"πŸ”’ Sequences: {sequences}")
if not sequences or not sequences[0]:
# Handle OOV case - try with original text
print("⚠️ Sequences empty, trying with less aggressive cleaning...")
simpler_clean = text.lower().strip()
sequences = tokenizer.texts_to_sequences([simpler_clean])
if not sequences or not sequences[0]:
return "❌ Error: Tidak dapat mengkonversi text ke sequences (terlalu banyak OOV words)"
# Pad sequences
padded = pad_sequences(sequences, maxlen=max_length, padding='post', truncating='post')
print(f"πŸ“ Padded shape: {padded.shape}")
# Make prediction with error handling
try:
predictions = model.predict(padded, verbose=0)
predicted_probs = predictions[0]
except Exception as pred_error:
return f"❌ Error dalam prediksi model: {str(pred_error)}"
print(f"🎯 Raw predictions: {predicted_probs}")
# Get predicted emotion with confidence threshold
predicted_idx = np.argmax(predicted_probs)
predicted_emotion = emotion_labels[predicted_idx]
confidence = float(predicted_probs[predicted_idx])
# Add confidence interpretation
if confidence < 0.3:
confidence_level = "RENDAH"
elif confidence < 0.6:
confidence_level = "SEDANG"
else:
confidence_level = "TINGGI"
# Format output with enhanced information
output = f"πŸ” Result:\n"
output += f"πŸ“ Original Text: {text}\n"
output += f"🧹 Cleaned Text: {cleaned_text}\n"
output += f"🎭 Predicted Emotion: {predicted_emotion.upper()}\n"
output += f"🎯 Confidence: {confidence:.3f} ({confidence*100:.1f}%) - {confidence_level}\n"
# Add sequence info for debugging
sequence_length = len([x for x in sequences[0] if x != 0]) # Non-padding tokens
output += f"πŸ“Š Sequence Info: {sequence_length} tokens dari {len(sequences[0])} max\n\n"
output += "πŸ“Š All Emotion Probabilities:\n"
# Create probability pairs and sort
prob_pairs = [(emotion_labels[i], predicted_probs[i]) for i in range(len(emotion_labels))]
prob_pairs.sort(key=lambda x: x[1], reverse=True)
for emotion, prob in prob_pairs:
bar_length = int(prob * 30)
bar = "β–ˆ" * bar_length + "β–‘" * (30 - bar_length)
output += f" {emotion:8} | {bar} | {prob:.3f} ({prob*100:.1f}%)\n"
# Add interpretation if confidence is low
if confidence < 0.4:
output += f"\n⚠️ PERHATIAN: Confidence rendah. Model kurang yakin dengan prediksi ini.\n"
output += f" Kemungkinan penyebab:\n"
output += f" β€’ Text mengandung banyak kata yang tidak dikenal model\n"
output += f" β€’ Text tidak jelas mengekspresikan emosi tertentu\n"
output += f" β€’ Text memiliki emosi campuran\n"
return output
except Exception as e:
print(f"❌ Prediction error: {e}")
return f"❌ Error dalam prediksi: {str(e)}\nDetail error untuk debugging: {type(e).__name__}"
def predict_demo_mode(text):
"""Enhanced demo prediction with better Indonesian keyword matching"""
if not text or not text.strip():
return "❌ Error: Teks tidak boleh kosong"
# Enhanced Indonesian keyword matching with emotional intensity
emotion_keywords = {
'happy': {
'primary': ['bahagia', 'senang', 'gembira', 'ceria', 'riang', 'sukses', 'bangga'],
'secondary': ['puas', 'suka', 'tertawa', 'tersenyum', 'beruntung', 'lega', 'syukur', 'hebat', 'keren', 'mantap'],
'intensifiers': ['sangat', 'sekali', 'banget', 'bgt', 'super', 'luar biasa']
},
'sadness': {
'primary': ['sedih', 'kecewa', 'galau', 'duka', 'terpuruk', 'hancur'],
'secondary': ['patah hati', 'kehilangan', 'menyesal', 'putus asa', 'lemah', 'kosong', 'hampa', 'nelangsa'],
'intensifiers': ['sangat', 'sekali', 'banget', 'bgt', 'amat']
},
'anger': {
'primary': ['marah', 'kesal', 'benci', 'jengkel', 'dongkol', 'murka'],
'secondary': ['geram', 'sebal', 'sebel', 'berang', 'gusar', 'emosi', 'panas', 'gondok'],
'intensifiers': ['sangat', 'sekali', 'banget', 'bgt', 'amat']
},
'fear': {
'primary': ['takut', 'cemas', 'khawatir', 'panik', 'gelisah'],
'secondary': ['was-was', 'nervous', 'tegang', 'deg-degan', 'grogi', 'resah', 'waspada'],
'intensifiers': ['sangat', 'sekali', 'banget', 'bgt', 'amat']
},
'love': {
'primary': ['cinta', 'sayang', 'kasih', 'rindu', 'romantis'],
'secondary': ['mesra', 'setia', 'mencintai', 'menyayangi', 'kangen', 'vermissen', 'asmara'],
'intensifiers': ['sangat', 'sekali', 'banget', 'bgt', 'amat']
}
}
# Clean and analyze text
cleaned_text = clean_text_comprehensive(text)
text_words = cleaned_text.lower().split()
# Calculate weighted scores
scores = {emotion: 0.0 for emotion in emotion_keywords.keys()}
found_keywords = {emotion: [] for emotion in emotion_keywords.keys()}
for emotion, keyword_groups in emotion_keywords.items():
# Primary keywords (higher weight)
for keyword in keyword_groups['primary']:
if keyword in cleaned_text.lower():
scores[emotion] += 3.0
found_keywords[emotion].append(f"{keyword} (primary)")
elif keyword in text_words:
scores[emotion] += 2.5
found_keywords[emotion].append(f"{keyword} (primary-word)")
# Secondary keywords (medium weight)
for keyword in keyword_groups['secondary']:
if keyword in cleaned_text.lower():
scores[emotion] += 2.0
found_keywords[emotion].append(f"{keyword} (secondary)")
elif keyword in text_words:
scores[emotion] += 1.5
found_keywords[emotion].append(f"{keyword} (secondary-word)")
# Intensifier bonus
for intensifier in keyword_groups['intensifiers']:
if intensifier in text_words:
scores[emotion] *= 1.2 # 20% bonus
if found_keywords[emotion]: # Only if emotion already detected
found_keywords[emotion].append(f"{intensifier} (intensifier)")
# If no strong emotion detected, check for neutral positive indicators
if sum(scores.values()) == 0:
neutral_positive = ['baik', 'oke', 'normal', 'biasa', 'standar']
if any(word in text_words for word in neutral_positive):
scores['happy'] = 1.0
else:
scores['happy'] = 0.5 # Default mild positive
# Normalize scores
total_score = sum(scores.values())
for emotion in scores:
scores[emotion] = scores[emotion] / total_score if total_score > 0 else 0
# Get prediction
predicted_emotion = max(scores, key=scores.get)
confidence = scores[predicted_emotion]
# Format output
output = f"πŸ” DEMO Result:\n"
output += f"πŸ“ Original Text: {text}\n"
output += f"🧹 Cleaned Text: {cleaned_text}\n"
output += f"🎭 Predicted Emotion: {predicted_emotion.upper()}\n"
output += f"🎯 Confidence: {confidence:.3f} ({confidence*100:.1f}%)\n\n"
# Show found keywords for transparency
if found_keywords[predicted_emotion]:
output += f"πŸ” Keywords found for {predicted_emotion}: {', '.join(found_keywords[predicted_emotion])}\n\n"
output += "πŸ“Š All Emotion Probabilities:\n"
# Sort and display
sorted_emotions = sorted(scores.items(), key=lambda x: x[1], reverse=True)
for emotion, prob in sorted_emotions:
bar_length = int(prob * 30)
bar = "β–ˆ" * bar_length + "β–‘" * (30 - bar_length)
output += f" {emotion:8} | {bar} | {prob:.3f} ({prob*100:.1f}%)\n"
output += "\n⚠️ DEMO MODE: Menggunakan keyword matching.\n"
output += "Upload file model untuk hasil akurat."
return output
# Initialize system
print("πŸš€ Initializing Indonesian Emotion Classifier...")
available_files, missing_files, tokenizer_file = check_available_files()
if missing_files:
print(f"❌ Missing files: {missing_files}")
predict_function = predict_demo_mode
app_title = "🎭 Indonesian Emotion Classifier (DEMO)"
app_description = f"""
🚨 **DEMO MODE**: Beberapa file tidak ditemukan!
**File yang ada:** {available_files if available_files else 'Tidak ada'}
**File yang hilang:** {missing_files}
**Untuk mode penuh, upload file berikut:**
- `best_bilstm_model.h5` (model yang dilatih)
- File tokenizer: `tokenizer_raw.pkl` ATAU `datasets.pkl` ATAU `preprocessor.pkl`
Saat ini menggunakan enhanced keyword matching dengan dukungan bahasa Indonesia yang lebih baik.
"""
else:
# Try to load model system
model_loaded = load_model_and_components()
if model_loaded:
print("βœ… Model system loaded successfully!")
predict_function = predict_emotion_with_loaded_model
app_title = "🎭 Indonesian Emotion Classifier"
app_description = """
**Klasifikasi emosi untuk teks bahasa Indonesia menggunakan BiLSTM.**
βœ… **Model fully loaded dan siap digunakan!**
**Emotions:** anger, fear, happy, love, sadness
Model menggunakan arsitektur BiLSTM dengan preprocessing yang dioptimalkan untuk bahasa Indonesia.
Dilengkapi dengan enhanced text cleaning dan confidence scoring.
"""
else:
print("⚠️ Model loading failed, using enhanced demo mode")
predict_function = predict_demo_mode
app_title = "🎭 Indonesian Emotion Classifier (ENHANCED DEMO)"
app_description = """
🚨 **ENHANCED DEMO MODE**: File ditemukan tapi gagal dimuat!
Kemungkinan ada masalah kompatibilitas. Menggunakan enhanced keyword matching
dengan dukungan bahasa Indonesia yang lebih baik dan weighted scoring.
"""
# Enhanced examples with more diverse Indonesian text
enhanced_examples = [
# Happy examples
["Aku senang banget tahun ini banyak pencapaian"],
["Saya sangat bahagia hari ini, semuanya berjalan lancar"],
["Wah, hasil ujianku bagus banget! Luar biasa!"],
["Hari ini cuaca sangat cerah dan indah, bikin hati senang"],
["Terima kasih atas semua bantuan kalian, aku terharu"],
# Angry examples
["Saya marah sekali dengan kejadian ini, tidak adil!"],
["Kesal banget sama pelayanan yang buruk ini"],
["Geram lihat ketidakadilan seperti ini terus terjadi"],
# Sad examples
["Saya sedih banget hari ini, rasanya kosong"],
["Dia sudah pergi dan tidak akan kembali, hatiku hancur"],
["Kenapa hidup ini begitu sulit? Aku lelah"],
["Patah hati rasanya seperti dunia berakhir"],
# Fear examples
["Saya takut dengan situasi ini, tidak tahu harus berbuat apa"],
["Aku khawatir dengan masa depan yang tidak pasti"],
["Cemas banget menghadapi ujian besok"],
# Love examples
["Saya cinta kamu selamanya, tidak akan berubah"],
["Rindu banget sama keluarga di kampung halaman"],
["Aku sayang sekali sama teman-teman terbaikku"]
]
# Create interface
demo = gr.Interface(
fn=predict_function,
inputs=[
gr.Textbox(
label="Input Text (Bahasa Indonesia)",
placeholder="Masukkan kalimat dalam bahasa Indonesia...",
lines=3,
max_lines=5
)
],
outputs=[
gr.Textbox(
label="Emotion Analysis Result",
lines=15,
max_lines=25,
show_copy_button=True
)
],
title=app_title,
description=app_description,
examples=enhanced_examples,
cache_examples=False,
theme=gr.themes.Soft(),
analytics_enabled=False
)
if __name__ == "__main__":
print("πŸš€ Starting Enhanced Indonesian Emotion Classifier...")
if ON_SPACES:
demo.launch()
else:
demo.launch(
server_name="0.0.0.0",
server_port=7860,
share=False
)
print("βœ… App launched successfully!")