old-code / sentiment.py
agentpulse's picture
Upload 14 files
306ab7a verified
Raw
History Blame Contribute Delete
12.5 kB
"""
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,
)