|
| 1 | +"""PMC-2M with summarized inline references Dataset.""" |
| 2 | + |
| 3 | +import json |
| 4 | +import os |
| 5 | +from typing import Callable, Dict, Literal, Optional, Union |
| 6 | + |
| 7 | +import torch |
| 8 | +from mmlearn.conf import external_store |
| 9 | +from mmlearn.constants import EXAMPLE_INDEX_KEY |
| 10 | +from mmlearn.datasets.core import Modalities |
| 11 | +from mmlearn.datasets.core.example import Example |
| 12 | +from omegaconf import MISSING |
| 13 | +from PIL import Image |
| 14 | +from torch.utils.data import Dataset |
| 15 | +from torchvision.transforms import ToTensor |
| 16 | + |
| 17 | + |
| 18 | +@external_store(group="datasets", root_dir=os.getenv("PMC2M_SUMM_ROOT_DIR", MISSING)) |
| 19 | +class PMC2MSum(Dataset[Example]): |
| 20 | + """PMC-2M with summarized inline references dataset. |
| 21 | +
|
| 22 | + Parameters |
| 23 | + ---------- |
| 24 | + root_dir : str |
| 25 | + Path to the root folder containing jsonl file with data entries. |
| 26 | + split : {"train", "valid", "test"} |
| 27 | + Dataset split. |
| 28 | + transform : Optional[Callable], default=None |
| 29 | + Transform applied to images. |
| 30 | + tokenizer : Optional[Callable], default=None |
| 31 | + Function applied to textual captions. |
| 32 | + """ |
| 33 | + |
| 34 | + def __init__( |
| 35 | + self, |
| 36 | + root_dir: str, |
| 37 | + split: Literal["train", "valid", "test"] = "train", |
| 38 | + transform: Optional[Callable[[Image.Image], torch.Tensor]] = None, |
| 39 | + tokenizer: Optional[ |
| 40 | + Callable[[str], Union[torch.Tensor, Dict[str, torch.Tensor]]] |
| 41 | + ] = None, |
| 42 | + ) -> None: |
| 43 | + """Initialize the dataset.""" |
| 44 | + data_path = os.path.join(root_dir, f"{split}.jsonl") |
| 45 | + with open(data_path, encoding="utf-8") as file: |
| 46 | + entries = [json.loads(line) for line in file.readlines()] |
| 47 | + self.entries = entries |
| 48 | + |
| 49 | + self.root_dir = root_dir |
| 50 | + |
| 51 | + if transform is None: |
| 52 | + self.transform = ToTensor() |
| 53 | + else: |
| 54 | + self.transform = transform |
| 55 | + |
| 56 | + self.tokenizer = tokenizer |
| 57 | + |
| 58 | + def __getitem__(self, idx: int) -> Example: |
| 59 | + """Return the idx'th data sample.""" |
| 60 | + entry = self.entries[idx] |
| 61 | + # load image |
| 62 | + try: |
| 63 | + with Image.open(entry["image_fullpath"]) as img: |
| 64 | + image = img.convert("RGB") |
| 65 | + except Exception as e: |
| 66 | + print( |
| 67 | + f"Error loading image for entry {idx}: image_path={entry['image_fullpath']}", |
| 68 | + e, |
| 69 | + ) |
| 70 | + idx = (idx + 1) % len(self.entries) |
| 71 | + return self.__getitem__(idx) |
| 72 | + |
| 73 | + # load text |
| 74 | + caption = " ".join([entry["caption"], entry["intext_refs_summary"]]) |
| 75 | + |
| 76 | + # apply transform and tokenization |
| 77 | + if self.transform is not None: |
| 78 | + image = self.transform(image) |
| 79 | + |
| 80 | + tokens = self.tokenizer(caption) if self.tokenizer is not None else None |
| 81 | + |
| 82 | + example = Example( |
| 83 | + { |
| 84 | + Modalities.RGB.name: image, |
| 85 | + Modalities.TEXT.name: caption, |
| 86 | + EXAMPLE_INDEX_KEY: idx, |
| 87 | + } |
| 88 | + ) |
| 89 | + |
| 90 | + if tokens is not None: |
| 91 | + if isinstance(tokens, dict): # output of HFTokenizer |
| 92 | + assert ( |
| 93 | + Modalities.TEXT.name in tokens |
| 94 | + ), f"Missing key `{Modalities.TEXT.name}` in tokens." |
| 95 | + example.update(tokens) |
| 96 | + else: |
| 97 | + example[Modalities.TEXT.name] = tokens |
| 98 | + |
| 99 | + return example |
| 100 | + |
| 101 | + def __len__(self) -> int: |
| 102 | + """Return the length of the dataset.""" |
| 103 | + return len(self.entries) |
0 commit comments