Jatin112002 commited on
Commit
7404c54
·
verified ·
1 Parent(s): 5c71967

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +30 -7
app.py CHANGED
@@ -1,20 +1,43 @@
1
  from transformers import pipeline
2
  import gradio as gr
 
 
 
 
3
 
4
- # Load sentiment analysis model
5
- sentiment_model = pipeline("sentiment-analysis")
6
 
 
 
 
 
7
  def analyze_sentiment(text):
8
- result = sentiment_model(text)[0]
9
- return f"Sentiment: {result['label']} (Confidence: {result['score']:.2f})"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
 
11
  # Create Gradio interface
12
  iface = gr.Interface(
13
  fn=analyze_sentiment,
14
  inputs="text",
15
  outputs="text",
16
- title="Sentiment Analysis App",
17
- description="Enter a sentence to analyze its sentiment (Positive/Negative)."
 
18
  )
19
 
20
- iface.launch()
 
1
  from transformers import pipeline
2
  import gradio as gr
3
+ import lime
4
+ import lime.lime_text
5
+ import numpy as np
6
+ from sklearn.pipeline import make_pipeline
7
 
8
+ # Load multi-class sentiment analysis model
9
+ sentiment_model = pipeline("text-classification", model="cardiffnlp/twitter-roberta-base-sentiment", top_k=None)
10
 
11
+ # Define possible sentiment classes
12
+ labels = ["very negative", "negative", "slightly negative", "neutral", "slightly positive", "positive", "very positive", "anger", "joy", "sadness"]
13
+
14
+ # Function to get sentiment prediction
15
  def analyze_sentiment(text):
16
+ results = sentiment_model(text)
17
+ scores = {res['label']: res['score'] for res in results[0]}
18
+ sorted_scores = sorted(scores.items(), key=lambda x: x[1], reverse=True)
19
+ top_label, top_confidence = sorted_scores[0]
20
+ return f"Sentiment: {top_label} (Confidence: {top_confidence:.2f})"
21
+
22
+ # Explainability function using LIME
23
+ def explain_prediction(text):
24
+ explainer = lime.lime_text.LimeTextExplainer(class_names=labels)
25
+
26
+ def predictor(texts):
27
+ predictions = [sentiment_model(text)[0] for text in texts]
28
+ return np.array([[pred[label] if label in pred else 0 for label in labels] for pred in predictions])
29
+
30
+ exp = explainer.explain_instance(text, predictor, num_features=6)
31
+ return exp.as_list()
32
 
33
  # Create Gradio interface
34
  iface = gr.Interface(
35
  fn=analyze_sentiment,
36
  inputs="text",
37
  outputs="text",
38
+ title="Multi-Class Sentiment Analysis App",
39
+ description="Enter a sentence to analyze its sentiment across multiple categories.",
40
+ live=True
41
  )
42
 
43
+ iface.launch()