Tiny Python utility that detects emotions in English text using a Hugging Face Transformers pipeline.
- Model:
j-hartmann/emotion-english-distilroberta-base - Task:
text-classification(returns all emotion scores viatop_k=None)
Create/activate a virtual environment, then install dependencies:
python -m venv venv
source venv/bin/activate
pip install --upgrade pip
pip install transformers torchNotes:
- The first run downloads the model weights (requires internet).
- If you’re on Apple Silicon,
torchwheels are supported; if install issues occur, use the official PyTorch install command for your platform.
The core function is emotion_detector(text) in emotion_detection.py.
from emotion_detection import emotion_detector
print(emotion_detector("I’m really excited about this!"))python -c "from emotion_detection import emotion_detector; print(emotion_detector('I’m really excited about this!'))"For non-empty input, the function returns a dictionary mapping emotion labels to scores (rounded to 2 decimals), for example:
{
"joy": 0.87,
"anger": 0.02,
"sadness": 0.03
}For blank input ("" / None), it returns:
({"error": "Input cannot be blank"}, 400)emotion_detection.py: Loads the model pipeline and exposesemotion_detector(text).
- Hugging Face model:
j-hartmann/emotion-english-distilroberta-base - Transformers library:
transformers