Update app.py
Browse files
app.py
CHANGED
|
@@ -1,181 +1,182 @@
|
|
| 1 |
-
# app.py
|
| 2 |
-
import gradio as gr
|
| 3 |
-
import torch
|
| 4 |
-
import torch.nn as nn
|
| 5 |
-
import numpy as np
|
| 6 |
-
import pandas as pd
|
| 7 |
-
import spacy
|
| 8 |
-
import textstat
|
| 9 |
-
from nltk.tokenize import word_tokenize
|
| 10 |
-
import nltk
|
| 11 |
-
import re
|
| 12 |
-
import joblib
|
| 13 |
-
from transformers import BertTokenizerFast, BertForSequenceClassification
|
| 14 |
-
from sentence_transformers import SentenceTransformer
|
| 15 |
-
|
| 16 |
-
# --- 1. SETUP: Constants and Model Loading ---
|
| 17 |
-
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 18 |
-
FINETUNE_MODEL_NAME = 'bert-base-uncased'
|
| 19 |
-
MAX_LEN_BERT = 128
|
| 20 |
-
print(f"Using device: {DEVICE}")
|
| 21 |
-
NLP = spacy.load('en_core_web_sm', disable=['ner'])
|
| 22 |
-
SCALER = joblib.load('scaler_mlp_discrete.joblib')
|
| 23 |
-
|
| 24 |
-
# --- (Re)Define the PyTorch MLP Model Class ---
|
| 25 |
-
class AdvancedMLP(nn.Module):
|
| 26 |
-
# ... (This class is correct, no changes needed)
|
| 27 |
-
def __init__(self, input_dim, num_classes=2):
|
| 28 |
-
super(AdvancedMLP, self).__init__()
|
| 29 |
-
self.layer_1 = nn.Linear(input_dim, 512)
|
| 30 |
-
self.relu1 = nn.ReLU()
|
| 31 |
-
self.batchnorm1 = nn.BatchNorm1d(512)
|
| 32 |
-
self.dropout1 = nn.Dropout(0.3)
|
| 33 |
-
self.layer_2 = nn.Linear(512, 128)
|
| 34 |
-
self.relu2 = nn.ReLU()
|
| 35 |
-
self.batchnorm2 = nn.BatchNorm1d(128)
|
| 36 |
-
self.dropout2 = nn.Dropout(0.3)
|
| 37 |
-
self.output_layer = nn.Linear(128, num_classes)
|
| 38 |
-
|
| 39 |
-
def forward(self, x):
|
| 40 |
-
x = self.layer_1(x); x = self.relu1(x); x = self.batchnorm1(x); x = self.dropout1(x)
|
| 41 |
-
x = self.layer_2(x); x = self.relu2(x); x = self.batchnorm2(x); x = self.dropout2(x)
|
| 42 |
-
x = self.output_layer(x)
|
| 43 |
-
return x
|
| 44 |
-
|
| 45 |
-
# --- Load All Models and Artifacts ---
|
| 46 |
-
print("Loading models and artifacts...")
|
| 47 |
-
try:
|
| 48 |
-
nltk.download('punkt', quiet=True)
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
MLP_MODEL
|
| 60 |
-
MLP_MODEL.
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
print("
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
features
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
features['
|
| 89 |
-
features['
|
| 90 |
-
features['
|
| 91 |
-
features['
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
features['
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
features['
|
| 103 |
-
features['
|
| 104 |
-
features['
|
| 105 |
-
features['
|
| 106 |
-
features['
|
| 107 |
-
features['
|
| 108 |
-
features['
|
| 109 |
-
features['
|
| 110 |
-
features['
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
'
|
| 115 |
-
'
|
| 116 |
-
'
|
| 117 |
-
'
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
"
|
| 160 |
-
"
|
| 161 |
-
)
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
["
|
| 165 |
-
["
|
| 166 |
-
["What
|
| 167 |
-
]
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
|
|
|
| 181 |
demo.launch(debug=True)
|
|
|
|
| 1 |
+
# app.py
|
| 2 |
+
import gradio as gr
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn as nn
|
| 5 |
+
import numpy as np
|
| 6 |
+
import pandas as pd
|
| 7 |
+
import spacy
|
| 8 |
+
import textstat
|
| 9 |
+
from nltk.tokenize import word_tokenize
|
| 10 |
+
import nltk
|
| 11 |
+
import re
|
| 12 |
+
import joblib
|
| 13 |
+
from transformers import BertTokenizerFast, BertForSequenceClassification
|
| 14 |
+
from sentence_transformers import SentenceTransformer
|
| 15 |
+
|
| 16 |
+
# --- 1. SETUP: Constants and Model Loading ---
|
| 17 |
+
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 18 |
+
FINETUNE_MODEL_NAME = 'bert-base-uncased'
|
| 19 |
+
MAX_LEN_BERT = 128
|
| 20 |
+
print(f"Using device: {DEVICE}")
|
| 21 |
+
NLP = spacy.load('en_core_web_sm', disable=['ner'])
|
| 22 |
+
SCALER = joblib.load('scaler_mlp_discrete.joblib')
|
| 23 |
+
|
| 24 |
+
# --- (Re)Define the PyTorch MLP Model Class ---
|
| 25 |
+
class AdvancedMLP(nn.Module):
|
| 26 |
+
# ... (This class is correct, no changes needed)
|
| 27 |
+
def __init__(self, input_dim, num_classes=2):
|
| 28 |
+
super(AdvancedMLP, self).__init__()
|
| 29 |
+
self.layer_1 = nn.Linear(input_dim, 512)
|
| 30 |
+
self.relu1 = nn.ReLU()
|
| 31 |
+
self.batchnorm1 = nn.BatchNorm1d(512)
|
| 32 |
+
self.dropout1 = nn.Dropout(0.3)
|
| 33 |
+
self.layer_2 = nn.Linear(512, 128)
|
| 34 |
+
self.relu2 = nn.ReLU()
|
| 35 |
+
self.batchnorm2 = nn.BatchNorm1d(128)
|
| 36 |
+
self.dropout2 = nn.Dropout(0.3)
|
| 37 |
+
self.output_layer = nn.Linear(128, num_classes)
|
| 38 |
+
|
| 39 |
+
def forward(self, x):
|
| 40 |
+
x = self.layer_1(x); x = self.relu1(x); x = self.batchnorm1(x); x = self.dropout1(x)
|
| 41 |
+
x = self.layer_2(x); x = self.relu2(x); x = self.batchnorm2(x); x = self.dropout2(x)
|
| 42 |
+
x = self.output_layer(x)
|
| 43 |
+
return x
|
| 44 |
+
|
| 45 |
+
# --- Load All Models and Artifacts ---
|
| 46 |
+
print("Loading models and artifacts...")
|
| 47 |
+
try:
|
| 48 |
+
nltk.download('punkt', quiet=True)
|
| 49 |
+
nltk.download('punkt_tab', quiet=True)
|
| 50 |
+
|
| 51 |
+
TOKENIZER = BertTokenizerFast.from_pretrained(FINETUNE_MODEL_NAME)
|
| 52 |
+
|
| 53 |
+
bert_for_seq_clf = BertForSequenceClassification.from_pretrained(FINETUNE_MODEL_NAME, num_labels=2)
|
| 54 |
+
# NOTE: Ensure you have the correct file for the best BERT model. The user provided 'fold_4'.
|
| 55 |
+
bert_for_seq_clf.load_state_dict(torch.load("best_bert_finetuned_fold_4.bin", map_location=DEVICE))
|
| 56 |
+
BERT_EMBEDDING_MODEL = bert_for_seq_clf.bert.to(DEVICE).eval()
|
| 57 |
+
|
| 58 |
+
INPUT_DIM_MLP = 768 + 19
|
| 59 |
+
MLP_MODEL = AdvancedMLP(input_dim=INPUT_DIM_MLP).to(DEVICE)
|
| 60 |
+
MLP_MODEL.load_state_dict(torch.load("best_mlp_combined_features_ZuCo.bin", map_location=DEVICE))
|
| 61 |
+
MLP_MODEL.eval()
|
| 62 |
+
|
| 63 |
+
NLP = spacy.load('en_core_web_sm', disable=['ner'])
|
| 64 |
+
|
| 65 |
+
# NOTE: Ensure this filename matches the scaler you saved.
|
| 66 |
+
SCALER = joblib.load('scaler_mlp_discrete.joblib')
|
| 67 |
+
|
| 68 |
+
print("All models and artifacts loaded successfully.")
|
| 69 |
+
|
| 70 |
+
except FileNotFoundError as e:
|
| 71 |
+
print(f"ERROR: A required file was not found: {e.name}")
|
| 72 |
+
print("Please ensure 'best_bert_finetuned_fold_4.bin', 'best_mlp_combined_features_ZuCo.bin', and 'scaler_mlp_discrete.joblib' are in the same directory.")
|
| 73 |
+
exit()
|
| 74 |
+
|
| 75 |
+
# --- 2. PREPROCESSING & FEATURE ENGINEERING FUNCTIONS ---
|
| 76 |
+
def clean_text(text):
|
| 77 |
+
text = str(text).lower()
|
| 78 |
+
return re.sub(r'\\s+', ' ', text).strip()
|
| 79 |
+
|
| 80 |
+
# FIX 1: Pass the `nlp_model` object as an argument.
|
| 81 |
+
def get_discrete_features(sentence, nlp_model):
|
| 82 |
+
"""Calculates all 19 discrete linguistic features for a single sentence."""
|
| 83 |
+
features = {}
|
| 84 |
+
|
| 85 |
+
# ... (rest of the feature calculation is correct)
|
| 86 |
+
features['char_count'] = len(sentence)
|
| 87 |
+
words = sentence.split()
|
| 88 |
+
features['word_count'] = len(words)
|
| 89 |
+
features['avg_word_length'] = features['char_count'] / features['word_count'] if features['word_count'] > 0 else 0
|
| 90 |
+
features['flesch_ease'] = textstat.flesch_reading_ease(sentence)
|
| 91 |
+
features['flesch_grade'] = textstat.flesch_kincaid_grade(sentence)
|
| 92 |
+
features['gunning_fog'] = textstat.gunning_fog(sentence)
|
| 93 |
+
tokens = word_tokenize(sentence)
|
| 94 |
+
features['ttr'] = len(set(tokens)) / len(tokens) if tokens else 0
|
| 95 |
+
features['lex_density_proxy'] = sum(1 for w in tokens if len(w) > 6) / len(tokens) if tokens else 0
|
| 96 |
+
|
| 97 |
+
# FIX 2: Use the passed `nlp_model` argument instead of the global name `NLP`.
|
| 98 |
+
doc = nlp_model(sentence)
|
| 99 |
+
dep_distances = [abs(token.i - token.head.i) for token in doc if token.head is not token]
|
| 100 |
+
pos_counts = doc.count_by(spacy.attrs.POS)
|
| 101 |
+
|
| 102 |
+
features['num_subord_clauses'] = sum(1 for token in doc if token.dep_ == 'mark')
|
| 103 |
+
features['num_conj_clauses'] = sum(1 for token in doc if token.dep_ == 'cc' and token.head.pos_ == 'VERB')
|
| 104 |
+
features['avg_dep_dist'] = np.mean(dep_distances) if dep_distances else 0
|
| 105 |
+
features['max_dep_dist'] = np.max(dep_distances) if dep_distances else 0
|
| 106 |
+
features['num_verbs'] = pos_counts.get(spacy.parts_of_speech.VERB, 0)
|
| 107 |
+
features['num_nouns'] = pos_counts.get(spacy.parts_of_speech.NOUN, 0) + pos_counts.get(spacy.parts_of_speech.PROPN, 0)
|
| 108 |
+
features['num_adjectives'] = pos_counts.get(spacy.parts_of_speech.ADJ, 0)
|
| 109 |
+
features['num_adverbs'] = pos_counts.get(spacy.parts_of_speech.ADV, 0)
|
| 110 |
+
features['num_prepositions'] = pos_counts.get(spacy.parts_of_speech.ADP, 0)
|
| 111 |
+
features['num_conjunctions'] = pos_counts.get(spacy.parts_of_speech.CCONJ, 0) + pos_counts.get(spacy.parts_of_speech.SCONJ, 0)
|
| 112 |
+
|
| 113 |
+
feature_order = [
|
| 114 |
+
'char_count', 'word_count', 'avg_word_length', 'ttr', 'lex_density_proxy',
|
| 115 |
+
'flesch_ease', 'flesch_grade', 'gunning_fog', 'num_subord_clauses',
|
| 116 |
+
'num_conj_clauses', 'avg_dep_dist', 'max_dep_dist', 'num_verbs',
|
| 117 |
+
'num_nouns', 'num_adjectives', 'num_adverbs', 'num_prepositions', 'num_conjunctions',
|
| 118 |
+
'ollama_llm_rating'
|
| 119 |
+
]
|
| 120 |
+
features['ollama_llm_rating'] = 3.0
|
| 121 |
+
return np.array([features[k] for k in feature_order]).reshape(1, -1)
|
| 122 |
+
|
| 123 |
+
def get_bert_embedding(sentence):
|
| 124 |
+
# ... (This function is correct, no changes needed)
|
| 125 |
+
encoded = TOKENIZER.encode_plus(sentence, add_special_tokens=True, max_length=MAX_LEN_BERT, return_token_type_ids=False, padding='max_length', truncation=True, return_attention_mask=True, return_tensors='pt')
|
| 126 |
+
input_ids, attention_mask = encoded['input_ids'].to(DEVICE), encoded['attention_mask'].to(DEVICE)
|
| 127 |
+
with torch.no_grad():
|
| 128 |
+
outputs = BERT_EMBEDDING_MODEL(input_ids, attention_mask=attention_mask)
|
| 129 |
+
embedding = outputs.last_hidden_state[:, 0, :].cpu().numpy()
|
| 130 |
+
return embedding
|
| 131 |
+
|
| 132 |
+
# --- 3. THE PREDICTION FUNCTION ---
|
| 133 |
+
def predict_cognitive_state(sentence):
|
| 134 |
+
if not sentence.strip():
|
| 135 |
+
return {"Normal Reading (NR)": 0, "Task-Specific Reading (TSR)": 0}
|
| 136 |
+
|
| 137 |
+
cleaned = clean_text(sentence)
|
| 138 |
+
|
| 139 |
+
# FIX 3: Pass the loaded NLP model into the function.
|
| 140 |
+
discrete_features = get_discrete_features(cleaned, NLP)
|
| 141 |
+
|
| 142 |
+
scaled_discrete_features = SCALER.transform(discrete_features)
|
| 143 |
+
bert_embedding = get_bert_embedding(cleaned)
|
| 144 |
+
combined_features = np.concatenate((bert_embedding, scaled_discrete_features), axis=1)
|
| 145 |
+
|
| 146 |
+
features_tensor = torch.tensor(combined_features, dtype=torch.float32).to(DEVICE)
|
| 147 |
+
with torch.no_grad():
|
| 148 |
+
logits = MLP_MODEL(features_tensor)
|
| 149 |
+
probabilities = torch.softmax(logits, dim=1).cpu().numpy()[0]
|
| 150 |
+
|
| 151 |
+
labels = ["Normal Reading (NR)", "Task-Specific Reading (TSR)"]
|
| 152 |
+
confidences = {label: float(prob) for label, prob in zip(labels, probabilities)}
|
| 153 |
+
|
| 154 |
+
return confidences
|
| 155 |
+
|
| 156 |
+
# --- 4. GRADIO INTERFACE ---
|
| 157 |
+
title = "🧠 Cognitive State Analysis from Text"
|
| 158 |
+
description = (
|
| 159 |
+
"Enter a sentence to predict its cognitive state. This demo uses a fine-tuned BERT model for semantic "
|
| 160 |
+
"embeddings combined with 19 discrete linguistic features, fed into a Multi-Layer Perceptron (MLP) "
|
| 161 |
+
"to classify text as either 'Normal Reading (NR)' or 'Task-Specific Reading (TSR)' based on the ZuCo dataset."
|
| 162 |
+
)
|
| 163 |
+
example_list = [
|
| 164 |
+
["Through his son Timothy Bush, Jr., who was also a blacksmith, descended two American Presidents -George H. W. Bush and George W. Bush."],
|
| 165 |
+
["He received his bachelor's degree in 1965 and master's degree in political science in 1966 both from the University of Wyoming."],
|
| 166 |
+
["What does the abbreviation Ph.D. stand for?"],
|
| 167 |
+
["What is the name of the director of the 2003 American film 'The Haunted Mansion'?"],
|
| 168 |
+
]
|
| 169 |
+
|
| 170 |
+
demo = gr.Interface(
|
| 171 |
+
fn=predict_cognitive_state,
|
| 172 |
+
inputs=gr.Textbox(lines=3, label="Input Sentence", placeholder="Type a sentence here..."),
|
| 173 |
+
outputs=gr.Label(num_top_classes=2, label="Prediction"),
|
| 174 |
+
title=title,
|
| 175 |
+
description=description,
|
| 176 |
+
examples=example_list,
|
| 177 |
+
allow_flagging="never"
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
if __name__ == "__main__":
|
| 181 |
+
# FIX 4: Corrected the typo from Launch to launch (lowercase 'l').
|
| 182 |
demo.launch(debug=True)
|