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
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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
"""
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__)


# ═══════════════════════════════════════════════════════════════════════════════
# SCHEMA
# ═══════════════════════════════════════════════════════════════════════════════

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);
        """)


# ═══════════════════════════════════════════════════════════════════════════════
# 1. DUPLICATE DETECTION
# ═══════════════════════════════════════════════════════════════════════════════

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}
    """
    # Build hash → first occurrence map
    hash_map: dict[str, tuple] = {}  # hash → (source, source_id, model_slug)
    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:
            # Exact duplicate
            results[key] = 0.0
        else:
            hash_map[h] = key
            results[key] = 1.0  # provisional — check near-duplicates below

    # Near-duplicate check (only for texts that passed exact duplicate check)
    # Sample-based for performance — check against last 500 unique texts
    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]:  # check 50 nearest
            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  # near-duplicate: reduce score
        else:
            results[key] = 1.0

    return results


# ═══════════════════════════════════════════════════════════════════════════════
# 2. BOT / SPAM DETECTION
# ═══════════════════════════════════════════════════════════════════════════════

GENERIC_PATTERNS = [
    r"^.{0,15}$",                    # too short
    r"(check out|click here|visit|buy now|discount|promo)",  # spam
    r"^(yes|no|true|false|ok|thanks|same|agreed|this)\.?$",  # zero-content
    r"(.)\1{5,}",                    # repeated characters
    r"([\U0001F600-\U0001F9FF]){4,}",  # emoji spam
]

BOT_TEMPLATES = [
    r"i asked (chatgpt|claude|gemini) (to|about)",  # templated prompt sharing
    r"here'?s what .+ said",
    r"^thread:?\s*\d+/",              # automated thread numbering
]


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)."""
    # Track per-author posting frequency
    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 = []

        # Generic content check
        for pattern in GENERIC_PATTERNS:
            if re.search(pattern, text.lower()):
                score -= 0.3
                reasons.append("generic_content")
                break

        # Bot template check
        for pattern in BOT_TEMPLATES:
            if re.search(pattern, text.lower()):
                score -= 0.2
                reasons.append("bot_template")
                break

        # Author posting frequency (>20 posts in our data = suspicious)
        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")

        # Text length — very short texts have less signal
        if len(text) < 30:
            score -= 0.15
            reasons.append("very_short")

        results[key] = max(score, 0.0)

    return results


# ═══════════════════════════════════════════════════════════════════════════════
# 3. SOURCE CREDIBILITY SCORING
# ═══════════════════════════════════════════════════════════════════════════════

# Base credibility by platform (higher = more rigorous community)
PLATFORM_CREDIBILITY = {
    "stackoverflow": 0.90,   # heavily moderated, technical
    "hn": 0.85,              # curated, technical community
    "github_disc": 0.85,     # developer context
    "devto": 0.70,           # developer blogs, some SEO spam
    "mastodon": 0.65,        # smaller but genuine community
    "lemmy": 0.65,           # niche, genuine
    "v2ex": 0.70,            # chinese dev community, active moderation
    "reddit": 0.60,          # large, noisy, some bots
    "bluesky": 0.55,         # social media, high noise
}


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 bonus: highly engaged content is community-validated
        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


# ═══════════════════════════════════════════════════════════════════════════════
# 4. SPECIFICITY SCORING
# ═══════════════════════════════════════════════════════════════════════════════

SPECIFIC_TERMS = [
    # Model-specific technical 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",  # model sizes like "70B"
    r"\$[\d.]+",      # pricing mentions
]


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))
        # 0 matches = 0.3 (generic), 3+ matches = 1.0 (very specific)
        score = min(0.3 + matches * 0.25, 1.0)
        results[key] = score

    return results


# ═══════════════════════════════════════════════════════════════════════════════
# MAIN: Score all texts
# ═══════════════════════════════════════════════════════════════════════════════

def run_quality_scoring() -> dict:
    conn = get_connection()
    init_quality_tables()

    # Load all scored texts
    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))

    # Compute all sub-scores
    uniqueness = compute_uniqueness(texts)
    bot_scores = compute_bot_scores(texts)
    credibility = compute_credibility(texts)
    specificity = compute_specificity(texts)

    # Composite quality score
    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]}%)")