Spaces:
Sleeping
Sleeping
File size: 1,471 Bytes
b0272e3 |
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 41 42 43 44 45 46 47 48 49 |
from transformers import pipeline
class SentimentAnalyzer:
"""Class for analyzing the sentiment of sentences
"""
def __init__(self) -> None:
"""initializes the class with sentiment analysis pipeline using the distilbert-base-uncased-finetuned-sst-2-english model
"""
self.analyzer = pipeline(
"sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english")
def score_sentiment(self, sentence: str) -> float:
"""Uses the analyzer to analyze the sentiment of the provided sentence
Parameters
----------
sentence : str
a short sentence to be analyzed
Returns
-------
float
score of the sentiment from 0 to 1. Below 0.5 is negative, above is positive. 0.5 is neutral
"""
return self.analyzer(sentence)[0]
def get_sentiment(self, sentence: str) -> str:
"""returns the label of the sentiment provided
Parameters
----------
sentence : str
a short sentence to be analyzed
Returns
-------
str
label of the sentiment wether it is positive, negative, or neutral
"""
sentiment_score = self.score_sentiment(sentence)
return sentiment_score['label']
if __name__ == "__main__":
sentence = "I love you"
sentiment_analyzer = SentimentAnalyzer()
print(sentiment_analyzer.get_sentiment(sentence)) |