Upload folder using huggingface_hub
Browse files- .cache_ggshield +1 -0
- README.md +3 -9
- app.py +181 -0
- best_bert_finetuned_fold_4.bin +3 -0
- best_mlp_combined_features_ZuCo.bin +3 -0
- requirements.txt +17 -0
- scaler_mlp_discrete.joblib +3 -0
- zuco-cognitive-analysis/.gitattributes +35 -0
- zuco-cognitive-analysis/README.md +11 -0
.cache_ggshield
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"last_found_secrets": [{"name": "Hugging Face user access token - c:\\Users\\Eda AYDIN\\OneDrive\\Belgeler\\GitHub\\zuco-cognitive-analysis\\hf_token.txt", "match": "34e13d1e38bc8f71e3dabe944490cc27ddcdbb054d9490ccc5e755d81869c00c"}]}
|
README.md
CHANGED
@@ -1,12 +1,6 @@
|
|
1 |
---
|
2 |
-
title:
|
3 |
-
emoji: 🦀
|
4 |
-
colorFrom: green
|
5 |
-
colorTo: red
|
6 |
-
sdk: gradio
|
7 |
-
sdk_version: 5.38.2
|
8 |
app_file: app.py
|
9 |
-
|
|
|
10 |
---
|
11 |
-
|
12 |
-
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
|
|
1 |
---
|
2 |
+
title: zuco-cognitive-anayzer
|
|
|
|
|
|
|
|
|
|
|
3 |
app_file: app.py
|
4 |
+
sdk: gradio
|
5 |
+
sdk_version: 5.18.0
|
6 |
---
|
|
|
|
app.py
ADDED
@@ -0,0 +1,181 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
TOKENIZER = BertTokenizerFast.from_pretrained(FINETUNE_MODEL_NAME)
|
51 |
+
|
52 |
+
bert_for_seq_clf = BertForSequenceClassification.from_pretrained(FINETUNE_MODEL_NAME, num_labels=2)
|
53 |
+
# NOTE: Ensure you have the correct file for the best BERT model. The user provided 'fold_4'.
|
54 |
+
bert_for_seq_clf.load_state_dict(torch.load("best_bert_finetuned_fold_4.bin", map_location=DEVICE))
|
55 |
+
BERT_EMBEDDING_MODEL = bert_for_seq_clf.bert.to(DEVICE).eval()
|
56 |
+
|
57 |
+
INPUT_DIM_MLP = 768 + 19
|
58 |
+
MLP_MODEL = AdvancedMLP(input_dim=INPUT_DIM_MLP).to(DEVICE)
|
59 |
+
MLP_MODEL.load_state_dict(torch.load("best_mlp_combined_features_ZuCo.bin", map_location=DEVICE))
|
60 |
+
MLP_MODEL.eval()
|
61 |
+
|
62 |
+
NLP = spacy.load('en_core_web_sm', disable=['ner'])
|
63 |
+
|
64 |
+
# NOTE: Ensure this filename matches the scaler you saved.
|
65 |
+
SCALER = joblib.load('scaler_mlp_discrete.joblib')
|
66 |
+
|
67 |
+
print("All models and artifacts loaded successfully.")
|
68 |
+
|
69 |
+
except FileNotFoundError as e:
|
70 |
+
print(f"ERROR: A required file was not found: {e.name}")
|
71 |
+
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.")
|
72 |
+
exit()
|
73 |
+
|
74 |
+
# --- 2. PREPROCESSING & FEATURE ENGINEERING FUNCTIONS ---
|
75 |
+
def clean_text(text):
|
76 |
+
text = str(text).lower()
|
77 |
+
return re.sub(r'\\s+', ' ', text).strip()
|
78 |
+
|
79 |
+
# FIX 1: Pass the `nlp_model` object as an argument.
|
80 |
+
def get_discrete_features(sentence, nlp_model):
|
81 |
+
"""Calculates all 19 discrete linguistic features for a single sentence."""
|
82 |
+
features = {}
|
83 |
+
|
84 |
+
# ... (rest of the feature calculation is correct)
|
85 |
+
features['char_count'] = len(sentence)
|
86 |
+
words = sentence.split()
|
87 |
+
features['word_count'] = len(words)
|
88 |
+
features['avg_word_length'] = features['char_count'] / features['word_count'] if features['word_count'] > 0 else 0
|
89 |
+
features['flesch_ease'] = textstat.flesch_reading_ease(sentence)
|
90 |
+
features['flesch_grade'] = textstat.flesch_kincaid_grade(sentence)
|
91 |
+
features['gunning_fog'] = textstat.gunning_fog(sentence)
|
92 |
+
tokens = word_tokenize(sentence)
|
93 |
+
features['ttr'] = len(set(tokens)) / len(tokens) if tokens else 0
|
94 |
+
features['lex_density_proxy'] = sum(1 for w in tokens if len(w) > 6) / len(tokens) if tokens else 0
|
95 |
+
|
96 |
+
# FIX 2: Use the passed `nlp_model` argument instead of the global name `NLP`.
|
97 |
+
doc = nlp_model(sentence)
|
98 |
+
dep_distances = [abs(token.i - token.head.i) for token in doc if token.head is not token]
|
99 |
+
pos_counts = doc.count_by(spacy.attrs.POS)
|
100 |
+
|
101 |
+
features['num_subord_clauses'] = sum(1 for token in doc if token.dep_ == 'mark')
|
102 |
+
features['num_conj_clauses'] = sum(1 for token in doc if token.dep_ == 'cc' and token.head.pos_ == 'VERB')
|
103 |
+
features['avg_dep_dist'] = np.mean(dep_distances) if dep_distances else 0
|
104 |
+
features['max_dep_dist'] = np.max(dep_distances) if dep_distances else 0
|
105 |
+
features['num_verbs'] = pos_counts.get(spacy.parts_of_speech.VERB, 0)
|
106 |
+
features['num_nouns'] = pos_counts.get(spacy.parts_of_speech.NOUN, 0) + pos_counts.get(spacy.parts_of_speech.PROPN, 0)
|
107 |
+
features['num_adjectives'] = pos_counts.get(spacy.parts_of_speech.ADJ, 0)
|
108 |
+
features['num_adverbs'] = pos_counts.get(spacy.parts_of_speech.ADV, 0)
|
109 |
+
features['num_prepositions'] = pos_counts.get(spacy.parts_of_speech.ADP, 0)
|
110 |
+
features['num_conjunctions'] = pos_counts.get(spacy.parts_of_speech.CCONJ, 0) + pos_counts.get(spacy.parts_of_speech.SCONJ, 0)
|
111 |
+
|
112 |
+
feature_order = [
|
113 |
+
'char_count', 'word_count', 'avg_word_length', 'ttr', 'lex_density_proxy',
|
114 |
+
'flesch_ease', 'flesch_grade', 'gunning_fog', 'num_subord_clauses',
|
115 |
+
'num_conj_clauses', 'avg_dep_dist', 'max_dep_dist', 'num_verbs',
|
116 |
+
'num_nouns', 'num_adjectives', 'num_adverbs', 'num_prepositions', 'num_conjunctions',
|
117 |
+
'ollama_llm_rating'
|
118 |
+
]
|
119 |
+
features['ollama_llm_rating'] = 3.0
|
120 |
+
return np.array([features[k] for k in feature_order]).reshape(1, -1)
|
121 |
+
|
122 |
+
def get_bert_embedding(sentence):
|
123 |
+
# ... (This function is correct, no changes needed)
|
124 |
+
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')
|
125 |
+
input_ids, attention_mask = encoded['input_ids'].to(DEVICE), encoded['attention_mask'].to(DEVICE)
|
126 |
+
with torch.no_grad():
|
127 |
+
outputs = BERT_EMBEDDING_MODEL(input_ids, attention_mask=attention_mask)
|
128 |
+
embedding = outputs.last_hidden_state[:, 0, :].cpu().numpy()
|
129 |
+
return embedding
|
130 |
+
|
131 |
+
# --- 3. THE PREDICTION FUNCTION ---
|
132 |
+
def predict_cognitive_state(sentence):
|
133 |
+
if not sentence.strip():
|
134 |
+
return {"Normal Reading (NR)": 0, "Task-Specific Reading (TSR)": 0}
|
135 |
+
|
136 |
+
cleaned = clean_text(sentence)
|
137 |
+
|
138 |
+
# FIX 3: Pass the loaded NLP model into the function.
|
139 |
+
discrete_features = get_discrete_features(cleaned, NLP)
|
140 |
+
|
141 |
+
scaled_discrete_features = SCALER.transform(discrete_features)
|
142 |
+
bert_embedding = get_bert_embedding(cleaned)
|
143 |
+
combined_features = np.concatenate((bert_embedding, scaled_discrete_features), axis=1)
|
144 |
+
|
145 |
+
features_tensor = torch.tensor(combined_features, dtype=torch.float32).to(DEVICE)
|
146 |
+
with torch.no_grad():
|
147 |
+
logits = MLP_MODEL(features_tensor)
|
148 |
+
probabilities = torch.softmax(logits, dim=1).cpu().numpy()[0]
|
149 |
+
|
150 |
+
labels = ["Normal Reading (NR)", "Task-Specific Reading (TSR)"]
|
151 |
+
confidences = {label: float(prob) for label, prob in zip(labels, probabilities)}
|
152 |
+
|
153 |
+
return confidences
|
154 |
+
|
155 |
+
# --- 4. GRADIO INTERFACE ---
|
156 |
+
title = "🧠 Cognitive State Analysis from Text"
|
157 |
+
description = (
|
158 |
+
"Enter a sentence to predict its cognitive state. This demo uses a fine-tuned BERT model for semantic "
|
159 |
+
"embeddings combined with 19 discrete linguistic features, fed into a Multi-Layer Perceptron (MLP) "
|
160 |
+
"to classify text as either 'Normal Reading (NR)' or 'Task-Specific Reading (TSR)' based on the ZuCo dataset."
|
161 |
+
)
|
162 |
+
example_list = [
|
163 |
+
["Through his son Timothy Bush, Jr., who was also a blacksmith, descended two American Presidents -George H. W. Bush and George W. Bush."],
|
164 |
+
["He received his bachelor's degree in 1965 and master's degree in political science in 1966 both from the University of Wyoming."],
|
165 |
+
["What does the abbreviation Ph.D. stand for?"],
|
166 |
+
["What is the name of the director of the 2003 American film 'The Haunted Mansion'?"],
|
167 |
+
]
|
168 |
+
|
169 |
+
demo = gr.Interface(
|
170 |
+
fn=predict_cognitive_state,
|
171 |
+
inputs=gr.Textbox(lines=3, label="Input Sentence", placeholder="Type a sentence here..."),
|
172 |
+
outputs=gr.Label(num_top_classes=2, label="Prediction"),
|
173 |
+
title=title,
|
174 |
+
description=description,
|
175 |
+
examples=example_list,
|
176 |
+
allow_flagging="never"
|
177 |
+
)
|
178 |
+
|
179 |
+
if __name__ == "__main__":
|
180 |
+
# FIX 4: Corrected the typo from Launch to launch (lowercase 'l').
|
181 |
+
demo.launch(debug=True)
|
best_bert_finetuned_fold_4.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:c03bb18d973a176c60afc90b779c5182cbbec3c84d45f7a37a068d75e7d80a78
|
3 |
+
size 438020695
|
best_mlp_combined_features_ZuCo.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:b8064f0cea8b4aa252bcfb8625f2f9dc5d505a22f4902dbf6d142f7c8e46e34f
|
3 |
+
size 1893958
|
requirements.txt
ADDED
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# --- Core Libraries ---
|
2 |
+
torch
|
3 |
+
transformers
|
4 |
+
gradio
|
5 |
+
numpy
|
6 |
+
pandas
|
7 |
+
textstat
|
8 |
+
nltk
|
9 |
+
joblib
|
10 |
+
scikit-learn
|
11 |
+
sentence-transformers
|
12 |
+
|
13 |
+
# --- SpaCy Library ---
|
14 |
+
spacy==3.7.2
|
15 |
+
|
16 |
+
# --- SpaCy Model (installed as a package via direct link) ---
|
17 |
+
https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-3.7.1/en_core_web_sm-3.7.1-py3-none-any.whl
|
scaler_mlp_discrete.joblib
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:fb6563832a53d4b3b13ec487f60580883feea9d71605a98d18f4d2f355d5bc0e
|
3 |
+
size 1599
|
zuco-cognitive-analysis/.gitattributes
ADDED
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
3 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
4 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
5 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
6 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
7 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
8 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
9 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
10 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
11 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
12 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
13 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
14 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
15 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
16 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
17 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
18 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
19 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
20 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
21 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
22 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
23 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
24 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
25 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
26 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
27 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
28 |
+
*.tar filter=lfs diff=lfs merge=lfs -text
|
29 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
30 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
31 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
32 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
33 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
zuco-cognitive-analysis/README.md
ADDED
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
title: Zuco Cognitive Analysis
|
3 |
+
emoji: 🦀
|
4 |
+
colorFrom: indigo
|
5 |
+
colorTo: green
|
6 |
+
sdk: docker
|
7 |
+
pinned: false
|
8 |
+
license: apache-2.0
|
9 |
+
---
|
10 |
+
|
11 |
+
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|