jeevitha-app's picture
Update app.py
3b908e2 verified
# ============================================================
# 🌍 Multi-Lingual Sentiment Analysis (English + Persian)
# Simple & Clean Deployment (No SHAP Visualization)
# ============================================================
import gradio as gr
import joblib
import numpy as np
# ------------------------------------------------------------
# 1️⃣ Load Pretrained Models and Vectorizers
# ------------------------------------------------------------
try:
english_model = joblib.load("best_model_english.pkl")
english_vectorizer = joblib.load("tfidf_vectorizer_english.pkl")
persian_model = joblib.load("best_model_persian.pkl")
persian_vectorizer = joblib.load("tfidf_vectorizer_persian.pkl")
print("✅ Models and vectorizers loaded successfully!")
except Exception as e:
raise RuntimeError(f"❌ Error loading models: {e}")
# Define class labels
english_labels = ["Negative", "Neutral", "Positive"]
persian_labels = ["منفی", "خنثی", "مثبت"]
# ------------------------------------------------------------
# 2️⃣ Prediction Function (No SHAP)
# ------------------------------------------------------------
def predict_sentiment(text, language):
if not text.strip():
return "⚠️ Please enter a comment to analyze."
try:
if language == "English":
model, vectorizer, labels = english_model, english_vectorizer, english_labels
else:
model, vectorizer, labels = persian_model, persian_vectorizer, persian_labels
X_input = vectorizer.transform([text])
probs = model.predict_proba(X_input)[0]
pred_idx = np.argmax(probs)
pred_class = labels[pred_idx]
conf = probs[pred_idx]
# Output explanation
explanation = f"""
### 🧠 Predicted Sentiment: **{pred_class}**
**Confidence:** {conf:.2f}
"""
return explanation
except Exception as e:
return f"❌ Error during prediction: {str(e)}"
# ------------------------------------------------------------
# 3️⃣ Gradio Interface
# ------------------------------------------------------------
title = "🌐 Multi-Lingual Sentiment Analysis (English + Persian)"
description = """
Select a language, type a comment, and get the predicted sentiment instantly.
"""
examples = [
["I love this product! Highly recommend.", "English"],
["Bad experience ever, totally disappointed.", "English"],
["The service was okay, nothing special.", "English"],
["این محصول فوق‌العاده است", "Persian"],
["تجربه‌ی بدی بود، ناراضی‌ام", "Persian"],
["کیفیتش متوسط بود", "Persian"]
]
demo = gr.Interface(
fn=predict_sentiment,
inputs=[
gr.Textbox(lines=3, label="Enter your comment"),
gr.Radio(["English", "Persian"], label="Choose Dataset/Language", value="English")
],
outputs=gr.Markdown(label="Prediction"),
title=title,
description=description,
examples=examples,
theme="gradio/soft"
)
if __name__ == "__main__":
demo.launch()