File size: 4,631 Bytes
05986e9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# ============================================================
#  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()