Update app.py
Browse files
app.py
CHANGED
|
@@ -5,13 +5,10 @@ import gradio as gr
|
|
| 5 |
import spacy
|
| 6 |
import nltk
|
| 7 |
import numpy as np
|
| 8 |
-
import pandas as pd
|
| 9 |
from nltk.stem import WordNetLemmatizer
|
| 10 |
from spacy.lang.en.stop_words import STOP_WORDS
|
| 11 |
|
| 12 |
-
#
|
| 13 |
-
# 1. Setup dependencies
|
| 14 |
-
# ------------------------------
|
| 15 |
try:
|
| 16 |
nltk.data.find('tokenizers/punkt')
|
| 17 |
nltk.data.find('tokenizers/punkt_tab')
|
|
@@ -20,7 +17,7 @@ except LookupError:
|
|
| 20 |
nltk.download('punkt')
|
| 21 |
nltk.download('punkt_tab')
|
| 22 |
nltk.download('wordnet')
|
| 23 |
-
|
| 24 |
try:
|
| 25 |
nlp = spacy.load("en_core_web_sm")
|
| 26 |
except OSError:
|
|
@@ -30,18 +27,13 @@ except OSError:
|
|
| 30 |
|
| 31 |
lemmatizer = WordNetLemmatizer()
|
| 32 |
|
| 33 |
-
|
| 34 |
-
# 2. Load model and vectorizer
|
| 35 |
-
# ------------------------------
|
| 36 |
-
logistic_regression_model = joblib.load('logistic_regression_bow.pkl') # ensure this is the TF‑IDF model
|
| 37 |
tfidf_vectorizer = joblib.load('vectorizer_tfidf.pkl')
|
| 38 |
|
| 39 |
-
#
|
| 40 |
feature_names = np.array(tfidf_vectorizer.get_feature_names_out())
|
| 41 |
|
| 42 |
-
# ------------------------------
|
| 43 |
# 3. Label mapping
|
| 44 |
-
# ------------------------------
|
| 45 |
label_mapping = {
|
| 46 |
0: 'sadness',
|
| 47 |
1: 'joy',
|
|
@@ -51,12 +43,10 @@ label_mapping = {
|
|
| 51 |
5: 'surprise'
|
| 52 |
}
|
| 53 |
|
| 54 |
-
#
|
| 55 |
-
# 4. Text cleaning (identical to training)
|
| 56 |
-
# ------------------------------
|
| 57 |
def basic_cleaning(text):
|
| 58 |
text = re.sub(r'http\S+', '', text)
|
| 59 |
-
text = re.sub(r'[^a-zA-Z\s]', '', text)
|
| 60 |
text = re.sub(r'\w*\d\w*', '', text)
|
| 61 |
text = re.sub(r'<.*?>', '', text)
|
| 62 |
text = text.lower()
|
|
@@ -70,82 +60,74 @@ def fully_cleaned(text):
|
|
| 70 |
tokens = [lemmatizer.lemmatize(token) for token in tokens]
|
| 71 |
return ' '.join(tokens)
|
| 72 |
|
| 73 |
-
#
|
| 74 |
-
# 5. Prediction + interpretation
|
| 75 |
-
# ------------------------------
|
| 76 |
@spaces.GPU
|
| 77 |
-
def
|
| 78 |
if not text.strip():
|
| 79 |
-
return "Unknown", []
|
| 80 |
-
|
| 81 |
cleaned_text = fully_cleaned(text)
|
| 82 |
text_tfidf = tfidf_vectorizer.transform([cleaned_text])
|
| 83 |
-
|
| 84 |
-
#
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
#
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
else:
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
return emotion, highlighted, weight_str
|
| 120 |
-
|
| 121 |
-
# ------------------------------
|
| 122 |
-
# 6. Gradio interface
|
| 123 |
-
# ------------------------------
|
| 124 |
-
with gr.Blocks(title="Emotion Classifier with Interpretation") as demo:
|
| 125 |
-
gr.Markdown("# Emotion Classifier with Word‑level Interpretation")
|
| 126 |
-
gr.Markdown("Enter a sentence. The model will predict the emotion and show which words **positively** influenced that prediction, along with their exact weights (coefficients).")
|
| 127 |
-
|
| 128 |
with gr.Row():
|
| 129 |
with gr.Column():
|
| 130 |
-
input_text = gr.Textbox(lines=5, placeholder="
|
| 131 |
-
submit_btn = gr.Button("Classify")
|
|
|
|
| 132 |
with gr.Column():
|
| 133 |
-
|
| 134 |
output_highlights = gr.HighlightedText(
|
| 135 |
-
label="Word
|
| 136 |
combine_adjacent=False,
|
| 137 |
show_legend=True
|
| 138 |
)
|
| 139 |
-
|
| 140 |
-
|
| 141 |
submit_btn.click(
|
| 142 |
-
fn=
|
| 143 |
inputs=input_text,
|
| 144 |
-
outputs=[
|
| 145 |
)
|
| 146 |
|
| 147 |
-
#
|
| 148 |
-
# 7. Launch
|
| 149 |
-
# ------------------------------
|
| 150 |
if __name__ == "__main__":
|
| 151 |
-
demo.launch()
|
|
|
|
| 5 |
import spacy
|
| 6 |
import nltk
|
| 7 |
import numpy as np
|
|
|
|
| 8 |
from nltk.stem import WordNetLemmatizer
|
| 9 |
from spacy.lang.en.stop_words import STOP_WORDS
|
| 10 |
|
| 11 |
+
# 1. Setup NLTK and SpaCy dependencies
|
|
|
|
|
|
|
| 12 |
try:
|
| 13 |
nltk.data.find('tokenizers/punkt')
|
| 14 |
nltk.data.find('tokenizers/punkt_tab')
|
|
|
|
| 17 |
nltk.download('punkt')
|
| 18 |
nltk.download('punkt_tab')
|
| 19 |
nltk.download('wordnet')
|
| 20 |
+
|
| 21 |
try:
|
| 22 |
nlp = spacy.load("en_core_web_sm")
|
| 23 |
except OSError:
|
|
|
|
| 27 |
|
| 28 |
lemmatizer = WordNetLemmatizer()
|
| 29 |
|
| 30 |
+
logistic_regression_tfidf_model = joblib.load('logistic_regression_bow.pkl')
|
|
|
|
|
|
|
|
|
|
| 31 |
tfidf_vectorizer = joblib.load('vectorizer_tfidf.pkl')
|
| 32 |
|
| 33 |
+
# Extract feature names at startup for word mapping
|
| 34 |
feature_names = np.array(tfidf_vectorizer.get_feature_names_out())
|
| 35 |
|
|
|
|
| 36 |
# 3. Label mapping
|
|
|
|
| 37 |
label_mapping = {
|
| 38 |
0: 'sadness',
|
| 39 |
1: 'joy',
|
|
|
|
| 43 |
5: 'surprise'
|
| 44 |
}
|
| 45 |
|
| 46 |
+
# 4. Include the text cleaning functions from your notebook (Kept identical)
|
|
|
|
|
|
|
| 47 |
def basic_cleaning(text):
|
| 48 |
text = re.sub(r'http\S+', '', text)
|
| 49 |
+
text = re.sub(r'[^a-zA-Z\s]', '', text)
|
| 50 |
text = re.sub(r'\w*\d\w*', '', text)
|
| 51 |
text = re.sub(r'<.*?>', '', text)
|
| 52 |
text = text.lower()
|
|
|
|
| 60 |
tokens = [lemmatizer.lemmatize(token) for token in tokens]
|
| 61 |
return ' '.join(tokens)
|
| 62 |
|
| 63 |
+
# 5. Prediction & Interpretation function
|
|
|
|
|
|
|
| 64 |
@spaces.GPU
|
| 65 |
+
def predict_emotion_with_interpretation(text):
|
| 66 |
if not text.strip():
|
| 67 |
+
return "Unknown", []
|
| 68 |
+
|
| 69 |
cleaned_text = fully_cleaned(text)
|
| 70 |
text_tfidf = tfidf_vectorizer.transform([cleaned_text])
|
| 71 |
+
|
| 72 |
+
# Get the predicted class index
|
| 73 |
+
prediction = logistic_regression_tfidf_model.predict(text_tfidf)[0]
|
| 74 |
+
predicted_emotion = label_mapping.get(prediction, "Unknown")
|
| 75 |
+
|
| 76 |
+
# --- Interpretation Logic ---
|
| 77 |
+
word_weights = {}
|
| 78 |
+
if hasattr(logistic_regression_tfidf_model, "coef_"):
|
| 79 |
+
# Get the coefficients assigned to features for the predicted class
|
| 80 |
+
coefs = logistic_regression_tfidf_model.coef_[prediction]
|
| 81 |
+
|
| 82 |
+
# Identify features present in the user's input string
|
| 83 |
+
_, present_word_indices = text_tfidf.nonzero()
|
| 84 |
+
|
| 85 |
+
for idx in present_word_indices:
|
| 86 |
+
word = feature_names[idx]
|
| 87 |
+
weight = coefs[idx]
|
| 88 |
+
if weight > 0: # Only look at words that positively correlate with this class
|
| 89 |
+
word_weights[word] = weight
|
| 90 |
+
|
| 91 |
+
# Break original text into words to build the highlight tuples for Gradio
|
| 92 |
+
words = text.split()
|
| 93 |
+
highlighted_output = []
|
| 94 |
+
|
| 95 |
+
for word in words:
|
| 96 |
+
# Match back using the exact basic cleaning and lemmatization logic
|
| 97 |
+
clean_w = lemmatizer.lemmatize(basic_cleaning(word).strip())
|
| 98 |
+
|
| 99 |
+
if clean_w in word_weights:
|
| 100 |
+
# Append word with the classification label to highlight it
|
| 101 |
+
highlighted_output.append((word + " ", predicted_emotion))
|
| 102 |
else:
|
| 103 |
+
highlighted_output.append((word + " ", None))
|
| 104 |
+
|
| 105 |
+
return predicted_emotion, highlighted_output
|
| 106 |
+
|
| 107 |
+
# 6. Gradio Interface (Updated layout structure to present the interpretation)
|
| 108 |
+
with gr.Blocks(title="Emotion Classifier") as demo:
|
| 109 |
+
gr.Markdown("# Emotion Classifier")
|
| 110 |
+
gr.Markdown("Enter a sentence to classify its emotion and instantly see which words contributed to the prediction.")
|
| 111 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
with gr.Row():
|
| 113 |
with gr.Column():
|
| 114 |
+
input_text = gr.Textbox(lines=5, placeholder="Enter text here...", label="Input Text")
|
| 115 |
+
submit_btn = gr.Button("Classify Emotion")
|
| 116 |
+
|
| 117 |
with gr.Column():
|
| 118 |
+
output_label = gr.Textbox(label="Predicted Emotion")
|
| 119 |
output_highlights = gr.HighlightedText(
|
| 120 |
+
label="Word Contribution Interpretation",
|
| 121 |
combine_adjacent=False,
|
| 122 |
show_legend=True
|
| 123 |
)
|
| 124 |
+
|
|
|
|
| 125 |
submit_btn.click(
|
| 126 |
+
fn=predict_emotion_with_interpretation,
|
| 127 |
inputs=input_text,
|
| 128 |
+
outputs=[output_label, output_highlights]
|
| 129 |
)
|
| 130 |
|
| 131 |
+
# Launch the interface
|
|
|
|
|
|
|
| 132 |
if __name__ == "__main__":
|
| 133 |
+
demo.launch()
|