| """ |
| Data Quality Layer. |
| |
| Filters and scores every collected text for trustworthiness before it |
| enters the sentiment pipeline. Three sub-systems: |
| |
| 1. DUPLICATE DETECTION |
| - Exact duplicate (same text across sources) |
| - Near-duplicate (cosine similarity via character trigrams, >0.85 threshold) |
| - Cross-model duplicate (same post attributed to multiple models) |
| |
| 2. BOT / SPAM DETECTION |
| - Repetitive posting pattern (same author, similar text, high frequency) |
| - Generic content (text too short, no specifics, templated phrases) |
| - Engagement anomaly (extremely high/low engagement vs author baseline) |
| - New account signal (no engagement history → lower trust) |
| |
| 3. SOURCE CREDIBILITY SCORING |
| - Author history (repeat authors with consistent engagement = higher trust) |
| - Platform weighting (SO/HN higher base credibility than Bluesky/Reddit) |
| - Engagement ratio (high engagement = community-validated content) |
| - Specificity score (mentions specific model features/versions vs generic) |
| |
| Output: each text gets a `quality_score` (0-1) that multiplies its sentiment weight. |
| Texts scoring < 0.3 are flagged as low-quality and excluded from scoring. |
| |
| Usage: |
| python -m scoring.data_quality — score all texts |
| python -m scoring.data_quality --stats — print quality distribution |
| """ |
|
|
| import re |
| import math |
| import json |
| import logging |
| import hashlib |
| from collections import defaultdict, Counter |
| from pathlib import Path |
| import sys |
|
|
| sys.path.insert(0, str(Path(__file__).parent.parent)) |
| from db.schema import get_connection, db |
|
|
| logger = logging.getLogger(__name__) |
|
|
|
|
| |
| |
| |
|
|
| def init_quality_tables(): |
| with db() as conn: |
| conn.executescript(""" |
| CREATE TABLE IF NOT EXISTS data_quality ( |
| id INTEGER PRIMARY KEY AUTOINCREMENT, |
| source TEXT NOT NULL, |
| source_id INTEGER NOT NULL, |
| model_slug TEXT NOT NULL, |
| |
| -- Quality sub-scores (0-1, higher = better quality) |
| uniqueness REAL, -- 1.0 = totally unique, 0.0 = exact duplicate |
| bot_score REAL, -- 1.0 = definitely human, 0.0 = likely bot |
| credibility REAL, -- 1.0 = high-credibility source, 0.0 = low |
| specificity REAL, -- 1.0 = very specific about model, 0.0 = generic |
| |
| -- Composite |
| quality_score REAL, -- weighted average of sub-scores |
| is_flagged INTEGER DEFAULT 0, -- 1 = excluded from scoring |
| |
| -- Metadata |
| duplicate_of INTEGER, -- source_id of the original if duplicate |
| flag_reasons TEXT, -- JSON list of reasons |
| |
| computed_at TEXT NOT NULL DEFAULT (datetime('now')), |
| UNIQUE(source, source_id, model_slug) |
| ); |
| CREATE INDEX IF NOT EXISTS idx_dq_model ON data_quality(model_slug); |
| CREATE INDEX IF NOT EXISTS idx_dq_quality ON data_quality(quality_score); |
| """) |
|
|
|
|
| |
| |
| |
|
|
| def _text_hash(text: str) -> str: |
| """Normalize and hash text for exact duplicate detection.""" |
| normalized = re.sub(r'\s+', ' ', text.lower().strip()) |
| normalized = re.sub(r'https?://\S+', '', normalized) |
| normalized = re.sub(r'@\w+', '', normalized) |
| return hashlib.md5(normalized.encode()).hexdigest() |
|
|
|
|
| def _trigram_set(text: str) -> set: |
| """Character trigrams for near-duplicate detection.""" |
| text = re.sub(r'\s+', ' ', text.lower().strip()) |
| if len(text) < 3: |
| return set() |
| return {text[i:i+3] for i in range(len(text) - 2)} |
|
|
|
|
| def _jaccard_similarity(set_a: set, set_b: set) -> float: |
| if not set_a or not set_b: |
| return 0.0 |
| intersection = len(set_a & set_b) |
| union = len(set_a | set_b) |
| return intersection / union if union > 0 else 0.0 |
|
|
|
|
| def compute_uniqueness(texts: list[dict]) -> dict[tuple, float]: |
| """ |
| Score uniqueness for each text. |
| Returns {(source, source_id, model_slug): uniqueness_score} |
| """ |
| |
| hash_map: dict[str, tuple] = {} |
| trigram_map: dict[tuple, set] = {} |
| results = {} |
|
|
| for t in texts: |
| key = (t["source"], t["source_id"], t["model_slug"]) |
| text = t["text"] or "" |
| h = _text_hash(text) |
| trigrams = _trigram_set(text) |
| trigram_map[key] = trigrams |
|
|
| if h in hash_map: |
| |
| results[key] = 0.0 |
| else: |
| hash_map[h] = key |
| results[key] = 1.0 |
|
|
| |
| |
| unique_keys = [k for k, v in results.items() if v > 0] |
| recent = unique_keys[-500:] |
|
|
| for i, key in enumerate(unique_keys): |
| if results[key] == 0.0: |
| continue |
| tri_a = trigram_map.get(key, set()) |
| if not tri_a: |
| continue |
|
|
| max_sim = 0 |
| for other_key in recent[max(0, i-50):i]: |
| if other_key == key: |
| continue |
| tri_b = trigram_map.get(other_key, set()) |
| sim = _jaccard_similarity(tri_a, tri_b) |
| max_sim = max(max_sim, sim) |
|
|
| if max_sim > 0.85: |
| results[key] = 1.0 - max_sim |
| else: |
| results[key] = 1.0 |
|
|
| return results |
|
|
|
|
| |
| |
| |
|
|
| GENERIC_PATTERNS = [ |
| r"^.{0,15}$", |
| r"(check out|click here|visit|buy now|discount|promo)", |
| r"^(yes|no|true|false|ok|thanks|same|agreed|this)\.?$", |
| r"(.)\1{5,}", |
| r"([\U0001F600-\U0001F9FF]){4,}", |
| ] |
|
|
| BOT_TEMPLATES = [ |
| r"i asked (chatgpt|claude|gemini) (to|about)", |
| r"here'?s what .+ said", |
| r"^thread:?\s*\d+/", |
| ] |
|
|
|
|
| def compute_bot_scores(texts: list[dict]) -> dict[tuple, float]: |
| """Score how likely each text is from a real human (1.0) vs bot (0.0).""" |
| |
| author_posts: dict[str, list] = defaultdict(list) |
| for t in texts: |
| author = t.get("author") or "anonymous" |
| author_posts[author].append(t) |
|
|
| results = {} |
| for t in texts: |
| key = (t["source"], t["source_id"], t["model_slug"]) |
| text = t["text"] or "" |
| author = t.get("author") or "anonymous" |
| score = 1.0 |
| reasons = [] |
|
|
| |
| for pattern in GENERIC_PATTERNS: |
| if re.search(pattern, text.lower()): |
| score -= 0.3 |
| reasons.append("generic_content") |
| break |
|
|
| |
| for pattern in BOT_TEMPLATES: |
| if re.search(pattern, text.lower()): |
| score -= 0.2 |
| reasons.append("bot_template") |
| break |
|
|
| |
| author_count = len(author_posts.get(author, [])) |
| if author_count > 50: |
| score -= 0.4 |
| reasons.append("high_frequency_author") |
| elif author_count > 20: |
| score -= 0.2 |
| reasons.append("frequent_author") |
|
|
| |
| if len(text) < 30: |
| score -= 0.15 |
| reasons.append("very_short") |
|
|
| results[key] = max(score, 0.0) |
|
|
| return results |
|
|
|
|
| |
| |
| |
|
|
| |
| PLATFORM_CREDIBILITY = { |
| "stackoverflow": 0.90, |
| "hn": 0.85, |
| "github_disc": 0.85, |
| "devto": 0.70, |
| "mastodon": 0.65, |
| "lemmy": 0.65, |
| "v2ex": 0.70, |
| "reddit": 0.60, |
| "bluesky": 0.55, |
| } |
|
|
|
|
| def compute_credibility(texts: list[dict]) -> dict[tuple, float]: |
| """Score source credibility per text.""" |
| results = {} |
| for t in texts: |
| key = (t["source"], t["source_id"], t["model_slug"]) |
| base = PLATFORM_CREDIBILITY.get(t["source"], 0.5) |
|
|
| |
| engagement = t.get("engagement", 0) |
| if engagement > 5: |
| base = min(base + 0.1, 1.0) |
| elif engagement > 20: |
| base = min(base + 0.2, 1.0) |
|
|
| results[key] = base |
|
|
| return results |
|
|
|
|
| |
| |
| |
|
|
| SPECIFIC_TERMS = [ |
| |
| r"(context window|token|latency|throughput|ttft|tps)", |
| r"(api|endpoint|rate limit|pricing|cost per|million tokens)", |
| r"(benchmark|eval|score|elo|mmlu|humaneval|arena)", |
| r"(hallucin|accuracy|quality|performance|speed|slow|fast)", |
| r"(fine-?tun|rlhf|dpo|rag|function call|tool use)", |
| r"(version|update|release|v\d|model card)", |
| r"(parameter|weight|quantiz|gguf|fp16|int8)", |
| r"\b\d+[bB]\b", |
| r"\$[\d.]+", |
| ] |
|
|
|
|
| def compute_specificity(texts: list[dict]) -> dict[tuple, float]: |
| """Score how specific each text is about LLM details (vs generic chatter).""" |
| results = {} |
| for t in texts: |
| key = (t["source"], t["source_id"], t["model_slug"]) |
| text = t["text"] or "" |
| text_lower = text.lower() |
|
|
| matches = sum(1 for p in SPECIFIC_TERMS if re.search(p, text_lower)) |
| |
| score = min(0.3 + matches * 0.25, 1.0) |
| results[key] = score |
|
|
| return results |
|
|
|
|
| |
| |
| |
|
|
| def run_quality_scoring() -> dict: |
| conn = get_connection() |
| init_quality_tables() |
|
|
| |
| rows = conn.execute(""" |
| SELECT source, source_id, model_slug, text_preview, engagement_weight |
| FROM sentiment_scores |
| """).fetchall() |
|
|
| texts = [{"source": r[0], "source_id": r[1], "model_slug": r[2], |
| "text": r[3], "engagement": r[4] or 0} for r in rows] |
|
|
| if not texts: |
| conn.close() |
| return {"total": 0} |
|
|
| logger.info("[quality] scoring %d texts...", len(texts)) |
|
|
| |
| uniqueness = compute_uniqueness(texts) |
| bot_scores = compute_bot_scores(texts) |
| credibility = compute_credibility(texts) |
| specificity = compute_specificity(texts) |
|
|
| |
| WEIGHTS = {"uniqueness": 0.30, "bot": 0.25, "credibility": 0.25, "specificity": 0.20} |
| flagged = 0 |
| total = 0 |
|
|
| with db() as wconn: |
| batch = [] |
| for t in texts: |
| key = (t["source"], t["source_id"], t["model_slug"]) |
| u = uniqueness.get(key, 1.0) |
| b = bot_scores.get(key, 1.0) |
| c = credibility.get(key, 0.5) |
| s = specificity.get(key, 0.5) |
|
|
| quality = (u * WEIGHTS["uniqueness"] + |
| b * WEIGHTS["bot"] + |
| c * WEIGHTS["credibility"] + |
| s * WEIGHTS["specificity"]) |
|
|
| is_flagged = 1 if quality < 0.3 else 0 |
| if is_flagged: |
| flagged += 1 |
|
|
| reasons = [] |
| if u < 0.3: reasons.append("duplicate") |
| if b < 0.5: reasons.append("bot_suspected") |
| if s < 0.4: reasons.append("too_generic") |
|
|
| batch.append(( |
| t["source"], t["source_id"], t["model_slug"], |
| u, b, c, s, quality, is_flagged, |
| json.dumps(reasons) if reasons else None, |
| )) |
| total += 1 |
|
|
| if len(batch) >= 200: |
| wconn.executemany(""" |
| INSERT OR REPLACE INTO data_quality |
| (source, source_id, model_slug, |
| uniqueness, bot_score, credibility, specificity, |
| quality_score, is_flagged, flag_reasons) |
| VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) |
| """, batch) |
| batch = [] |
|
|
| if batch: |
| wconn.executemany(""" |
| INSERT OR REPLACE INTO data_quality |
| (source, source_id, model_slug, |
| uniqueness, bot_score, credibility, specificity, |
| quality_score, is_flagged, flag_reasons) |
| VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) |
| """, batch) |
|
|
| conn.close() |
| logger.info("[quality] scored %d texts, flagged %d (%.1f%%) as low-quality", |
| total, flagged, flagged / max(total, 1) * 100) |
|
|
| return {"total": total, "flagged": flagged, "flagged_pct": flagged / max(total, 1) * 100} |
|
|
|
|
| if __name__ == "__main__": |
| logging.basicConfig(level=logging.INFO, |
| format="%(asctime)s [%(levelname)s] %(name)s — %(message)s") |
|
|
| import argparse |
| parser = argparse.ArgumentParser() |
| parser.add_argument("--stats", action="store_true") |
| args = parser.parse_args() |
|
|
| result = run_quality_scoring() |
| print(f"\nScored {result['total']} texts, flagged {result['flagged']} ({result['flagged_pct']:.1f}%)") |
|
|
| if args.stats: |
| conn = get_connection() |
| print("\n=== Quality Distribution ===") |
| for bucket in ["0.0-0.3 (flagged)", "0.3-0.5 (low)", "0.5-0.7 (medium)", "0.7-0.9 (good)", "0.9-1.0 (excellent)"]: |
| lo, hi = float(bucket.split("-")[0]), float(bucket.split("-")[1].split(" ")[0]) |
| n = conn.execute("SELECT COUNT(*) FROM data_quality WHERE quality_score >= ? AND quality_score < ?", (lo, hi)).fetchone()[0] |
| print(f" {bucket}: {n}") |
|
|
| print("\n=== Flagged by reason ===") |
| for r in conn.execute(""" |
| SELECT flag_reasons, COUNT(*) FROM data_quality |
| WHERE is_flagged = 1 AND flag_reasons IS NOT NULL |
| GROUP BY flag_reasons ORDER BY COUNT(*) DESC LIMIT 10 |
| """).fetchall(): |
| print(f" {r[0]}: {r[1]}") |
|
|
| print("\n=== Quality by source ===") |
| for r in conn.execute(""" |
| SELECT source, COUNT(*), ROUND(AVG(quality_score),3), |
| SUM(is_flagged), ROUND(SUM(is_flagged)*100.0/COUNT(*),1) |
| FROM data_quality GROUP BY source ORDER BY AVG(quality_score) DESC |
| """).fetchall(): |
| print(f" {r[0]:<20} n={r[1]:<5} avg_quality={r[2]} flagged={r[3]} ({r[4]}%)") |
|
|