Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,38 +1,56 @@
|
|
| 1 |
-
# app.py
|
| 2 |
-
import gradio as gr
|
| 3 |
-
import joblib
|
| 4 |
-
|
| 5 |
-
# ---
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
vectorizer
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app.py (with human-readable labels)
|
| 2 |
+
import gradio as gr
|
| 3 |
+
import joblib
|
| 4 |
+
|
| 5 |
+
# --- Load Model and Vectorizer ---
|
| 6 |
+
try:
|
| 7 |
+
model = joblib.load('logistic_regression_model.joblib')
|
| 8 |
+
vectorizer = joblib.load('tfidf_vectorizer.joblib')
|
| 9 |
+
print("β
Model and vectorizer loaded successfully!")
|
| 10 |
+
except Exception as e:
|
| 11 |
+
print(f"π Error loading files: {e}")
|
| 12 |
+
model, vectorizer = None, None
|
| 13 |
+
|
| 14 |
+
# --- Define Prediction Logic with Label Mapping ---
|
| 15 |
+
def predict_sentiment(text):
|
| 16 |
+
if not model or not vectorizer:
|
| 17 |
+
return "ERROR: Model is not loaded. Check terminal logs."
|
| 18 |
+
|
| 19 |
+
try:
|
| 20 |
+
# 1. Transform the input text
|
| 21 |
+
vectorized_text = vectorizer.transform([text])
|
| 22 |
+
|
| 23 |
+
# 2. Make a numerical prediction
|
| 24 |
+
prediction = model.predict(vectorized_text)
|
| 25 |
+
numeric_prediction = prediction[0]
|
| 26 |
+
|
| 27 |
+
# --- NEW CODE: Map prediction to labels ---
|
| 28 |
+
# 3. Define the mapping from numbers to labels
|
| 29 |
+
sentiment_map = {
|
| 30 |
+
0: "Neutral π",
|
| 31 |
+
1: "Happy π",
|
| 32 |
+
2: "Sad π"
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
# 4. Get the label from the map.
|
| 36 |
+
# The .get() method safely returns a default value if the key isn't found.
|
| 37 |
+
sentiment_label = sentiment_map.get(numeric_prediction, "Unknown Prediction")
|
| 38 |
+
|
| 39 |
+
# 5. Return the final human-readable label
|
| 40 |
+
return sentiment_label
|
| 41 |
+
|
| 42 |
+
except Exception as e:
|
| 43 |
+
print(f"--- PREDICTION ERROR --- \n{e}\n --- END ---")
|
| 44 |
+
return f"An error occurred during prediction: {e}"
|
| 45 |
+
|
| 46 |
+
# --- Create and Launch the Gradio Interface ---
|
| 47 |
+
iface = gr.Interface(
|
| 48 |
+
fn=predict_sentiment,
|
| 49 |
+
inputs=gr.Textbox(lines=5, label="Enter a Sentence"),
|
| 50 |
+
outputs=gr.Label(label="Predicted Sentiment"),
|
| 51 |
+
title="Sentiment Analysis Model",
|
| 52 |
+
description="Analyzes text and classifies it as Happy, Sad, or Neutral."
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
print("π Launching Gradio app...")
|
| 56 |
+
iface.launch()
|