File size: 23,616 Bytes
fe7219e
d6550ca
b025efa
6486c8f
aacc12e
60b118e
fe7219e
d6550ca
6486c8f
 
d6550ca
 
 
aacc12e
 
 
60b118e
aacc12e
 
 
 
 
 
d6550ca
 
aacc12e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d6550ca
aacc12e
d6550ca
aacc12e
 
60b118e
aacc12e
 
 
 
60b118e
aacc12e
 
60b118e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aacc12e
60b118e
aacc12e
 
 
 
 
60b118e
 
aacc12e
60b118e
 
 
 
aacc12e
 
 
 
 
60b118e
 
 
 
aacc12e
 
6486c8f
60b118e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aacc12e
60b118e
 
aacc12e
 
d6550ca
 
aacc12e
d6550ca
b025efa
6486c8f
d6550ca
aacc12e
d6550ca
 
 
 
 
aacc12e
 
 
6486c8f
aacc12e
d6550ca
 
6486c8f
aacc12e
6486c8f
 
d6550ca
 
fe7219e
aacc12e
d6550ca
aacc12e
 
 
 
 
 
60b118e
aacc12e
60b118e
aacc12e
 
 
 
 
 
 
60b118e
aacc12e
 
 
 
 
 
60b118e
aacc12e
 
 
 
 
 
 
 
 
60b118e
aacc12e
60b118e
aacc12e
60b118e
aacc12e
 
 
 
 
 
 
 
 
 
60b118e
 
 
 
 
aacc12e
 
 
 
 
d6550ca
6486c8f
aacc12e
 
 
 
 
60b118e
 
 
 
 
 
 
aacc12e
60b118e
aacc12e
 
 
60b118e
6486c8f
 
 
d6550ca
aacc12e
d6550ca
6486c8f
d6550ca
6486c8f
 
aacc12e
60b118e
fe7219e
d6550ca
 
 
b025efa
d6550ca
fe7219e
 
d6550ca
b025efa
aacc12e
 
60b118e
aacc12e
 
fe7219e
aacc12e
 
fe7219e
d6550ca
aacc12e
 
fe7219e
b025efa
60b118e
 
 
 
 
 
fe7219e
b025efa
60b118e
aacc12e
fe7219e
60b118e
 
 
 
 
 
aacc12e
 
fe7219e
60b118e
b025efa
 
aacc12e
fe7219e
60b118e
 
 
 
 
 
 
 
 
aacc12e
 
 
60b118e
 
 
 
 
 
 
 
b025efa
aacc12e
 
 
d6550ca
aacc12e
 
60b118e
 
 
 
 
 
 
 
 
 
b025efa
d6550ca
fe7219e
 
aacc12e
60b118e
fe7219e
aacc12e
60b118e
aacc12e
 
 
60b118e
aacc12e
60b118e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aacc12e
 
 
 
 
 
60b118e
 
 
aacc12e
60b118e
 
 
aacc12e
60b118e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aacc12e
60b118e
 
 
 
 
aacc12e
 
 
 
 
 
 
 
 
 
 
 
 
 
60b118e
aacc12e
60b118e
 
 
 
 
 
aacc12e
 
 
 
 
60b118e
 
aacc12e
 
 
 
 
 
 
d6550ca
 
aacc12e
d6550ca
aacc12e
 
 
 
 
 
fe7219e
aacc12e
 
fe7219e
aacc12e
 
 
fe7219e
60b118e
b025efa
aacc12e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60b118e
aacc12e
 
60b118e
aacc12e
60b118e
aacc12e
60b118e
aacc12e
60b118e
 
aacc12e
b025efa
60b118e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aacc12e
b025efa
d6550ca
b025efa
 
aacc12e
b025efa
aacc12e
 
b025efa
 
 
 
 
60b118e
 
aacc12e
b025efa
 
aacc12e
d6550ca
60b118e
b025efa
d6550ca
 
b025efa
 
fe7219e
60b118e
6486c8f
d6550ca
 
 
 
aacc12e
d6550ca
 
 
6486c8f
aacc12e
1
2
3
4
5
6
7
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
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!")