File size: 4,637 Bytes
f9ed2b4 | 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 | #!/usr/bin/env python3
"""Reusable PyTorch datasets backed by CSV image indexes."""
from __future__ import annotations
import csv
import json
import sys
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Callable, Literal
from PIL import Image
from torch.utils.data import Dataset
csv.field_size_limit(min(sys.maxsize, 2_147_483_647))
LabelMode = Literal["binary", "ai_model", "real_source", "unified"]
@dataclass(frozen=True)
class IndexedSample:
image_path: str
label: int
label_type: str
source_name: str
row: dict[str, str]
class CSVIndexDataset(Dataset):
"""Dataset for AI/real CSV image indexes.
Label modes:
- binary: AI=1, real=0.
- ai_model: AI samples use source_model_id; real samples use 0.
- real_source: real samples use real_source_id; AI samples use 1.
- unified: AI samples use source_model_id; real samples use negative real_source_id.
"""
def __init__(
self,
csv_paths: str | Path | list[str | Path],
transform: Callable[[Image.Image], Any] | None = None,
label_mode: LabelMode = "binary",
return_metadata: bool = False,
):
self.csv_paths = [Path(csv_paths)] if isinstance(csv_paths, (str, Path)) else [Path(p) for p in csv_paths]
self.transform = transform
self.label_mode = label_mode
self.return_metadata = return_metadata
self.samples = self._load_samples()
def _load_samples(self) -> list[IndexedSample]:
samples: list[IndexedSample] = []
for csv_path in self.csv_paths:
with csv_path.open("r", newline="", encoding="utf-8") as f:
reader = csv.DictReader(f)
for row in reader:
image_path = row.get("image_path", "")
if not image_path:
continue
label_type = row.get("label_type", "")
source_name = row.get("source_model_name") or row.get("real_source_label") or row.get("source_dataset", "")
samples.append(
IndexedSample(
image_path=image_path,
label=self._label_for_row(row),
label_type=label_type,
source_name=source_name,
row=row,
)
)
return samples
def _label_for_row(self, row: dict[str, str]) -> int:
label_type = row.get("label_type")
if self.label_mode == "binary":
return int(float(row.get("binary_label", 0)))
if self.label_mode == "ai_model":
return int(row.get("source_model_id") or 0)
if self.label_mode == "real_source":
if label_type == "real":
return int(row.get("real_source_id") or 0)
return 1
if self.label_mode == "unified":
if label_type == "real":
return int(row.get("real_source_id") or 0)
return int(row.get("source_model_id") or 0)
raise ValueError(f"Unsupported label_mode: {self.label_mode}")
def __len__(self) -> int:
return len(self.samples)
def __getitem__(self, idx: int):
sample = self.samples[idx]
image = Image.open(sample.image_path).convert("RGB")
if self.transform is not None:
image = self.transform(image)
if self.return_metadata:
return image, sample.label, sample.row
return image, sample.label
def load_dataset_summary(path: str | Path) -> dict[str, Any]:
with Path(path).open("r", encoding="utf-8") as f:
return json.load(f)
def main() -> None:
import argparse
parser = argparse.ArgumentParser(description="Inspect CSV index dataset sizes.")
parser.add_argument("csv", nargs="+", type=Path)
parser.add_argument("--label-mode", choices=["binary", "ai_model", "real_source", "unified"], default="binary")
args = parser.parse_args()
ds = CSVIndexDataset(args.csv, label_mode=args.label_mode)
counts: dict[int, int] = {}
type_counts: dict[str, int] = {}
for sample in ds.samples:
counts[sample.label] = counts.get(sample.label, 0) + 1
type_counts[sample.label_type] = type_counts.get(sample.label_type, 0) + 1
print(json.dumps({"total": len(ds), "label_counts": counts, "type_counts": type_counts}, indent=2))
if __name__ == "__main__":
main()
|