Download src/dataset.py from ElenaZhan/TrueSight_AI_Detection_with_Stability_Checks: direct link, hf CLI and curl.
- Browser
- Download file 7.98 kB
-
https://huggingface.co/spaces/ElenaZhan/TrueSight_AI_Detection_with_Stability_Checks/resolve/main/src/dataset.py
- Command line
-
hf download hf://spaces/ElenaZhan/TrueSight_AI_Detection_with_Stability_Checks/src/dataset.py
-
curl -L -o dataset.py https://huggingface.co/spaces/ElenaZhan/TrueSight_AI_Detection_with_Stability_Checks/resolve/main/src/dataset.py
7.98 kB
| """PyTorch Dataset over a manifest CSV. Deliverable for teammate A. | |
| This module plus a manifest is the ENTIRE interface. Do not import build_sid.py, do not | |
| touch HuggingFace, do not sample your own images -- if you do, your numbers stop being | |
| comparable with everyone else's. | |
| from dataset import SidCropDataset, make_loader | |
| train_ds = SidCropDataset("manifests/train.csv", train=True) | |
| val_ds = SidCropDataset("manifests/val.csv", train=False) | |
| __getitem__ returns (tensor[3,224,224], label_bin). Pass return_meta=True to also get | |
| label_orig, which teammate C needs to report recall separately for full_synthetic vs | |
| tampered. | |
| WHY THE MODEL INPUT IS A CROP AND NOT A RESIZE | |
| CLIP's stock preprocessing is Resize(224) + CenterCrop(224). That Resize is a low-pass | |
| filter, and it throws away exactly the high-frequency generative artifacts that this whole | |
| pipeline was built to preserve -- it would undo the crop-not-resize rule at the last step. | |
| Going from our 256px crop to the model's 224px input is therefore a CENTER CROP. | |
| If you swap in a backbone with a different input size, crop to it; do not resize to it. | |
| """ | |
| from __future__ import annotations | |
| import csv | |
| import sys | |
| from pathlib import Path | |
| import numpy as np | |
| import torch | |
| from PIL import Image | |
| from torch.utils.data import DataLoader, Dataset, WeightedRandomSampler | |
| sys.path.insert(0, str(Path(__file__).resolve().parent)) | |
| import common as C # noqa: E402 | |
| from transforms import TrainAugment # noqa: E402 | |
| def _center_crop(img: Image.Image, size: int) -> Image.Image: | |
| w, h = img.size | |
| if w == size and h == size: | |
| return img | |
| if w < size or h < size: | |
| raise ValueError("crop %dx%d is smaller than the model input %d; " | |
| "resizing here would defeat the pipeline" % (w, h, size)) | |
| x, y = (w - size) // 2, (h - size) // 2 | |
| return img.crop((x, y, x + size, y + size)) | |
| class SidCropDataset(Dataset): | |
| def __init__(self, manifest, cfg=None, train: bool = False, augment=None, | |
| return_meta: bool = False, input_size: int = None, normalize: bool = True): | |
| """ | |
| manifest path to manifests/train.csv or manifests/val.csv | |
| train convenience flag; when augment is None it decides whether to augment | |
| augment True/False to override, or your own callable(PIL) -> PIL | |
| return_meta also return {"img_id", "label_orig", "crop_idx", "source"} | |
| """ | |
| self.cfg = cfg or C.load_config() | |
| self.root = Path(self.cfg["_root"]) | |
| mp = Path(manifest) | |
| if not mp.is_absolute(): | |
| mp = self.root / mp | |
| with open(mp, newline="", encoding="utf-8") as fh: | |
| self.rows = list(csv.DictReader(fh)) | |
| if not self.rows: | |
| raise ValueError("empty manifest: %s" % mp) | |
| d = self.cfg["dataset"] | |
| self.input_size = int(input_size or d["model_input_size"]) | |
| self.return_meta = return_meta | |
| self.normalize = normalize | |
| self.mean = torch.tensor(d["normalize_mean"], dtype=torch.float32).view(3, 1, 1) | |
| self.std = torch.tensor(d["normalize_std"], dtype=torch.float32).view(3, 1, 1) | |
| if augment is None: | |
| augment = bool(train) | |
| if augment is True: | |
| self.augment = TrainAugment(self.cfg) | |
| elif augment is False: | |
| self.augment = None | |
| else: | |
| self.augment = augment | |
| # -- helpers teammate A will want ------------------------------------------------ | |
| def labels(self) -> np.ndarray: | |
| return np.array([int(r["label_bin"]) for r in self.rows]) | |
| def labels_orig(self) -> np.ndarray: | |
| return np.array([int(r["label_orig"]) for r in self.rows]) | |
| def pos_weight(self) -> torch.Tensor: | |
| """For BCEWithLogitsLoss(pos_weight=...) when the manifest is not 1:1. | |
| The shipped manifests are 1 real : 2 synthetic, so this returns ~0.5. Forgetting it | |
| biases the model toward predicting 'synthetic' and inflates apparent recall. | |
| """ | |
| y = self.labels() | |
| n_pos, n_neg = int((y == 1).sum()), int((y == 0).sum()) | |
| return torch.tensor([n_neg / max(n_pos, 1)], dtype=torch.float32) | |
| def balanced_sampler(self) -> WeightedRandomSampler: | |
| """The other way to handle the 1:2 ratio: sample it back to 1:1 each epoch.""" | |
| y = self.labels() | |
| cnt = np.bincount(y, minlength=2).astype(np.float64) | |
| w = (1.0 / np.maximum(cnt, 1))[y] | |
| return WeightedRandomSampler(torch.as_tensor(w, dtype=torch.double), len(w), True) | |
| # -- Dataset --------------------------------------------------------------------- | |
| def __len__(self) -> int: | |
| return len(self.rows) | |
| def __getitem__(self, i: int): | |
| r = self.rows[i] | |
| p = Path(r["crop_path"]) | |
| img = Image.open(p if p.is_absolute() else self.root / p) | |
| img.load() | |
| if img.mode != "RGB": | |
| img = img.convert("RGB") | |
| if self.augment is not None: | |
| img = self.augment(img) | |
| img = _center_crop(img, self.input_size) # CROP, never resize -- see module docstring | |
| a = torch.from_numpy(np.asarray(img, dtype=np.uint8).copy()) | |
| x = a.permute(2, 0, 1).float().div_(255.0) | |
| if self.normalize: | |
| x = (x - self.mean) / self.std | |
| y = int(r["label_bin"]) | |
| if not self.return_meta: | |
| return x, y | |
| return x, y, {"img_id": r["img_id"], "label_orig": int(r["label_orig"]), | |
| "crop_idx": int(r["crop_idx"]), "source": r["source"]} | |
| def make_loader(manifest, batch_size: int = 64, train: bool = False, num_workers: int = 4, | |
| balanced: bool = False, cfg=None, **kw) -> DataLoader: | |
| ds = SidCropDataset(manifest, cfg=cfg, train=train, **kw) | |
| sampler = ds.balanced_sampler() if (train and balanced) else None | |
| return DataLoader(ds, batch_size=batch_size, shuffle=(train and sampler is None), | |
| sampler=sampler, num_workers=num_workers, | |
| pin_memory=torch.cuda.is_available(), drop_last=train, | |
| persistent_workers=num_workers > 0) | |
| # -------------------------------------------------------------------------------------- | |
| def _self_test() -> int: | |
| """python src/dataset.py [manifest]""" | |
| cfg = C.load_config() | |
| mp = sys.argv[1] if len(sys.argv) > 1 else "manifests/val.csv" | |
| if not (Path(cfg["_root"]) / mp).exists(): | |
| print("manifest %s not built yet" % mp) | |
| return 1 | |
| ds = SidCropDataset(mp, cfg=cfg, train=False, return_meta=True) | |
| x, y, m = ds[0] | |
| print("clean : x%s %s range [%.2f, %.2f] y=%d meta=%s" | |
| % (tuple(x.shape), x.dtype, x.min(), x.max(), y, m)) | |
| assert tuple(x.shape) == (3, ds.input_size, ds.input_size) | |
| ds_a = SidCropDataset(mp, cfg=cfg, train=True, return_meta=False) | |
| xa, ya = ds_a[0] | |
| print("augment: x%s differs from clean: %s" % (tuple(xa.shape), bool((xa - x).abs().max() > 0))) | |
| y_all = ds.labels() | |
| print("manifest: %d crops, %d images, label_bin 0/1 = %d/%d, pos_weight=%.3f" | |
| % (len(ds), len({r["img_id"] for r in ds.rows}), | |
| int((y_all == 0).sum()), int((y_all == 1).sum()), float(ds.pos_weight()))) | |
| import collections | |
| print("label_orig:", dict(sorted(collections.Counter(ds.labels_orig().tolist()).items()))) | |
| # both crops of one image must share a split -- verified here as "no img_id in two splits" | |
| splits = collections.defaultdict(set) | |
| for r in ds.rows: | |
| splits[r["img_id"]].add(r["split"]) | |
| bad = [k for k, v in splits.items() if len(v) > 1] | |
| print("img_ids spanning >1 split: %d (must be 0)" % len(bad)) | |
| assert not bad | |
| dl = make_loader(mp, batch_size=8, train=False, num_workers=0) | |
| xb, yb = next(iter(dl)) | |
| print("loader : batch %s labels %s" % (tuple(xb.shape), yb.tolist())) | |
| print("ALL CHECKS PASSED") | |
| return 0 | |
| if __name__ == "__main__": | |
| raise SystemExit(_self_test()) | |