| 1 | """Within-source near-duplicate detection.""" |
| 2 | |
| 3 | from __future__ import annotations |
| 4 | |
| 5 | import re |
| 6 | |
| 7 | from . import cjk, fusion, reddit_refs, rust_accel, schema |
| 8 | |
| 9 | STOPWORDS = frozenset( |
| 10 | { |
| 11 | "the", |
| 12 | "a", |
| 13 | "an", |
| 14 | "to", |
| 15 | "for", |
| 16 | "how", |
| 17 | "is", |
| 18 | "in", |
| 19 | "of", |
| 20 | "on", |
| 21 | "and", |
| 22 | "with", |
| 23 | "from", |
| 24 | "by", |
| 25 | "at", |
| 26 | "this", |
| 27 | "that", |
| 28 | "it", |
| 29 | "what", |
| 30 | "are", |
| 31 | "do", |
| 32 | "can", |
| 33 | } |
| 34 | ) | cjk.CHINESE_STOPWORDS |
| 35 | |
| 36 | |
| 37 | def normalize_text(text: str) -> str: |
| 38 | text = re.sub(r"[^\w\s]", " ", text.lower()) |
| 39 | return re.sub(r"\s+", " ", text).strip() |
| 40 | |
| 41 | |
| 42 | def _ngrams_of_normalized(norm: str, n: int = 3) -> set[str]: |
| 43 | if len(norm) < n: |
| 44 | return {norm} if norm else set() |
| 45 | return {norm[index:index + n] for index in range(len(norm) - n + 1)} |
| 46 | |
| 47 | |
| 48 | def get_ngrams(text: str, n: int = 3) -> set[str]: |
| 49 | return _ngrams_of_normalized(normalize_text(text), n) |
| 50 | |
| 51 | |
| 52 | def jaccard_similarity(left: set[str], right: set[str]) -> float: |
| 53 | if not left or not right: |
| 54 | return 0.0 |
| 55 | union = left | right |
| 56 | if not union: |
| 57 | return 0.0 |
| 58 | return len(left & right) / len(union) |
| 59 | |
| 60 | |
| 61 | def token_jaccard(text_a: str, text_b: str) -> float: |
| 62 | tokens_a = { |
| 63 | token |
| 64 | for token in cjk.segment(normalize_text(text_a)) |
| 65 | if len(token) > 1 and token not in STOPWORDS |
| 66 | } |
| 67 | tokens_b = { |
| 68 | token |
| 69 | for token in cjk.segment(normalize_text(text_b)) |
| 70 | if len(token) > 1 and token not in STOPWORDS |
| 71 | } |
| 72 | return jaccard_similarity(tokens_a, tokens_b) |
| 73 | |
| 74 | |
| 75 | def hybrid_similarity(text_a: str, text_b: str) -> float: |
| 76 | return max( |
| 77 | jaccard_similarity(get_ngrams(text_a), get_ngrams(text_b)), |
| 78 | token_jaccard(text_a, text_b), |
| 79 | ) |
| 80 | |
| 81 | |
| 82 | def _tokenize(normalized: str) -> frozenset[str]: |
| 83 | return frozenset( |
| 84 | tok for tok in cjk.segment(normalized) |
| 85 | if len(tok) > 1 and tok not in STOPWORDS |
| 86 | ) |
| 87 | |
| 88 | |
| 89 | class _PreparedText: |
| 90 | """Pre-computed text representations for fast repeated similarity checks.""" |
| 91 | |
| 92 | __slots__ = ("ngrams", "tokens") |
| 93 | |
| 94 | def __init__(self, raw: str) -> None: |
| 95 | norm = normalize_text(raw) |
| 96 | self.ngrams = _ngrams_of_normalized(norm) |
| 97 | self.tokens = _tokenize(norm) |
| 98 | |
| 99 | |
| 100 | def prepared_similarity(a: _PreparedText, b: _PreparedText) -> float: |
| 101 | return max( |
| 102 | jaccard_similarity(a.ngrams, b.ngrams), |
| 103 | jaccard_similarity(a.tokens, b.tokens), |
| 104 | ) |
| 105 | |
| 106 | |
| 107 | def item_text(item: schema.SourceItem) -> str: |
| 108 | parts = [item.title, item.body, item.author or "", item.container or ""] |
| 109 | return " ".join(part for part in parts if part).strip() |
| 110 | |
| 111 | |
| 112 | def _url_dedupe_key( |
| 113 | item: schema.SourceItem, |
| 114 | *, |
| 115 | polymarket_eids_by_url: dict[str, set[str]] | None = None, |
| 116 | ) -> tuple[str, str] | None: |
| 117 | """Normalized ``(source, identity_url)`` for exact-URL deduplication, or None.""" |
| 118 | if item.source == "hackernews": |
| 119 | hn_url = (item.metadata or {}).get("hn_url") |
| 120 | if hn_url and str(hn_url).strip(): |
| 121 | return (item.source, fusion._normalize_url(str(hn_url))) |
| 122 | if item.source == "polymarket": |
| 123 | poly_key = fusion.polymarket_url_key(item, polymarket_eids_by_url) |
| 124 | return (item.source, poly_key) if poly_key is not None else None |
| 125 | url = (item.url or "").strip() |
| 126 | if not url: |
| 127 | return None |
| 128 | if item.source == "reddit": |
| 129 | thread = reddit_refs.thread_key(url) |
| 130 | if thread: |
| 131 | return (item.source, thread) |
| 132 | return (item.source, fusion._normalize_url(url)) |
| 133 | |
| 134 | |
| 135 | def _is_url_only_dedupe( |
| 136 | item: schema.SourceItem, |
| 137 | conflicted_poly_urls: set[str] | None = None, |
| 138 | ) -> bool: |
| 139 | if item.source == "jobs": |
| 140 | return True |
| 141 | if item.source == "polymarket": |
| 142 | if (item.metadata or {}).get("matched_market"): |
| 143 | return True |
| 144 | if conflicted_poly_urls and item.url: |
| 145 | return fusion._normalize_url(item.url) in conflicted_poly_urls |
| 146 | return False |
| 147 | |
| 148 | |
| 149 | def dedupe_items(items: list[schema.SourceItem], threshold: float = 0.7) -> list[schema.SourceItem]: |
| 150 | """Remove exact-URL and near-duplicate items while keeping earlier, better-scored items. |
| 151 | |
| 152 | Every source first collapses normalized ``(source, url)`` duplicates (using |
| 153 | ``hn_url`` for Hacker News and canonical ``thread_key`` for Reddit), merging |
| 154 | enrichment, engagement, and metadata from later copies into the first |
| 155 | occurrence before text similarity runs so a bare copy never discards a |
| 156 | saved copy's transcripts, comments, or ``matched_market``. |
| 157 | |
| 158 | Jobs are deduped by normalized URL only: distinct postings on the same |
| 159 | careers board share heavy boilerplate (company intro, "TL;DR", benefits) |
| 160 | that trips fuzzy text similarity and collapses unrelated roles (a 26-role |
| 161 | board fell to 7). A unique posting URL is an unambiguous identity, so use |
| 162 | it instead. |
| 163 | |
| 164 | Polymarket events that carry a matched market are deduped by normalized |
| 165 | event URL only for the same reason: "Pro Football: 2027 Champion" and |
| 166 | "Pro Football: 2027 NFC Champion" share most of their text but are |
| 167 | different questions. Unmatched Polymarket items share the same URL pass so |
| 168 | mixed matched/unmatched copies of one event merge and never survive together. |
| 169 | """ |
| 170 | # Pass 1: collapse exact normalized-URL duplicates in-order, merging |
| 171 | # enrichment/counts/metadata from later copies without mutating caller inputs. |
| 172 | # Reused Polymarket slug URLs carrying distinct known event_ids (and ID-less |
| 173 | # copies at those URLs) get disjoint keys so conflicting events never merge |
| 174 | # or bridge through an ID-less copy. |
| 175 | poly_eids = fusion.polymarket_event_ids_by_url(items) |
| 176 | conflicted_poly_urls = {url for url, eids in poly_eids.items() if len(eids) > 1} |
| 177 | url_index: dict[tuple[str, str], int] = {} |
| 178 | cloned_indices: set[int] = set() |
| 179 | collapsed: list[schema.SourceItem] = [] |
| 180 | for item in items: |
| 181 | url_key = _url_dedupe_key(item, polymarket_eids_by_url=poly_eids) |
| 182 | if url_key is None: |
| 183 | collapsed.append(item) |
| 184 | continue |
| 185 | existing_idx = url_index.get(url_key) |
| 186 | if existing_idx is None: |
| 187 | url_index[url_key] = len(collapsed) |
| 188 | collapsed.append(item) |
| 189 | continue |
| 190 | if existing_idx not in cloned_indices: |
| 191 | collapsed[existing_idx] = fusion._clone_source_item(collapsed[existing_idx]) |
| 192 | cloned_indices.add(existing_idx) |
| 193 | fusion.merge_source_items(collapsed[existing_idx], item) |
| 194 | |
| 195 | # Pass 2: fuzzy near-duplicate removal on remaining distinct-URL items. |
| 196 | mode = rust_accel.engine_mode() |
| 197 | use_rust = mode == "rust" or (mode == "auto" and len(collapsed) >= 12) |
| 198 | if use_rust: |
| 199 | entries: list[dict[str, str]] = [] |
| 200 | has_jieba_cjk = False |
| 201 | jieba_active = cjk._jieba is not None |
| 202 | for item in collapsed: |
| 203 | if _is_url_only_dedupe(item, conflicted_poly_urls): |
| 204 | entries.append({"mode": "url_only", "text": ""}) |
| 205 | else: |
| 206 | text = item_text(item) |
| 207 | if jieba_active and cjk.has_cjk(text): |
| 208 | has_jieba_cjk = True |
| 209 | break |
| 210 | entries.append({"mode": "fuzzy", "text": text}) |
| 211 | if not has_jieba_cjk: |
| 212 | kept_indices = rust_accel.dedupe_kept_indices(entries, threshold) |
| 213 | if kept_indices is not None: |
| 214 | return [collapsed[idx] for idx in kept_indices] |
| 215 | |
| 216 | kept: list[schema.SourceItem] = [] |
| 217 | kept_prepared: list[_PreparedText] = [] |
| 218 | for item in collapsed: |
| 219 | if _is_url_only_dedupe(item, conflicted_poly_urls): |
| 220 | kept.append(item) |
| 221 | continue |
| 222 | text = item_text(item) |
| 223 | if not text: |
| 224 | kept.append(item) |
| 225 | continue |
| 226 | prep = _PreparedText(text) |
| 227 | is_duplicate = False |
| 228 | for existing_prep in kept_prepared: |
| 229 | if prepared_similarity(prep, existing_prep) >= threshold: |
| 230 | is_duplicate = True |
| 231 | break |
| 232 | if not is_duplicate: |
| 233 | kept.append(item) |
| 234 | kept_prepared.append(prep) |
| 235 | return kept |
| 236 |