bparekh99 commited on
Commit
521ad8c
·
verified ·
1 Parent(s): c6b8271

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +30 -24
app.py CHANGED
@@ -1,50 +1,56 @@
1
  import gradio as gr
2
  from transformers import pipeline, AutoTokenizer, AutoModelForSequenceClassification
3
- import shap
4
- import numpy as np
5
 
6
- # Load model and tokenizer
7
  def load_model():
8
  model_name = "cardiffnlp/twitter-roberta-base-sentiment"
9
  tokenizer = AutoTokenizer.from_pretrained(model_name)
10
  model = AutoModelForSequenceClassification.from_pretrained(model_name)
11
  sentiment_pipeline = pipeline("sentiment-analysis", model=model, tokenizer=tokenizer)
12
- return sentiment_pipeline, tokenizer, model
13
 
14
- sentiment_pipeline, tokenizer, model = load_model()
15
-
16
- # Label mapping
17
  label_map = {"LABEL_0": "negative", "LABEL_1": "neutral", "LABEL_2": "positive"}
18
 
19
- # Gradio inference function
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  def analyze_sentiment(text):
21
  if not text.strip():
22
- return "Please enter text.", "", None
23
-
24
- # Get prediction
25
  result = sentiment_pipeline(text)[0]
26
  sentiment = label_map[result["label"]]
27
  confidence = result["score"]
28
-
29
- # Explain with SHAP
30
- explainer = shap.Explainer(sentiment_pipeline)
31
- shap_values = explainer([text])
32
- explanation_html = shap.plots.text(shap_values[0], display=False)
33
-
34
  sentiment_result = f"**Sentiment**: {sentiment.capitalize()} \n**Confidence**: {confidence:.2f}"
35
- return sentiment_result, shap_values.data[0], explanation_html
36
 
37
- # Gradio Interface
38
  iface = gr.Interface(
39
  fn=analyze_sentiment,
40
- inputs=gr.Textbox(label="Enter text", lines=4, placeholder="Type something here..."),
41
  outputs=[
42
  gr.Markdown(label="Sentiment Result"),
43
- gr.Textbox(label="Tokenized Input"),
44
- gr.HTML(label="SHAP Explanation"),
45
  ],
46
- title="Sentiment Analyzer with Explanation",
47
- description="Enter a sentence or paragraph. This app will classify its sentiment as Positive, Negative, or Neutral and explain why using SHAP values.",
48
  )
49
 
50
  if __name__ == "__main__":
 
1
  import gradio as gr
2
  from transformers import pipeline, AutoTokenizer, AutoModelForSequenceClassification
 
 
3
 
4
+ # Load sentiment model
5
  def load_model():
6
  model_name = "cardiffnlp/twitter-roberta-base-sentiment"
7
  tokenizer = AutoTokenizer.from_pretrained(model_name)
8
  model = AutoModelForSequenceClassification.from_pretrained(model_name)
9
  sentiment_pipeline = pipeline("sentiment-analysis", model=model, tokenizer=tokenizer)
10
+ return sentiment_pipeline
11
 
12
+ sentiment_pipeline = load_model()
 
 
13
  label_map = {"LABEL_0": "negative", "LABEL_1": "neutral", "LABEL_2": "positive"}
14
 
15
+ # Simple explanation generator
16
+ def explain_sentiment(text, sentiment):
17
+ text_lower = text.lower()
18
+ if sentiment == "positive":
19
+ if any(word in text_lower for word in ["love", "great", "happy", "excellent", "good", "amazing"]):
20
+ return "Detected positive language such as 'great', 'happy', or 'love'."
21
+ else:
22
+ return "Overall positive tone based on context."
23
+ elif sentiment == "negative":
24
+ if any(word in text_lower for word in ["hate", "bad", "terrible", "awful", "worst", "sad"]):
25
+ return "Detected negative words like 'hate', 'bad', or 'worst'."
26
+ else:
27
+ return "Overall negative tone based on context."
28
+ else:
29
+ return "Text appears to be neutral with no strong emotional cues."
30
+
31
+ # Gradio function
32
  def analyze_sentiment(text):
33
  if not text.strip():
34
+ return "Please enter some text.", ""
35
+
 
36
  result = sentiment_pipeline(text)[0]
37
  sentiment = label_map[result["label"]]
38
  confidence = result["score"]
39
+ explanation = explain_sentiment(text, sentiment)
40
+
 
 
 
 
41
  sentiment_result = f"**Sentiment**: {sentiment.capitalize()} \n**Confidence**: {confidence:.2f}"
42
+ return sentiment_result, explanation
43
 
44
+ # Gradio interface
45
  iface = gr.Interface(
46
  fn=analyze_sentiment,
47
+ inputs=gr.Textbox(lines=4, placeholder="Type something here..."),
48
  outputs=[
49
  gr.Markdown(label="Sentiment Result"),
50
+ gr.Textbox(label="Explanation")
 
51
  ],
52
+ title="Fast Sentiment Analyzer",
53
+ description="Enter some text. This app will classify the sentiment (Positive, Negative, or Neutral) and offer a basic explanation.",
54
  )
55
 
56
  if __name__ == "__main__":