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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
detector.py - core engine for SentimentDetector (no UI code).
|
| 3 |
+
|
| 4 |
+
Pipeline, per sentence
|
| 5 |
+
1. RoBERTa sentiment model on the raw sentence -> literal polarity (pos - neg)
|
| 6 |
+
2. Same model on the emoji-stripped sentence -> text-only polarity (isolates emoji effect)
|
| 7 |
+
3. Emoji / emoticon lexicon -> emoji valence, blended into (1)
|
| 8 |
+
4. RoBERTa irony model -> irony probability
|
| 9 |
+
5. Rule cues (phrases, typography, text-vs-emoji) -> cue score
|
| 10 |
+
6. Noisy-OR fusion of (4) and (5) -> sarcasm probability
|
| 11 |
+
7. Polarity inversion when sarcastic -> intended polarity
|
| 12 |
+
8. RoBERTa emotion model -> anger / joy / optimism / sadness
|
| 13 |
+
Sentences are then aggregated into a per-author profile (recency-weighted mood,
|
| 14 |
+
trend, volatility, sarcasm rate, dominant emotion).
|
| 15 |
+
"""
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
import re
|
| 19 |
+
from dataclasses import dataclass
|
| 20 |
+
from typing import Dict, List, Optional, Tuple
|
| 21 |
+
|
| 22 |
+
import emoji
|
| 23 |
+
import numpy as np
|
| 24 |
+
import torch
|
| 25 |
+
from transformers import AutoModelForSequenceClassification, AutoTokenizer
|
| 26 |
+
|
| 27 |
+
# --------------------------------------------------------------------------- config
|
| 28 |
+
MODELS = {
|
| 29 |
+
"sentiment": ("cardiffnlp/twitter-roberta-base-sentiment-latest", ["negative", "neutral", "positive"]),
|
| 30 |
+
"irony": ("cardiffnlp/twitter-roberta-base-irony", ["non_irony", "irony"]),
|
| 31 |
+
"emotion": ("cardiffnlp/twitter-roberta-base-emotion", ["anger", "joy", "optimism", "sadness"]),
|
| 32 |
+
}
|
| 33 |
+
SARCASM_THRESHOLD = 0.55 # sarcasm probability above which polarity is inverted
|
| 34 |
+
LABEL_THRESHOLD = 0.25 # |score| below this is "neutral"
|
| 35 |
+
MAX_SENTENCES = 60
|
| 36 |
+
MAX_EXPLAIN_WORDS = 40
|
| 37 |
+
RECENCY_HALF_LIFE = 4 # sentences; recent sentences count more towards "current mood"
|
| 38 |
+
|
| 39 |
+
# --------------------------------------------------------------------------- lexicons
|
| 40 |
+
# Emoji valence in [-1, 1]. Keys have variation selectors / skin tones removed.
|
| 41 |
+
EMOJI_VALENCE: Dict[str, float] = {
|
| 42 |
+
"😀": .7, "😃": .7, "😄": .8, "😁": .7, "😊": .8, "🙂": .3, "😍": .9, "🥰": .9, "😘": .7,
|
| 43 |
+
"😂": .6, "🤣": .6, "😎": .6, "🎉": .8, "🎊": .8, "👍": .6, "👏": .7, "❤": .9, "💖": .8,
|
| 44 |
+
"🔥": .6, "✨": .5, "🙏": .4, "💪": .6, "🥳": .9, "😌": .5, "🤩": .9, "😇": .6, "💯": .7,
|
| 45 |
+
"🚀": .6, "✅": .5, "🌟": .6, "😅": .2, "😉": .3, "☺": .7, "🍕": .3,
|
| 46 |
+
"😞": -.7, "😢": -.8, "😭": -.8, "😡": -.9, "🤬": -.9, "😠": -.8, "😤": -.6, "😩": -.7,
|
| 47 |
+
"😫": -.7, "😖": -.6, "😣": -.6, "😔": -.6, "💔": -.9, "👎": -.7, "😱": -.5, "😰": -.6,
|
| 48 |
+
"😨": -.6, "🤮": -.9, "🤢": -.8, "😒": -.6, "🙄": -.6, "😑": -.4, "😐": -.2, "☹": -.6,
|
| 49 |
+
"🙁": -.5, "😟": -.5, "😓": -.5, "🥺": -.2, "💀": -.2, "🤡": -.6, "❌": -.5,
|
| 50 |
+
"🙃": -.1, "😏": -.1,
|
| 51 |
+
}
|
| 52 |
+
# Emoji that commonly flag irony / eye-rolling when paired with positive words.
|
| 53 |
+
IRONIC_EMOJI = {"🙄", "😒", "🙃", "😏", "🤡", "😑"}
|
| 54 |
+
|
| 55 |
+
EMOTICON_VALENCE = {":)": .6, ":D": .8, ";)": .3, ":P": .4, ":p": .4, "XD": .6,
|
| 56 |
+
":(": -.6, ":'(": -.8, ":/": -.3, ":|": -.1, "<3": .8, "</3": -.8}
|
| 57 |
+
_EMOTICON_RE = re.compile(r"(?<![\w/])(</3|<3|:'\(|[:;]-?[)(DPp/|]|XD)(?!\w)")
|
| 58 |
+
|
| 59 |
+
_LEXICAL_CUES = [
|
| 60 |
+
(r"\byeah,?\s+(right|sure)\b", "'yeah right'"),
|
| 61 |
+
(r"\boh,?\s+(great|wonderful|fantastic|perfect|lovely|joy|brilliant)\b", "'oh great'"),
|
| 62 |
+
(r"\bjust what i (needed|wanted|ordered)\b", "'just what I needed'"),
|
| 63 |
+
(r"\bthanks a lot\b|\bthanks for nothing\b|\bthanks,? (genius|captain obvious)\b", "mock thanks"),
|
| 64 |
+
(r"\bwhat a (great|wonderful|brilliant|fantastic|lovely) (idea|day|surprise|way)\b", "'what a great ...'"),
|
| 65 |
+
(r"\b(love|adore) (how|that|it when|waiting|being)\b", "'love how ...'"),
|
| 66 |
+
(r"\bsure,? because\b|\bbecause that (always )?works\b", "'sure, because'"),
|
| 67 |
+
(r"\bas if\b", "'as if'"),
|
| 68 |
+
(r"\bsuch a (surprise|shocker)\b|\bshocker\b", "'shocker'"),
|
| 69 |
+
(r"\bnot like i('m| am) (bitter|complaining|jealous)\b", "'not like I'm bitter'"),
|
| 70 |
+
(r"\b(great|wonderful|fantastic|perfect|brilliant)\b[,.!]?\s+(another|more|now)\b", "positive word + 'another'"),
|
| 71 |
+
(r"\btruly living the dream\b|\bliving the dream\b", "'living the dream'"),
|
| 72 |
+
(r"(^|\s)/s\b", "'/s' tag"),
|
| 73 |
+
]
|
| 74 |
+
_TYPO_CUES = [
|
| 75 |
+
(r"\.{3,}|…", "ellipsis"),
|
| 76 |
+
(r"\b(?:[a-z][A-Z]){2,}[a-z]?\b", "aLtErNaTiNg case"),
|
| 77 |
+
(r"[\"“](great|nice|helpful|smart|genius|wonderful|perfect|amazing|good)[\"”]", "scare-quoted praise"),
|
| 78 |
+
(r"\b[A-Z]{3,}\b", "ALL-CAPS emphasis"),
|
| 79 |
+
(r"(\w)\1{2,}", "letter elongation"),
|
| 80 |
+
(r"!{3,}", "repeated !"),
|
| 81 |
+
]
|
| 82 |
+
LEXICAL_CUES = [(re.compile(p, re.I), n) for p, n in _LEXICAL_CUES]
|
| 83 |
+
TYPO_CUES = [(re.compile(p), n) for p, n in _TYPO_CUES]
|
| 84 |
+
|
| 85 |
+
_SKIN_VS = re.compile("[\U0001F3FB-\U0001F3FF\uFE0F\u200D]")
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
# --------------------------------------------------------------------------- text utils
|
| 89 |
+
def preprocess(text: str) -> str:
|
| 90 |
+
"""Normalise @mentions and URLs the way the Cardiff models were trained."""
|
| 91 |
+
text = re.sub(r"@\w+", "@user", text)
|
| 92 |
+
text = re.sub(r"https?://\S+", "http", text)
|
| 93 |
+
return text.strip()
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def strip_emoji(text: str) -> str:
|
| 97 |
+
return re.sub(r"\s{2,}", " ", emoji.replace_emoji(text, replace="")).strip()
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def norm_emoji(e: str) -> str:
|
| 101 |
+
return _SKIN_VS.sub("", e)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def split_sentences(text: str) -> List[str]:
|
| 105 |
+
"""Regex splitter; emoji/punctuation-only fragments are glued to the previous sentence."""
|
| 106 |
+
parts: List[str] = []
|
| 107 |
+
for line in re.split(r"\n+", text.strip()):
|
| 108 |
+
parts += re.split(r"(?<=[.!?…])\s+", line.strip())
|
| 109 |
+
merged: List[str] = []
|
| 110 |
+
for p in parts:
|
| 111 |
+
p = p.strip()
|
| 112 |
+
if not p:
|
| 113 |
+
continue
|
| 114 |
+
if merged: # "…needed... 🙄 Whatever" -> the 🙄 belongs to the previous sentence
|
| 115 |
+
lead, pos = "", 0
|
| 116 |
+
for m in emoji.emoji_list(p):
|
| 117 |
+
if p[pos:m["match_start"]].strip() == "":
|
| 118 |
+
lead += m["emoji"]
|
| 119 |
+
pos = m["match_end"]
|
| 120 |
+
else:
|
| 121 |
+
break
|
| 122 |
+
if lead:
|
| 123 |
+
merged[-1] += " " + lead
|
| 124 |
+
p = p[pos:].strip()
|
| 125 |
+
if not p:
|
| 126 |
+
continue
|
| 127 |
+
if merged and not re.search(r"[A-Za-z0-9]", strip_emoji(p)):
|
| 128 |
+
merged[-1] += " " + p
|
| 129 |
+
else:
|
| 130 |
+
merged.append(p)
|
| 131 |
+
return merged[:MAX_SENTENCES]
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def emoji_signal(text: str) -> Tuple[List[str], List[float]]:
|
| 135 |
+
"""Return (emoji/emoticon symbols found, their valences)."""
|
| 136 |
+
symbols, vals = [], []
|
| 137 |
+
for m in emoji.emoji_list(text):
|
| 138 |
+
e = m["emoji"]
|
| 139 |
+
symbols.append(e)
|
| 140 |
+
v = EMOJI_VALENCE.get(norm_emoji(e))
|
| 141 |
+
if v is not None:
|
| 142 |
+
vals.append(v)
|
| 143 |
+
for m in _EMOTICON_RE.finditer(re.sub(r"https?://\S+", "", text)):
|
| 144 |
+
tok = m.group(1).replace("-", "")
|
| 145 |
+
if tok in EMOTICON_VALENCE:
|
| 146 |
+
symbols.append(m.group(1))
|
| 147 |
+
vals.append(EMOTICON_VALENCE[tok])
|
| 148 |
+
return symbols, vals
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def detect_cues(text: str) -> Tuple[List[str], float]:
|
| 152 |
+
cues, score = [], 0.0
|
| 153 |
+
for pat, name in LEXICAL_CUES:
|
| 154 |
+
if pat.search(text):
|
| 155 |
+
cues.append(name)
|
| 156 |
+
score += 0.30
|
| 157 |
+
for pat, name in TYPO_CUES:
|
| 158 |
+
if pat.search(text):
|
| 159 |
+
cues.append(name)
|
| 160 |
+
score += 0.12
|
| 161 |
+
return cues, min(score, 1.0)
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def label_from_score(score: float) -> str:
|
| 165 |
+
if score >= LABEL_THRESHOLD:
|
| 166 |
+
return "positive"
|
| 167 |
+
if score <= -LABEL_THRESHOLD:
|
| 168 |
+
return "negative"
|
| 169 |
+
return "neutral"
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
# --------------------------------------------------------------------------- result types
|
| 173 |
+
@dataclass
|
| 174 |
+
class SentenceResult:
|
| 175 |
+
text: str
|
| 176 |
+
literal: float # what the words + emojis say on the surface
|
| 177 |
+
intended: float # after sarcasm-aware inversion
|
| 178 |
+
label: str
|
| 179 |
+
probs: Dict[str, float]
|
| 180 |
+
irony: float # raw irony-model probability
|
| 181 |
+
sarcasm: float # fused sarcasm probability
|
| 182 |
+
is_sarcastic: bool
|
| 183 |
+
emojis: List[str]
|
| 184 |
+
emoji_valence: Optional[float]
|
| 185 |
+
cues: List[str]
|
| 186 |
+
emotion: str
|
| 187 |
+
emotions: Dict[str, float]
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
@dataclass
|
| 191 |
+
class TextProfile:
|
| 192 |
+
sentences: List[SentenceResult]
|
| 193 |
+
mean: float
|
| 194 |
+
overall: float # recency-weighted "current mood"
|
| 195 |
+
overall_label: str
|
| 196 |
+
volatility: float
|
| 197 |
+
slope: float
|
| 198 |
+
trend: str
|
| 199 |
+
sarcasm_rate: float
|
| 200 |
+
sarcasm_shift: float # mean(intended - literal): how much sarcasm-awareness changed the read
|
| 201 |
+
dominant_emotion: str
|
| 202 |
+
emotion_mean: Dict[str, float]
|
| 203 |
+
emoji_count: int
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
# --------------------------------------------------------------------------- detector
|
| 207 |
+
class SentimentDetector:
|
| 208 |
+
def __init__(self, device: Optional[str] = None):
|
| 209 |
+
self.device = device or ("cuda" if torch.cuda.is_available() else "cpu")
|
| 210 |
+
self._cache: Dict[str, tuple] = {}
|
| 211 |
+
|
| 212 |
+
# ---- model plumbing
|
| 213 |
+
def _load(self, key: str):
|
| 214 |
+
if key not in self._cache:
|
| 215 |
+
name, default = MODELS[key]
|
| 216 |
+
tok = AutoTokenizer.from_pretrained(name)
|
| 217 |
+
model = AutoModelForSequenceClassification.from_pretrained(name).to(self.device).eval()
|
| 218 |
+
id2label = [str(model.config.id2label[i]).lower() for i in range(model.config.num_labels)]
|
| 219 |
+
labels = default if all(l.startswith("label_") for l in id2label) else id2label
|
| 220 |
+
self._cache[key] = (tok, model, labels)
|
| 221 |
+
return self._cache[key]
|
| 222 |
+
|
| 223 |
+
def warmup(self) -> None:
|
| 224 |
+
for k in MODELS:
|
| 225 |
+
self._load(k)
|
| 226 |
+
|
| 227 |
+
def _idx(self, key: str, label: str, fallback: int) -> int:
|
| 228 |
+
labels = self._load(key)[2]
|
| 229 |
+
return labels.index(label) if label in labels else fallback
|
| 230 |
+
|
| 231 |
+
@torch.inference_mode()
|
| 232 |
+
def _probs(self, key: str, texts: List[str], batch_size: int = 32) -> np.ndarray:
|
| 233 |
+
tok, model, _ = self._load(key)
|
| 234 |
+
out = []
|
| 235 |
+
for i in range(0, len(texts), batch_size):
|
| 236 |
+
enc = tok(texts[i:i + batch_size], padding=True, truncation=True,
|
| 237 |
+
max_length=128, return_tensors="pt").to(self.device)
|
| 238 |
+
out.append(torch.softmax(model(**enc).logits, dim=-1).cpu().numpy())
|
| 239 |
+
return np.concatenate(out) if out else np.zeros((0, 1))
|
| 240 |
+
|
| 241 |
+
# ---- convenience for evaluation scripts
|
| 242 |
+
def sentiment_probs(self, texts: List[str]) -> np.ndarray:
|
| 243 |
+
"""Baseline model only. Columns: [negative, neutral, positive]."""
|
| 244 |
+
P = self._probs("sentiment", [preprocess(t) for t in texts])
|
| 245 |
+
return P[:, [self._idx("sentiment", "negative", 0), self._idx("sentiment", "neutral", 1),
|
| 246 |
+
self._idx("sentiment", "positive", 2)]]
|
| 247 |
+
|
| 248 |
+
def irony_probs(self, texts: List[str]) -> np.ndarray:
|
| 249 |
+
"""Baseline irony model only."""
|
| 250 |
+
return self._probs("irony", [preprocess(t) for t in texts])[:, self._idx("irony", "irony", 1)]
|
| 251 |
+
|
| 252 |
+
# ---- main API
|
| 253 |
+
def analyze(self, text: str, sarcasm_aware: bool = True, emoji_aware: bool = True) -> TextProfile:
|
| 254 |
+
sentences = split_sentences(text)
|
| 255 |
+
if not sentences:
|
| 256 |
+
raise ValueError("No text to analyze.")
|
| 257 |
+
|
| 258 |
+
raw = [preprocess(s) for s in sentences]
|
| 259 |
+
stripped = [preprocess(strip_emoji(s)) or preprocess(s) for s in sentences]
|
| 260 |
+
model_in = raw if emoji_aware else stripped
|
| 261 |
+
|
| 262 |
+
P_full = self._probs("sentiment", model_in)
|
| 263 |
+
P_txt = self._probs("sentiment", stripped) if emoji_aware else P_full
|
| 264 |
+
irony = self._probs("irony", model_in)[:, self._idx("irony", "irony", 1)]
|
| 265 |
+
emo = self._probs("emotion", model_in)
|
| 266 |
+
emo_labels = self._load("emotion")[2]
|
| 267 |
+
ineg, ineu, ipos = (self._idx("sentiment", "negative", 0), self._idx("sentiment", "neutral", 1),
|
| 268 |
+
self._idx("sentiment", "positive", 2))
|
| 269 |
+
|
| 270 |
+
results: List[SentenceResult] = []
|
| 271 |
+
for i, s in enumerate(sentences):
|
| 272 |
+
neg, neu, pos = float(P_full[i][ineg]), float(P_full[i][ineu]), float(P_full[i][ipos])
|
| 273 |
+
model_score = pos - neg
|
| 274 |
+
txt_score = float(P_txt[i][ipos] - P_txt[i][ineg])
|
| 275 |
+
|
| 276 |
+
found, vals = emoji_signal(s) if emoji_aware else ([], [])
|
| 277 |
+
emo_val = float(np.mean(vals)) if vals else None
|
| 278 |
+
if emo_val is not None:
|
| 279 |
+
w = min(0.4, 0.2 * len(vals)) # emojis get up to 40% of the say
|
| 280 |
+
literal = (1 - w) * model_score + w * emo_val
|
| 281 |
+
else:
|
| 282 |
+
literal = model_score
|
| 283 |
+
literal = float(np.clip(literal, -1, 1))
|
| 284 |
+
|
| 285 |
+
cues, cue_score = detect_cues(s)
|
| 286 |
+
if emo_val is not None and txt_score > 0.25:
|
| 287 |
+
ironic = any(norm_emoji(e) in IRONIC_EMOJI for e in found)
|
| 288 |
+
if emo_val < -0.25 or ironic: # "Great job." + eye-roll
|
| 289 |
+
cues.append("positive words + negative/ironic emoji")
|
| 290 |
+
cue_score = min(1.0, cue_score + 0.35)
|
| 291 |
+
|
| 292 |
+
irony_p = float(irony[i])
|
| 293 |
+
sarcasm = 1 - (1 - 0.85 * irony_p) * (1 - cue_score) # noisy-OR fusion
|
| 294 |
+
is_sarc = sarcasm >= SARCASM_THRESHOLD
|
| 295 |
+
|
| 296 |
+
if sarcasm_aware and is_sarc:
|
| 297 |
+
intended = -literal * (0.4 + 0.6 * sarcasm) if literal > 0.1 else literal - 0.25 * sarcasm
|
| 298 |
+
else:
|
| 299 |
+
intended = literal
|
| 300 |
+
intended = float(np.clip(intended, -1, 1))
|
| 301 |
+
|
| 302 |
+
label = label_from_score(intended)
|
| 303 |
+
if not (sarcasm_aware and is_sarc) and min(pos, neg) > 0.3 and abs(intended) < LABEL_THRESHOLD:
|
| 304 |
+
label = "mixed"
|
| 305 |
+
|
| 306 |
+
e_probs = {emo_labels[j]: float(emo[i][j]) for j in range(len(emo_labels))}
|
| 307 |
+
results.append(SentenceResult(
|
| 308 |
+
text=s, literal=literal, intended=intended, label=label,
|
| 309 |
+
probs={"negative": neg, "neutral": neu, "positive": pos},
|
| 310 |
+
irony=irony_p, sarcasm=float(sarcasm), is_sarcastic=is_sarc,
|
| 311 |
+
emojis=found, emoji_valence=emo_val, cues=cues,
|
| 312 |
+
emotion=max(e_probs, key=e_probs.get), emotions=e_probs))
|
| 313 |
+
|
| 314 |
+
return self._profile(results)
|
| 315 |
+
|
| 316 |
+
def _profile(self, results: List[SentenceResult]) -> TextProfile:
|
| 317 |
+
n = len(results)
|
| 318 |
+
scores = np.array([r.intended for r in results])
|
| 319 |
+
weights = 0.5 ** ((n - 1 - np.arange(n)) / RECENCY_HALF_LIFE)
|
| 320 |
+
overall = float((weights * scores).sum() / weights.sum())
|
| 321 |
+
slope = float(np.polyfit(np.arange(n), scores, 1)[0]) if n >= 3 else 0.0
|
| 322 |
+
trend = "improving" if slope > 0.05 else "declining" if slope < -0.05 else "stable"
|
| 323 |
+
emo_mean = {k: float(np.mean([r.emotions[k] for r in results])) for k in results[0].emotions}
|
| 324 |
+
return TextProfile(
|
| 325 |
+
sentences=results, mean=float(scores.mean()), overall=overall,
|
| 326 |
+
overall_label=label_from_score(overall), volatility=float(scores.std()),
|
| 327 |
+
slope=slope, trend=trend,
|
| 328 |
+
sarcasm_rate=float(np.mean([r.is_sarcastic for r in results])),
|
| 329 |
+
sarcasm_shift=float(np.mean([r.intended - r.literal for r in results])),
|
| 330 |
+
dominant_emotion=max(emo_mean, key=emo_mean.get), emotion_mean=emo_mean,
|
| 331 |
+
emoji_count=sum(len(r.emojis) for r in results))
|
| 332 |
+
|
| 333 |
+
# ---- explainability: leave-one-word-out occlusion on the literal sentiment score
|
| 334 |
+
def explain(self, sentence: str, emoji_aware: bool = True) -> List[Tuple[str, Optional[str]]]:
|
| 335 |
+
words = sentence.split()
|
| 336 |
+
if len(words) < 2 or len(words) > MAX_EXPLAIN_WORDS:
|
| 337 |
+
return [(sentence + " ", None)]
|
| 338 |
+
variants = [sentence] + [" ".join(words[:i] + words[i + 1:]) for i in range(len(words))]
|
| 339 |
+
prep = (lambda t: preprocess(t)) if emoji_aware else (lambda t: preprocess(strip_emoji(t)))
|
| 340 |
+
P = self._probs("sentiment", [prep(v) for v in variants])
|
| 341 |
+
ipos, ineg = self._idx("sentiment", "positive", 2), self._idx("sentiment", "negative", 0)
|
| 342 |
+
sc = P[:, ipos] - P[:, ineg]
|
| 343 |
+
contrib = sc[0] - sc[1:] # >0: removing the word lowers the score, i.e. it pushed positive
|
| 344 |
+
out: List[Tuple[str, Optional[str]]] = []
|
| 345 |
+
for w, c in zip(words, contrib):
|
| 346 |
+
lab = "pushes positive" if c > 0.08 else "pushes negative" if c < -0.08 else None
|
| 347 |
+
out.append((w + " ", lab))
|
| 348 |
+
return out
|