---
type: "Source File"
title: "\"\"\"Deterministic URL and story identity helpers shared by CopeCheck pipelines."
description: "\"\"\"Deterministic URL and story identity helpers shared by CopeCheck pipelines. The identity deliberately contains no ingestion-channel prefix. A publisher URL discovered by RSS, Google News, Brave, or a user submission."
resource: "https://uk.copecheck.com"
tags: ["copecheck", "uk", "source-file", "py"]
timestamp: "2026-08-25T12:01:42Z"
site: "uk"
source_path: "copecheck-uk/canonical_identity.py"
---

# """Deterministic URL and story identity helpers shared by CopeCheck pipelines.

Source path: `copecheck-uk/canonical_identity.py`  
Index snapshot generated: `2026-11-24T13:42:54Z`  
File modified: `2026-08-25T12:01:42Z`

```py
"""Deterministic URL and story identity helpers shared by CopeCheck pipelines.

The identity deliberately contains no ingestion-channel prefix.  A publisher
URL discovered by RSS, Google News, Brave, or a user submission must resolve
to the same key.
"""
from __future__ import annotations

import hashlib
import html
import re
import unicodedata
from difflib import SequenceMatcher
from urllib.parse import parse_qsl, quote, unquote, urlencode, urlsplit, urlunsplit


TRACKING_KEYS = {
    "fbclid", "gclid", "dclid", "msclkid", "twclid", "ttclid",
    "mc_cid", "mc_eid", "mkt_tok", "igshid", "vero_conv", "vero_id",
    "cmpid", "ocid", "taid", "smid", "guccounter", "guce_referrer",
    "guce_referrer_sig", "ito",
}


def _is_tracking_param(key: str, value: str) -> bool:
    lower = key.lower()
    if lower.startswith(("utm_", "pk_", "wt_")):
        return True
    if lower in TRACKING_KEYS:
        return True
    # Economic Times uses this solely for its mobile/desktop referral view.
    if lower == "from" and value.lower() in {"mdr", "desktop", "mobile"}:
        return True
    return False


def canonical_url(url: str | None) -> str:
    """Return a conservative publisher URL identity.

    Fragments, default ports, presentation-only mobile/AMP forms, and
    unambiguous tracking parameters are removed.  Semantic query parameters
    such as article IDs are retained.
    """
    raw = html.unescape(str(url or "")).strip()
    if not raw:
        return ""
    if raw.startswith("//"):
        raw = "https:" + raw
    if "://" not in raw:
        raw = "https://" + raw.lstrip("/")
    try:
        parts = urlsplit(raw)
    except ValueError:
        return raw

    host = (parts.hostname or "").lower().rstrip(".")
    path = parts.path or "/"
    query_pairs = parse_qsl(parts.query, keep_blank_values=True)

    # Unwrap ordinary Google redirect links.  Opaque news.google.com RSS
    # article IDs cannot be decoded safely and remain their own canonical URL;
    # their story-level duplicate is caught by the event fingerprint.
    if host in {"google.com", "www.google.com"} and path.rstrip("/") == "/url":
        redirect = next((value for key, value in query_pairs if key in {"url", "q"}), "")
        if redirect.startswith(("http://", "https://")):
            return canonical_url(redirect)

    for prefix in ("www.", "m.", "amp."):
        if host.startswith(prefix) and host.count(".") >= 2:
            host = host[len(prefix):]
            break
    try:
        port = parts.port
    except ValueError:
        port = None
    if port and port not in {80, 443}:
        host = f"{host}:{port}"

    path = re.sub(r"/{2,}", "/", unquote(path))
    path = re.sub(r"/comment-page-\d+/?$", "", path, flags=re.IGNORECASE)
    path = re.sub(r"/(?:amp|amp/)$", "", path, flags=re.IGNORECASE)
    if path != "/":
        path = path.rstrip("/")
    path = quote(path or "/", safe="/%:@!$&'()*+,;=-._~")

    kept = [
        (key, value)
        for key, value in query_pairs
        if not _is_tracking_param(key, value)
    ]
    kept.sort(key=lambda item: (item[0].lower(), item[1]))
    query = urlencode(kept, doseq=True)
    # HTTP/HTTPS variants are one publisher resource for dedupe purposes.
    return urlunsplit(("https", host, path, query, ""))


def canonical_url_hash(url: str | None) -> str:
    value = canonical_url(url)
    return hashlib.sha256(value.encode("utf-8")).hexdigest()[:32] if value else ""


def normalise_text(value: str | None) -> str:
    text = unicodedata.normalize("NFKC", html.unescape(str(value or ""))).lower()
    text = re.sub(r"https?://\S+", " ", text)
    text = re.sub(r"[^a-z0-9%]+", " ", text)
    return re.sub(r"\s+", " ", text).strip()


[redacted secret-like line]
[redacted secret-like line]


SEMANTIC_STOPWORDS = {
    "the", "and", "for", "that", "this", "with", "from", "into", "all",
    "at", "in", "on", "of", "to", "a", "an", "is", "are", "was", "were",
    "says", "said", "believes", "believe", "predicts", "predict", "according",
}


[redacted secret-like line]
    text = unicodedata.normalize("NFKC", html.unescape(str(value or ""))).lower()
    text = text.replace("’", "'").replace("‘", "'")
    replacements = (
        (r"\b(?:won't|wont|won\s+t)\b", "not"),
        (r"\bartificial intelligence\b", "ai"),
        (r"\b(?:humans|human beings|persons)\b", "people"),
        (r"\btwo decades\b", "20 years"),
        (r"\b(?:need|have) to work\b", "work"),
        (r"\b(?:inside|within)\b", "in"),
        (r"\bjob (?:cuts|losses)\b|\blayoffs?\b", "jobloss"),
        (r"\bchief executives?\b", "ceo"),
    )
    for pattern, replacement in replacements:
        text = re.sub(pattern, replacement, text)
[redacted secret-like line]
[redacted secret-like line]


def _semantic_jaccard(left: str, right: str) -> tuple[float, int]:
[redacted secret-like line]
    if not a or not b:
        return 0.0, 0
    common = len(a & b)
    return common / len(a | b), common


def _jaccard(left: str, right: str) -> float:
[redacted secret-like line]
    if not a or not b:
        return 0.0
    return len(a & b) / len(a | b)


def _numbers(value: str) -> set[str]:
    return set(re.findall(r"\b\d+(?:\.\d+)?%?\b", normalise_text(value)))


def exact_statement_match(title_a: str, quote_a: str,
                          title_b: str, quote_b: str) -> bool:
    """Match the same substantive statement even when resurfaced much later.

    Headlines can recur for periodic reports and continuing live pages, so a
    title-only match is intentionally left to the bounded fuzzy-event window.
    """
    left_quote, right_quote = normalise_text(quote_a), normalise_text(quote_b)
    if len(left_quote) >= 40 and left_quote == right_quote:
        return True
    shorter, longer = sorted((left_quote, right_quote), key=len)
    if len(shorter) >= 60 and len(shorter.split()) >= 10 and shorter in longer:
        return True
    return False


def same_event(
    *,
    canonical_a: str,
    title_a: str,
    quote_a: str,
    canonical_b: str,
    title_b: str,
    quote_b: str,
) -> bool:
    """Conservatively decide whether two observations are one story/event."""
    if canonical_a and canonical_a == canonical_b:
        return True
    title_a_n, title_b_n = normalise_text(title_a), normalise_text(title_b)
    quote_a_n, quote_b_n = normalise_text(quote_a), normalise_text(quote_b)

    # Conflicting quantities usually describe different claims.  Years alone
    # are ignored because syndicators often add or omit the publication year.
    nums_a = {n for n in _numbers(title_a_n + " " + quote_a_n) if not re.fullmatch(r"20\d{2}", n)}
    nums_b = {n for n in _numbers(title_b_n + " " + quote_b_n) if not re.fullmatch(r"20\d{2}", n)}
    if nums_a and nums_b and nums_a.isdisjoint(nums_b):
        return False

    if len(title_a_n) >= 24 and title_a_n == title_b_n:
        return True
    if len(quote_a_n) >= 40 and quote_a_n == quote_b_n:
        return True

    title_ratio = SequenceMatcher(None, title_a_n, title_b_n).ratio() if title_a_n and title_b_n else 0.0
    quote_ratio = SequenceMatcher(None, quote_a_n, quote_b_n).ratio() if quote_a_n and quote_b_n else 0.0
    title_j = _jaccard(title_a_n, title_b_n)
    quote_j = _jaccard(quote_a_n, quote_b_n)
    semantic_quote_j, semantic_quote_common = _semantic_jaccard(quote_a_n, quote_b_n)
    semantic_title_j, semantic_title_common = _semantic_jaccard(title_a_n, title_b_n)
    if len(title_a_n) >= 30 and (title_ratio >= 0.90 or title_j >= 0.82):
        return True
    if len(quote_a_n) >= 50 and (quote_ratio >= 0.88 or quote_j >= 0.78):
        return True
    if semantic_quote_common >= 4 and semantic_quote_j >= 0.62:
        return True
    if semantic_title_common >= 6 and semantic_title_j >= 0.72:
        return True
    return title_j >= 0.64 and quote_j >= 0.60


def new_event_fingerprint(
    figure_id: str,
    source_title: str | None,
    quote_text: str | None,
    observed_date: str,
) -> str:
    """Create a stable candidate key; transaction-time matching may reuse one."""
    title = normalise_text(source_title)
    quote_text = normalise_text(quote_text)
    signature = quote_text if len(quote_text.split()) >= 6 else title
    basis = "\n".join((figure_id, signature, str(observed_date)[:10]))
    return hashlib.sha256(basis.encode("utf-8")).hexdigest()[:32]


def provenance_key(canonical: str, source_title: str, quote_text: str) -> str:
    # Include both resource identity and observation text.  Using only the
    # event's representative key would erase distinct publisher provenance.
    basis = "\n".join((
        canonical or "",
        normalise_text(source_title),
        normalise_text(quote_text),
    ))
    return hashlib.sha256(basis.encode("utf-8")).hexdigest()[:32]
```
