File size: 12,544 Bytes
b3b12cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
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
98
99
100
101
102
103
104
105
106
107
108
109
110
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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
"""
Multi-layered NLP sentiment scoring engine.

Produces 12 sentiment dimensions per text, aggregated into composite scores per model.
Designed for time-series analysis of LLM perception across social/developer platforms.

Architecture:
  Layer 1 — Lexicon-based (VADER + TextBlob): fast, interpretable, baseline
  Layer 2 — Transformer-based (FinBERT / distilbert-sst2): nuanced financial + general sentiment
  Layer 3 — Domain-specific aspect extraction: LLM performance dimensions
  Layer 4 — Engagement-weighted scoring: likes/upvotes amplify signal strength
  Layer 5 — Time-series indicators: momentum, volatility, z-scores
"""

import re
import math
import logging
from dataclasses import dataclass, field, asdict
from datetime import datetime, timezone

from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
from textblob import TextBlob

logger = logging.getLogger(__name__)

# ── Layer 1: Lexicon Scorers ──────────────────────────────────────────────────

_vader = SentimentIntensityAnalyzer()

def vader_scores(text: str) -> dict:
    """VADER: optimised for social media (handles emojis, slang, caps, punctuation)."""
    vs = _vader.polarity_scores(text)
    return {
        "vader_compound": vs["compound"],    # -1 to +1 overall
        "vader_pos":      vs["pos"],         # 0-1 proportion positive
        "vader_neg":      vs["neg"],         # 0-1 proportion negative
        "vader_neu":      vs["neu"],         # 0-1 proportion neutral
    }

def textblob_scores(text: str) -> dict:
    """TextBlob: pattern-based, captures polarity + subjectivity."""
    blob = TextBlob(text)
    return {
        "tb_polarity":     blob.sentiment.polarity,      # -1 to +1
        "tb_subjectivity": blob.sentiment.subjectivity,   # 0 (objective) to 1 (subjective)
    }

# ── Layer 2: Transformer Scorers ─────────────────────────────────────────────

_finbert = None
_distilbert = None

def _get_finbert():
    global _finbert
    if _finbert is None:
        from transformers import pipeline
        _finbert = pipeline("sentiment-analysis", model="ProsusAI/finbert",
                            truncation=True, max_length=512)
        logger.info("[sentiment] FinBERT loaded")
    return _finbert

def _get_distilbert():
    global _distilbert
    if _distilbert is None:
        from transformers import pipeline
        _distilbert = pipeline("sentiment-analysis",
                               model="distilbert/distilbert-base-uncased-finetuned-sst-2-english",
                               truncation=True, max_length=512)
        logger.info("[sentiment] DistilBERT-SST2 loaded")
    return _distilbert

def finbert_scores(text: str) -> dict:
    """FinBERT: financial sentiment (positive / negative / neutral)."""
    try:
        result = _get_finbert()(text[:512])[0]
        label = result["label"].lower()  # positive, negative, neutral
        score = result["score"]
        # Convert to -1 to +1 scale
        if label == "positive":
            finbert_val = score
        elif label == "negative":
            finbert_val = -score
        else:
            finbert_val = 0.0
        return {"finbert_sentiment": finbert_val, "finbert_confidence": score}
    except Exception as e:
        logger.debug("finbert error: %s", e)
        return {"finbert_sentiment": 0.0, "finbert_confidence": 0.0}

def distilbert_scores(text: str) -> dict:
    """DistilBERT SST-2: general positive/negative sentiment."""
    try:
        result = _get_distilbert()(text[:512])[0]
        label = result["label"]  # POSITIVE or NEGATIVE
        score = result["score"]
        val = score if label == "POSITIVE" else -score
        return {"distilbert_sentiment": val, "distilbert_confidence": score}
    except Exception as e:
        logger.debug("distilbert error: %s", e)
        return {"distilbert_sentiment": 0.0, "distilbert_confidence": 0.0}


# ── Layer 3: Domain-Specific Aspect Extraction ────────────────────────────────
#
# Instead of general "positive/negative", detect LLM-specific dimensions:
#   - Performance perception (speed, quality, accuracy)
#   - Reliability perception (downtime, errors, hallucinations)
#   - Cost perception (expensive, cheap, value)
#   - Innovation perception (breakthrough, impressive, game-changer)
#   - Adoption signal (using, switched to, migrated, building with)
#   - Complaint signal (broken, worse, degraded, disappointed)

ASPECT_LEXICONS = {
    "performance": {
        "positive": ["fast", "quick", "impressive", "excellent", "powerful", "capable",
                     "accurate", "smart", "intelligent", "brilliant", "amazing",
                     "best", "superior", "outperforms", "crushes", "dominates",
                     "state-of-the-art", "sota", "benchmark", "top", "leading"],
        "negative": ["slow", "dumb", "stupid", "terrible", "awful", "poor",
                     "inaccurate", "wrong", "garbage", "useless", "mediocre",
                     "worse", "inferior", "disappointing", "underwhelming"],
    },
    "reliability": {
        "positive": ["reliable", "stable", "consistent", "dependable", "solid",
                     "robust", "uptime", "available", "works well"],
        "negative": ["hallucinate", "hallucination", "unreliable", "inconsistent",
                     "broken", "crash", "error", "bug", "fail", "down", "outage",
                     "degraded", "throttled", "timeout", "429", "500", "rate limit"],
    },
    "cost": {
        "positive": ["cheap", "affordable", "value", "cost-effective", "free",
                     "fair price", "reasonable", "bargain", "open source", "open-source"],
        "negative": ["expensive", "overpriced", "costly", "ripoff", "pricey",
                     "not worth", "waste of money", "too much", "$$$"],
    },
    "innovation": {
        "positive": ["breakthrough", "revolutionary", "game-changer", "innovative",
                     "novel", "impressive", "exciting", "next-gen", "frontier",
                     "leap", "paradigm", "unprecedented"],
        "negative": ["incremental", "nothing new", "overhyped", "hype", "marketing",
                     "same old", "rehash", "disappointed"],
    },
    "adoption": {
        "positive": ["using", "switched to", "migrated", "building with", "deployed",
                     "adopted", "integrated", "love using", "recommend", "try it",
                     "my go-to", "daily driver", "production"],
        "negative": ["stopped using", "switched away", "abandoned", "dropped",
                     "going back to", "unsubscribed", "cancelled"],
    },
}

def aspect_scores(text: str) -> dict:
    """Score text along domain-specific LLM perception dimensions."""
    text_lower = text.lower()
    scores = {}

    for aspect, lexicon in ASPECT_LEXICONS.items():
        pos_count = sum(1 for w in lexicon["positive"] if w in text_lower)
        neg_count = sum(1 for w in lexicon["negative"] if w in text_lower)
        total     = pos_count + neg_count

        if total == 0:
            scores[f"aspect_{aspect}"] = 0.0
            scores[f"aspect_{aspect}_intensity"] = 0.0
        else:
            # Score: -1 (all negative mentions) to +1 (all positive)
            scores[f"aspect_{aspect}"] = (pos_count - neg_count) / total
            # Intensity: how much does this text discuss this aspect? (0 = not at all)
            scores[f"aspect_{aspect}_intensity"] = min(total / 5.0, 1.0)

    return scores


# ── Layer 4: Engagement-Weighted Scoring ──────────────────────────────────────

def engagement_weight(likes: int = 0, reposts: int = 0, replies: int = 0,
                      score: int = 0, views: int = 0) -> float:
    """
    Compute an engagement multiplier that amplifies high-signal posts.
    Uses log-scale to prevent viral posts from dominating.
    Returns a weight in [0.1, 5.0] range.
    """
    raw = (likes or 0) + (reposts or 0) * 2 + (replies or 0) * 0.5 + (score or 0) + (views or 0) * 0.01
    if raw <= 0:
        return 0.1
    # log-scale: 1 engagement → 0.1, 10 → ~1.1, 100 → ~2.1, 1000 → ~3.1
    return min(0.1 + math.log10(max(raw, 1)), 5.0)


# ── Composite Scorer ──────────────────────────────────────────────────────────

@dataclass
class SentimentResult:
    """All sentiment dimensions for a single text."""
    # Layer 1: Lexicon
    vader_compound: float = 0.0
    vader_pos: float = 0.0
    vader_neg: float = 0.0
    vader_neu: float = 0.0
    tb_polarity: float = 0.0
    tb_subjectivity: float = 0.0

    # Layer 2: Transformer
    finbert_sentiment: float = 0.0
    finbert_confidence: float = 0.0
    distilbert_sentiment: float = 0.0
    distilbert_confidence: float = 0.0

    # Layer 3: Aspects
    aspect_performance: float = 0.0
    aspect_performance_intensity: float = 0.0
    aspect_reliability: float = 0.0
    aspect_reliability_intensity: float = 0.0
    aspect_cost: float = 0.0
    aspect_cost_intensity: float = 0.0
    aspect_innovation: float = 0.0
    aspect_innovation_intensity: float = 0.0
    aspect_adoption: float = 0.0
    aspect_adoption_intensity: float = 0.0

    # Layer 4: Engagement
    engagement_weight: float = 0.1

    # Composites
    composite_sentiment: float = 0.0     # weighted average of all sentiment layers
    composite_quality: float = 0.0       # performance + reliability aspects
    composite_buzz: float = 0.0          # innovation + adoption + engagement

    def to_dict(self) -> dict:
        return asdict(self)


def score_text(text: str, likes: int = 0, reposts: int = 0, replies: int = 0,
               score: int = 0, views: int = 0,
               use_transformers: bool = True) -> SentimentResult:
    """
    Score a single text across all sentiment dimensions.

    Args:
        text: the post/title text
        likes/reposts/replies/score/views: engagement metrics from the platform
        use_transformers: if False, skip FinBERT + DistilBERT (faster, CPU-only)

    Returns:
        SentimentResult with all 20+ dimensions populated
    """
    if not text or not text.strip():
        return SentimentResult()

    # Clean text
    text = re.sub(r'https?://\S+', '', text)  # remove URLs
    text = re.sub(r'@\w+', '', text)          # remove @mentions
    text = text.strip()
    if len(text) < 5:
        return SentimentResult()

    # Layer 1
    v = vader_scores(text)
    t = textblob_scores(text)

    # Layer 2
    f = {"finbert_sentiment": 0.0, "finbert_confidence": 0.0}
    d = {"distilbert_sentiment": 0.0, "distilbert_confidence": 0.0}
    if use_transformers:
        f = finbert_scores(text)
        d = distilbert_scores(text)

    # Layer 3
    a = aspect_scores(text)

    # Layer 4
    ew = engagement_weight(likes, reposts, replies, score, views)

    # ── Composites ────────────────────────────────────────────────────────

    # Composite sentiment: weighted blend of all sentiment signals
    # VADER is best for social media, FinBERT for financial framing, DistilBERT for general
    composite_sentiment = (
        v["vader_compound"] * 0.30 +
        t["tb_polarity"] * 0.10 +
        f["finbert_sentiment"] * 0.35 +
        d["distilbert_sentiment"] * 0.25
    )

    # Composite quality perception: performance + reliability aspects
    perf = a.get("aspect_performance", 0) * a.get("aspect_performance_intensity", 0)
    reli = a.get("aspect_reliability", 0) * a.get("aspect_reliability_intensity", 0)
    composite_quality = (perf + reli) / 2

    # Composite buzz: innovation + adoption + engagement amplification
    inno = a.get("aspect_innovation", 0) * a.get("aspect_innovation_intensity", 0)
    adop = a.get("aspect_adoption", 0) * a.get("aspect_adoption_intensity", 0)
    composite_buzz = (inno + adop) / 2 * ew

    return SentimentResult(
        **v, **t, **f, **d, **a,
        engagement_weight=ew,
        composite_sentiment=composite_sentiment,
        composite_quality=composite_quality,
        composite_buzz=composite_buzz,
    )