import gradio as gr from transformers import pipeline sentiment_classifier = pipeline("text-classification", return_all_scores=True) def classifier(text): pred = sentiment_classifier(text) return {p["label"]: p["score"] for p in pred[0]} def interpretation_function(text): explainer = shap.Explainer(sentiment_classifier) shap_values = explainer([text]) # Dimensions are (batch size, text size, number of classes) # Since we care about positive sentiment, use index 1 scores = list(zip(shap_values.data[0], shap_values.values[0, :, 1])) # Scores contains (word, score) pairs # Format expected by gr.components.Interpretation return {"original": text, "interpretation": scores} with gr.Blocks() as demo: with gr.Row(): with gr.Column(): input_text = gr.Textbox(label="Input Text") with gr.Row(): classify = gr.Button("Classify Sentiment") interpret = gr.Button("Interpret") with gr.Column(): label = gr.Label(label="Predicted Sentiment") with gr.Column(): interpretation = gr.components.Interpretation(input_text) classify.click(classifier, input_text, label) interpret.click(interpretation_function, input_text, interpretation) demo.launch(share = True)