Spaces:
Sleeping
Sleeping
| import gradio as gr | |
| import joblib | |
| import shap | |
| import numpy as np | |
| import matplotlib.pyplot as plt | |
| import tempfile | |
| import os | |
| # --------------------------------------------------------- | |
| # Load both models and vectorizers | |
| # --------------------------------------------------------- | |
| english_model = joblib.load("models/english_model.pkl") | |
| english_vec = joblib.load("models/english_vectorizer.pkl") | |
| persian_model = joblib.load("models/persian_model.pkl") | |
| persian_vec = joblib.load("models/persian_vectorizer.pkl") | |
| class_names = ["Negative", "Neutral", "Positive"] | |
| # --------------------------------------------------------- | |
| # Prediction + Interpretability Function | |
| # --------------------------------------------------------- | |
| def predict_sentiment(text, language): | |
| if not text.strip(): | |
| return "Please enter text!", None | |
| if language == "English": | |
| model, vec = english_model, english_vec | |
| else: | |
| model, vec = persian_model, persian_vec | |
| X = vec.transform([text]) | |
| probs = model.predict_proba(X)[0] | |
| pred_idx = np.argmax(probs) | |
| label = class_names[pred_idx] | |
| # --- SHAP interpretability --- | |
| explainer = shap.LinearExplainer(model, vec.transform([text])) | |
| shap_vals = explainer(X) | |
| shap_values = shap_vals.values[0][:, pred_idx] | |
| feature_names = vec.get_feature_names_out() | |
| top_idx = np.argsort(-abs(shap_values))[:10] | |
| tokens = [feature_names[i] for i in top_idx] | |
| impacts = [shap_values[i] for i in top_idx] | |
| # Save temporary bar chart | |
| fig, ax = plt.subplots(figsize=(6, 3)) | |
| colors = ["crimson" if v > 0 else "steelblue" for v in impacts] | |
| ax.barh(tokens, impacts, color=colors) | |
| ax.invert_yaxis() | |
| ax.set_title(f"Top Words driving {label} prediction") | |
| tmp_path = tempfile.mktemp(suffix=".png") | |
| plt.tight_layout() | |
| plt.savefig(tmp_path) | |
| plt.close(fig) | |
| explanation = f""" | |
| **Predicted Sentiment:** {label}\n | |
| **Confidence:** {probs[pred_idx]:.2f}\n | |
| **Top Influential Words:**\n | |
| {', '.join(tokens)} | |
| """ | |
| return explanation, tmp_path | |
| # --------------------------------------------------------- | |
| # Gradio UI | |
| # --------------------------------------------------------- | |
| iface = gr.Interface( | |
| fn=predict_sentiment, | |
| inputs=[ | |
| gr.Textbox(lines=3, label="Enter comment"), | |
| gr.Radio(["English", "Persian"], label="Choose Dataset/Language") | |
| ], | |
| outputs=[ | |
| gr.Markdown(label="Prediction + Interpretation"), | |
| gr.Image(label="Top Word Contributions") | |
| ], | |
| title="๐ Multi-Lingual Sentiment Analysis (English + Persian)", | |
| description="Select a language, type a comment, and see both the prediction and SHAP interpretability." | |
| ) | |
| iface.launch() | |