empath-ai / app.py
Navsatitagain's picture
Create app.py
cc9c39b verified
raw
history blame
1.76 kB
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()