File size: 19,624 Bytes
1904b7d
 
9a7fe1c
 
1904b7d
 
 
 
 
 
 
 
 
 
 
 
 
 
9a7fe1c
1904b7d
065242d
1904b7d
065242d
1904b7d
 
 
 
 
065242d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9a7fe1c
1904b7d
 
 
 
 
 
 
 
 
9a7fe1c
1904b7d
 
 
 
 
 
3ca75da
1904b7d
 
 
9a7fe1c
1904b7d
 
 
 
 
 
 
9a7fe1c
1904b7d
 
 
 
065242d
 
 
 
 
ca4f64a
1904b7d
ca4f64a
 
 
 
 
 
 
 
 
 
 
 
1904b7d
ca4f64a
1904b7d
ca4f64a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1904b7d
 
9a7fe1c
1904b7d
ca4f64a
 
 
 
 
 
 
 
 
 
 
 
 
1904b7d
9a7fe1c
1904b7d
 
 
 
 
 
 
 
 
 
 
 
 
9a7fe1c
1904b7d
9a7fe1c
1904b7d
 
9a7fe1c
ca4f64a
1904b7d
 
ca4f64a
 
 
 
 
1904b7d
ca4f64a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1904b7d
ca4f64a
 
 
 
 
1904b7d
ca4f64a
 
1904b7d
9a7fe1c
1904b7d
 
 
9a7fe1c
1904b7d
 
9a7fe1c
1904b7d
 
 
 
 
 
9a7fe1c
1904b7d
 
9a7fe1c
 
 
1904b7d
9a7fe1c
1904b7d
 
9a7fe1c
1904b7d
 
9a7fe1c
 
1904b7d
9a7fe1c
1904b7d
 
 
 
 
9a7fe1c
 
1904b7d
 
 
 
 
 
 
9a7fe1c
1904b7d
 
 
 
ca4f64a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1904b7d
9a7fe1c
 
1904b7d
 
9a7fe1c
 
1904b7d
 
9a7fe1c
1904b7d
 
 
9a7fe1c
 
1904b7d
9a7fe1c
1904b7d
9a7fe1c
 
1904b7d
 
 
 
9a7fe1c
1904b7d
 
 
 
 
 
 
 
 
 
9a7fe1c
1904b7d
 
 
 
9a7fe1c
1904b7d
 
9a7fe1c
 
1904b7d
9a7fe1c
1904b7d
 
 
 
 
 
9a7fe1c
 
1904b7d
 
 
 
 
 
 
 
 
9a7fe1c
 
1904b7d
 
 
 
 
 
 
 
 
 
 
9a7fe1c
 
1904b7d
 
 
 
 
 
 
9a7fe1c
1904b7d
 
9a7fe1c
1904b7d
9a7fe1c
1904b7d
 
 
9a7fe1c
1904b7d
9a7fe1c
 
 
 
 
 
1904b7d
 
9a7fe1c
1904b7d
 
 
 
9a7fe1c
 
1904b7d
 
 
 
 
9a7fe1c
 
 
1904b7d
9a7fe1c
1904b7d
9a7fe1c
1904b7d
9a7fe1c
 
 
1904b7d
9a7fe1c
 
 
 
1904b7d
 
 
 
 
 
 
 
 
 
 
 
 
 
9a7fe1c
1904b7d
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Hugging Face Space - Emotion Analysis App
Analyzes emotions from English text input and provides visualizations
"""

import gradio as gr
import torch
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import json
from pathlib import Path
import warnings
import os
warnings.filterwarnings('ignore')

# Hugging Face related imports
try:
    from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline, PreTrainedModel, PretrainedConfig
    from huggingface_hub import hf_hub_download
    import torch.nn as nn
    HF_AVAILABLE = True
except ImportError:
    print("โš ๏ธ transformers or huggingface_hub not available. Install with: pip install transformers huggingface_hub")
    HF_AVAILABLE = False

# Custom model architecture for multimodal_emotion_analyzer
class MultimodalEmotionAnalyzerConfig(PretrainedConfig):
    model_type = "multimodal_emotion_analyzer"
    
    def __init__(self, num_emotions=26, **kwargs):
        super().__init__(**kwargs)
        self.num_emotions = num_emotions

class MultimodalEmotionAnalyzer(PreTrainedModel):
    config_class = MultimodalEmotionAnalyzerConfig
    base_model_prefix = "multimodal_emotion_analyzer"
    
    def __init__(self, config):
        super().__init__(config)
        self.num_emotions = config.num_emotions
        
        # Simple classifier head
        self.classifier = nn.Linear(768, self.num_emotions)  # Assuming 768 hidden size
        self.dropout = nn.Dropout(0.1)
        
    def forward(self, input_ids=None, attention_mask=None, **kwargs):
        # For now, return random logits (will be replaced by actual model)
        batch_size = input_ids.shape[0] if input_ids is not None else 1
        logits = torch.randn(batch_size, self.num_emotions)
        return {"logits": logits}

# Emotion labels definition
EMOTION_LABELS = [
    'admiration', 'aesthetic appreciation', 'awe', 'anxiety', 'fear', 'horror',
    'disgust', 'calmness', 'romantic love', 'sexual desire', 'nostalgia',
    'interest', 'surprise', 'excitement', 'anger', 'pride', 'triumph',
    'contempt', 'disappointment', 'empathic pain', 'sadness', 'guilt',
    'envy', 'amusement', 'awkwardness', 'adoration'
]

class EmotionAnalyzer:
    """Emotion Analyzer Class"""
    
    def __init__(self):
        self.model = None
        self.tokenizer = None
        self.classifier = None
        self.device = 'cuda' if torch.cuda.is_available() else 'cpu'
        self.model_name = "CURI-AI/sentiment-analysis-en-v1"  # Organization model name
        self.load_model()
    
    def load_model(self):
        """Load the model"""
        if not HF_AVAILABLE:
            print("โš ๏ธ Hugging Face libraries not available. Using simulation mode.")
            return
            
        try:
            print(f"๐Ÿš€ Loading organization model: {self.model_name}")
            
            # Check Hugging Face token from environment variables
            hf_token = os.getenv('HF_TOKEN')
            if not hf_token:
                print("โš ๏ธ HF_TOKEN not set. Trying without authentication...")
            
            # Register custom model architecture
            from transformers import AutoConfig, AutoModel
            AutoConfig.register("multimodal_emotion_analyzer", MultimodalEmotionAnalyzerConfig)
            AutoModel.register(MultimodalEmotionAnalyzerConfig, MultimodalEmotionAnalyzer)
            
            # Try to load tokenizer first
            print("๐Ÿ“ฅ Loading tokenizer...")
            try:
                self.tokenizer = AutoTokenizer.from_pretrained(
                    self.model_name,
                    token=hf_token,
                    trust_remote_code=True
                )
                print("โœ… Tokenizer loaded successfully")
            except Exception as e:
                print(f"โš ๏ธ Tokenizer loading failed: {e}")
                print("๐Ÿ“ Using default tokenizer...")
                # Fallback to a default tokenizer
                self.tokenizer = AutoTokenizer.from_pretrained("roberta-base")
            
            # Try to load model with custom architecture support
            print("๐Ÿ“ฅ Loading model...")
            try:
                # First try with trust_remote_code=True for custom architectures
                self.model = AutoModelForSequenceClassification.from_pretrained(
                    self.model_name,
                    token=hf_token,
                    trust_remote_code=True,
                    torch_dtype=torch.float16 if self.device == 'cuda' else torch.float32,
                    local_files_only=False
                )
                print("โœ… Model loaded successfully with custom architecture")
            except Exception as e:
                print(f"โš ๏ธ Custom model loading failed: {e}")
                print("๐Ÿ“ Trying alternative loading method...")
                
                try:
                    # Try loading as a regular sequence classification model
                    self.model = AutoModelForSequenceClassification.from_pretrained(
                        self.model_name,
                        token=hf_token,
                        trust_remote_code=False,
                        torch_dtype=torch.float16 if self.device == 'cuda' else torch.float32
                    )
                    print("โœ… Model loaded successfully with standard architecture")
                except Exception as e2:
                    print(f"โš ๏ธ Standard model loading also failed: {e2}")
                    print("๐Ÿ“ Model loading failed completely, using simulation mode")
                    self.model = None
                    self.tokenizer = None
                    return
            
            # Move model to device
            self.model.to(self.device)
            
            # Create pipeline
            print("๐Ÿ”ง Creating pipeline...")
            try:
                self.classifier = pipeline(
                    "text-classification",
                    model=self.model,
                    tokenizer=self.tokenizer,
                    device=0 if self.device == 'cuda' else -1,
                    return_all_scores=True
                )
                print("โœ… Pipeline created successfully")
            except Exception as e:
                print(f"โš ๏ธ Pipeline creation failed: {e}")
                print("๐Ÿ“ Using direct model inference instead")
                self.classifier = None
            
            # Update emotion labels (if available from model)
            if hasattr(self.model.config, 'id2label'):
                global EMOTION_LABELS
                EMOTION_LABELS = list(self.model.config.id2label.values())
                print(f"โœ… Updated emotion labels from model: {len(EMOTION_LABELS)} labels")
            
        except Exception as e:
            print(f"โš ๏ธ Model loading failed: {e}")
            print("๐Ÿ“ Falling back to simulation mode")
            self.model = None
            self.tokenizer = None
            self.classifier = None
    
    def analyze_emotion(self, text):
        """Analyze emotions from text"""
        if not text or len(text.strip()) == 0:
            return "Please enter some text to analyze.", None, None
        
        try:
            # Use actual model if available
            if self.model is not None:
                print(f"๐Ÿ” Analyzing text with model: {text[:50]}...")
                
                # Try pipeline first, then direct model inference
                if self.classifier is not None:
                    try:
                        # Use pipeline
                        results = self.classifier(text)
                        
                        # Process results
                        if results and len(results) > 0:
                            scores = results[0]  # First result
                            emotion_scores = np.zeros(len(EMOTION_LABELS))
                            
                            # Score mapping
                            for score_info in scores:
                                label = score_info['label']
                                score = score_info['score']
                                
                                # Map label if it exists in emotion labels
                                if label in EMOTION_LABELS:
                                    idx = EMOTION_LABELS.index(label)
                                    emotion_scores[idx] = score
                                else:
                                    # Find most similar label
                                    for i, emotion in enumerate(EMOTION_LABELS):
                                        if label.lower() in emotion.lower() or emotion.lower() in label.lower():
                                            emotion_scores[i] = score
                                            break
                            
                            print("โœ… Pipeline inference completed")
                        else:
                            print("โš ๏ธ Pipeline returned empty results, trying direct inference")
                            emotion_scores = self.direct_model_inference(text)
                    except Exception as e:
                        print(f"โš ๏ธ Pipeline inference failed: {e}, trying direct inference")
                        emotion_scores = self.direct_model_inference(text)
                else:
                    # Use direct model inference
                    emotion_scores = self.direct_model_inference(text)
            else:
                # Simulation mode (when actual model is not available)
                print("๐Ÿ“ Using simulation mode")
                emotion_scores = self.simulate_emotion_analysis(text)
            
            # Generate result text
            result_text = self.generate_result_text(text, emotion_scores)
            
            # Create visualizations
            charts = self.create_visualizations(emotion_scores)
            
            return result_text, charts[0], charts[1]
            
        except Exception as e:
            print(f"โŒ Analysis error: {e}")
            return f"โŒ An error occurred during analysis: {str(e)}", None, None
    
    def simulate_emotion_analysis(self, text):
        """Simulate emotion analysis (when actual model is not available)"""
        # Generate emotion scores based on text
        np.random.seed(hash(text) % 2**32)  # Consistent results for same text
        
        # Base scores
        base_scores = np.random.beta(2, 5, len(EMOTION_LABELS))
        
        # Adjust scores based on text keywords
        text_lower = text.lower()
        
        # Positive emotion keywords
        positive_keywords = ['happy', 'joy', 'excited', 'love', 'great', 'wonderful', 'amazing', 'proud', 'success']
        if any(keyword in text_lower for keyword in positive_keywords):
            positive_indices = [EMOTION_LABELS.index('amusement'), EMOTION_LABELS.index('excitement'), 
                              EMOTION_LABELS.index('pride'), EMOTION_LABELS.index('romantic love')]
            for idx in positive_indices:
                if idx < len(base_scores):
                    base_scores[idx] += 0.3
        
        # Negative emotion keywords
        negative_keywords = ['sad', 'angry', 'fear', 'anxiety', 'disappointment', 'pain', 'guilt', 'horror']
        if any(keyword in text_lower for keyword in negative_keywords):
            negative_indices = [EMOTION_LABELS.index('sadness'), EMOTION_LABELS.index('anger'),
                              EMOTION_LABELS.index('fear'), EMOTION_LABELS.index('anxiety')]
            for idx in negative_indices:
                if idx < len(base_scores):
                    base_scores[idx] += 0.3
        
        # Normalize scores (0-1 range)
        emotion_scores = np.clip(base_scores, 0, 1)
        
        return emotion_scores
    
    def direct_model_inference(self, text):
        """Direct model inference without pipeline"""
        try:
            print("๐Ÿ” Using direct model inference...")
            
            # Tokenize input
            inputs = self.tokenizer(
                text, 
                return_tensors="pt", 
                truncation=True, 
                max_length=512,
                padding=True
            )
            
            # Move inputs to device
            inputs = {k: v.to(self.device) for k, v in inputs.items()}
            
            # Get model outputs
            with torch.no_grad():
                outputs = self.model(**inputs)
                
                # Handle different output formats
                if hasattr(outputs, 'logits'):
                    logits = outputs.logits
                elif hasattr(outputs, 'last_hidden_state'):
                    logits = outputs.last_hidden_state.mean(dim=1)  # Pooling
                else:
                    # Try to get the first output
                    logits = outputs[0] if isinstance(outputs, tuple) else outputs
                
                # Convert to probabilities
                if logits.shape[-1] == len(EMOTION_LABELS):
                    # Direct emotion classification
                    emotion_scores = torch.softmax(logits, dim=-1).cpu().numpy()[0]
                else:
                    # Need to map to emotion labels
                    print(f"โš ๏ธ Model output shape {logits.shape} doesn't match emotions {len(EMOTION_LABELS)}")
                    emotion_scores = self.simulate_emotion_analysis(text)
                
                print("โœ… Direct model inference completed")
                return emotion_scores
                
        except Exception as e:
            print(f"โš ๏ธ Direct model inference failed: {e}")
            print("๐Ÿ“ Falling back to simulation")
            return self.simulate_emotion_analysis(text)
    
    def generate_result_text(self, text, emotion_scores):
        """Generate result text"""
        # Find top 5 emotions
        top_indices = np.argsort(emotion_scores)[-5:][::-1]
        
        result = f"๐Ÿ“ **Input Text**: {text}\n\n"
        result += "๐ŸŽญ **Emotion Analysis Results** (Top 5):\n\n"
        
        for i, idx in enumerate(top_indices):
            emotion = EMOTION_LABELS[idx]
            score = emotion_scores[idx]
            percentage = score * 100
            
            # Add emoji
            emoji = self.get_emotion_emoji(emotion)
            
            result += f"{i+1}. {emoji} **{emotion.title()}**: {percentage:.1f}%\n"
        
        result += f"\n๐Ÿ“Š **Total Emotions**: {len(EMOTION_LABELS)} categories"
        result += f"\n๐Ÿ” **Analysis Mode**: {'Real Model' if self.classifier else 'Simulation'}"
        
        return result
    
    def get_emotion_emoji(self, emotion):
        """Return appropriate emoji for emotion"""
        emoji_map = {
            'joy': '๐Ÿ˜Š', 'sadness': '๐Ÿ˜ข', 'anger': '๐Ÿ˜ ', 'fear': '๐Ÿ˜จ',
            'surprise': '๐Ÿ˜ฒ', 'disgust': '๐Ÿคข', 'love': '๐Ÿฅฐ', 'pride': '๐Ÿ˜Œ',
            'amusement': '๐Ÿ˜„', 'anxiety': '๐Ÿ˜ฐ', 'calmness': '๐Ÿ˜Œ', 'excitement': '๐Ÿคฉ',
            'interest': '๐Ÿค”', 'awe': '๐Ÿ˜ฎ', 'admiration': '๐Ÿ˜', 'gratitude': '๐Ÿ™',
            'hope': '๐Ÿคž', 'relief': '๐Ÿ˜Œ', 'satisfaction': '๐Ÿ˜Š', 'confusion': '๐Ÿ˜•',
            'embarrassment': '๐Ÿ˜ณ', 'guilt': '๐Ÿ˜ฃ', 'shame': '๐Ÿ˜ž', 'contempt': '๐Ÿ˜',
            'envy': '๐Ÿ˜’', 'jealousy': '๐Ÿ˜ค', 'disappointment': '๐Ÿ˜”', 'frustration': '๐Ÿ˜ค'
        }
        
        # Find keyword in emotion name
        for key, emoji in emoji_map.items():
            if key in emotion.lower():
                return emoji
        
        return '๐ŸŽญ'  # Default emoji
    
    def create_visualizations(self, emotion_scores):
        """Create visualizations"""
        # 1. Top 10 emotions bar chart
        top_indices = np.argsort(emotion_scores)[-10:][::-1]
        top_emotions = [EMOTION_LABELS[i].title() for i in top_indices]
        top_scores = [emotion_scores[i] for i in top_indices]
        
        fig1 = px.bar(
            x=top_scores,
            y=top_emotions,
            orientation='h',
            title="๐ŸŽญ Top 10 Emotion Scores",
            labels={'x': 'Emotion Score', 'y': 'Emotion'},
            color=top_scores,
            color_continuous_scale='viridis'
        )
        fig1.update_layout(
            height=400,
            showlegend=False,
            xaxis_range=[0, 1]
        )
        
        # 2. Overall emotion distribution heatmap
        # Arrange 26 emotions in 5x6 grid
        grid_size = 6
        emotion_grid = np.zeros((5, grid_size))
        
        for i, score in enumerate(emotion_scores):
            row = i // grid_size
            col = i % grid_size
            if row < 5:
                emotion_grid[row, col] = score
        
        fig2 = px.imshow(
            emotion_grid,
            title="๐ŸŽจ Overall Emotion Distribution Heatmap",
            labels={'x': 'Emotion Group', 'y': 'Emotion Category'},
            color_continuous_scale='RdYlBu_r',
            aspect="auto"
        )
        fig2.update_layout(height=400)
        
        return fig1, fig2

# Create emotion analyzer instance
analyzer = EmotionAnalyzer()

# Gradio interface
def analyze_text(text):
    """Text analysis function"""
    result_text, chart1, chart2 = analyzer.analyze_emotion(text)
    return result_text, chart1, chart2

# Example texts
examples = [
    ["Today was such a happy day! I spent time with friends and had delicious food together."],
    ["This movie was so scary that I don't think I can sleep tonight. It was truly terrifying."],
    ["I'm so proud and happy that I got a good grade on the exam. All my hard work paid off."],
    ["I feel jealous and sad that my friend likes the same person I like."],
    ["I'm excited and nervous about starting a new project."],
    ["Looking at beautiful nature makes me feel calm and grateful."]
]

# Create Gradio interface
iface = gr.Interface(
    fn=analyze_text,
    inputs=[
        gr.Textbox(
            label="๐Ÿ“ Enter text to analyze",
            placeholder="How are you feeling today? Please describe in detail...",
            lines=3,
            max_lines=5
        )
    ],
    outputs=[
        gr.Markdown(label="๐Ÿ“Š Analysis Results"),
        gr.Plot(label="๐ŸŽญ Top Emotions Chart"),
        gr.Plot(label="๐ŸŽจ Overall Emotion Distribution")
    ],
    title="๐ŸŽญ Multimodal Emotion Analyzer",
    description="""
    **AI model that analyzes 26 different emotions!**
    
    ๐Ÿ“ Enter English text to analyze emotions and get visualizations.
    ๐ŸŽฏ View top emotions and overall emotion distribution in charts.
    ๐ŸŒŸ Designed for English text input.
    
    **Supported Emotions**: admiration, aesthetic appreciation, awe, anxiety, fear, horror, 
    disgust, calmness, romantic love, sexual desire, nostalgia, interest, surprise, 
    excitement, anger, pride, triumph, contempt, disappointment, empathic pain, 
    sadness, guilt, envy, amusement, awkwardness, adoration
    """,
    examples=examples,
    theme=gr.themes.Soft(),
    css="""
    .gradio-container {
        max-width: 1200px !important;
        margin: 0 auto !important;
    }
    .gradio-interface {
        padding: 20px !important;
    }
    """
)

# Launch
if __name__ == "__main__":
    iface.launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=False
    )