File size: 1,196 Bytes
62059a2
 
 
 
4c3e148
62059a2
4c3e148
 
62059a2
4c3e148
 
 
62059a2
 
 
4c3e148
 
 
 
 
 
 
 
62059a2
 
4c3e148
 
 
 
 
 
62059a2
4c3e148
62059a2
4c3e148
 
62059a2
4c3e148
 
62059a2
4c3e148
 
 
 
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
import json
import gradio as gr
from textblob import TextBlob

def sentiment_analysis(text: str) -> dict:
    """
    Analyze the sentiment of the given text and return a dict (not a string).
    HF + MCP both like dicts better.
    """
    if not text:
        return {"error": "No text provided"}

    blob = TextBlob(text)
    sentiment = blob.sentiment

    return {
        "polarity": round(sentiment.polarity, 2),
        "subjectivity": round(sentiment.subjectivity, 2),
        "assessment": (
            "positive" if sentiment.polarity > 0
            else "negative" if sentiment.polarity < 0
            else "neutral"
        ),
    }

# ---------- Gradio UI ----------
with gr.Blocks() as demo:
    gr.Markdown("# Text Sentiment Analysis (MCP)")
    inp = gr.Textbox(placeholder="Enter text to analyze...", label="Text")
    out = gr.JSON(label="Sentiment")
    btn = gr.Button("Analyze")

    btn.click(fn=sentiment_analysis, inputs=inp, outputs=out)

# HF looks for this:
app = demo

# ---------- MCP ----------
mcp_app = gr.mcp.App()

@mcp_app.tool()
def analyze(text: str) -> dict:
    """MCP tool to expose the same sentiment analysis."""
    return sentiment_analysis(text)