File size: 1,239 Bytes
7fb74eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# backend/sentiment_analyzer.py

from textblob import TextBlob

def analyze_sentiment(text: str) -> dict:
    """
    Analyzes the sentiment of a given text.

    Args:
        text (str): The input text to analyze.

    Returns:
        dict: A dictionary containing the sentiment class (positive, neutral, negative)
                and the polarity score.
    """
    if not isinstance(text, str):
        return {"class": "invalid_input", "polarity": None}

    analysis = TextBlob(text)
    polarity = analysis.sentiment.polarity

    if polarity > 0.05:
        sentiment_class = "positive"
    elif polarity < -0.05:
        sentiment_class = "negative"
    else:
        sentiment_class = "neutral"

    return {"class": sentiment_class, "polarity": polarity}

# Example Usage (for testing this module independently)
if __name__ == "__main__":
    print("--- Testing Sentiment Analysis ---")
    text1 = "This is a wonderful product, I love it!"
    text2 = "I am so thrilled to have this broken piece of junk."
    text3 = "The weather today is neither good nor bad."

    print(f"'{text1}' -> {analyze_sentiment(text1)}")
    print(f"'{text2}' -> {analyze_sentiment(text2)}")
    print(f"'{text3}' -> {analyze_sentiment(text3)}")