| """ |
| 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__) |
|
|
| |
|
|
| _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"], |
| "vader_pos": vs["pos"], |
| "vader_neg": vs["neg"], |
| "vader_neu": vs["neu"], |
| } |
|
|
| def textblob_scores(text: str) -> dict: |
| """TextBlob: pattern-based, captures polarity + subjectivity.""" |
| blob = TextBlob(text) |
| return { |
| "tb_polarity": blob.sentiment.polarity, |
| "tb_subjectivity": blob.sentiment.subjectivity, |
| } |
|
|
| |
|
|
| _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() |
| score = result["score"] |
| |
| 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"] |
| 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} |
|
|
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| 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: |
| |
| scores[f"aspect_{aspect}"] = (pos_count - neg_count) / total |
| |
| scores[f"aspect_{aspect}_intensity"] = min(total / 5.0, 1.0) |
|
|
| return scores |
|
|
|
|
| |
|
|
| 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 |
| |
| return min(0.1 + math.log10(max(raw, 1)), 5.0) |
|
|
|
|
| |
|
|
| @dataclass |
| class SentimentResult: |
| """All sentiment dimensions for a single text.""" |
| |
| 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 |
|
|
| |
| finbert_sentiment: float = 0.0 |
| finbert_confidence: float = 0.0 |
| distilbert_sentiment: float = 0.0 |
| distilbert_confidence: float = 0.0 |
|
|
| |
| 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 |
|
|
| |
| engagement_weight: float = 0.1 |
|
|
| |
| composite_sentiment: float = 0.0 |
| composite_quality: float = 0.0 |
| composite_buzz: float = 0.0 |
|
|
| 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() |
|
|
| |
| text = re.sub(r'https?://\S+', '', text) |
| text = re.sub(r'@\w+', '', text) |
| text = text.strip() |
| if len(text) < 5: |
| return SentimentResult() |
|
|
| |
| v = vader_scores(text) |
| t = textblob_scores(text) |
|
|
| |
| 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) |
|
|
| |
| a = aspect_scores(text) |
|
|
| |
| ew = engagement_weight(likes, reposts, replies, score, views) |
|
|
| |
|
|
| |
| |
| composite_sentiment = ( |
| v["vader_compound"] * 0.30 + |
| t["tb_polarity"] * 0.10 + |
| f["finbert_sentiment"] * 0.35 + |
| d["distilbert_sentiment"] * 0.25 |
| ) |
|
|
| |
| 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 |
|
|
| |
| 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, |
| ) |
|
|