Spaces:
Build error
Build error
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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__":
|
| 51 |
+
iface.launch()
|