vangru commited on
Commit
326a4f2
·
verified ·
1 Parent(s): e8d040e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +21 -19
app.py CHANGED
@@ -1,40 +1,42 @@
1
  import gradio as gr
2
- import torch
3
  import shap
4
- import numpy as np
5
- import matplotlib.pyplot as plt
6
  from transformers import pipeline
7
 
8
- # Load sentiment model
9
- classifier = pipeline("sentiment-analysis")
 
 
 
10
 
11
- def predict_with_shap(text):
 
 
 
12
  if not text.strip():
13
- return "Please enter text", None
14
 
15
- # Get prediction
16
  result = classifier(text)[0]
17
  label = result["label"]
18
  score = result["score"]
19
 
20
- # SHAP explainer
21
- explainer = shap.Explainer(classifier)
22
  shap_values = explainer([text])
23
 
24
- # Plot SHAP values
25
- plt.figure()
26
- shap.plots.text(shap_values[0], display=False)
27
 
28
- return f"Prediction: {label} (Confidence: {score:.2f})", plt.gcf()
29
 
30
- with gr.Blocks(title="Sentiment Analysis with SHAP") as demo:
31
- gr.Markdown("# Sentiment Analysis with SHAP Explanation")
32
 
33
  inp = gr.Textbox(lines=4, placeholder="Enter text here...")
34
- out_text = gr.Textbox(label="Prediction")
35
- out_plot = gr.Plot(label="SHAP Explanation")
 
36
  btn = gr.Button("Analyze")
37
 
38
- btn.click(predict_with_shap, inp, [out_text, out_plot])
39
 
40
  demo.launch()
 
1
  import gradio as gr
 
2
  import shap
 
 
3
  from transformers import pipeline
4
 
5
+ # Use lighter model (important for HF)
6
+ classifier = pipeline(
7
+ "sentiment-analysis",
8
+ model="distilbert-base-uncased-finetuned-sst-2-english"
9
+ )
10
 
11
+ # Create SHAP explainer once
12
+ explainer = shap.Explainer(classifier)
13
+
14
+ def analyze(text):
15
  if not text.strip():
16
+ return "Please enter text", ""
17
 
18
+ # Prediction
19
  result = classifier(text)[0]
20
  label = result["label"]
21
  score = result["score"]
22
 
23
+ # SHAP values
 
24
  shap_values = explainer([text])
25
 
26
+ # Convert SHAP to HTML
27
+ shap_html = shap.plots.text(shap_values[0], display=False)
 
28
 
29
+ return f"Prediction: {label} (Confidence: {score:.2f})", shap_html
30
 
31
+ with gr.Blocks() as demo:
32
+ gr.Markdown("# Sentiment Analysis with SHAP")
33
 
34
  inp = gr.Textbox(lines=4, placeholder="Enter text here...")
35
+ prediction = gr.Textbox(label="Prediction")
36
+ shap_output = gr.HTML(label="SHAP Explanation")
37
+
38
  btn = gr.Button("Analyze")
39
 
40
+ btn.click(analyze, inp, [prediction, shap_output])
41
 
42
  demo.launch()