Spaces:
Sleeping
Sleeping
File size: 1,901 Bytes
8ad5b10 1158562 8ad5b10 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
# 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()
|