mcp-sentiment / app.py
wlchee's picture
Update app.py
3f2c46b verified
import gradio as gr
from transformers import pipeline
# Load pretrained sentiment analysis pipeline
sentiment_pipeline = pipeline("sentiment-analysis")
def sentiment_analysis(text: str) -> dict:
"""
Analyze sentiment using a transformer model, without lexicon.
Args:
text (str): The input text.
Returns:
dict: Polarity (mapped from model confidence), assessment, and subjectivity (heuristic).
"""
result = sentiment_pipeline(text)[0]
label = result['label']
score = result['score']
polarity = score if label == "POSITIVE" else -score
assessment = "positive" if polarity > 0.2 else "negative" if polarity < -0.2 else "neutral"
# Heuristic for subjectivity: high confidence implies more subjective
subjectivity = round(score, 2)
return {
"polarity": round(polarity, 2),
"subjectivity": subjectivity,
"assessment": assessment
}
# Gradio Interface
demo = gr.Interface(
fn=sentiment_analysis,
inputs=gr.Textbox(placeholder="Enter text to analyze...", lines=4),
outputs=gr.JSON(),
title="Transformer-Based Sentiment Analysis",
description="Analyze sentiment using a pre-trained BERT model (no lexicons or rule-based logic)."
)
# Run on Gradio MCP
if __name__ == "__main__":
demo.launch(mcp_server=True, share=True)