File size: 1,673 Bytes
685f307
 
85b90a3
 
ef825e1
e734d94
685f307
85b90a3
685f307
85b90a3
 
685f307
 
85b90a3
 
 
 
 
 
685f307
 
85b90a3
 
 
 
6c3e4b6
85b90a3
 
 
 
 
 
 
 
6c3e4b6
85b90a3
 
 
 
 
6c3e4b6
 
 
 
685f307
ef825e1
5fc4041
ef825e1
 
 
 
 
 
 
 
1bb5fea
6c3e4b6
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
import json
from textblob import TextBlob
from fastapi import FastAPI, HTTPException
import uvicorn
import gradio as gr
import mcp

app = FastAPI()

def analyze_sentiment(text: str) -> dict:
    """Core sentiment analysis logic"""
    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"
    }

@app.post("/mcp/sentiment")
async def handle_mcp_request(data: dict):
    """
    MCP-compatible endpoint
    Format: {"parameters": {"text": "your text"}}
    """
    try:
        text = data.get("parameters", {}).get("text", "")
        if not text:
            raise HTTPException(status_code=400, detail="Missing 'text' parameter")
        
        return {
            "jsonrpc": "2.0",
            "result": analyze_sentiment(text),
            "id": "sentiment-response"
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@app.get("/")
async def health_check():
    """Required for Hugging Face health checks"""
    return {"status": "OK"}

demo = gr.Interface(
    fn=analyze_sentiment,
    inputs=gr.Textbox(placeholder="Enter text to analyze..."),
    outputs=gr.Textbox(),  
    title="Text Sentiment Analysis",
    description="Analyze the sentiment of text using TextBlob"
)

# Launch the interface and MCP server
if __name__ == "__main__":
    demo.launch(mcp_server=True)
    uvicorn.run(app, host="0.0.0.0", port=7860)  # HF uses 7860