File size: 8,205 Bytes
08853d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c2b2493
08853d8
 
 
 
 
 
 
 
 
 
 
c2b2493
08853d8
 
 
 
 
 
 
 
 
 
 
c2b2493
08853d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
207
208
209
210
211
212
213
214
215
216
217
218
import os
import json

import datasets
from PIL import Image


_DESCRIPTION = """
The Arxiv Figure Table Database (AFTdb) facilitates the linking of documentary
objects, such as figures and tables, with their captions. This enables a
comprehensive description of document-oriented images (excluding images from
cameras). For the table component, the character structure is preserved in
addition to the image of the table and its caption. This database is ideal
for multimodal processing of documentary images.
"""
_LICENSE = "apache-2.0"
_CITATION = """
@online{AFTdb,
  AUTHOR = {Cyrile Delestre},
  URL = {},
  YEAR = {2024},
  KEYWORDS = {NLP ; Multimodal}
}
"""
_NB_TAR_FIGURE = [158, 4] # train, test
_NB_TAR_TABLE = [17, 1] # train, test


def extract_files_tar(all_path, data_dir, nb_files):
    paths = [
        os.path.join(data_dir, f"train-{ii:03d}.tar")
        for ii in range(nb_files[0])
    ]
    all_path['train'] += paths
    paths = [
        os.path.join(data_dir, f"test-{ii:03d}.tar")
        for ii in range(nb_files[1])
    ]
    all_path['test'] += paths


class AFTConfig(datasets.BuilderConfig):
    """Builder Config for AFT"""
 
    def __init__(self, nb_files_figure, nb_files_table, **kwargs):
        """BuilderConfig for Food-101.
        Args:
          data_url: `string`, url to download the zip file from.
        """
        super().__init__(version=datasets.__version__, **kwargs)
        self.nb_files_figure = nb_files_figure
        self.nb_files_table = nb_files_table


class AFT_Dataset(datasets.GeneratorBasedBuilder):
    """Arxiv Figure Table (AFT) dataset"""

    BUILDER_CONFIGS = [
        AFTConfig(
            name="figure",
            description=(
                "Dataset containing scientific article figures associated "
                "with their caption, summary, and article title."
            ),
            data_dir="./{type}",
            nb_files_figure=_NB_TAR_FIGURE,
            nb_files_table=None
        ),
        AFTConfig(
            name="table",
            description=(
                "Dataset containing tables in JPG image format from "
                "scientific articles, along with the corresponding textual "
                "representation of the table, including its caption, summary, "
                "and article title."
            ),
            data_dir="./{type}",
            nb_files_figure=None,
            nb_files_table=_NB_TAR_TABLE
        ),
        AFTConfig(
            name="figure+table",
            description=(
                "Dataset containing figure and tables in JPG image format "
                "from scientific articles, along with the corresponding "
                "textual representation of the table, including its caption, "
                "summary, and article title."
            ),
            data_dir="./{type}",
            nb_files_figure=_NB_TAR_FIGURE,
            nb_files_table=_NB_TAR_TABLE
        )
    ]

    DEFAULT_CONFIG_NAME = "figure+table"

    def _info(self):
        return datasets.DatasetInfo(
            description=_DESCRIPTION,
            features=datasets.Features(
                {
                    'id': datasets.Value('string'),
                    'paper_id': datasets.Value('string'),
                    'type': datasets.Value('string'),
                    'authors': datasets.Value('string'),
                    'categories': datasets.Value('string'),
                    'title': {
                        'english': datasets.Value('string'),
                        'french': datasets.Value('string')
                    },
                    'summary': {
                        'english': datasets.Value('string'),
                        'french': datasets.Value('string')
                    },
                    'caption': {
                        'english': datasets.Value('string'),
                        'french': datasets.Value('string')
                    },
                    'image': datasets.Image(),
                    'data': datasets.Value('string'),
                    'newcommands': datasets.Sequence(datasets.Value('string'))
                }
            ),
            citation=_CITATION,
            license=_LICENSE
        )

    def _split_generators(self, dl_manager: datasets.DownloadManager):
        all_path = dict(train=[], test=[])
        if self.config.nb_files_figure:
            extract_files_tar(
                all_path=all_path,
                data_dir=self.config.data_dir.format(type='figure'),
                nb_files=self.config.nb_files_figure
            )
        if self.config.nb_files_table:
            extract_files_tar(
                all_path=all_path,
                data_dir=self.config.data_dir.format(type='table'),
                nb_files=self.config.nb_files_table
            )
        if dl_manager.is_streaming:
            downloaded_files = dl_manager.download(all_path)
        else:
            downloaded_files = dl_manager.download_and_extract(all_path)
        return [
            datasets.SplitGenerator(
                name=datasets.Split.TRAIN,
                gen_kwargs={
                    'filepaths': downloaded_files['train'],
                    'is_streaming': dl_manager.is_streaming
                }
            ),
            datasets.SplitGenerator(
                name=datasets.Split.TEST,
                gen_kwargs={
                    "filepaths": downloaded_files['test'],
                    'is_streaming': dl_manager.is_streaming
                }
            )
        ]

    def _generate_examples(self, filepaths, is_streaming):
        if is_streaming:
            _json, _jpg = False, False
            dl_manager = datasets.DownloadManager()
            for path_tar in filepaths:
                iter_tar = dl_manager.iter_archive(path_tar)
                for path, file_obj in iter_tar:
                    if path.endswith('.json'):
                        metadata = json.load(file_obj)
                        _json = True
                    if path.endswith('.jpg'):
                        img = Image.open(file_obj)
                        _jpg = True
                    if _json and _jpg:
                        _json, _jpg = False, False
                        yield metadata['id'], {
                            'id': metadata['id'],
                            'paper_id': metadata['paper_id'],
                            'type': metadata['type'],
                            'authors': metadata['authors'],
                            'categories': metadata['categories'],
                            'title': metadata['title'],
                            'summary': metadata['summary'],
                            'caption': metadata['caption'],
                            'image': img,
                            'data': metadata['data'],
                            'newcommands': metadata['newcommands']
                        }
        else:
            for path in filepaths:
                all_file = os.listdir(path)
                all_id_obs = sorted(
                    set(map(lambda x: x.split('.')[0], all_file))
                )
                for id_obs in all_id_obs:
                    path_metadata = os.path.join(
                        path,
                        f"{id_obs}.metadata.json"
                    )
                    path_image = os.path.join(path, f"{id_obs}.image.jpg")
                    metadata = json.load(open(path_metadata, 'r'))
                    img = Image.open(path_image)
                    yield id_obs, {
                        'id': metadata['id'],
                        'paper_id': metadata['paper_id'],
                        'type': metadata['type'],
                        'authors': metadata['authors'],
                        'categories': metadata['categories'],
                        'title': metadata['title'],
                        'summary': metadata['summary'],
                        'caption': metadata['caption'],
                        'image': img,
                        'data': metadata['data'],
                        'newcommands': metadata['newcommands']
                    }