Datasets:
Download loading_example.py from Shelly97/HateSieve-Dataset-multimodal-hate-triplets: direct link, hf CLI and curl.
- Browser
- Download file 2.14 kB
-
https://huggingface.co/datasets/Shelly97/HateSieve-Dataset-multimodal-hate-triplets/resolve/main/loading_example.py
- Command line
-
hf download hf://datasets/Shelly97/HateSieve-Dataset-multimodal-hate-triplets/loading_example.py
-
curl -L -o loading_example.py https://huggingface.co/datasets/Shelly97/HateSieve-Dataset-multimodal-hate-triplets/resolve/main/loading_example.py
2.14 kB
| """PyTorch loading example for Shelly97/multimodal-hate-triplets. | |
| Install: pip install -U datasets pillow torch transformers | |
| The processor is supplied by the caller to match the training model. | |
| """ | |
| import torch | |
| from torch.utils.data import Dataset | |
| def process_image_text(image, text, processor): | |
| processed = processor( | |
| text=text, images=image, max_length=77, padding="max_length", | |
| truncation=True, return_tensors="pt", | |
| ) | |
| return {key: processed[key].squeeze(0) | |
| for key in ("pixel_values", "input_ids", "attention_mask")} | |
| def load_and_process(example, processor): | |
| result = {} | |
| for key in ("org", "pos", "neg"): | |
| # Hugging Face Image columns decode directly into PIL images. | |
| with example[f"{key}_img"].convert("RGB") as image: | |
| result[key] = process_image_text(image, example[f"{key}_txt"], processor) | |
| result["label"] = example["org_label"] | |
| return result | |
| class MultimodalDataset(Dataset): | |
| def __init__(self, data, processor): | |
| self.data = data | |
| self.processor = processor | |
| def __len__(self): | |
| return len(self.data) | |
| def __getitem__(self, idx): | |
| # Propagate corrupt data/processor errors so training cannot silently lose rows. | |
| return load_and_process(self.data[idx], self.processor) | |
| def collate_fn(batch): | |
| if not batch: | |
| return None | |
| result = { | |
| key: {field: torch.stack([item[key][field] for item in batch]) | |
| for field in ("pixel_values", "input_ids", "attention_mask")} | |
| for key in ("org", "pos", "neg") | |
| } | |
| result["label"] = torch.tensor([item["label"] for item in batch], dtype=torch.long) | |
| return result | |
| # Usage (after publication): | |
| # from datasets import load_dataset | |
| # from transformers import CLIPProcessor | |
| # from torch.utils.data import DataLoader | |
| # processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32") | |
| # data_pairs = load_dataset("Shelly97/multimodal-hate-triplets", split="train") | |
| # dataset = MultimodalDataset(data_pairs, processor) | |
| # loader = DataLoader(dataset, batch_size=32, shuffle=True, collate_fn=collate_fn) | |