wlchee commited on
Commit
6d92c9d
·
verified ·
1 Parent(s): ca042ba

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +25 -17
app.py CHANGED
@@ -1,37 +1,45 @@
1
  import gradio as gr
2
- from textblob import TextBlob
3
- import nltk
4
 
 
 
5
 
6
- nltk.download('punkt')
7
  def sentiment_analysis(text: str) -> dict:
8
  """
9
- Analyze the sentiment of the given text.
10
 
11
  Args:
12
- text (str): The text to analyze
13
 
14
  Returns:
15
- dict: A dictionary containing polarity, subjectivity, and assessment
16
  """
17
- blob = TextBlob(text)
18
- sentiment = blob.sentiment
19
 
 
 
 
 
 
 
 
 
 
20
  return {
21
- "polarity": round(sentiment.polarity, 2), # -1 (negative) to 1 (positive)
22
- "subjectivity": round(sentiment.subjectivity, 2), # 0 (objective) to 1 (subjective)
23
- "assessment": "positive" if sentiment.polarity > 0 else "negative" if sentiment.polarity < 0 else "neutral"
24
  }
25
 
26
- # Create the Gradio interface
27
  demo = gr.Interface(
28
  fn=sentiment_analysis,
29
- inputs=gr.Textbox(placeholder="Enter text to analyze..."),
30
  outputs=gr.JSON(),
31
- title="Text Sentiment Analysis",
32
- description="Analyze the sentiment of text using TextBlob"
33
  )
34
 
35
- # Launch the interface and MCP server
36
  if __name__ == "__main__":
37
- demo.launch(mcp_server=True)
 
1
  import gradio as gr
2
+ from transformers import pipeline
 
3
 
4
+ # Load pretrained sentiment analysis pipeline
5
+ sentiment_pipeline = pipeline("sentiment-analysis")
6
 
 
7
  def sentiment_analysis(text: str) -> dict:
8
  """
9
+ Analyze sentiment using a transformer model, without lexicon.
10
 
11
  Args:
12
+ text (str): The input text.
13
 
14
  Returns:
15
+ dict: Polarity (mapped from model confidence), assessment, and subjectivity (heuristic).
16
  """
17
+ result = sentiment_pipeline(text)[0]
 
18
 
19
+ label = result['label']
20
+ score = result['score']
21
+
22
+ polarity = score if label == "POSITIVE" else -score
23
+ assessment = "positive" if polarity > 0.2 else "negative" if polarity < -0.2 else "neutral"
24
+
25
+ # Heuristic for subjectivity: high confidence implies more subjective
26
+ subjectivity = round(score, 2)
27
+
28
  return {
29
+ "polarity": round(polarity, 2),
30
+ "subjectivity": subjectivity,
31
+ "assessment": assessment
32
  }
33
 
34
+ # Gradio Interface
35
  demo = gr.Interface(
36
  fn=sentiment_analysis,
37
+ inputs=gr.Textbox(placeholder="Enter text to analyze...", lines=4),
38
  outputs=gr.JSON(),
39
+ title="Transformer-Based Sentiment Analysis",
40
+ description="Analyze sentiment using a pre-trained BERT model (no lexicons or rule-based logic)."
41
  )
42
 
43
+ # Run on Gradio MCP
44
  if __name__ == "__main__":
45
+ demo.launch(mcp_server=True)