Update app.py
Browse files
app.py
CHANGED
|
@@ -1,14 +1,16 @@
|
|
| 1 |
-
import spaces
|
| 2 |
import re
|
| 3 |
import joblib
|
| 4 |
import gradio as gr
|
| 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 |
-
#
|
|
|
|
|
|
|
| 12 |
try:
|
| 13 |
nltk.data.find('tokenizers/punkt')
|
| 14 |
nltk.data.find('tokenizers/punkt_tab')
|
|
@@ -17,7 +19,7 @@ except LookupError:
|
|
| 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,13 +29,18 @@ except OSError:
|
|
| 27 |
|
| 28 |
lemmatizer = WordNetLemmatizer()
|
| 29 |
|
| 30 |
-
|
|
|
|
|
|
|
|
|
|
| 31 |
tfidf_vectorizer = joblib.load('vectorizer_tfidf.pkl')
|
| 32 |
|
| 33 |
-
#
|
| 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,10 +50,12 @@ label_mapping = {
|
|
| 43 |
5: 'surprise'
|
| 44 |
}
|
| 45 |
|
| 46 |
-
#
|
|
|
|
|
|
|
| 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,74 +69,82 @@ def fully_cleaned(text):
|
|
| 60 |
tokens = [lemmatizer.lemmatize(token) for token in tokens]
|
| 61 |
return ' '.join(tokens)
|
| 62 |
|
| 63 |
-
#
|
|
|
|
|
|
|
| 64 |
@spaces.GPU
|
| 65 |
-
def
|
| 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 |
-
#
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
#
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 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 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
with gr.Row():
|
| 113 |
with gr.Column():
|
| 114 |
-
input_text = gr.Textbox(lines=5, placeholder="
|
| 115 |
-
submit_btn = gr.Button("Classify
|
| 116 |
-
|
| 117 |
with gr.Column():
|
| 118 |
-
|
| 119 |
output_highlights = gr.HighlightedText(
|
| 120 |
-
label="Word
|
| 121 |
combine_adjacent=False,
|
| 122 |
show_legend=True
|
| 123 |
)
|
| 124 |
-
|
|
|
|
| 125 |
submit_btn.click(
|
| 126 |
-
fn=
|
| 127 |
inputs=input_text,
|
| 128 |
-
outputs=[
|
| 129 |
)
|
| 130 |
|
| 131 |
-
#
|
|
|
|
|
|
|
| 132 |
if __name__ == "__main__":
|
| 133 |
demo.launch()
|
|
|
|
|
|
|
| 1 |
import re
|
| 2 |
import joblib
|
| 3 |
import gradio as gr
|
| 4 |
import spacy
|
| 5 |
import nltk
|
| 6 |
import numpy as np
|
| 7 |
+
import pandas as pd
|
| 8 |
from nltk.stem import WordNetLemmatizer
|
| 9 |
from spacy.lang.en.stop_words import STOP_WORDS
|
| 10 |
|
| 11 |
+
# ------------------------------
|
| 12 |
+
# 1. Setup dependencies
|
| 13 |
+
# ------------------------------
|
| 14 |
try:
|
| 15 |
nltk.data.find('tokenizers/punkt')
|
| 16 |
nltk.data.find('tokenizers/punkt_tab')
|
|
|
|
| 19 |
nltk.download('punkt')
|
| 20 |
nltk.download('punkt_tab')
|
| 21 |
nltk.download('wordnet')
|
| 22 |
+
|
| 23 |
try:
|
| 24 |
nlp = spacy.load("en_core_web_sm")
|
| 25 |
except OSError:
|
|
|
|
| 29 |
|
| 30 |
lemmatizer = WordNetLemmatizer()
|
| 31 |
|
| 32 |
+
# ------------------------------
|
| 33 |
+
# 2. Load model and vectorizer
|
| 34 |
+
# ------------------------------
|
| 35 |
+
logistic_regression_model = joblib.load('logistic_regression_bow.pkl') # ensure this is the TF‑IDF model
|
| 36 |
tfidf_vectorizer = joblib.load('vectorizer_tfidf.pkl')
|
| 37 |
|
| 38 |
+
# Get all feature names (unigrams + possible n‑grams)
|
| 39 |
feature_names = np.array(tfidf_vectorizer.get_feature_names_out())
|
| 40 |
|
| 41 |
+
# ------------------------------
|
| 42 |
# 3. Label mapping
|
| 43 |
+
# ------------------------------
|
| 44 |
label_mapping = {
|
| 45 |
0: 'sadness',
|
| 46 |
1: 'joy',
|
|
|
|
| 50 |
5: 'surprise'
|
| 51 |
}
|
| 52 |
|
| 53 |
+
# ------------------------------
|
| 54 |
+
# 4. Text cleaning (identical to training)
|
| 55 |
+
# ------------------------------
|
| 56 |
def basic_cleaning(text):
|
| 57 |
text = re.sub(r'http\S+', '', text)
|
| 58 |
+
text = re.sub(r'[^a-zA-Z\s]', '', text) # removes punctuation and digits
|
| 59 |
text = re.sub(r'\w*\d\w*', '', text)
|
| 60 |
text = re.sub(r'<.*?>', '', text)
|
| 61 |
text = text.lower()
|
|
|
|
| 69 |
tokens = [lemmatizer.lemmatize(token) for token in tokens]
|
| 70 |
return ' '.join(tokens)
|
| 71 |
|
| 72 |
+
# ------------------------------
|
| 73 |
+
# 5. Prediction + interpretation
|
| 74 |
+
# ------------------------------
|
| 75 |
@spaces.GPU
|
| 76 |
+
def predict_with_interpretation(text):
|
| 77 |
if not text.strip():
|
| 78 |
+
return "Unknown", [], ""
|
| 79 |
+
|
| 80 |
cleaned_text = fully_cleaned(text)
|
| 81 |
text_tfidf = tfidf_vectorizer.transform([cleaned_text])
|
| 82 |
+
|
| 83 |
+
# Prediction
|
| 84 |
+
pred_idx = logistic_regression_model.predict(text_tfidf)[0]
|
| 85 |
+
emotion = label_mapping.get(pred_idx, "Unknown")
|
| 86 |
+
|
| 87 |
+
# Get coefficients for the predicted class
|
| 88 |
+
coefs = logistic_regression_model.coef_[pred_idx]
|
| 89 |
+
|
| 90 |
+
# Find which features (words) are present in the input
|
| 91 |
+
_, indices = text_tfidf.nonzero()
|
| 92 |
+
present_features = [(feature_names[i], coefs[i]) for i in indices if coefs[i] > 0]
|
| 93 |
+
# Sort by weight descending
|
| 94 |
+
present_features.sort(key=lambda x: x[1], reverse=True)
|
| 95 |
+
|
| 96 |
+
# Build highlighted text with original words
|
| 97 |
+
# We'll tokenize the original text by splitting on spaces, but keep punctuation
|
| 98 |
+
original_words = text.split()
|
| 99 |
+
highlighted = []
|
| 100 |
+
for word in original_words:
|
| 101 |
+
# Clean the word exactly as in training (but without removing stopwords)
|
| 102 |
+
clean_word = lemmatizer.lemmatize(basic_cleaning(word).strip())
|
| 103 |
+
# Check if this clean version exists in our present_features
|
| 104 |
+
match = next((w for w, wt in present_features if w == clean_word), None)
|
| 105 |
+
if match:
|
| 106 |
+
# Important: show the ORIGINAL word, but colour it
|
| 107 |
+
highlighted.append((word, emotion))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
else:
|
| 109 |
+
highlighted.append((word, None))
|
| 110 |
+
|
| 111 |
+
# Prepare a readable table of words and weights
|
| 112 |
+
if present_features:
|
| 113 |
+
weight_df = pd.DataFrame(present_features, columns=["Word", "Weight"])
|
| 114 |
+
weight_str = weight_df.to_string(index=False)
|
| 115 |
+
else:
|
| 116 |
+
weight_str = "No positive contributing words found."
|
| 117 |
+
|
| 118 |
+
return emotion, highlighted, weight_str
|
| 119 |
+
|
| 120 |
+
# ------------------------------
|
| 121 |
+
# 6. Gradio interface
|
| 122 |
+
# ------------------------------
|
| 123 |
+
with gr.Blocks(title="Emotion Classifier with Interpretation") as demo:
|
| 124 |
+
gr.Markdown("# Emotion Classifier with Word‑level Interpretation")
|
| 125 |
+
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).")
|
| 126 |
+
|
| 127 |
with gr.Row():
|
| 128 |
with gr.Column():
|
| 129 |
+
input_text = gr.Textbox(lines=5, placeholder="Type your sentence here...", label="Input")
|
| 130 |
+
submit_btn = gr.Button("Classify")
|
|
|
|
| 131 |
with gr.Column():
|
| 132 |
+
output_emotion = gr.Textbox(label="Predicted Emotion")
|
| 133 |
output_highlights = gr.HighlightedText(
|
| 134 |
+
label="Word Contributions (coloured = positive influence)",
|
| 135 |
combine_adjacent=False,
|
| 136 |
show_legend=True
|
| 137 |
)
|
| 138 |
+
output_weights = gr.Textbox(label="Word Weights (sorted)", lines=8)
|
| 139 |
+
|
| 140 |
submit_btn.click(
|
| 141 |
+
fn=predict_with_interpretation,
|
| 142 |
inputs=input_text,
|
| 143 |
+
outputs=[output_emotion, output_highlights, output_weights]
|
| 144 |
)
|
| 145 |
|
| 146 |
+
# ------------------------------
|
| 147 |
+
# 7. Launch
|
| 148 |
+
# ------------------------------
|
| 149 |
if __name__ == "__main__":
|
| 150 |
demo.launch()
|