Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,37 +1,55 @@
|
|
| 1 |
import json
|
| 2 |
-
import gradio as gr
|
| 3 |
from textblob import TextBlob
|
|
|
|
|
|
|
| 4 |
|
| 5 |
-
|
| 6 |
-
"""
|
| 7 |
-
Analyze the sentiment of the given text.
|
| 8 |
-
|
| 9 |
-
Args:
|
| 10 |
-
text (str): The text to analyze
|
| 11 |
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
"""
|
| 15 |
blob = TextBlob(text)
|
| 16 |
sentiment = blob.sentiment
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
"
|
| 20 |
-
"
|
| 21 |
-
|
|
|
|
| 22 |
}
|
| 23 |
|
| 24 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
|
| 26 |
-
# Create
|
| 27 |
demo = gr.Interface(
|
| 28 |
-
fn=
|
| 29 |
-
inputs=gr.Textbox(
|
| 30 |
-
outputs=gr.
|
| 31 |
-
title="
|
| 32 |
-
description="Analyze the sentiment of text using TextBlob"
|
| 33 |
)
|
| 34 |
|
| 35 |
-
# Launch the interface and MCP server
|
| 36 |
if __name__ == "__main__":
|
| 37 |
-
|
|
|
|
| 1 |
import json
|
|
|
|
| 2 |
from textblob import TextBlob
|
| 3 |
+
from fastapi import FastAPI, HTTPException
|
| 4 |
+
import uvicorn
|
| 5 |
|
| 6 |
+
app = FastAPI()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
+
def analyze_sentiment(text: str) -> dict:
|
| 9 |
+
"""Core sentiment analysis logic"""
|
|
|
|
| 10 |
blob = TextBlob(text)
|
| 11 |
sentiment = blob.sentiment
|
| 12 |
+
return {
|
| 13 |
+
"polarity": round(sentiment.polarity, 2),
|
| 14 |
+
"subjectivity": round(sentiment.subjectivity, 2),
|
| 15 |
+
"assessment": "positive" if sentiment.polarity > 0
|
| 16 |
+
else "negative" if sentiment.polarity < 0
|
| 17 |
+
else "neutral"
|
| 18 |
}
|
| 19 |
|
| 20 |
+
@app.post("/mcp/sentiment")
|
| 21 |
+
async def handle_mcp_request(data: dict):
|
| 22 |
+
"""
|
| 23 |
+
MCP-compatible endpoint
|
| 24 |
+
Expected input: {"parameters": {"text": "your text here"}}
|
| 25 |
+
"""
|
| 26 |
+
try:
|
| 27 |
+
text = data.get("parameters", {}).get("text", "")
|
| 28 |
+
if not text:
|
| 29 |
+
raise HTTPException(status_code=400, detail="Missing 'text' parameter")
|
| 30 |
+
|
| 31 |
+
result = analyze_sentiment(text)
|
| 32 |
+
return {
|
| 33 |
+
"jsonrpc": "2.0",
|
| 34 |
+
"result": result,
|
| 35 |
+
"id": "sentiment-response"
|
| 36 |
+
}
|
| 37 |
+
except Exception as e:
|
| 38 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 39 |
+
|
| 40 |
+
from fastapi.staticfiles import StaticFiles
|
| 41 |
+
import gradio as gr
|
| 42 |
+
|
| 43 |
+
# Mount Gradio interface at /ui
|
| 44 |
+
app.mount("/ui", gr.routes.App.create_app(demo))
|
| 45 |
|
| 46 |
+
# Create Gradio interface (same as original)
|
| 47 |
demo = gr.Interface(
|
| 48 |
+
fn=lambda text: analyze_sentiment(text),
|
| 49 |
+
inputs=gr.Textbox(),
|
| 50 |
+
outputs=gr.JSON(),
|
| 51 |
+
title="Sentiment Analysis UI"
|
|
|
|
| 52 |
)
|
| 53 |
|
|
|
|
| 54 |
if __name__ == "__main__":
|
| 55 |
+
uvicorn.run(app, host="0.0.0.0", port=8000)
|