File size: 1,760 Bytes
cc9c39b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
from transformers import pipeline

MODEL_ID = "j-hartmann/emotion-english-distilroberta-base"

text_emotion = pipeline(
    task="text-classification",
    model=MODEL_ID,
    return_all_scores=True
)

def analyze_text(text: str):
    """Return top emotion, its confidence, and all scores."""
    if not text or not text.strip():
        return "—", 0.0, {"notice": "Please enter some text."}

       result = text_emotion(text)[0]
    sorted_pairs = sorted(
        [(r["label"], float(r["score"])) for r in result],
        key=lambda x: x[1],
        reverse=True
    )
    top_label, top_score = sorted_pairs[0]
    all_scores = {label.lower(): round(score, 4) for label, score in sorted_pairs}
    return top_label, round(top_score, 4), all_scores

with gr.Blocks(title="Empath AI — Text Emotions") as demo:
    gr.Markdown("# Empath AI — Text Emotion Detection\nPaste text and click **Analyze**.")

    with gr.Row():
        inp = gr.Textbox(
            label="Enter text",
            placeholder="Example: I'm so happy with the result today!",
            lines=4
        )
        btn = gr.Button("Analyze", variant="primary")

    with gr.Row():
        top = gr.Textbox(label="Top Emotion", interactive=False)
        conf = gr.Number(label="Confidence (0–1)", interactive=False)

    all_scores = gr.JSON(label="All Emotion Scores")

    gr.Examples(
        examples=[
            ["I'm thrilled with how this turned out!"],
            ["This is taking too long and I'm getting frustrated."],
            ["I'm worried this might fail."],
            ["Thanks so much—this really helped."]
        ],
        inputs=inp
    )

    btn.click(analyze_text, inputs=inp, outputs=[top, conf, all_scores])

demo.launch()