Arvind111's picture
Update app.py
1158562 verified
# app.py (with human-readable labels)
import gradio as gr
import joblib
# --- Load Model and Vectorizer ---
try:
model = joblib.load('logistic_regression_model.joblib')
vectorizer = joblib.load('tfidf_vectorizer.joblib')
print("βœ… Model and vectorizer loaded successfully!")
except Exception as e:
print(f"πŸ›‘ Error loading files: {e}")
model, vectorizer = None, None
# --- Define Prediction Logic with Label Mapping ---
def predict_sentiment(text):
if not model or not vectorizer:
return "ERROR: Model is not loaded. Check terminal logs."
try:
# 1. Transform the input text
vectorized_text = vectorizer.transform([text])
# 2. Make a numerical prediction
prediction = model.predict(vectorized_text)
numeric_prediction = prediction[0]
# --- NEW CODE: Map prediction to labels ---
# 3. Define the mapping from numbers to labels
sentiment_map = {
0: "NEUTRAL",
1: "HAPPY",
2: "SAD"
}
# 4. Get the label from the map.
# The .get() method safely returns a default value if the key isn't found.
sentiment_label = sentiment_map.get(numeric_prediction, "Unknown Prediction")
# 5. Return the final human-readable label
return sentiment_label
except Exception as e:
print(f"--- PREDICTION ERROR --- \n{e}\n --- END ---")
return f"An error occurred during prediction: {e}"
# --- Create and Launch the Gradio Interface ---
iface = gr.Interface(
fn=predict_sentiment,
inputs=gr.Textbox(lines=5, label="Enter a Sentence"),
outputs=gr.Label(label="Predicted Sentiment"),
title="Sentiment Analysis Model",
description="Analyzes text and classifies it as Happy, Sad, or Neutral."
)
print("πŸš€ Launching Gradio app...")
iface.launch()