Datasets:
File size: 9,384 Bytes
e1ced61 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 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 | """Per-item fingerprints for decontamination (``docs/02_DATA_PIPELINE.md`` §5).
Each normalized item is reduced to a set of fingerprints that support exact and
fuzzy matching against the frozen evaluation registry:
- exact identity: ``base_id``, ``source``/``native_id``, raw ``question_sha256``,
``choices_sha256``, per-image ``image_sha256``
- canonical question SHA-256: NFKC + lowercase + whitespace collapse
- 64-bit perceptual hash (pHash) per image
- 128-permutation MinHash over question *character* 5-grams
- 128-permutation MinHash over choice *character* 5-grams
- 128-permutation MinHash over OCR *token* 5-grams (populated by the P5 OCR pass;
left empty at P3 — OCR extraction requires the PaddleOCR service)
The original model input is never normalized: only a fingerprint *copy* is
(``docs/02`` §5.1). MinHash is hand-rolled rather than delegated to ``datasketch``
so the signature is a pure function of the seed and the shingles — no dependency
on Python's process-salted ``hash`` — which is what makes the allowlist
byte-identical for a fixed seed/input (``docs/07`` §5 completion condition).
"""
from __future__ import annotations
import hashlib
import json
import unicodedata
from collections.abc import Callable, Mapping, Sequence
from dataclasses import asdict, dataclass, field
from pathlib import Path
from typing import Any
import numpy as np
from PIL import Image
from ..hashing import sha256_text
# --- MinHash ---------------------------------------------------------------
MINHASH_PERMUTATIONS = 128
# Fixed seed: changing it changes every signature and every allowlist byte.
# Frozen before the pilot per docs/02 §5.3 ("threshold는 결과를 보고 조정하지
# 않고 pilot 전에 config로 동결한다"); the seed is part of that freeze.
MINHASH_SEED = 20260728
# 2**61 - 1, the Mersenne prime used for (a*x + b) mod p MinHash permutations.
_MERSENNE_PRIME = (1 << 61) - 1
CHAR_NGRAM = 5
TOKEN_NGRAM = 5
def _permutations(num: int, seed: int) -> tuple[tuple[int, ...], tuple[int, ...]]:
"""Deterministic ``(a, b)`` permutation coefficients for ``num`` hashes."""
rng = np.random.default_rng(seed)
a = rng.integers(1, _MERSENNE_PRIME, size=num)
b = rng.integers(0, _MERSENNE_PRIME, size=num)
return tuple(int(x) for x in a), tuple(int(x) for x in b)
_A, _B = _permutations(MINHASH_PERMUTATIONS, MINHASH_SEED)
def _shingle_hash(shingle: str) -> int:
"""Deterministic 64-bit hash of one shingle (SHA-1 prefix, not Python hash)."""
digest = hashlib.sha1(shingle.encode("utf-8")).digest()
return int.from_bytes(digest[:8], "big")
def char_ngrams(text: str, n: int = CHAR_NGRAM) -> list[str]:
"""Character n-grams of ``text`` (short text yields one short shingle)."""
if not text:
return []
if len(text) <= n:
return [text]
return [text[i : i + n] for i in range(len(text) - n + 1)]
def token_ngrams(tokens: Sequence[str], n: int = TOKEN_NGRAM) -> list[str]:
"""Token n-grams joined by NUL (few tokens yield one joined shingle)."""
if not tokens:
return []
if len(tokens) <= n:
return ["\0".join(tokens)]
return ["\0".join(tokens[i : i + n]) for i in range(len(tokens) - n + 1)]
def minhash_signature(shingles: Sequence[str]) -> tuple[int, ...]:
"""128-permutation MinHash signature over ``shingles``.
An empty shingle set yields an empty signature (treated as Jaccard 0 against
anything, never a false near-dup).
"""
if not shingles:
return ()
hashes = [_shingle_hash(s) for s in shingles]
signature = [int(_MERSENNE_PRIME)] * MINHASH_PERMUTATIONS
for token_hash in hashes:
for i in range(MINHASH_PERMUTATIONS):
value = (_A[i] * token_hash + _B[i]) % _MERSENNE_PRIME
if value < signature[i]:
signature[i] = value
return tuple(signature)
def estimated_jaccard(sig_a: Sequence[int], sig_b: Sequence[int]) -> float:
"""Fraction of matching signature positions (0.0 if either is empty)."""
if not sig_a or not sig_b:
return 0.0
matches = sum(1 for x, y in zip(sig_a, sig_b, strict=True) if x == y)
return matches / len(sig_a)
# --- text normalization ----------------------------------------------------
def canonical_question(text: str) -> str:
"""NFKC, lowercase, whitespace collapse (``docs/02`` §5.1)."""
normalized = unicodedata.normalize("NFKC", text)
normalized = " ".join(normalized.split())
return normalized.lower()
def canonical_question_sha256(text: str) -> str:
return sha256_text(canonical_question(text))
def choice_text(choices: Sequence[Mapping[str, Any]]) -> str:
"""Concatenated choice text in source order (the choice fingerprint input)."""
return " ".join(str(c.get("text", "")) for c in choices)
# --- pHash -----------------------------------------------------------------
def phash_hex(image_path: str | Path) -> str:
"""64-bit perceptual hash of an image as 16 hex chars (``imagehash``)."""
with Image.open(Path(image_path)) as image:
# imagehash.phash is a deterministic DCT over a 32x32 grayscale resize;
# hash_size=8 yields 64 bits.
from imagehash import phash
return str(phash(image, hash_size=8))
def phash_hamming(a_hex: str, b_hex: str) -> int:
"""Hamming distance between two pHash hex strings (``imagehash``)."""
from imagehash import hex_to_hash
return int(hex_to_hash(a_hex) - hex_to_hash(b_hex))
# --- one item's fingerprints ----------------------------------------------
@dataclass(frozen=True)
class Fingerprints:
"""All fingerprints for one normalized item or registry row."""
base_id: str
source: str
source_revision: str
config: str
split: str
native_id: str
policy: str
question_sha256: str
choices_sha256: str
question_canonical_sha256: str
image_sha256: tuple[str, ...]
image_phash: tuple[str, ...]
question_minhash: tuple[int, ...]
choice_minhash: tuple[int, ...]
ocr_minhash: tuple[int, ...] = ()
derived_from_eval: bool = False
raw: dict[str, Any] = field(default_factory=dict)
def to_record(self) -> dict[str, Any]:
record = asdict(self)
record["image_sha256"] = list(self.image_sha256)
record["image_phash"] = list(self.image_phash)
record["question_minhash"] = list(self.question_minhash)
record["choice_minhash"] = list(self.choice_minhash)
record["ocr_minhash"] = list(self.ocr_minhash)
return record
def _choices_of(row: Mapping[str, Any]) -> list[dict[str, Any]]:
choices = row.get("choices") or []
out: list[dict[str, Any]] = []
for choice in choices:
if isinstance(choice, Mapping):
out.append({"key": str(choice.get("key", "")), "text": str(choice.get("text", ""))})
else:
out.append({"key": "", "text": str(choice)})
return out
def fingerprint_row(
row: Mapping[str, Any],
*,
resolve_image: Callable[[str], str | Path] | None = None,
) -> Fingerprints:
"""Compute fingerprints for one normalized item or registry row.
``resolve_image`` maps an ``image_paths`` entry to an image file. When it is
``None`` (e.g. the frozen registry, which carries only ``image_sha256`` and
no pixels), pHash is skipped and only the text/exact fingerprints are
produced.
"""
base_id = str(row["base_id"])
question = str(row.get("question", ""))
choices = _choices_of(row)
image_paths: list[str] = list(row.get("image_paths", []) or [])
image_sha256: tuple[str, ...] = tuple(row.get("image_sha256", []) or [])
image_phash: tuple[str, ...] = ()
if resolve_image is not None and image_paths:
image_phash = tuple(phash_hex(resolve_image(p)) for p in image_paths)
provenance = row.get("provenance") or {}
derived = bool(provenance.get("derived_from_eval", False))
return Fingerprints(
base_id=base_id,
source=str(row.get("source", "")),
source_revision=str(row.get("source_revision", "")),
config=str(row.get("source_config", row.get("config", ""))),
split=str(row.get("source_split", row.get("split", ""))),
native_id=str(row.get("source_native_id", row.get("native_id", ""))),
policy=str(row.get("policy", "")),
question_sha256=str(row.get("question_sha256", sha256_text(question))),
choices_sha256=str(row.get("choices_sha256", "")),
question_canonical_sha256=canonical_question_sha256(question) if question else "",
image_sha256=image_sha256,
image_phash=image_phash,
question_minhash=minhash_signature(char_ngrams(canonical_question(question))),
choice_minhash=minhash_signature(char_ngrams(canonical_question(choice_text(choices)))),
ocr_minhash=(),
derived_from_eval=derived,
raw=_compact_raw(row),
)
def _compact_raw(row: Mapping[str, Any]) -> dict[str, Any]:
"""A stable JSON-serializable copy of the source row for audit/rebuild."""
compacted: dict[str, Any] = json.loads(json.dumps(dict(row), sort_keys=True))
return compacted
def ocr_signature(ocr_text: str) -> tuple[int, ...]:
"""MinHash over OCR token 5-grams (called by the P5 OCR enrichment pass)."""
return minhash_signature(token_ngrams(ocr_text.split()))
|