Download src/common.py from ElenaZhan/TrueSight_AI_Detection_with_Stability_Checks: direct link, hf CLI and curl.
- Browser
- Download file 20.7 kB
-
https://huggingface.co/spaces/ElenaZhan/TrueSight_AI_Detection_with_Stability_Checks/resolve/main/src/common.py
- Command line
-
hf download hf://spaces/ElenaZhan/TrueSight_AI_Detection_with_Stability_Checks/src/common.py
-
curl -L -o common.py https://huggingface.co/spaces/ElenaZhan/TrueSight_AI_Detection_with_Stability_Checks/resolve/main/src/common.py
20.7 kB
| """Shared helpers for the SID_Set data pipeline. | |
| Deliberately dependency-light: numpy + pillow + pyarrow + huggingface_hub only. | |
| scikit-learn / scipy / imagehash are NOT installed in the `techjam` env and must not be, | |
| so logistic regression, ROC AUC, rank statistics and the pHash DCT are implemented here. | |
| """ | |
| from __future__ import annotations | |
| import hashlib | |
| import io | |
| import json | |
| import threading | |
| import time | |
| from collections import OrderedDict | |
| from concurrent.futures import ThreadPoolExecutor | |
| from dataclasses import dataclass | |
| from pathlib import Path | |
| from typing import Callable, Iterator, Sequence | |
| import numpy as np | |
| import yaml | |
| from PIL import Image | |
| # Large synthetic images are legitimate here; disable the decompression-bomb guard. | |
| Image.MAX_IMAGE_PIXELS = None | |
| # -------------------------------------------------------------------------------------- | |
| # config / paths | |
| # -------------------------------------------------------------------------------------- | |
| def project_root() -> Path: | |
| """Repo root = parent of src/.""" | |
| return Path(__file__).resolve().parent.parent | |
| def load_config(path=None) -> dict: | |
| path = Path(path) if path else project_root() / "configs" / "data.yaml" | |
| with open(path, "r", encoding="utf-8") as fh: | |
| cfg = yaml.safe_load(fh) | |
| cfg["_root"] = str(project_root()) | |
| return cfg | |
| def rpath(cfg: dict, *parts: str) -> Path: | |
| """Resolve a config-relative path against the project root.""" | |
| return Path(cfg["_root"]).joinpath(*parts) | |
| def ensure_dir(p: Path) -> Path: | |
| p.mkdir(parents=True, exist_ok=True) | |
| return p | |
| # -------------------------------------------------------------------------------------- | |
| # stable hashing | |
| # | |
| # Python's builtin hash() is salted per process (PYTHONHASHSEED), so a split derived from it | |
| # silently changes between runs and between machines. That is an invisible train/test leak. | |
| # Everything that must be reproducible goes through md5. | |
| # -------------------------------------------------------------------------------------- | |
| def md5_int(*parts) -> int: | |
| h = hashlib.md5("\x1f".join(str(p) for p in parts).encode("utf-8")).hexdigest() | |
| return int(h, 16) | |
| def md5_unit(*parts) -> float: | |
| """Deterministic float in [0, 1).""" | |
| return (md5_int(*parts) % (1 << 53)) / float(1 << 53) | |
| def md5_rng(*parts) -> np.random.Generator: | |
| """Deterministic numpy Generator keyed on content, not on call order.""" | |
| return np.random.default_rng(md5_int(*parts) % (1 << 63)) | |
| def md5_order_key(*parts) -> str: | |
| """Sort key giving a fixed pseudo-random permutation of any id set.""" | |
| return hashlib.md5("\x1f".join(str(p) for p in parts).encode("utf-8")).hexdigest() | |
| # -------------------------------------------------------------------------------------- | |
| # image header probe (no pixel decode) | |
| # | |
| # CRITICAL: this must run on the RAW bytes. If the image is auto-decoded by `datasets`, | |
| # img.format becomes None and img.quantization disappears, and the audit silently reports | |
| # "no difference" when the difference is total. | |
| # -------------------------------------------------------------------------------------- | |
| def probe_header(raw: bytes): | |
| try: | |
| im = Image.open(io.BytesIO(raw)) | |
| w, h = im.size | |
| return { | |
| "format": im.format or "UNKNOWN", | |
| "mode": im.mode, | |
| "width": int(w), | |
| "height": int(h), | |
| "n_bytes": len(raw), | |
| "bytes_per_px": len(raw) / float(max(w * h, 1)), | |
| "has_quant": int(bool(getattr(im, "quantization", None))), | |
| } | |
| except Exception: | |
| return None | |
| def decode_rgb(raw: bytes, allowed_modes=("RGB",)): | |
| """Decode to RGB, or None. | |
| Modes outside `allowed_modes` are DROPPED, never converted: turning a greyscale image | |
| into RGB fabricates a channel correlation that real colour photographs do not have, and | |
| that fabrication would itself become a shortcut. | |
| RGBA is the one exception worth allowing, and only when the alpha channel is fully | |
| opaque -- then dropping it discards a constant channel and the RGB pixels are untouched. | |
| It has to be opted into via config (`normalize.allowed_modes`), because v1 was built with | |
| RGB only and rebuilding it must stay byte-identical. | |
| """ | |
| try: | |
| im = Image.open(io.BytesIO(raw)) | |
| im.load() | |
| if im.mode == "RGB": | |
| return im | |
| if im.mode == "RGBA" and "RGBA" in allowed_modes: | |
| if np.asarray(im.split()[-1]).min() != 255: | |
| return None # real transparency: the RGB under it is not meaningful | |
| return im.convert("RGB") | |
| return None | |
| except Exception: | |
| return None | |
| # -------------------------------------------------------------------------------------- | |
| # rank statistics / ROC AUC / logistic regression (numpy only) | |
| # -------------------------------------------------------------------------------------- | |
| def _average_ranks(x: np.ndarray) -> np.ndarray: | |
| """Equivalent of scipy.stats.rankdata(method="average"), without scipy.""" | |
| order = np.argsort(x, kind="mergesort") | |
| ranks = np.empty(len(x), dtype=np.float64) | |
| xs = x[order] | |
| i = 0 | |
| while i < len(xs): | |
| j = i | |
| while j + 1 < len(xs) and xs[j + 1] == xs[i]: | |
| j += 1 | |
| ranks[order[i:j + 1]] = 0.5 * (i + j) + 1.0 | |
| i = j + 1 | |
| return ranks | |
| def roc_auc(y, score) -> float: | |
| """Mann-Whitney U form, exact under ties.""" | |
| y = np.asarray(y).astype(int) | |
| score = np.asarray(score, dtype=np.float64) | |
| n1 = int((y == 1).sum()) | |
| n0 = int((y == 0).sum()) | |
| if n1 == 0 or n0 == 0: | |
| return float("nan") | |
| r = _average_ranks(score) | |
| return float((r[y == 1].sum() - n1 * (n1 + 1) / 2.0) / (n1 * n0)) | |
| def _sigmoid(z: np.ndarray) -> np.ndarray: | |
| out = np.empty_like(z) | |
| pos = z >= 0 | |
| out[pos] = 1.0 / (1.0 + np.exp(-z[pos])) | |
| e = np.exp(z[~pos]) | |
| out[~pos] = e / (1.0 + e) | |
| return out | |
| def fit_logreg(X: np.ndarray, y: np.ndarray, l2: float = 1e-3, iters: int = 60) -> np.ndarray: | |
| """Newton / IRLS with ridge damping. X must NOT already contain an intercept column.""" | |
| n, d = X.shape | |
| Xb = np.hstack([np.ones((n, 1)), X]) | |
| w = np.zeros(d + 1) | |
| pen = np.eye(d + 1) * l2 * n | |
| pen[0, 0] = 0.0 # never penalise the intercept | |
| for _ in range(iters): | |
| p = _sigmoid(Xb @ w) | |
| g = Xb.T @ (p - y) + pen @ w | |
| s = np.clip(p * (1 - p), 1e-8, None) | |
| H = (Xb * s[:, None]).T @ Xb + pen | |
| try: | |
| step = np.linalg.solve(H, g) | |
| except np.linalg.LinAlgError: | |
| step = np.linalg.lstsq(H, g, rcond=None)[0] | |
| w = w - step | |
| if np.max(np.abs(step)) < 1e-9: | |
| break | |
| return w | |
| def predict_logreg(w: np.ndarray, X: np.ndarray) -> np.ndarray: | |
| return _sigmoid(np.hstack([np.ones((X.shape[0], 1)), X]) @ w) | |
| def _standardize(train: np.ndarray, apply_to): | |
| mu = train.mean(axis=0) | |
| sd = train.std(axis=0) | |
| sd[sd < 1e-12] = 1.0 | |
| return [(a - mu) / sd for a in apply_to] | |
| def grouped_cv_auc(X, y, groups, folds: int = 5, l2: float = 1e-3, seed_tag: str = "cv") -> dict: | |
| """AUC of a logistic regression on `X`. | |
| Folds are assigned by md5 of the group id (img_id), so the two crops of one photo can | |
| never land on opposite sides of a fold boundary and inflate the score. | |
| Returns both the in-sample AUC and the out-of-fold AUC; the out-of-fold one is the | |
| number to report. | |
| """ | |
| X = np.asarray(X, dtype=np.float64) | |
| y = np.asarray(y).astype(int) | |
| fold_of = np.array([md5_int(seed_tag, g) % folds for g in groups]) | |
| (Xs,) = _standardize(X, [X]) | |
| w_full = fit_logreg(Xs, y, l2=l2) | |
| in_sample = roc_auc(y, predict_logreg(w_full, Xs)) | |
| oof = np.full(len(y), np.nan) | |
| for f in range(folds): | |
| te = fold_of == f | |
| tr = ~te | |
| if te.sum() == 0 or len(np.unique(y[tr])) < 2: | |
| continue | |
| Xtr, Xte = _standardize(X[tr], [X[tr], X[te]]) | |
| w = fit_logreg(Xtr, y[tr], l2=l2) | |
| oof[te] = predict_logreg(w, Xte) | |
| ok = ~np.isnan(oof) | |
| oof_auc = roc_auc(y[ok], oof[ok]) if ok.sum() else float("nan") | |
| return { | |
| "auc_in_sample": in_sample, | |
| "auc_out_of_fold": oof_auc, | |
| "n": int(len(y)), | |
| "n_pos": int((y == 1).sum()), | |
| "n_neg": int((y == 0).sum()), | |
| "coef": w_full.tolist(), | |
| } | |
| def single_feature_auc(x, y) -> float: | |
| """AUC of one raw feature, sign-corrected. Shows which column carries the shortcut.""" | |
| a = roc_auc(y, np.asarray(x, dtype=np.float64)) | |
| return a if (a != a or a >= 0.5) else 1.0 - a | |
| def percentiles(vals, qs=(10, 50, 90)) -> dict: | |
| a = np.asarray(list(vals), dtype=np.float64) | |
| if a.size == 0: | |
| return {"p%d" % q: float("nan") for q in qs} | |
| return {"p%d" % q: float(np.percentile(a, q)) for q in qs} | |
| # -------------------------------------------------------------------------------------- | |
| # perceptual hash (DCT-II via a cosine basis matrix; scipy is unavailable) | |
| # -------------------------------------------------------------------------------------- | |
| _DCT_CACHE = {} | |
| def _dct_matrix(n: int) -> np.ndarray: | |
| M = _DCT_CACHE.get(n) | |
| if M is None: | |
| k = np.arange(n).reshape(-1, 1) | |
| i = np.arange(n).reshape(1, -1) | |
| M = np.cos(np.pi * (2 * i + 1) * k / (2.0 * n)) | |
| M[0] *= 1.0 / np.sqrt(2.0) | |
| M *= np.sqrt(2.0 / n) | |
| _DCT_CACHE[n] = M | |
| return M | |
| def crop_and_encode(img: Image.Image, key, cfg: dict): | |
| """Normalize one source image into its crops. SHARED BY EVERY DATASET. | |
| Both SID_Set and WildFake must go through this exact function. If the two datasets were | |
| normalized by even slightly different code, the difference would itself become a | |
| "which dataset is this" signal -- the confound the merge is most at risk from. | |
| `key` is whatever identifies the image (img_id, or a zip member name); all randomness is | |
| derived from it by md5, never from call order. | |
| Returns [(crop_idx, crop_mode, jpeg_q, jpeg_bytes), ...]. | |
| """ | |
| n = cfg["normalize"] | |
| size = int(n["crop_size"]) | |
| modes = list(n["crop_modes"]) | |
| qmin, qmax = int(n["jpeg_quality_min"]), int(n["jpeg_quality_max"]) | |
| w, h = img.size | |
| out = [] | |
| for k in range(int(n["crops_per_image"])): | |
| mode = modes[k % len(modes)] | |
| rng = md5_rng("crop", key, k) | |
| if mode == "center": | |
| x, y = (w - size) // 2, (h - size) // 2 | |
| else: | |
| x = int(rng.integers(0, w - size + 1)) | |
| y = int(rng.integers(0, h - size + 1)) | |
| # Randomized quality, not fixed: reals arrive as JPEG (so they become double-JPEG) | |
| # while synthetics arrive as PNG (single-JPEG). A fixed quality would turn that | |
| # asymmetry into a fresh, equally learnable shortcut. | |
| q = int(md5_rng("q", key, k).integers(qmin, qmax + 1)) | |
| buf = io.BytesIO() | |
| img.crop((x, y, x + size, y + size)).save( | |
| buf, "JPEG", quality=q, subsampling=int(n["jpeg_subsampling"]), | |
| optimize=bool(n["jpeg_optimize"])) | |
| out.append((k, mode, q, buf.getvalue())) | |
| return out | |
| def phash(img: Image.Image, dct_size: int = 32, bits: int = 8) -> int: | |
| """64-bit perceptual hash (bits=8 -> 8x8 low-frequency block, DC excluded from the median).""" | |
| g = np.asarray(img.convert("L").resize((dct_size, dct_size), Image.Resampling.LANCZOS), | |
| dtype=np.float64) | |
| M = _dct_matrix(dct_size) | |
| d = M @ g @ M.T | |
| low = d[:bits, :bits] | |
| med = np.median(low.flatten()[1:]) # drop the DC term before taking the median | |
| h = 0 | |
| for v in low.flatten(): | |
| h = (h << 1) | int(v > med) | |
| return h | |
| def hamming(a: int, b: int) -> int: | |
| return bin(a ^ b).count("1") | |
| class PHashIndex: | |
| """Bucketed near-duplicate index, exact within `threshold` bits for 64-bit hashes. | |
| The hash is split into (threshold + 1) bands; by pigeonhole, two hashes within | |
| `threshold` bits must share at least one identical band. Band lookup therefore gives | |
| exact recall with no O(n^2) scan. | |
| """ | |
| def __init__(self, threshold: int = 6, nbits: int = 64): | |
| self.threshold = threshold | |
| self.nbits = nbits | |
| self.nbands = threshold + 1 | |
| self.width = (nbits + self.nbands - 1) // self.nbands | |
| self.bands = [dict() for _ in range(self.nbands)] | |
| self.n = 0 | |
| def _band_keys(self, h: int): | |
| mask = (1 << self.width) - 1 | |
| return [(h >> (b * self.width)) & mask for b in range(self.nbands)] | |
| def query(self, h: int): | |
| """Return a stored hash within `threshold` bits, or None.""" | |
| for b, key in enumerate(self._band_keys(h)): | |
| for cand in self.bands[b].get(key, ()): | |
| if hamming(cand, h) <= self.threshold: | |
| return cand | |
| return None | |
| def add(self, h: int) -> None: | |
| for b, key in enumerate(self._band_keys(h)): | |
| self.bands[b].setdefault(key, []).append(h) | |
| self.n += 1 | |
| def add_if_new(self, h: int) -> bool: | |
| """True if inserted (i.e. not a near-duplicate of anything already indexed).""" | |
| if self.query(h) is not None: | |
| return False | |
| self.add(h) | |
| return True | |
| # -------------------------------------------------------------------------------------- | |
| # HuggingFace parquet access | |
| # | |
| # We do NOT use datasets(streaming=True): it walks shards in a fixed order and cannot skip a | |
| # row group, so any filter still pays for every byte of the 140 GB. Reading the parquet files | |
| # directly lets us (a) never request the `mask` column and (b) fetch only the row groups we | |
| # selected. Either way nothing but the normalized crops is ever written to disk. | |
| # -------------------------------------------------------------------------------------- | |
| class RowGroupRef: | |
| split: str # our split name: "train" | "val" | |
| shard: str # e.g. data/validation-00000-of-00034.parquet | |
| rg: int | |
| n_rows: int | |
| class SidSource: | |
| def __init__(self, cfg: dict, verbose: bool = True): | |
| self.cfg = cfg | |
| self.repo = cfg["source"]["hf_repo"] | |
| self.revision = cfg["source"].get("hf_revision", "main") | |
| self.max_retries = int(cfg["source"]["max_retries"]) | |
| self.backoff = float(cfg["source"]["retry_backoff_s"]) | |
| self.verbose = verbose | |
| self._fs = None | |
| self._fs_lock = threading.Lock() | |
| self._local = threading.local() | |
| self.cache_dir = ensure_dir(rpath(cfg, cfg["paths"]["cache_dir"])) | |
| # -- low level ------------------------------------------------------------------- | |
| def fs(self): | |
| if self._fs is None: | |
| with self._fs_lock: | |
| if self._fs is None: | |
| from huggingface_hub import HfFileSystem | |
| self._fs = HfFileSystem() | |
| return self._fs | |
| def _hf_path(self, shard: str) -> str: | |
| return "datasets/%s@%s/%s" % (self.repo, self.revision, shard) | |
| def _parquet_file(self, shard: str): | |
| """One ParquetFile per (thread, shard): HTTP file handles are not thread-safe.""" | |
| cache = getattr(self._local, "pf", None) | |
| if cache is None: | |
| cache = self._local.pf = OrderedDict() | |
| if shard in cache: | |
| return cache[shard] | |
| import pyarrow.parquet as pq | |
| pf = self._retry(lambda: pq.ParquetFile(self.fs.open(self._hf_path(shard), "rb")), | |
| what="open " + shard) | |
| cache[shard] = pf | |
| while len(cache) > 4: | |
| cache.popitem(last=False) | |
| return pf | |
| def _retry(self, fn: Callable, what: str = ""): | |
| last = None | |
| for attempt in range(self.max_retries): | |
| try: | |
| return fn() | |
| except Exception as exc: # network flakiness is expected here | |
| last = exc | |
| if attempt + 1 < self.max_retries: | |
| time.sleep(self.backoff * (2 ** attempt)) | |
| raise RuntimeError("failed after %d tries: %s: %s" % (self.max_retries, what, last)) | |
| # -- shard / row-group index ------------------------------------------------------ | |
| def list_shards(self, split: str): | |
| hf_split = self.cfg["source"]["splits"][split] | |
| from huggingface_hub import HfApi | |
| info = self._retry(lambda: HfApi().dataset_info(self.repo, revision=self.revision), | |
| what="dataset_info") | |
| return sorted(s.rfilename for s in info.siblings | |
| if s.rfilename.startswith("data/%s-" % hf_split) | |
| and s.rfilename.endswith(".parquet")) | |
| def row_group_index(self, split: str): | |
| """(shard, row_group, n_rows) for every row group in a split. Cached on disk.""" | |
| cache = self.cache_dir / ("rowgroups_%s.json" % split) | |
| if cache.exists(): | |
| data = json.loads(cache.read_text(encoding="utf-8")) | |
| return [RowGroupRef(split, d["shard"], d["rg"], d["n_rows"]) for d in data] | |
| shards = self.list_shards(split) | |
| if self.verbose: | |
| print("[index] reading %d parquet footers for split=%s ..." % (len(shards), split)) | |
| def footer(shard: str): | |
| md = self._parquet_file(shard).metadata | |
| return [(shard, i, md.row_group(i).num_rows) for i in range(md.num_row_groups)] | |
| out = [] | |
| with ThreadPoolExecutor(max_workers=int(self.cfg["source"]["index_workers"])) as ex: | |
| for res in ex.map(footer, shards): | |
| out.extend(RowGroupRef(split, s, i, n) for s, i, n in res) | |
| cache.write_text(json.dumps([r.__dict__ for r in out]), encoding="utf-8") | |
| if self.verbose: | |
| print("[index] %d row groups, %d rows" % (len(out), sum(r.n_rows for r in out))) | |
| return out | |
| def shuffled_row_groups(refs, tag: str = "rg"): | |
| """Fixed pseudo-random row-group order. | |
| Row groups in SID_Set are class-interleaved (verified: roughly 1/3 per class inside | |
| every row group of both splits), so taking whole row groups in md5 order is an | |
| unbiased sample AND lets us skip the row groups we do not need. | |
| """ | |
| return sorted(refs, key=lambda r: md5_order_key(tag, r.shard, r.rg)) | |
| # -- data fetch ------------------------------------------------------------------- | |
| def read_row_group(self, ref: RowGroupRef, columns) -> list: | |
| def _do(): | |
| tbl = self._parquet_file(ref.shard).read_row_group(ref.rg, columns=list(columns)) | |
| return tbl.to_pylist() | |
| rows = self._retry(_do, what="read %s#%d" % (ref.shard, ref.rg)) | |
| for r in rows: | |
| r["_shard"] = ref.shard | |
| r["_rg"] = ref.rg | |
| return rows | |
| def iter_row_groups(self, refs, columns, workers=None, window=None) -> Iterator: | |
| """Fetch row groups in parallel but YIELD THEM IN `refs` ORDER. | |
| Order matters: quota accounting downstream must not depend on which HTTP request | |
| happened to finish first, or the selected sample silently changes between runs. | |
| The bounded window keeps peak memory at roughly window * 56 MB. | |
| """ | |
| workers = workers or int(self.cfg["source"]["fetch_workers"]) | |
| window = window or int(self.cfg["source"]["prefetch_window"]) | |
| refs = list(refs) | |
| ex = ThreadPoolExecutor(max_workers=workers) | |
| try: | |
| pending = OrderedDict() | |
| nxt = 0 | |
| while nxt < min(window, len(refs)): | |
| pending[nxt] = ex.submit(self.read_row_group, refs[nxt], columns) | |
| nxt += 1 | |
| while pending: | |
| idx = min(pending) | |
| fut = pending.pop(idx) | |
| yield refs[idx], fut.result() | |
| if nxt < len(refs): | |
| pending[nxt] = ex.submit(self.read_row_group, refs[nxt], columns) | |
| nxt += 1 | |
| finally: | |
| # The caller breaks out of this loop as soon as the quotas are full. Without | |
| # cancel_futures, shutdown would block for a full prefetch window of downloads. | |
| ex.shutdown(wait=False, cancel_futures=True) | |
| # -------------------------------------------------------------------------------------- | |
| # small utilities | |
| # -------------------------------------------------------------------------------------- | |
| def fmt_secs(s: float) -> str: | |
| s = int(s) | |
| if s >= 3600: | |
| return "%dh%02dm%02ds" % (s // 3600, (s % 3600) // 60, s % 60) | |
| return "%dm%02ds" % (s // 60, s % 60) | |
| def label_bin(label_orig) -> int: | |
| return int(int(label_orig) != 0) | |