""" 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("""
Analyze emotions in English and Malay text with high accuracy!
Model: rmtariq/multilingual-emotion-classifier |
Accuracy: 85% |
Languages: ๐ฌ๐ง English, ๐ฒ๐พ Malay
๐ญ Multilingual Emotion Classifier | Built with โค๏ธ by rmtariq | Powered by ๐ค Transformers & Gradio