Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from transformers import pipeline
|
3 |
+
|
4 |
+
MODEL_ID = "j-hartmann/emotion-english-distilroberta-base"
|
5 |
+
|
6 |
+
text_emotion = pipeline(
|
7 |
+
task="text-classification",
|
8 |
+
model=MODEL_ID,
|
9 |
+
return_all_scores=True
|
10 |
+
)
|
11 |
+
|
12 |
+
def analyze_text(text: str):
|
13 |
+
"""Return top emotion, its confidence, and all scores."""
|
14 |
+
if not text or not text.strip():
|
15 |
+
return "—", 0.0, {"notice": "Please enter some text."}
|
16 |
+
|
17 |
+
result = text_emotion(text)[0]
|
18 |
+
sorted_pairs = sorted(
|
19 |
+
[(r["label"], float(r["score"])) for r in result],
|
20 |
+
key=lambda x: x[1],
|
21 |
+
reverse=True
|
22 |
+
)
|
23 |
+
top_label, top_score = sorted_pairs[0]
|
24 |
+
all_scores = {label.lower(): round(score, 4) for label, score in sorted_pairs}
|
25 |
+
return top_label, round(top_score, 4), all_scores
|
26 |
+
|
27 |
+
with gr.Blocks(title="Empath AI — Text Emotions") as demo:
|
28 |
+
gr.Markdown("# Empath AI — Text Emotion Detection\nPaste text and click **Analyze**.")
|
29 |
+
|
30 |
+
with gr.Row():
|
31 |
+
inp = gr.Textbox(
|
32 |
+
label="Enter text",
|
33 |
+
placeholder="Example: I'm so happy with the result today!",
|
34 |
+
lines=4
|
35 |
+
)
|
36 |
+
btn = gr.Button("Analyze", variant="primary")
|
37 |
+
|
38 |
+
with gr.Row():
|
39 |
+
top = gr.Textbox(label="Top Emotion", interactive=False)
|
40 |
+
conf = gr.Number(label="Confidence (0–1)", interactive=False)
|
41 |
+
|
42 |
+
all_scores = gr.JSON(label="All Emotion Scores")
|
43 |
+
|
44 |
+
gr.Examples(
|
45 |
+
examples=[
|
46 |
+
["I'm thrilled with how this turned out!"],
|
47 |
+
["This is taking too long and I'm getting frustrated."],
|
48 |
+
["I'm worried this might fail."],
|
49 |
+
["Thanks so much—this really helped."]
|
50 |
+
],
|
51 |
+
inputs=inp
|
52 |
+
)
|
53 |
+
|
54 |
+
btn.click(analyze_text, inputs=inp, outputs=[top, conf, all_scores])
|
55 |
+
|
56 |
+
demo.launch()
|