Ashed00 commited on
Commit
039a1e6
Β·
verified Β·
1 Parent(s): 47b8b45

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +15 -27
app.py CHANGED
@@ -4,8 +4,6 @@ import torch
4
  import gradio as gr
5
  import matplotlib.pyplot as plt
6
  import numpy as np
7
- from io import BytesIO
8
- from PIL import Image
9
 
10
  # Load model and tokenizer
11
  tokenizer = AutoTokenizer.from_pretrained("nlptown/bert-base-multilingual-uncased-sentiment")
@@ -50,32 +48,23 @@ def analyze_text(text):
50
  # Generate SHAP explanations
51
  shap_values = explainer([text])
52
 
53
- # Create matplotlib figures for each class
54
- images = []
55
- for i in range(5):
56
- plt.figure(figsize=(10, 3))
57
- shap.plots.text(shap_values[:, :, i], display=False)
58
- plt.title(f"Feature importance for {output_names_list[i]}")
59
- plt.tight_layout()
60
-
61
- # Save plot to in-memory buffer
62
- buf = BytesIO()
63
- plt.savefig(buf, format="png", bbox_inches="tight")
64
- plt.close()
65
- buf.seek(0)
66
-
67
- # Convert BytesIO to PIL Image
68
- image = Image.open(buf)
69
- images.append(image)
70
 
71
  # Format confidence scores
72
  confidence_scores = {model.config.id2label[i]: float(probabilities[i])
73
- for i in range(len(probabilities))}
74
 
75
- return (predicted_label, confidence_scores, *images)
 
 
76
 
77
- # Create Gradio interface with image components
78
- with gr.Blocks() as demo:
79
  gr.Markdown("## πŸ” BERT Sentiment Analysis with SHAP Explanations")
80
 
81
  with gr.Row():
@@ -92,7 +81,7 @@ with gr.Blocks() as demo:
92
  gr.Markdown("""
93
  ### SHAP Explanations
94
  Below you can see how each word contributes to different sentiment scores (1-5 stars).
95
- Positive values increase the score, negative values decrease it.
96
  """)
97
 
98
  # Individual Explanation Rows
@@ -100,9 +89,8 @@ with gr.Blocks() as demo:
100
  for i in range(5):
101
  with gr.Row():
102
  plot_components.append(
103
- gr.Image(
104
  label=f"Explanation for {model.config.id2label[i]}",
105
- type="pil",
106
  elem_classes=f"shap-plot-{i+1}"
107
  )
108
  )
@@ -124,4 +112,4 @@ with gr.Blocks() as demo:
124
  )
125
 
126
  if __name__ == "__main__":
127
- demo.launch(share=True)
 
4
  import gradio as gr
5
  import matplotlib.pyplot as plt
6
  import numpy as np
 
 
7
 
8
  # Load model and tokenizer
9
  tokenizer = AutoTokenizer.from_pretrained("nlptown/bert-base-multilingual-uncased-sentiment")
 
48
  # Generate SHAP explanations
49
  shap_values = explainer([text])
50
 
51
+ # Create HTML visualizations for all classes
52
+ html_plots = []
53
+ for i in range(shap_values.shape[-1]):
54
+ # Create SHAP text plot and convert to HTML
55
+ plot_html = shap.plots.text(shap_values[0, :, i], display=False)
56
+ html_plots.append(plot_html)
 
 
 
 
 
 
 
 
 
 
 
57
 
58
  # Format confidence scores
59
  confidence_scores = {model.config.id2label[i]: float(probabilities[i])
60
+ for i in range(len(probabilities))}
61
 
62
+ return (predicted_label,
63
+ confidence_scores,
64
+ *html_plots)
65
 
66
+ # Create Gradio interface with HTML components
67
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
68
  gr.Markdown("## πŸ” BERT Sentiment Analysis with SHAP Explanations")
69
 
70
  with gr.Row():
 
81
  gr.Markdown("""
82
  ### SHAP Explanations
83
  Below you can see how each word contributes to different sentiment scores (1-5 stars).
84
+ Red text increases the score, blue decreases it.
85
  """)
86
 
87
  # Individual Explanation Rows
 
89
  for i in range(5):
90
  with gr.Row():
91
  plot_components.append(
92
+ gr.HTML(
93
  label=f"Explanation for {model.config.id2label[i]}",
 
94
  elem_classes=f"shap-plot-{i+1}"
95
  )
96
  )
 
112
  )
113
 
114
  if __name__ == "__main__":
115
+ demo.launch(debug = True