Spaces:
Sleeping
Sleeping
Update app.py
Browse files
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 |
-
#
|
| 9 |
-
classifier = pipeline(
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
-
|
|
|
|
|
|
|
|
|
|
| 12 |
if not text.strip():
|
| 13 |
-
return "Please enter text",
|
| 14 |
|
| 15 |
-
#
|
| 16 |
result = classifier(text)[0]
|
| 17 |
label = result["label"]
|
| 18 |
score = result["score"]
|
| 19 |
|
| 20 |
-
# SHAP
|
| 21 |
-
explainer = shap.Explainer(classifier)
|
| 22 |
shap_values = explainer([text])
|
| 23 |
|
| 24 |
-
#
|
| 25 |
-
|
| 26 |
-
shap.plots.text(shap_values[0], display=False)
|
| 27 |
|
| 28 |
-
return f"Prediction: {label} (Confidence: {score:.2f})",
|
| 29 |
|
| 30 |
-
with gr.Blocks(
|
| 31 |
-
gr.Markdown("# Sentiment Analysis with SHAP
|
| 32 |
|
| 33 |
inp = gr.Textbox(lines=4, placeholder="Enter text here...")
|
| 34 |
-
|
| 35 |
-
|
|
|
|
| 36 |
btn = gr.Button("Analyze")
|
| 37 |
|
| 38 |
-
btn.click(
|
| 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()
|