ranpox commited on
Commit
2d654a6
1 Parent(s): 7f6a701
Files changed (1) hide show
  1. xfund.py +277 -0
xfund.py ADDED
@@ -0,0 +1,277 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Lint as: python3
2
+ import json
3
+ import logging
4
+ import os
5
+ import numpy as np
6
+ from PIL import Image
7
+ import datasets
8
+ from transformers import AutoTokenizer
9
+
10
+
11
+ _URL = "https://github.com/doc-analysis/XFUND/releases/download/v1.0/"
12
+
13
+ _LANG = ["zh", "de", "es", "fr", "en", "it", "ja", "pt"]
14
+ logger = logging.getLogger(__name__)
15
+
16
+
17
+ def normalize_bbox(bbox, size):
18
+ return [
19
+ int(1000 * bbox[0] / size[0]),
20
+ int(1000 * bbox[1] / size[1]),
21
+ int(1000 * bbox[2] / size[0]),
22
+ int(1000 * bbox[3] / size[1]),
23
+ ]
24
+
25
+
26
+ def simplify_bbox(bbox):
27
+ return [
28
+ min(bbox[0::2]),
29
+ min(bbox[1::2]),
30
+ max(bbox[2::2]),
31
+ max(bbox[3::2]),
32
+ ]
33
+
34
+
35
+ def merge_bbox(bbox_list):
36
+ x0, y0, x1, y1 = list(zip(*bbox_list))
37
+ return [min(x0), min(y0), max(x1), max(y1)]
38
+
39
+
40
+ def load_image(image_path):
41
+ image = Image.open(image_path).convert("RGB")
42
+ w, h = image.size
43
+ # resize image to 224x224
44
+ image = image.resize((224, 224))
45
+ image = np.asarray(image)
46
+ image = image[:, :, ::-1] # flip color channels from RGB to BGR
47
+ image = image.transpose(2, 0, 1) # move channels to first dimension
48
+ return image, (w, h)
49
+
50
+ class XFUNDConfig(datasets.BuilderConfig):
51
+ """BuilderConfig for XFUND."""
52
+
53
+ def __init__(self, lang, additional_langs=None, **kwargs):
54
+ """
55
+ Args:
56
+ lang: string, language for the input text
57
+ **kwargs: keyword arguments forwarded to super.
58
+ """
59
+ super(XFUNDConfig, self).__init__(**kwargs)
60
+ self.lang = lang
61
+ self.additional_langs = additional_langs
62
+
63
+
64
+ class XFUND(datasets.GeneratorBasedBuilder):
65
+ """XFUND dataset."""
66
+
67
+ BUILDER_CONFIGS = [XFUNDConfig(name=f"xfund.{lang}", lang=lang) for lang in _LANG]
68
+
69
+ tokenizer = AutoTokenizer.from_pretrained("xlm-roberta-base")
70
+
71
+ def _info(self):
72
+ return datasets.DatasetInfo(
73
+ features=datasets.Features(
74
+ {
75
+ "id": datasets.Value("string"),
76
+ "input_ids": datasets.Sequence(datasets.Value("int64")),
77
+ "bbox": datasets.Sequence(datasets.Sequence(datasets.Value("int64"))),
78
+ "labels": datasets.Sequence(
79
+ datasets.ClassLabel(
80
+ names=["O", "B-QUESTION", "B-ANSWER", "B-HEADER", "I-ANSWER", "I-QUESTION", "I-HEADER"]
81
+ )
82
+ ),
83
+ "image": datasets.Array3D(shape=(3, 224, 224), dtype="uint8"),
84
+ "entities": datasets.Sequence(
85
+ {
86
+ "start": datasets.Value("int64"),
87
+ "end": datasets.Value("int64"),
88
+ "label": datasets.ClassLabel(names=["HEADER", "QUESTION", "ANSWER"]),
89
+ }
90
+ ),
91
+ "relations": datasets.Sequence(
92
+ {
93
+ "head": datasets.Value("int64"),
94
+ "tail": datasets.Value("int64"),
95
+ "start_index": datasets.Value("int64"),
96
+ "end_index": datasets.Value("int64"),
97
+ }
98
+ ),
99
+ }
100
+ ),
101
+ supervised_keys=None,
102
+ )
103
+
104
+ def _split_generators(self, dl_manager):
105
+ """Returns SplitGenerators."""
106
+ urls_to_download = {
107
+ "train": [f"{_URL}{self.config.lang}.train.json", f"{_URL}{self.config.lang}.train.zip"],
108
+ "val": [f"{_URL}{self.config.lang}.val.json", f"{_URL}{self.config.lang}.val.zip"],
109
+ # "test": [f"{_URL}{self.config.lang}.test.json", f"{_URL}{self.config.lang}.test.zip"],
110
+ }
111
+ downloaded_files = dl_manager.download_and_extract(urls_to_download)
112
+ train_files_for_many_langs = [downloaded_files["train"]]
113
+ val_files_for_many_langs = [downloaded_files["val"]]
114
+ # test_files_for_many_langs = [downloaded_files["test"]]
115
+ if self.config.additional_langs:
116
+ additional_langs = self.config.additional_langs.split("+")
117
+ if "all" in additional_langs:
118
+ additional_langs = [lang for lang in _LANG if lang != self.config.lang]
119
+ for lang in additional_langs:
120
+ urls_to_download = {"train": [f"{_URL}{lang}.train.json", f"{_URL}{lang}.train.zip"]}
121
+ additional_downloaded_files = dl_manager.download_and_extract(urls_to_download)
122
+ train_files_for_many_langs.append(additional_downloaded_files["train"])
123
+
124
+ logger.info(f"Training on {self.config.lang} with additional langs({self.config.additional_langs})")
125
+ logger.info(f"Evaluating on {self.config.lang}")
126
+ logger.info(f"Testing on {self.config.lang}")
127
+ return [
128
+ datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={"filepaths": train_files_for_many_langs}),
129
+ datasets.SplitGenerator(
130
+ name=datasets.Split.VALIDATION, gen_kwargs={"filepaths": val_files_for_many_langs}
131
+ ),
132
+ # datasets.SplitGenerator(name=datasets.Split.TEST, gen_kwargs={"filepaths": test_files_for_many_langs}),
133
+ ]
134
+
135
+ def _generate_examples(self, filepaths):
136
+ for filepath in filepaths:
137
+ logger.info("Generating examples from = %s", filepath)
138
+ with open(filepath[0], "r") as f:
139
+ data = json.load(f)
140
+
141
+ for doc in data["documents"]:
142
+ doc["img"]["fpath"] = os.path.join(filepath[1], doc["img"]["fname"])
143
+ image, size = load_image(doc["img"]["fpath"])
144
+ document = doc["document"]
145
+ tokenized_doc = {"input_ids": [], "bbox": [], "labels": []}
146
+ entities = []
147
+ relations = []
148
+ id2label = {}
149
+ entity_id_to_index_map = {}
150
+ empty_entity = set()
151
+ for line in document:
152
+ if len(line["text"]) == 0:
153
+ empty_entity.add(line["id"])
154
+ continue
155
+ id2label[line["id"]] = line["label"]
156
+ relations.extend([tuple(sorted(l)) for l in line["linking"]])
157
+ tokenized_inputs = self.tokenizer(
158
+ line["text"],
159
+ add_special_tokens=False,
160
+ return_offsets_mapping=True,
161
+ return_attention_mask=False,
162
+ )
163
+ text_length = 0
164
+ ocr_length = 0
165
+ bbox = []
166
+ last_box = None
167
+ for token_id, offset in zip(tokenized_inputs["input_ids"], tokenized_inputs["offset_mapping"]):
168
+ if token_id == 6:
169
+ bbox.append(None)
170
+ continue
171
+ text_length += offset[1] - offset[0]
172
+ tmp_box = []
173
+ while ocr_length < text_length:
174
+ ocr_word = line["words"].pop(0)
175
+ ocr_length += len(
176
+ self.tokenizer._tokenizer.normalizer.normalize_str(ocr_word["text"].strip())
177
+ )
178
+ tmp_box.append(simplify_bbox(ocr_word["box"]))
179
+ if len(tmp_box) == 0:
180
+ tmp_box = last_box
181
+ bbox.append(normalize_bbox(merge_bbox(tmp_box), size))
182
+ last_box = tmp_box
183
+ bbox = [
184
+ [bbox[i + 1][0], bbox[i + 1][1], bbox[i + 1][0], bbox[i + 1][1]] if b is None else b
185
+ for i, b in enumerate(bbox)
186
+ ]
187
+ if line["label"] == "other":
188
+ label = ["O"] * len(bbox)
189
+ else:
190
+ label = [f"I-{line['label'].upper()}"] * len(bbox)
191
+ label[0] = f"B-{line['label'].upper()}"
192
+ tokenized_inputs.update({"bbox": bbox, "labels": label})
193
+ if label[0] != "O":
194
+ entity_id_to_index_map[line["id"]] = len(entities)
195
+ entities.append(
196
+ {
197
+ "start": len(tokenized_doc["input_ids"]),
198
+ "end": len(tokenized_doc["input_ids"]) + len(tokenized_inputs["input_ids"]),
199
+ "label": line["label"].upper(),
200
+ }
201
+ )
202
+ for i in tokenized_doc:
203
+ tokenized_doc[i] = tokenized_doc[i] + tokenized_inputs[i]
204
+ relations = list(set(relations))
205
+ relations = [rel for rel in relations if rel[0] not in empty_entity and rel[1] not in empty_entity]
206
+ kvrelations = []
207
+ for rel in relations:
208
+ pair = [id2label[rel[0]], id2label[rel[1]]]
209
+ if pair == ["question", "answer"]:
210
+ kvrelations.append(
211
+ {"head": entity_id_to_index_map[rel[0]], "tail": entity_id_to_index_map[rel[1]]}
212
+ )
213
+ elif pair == ["answer", "question"]:
214
+ kvrelations.append(
215
+ {"head": entity_id_to_index_map[rel[1]], "tail": entity_id_to_index_map[rel[0]]}
216
+ )
217
+ else:
218
+ continue
219
+
220
+ def get_relation_span(rel):
221
+ bound = []
222
+ for entity_index in [rel["head"], rel["tail"]]:
223
+ bound.append(entities[entity_index]["start"])
224
+ bound.append(entities[entity_index]["end"])
225
+ return min(bound), max(bound)
226
+
227
+ relations = sorted(
228
+ [
229
+ {
230
+ "head": rel["head"],
231
+ "tail": rel["tail"],
232
+ "start_index": get_relation_span(rel)[0],
233
+ "end_index": get_relation_span(rel)[1],
234
+ }
235
+ for rel in kvrelations
236
+ ],
237
+ key=lambda x: x["head"],
238
+ )
239
+ chunk_size = 512
240
+ for chunk_id, index in enumerate(range(0, len(tokenized_doc["input_ids"]), chunk_size)):
241
+ item = {}
242
+ for k in tokenized_doc:
243
+ item[k] = tokenized_doc[k][index : index + chunk_size]
244
+ entities_in_this_span = []
245
+ global_to_local_map = {}
246
+ for entity_id, entity in enumerate(entities):
247
+ if (
248
+ index <= entity["start"] < index + chunk_size
249
+ and index <= entity["end"] < index + chunk_size
250
+ ):
251
+ entity["start"] = entity["start"] - index
252
+ entity["end"] = entity["end"] - index
253
+ global_to_local_map[entity_id] = len(entities_in_this_span)
254
+ entities_in_this_span.append(entity)
255
+ relations_in_this_span = []
256
+ for relation in relations:
257
+ if (
258
+ index <= relation["start_index"] < index + chunk_size
259
+ and index <= relation["end_index"] < index + chunk_size
260
+ ):
261
+ relations_in_this_span.append(
262
+ {
263
+ "head": global_to_local_map[relation["head"]],
264
+ "tail": global_to_local_map[relation["tail"]],
265
+ "start_index": relation["start_index"] - index,
266
+ "end_index": relation["end_index"] - index,
267
+ }
268
+ )
269
+ item.update(
270
+ {
271
+ "id": f"{doc['id']}_{chunk_id}",
272
+ "image": image,
273
+ "entities": entities_in_this_span,
274
+ "relations": relations_in_this_span,
275
+ }
276
+ )
277
+ yield f"{doc['id']}_{chunk_id}", item