Spaces:
Running
Running
File size: 10,746 Bytes
037f340 | 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 | """Visualization module for emotion analysis results."""
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
from pathlib import Path
from typing import Dict, Optional
from datetime import datetime
class EmotionVisualizer:
"""Generate visualizations for emotion analysis results."""
def __init__(self, output_dir: Path = None):
"""
Initialize the visualizer.
Args:
output_dir: Directory to save visualization files
"""
self.output_dir = output_dir or Path("visualizations")
self.output_dir.mkdir(exist_ok=True)
# Set style
plt.style.use('default')
sns.set_palette("husl")
# Emotion colors for consistency
self.emotion_colors = {
'joy': '#FFD700', # Gold
'sadness': '#4169E1', # Royal Blue
'anger': '#DC143C', # Crimson
'fear': '#9370DB', # Medium Purple
'love': '#FF69B4', # Hot Pink
'surprise': '#FF8C00', # Dark Orange
}
def create_emotion_bar_chart(self,
probabilities: Dict[str, float],
text: str = "",
save_path: Optional[Path] = None,
show_chart: bool = True,
primary_emotion: Optional[str] = None) -> Path:
"""
Create a bar chart showing emotion probabilities.
Args:
probabilities: Dict of emotion -> probability
text: Input text (for title)
save_path: Where to save the chart
show_chart: Whether to display the chart
primary_emotion: Explicit primary emotion to override argmax
Returns:
Path to saved chart image
"""
# Prepare data
emotions = list(probabilities.keys())
probs = list(probabilities.values())
colors = [self.emotion_colors.get(emo, '#808080') for emo in emotions]
# Create figure
plt.figure(figsize=(12, 8))
# Create bars
bars = plt.bar(emotions, probs, color=colors, alpha=0.8, edgecolor='black', linewidth=1)
# Customize chart
plt.title(f'Emotion Analysis Results\n"{text[:60]}{"..." if len(text) > 60 else ""}"',
fontsize=16, fontweight='bold', pad=20)
plt.xlabel('Emotions', fontsize=14, fontweight='bold')
plt.ylabel('Probability', fontsize=14, fontweight='bold')
# Add percentage labels on bars
for bar, prob in zip(bars, probs):
height = bar.get_height()
plt.text(bar.get_x() + bar.get_width()/2., height + 0.01,
f'{prob:.1%}', ha='center', va='bottom',
fontweight='bold', fontsize=12)
# Customize appearance
plt.ylim(0, max(probs) * 1.2)
plt.xticks(rotation=45, fontsize=12)
plt.yticks(fontsize=12)
plt.grid(axis='y', alpha=0.3, linestyle='--')
# Add emotion indicators
if primary_emotion is None:
max_emotion = max(probabilities, key=probabilities.get)
else:
max_emotion = primary_emotion
max_prob = probabilities[max_emotion]
plt.text(0.02, 0.98, f'Primary: {max_emotion.upper()} ({max_prob:.1%})',
transform=plt.gca().transAxes, fontsize=14, fontweight='bold',
bbox=dict(boxstyle="round,pad=0.3", facecolor="lightblue", alpha=0.7),
verticalalignment='top')
plt.tight_layout()
# Save chart
if save_path is None:
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
save_path = self.output_dir / f"emotion_analysis_{timestamp}.png"
plt.savefig(save_path, dpi=300, bbox_inches='tight',
facecolor='white', edgecolor='none')
if show_chart:
plt.show()
else:
plt.close()
return save_path
def create_comparison_chart(self,
results_list: list,
titles: list = None,
save_path: Optional[Path] = None,
show_chart: bool = True) -> Path:
"""
Create a comparison chart for multiple predictions.
Args:
results_list: List of prediction results
titles: List of titles for each prediction
save_path: Where to save the chart
show_chart: Whether to display the chart
Returns:
Path to saved chart image
"""
if not results_list:
raise ValueError("No results provided for comparison")
# Prepare data
emotions = list(results_list[0]['probabilities'].keys())
n_samples = len(results_list)
if titles is None:
titles = [f"Sample {i+1}" for i in range(n_samples)]
# Create figure with subplots
fig, axes = plt.subplots(1, n_samples, figsize=(6*n_samples, 6))
if n_samples == 1:
axes = [axes]
fig.suptitle('Emotion Analysis Comparison', fontsize=18, fontweight='bold')
for idx, (result, title, ax) in enumerate(zip(results_list, titles, axes)):
probs = list(result['probabilities'].values())
colors = [self.emotion_colors.get(emo, '#808080') for emo in emotions]
bars = ax.bar(emotions, probs, color=colors, alpha=0.8,
edgecolor='black', linewidth=1)
# Add labels
for bar, prob in zip(bars, probs):
height = bar.get_height()
ax.text(bar.get_x() + bar.get_width()/2., height + 0.01,
f'{prob:.1%}', ha='center', va='bottom',
fontweight='bold', fontsize=10)
ax.set_title(f'{title}\n🎯 {result["emotion"].upper()} ({result["confidence"]:.1%})')
ax.set_ylim(0, 1)
ax.tick_params(axis='x', rotation=45)
ax.grid(axis='y', alpha=0.3, linestyle='--')
plt.tight_layout()
# Save chart
if save_path is None:
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
save_path = self.output_dir / f"emotion_comparison_{timestamp}.png"
plt.savefig(save_path, dpi=300, bbox_inches='tight',
facecolor='white', edgecolor='none')
if show_chart:
plt.show()
else:
plt.close()
return save_path
def create_detailed_analysis_chart(self,
result: dict,
text: str = "",
save_path: Optional[Path] = None,
show_chart: bool = True) -> Path:
"""
Create a simplified detailed analysis chart with only the bar chart.
Args:
result: Prediction result dictionary
text: Input text
save_path: Where to save the chart
show_chart: Whether to display the chart
Returns:
Path to saved chart image
"""
fig = plt.figure(figsize=(14, 8))
# Single bar chart with enhanced styling
emotions = list(result['probabilities'].keys())
probs = list(result['probabilities'].values())
colors = [self.emotion_colors.get(emo, '#808080') for emo in emotions]
# Verify probabilities sum to 100%
total_prob = sum(probs)
if abs(total_prob - 1.0) > 0.001:
print(f"⚠️ Warning: Probabilities sum to {total_prob:.4f}, not 1.0")
bars = plt.bar(emotions, probs, color=colors, alpha=0.8,
edgecolor='black', linewidth=2, width=0.6)
# Add percentage labels on bars
for bar, prob in zip(bars, probs):
height = bar.get_height()
plt.text(bar.get_x() + bar.get_width()/2., height + 0.01,
f'{prob:.1%}', ha='center', va='bottom',
fontweight='bold', fontsize=14)
# Enhanced styling
plt.title(f'Emotion Analysis Results\n"{text[:80]}{"..." if len(text) > 80 else ""}"',
fontsize=18, fontweight='bold', pad=20)
plt.xlabel('Emotions', fontsize=16, fontweight='bold')
plt.ylabel('Probability', fontsize=16, fontweight='bold')
# Set y-axis to show 0-100%
plt.ylim(0, 1.0)
plt.gca().yaxis.set_major_formatter(plt.FuncFormatter(lambda y, _: f'{y:.0%}'))
# Customize appearance
plt.xticks(rotation=0, fontsize=13, fontweight='bold')
plt.yticks(fontsize=12)
plt.grid(axis='y', alpha=0.3, linestyle='--')
# Add primary emotion indicator
max_emotion = max(result['probabilities'], key=result['probabilities'].get)
max_prob = result['probabilities'][max_emotion]
plt.text(0.02, 0.98, f'Primary Emotion: {max_emotion.upper()} ({max_prob:.1%})',
transform=plt.gca().transAxes, fontsize=16, fontweight='bold',
bbox=dict(boxstyle="round,pad=0.5", facecolor="lightblue", alpha=0.8),
verticalalignment='top')
# Add verification text
plt.text(0.98, 0.02, f'Total: {sum(probs):.1%}',
transform=plt.gca().transAxes, fontsize=12,
bbox=dict(boxstyle="round,pad=0.3", facecolor="lightgreen", alpha=0.7),
horizontalalignment='right', verticalalignment='bottom')
plt.tight_layout()
# Save chart
if save_path is None:
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
save_path = self.output_dir / f"detailed_analysis_{timestamp}.png"
plt.savefig(save_path, dpi=300, bbox_inches='tight',
facecolor='white', edgecolor='none')
if show_chart:
plt.show()
else:
plt.close()
return save_path
def create_quick_chart(probabilities: dict, text: str = "", show: bool = True) -> Path:
"""Quick function to create a simple emotion bar chart."""
visualizer = EmotionVisualizer()
return visualizer.create_emotion_bar_chart(probabilities, text, show_chart=show)
if __name__ == "__main__":
# Demo visualization
sample_probs = {
'joy': 0.7,
'sadness': 0.1,
'anger': 0.08,
'fear': 0.06,
'love': 0.04,
'surprise': 0.02
}
visualizer = EmotionVisualizer()
chart_path = visualizer.create_emotion_bar_chart(
sample_probs,
"I'm feeling so happy today, everything is wonderful!"
)
print(f"📊 Chart saved to: {chart_path}") |