CoolFace
Apppublic

snowc2023/simple-sentiment-analyzer

sourceHugging Faceupdated 3y agoView on Hugging Face
0likes
engine.py47 linesDownload Raw Back to root
1from transformers import pipeline2 3class SentimentAnalyzer:4    """Class for analyzing the sentiment of sentences5    """6 7    def __init__(self) -> None:8        """initializes the class with sentiment analysis pipeline using the distilbert-base-uncased-finetuned-sst-2-english model9        """10        self.analyzer = pipeline(11            "sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english")12 13    def score_sentiment(self, sentence: str) -> float:14        """Uses the analyzer to analyze the sentiment of the provided sentence15 16        Parameters17        ----------18        sentence : str19            a short sentence to be analyzed20 21        Returns22        -------23        float24            score of the sentiment from 0 to 1. Below 0.5 is negative, above is positive. 0.5 is neutral25        """26        return self.analyzer(sentence)[0]27 28    def get_sentiment(self, sentence: str) -> str:29        """returns the label of the sentiment provided30 31        Parameters32        ----------33        sentence : str34            a short sentence to be analyzed35 36        Returns37        -------38        str39            label of the sentiment wether it is positive, negative, or neutral40        """41        sentiment_score = self.score_sentiment(sentence)42        return sentiment_score['label']43 44if __name__ == "__main__":45    sentence = "I love you"46    sentiment_analyzer = SentimentAnalyzer()47    print(sentiment_analyzer.get_sentiment(sentence))