rahmanashis01 commited on
Commit
4c3e148
·
verified ·
1 Parent(s): 62059a2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +29 -24
app.py CHANGED
@@ -2,38 +2,43 @@ import json
2
  import gradio as gr
3
  from textblob import TextBlob
4
 
5
-
6
- def sentiment_analysis(text: str) -> str:
7
  """
8
- Analyze the sentiment of the given text.
9
-
10
- Args:
11
- text (str): The text to analyze
12
-
13
- Returns:
14
- str: A JSON string containing polarity, subjectivity, and assessment
15
  """
 
 
 
16
  blob = TextBlob(text)
17
  sentiment = blob.sentiment
18
 
19
- result = {
20
- "polarity": round(sentiment.polarity, 2), # -1 (negative) to 1 (positive)
21
- "subjectivity": round(sentiment.subjectivity, 2), # 0 (objective) to 1 (subjective)
22
- "assessment": "positive" if sentiment.polarity > 0 else "negative" if sentiment.polarity < 0 else "neutral",
 
 
 
 
23
  }
24
 
25
- return json.dumps(result)
 
 
 
 
 
26
 
 
27
 
28
- demo = gr.Interface(
29
- fn=sentiment_analysis,
30
- inputs=gr.Textbox(placeholder="Enter text to analyze..."),
31
- outputs=gr.Textbox(), # Changed from gr.JSON() to gr.Textbox()
32
- title="Text Sentiment Analysis",
33
- description="Analyze the sentiment of text using TextBlob",
34
- )
35
 
 
 
36
 
37
- # Launch the interface and MCP server
38
- if __name__ == "__main__":
39
- demo.launch(mcp_server=True)
 
 
2
  import gradio as gr
3
  from textblob import TextBlob
4
 
5
+ def sentiment_analysis(text: str) -> dict:
 
6
  """
7
+ Analyze the sentiment of the given text and return a dict (not a string).
8
+ HF + MCP both like dicts better.
 
 
 
 
 
9
  """
10
+ if not text:
11
+ return {"error": "No text provided"}
12
+
13
  blob = TextBlob(text)
14
  sentiment = blob.sentiment
15
 
16
+ return {
17
+ "polarity": round(sentiment.polarity, 2),
18
+ "subjectivity": round(sentiment.subjectivity, 2),
19
+ "assessment": (
20
+ "positive" if sentiment.polarity > 0
21
+ else "negative" if sentiment.polarity < 0
22
+ else "neutral"
23
+ ),
24
  }
25
 
26
+ # ---------- Gradio UI ----------
27
+ with gr.Blocks() as demo:
28
+ gr.Markdown("# Text Sentiment Analysis (MCP)")
29
+ inp = gr.Textbox(placeholder="Enter text to analyze...", label="Text")
30
+ out = gr.JSON(label="Sentiment")
31
+ btn = gr.Button("Analyze")
32
 
33
+ btn.click(fn=sentiment_analysis, inputs=inp, outputs=out)
34
 
35
+ # HF looks for this:
36
+ app = demo
 
 
 
 
 
37
 
38
+ # ---------- MCP ----------
39
+ mcp_app = gr.mcp.App()
40
 
41
+ @mcp_app.tool()
42
+ def analyze(text: str) -> dict:
43
+ """MCP tool to expose the same sentiment analysis."""
44
+ return sentiment_analysis(text)