Spaces:
Sleeping
Sleeping
File size: 1,243 Bytes
54a8fa8 | 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 | import gradio as gr
from transformers import pipeline
import nltk
# Download nltk sentence tokenizer data once
nltk.download('punkt')
nltk.download('punkt_tab')
from nltk.tokenize import sent_tokenize
classifier = pipeline(
"text-classification",
model="j-hartmann/emotion-english-distilroberta-base",
top_k=1
)
def predict_emotion(text):
sentences = sent_tokenize(text) # Split text into sentences
results = []
for sentence in sentences:
result = classifier(sentence)
# Handle nested list result if any
if isinstance(result[0], list):
prediction = result[0][0]
else:
prediction = result[0]
label = prediction["label"]
score = prediction["score"]
results.append(f"{sentence.strip()} - Emotion: {label}, Confidence: {score:.2f}")
return "\n".join(results)
demo = gr.Interface(
fn=predict_emotion,
inputs=gr.Textbox(lines=5, placeholder="Enter multiple sentences here...", label="Input Text"),
outputs=gr.Textbox(label="Emotion per Sentence"),
title="Emotion Classifier by Sentence",
description="Enter text with multiple sentences. Each sentence's emotion and confidence is shown separately."
)
demo.launch()
|