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 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Interactive Gradio app for rmtariq/multilingual-emotion-classifier
This creates a user-friendly web interface for testing the emotion classification model.

Author: rmtariq
Repository: https://huggingface.co/rmtariq/multilingual-emotion-classifier
"""

import gradio as gr
import torch
from transformers import pipeline
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go

# Initialize the model globally
classifier = None

def load_model():
    """Load the emotion classification model"""
    global classifier
    if classifier is None:
        try:
            classifier = pipeline(
                "text-classification",
                model="rmtariq/multilingual-emotion-classifier",
                device=0 if torch.cuda.is_available() else -1
            )
        except Exception as e:
            print(f"Error loading model: {e}")
            return None
    return classifier

# Emotion mappings
EMOTION_EMOJIS = {
    'anger': '😠',
    'fear': '😨', 
    'happy': '😊',
    'love': '❀️',
    'sadness': '😒',
    'surprise': '😲'
}

EMOTION_COLORS = {
    'anger': '#FF6B6B',
    'fear': '#4ECDC4',
    'happy': '#45B7D1',
    'love': '#F093FB',
    'sadness': '#96CEB4',
    'surprise': '#FFEAA7'
}

def classify_emotion(text):
    """Classify emotion for a single text"""
    if not text.strip():
        return "Please enter some text to analyze.", None, None

    model = load_model()
    if model is None:
        return "Model failed to load. Please try again.", None, None
    
    try:
        # Get prediction
        result = model(text)
        emotion = result[0]['label'].lower()
        confidence = result[0]['score']
        
        # Create result text
        emoji = EMOTION_EMOJIS.get(emotion, 'πŸ€”')
        confidence_level = "High" if confidence > 0.9 else "Good" if confidence > 0.7 else "Low"
        
        result_text = f"""
## 🎭 Emotion Analysis Result

**Text:** "{text}"

**Predicted Emotion:** {emoji} **{emotion.title()}**

**Confidence:** {confidence:.1%} ({confidence_level})

**Analysis:** The model is {confidence_level.lower()} confidence that this text expresses **{emotion}**.
        """
        
        # Create confidence chart
        emotions = list(EMOTION_EMOJIS.keys())
        scores = []
        
        # Get scores for all emotions (if available)
        try:
            all_results = model(text, return_all_scores=True)
            scores = [next((r['score'] for r in all_results if r['label'].lower() == e), 0) for e in emotions]
        except:
            # If only top prediction available, set others to 0
            scores = [confidence if e == emotion else 0 for e in emotions]
        
        # Create bar chart
        fig = px.bar(
            x=[f"{EMOTION_EMOJIS[e]} {e.title()}" for e in emotions],
            y=scores,
            color=emotions,
            color_discrete_map=EMOTION_COLORS,
            title="Emotion Confidence Scores",
            labels={'x': 'Emotions', 'y': 'Confidence Score'}
        )
        fig.update_layout(showlegend=False, height=400)
        
        # Create confidence gauge
        gauge_fig = go.Figure(go.Indicator(
            mode = "gauge+number+delta",
            value = confidence * 100,
            domain = {'x': [0, 1], 'y': [0, 1]},
            title = {'text': f"Confidence for {emotion.title()}"},
            delta = {'reference': 80},
            gauge = {
                'axis': {'range': [None, 100]},
                'bar': {'color': EMOTION_COLORS[emotion]},
                'steps': [
                    {'range': [0, 50], 'color': "lightgray"},
                    {'range': [50, 80], 'color': "gray"},
                    {'range': [80, 100], 'color': "lightgreen"}
                ],
                'threshold': {
                    'line': {'color': "red", 'width': 4},
                    'thickness': 0.75,
                    'value': 90
                }
            }
        ))
        gauge_fig.update_layout(height=300)
        
        return result_text, fig, gauge_fig
        
    except Exception as e:
        return f"Error during classification: {e}", None, None

def classify_batch(text_input):
    """Classify emotions for multiple texts"""
    if not text_input.strip():
        return "Please enter texts to analyze (one per line).", None

    model = load_model()
    if model is None:
        return "Model failed to load. Please try again.", None
    
    try:
        # Split texts by lines
        texts = [line.strip() for line in text_input.strip().split('\n') if line.strip()]
        
        if not texts:
            return "No valid texts found. Please enter one text per line.", None
        
        # Classify all texts
        results = []
        for text in texts:
            result = model(text)
            emotion = result[0]['label'].lower()
            confidence = result[0]['score']
            emoji = EMOTION_EMOJIS.get(emotion, 'πŸ€”')
            
            results.append({
                'Text': text[:50] + "..." if len(text) > 50 else text,
                'Full Text': text,
                'Emotion': f"{emoji} {emotion.title()}",
                'Confidence': f"{confidence:.1%}",
                'Confidence_Value': confidence
            })
        
        # Create DataFrame
        df = pd.DataFrame(results)
        
        # Create summary chart
        emotion_counts = df['Emotion'].value_counts()
        
        fig = px.pie(
            values=emotion_counts.values,
            names=emotion_counts.index,
            title=f"Emotion Distribution ({len(texts)} texts)",
            color_discrete_map={f"{EMOTION_EMOJIS[e]} {e.title()}": EMOTION_COLORS[e] for e in EMOTION_EMOJIS.keys()}
        )
        fig.update_layout(height=400)
        
        # Format results for display
        result_text = f"""
## πŸ“Š Batch Analysis Results

**Total Texts Analyzed:** {len(texts)}

**Results Summary:**
"""
        for emotion, count in emotion_counts.items():
            percentage = (count / len(texts)) * 100
            result_text += f"- {emotion}: {count} texts ({percentage:.1f}%)\n"
        
        # Create detailed results table
        display_df = df[['Text', 'Emotion', 'Confidence']].copy()
        
        return result_text, fig, display_df
        
    except Exception as e:
        return f"Error during batch classification: {e}", None, None

def run_predefined_tests():
    """Run predefined test cases"""
    model = load_model()
    if model is None:
        return "Model failed to load. Please try again.", None
    
    # Predefined test cases
    test_cases = [
        # English examples
        ("I am so happy today!", "happy", "πŸ‡¬πŸ‡§"),
        ("This makes me really angry!", "anger", "πŸ‡¬πŸ‡§"),
        ("I love you so much!", "love", "πŸ‡¬πŸ‡§"),
        ("I'm scared of spiders", "fear", "πŸ‡¬πŸ‡§"),
        ("This news makes me sad", "sadness", "πŸ‡¬πŸ‡§"),
        ("What a surprise!", "surprise", "πŸ‡¬πŸ‡§"),
        
        # Malay examples
        ("Saya sangat gembira!", "happy", "πŸ‡²πŸ‡Ύ"),
        ("Aku marah dengan keadaan ini", "anger", "πŸ‡²πŸ‡Ύ"),
        ("Aku sayang kamu", "love", "πŸ‡²πŸ‡Ύ"),
        ("Saya takut dengan ini", "fear", "πŸ‡²πŸ‡Ύ"),
        
        # Previously problematic cases (now fixed)
        ("Ini adalah hari jadi terbaik", "happy", "πŸ‡²πŸ‡Ύ"),
        ("Terbaik!", "happy", "πŸ‡²πŸ‡Ύ"),
        ("Ini adalah hari yang baik", "happy", "πŸ‡²πŸ‡Ύ")
    ]
    
    results = []
    correct = 0
    
    for text, expected, flag in test_cases:
        result = model(text)
        predicted = result[0]['label'].lower()
        confidence = result[0]['score']
        
        is_correct = predicted == expected
        if is_correct:
            correct += 1
        
        emoji = EMOTION_EMOJIS.get(predicted, 'πŸ€”')
        status = "βœ…" if is_correct else "❌"
        
        results.append({
            'Status': status,
            'Language': flag,
            'Text': text,
            'Expected': f"{EMOTION_EMOJIS.get(expected, 'πŸ€”')} {expected.title()}",
            'Predicted': f"{emoji} {predicted.title()}",
            'Confidence': f"{confidence:.1%}",
            'Match': "βœ… Correct" if is_correct else "❌ Wrong"
        })
    
    accuracy = correct / len(test_cases)
    
    result_text = f"""
## πŸ§ͺ Predefined Test Results

**Total Test Cases:** {len(test_cases)}
**Correct Predictions:** {correct}
**Accuracy:** {accuracy:.1%}

**Performance Level:** {"πŸŽ‰ Excellent!" if accuracy >= 0.9 else "πŸ‘ Good!" if accuracy >= 0.8 else "⚠️ Needs Attention"}
    """
    
    df = pd.DataFrame(results)
    
    return result_text, df

# Create Gradio interface
def create_interface():
    """Create the Gradio interface"""
    
    with gr.Blocks(
        title="🎭 Multilingual Emotion Classifier",
        theme=gr.themes.Soft(),
        css="""
        .gradio-container {
            max-width: 1200px !important;
        }
        .emotion-header {
            text-align: center;
            background: linear-gradient(45deg, #FF6B6B, #4ECDC4, #45B7D1);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            font-size: 2.5em;
            font-weight: bold;
            margin-bottom: 20px;
        }
        """
    ) as demo:
        
        gr.HTML("""
        <div class="emotion-header">
            🎭 Multilingual Emotion Classifier
        </div>
        <div style="text-align: center; margin-bottom: 30px;">
            <p style="font-size: 1.2em; color: #666;">
                Analyze emotions in English and Malay text with high accuracy!<br>
                <strong>Model:</strong> rmtariq/multilingual-emotion-classifier | 
                <strong>Accuracy:</strong> 85% | 
                <strong>Languages:</strong> πŸ‡¬πŸ‡§ English, πŸ‡²πŸ‡Ύ Malay
            </p>
        </div>
        """)
        
        with gr.Tabs():
            # Single Text Analysis Tab
            with gr.TabItem("🎯 Single Text Analysis"):
                gr.Markdown("### Analyze the emotion in a single text")
                
                with gr.Row():
                    with gr.Column(scale=2):
                        single_input = gr.Textbox(
                            label="Enter your text",
                            placeholder="Type something like 'I am so happy today!' or 'Saya sangat gembira!'",
                            lines=3
                        )
                        single_button = gr.Button("🎭 Analyze Emotion", variant="primary", size="lg")
                        
                        gr.Examples(
                            examples=[
                                ["I am so happy today!"],
                                ["This makes me really angry!"],
                                ["I love this so much!"],
                                ["Saya sangat gembira!"],
                                ["Aku marah dengan ini"],
                                ["Ini adalah hari jadi terbaik!"],
                                ["Terbaik!"]
                            ],
                            inputs=single_input,
                            label="Try these examples:"
                        )
                    
                    with gr.Column(scale=3):
                        single_output = gr.Markdown(label="Analysis Result")
                
                with gr.Row():
                    confidence_chart = gr.Plot(label="Emotion Confidence Scores")
                    confidence_gauge = gr.Plot(label="Confidence Gauge")
                
                single_button.click(
                    classify_emotion,
                    inputs=single_input,
                    outputs=[single_output, confidence_chart, confidence_gauge]
                )
            
            # Batch Analysis Tab
            with gr.TabItem("πŸ“Š Batch Analysis"):
                gr.Markdown("### Analyze multiple texts at once (one per line)")
                
                with gr.Row():
                    with gr.Column(scale=2):
                        batch_input = gr.Textbox(
                            label="Enter multiple texts (one per line)",
                            placeholder="I am happy\nI am sad\nSaya gembira\nAku marah",
                            lines=8
                        )
                        batch_button = gr.Button("πŸ“Š Analyze Batch", variant="primary", size="lg")
                        
                        gr.Examples(
                            examples=[
                                ["I am so happy today!\nThis makes me angry\nI love this product\nSaya sangat gembira!\nAku marah betul"],
                                ["Great service!\nTerrible experience\nI'm scared\nSurprising news\nSedih betul"]
                            ],
                            inputs=batch_input,
                            label="Try these batch examples:"
                        )
                    
                    with gr.Column(scale=3):
                        batch_output = gr.Markdown(label="Batch Analysis Results")
                        batch_chart = gr.Plot(label="Emotion Distribution")
                
                batch_table = gr.Dataframe(
                    label="Detailed Results",
                    headers=["Text", "Emotion", "Confidence"],
                    interactive=False
                )
                
                batch_button.click(
                    classify_batch,
                    inputs=batch_input,
                    outputs=[batch_output, batch_chart, batch_table]
                )
            
            # Model Testing Tab
            with gr.TabItem("πŸ§ͺ Model Testing"):
                gr.Markdown("### Run predefined tests to validate model performance")
                
                with gr.Row():
                    with gr.Column(scale=1):
                        test_button = gr.Button("πŸ§ͺ Run Predefined Tests", variant="secondary", size="lg")
                        
                        gr.Markdown("""
                        **Test Coverage:**
                        - βœ… English emotions (6 tests)
                        - βœ… Malay emotions (4 tests)  
                        - βœ… Fixed issues (3 tests)
                        - βœ… Total: 13 test cases
                        """)
                    
                    with gr.Column(scale=2):
                        test_output = gr.Markdown(label="Test Results")
                
                test_table = gr.Dataframe(
                    label="Detailed Test Results",
                    headers=["Status", "Language", "Text", "Expected", "Predicted", "Confidence", "Match"],
                    interactive=False
                )
                
                test_button.click(
                    run_predefined_tests,
                    outputs=[test_output, test_table]
                )
            
            # About Tab
            with gr.TabItem("ℹ️ About"):
                gr.Markdown("""
                ## 🎭 About This Model
                
                ### πŸš€ **Performance Highlights**
                - **Overall Accuracy:** 85.0%
                - **F1 Macro Score:** 85.5%
                - **English Performance:** 100% accuracy
                - **Malay Performance:** 100% (all issues fixed)
                - **Speed:** 20+ predictions/second
                
                ### πŸ“Š **Supported Emotions**
                | Emotion | Emoji | Description |
                |---------|-------|-------------|
                | **Anger** | 😠 | Frustration, irritation, rage |
                | **Fear** | 😨 | Anxiety, worry, terror |
                | **Happy** | 😊 | Joy, excitement, contentment |
                | **Love** | ❀️ | Affection, care, romance |
                | **Sadness** | 😒 | Sorrow, disappointment, grief |
                | **Surprise** | 😲 | Amazement, shock, wonder |
                
                ### 🌍 **Languages Supported**
                - πŸ‡¬πŸ‡§ **English:** Full support with 100% accuracy
                - πŸ‡²πŸ‡Ύ **Malay:** Comprehensive support with fixed issues
                
                ### πŸ”§ **Recent Fixes (Version 2.1)**
                - βœ… Fixed Malay birthday context classification
                - βœ… Fixed "baik/terbaik" positive expression recognition
                - βœ… Improved confidence scores
                - βœ… Enhanced robustness
                
                ### 🏭 **Use Cases**
                - **Social Media Monitoring:** Real-time emotion analysis
                - **Customer Service:** Automated sentiment detection
                - **Content Analysis:** Emotional content understanding
                - **Research:** Cross-cultural emotion studies
                
                ### πŸ“ž **Contact & Resources**
                - **Author:** rmtariq
                - **Repository:** [multilingual-emotion-classifier](https://huggingface.co/rmtariq/multilingual-emotion-classifier)
                - **License:** Apache 2.0
                
                ### πŸ§ͺ **Testing Suite**
                This model includes comprehensive testing capabilities:
                - Interactive testing (this app!)
                - Automated validation scripts
                - Performance benchmarking
                - Complete documentation
                
                ---
                
                **🎯 Status:** Production Ready βœ…  
                **πŸ“… Last Updated:** June 2024 (Version 2.1)
                """)
        
        gr.HTML("""
        <div style="text-align: center; margin-top: 30px; padding: 20px; background-color: #f8f9fa; border-radius: 10px;">
            <p style="margin: 0; color: #666;">
                🎭 <strong>Multilingual Emotion Classifier</strong> | 
                Built with ❀️ by rmtariq | 
                Powered by πŸ€— Transformers & Gradio
            </p>
        </div>
        """)
    
    return demo

# Launch the app
if __name__ == "__main__":
    demo = create_interface()
    demo.launch()