File size: 2,962 Bytes
914749b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import gradio as gr
from transformers import pipeline

# Initialize the sentiment analysis pipeline globally
# This will download and cache the model on the first run.
# The default model is 'distilbert-base-uncased-finetuned-sst-2-english'
try:
    sentiment_analyzer = pipeline("sentiment-analysis")
except Exception as e:
    print(f"Error initializing sentiment analysis pipeline: {e}")
    sentiment_analyzer = None

def sentiment_analysis(text: str) -> dict:
    """
    Analyze the sentiment of the given text using a Hugging Face transformers model.

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

    Returns:
        dict: A dictionary containing the sentiment assessment.
    """
    if not sentiment_analyzer:
        return {
            "assessment": "error",
            "polarity": 0.0,
            "details": "Sentiment analyzer not available."
        }
    
    # Handle empty or whitespace-only input
    if not text or not text.strip():
        return {
            "assessment": "neutral", # Or specific "empty_input"
            "polarity": 0.0,
            "model_score": 0.0,
            "details": "Input text is empty."
        }

    try:
        # The pipeline returns a list of dictionaries, e.g., [{'label': 'POSITIVE', 'score': 0.99}]
        # We take the first result as we are analyzing the whole text as one segment.
        result = sentiment_analyzer(text)[0] 
        label = result['label']
        score = result['score']

        assessment = "neutral" # Default assessment
        polarity = 0.0

        if label == "POSITIVE":
            assessment = "positive"
            polarity = score  # Score is confidence, directly maps to positive polarity
        elif label == "NEGATIVE":
            assessment = "negative"
            # To align with a -1 to 1 range like TextBlob, make polarity negative for negative sentiment
            polarity = -score 
        
        # Note: Subjectivity is not directly provided by this specific transformer model.
        # We return polarity, assessment, and the raw model score for more detail.
        return {
            "polarity": round(polarity, 2),
            "assessment": assessment,
            "model_score": round(score, 4) 
        }
    except Exception as e:
        print(f"Error during sentiment analysis for text '{text[:50]}...': {e}")
        return {
            "assessment": "error",
            "polarity": 0.0,
            "details": f"Error processing text: {str(e)}"
        }

# Create the Gradio interface
demo = gr.Interface(
    fn=sentiment_analysis,
    inputs=gr.Textbox(placeholder="Enter text to analyze..."),
    outputs=gr.JSON(),
    title="Advanced Text Sentiment Analysis (Transformers)",
    description="Analyze the sentiment of text using a Hugging Face Transformers model. Provides polarity, assessment, and model score."
)

# Launch the interface and MCP server
if __name__ == "__main__":
    demo.launch(mcp_server=True)