Spaces:
Runtime error
Runtime error
# 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)}") | |