Spaces:
Sleeping
Sleeping
Download app.py from jatinsoni/TextEmotionClassifier: direct link, hf CLI and curl.
- Browser
- Download file 1.24 kB
-
https://huggingface.co/spaces/jatinsoni/TextEmotionClassifier/resolve/main/app.py
- Command line
-
hf download hf://spaces/jatinsoni/TextEmotionClassifier/app.py
-
curl -L -o app.py https://huggingface.co/spaces/jatinsoni/TextEmotionClassifier/resolve/main/app.py
1.24 kB
| 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() | |