Spaces:
Sleeping
Sleeping
Download app.py from CURI-AI/sentiment-analysis-en: direct link, hf CLI and curl.
- Browser
- Download file 19.6 kB
-
https://huggingface.co/spaces/CURI-AI/sentiment-analysis-en/resolve/main/app.py
- Command line
-
hf download hf://spaces/CURI-AI/sentiment-analysis-en/app.py
-
curl -L -o app.py https://huggingface.co/spaces/CURI-AI/sentiment-analysis-en/resolve/main/app.py
19.6 kB
| #!/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 | |
| ) |