Download src/transforms.py from ElenaZhan/TrueSight_AI_Detection_with_Stability_Checks: direct link, hf CLI and curl.
- Browser
- Download file 8.34 kB
-
https://huggingface.co/spaces/ElenaZhan/TrueSight_AI_Detection_with_Stability_Checks/resolve/main/src/transforms.py
- Command line
-
hf download hf://spaces/ElenaZhan/TrueSight_AI_Detection_with_Stability_Checks/src/transforms.py
-
curl -L -o transforms.py https://huggingface.co/spaces/ElenaZhan/TrueSight_AI_Detection_with_Stability_Checks/resolve/main/src/transforms.py
8.34 kB
| """Training-time augmentation. Deliverable for teammate A. | |
| Applied ONLINE in Dataset.__getitem__. Nothing here is ever written to disk -- the on-disk | |
| crops stay clean, and the eval sets (src/build_eval_sets.py) are the only degraded pixels | |
| that get persisted. | |
| Two rules this module exists to enforce: | |
| 1. COMPOSE. Each sample stacks 2-3 ops in random order. Real redistribution is a chain | |
| (resize -> JPEG -> screenshot -> JPEG again), never one operation. A model trained on | |
| single transforms fails under composed degradation. | |
| 2. TRAINING RANGES ARE CONTINUOUS, EVAL LEVELS ARE DISCRETE. Evaluation uses | |
| JPEG q in {90, 70, 50, 30}. If training sampled those exact integers, the reported | |
| robustness would be measuring memorization rather than generalization. The ranges below | |
| span the eval points but the four exact values are skipped. | |
| Note on resizing: `random_crop` and `rescale` do resample the image. That is deliberate and | |
| is NOT in tension with the crop-not-resize rule in build_sid.py. There, resizing would have | |
| destroyed the artifact signal before the model ever saw it. Here, resampling IS the | |
| distortion we are teaching the model to survive. | |
| """ | |
| from __future__ import annotations | |
| import io | |
| import sys | |
| from pathlib import Path | |
| import numpy as np | |
| from PIL import Image, ImageEnhance, ImageFilter | |
| sys.path.insert(0, str(Path(__file__).resolve().parent)) | |
| import common as C # noqa: E402 | |
| # -------------------------------------------------------------------------------------- | |
| # individual ops: (PIL.Image, rng, params) -> PIL.Image, size preserved | |
| # -------------------------------------------------------------------------------------- | |
| def _uniform(rng, lo, hi) -> float: | |
| return float(rng.uniform(float(lo), float(hi))) | |
| def op_jpeg(img: Image.Image, rng, p: dict, forbidden=()) -> Image.Image: | |
| lo, hi = p["quality"] | |
| q = int(round(_uniform(rng, lo, hi))) | |
| # PIL needs an integer quality, so a continuous draw has to be rounded. Nudge off the | |
| # discrete eval levels; the +1 bias on four integers out of ~66 is negligible. | |
| while q in forbidden: | |
| q += 1 | |
| q = int(np.clip(q, 1, 100)) | |
| buf = io.BytesIO() | |
| img.save(buf, "JPEG", quality=q) | |
| buf.seek(0) | |
| out = Image.open(buf) | |
| out.load() | |
| return out.convert("RGB") | |
| def op_blur(img: Image.Image, rng, p: dict, **_) -> Image.Image: | |
| sigma = _uniform(rng, *p["sigma"]) | |
| return img.filter(ImageFilter.GaussianBlur(radius=sigma)) | |
| def op_noise(img: Image.Image, rng, p: dict, **_) -> Image.Image: | |
| sigma = _uniform(rng, *p["sigma"]) # sigma is in [0, 1] image units | |
| a = np.asarray(img, dtype=np.float32) / 255.0 | |
| a = a + rng.normal(0.0, sigma, a.shape).astype(np.float32) | |
| return Image.fromarray((np.clip(a, 0.0, 1.0) * 255.0 + 0.5).astype(np.uint8), "RGB") | |
| def op_jitter(img: Image.Image, rng, p: dict, **_) -> Image.Image: | |
| for key, enh in (("brightness", ImageEnhance.Brightness), | |
| ("contrast", ImageEnhance.Contrast), | |
| ("saturation", ImageEnhance.Color)): | |
| amt = float(p.get(key, 0.0)) | |
| if amt > 0: | |
| img = enh(img).enhance(1.0 + _uniform(rng, -amt, amt)) | |
| return img | |
| def op_random_crop(img: Image.Image, rng, p: dict, **_) -> Image.Image: | |
| w, h = img.size | |
| s = _uniform(rng, *p["scale"]) | |
| cw, ch = max(1, int(round(w * s))), max(1, int(round(h * s))) | |
| x = int(rng.integers(0, w - cw + 1)) | |
| y = int(rng.integers(0, h - ch + 1)) | |
| return img.crop((x, y, x + cw, y + ch)).resize((w, h), Image.Resampling.BICUBIC) | |
| def op_rescale(img: Image.Image, rng, p: dict, **_) -> Image.Image: | |
| """Downscale then upscale back: the classic 'someone reposted a screenshot' artifact.""" | |
| w, h = img.size | |
| f = _uniform(rng, *p["factor"]) | |
| sw, sh = max(8, int(round(w * f))), max(8, int(round(h * f))) | |
| small = img.resize((sw, sh), Image.Resampling.BILINEAR) | |
| return small.resize((w, h), Image.Resampling.BILINEAR) | |
| OPS = { | |
| "jpeg": op_jpeg, | |
| "blur": op_blur, | |
| "noise": op_noise, | |
| "jitter": op_jitter, | |
| "random_crop": op_random_crop, | |
| "rescale": op_rescale, | |
| } | |
| # -------------------------------------------------------------------------------------- | |
| class TrainAugment: | |
| """Randomly stacks `n_ops_min`..`n_ops_max` distinct ops, in random order. | |
| aug = TrainAugment(load_config()) | |
| img = aug(img) # PIL RGB in, PIL RGB out, same size | |
| """ | |
| def __init__(self, cfg: dict, rng=None): | |
| a = cfg["augment"] | |
| self.cfg = a | |
| self.n_min = int(a["n_ops_min"]) | |
| self.n_max = int(a["n_ops_max"]) | |
| self.names = [n for n in a["ops"] if n in OPS] | |
| self.params = a["ops"] | |
| self.weights = np.array([float(a["ops"][n].get("p", 1.0)) for n in self.names]) | |
| self.weights = self.weights / self.weights.sum() | |
| self.forbidden = tuple(int(q) for q in a.get("forbidden_jpeg_qualities", ())) | |
| self.rng = rng if rng is not None else np.random.default_rng() | |
| self._check_eval_overlap(cfg) | |
| def _check_eval_overlap(self, cfg: dict) -> None: | |
| """Fail loudly if the training JPEG range ever lands on an eval level.""" | |
| eval_qs = {int(c["quality"]) for c in cfg["eval_sets"]["conditions"].values() | |
| if c.get("op") == "jpeg"} | |
| missing = eval_qs - set(self.forbidden) | |
| if missing: | |
| raise ValueError( | |
| "eval JPEG levels %s are not listed in augment.forbidden_jpeg_qualities; " | |
| "training would sample the exact values it is evaluated on, and the " | |
| "robustness numbers would measure memorization" % sorted(missing)) | |
| def seeded(self, *key): | |
| """A copy whose randomness is derived from `key` -- for reproducible spot checks. | |
| Training itself should NOT use this: augmentation must differ every epoch. | |
| """ | |
| new = object.__new__(TrainAugment) | |
| new.__dict__.update(self.__dict__) | |
| new.rng = C.md5_rng(*key) | |
| return new | |
| def plan(self, rng=None): | |
| """The ops chosen for one sample, without applying them (used by the self-test).""" | |
| rng = rng or self.rng | |
| k = int(rng.integers(self.n_min, self.n_max + 1)) | |
| k = min(k, len(self.names)) | |
| idx = rng.choice(len(self.names), size=k, replace=False, p=self.weights) | |
| return [self.names[i] for i in idx] | |
| def __call__(self, img: Image.Image, rng=None) -> Image.Image: | |
| rng = rng if rng is not None else self.rng | |
| for name in self.plan(rng): | |
| img = OPS[name](img, rng, self.params[name], forbidden=self.forbidden) | |
| return img.convert("RGB") | |
| # -------------------------------------------------------------------------------------- | |
| def _self_test() -> int: | |
| """python src/transforms.py -- checks the two rules actually hold.""" | |
| import collections | |
| cfg = C.load_config() | |
| aug = TrainAugment(cfg, rng=np.random.default_rng(0)) | |
| counts = collections.Counter() | |
| for _ in range(20000): | |
| counts[len(aug.plan())] += 1 | |
| print("ops per sample:", dict(sorted(counts.items()))) | |
| assert set(counts) <= {2, 3}, "composition rule violated" | |
| rng = np.random.default_rng(1) | |
| qs = [] | |
| for _ in range(20000): | |
| lo, hi = cfg["augment"]["ops"]["jpeg"]["quality"] | |
| q = int(round(rng.uniform(lo, hi))) | |
| while q in aug.forbidden: | |
| q += 1 | |
| qs.append(q) | |
| hit = {q: qs.count(q) for q in cfg["augment"]["forbidden_jpeg_qualities"]} | |
| print("draws landing on eval levels:", hit) | |
| assert sum(hit.values()) == 0, "training sampled an eval JPEG level" | |
| print("q range actually used: %d..%d over %d distinct values" | |
| % (min(qs), max(qs), len(set(qs)))) | |
| img = Image.fromarray( | |
| np.random.default_rng(2).integers(0, 255, (256, 256, 3), dtype=np.uint8), "RGB") | |
| for name, fn in OPS.items(): | |
| out = fn(img, np.random.default_rng(3), cfg["augment"]["ops"][name], | |
| forbidden=aug.forbidden) | |
| assert out.size == img.size and out.mode == "RGB", name | |
| print(" %-12s ok size=%s mode=%s" % (name, out.size, out.mode)) | |
| out = aug(img) | |
| print("composed ok:", out.size, out.mode) | |
| print("ALL CHECKS PASSED") | |
| return 0 | |
| if __name__ == "__main__": | |
| raise SystemExit(_self_test()) | |