karthik55's picture
version 2
54a9c76 verified
import gradio as gr
import joblib
# Load models and vectorizer from the models folder
logistic_model = joblib.load("models/best_logistic_model.pkl")
svm_model = joblib.load("models/best_svc_model.pkl")
random_forest_model = joblib.load("models/best_rf_model.pkl")
knn_model = joblib.load("models/best_knn_model.pkl")
vectorizer = joblib.load("models/vectorizer.pkl")
# Model selection mapping
models = {
"Logistic Regression": logistic_model,
"SVM": svm_model,
"Random Forest": random_forest_model,
"KNN": knn_model,
}
# Prediction function
def predict_sentiment(review, model_name):
try:
if not review.strip():
return "Error: Review cannot be empty", None
if model_name not in models:
return "Error: Invalid model selected", None
# Preprocess the text
text_vector = vectorizer.transform([review])
# Predict using the selected model
model = models[model_name]
prediction = model.predict(text_vector)[0]
probabilities = model.predict_proba(text_vector)[0] if hasattr(model, "predict_proba") else None
# Format the output
sentiment = "Positive Feedback" if prediction == 1 else "Negative Feedback"
probabilities_output = (
{
"Positive": probabilities[1], # Raw probability (0.0 - 1.0)
"Negative": probabilities[0], # Raw probability (0.0 - 1.0)
}
if probabilities is not None
else "Probabilities not available"
)
return sentiment, probabilities_output
except Exception as e:
# Log the error to the console for debugging
print(f"Error in prediction: {e}")
return f"Error: {str(e)}", None
# Create Gradio Interface
inputs = [
gr.Textbox(label="Review Comment", placeholder="Enter your review here..."),
gr.Dropdown(choices=["Logistic Regression", "SVM", "Random Forest", "KNN"], label="Model"),
]
outputs = [
gr.Textbox(label="Predicted Sentiment Class"),
gr.Label(label="Predicted Probability"),
]
# Launch Gradio App
gr.Interface(
fn=predict_sentiment,
inputs=inputs,
outputs=outputs,
title="Sentiment Analysis",
description="Enter a review and select a model to predict sentiment.",
).launch()