# ============================================================ # HuggingFace Space — Emotion Classifier Demo # File: app.py (deploy as a Gradio Space) # ============================================================ # How to deploy: # 1. Go to https://huggingface.co/spaces → Create new Space # 2. Choose SDK: Gradio # 3. Add this file as app.py # 4. Add requirements.txt (contents below in comment) # 5. Space will auto-build and launch # # requirements.txt contents: # transformers>=4.40.0 # torch>=2.1.0 # gradio>=4.0.0 # ============================================================ import gradio as gr from transformers import pipeline # ── Load model from HuggingFace Hub ────────────────────────────────────────── MODEL_REPO = "your-hf-username/emotion-classifier-distilbert" # ← update this EMOTION_EMOJIS = { "sadness": "😢", "anger": "😠", "love": "❤️", "surprise": "😲", "fear": "😨", "joy": "😊", } EMOTION_COLORS = { "sadness": "#4a90d9", "anger": "#e74c3c", "love": "#e91e8c", "surprise": "#f39c12", "fear": "#8e44ad", "joy": "#27ae60", } print(f"Loading model: {MODEL_REPO} …") classifier = pipeline( "text-classification", model=MODEL_REPO, return_all_scores=True, ) print("Model loaded ✅") # ── Inference function ──────────────────────────────────────────────────────── def predict_emotion(text: str): if not text or not text.strip(): return "⚠️ Please enter some text.", {} results = classifier(text.strip())[0] # list of {label, score} scores = {r["label"]: round(r["score"] * 100, 2) for r in results} best = max(results, key=lambda x: x["score"]) best_label = best["label"] best_score = best["score"] * 100 emoji = EMOTION_EMOJIS.get(best_label, "🤔") summary = ( f"**{emoji} {best_label.capitalize()}** " f"({best_score:.1f}% confidence)" ) return summary, scores # ── Example sentences ───────────────────────────────────────────────────────── EXAMPLES = [ ["I feel so happy and grateful today!"], ["I am really angry about what happened."], ["I miss my dog so much, it breaks my heart."], ["Oh wow, I cannot believe that just happened!"], ["I'm terrified of what might come next."], ["I love spending time with you."], ] # ── Gradio UI ───────────────────────────────────────────────────────────────── with gr.Blocks( theme=gr.themes.Soft(), title="Emotion Classifier", css=""" .result-box { font-size: 1.4rem; padding: 12px; border-radius: 8px; } footer { display: none !important; } """, ) as demo: gr.Markdown( """ # 🎭 Emotion Classifier Detects **6 emotions** in English text using a fine-tuned DistilBERT model. """ ) with gr.Row(): with gr.Column(scale=2): text_input = gr.Textbox( label="Enter text", placeholder="Type a sentence and click Analyze…", lines=4, ) analyze_btn = gr.Button("Analyze Emotion", variant="primary") with gr.Column(scale=2): result_label = gr.Markdown( label="Top Prediction", elem_classes=["result-box"], ) scores_plot = gr.Label( label="Confidence Scores (%)", num_top_classes=6, ) gr.Examples( examples=EXAMPLES, inputs=text_input, label="Example sentences", ) gr.Markdown( """ --- **Labels:** 😢 Sadness · 😠 Anger · ❤️ Love · 😲 Surprise · 😨 Fear · 😊 Joy Model: `distilbert-base-uncased` fine-tuned for 10 epochs on ~19 000 labelled sentences. """ ) analyze_btn.click( fn=predict_emotion, inputs=text_input, outputs=[result_label, scores_plot], ) text_input.submit( fn=predict_emotion, inputs=text_input, outputs=[result_label, scores_plot], ) if __name__ == "__main__": demo.launch()