EmoTFIDF 1.4.2__tar.gz → 2.0.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. {EmoTFIDF-1.4.2 → emotfidf-2.0.1}/EmoTFIDF/EmoTFIDF.py +5 -3
  2. emotfidf-2.0.1/EmoTFIDF/__init__.py +5 -0
  3. emotfidf-2.0.1/EmoTFIDF/evidence/__init__.py +20 -0
  4. emotfidf-2.0.1/EmoTFIDF/evidence/analyzer.py +387 -0
  5. emotfidf-2.0.1/EmoTFIDF/evidence/explain.py +130 -0
  6. emotfidf-2.0.1/EmoTFIDF/evidence/lexeme_prior.py +81 -0
  7. emotfidf-2.0.1/EmoTFIDF/evidence/lexicon.py +86 -0
  8. emotfidf-2.0.1/EmoTFIDF/evidence/preprocessing.py +53 -0
  9. emotfidf-2.0.1/EmoTFIDF/evidence/prompt_features.py +78 -0
  10. emotfidf-2.0.1/EmoTFIDF/evidence/rules.py +91 -0
  11. emotfidf-2.0.1/EmoTFIDF/evidence/schemas.py +156 -0
  12. emotfidf-2.0.1/EmoTFIDF/evidence/verifier.py +112 -0
  13. emotfidf-2.0.1/EmoTFIDF/evidence/weighting.py +261 -0
  14. emotfidf-2.0.1/EmoTFIDF/nltk_resources.py +33 -0
  15. {EmoTFIDF-1.4.2 → emotfidf-2.0.1/EmoTFIDF.egg-info}/PKG-INFO +77 -5
  16. emotfidf-2.0.1/EmoTFIDF.egg-info/SOURCES.txt +35 -0
  17. emotfidf-2.0.1/EmoTFIDF.egg-info/requires.txt +8 -0
  18. {EmoTFIDF-1.4.2 → emotfidf-2.0.1}/EmoTFIDF.egg-info/top_level.txt +0 -1
  19. emotfidf-2.0.1/MANIFEST.in +2 -0
  20. EmoTFIDF-1.4.2/README.md → emotfidf-2.0.1/PKG-INFO +344 -258
  21. EmoTFIDF-1.4.2/EmoTFIDF.egg-info/PKG-INFO → emotfidf-2.0.1/README.md +298 -272
  22. emotfidf-2.0.1/pyproject.toml +3 -0
  23. emotfidf-2.0.1/setup.py +55 -0
  24. emotfidf-2.0.1/tests/test_benchmark_regression_smoke.py +10 -0
  25. emotfidf-2.0.1/tests/test_label_bridge.py +34 -0
  26. emotfidf-2.0.1/tests/test_v1_v2_compare.py +66 -0
  27. emotfidf-2.0.1/tests/test_v2_analyzer.py +83 -0
  28. emotfidf-2.0.1/tests/test_v2_calibration.py +80 -0
  29. emotfidf-2.0.1/tests/test_v2_explanation_quality.py +65 -0
  30. emotfidf-2.0.1/tests/test_v2_prompt_features.py +30 -0
  31. emotfidf-2.0.1/tests/test_v2_rules.py +44 -0
  32. emotfidf-2.0.1/tests/test_v2_verifier.py +41 -0
  33. EmoTFIDF-1.4.2/EmoTFIDF/__init__.py +0 -3
  34. EmoTFIDF-1.4.2/EmoTFIDF.egg-info/SOURCES.txt +0 -13
  35. EmoTFIDF-1.4.2/EmoTFIDF.egg-info/requires.txt +0 -7
  36. EmoTFIDF-1.4.2/setup.py +0 -51
  37. EmoTFIDF-1.4.2/tests/__init__.py +0 -3
  38. {EmoTFIDF-1.4.2 → emotfidf-2.0.1}/EmoTFIDF/emotions_lex.json +0 -0
  39. {EmoTFIDF-1.4.2 → emotfidf-2.0.1}/EmoTFIDF.egg-info/dependency_links.txt +0 -0
  40. {EmoTFIDF-1.4.2 → emotfidf-2.0.1}/LICENSE +0 -0
  41. {EmoTFIDF-1.4.2 → emotfidf-2.0.1}/setup.cfg +0 -0
  42. {EmoTFIDF-1.4.2 → emotfidf-2.0.1}/tests/test_emotfidf.py +0 -0
@@ -11,9 +11,11 @@ import seaborn as sns
11
11
  import torch
12
12
  from transformers import AutoTokenizer, AutoModelForSequenceClassification
13
13
 
14
- nltk.download('wordnet')
15
- nltk.download('punkt')
16
- nltk.download('stopwords')
14
+ from .nltk_resources import ensure_nltk_word_tokenize_deps
15
+
16
+ ensure_nltk_word_tokenize_deps()
17
+ nltk.download("wordnet", quiet=True)
18
+ nltk.download("stopwords", quiet=True)
17
19
 
18
20
  # Initialize the tokenizer and model for transformer-based emotion detection
19
21
  tokenizer = AutoTokenizer.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
@@ -0,0 +1,5 @@
1
+ """EmoTFIDF package: legacy V1 API in ``EmoTFIDF.EmoTFIDF`` and V2 evidence layer in ``EmoTFIDF.evidence``."""
2
+
3
+ from EmoTFIDF.evidence import EmoTFIDFv2
4
+
5
+ __all__ = ["EmoTFIDFv2"]
@@ -0,0 +1,20 @@
1
+ """
2
+ EmoTFIDF V2 — interpretable lexical + TF-IDF emotional evidence layer.
3
+
4
+ Use :class:`EmoTFIDF.evidence.analyzer.EmoTFIDFv2` for the main API. V1 remains in
5
+ ``EmoTFIDF.EmoTFIDF.EmoTFIDF`` unchanged.
6
+ """
7
+
8
+ from EmoTFIDF.evidence.analyzer import EmoTFIDFv2
9
+ from EmoTFIDF.evidence.schemas import (
10
+ AnalysisResult,
11
+ ExplanationBundle,
12
+ VerificationResult,
13
+ )
14
+
15
+ __all__ = [
16
+ "EmoTFIDFv2",
17
+ "AnalysisResult",
18
+ "VerificationResult",
19
+ "ExplanationBundle",
20
+ ]
@@ -0,0 +1,387 @@
1
+ """Main EmoTFIDF V2 analyzer: lexicon + corpus TF-IDF + transparent cue windows."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Dict, List, Optional, Sequence, Tuple
6
+
7
+ from nltk.corpus import stopwords
8
+ from sklearn.feature_extraction.text import TfidfVectorizer
9
+
10
+ from EmoTFIDF.evidence.lexeme_prior import (
11
+ contextual_affect_multiplier,
12
+ explanation_rank_multiplier,
13
+ )
14
+ from EmoTFIDF.evidence.lexicon import (
15
+ DEFAULT_EMOTION_LABELS,
16
+ inverse_count_emotion_shares,
17
+ load_lexicon,
18
+ )
19
+ from EmoTFIDF.evidence.preprocessing import (
20
+ content_tokens_for_coverage,
21
+ process_message_for_tfidf,
22
+ strip_edges,
23
+ tokenize_raw_sequence,
24
+ )
25
+ from EmoTFIDF.evidence.rules import (
26
+ INTENSIFIERS_DOWN,
27
+ INTENSIFIERS_UP,
28
+ NEGATION_CUES,
29
+ NEGATION_SUPPRESSED_JOY_TO_SADNESS_FRACTION,
30
+ find_negation_in_window,
31
+ intensifier_multiplier_in_window,
32
+ )
33
+ from EmoTFIDF.evidence.schemas import (
34
+ AnalysisResult,
35
+ Coverage,
36
+ IntensifierHit,
37
+ NegationHit,
38
+ TermContribution,
39
+ )
40
+ from EmoTFIDF.evidence.weighting import (
41
+ build_feature_vector,
42
+ distribution_entropy,
43
+ dominant_margin,
44
+ emotion_dict_zeros,
45
+ normalize_positive_l1,
46
+ per_emotion_max_and_topk,
47
+ select_dominant_emotions,
48
+ softmax_positive_or_zeros,
49
+ top_terms_by_emotion_from_contribs,
50
+ )
51
+
52
+
53
+ def _tfidf_weight_dict(vectorizer: Optional[TfidfVectorizer], processed_doc: str) -> Dict[str, float]:
54
+ if vectorizer is None or not processed_doc.strip():
55
+ return {}
56
+ mat = vectorizer.transform([processed_doc])
57
+ row = mat[0]
58
+ names = vectorizer.get_feature_names_out()
59
+ coo = row.tocoo()
60
+ return {str(names[j]): float(v) for v, j in zip(coo.data, coo.col)}
61
+
62
+
63
+ def _median_nonzero_weight(vectorizer: TfidfVectorizer, processed_docs: List[str]) -> float:
64
+ vals: List[float] = []
65
+ for d in processed_docs[:200]:
66
+ vals.extend(_tfidf_weight_dict(vectorizer, d).values())
67
+ if not vals:
68
+ return 0.25
69
+ vals.sort()
70
+ mid = len(vals) // 2
71
+ if len(vals) % 2:
72
+ return max(vals[mid], 1e-6)
73
+ return max(0.5 * (vals[mid - 1] + vals[mid]), 1e-6)
74
+
75
+
76
+ class EmoTFIDFv2:
77
+ """
78
+ Interpretable emotional evidence layer: lexicon hits, corpus TF-IDF weights,
79
+ and lightweight negation / intensifier windows.
80
+
81
+ Public methods
82
+ --------------
83
+ fit(corpus_texts)
84
+ Fit the TF-IDF vectorizer on processed documents (same preprocessing as V1).
85
+ analyze(text)
86
+ Return a rich :class:`AnalysisResult`.
87
+ analyze_batch(texts)
88
+ List of analysis dicts / results.
89
+ get_feature_vector(text)
90
+ Numeric feature vector (see ``feature_names`` on the analysis object).
91
+ explain(text)
92
+ Human-oriented explanation bundle as dict.
93
+ verify_label(text, predicted_label)
94
+ Lexical support for a proposed emotion label.
95
+ to_prompt_features(text)
96
+ Compact JSON-friendly features for LLM prompts.
97
+ """
98
+
99
+ def __init__(
100
+ self,
101
+ lexicon_path: Optional[str] = None,
102
+ *,
103
+ negation_window: int = 4,
104
+ intensifier_window: int = 3,
105
+ negation_factor: float = -0.55,
106
+ max_tfidf_features: int = 200,
107
+ ) -> None:
108
+ self.labels: List[str] = list(DEFAULT_EMOTION_LABELS)
109
+ self._lexicon: Dict[str, Any] = load_lexicon(lexicon_path)
110
+ self.negation_window = negation_window
111
+ self.intensifier_window = intensifier_window
112
+ self.negation_factor = negation_factor
113
+ self.max_tfidf_features = max_tfidf_features
114
+ self._vectorizer: Optional[TfidfVectorizer] = None
115
+ self._fallback_tfidf_weight: float = 0.25
116
+
117
+ def fit(self, corpus_texts: Sequence[str]) -> "EmoTFIDFv2":
118
+ """Fit TF-IDF on *corpus_texts* using V1-compatible preprocessing."""
119
+ if corpus_texts is None or len(corpus_texts) == 0:
120
+ raise ValueError("corpus_texts must be a non-empty sequence of strings.")
121
+ processed = [process_message_for_tfidf(str(t)) for t in corpus_texts]
122
+ sw = stopwords.words("english")
123
+ self._vectorizer = TfidfVectorizer(
124
+ max_features=self.max_tfidf_features,
125
+ stop_words=sw,
126
+ token_pattern=r"(?u)\b[A-Za-z]+\b",
127
+ )
128
+ self._vectorizer.fit(processed)
129
+ self._fallback_tfidf_weight = _median_nonzero_weight(self._vectorizer, processed)
130
+ return self
131
+
132
+ def analyze(self, text: str) -> AnalysisResult:
133
+ """Run the full V2 pipeline on a single string."""
134
+ if text is None:
135
+ text = ""
136
+ raw_tokens = [strip_edges(t) for t in tokenize_raw_sequence(str(text))]
137
+ raw_tokens = [t for t in raw_tokens if t]
138
+
139
+ processed = process_message_for_tfidf(str(text))
140
+ weights = _tfidf_weight_dict(self._vectorizer, processed)
141
+ proc_tokens = content_tokens_for_coverage(processed)
142
+ total_cov = len(proc_tokens) if proc_tokens else 0
143
+
144
+ negation_hits: List[NegationHit] = []
145
+ intensifier_hits: List[IntensifierHit] = []
146
+ term_contributions: List[TermContribution] = []
147
+ matched_in_order: List[str] = []
148
+ matched_set = set()
149
+
150
+ raw_scores = emotion_dict_zeros(self.labels)
151
+
152
+ for i, tok in enumerate(raw_tokens):
153
+ # Intensifier / downtoner tokens are cue-only (e.g. "extremely" wrongly tags joy in NRC).
154
+ if tok in INTENSIFIERS_UP or tok in INTENSIFIERS_DOWN or tok in NEGATION_CUES:
155
+ continue
156
+ if tok not in self._lexicon:
157
+ continue
158
+ # Inverse duplicate-count shares so repeated lexicon tags (e.g. two disgust)
159
+ # do not drown a single anger tag—general fix for multi-label NRC entries.
160
+ emotion_shares = inverse_count_emotion_shares(self._lexicon[tok])
161
+ if not emotion_shares:
162
+ continue
163
+
164
+ base = float(weights.get(tok, self._fallback_tfidf_weight))
165
+ neg_pair = find_negation_in_window(raw_tokens, i, self.negation_window)
166
+ negated = neg_pair is not None
167
+ neg_cue = neg_pair[0] if neg_pair else None
168
+ imult, icue, idir, icue_pos = intensifier_multiplier_in_window(
169
+ raw_tokens, i, self.intensifier_window
170
+ )
171
+
172
+ # Negation scales the whole affect token mass (same cue for all emotions on token).
173
+ emotional_mult = self.negation_factor if negated else 1.0
174
+ # Downweight temporal/discourse tokens that NRC still tags with affect (see lexeme_prior).
175
+ ctx_pen = contextual_affect_multiplier(tok)
176
+ mass = base * imult * emotional_mult * ctx_pen
177
+ rank_hint = explanation_rank_multiplier(tok, self._lexicon)
178
+ per_e: Dict[str, float] = emotion_dict_zeros(self.labels)
179
+ for e, w_share in emotion_shares.items():
180
+ contrib = mass * float(w_share)
181
+ per_e[e] = contrib
182
+ raw_scores[e] = raw_scores.get(e, 0.0) + contrib
183
+
184
+ emotions = sorted(emotion_shares.keys())
185
+
186
+ if neg_pair:
187
+ negation_hits.append(
188
+ NegationHit(
189
+ cue=neg_pair[0],
190
+ cue_position=neg_pair[1],
191
+ target_token=tok,
192
+ target_position=i,
193
+ emotions_affected=list(emotions),
194
+ )
195
+ )
196
+ if icue and idir and icue_pos >= 0 and abs(imult - 1.0) > 1e-9:
197
+ intensifier_hits.append(
198
+ IntensifierHit(
199
+ cue=icue,
200
+ cue_position=icue_pos,
201
+ direction=idir,
202
+ target_token=tok,
203
+ target_position=i,
204
+ multiplier=round(imult, 6),
205
+ )
206
+ )
207
+
208
+ term_contributions.append(
209
+ TermContribution(
210
+ token=tok,
211
+ position=i,
212
+ emotions=list(emotions),
213
+ base_weight=round(base, 6),
214
+ intensifier_multiplier=round(imult, 6),
215
+ negated=negated,
216
+ negation_cue=neg_cue,
217
+ intensifier_cue=icue,
218
+ per_emotion_contribution={k: round(v, 8) for k, v in per_e.items() if v != 0.0},
219
+ explanation_rank_hint=round(rank_hint, 6),
220
+ )
221
+ )
222
+ if tok not in matched_set:
223
+ matched_set.add(tok)
224
+ matched_in_order.append(tok)
225
+
226
+ # Transparent valence sink: suppressed joy from negation is not re-mapped to anger.
227
+ _apply_negation_joy_to_sadness_sink(raw_scores)
228
+
229
+ unmatched = [t for t in proc_tokens if t not in matched_set]
230
+ matched_count = len(matched_set)
231
+ coverage_ratio = (matched_count / total_cov) if total_cov else 0.0
232
+ unmatched_ratio = (len(unmatched) / total_cov) if total_cov else 0.0
233
+
234
+ coverage = Coverage(
235
+ matched_term_count=matched_count,
236
+ total_tokens_considered=total_cov,
237
+ coverage_ratio=round(coverage_ratio, 6),
238
+ matched_terms=list(matched_in_order),
239
+ unmatched_terms=sorted(set(unmatched))[:80],
240
+ )
241
+
242
+ mass_abs = sum(abs(raw_scores[e]) for e in self.labels)
243
+ mass_pos = sum(max(0.0, raw_scores[e]) for e in self.labels)
244
+ # Meaningful = lexicon-aligned affect activity (even if net polarity is negative pre-sink).
245
+ has_meaningful_signal = len(term_contributions) > 0 and mass_abs > 1e-12
246
+ # Low evidence when nothing matched or no positive mass to summarize as a distribution.
247
+ has_low_evidence = len(term_contributions) == 0 or mass_pos <= 1e-12
248
+
249
+ norm_pos = normalize_positive_l1(raw_scores, self.labels)
250
+ norm_sm = softmax_positive_or_zeros(raw_scores, self.labels)
251
+ top_terms = top_terms_by_emotion_from_contribs(
252
+ term_contributions, self.labels, top_k=5, lexicon=self._lexicon
253
+ )
254
+ maxv, topk = per_emotion_max_and_topk(term_contributions, self.labels, k=3)
255
+ ent = distribution_entropy(norm_sm, self.labels)
256
+ sm_margin = dominant_margin(norm_sm, self.labels)
257
+
258
+ can_dominant = has_meaningful_signal and mass_pos > 1e-12
259
+ dominant, top1s, top2s, pos_margin = select_dominant_emotions(
260
+ norm_pos,
261
+ raw_scores,
262
+ self.labels,
263
+ has_meaningful_signal=can_dominant,
264
+ single_dominant_margin=0.06,
265
+ )
266
+
267
+ support_summary = _build_support_summary(
268
+ dominant,
269
+ coverage_ratio,
270
+ negation_hits,
271
+ intensifier_hits,
272
+ has_meaningful_signal,
273
+ has_low_evidence,
274
+ )
275
+
276
+ feat_vec, feat_names = build_feature_vector(
277
+ raw_scores,
278
+ norm_sm,
279
+ coverage_ratio,
280
+ matched_count,
281
+ unmatched_ratio,
282
+ maxv,
283
+ topk,
284
+ len(negation_hits),
285
+ len(intensifier_hits),
286
+ ent,
287
+ sm_margin,
288
+ self.labels,
289
+ meaningful_signal_01=1.0 if has_meaningful_signal else 0.0,
290
+ total_positive_evidence=mass_pos,
291
+ total_abs_evidence=mass_abs,
292
+ )
293
+
294
+ raw_rounded = {e: round(raw_scores[e], 8) for e in self.labels}
295
+ norm_rounded = {e: round(norm_pos[e], 8) for e in self.labels}
296
+
297
+ return AnalysisResult(
298
+ raw_emotion_scores=raw_rounded,
299
+ normalized_emotion_scores=norm_rounded,
300
+ top_terms_by_emotion=top_terms,
301
+ term_contributions=term_contributions,
302
+ coverage=coverage,
303
+ matched_terms=list(matched_in_order),
304
+ unmatched_terms=coverage.unmatched_terms,
305
+ negation_hits=negation_hits,
306
+ intensifier_hits=intensifier_hits,
307
+ dominant_emotions=dominant,
308
+ support_summary=support_summary,
309
+ feature_vector=[round(float(x), 8) for x in feat_vec],
310
+ feature_names=feat_names,
311
+ total_evidence=round(mass_abs, 8),
312
+ total_positive_evidence=round(mass_pos, 8),
313
+ top1_score=round(top1s, 8),
314
+ top2_score=round(top2s, 8),
315
+ dominance_margin=round(pos_margin, 8),
316
+ has_meaningful_signal=has_meaningful_signal,
317
+ has_low_evidence=has_low_evidence,
318
+ )
319
+
320
+ def analyze_batch(self, texts: Sequence[str]) -> List[Dict[str, Any]]:
321
+ """Analyze many documents; returns JSON-ready dicts (stable ordering)."""
322
+ return [self.analyze(t).to_dict() for t in texts]
323
+
324
+ def get_feature_vector(self, text: str) -> Tuple[List[float], List[str]]:
325
+ """Return ``(feature_vector, feature_names)`` for *text*."""
326
+ r = self.analyze(text)
327
+ return list(r.feature_vector), list(r.feature_names)
328
+
329
+ def explain(self, text: str) -> Dict[str, Any]:
330
+ """Human-readable explanation bundle (see :mod:`EmoTFIDF.evidence.explain`)."""
331
+ from EmoTFIDF.evidence.explain import build_explanation
332
+
333
+ return build_explanation(self.analyze(text)).to_dict()
334
+
335
+ def verify_label(self, text: str, predicted_label: str) -> Dict[str, Any]:
336
+ """Lexical support check for a proposed label (see :mod:`EmoTFIDF.evidence.verifier`)."""
337
+ from EmoTFIDF.evidence.verifier import verify_label as verify
338
+
339
+ return verify(self.analyze(text), predicted_label).to_dict()
340
+
341
+ def to_prompt_features(self, text: str) -> Dict[str, Any]:
342
+ """Compact prompt-side features (see :mod:`EmoTFIDF.evidence.prompt_features`)."""
343
+ from EmoTFIDF.evidence.prompt_features import build_prompt_features
344
+
345
+ return build_prompt_features(self.analyze(text))
346
+
347
+
348
+ def _apply_negation_joy_to_sadness_sink(raw_scores: Dict[str, float]) -> None:
349
+ """
350
+ If negation drove *joy* negative, move part of that magnitude into *sadness* (explicit rule).
351
+
352
+ Without this, positive-mass normalization would show all-zero emotions even when the
353
+ reader should see a conservative negative-valence hint—not unrelated anger from min-shift.
354
+ """
355
+ joy = raw_scores.get("joy", 0.0)
356
+ if joy < 0.0:
357
+ raw_scores["sadness"] = raw_scores.get("sadness", 0.0) + NEGATION_SUPPRESSED_JOY_TO_SADNESS_FRACTION * abs(
358
+ joy
359
+ )
360
+
361
+
362
+ def _build_support_summary(
363
+ dominant: List[str],
364
+ coverage_ratio: float,
365
+ neg_hits: List[NegationHit],
366
+ int_hits: List[IntensifierHit],
367
+ has_meaningful_signal: bool,
368
+ has_low_evidence: bool,
369
+ ) -> str:
370
+ if not has_meaningful_signal or has_low_evidence:
371
+ if not has_meaningful_signal:
372
+ return "No emotional evidence detected from lexicon or phrase rules."
373
+ return "Lexicon hits present but no positive affect mass to summarize (treat as low evidence)."
374
+ dom = ", ".join(dominant[:2]) if dominant else "none"
375
+ strength = (
376
+ "strong"
377
+ if coverage_ratio >= 0.35
378
+ else "moderate"
379
+ if coverage_ratio >= 0.15
380
+ else "weak"
381
+ )
382
+ bits = [f"Dominant signal: {dom} (lexical coverage {strength})."]
383
+ if neg_hits:
384
+ bits.append(f"Negation cues affecting {len(neg_hits)} affect-bearing term(s).")
385
+ if int_hits:
386
+ bits.append(f"Intensifier/downtoner cues near {len(int_hits)} affect-bearing term(s).")
387
+ return " ".join(bits)
@@ -0,0 +1,130 @@
1
+ """Human-readable explanations from a V2 :class:`~EmoTFIDF.evidence.schemas.AnalysisResult`."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Dict, List
6
+
7
+ from EmoTFIDF.evidence.lexeme_prior import is_weak_contextual_lexeme
8
+ from EmoTFIDF.evidence.lexicon import DEFAULT_EMOTION_LABELS
9
+ from EmoTFIDF.evidence.schemas import AnalysisResult, ExplanationBundle
10
+
11
+
12
+ def _contribution_mass(c) -> float:
13
+ return sum(max(0.0, float(v)) for v in c.per_emotion_contribution.values())
14
+
15
+
16
+ def _select_top_contributing_words(analysis: AnalysisResult, limit: int = 12) -> List[Dict[str, Any]]:
17
+ """
18
+ Prefer lexicon-grounded affect tokens with strong positive mass and good rank hints.
19
+
20
+ Weak contextual lexemes (temporal/deictic NRC tags) are omitted whenever any stronger
21
+ contributor exists so explanations are not filler-dominated.
22
+ """
23
+ if not analysis.term_contributions:
24
+ return []
25
+
26
+ ranked = sorted(
27
+ analysis.term_contributions,
28
+ key=lambda c: (-_contribution_mass(c) * c.explanation_rank_hint, c.token),
29
+ )
30
+ non_weak = [c for c in ranked if not is_weak_contextual_lexeme(c.token)]
31
+ pool = non_weak if non_weak else ranked
32
+
33
+ out: List[Dict[str, Any]] = []
34
+ seen: set = set()
35
+ for c in pool:
36
+ if _contribution_mass(c) <= 1e-12:
37
+ continue
38
+ key = (c.token, tuple(sorted(c.emotions)))
39
+ if key in seen:
40
+ continue
41
+ seen.add(key)
42
+ out.append(
43
+ {
44
+ "token": c.token,
45
+ "emotions": list(c.emotions),
46
+ "base_tfidf_mass": c.base_weight,
47
+ "intensifier_multiplier": c.intensifier_multiplier,
48
+ "negated": c.negated,
49
+ "explanation_rank_hint": c.explanation_rank_hint,
50
+ "positive_mass": round(_contribution_mass(c), 6),
51
+ }
52
+ )
53
+ if len(out) >= limit:
54
+ break
55
+ return out
56
+
57
+
58
+ def build_explanation(analysis: AnalysisResult) -> ExplanationBundle:
59
+ """
60
+ Produce a concise explanation: dominant emotions, drivers, cue adjustments, and caveats.
61
+
62
+ Intended for debugging, demos, and documentation — not as a gold truth labeler.
63
+ """
64
+ no_signal = not analysis.has_meaningful_signal
65
+ low_ev = analysis.has_low_evidence
66
+
67
+ top_words = _select_top_contributing_words(analysis, limit=12)
68
+
69
+ adjustments: List[str] = []
70
+ for n in analysis.negation_hits:
71
+ adjustments.append(
72
+ f"Negation '{n.cue}' near '{n.target_token}' reduced or inverted "
73
+ f"{', '.join(n.emotions_affected)}; suppressed joy is partially attributed to sadness "
74
+ f"(see NEGATION_SUPPRESSED_JOY_TO_SADNESS_FRACTION in rules.py)."
75
+ )
76
+ for h in analysis.intensifier_hits:
77
+ adjustments.append(
78
+ f"{h.direction.title()}toner '{h.cue}' near '{h.target_token}' "
79
+ f"(×{h.multiplier:.3f})."
80
+ )
81
+
82
+ warnings: List[str] = []
83
+ if no_signal:
84
+ warnings.append("No emotional evidence detected from lexicon or phrase rules.")
85
+ elif low_ev:
86
+ warnings.append("Low positive affect mass; dominant emotions may be absent or unstable.")
87
+ if analysis.coverage.coverage_ratio < 0.12 and not no_signal:
88
+ warnings.append("Lexical coverage is low; treat scores as weak evidence.")
89
+ if analysis.negation_hits and not no_signal:
90
+ warnings.append("Negation handling is heuristic (local window, no full parsing).")
91
+
92
+ if no_signal:
93
+ commentary = (
94
+ "No lexicon hits in the seven-label space and no affect-bearing terms; "
95
+ "normalized scores are zeroed (no uniform pseudo-distribution)."
96
+ )
97
+ elif low_ev:
98
+ commentary = (
99
+ "Matched terms did not yield positive summarized mass after cue handling; "
100
+ "see raw scores and negation notes if present."
101
+ )
102
+ else:
103
+ ranked = sorted(
104
+ ((analysis.normalized_emotion_scores.get(e, 0.0), e) for e in DEFAULT_EMOTION_LABELS),
105
+ reverse=True,
106
+ )
107
+ top_s, top_e = ranked[0]
108
+ second_s = ranked[1][0] if len(ranked) > 1 else 0.0
109
+ margin = top_s - second_s
110
+ if margin < 0.08 and analysis.coverage.coverage_ratio >= 0.12:
111
+ commentary = (
112
+ f"Top emotion {top_e} is only marginally ahead of alternatives "
113
+ f"(margin {margin:.3f} on positive-mass normalization)."
114
+ )
115
+ else:
116
+ commentary = (
117
+ f"Lexical mass concentrates on {top_e} "
118
+ f"(normalized share {top_s:.3f}, margin {margin:.3f})."
119
+ )
120
+
121
+ return ExplanationBundle(
122
+ dominant_emotions=list(analysis.dominant_emotions),
123
+ top_contributing_words=top_words,
124
+ adjustment_notes=adjustments,
125
+ confidence_commentary=commentary,
126
+ warnings=warnings,
127
+ raw_support_summary=analysis.support_summary,
128
+ no_signal_detected=no_signal,
129
+ has_low_evidence=low_ev,
130
+ )
@@ -0,0 +1,81 @@
1
+ """
2
+ Lexeme-level priors for affect scoring and explanation ranking.
3
+
4
+ The NRC lexicon tags many **temporal / discourse** words with emotions (e.g. *yesterday* →
5
+ sadness). Those tags are lexicon-grounded but often **not** the emotional focus of a
6
+ sentence. We downweight their *mass* in the scorer and their *rank* in explanations
7
+ using a small, documented set—not sentence-specific hacks.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from typing import Any, Dict, FrozenSet
13
+
14
+ from EmoTFIDF.evidence.lexicon import inverse_count_emotion_shares
15
+
16
+ # High-frequency English tokens that are primarily temporal, spatial, or procedural
17
+ # in modern usage but still carry NRC emotion tags. Used only as a *soft* multiplier.
18
+ WEAK_CONTEXTUAL_AFFECT_LEXEMES: FrozenSet[str] = frozenset(
19
+ {
20
+ "yesterday",
21
+ "today",
22
+ "tomorrow",
23
+ "tonight",
24
+ "morning",
25
+ "afternoon",
26
+ "evening",
27
+ "midnight",
28
+ "week",
29
+ "month",
30
+ "year",
31
+ "decade",
32
+ "moment",
33
+ "minute",
34
+ "hour",
35
+ "daily",
36
+ "weekly",
37
+ "monthly",
38
+ "recently",
39
+ "currently",
40
+ "formerly",
41
+ "previously",
42
+ "later",
43
+ "soon",
44
+ "ago",
45
+ "now",
46
+ "date",
47
+ "calendar",
48
+ "schedule",
49
+ }
50
+ )
51
+
52
+
53
+ def contextual_affect_multiplier(token: str) -> float:
54
+ """
55
+ Multiply lexicon-derived affect mass for *token*.
56
+
57
+ Returns ``1.0`` for typical affect-bearing words, and a fraction in ``(0, 1)`` for
58
+ tokens in :data:`WEAK_CONTEXTUAL_AFFECT_LEXEMES` so they rarely dominate sadness/joy
59
+ over clearer affect words (*crying*, *happy*, etc.).
60
+ """
61
+ if token in WEAK_CONTEXTUAL_AFFECT_LEXEMES:
62
+ return 0.22
63
+ return 1.0
64
+
65
+
66
+ def is_weak_contextual_lexeme(token: str) -> bool:
67
+ return token in WEAK_CONTEXTUAL_AFFECT_LEXEMES
68
+
69
+
70
+ def explanation_rank_multiplier(token: str, lexicon: Dict[str, Any]) -> float:
71
+ """
72
+ Downrank weak contextual tokens and uprank lexicon entries with multiple seven-way
73
+ emotions (broader affect profile) for **explanation ordering only**.
74
+ """
75
+ raw = lexicon.get(token)
76
+ if not isinstance(raw, list):
77
+ return 1.0
78
+ u = len(inverse_count_emotion_shares(raw))
79
+ breadth = 0.52 + 0.16 * min(max(u, 1), 4)
80
+ weak = 0.11 if is_weak_contextual_lexeme(token) else 1.0
81
+ return float(breadth * weak)