File size: 7,325 Bytes
74e8f2f |
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 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 |
# Copyright 2024 Big Vision Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# pylint: disable=line-too-long
r"""Creates TFDS dataset for SciCap.
Preparing the data:
1) mkdir /tmp/data/scicap && cd /tmp/data/scicap
2) wget 'https://www.dropbox.com/s/t1sjqesl0pynaxo/scicap_data.zip?dl=0'
3) unzip -UU 'scicap_data.zip?dl=0' && rm 'scicap_data.zip?dl=0'
Then, run conversion locally (make sure to install tensorflow-datasets for the `tfds` util):
cd big_vision/datasets
env TFDS_DATA_DIR=/tmp/tfds tfds build --datasets=scicap
Example to load:
import tensorflow_datasets as tfds
dataset = tfds.load('scicap', split='train', data_dir='/tmp/tfds')
"""
# pylint: enable=line-too-long
import enum
import functools
import json
import os
import tensorflow_datasets as tfds
_DESCRIPTION = """SciCap dataset."""
_CITATION = """
@article{hsu2021scicap,
title={SciCap: Generating captions for scientific figures},
author={Hsu, Ting-Yao and Giles, C Lee and Huang, Ting-Hao'Kenneth'},
journal={arXiv preprint arXiv:2110.11624},
year={2021}
}
"""
# When running locally (recommended), copy files as above an use these:
_SCICAP_DIR = "/tmp/data/scicap/scicap_data"
class ScicapSubset(enum.Enum):
"""Versions of the SciCap dataset."""
SINGLE_SENTENCE = "single_sentence"
FIRST_SENTENCE = "first_sentence"
LEQ_100_TOKENS = "leq_100_tokens"
_SPLITS_TO_GENERATE = ["train", "test", "val"]
_CONFIG_TO_IDS_PATH = {
(ScicapSubset.SINGLE_SENTENCE, True): "Single-Sentence-Caption/Yes-Subfig",
(ScicapSubset.SINGLE_SENTENCE, False): "Single-Sentence-Caption/No-Subfig",
(ScicapSubset.FIRST_SENTENCE, True): "First-Sentence/Yes-Subfig",
(ScicapSubset.FIRST_SENTENCE, False): "First-Sentence/No-Subfig",
(ScicapSubset.LEQ_100_TOKENS, True):
"Caption-No-More-Than-100-Tokens/Yes-Subfig",
(ScicapSubset.LEQ_100_TOKENS, False):
"Caption-No-More-Than-100-Tokens/No-Subfig",
}
_SUBFIG_TO_PATH = {
True: "SciCap-Yes-Subfig-Img", False: "SciCap-No-Subfig-Img"
}
class ScicapConfig(tfds.core.BuilderConfig):
""""Configuration for SciCap caption length and subfigure inclusion."""
def __init__(self, *, subset: ScicapSubset, subfig: bool, **kwargs):
"""Parameters specifying how the dataset will be processed.
Args:
subset: Subset of the Scicap data (see enum above).
subfig: Whether or not figure with subfigures are included.
**kwargs: Passed on to the constructor of `BuilderConfig`.
"""
super(ScicapConfig, self).__init__(**kwargs)
self.subset = subset
self.subfig = subfig
@functools.cache
def _read_annotations(split: str, image_id: str):
"""Reads annotations for a single file."""
path = os.path.join(_SCICAP_DIR, "SciCap-Caption-All", split)
fname = os.path.join(path, image_id + ".json")
with open(fname, "r") as fin:
return json.load(fin)
class Scicap(tfds.core.GeneratorBasedBuilder):
"""DatasetBuilder for the SciCap dataset."""
VERSION = tfds.core.Version("1.0.0")
RELEASE_NOTES = {"1.0.0": "First release."}
BUILDER_CONFIGS = [
ScicapConfig(
name="single_sentence_subfig_yes",
description="Single sentence caption with subfigures allowed.",
subset=ScicapSubset.SINGLE_SENTENCE,
subfig=True
),
ScicapConfig(
name="single_sentence_subfig_no",
description="Single sentence caption with subfigures not allowed.",
subset=ScicapSubset.SINGLE_SENTENCE,
subfig=False
),
ScicapConfig(
name="first_sentence_subfig_yes",
description="First sentence of captions with subfigures allowed.",
subset=ScicapSubset.FIRST_SENTENCE,
subfig=True
),
ScicapConfig(
name="first_sentence_subfig_no",
description="First sentence of captions with subfigures not allowed.",
subset=ScicapSubset.FIRST_SENTENCE,
subfig=False
),
ScicapConfig(
name="leq_100_tokens_subfig_yes",
description="Captions with <= 100 tokens with subfigures allowed.",
subset=ScicapSubset.LEQ_100_TOKENS,
subfig=True
),
ScicapConfig(
name="leq_100_tokens_subfig_no",
description=("Captions with <= 100 tokens with subfigures"
" not allowed."),
subset=ScicapSubset.LEQ_100_TOKENS,
subfig=False
),
]
def _info(self):
"""Returns the metadata."""
return tfds.core.DatasetInfo(
builder=self,
description=_DESCRIPTION,
features=tfds.features.FeaturesDict({
"image/id": tfds.features.Text(),
"image/filename": tfds.features.Text(),
"image": tfds.features.Image(encoding_format="png"),
"caption/originally_extracted": tfds.features.Text(),
"caption/lowercase_and_token_and_remove_figure_index":
tfds.features.Text(),
"caption/normalized/basic_num": tfds.features.Text(),
"caption/normalized/advanced_equation_bracket":
tfds.features.Text(),
}),
supervised_keys=None,
homepage="https://github.com/tingyaohsu/SciCap",
citation=_CITATION,
)
def _split_generators(self, dl_manager: tfds.download.DownloadManager):
"""Returns SplitGenerators."""
return {split: self._generate_examples(split)
for split in _SPLITS_TO_GENERATE}
def _generate_examples(self, split: str):
"""Yields (key, example) tuples from test set."""
config_path = _CONFIG_TO_IDS_PATH[
(self.builder_config.subset, self.builder_config.subfig)]
image_path = os.path.join(
_SCICAP_DIR, _SUBFIG_TO_PATH[self.builder_config.subfig], split)
id_list_fname = os.path.join(
_SCICAP_DIR, "List-of-Files-for-Each-Experiments",
config_path, split, "file_idx.json")
with open(id_list_fname, "r") as fin:
split_images = json.load(fin)
for fname in split_images:
assert fname.endswith(".png")
image_id = fname[:-len(".png")]
annotations = _read_annotations(split, image_id)
yield fname, {
"image/id": image_id,
"image/filename": fname,
"image": os.path.join(image_path, fname),
"caption/originally_extracted": annotations["0-originally-extracted"],
"caption/lowercase_and_token_and_remove_figure_index":
annotations["1-lowercase-and-token-and-remove-figure-index"][
"caption"],
"caption/normalized/basic_num": annotations["2-normalized"][
"2-1-basic-num"]["caption"],
"caption/normalized/advanced_equation_bracket":
annotations["2-normalized"][
"2-2-advanced-euqation-bracket"]["caption"]
}
|