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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Lint as: python3
|
2 |
+
import json
|
3 |
+
import logging
|
4 |
+
import os
|
5 |
+
|
6 |
+
import datasets
|
7 |
+
|
8 |
+
from transformers import AutoTokenizer
|
9 |
+
|
10 |
+
def load_image(image_path):
|
11 |
+
image = Image.open(image_path).convert("RGB")
|
12 |
+
w, h = image.size
|
13 |
+
# resize image to 224x224
|
14 |
+
image = image.resize((224, 224))
|
15 |
+
image = np.asarray(image)
|
16 |
+
image = image[:, :, ::-1] # flip color channels from RGB to BGR
|
17 |
+
image = image.transpose(2, 0, 1) # move channels to first dimension
|
18 |
+
return image, (w, h)
|
19 |
+
|
20 |
+
|
21 |
+
def normalize_bbox(bbox, size):
|
22 |
+
return [
|
23 |
+
int(1000 * bbox[0] / size[0]),
|
24 |
+
int(1000 * bbox[1] / size[1]),
|
25 |
+
int(1000 * bbox[2] / size[0]),
|
26 |
+
int(1000 * bbox[3] / size[1]),
|
27 |
+
]
|
28 |
+
|
29 |
+
|
30 |
+
def simplify_bbox(bbox):
|
31 |
+
return [
|
32 |
+
min(bbox[0::2]),
|
33 |
+
min(bbox[1::2]),
|
34 |
+
max(bbox[2::2]),
|
35 |
+
max(bbox[3::2]),
|
36 |
+
]
|
37 |
+
|
38 |
+
|
39 |
+
def merge_bbox(bbox_list):
|
40 |
+
x0, y0, x1, y1 = list(zip(*bbox_list))
|
41 |
+
return [min(x0), min(y0), max(x1), max(y1)]
|
42 |
+
|
43 |
+
|
44 |
+
_URL = "https://github.com/doc-analysis/XFUN/releases/download/v1.0/"
|
45 |
+
|
46 |
+
_LANG = ["zh", "de", "es", "fr", "en", "it", "ja", "pt"]
|
47 |
+
logger = logging.getLogger(__name__)
|
48 |
+
|
49 |
+
|
50 |
+
class XFUNConfig(datasets.BuilderConfig):
|
51 |
+
"""BuilderConfig for XFUN."""
|
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(XFUNConfig, self).__init__(**kwargs)
|
60 |
+
self.lang = lang
|
61 |
+
self.additional_langs = additional_langs
|
62 |
+
|
63 |
+
|
64 |
+
class XFUN(datasets.GeneratorBasedBuilder):
|
65 |
+
"""XFUN dataset."""
|
66 |
+
|
67 |
+
BUILDER_CONFIGS = [XFUNConfig(name=f"xfun.{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 |
+
for token_id, offset in zip(tokenized_inputs["input_ids"], tokenized_inputs["offset_mapping"]):
|
167 |
+
if token_id == 6:
|
168 |
+
bbox.append(None)
|
169 |
+
continue
|
170 |
+
text_length += offset[1] - offset[0]
|
171 |
+
tmp_box = []
|
172 |
+
while ocr_length < text_length:
|
173 |
+
ocr_word = line["words"].pop(0)
|
174 |
+
ocr_length += len(
|
175 |
+
self.tokenizer._tokenizer.normalizer.normalize_str(ocr_word["text"].strip())
|
176 |
+
)
|
177 |
+
tmp_box.append(simplify_bbox(ocr_word["box"]))
|
178 |
+
if len(tmp_box) == 0:
|
179 |
+
tmp_box = last_box
|
180 |
+
bbox.append(normalize_bbox(merge_bbox(tmp_box), size))
|
181 |
+
last_box = tmp_box # noqa
|
182 |
+
bbox = [
|
183 |
+
[bbox[i + 1][0], bbox[i + 1][1], bbox[i + 1][0], bbox[i + 1][1]] if b is None else b
|
184 |
+
for i, b in enumerate(bbox)
|
185 |
+
]
|
186 |
+
if line["label"] == "other":
|
187 |
+
label = ["O"] * len(bbox)
|
188 |
+
else:
|
189 |
+
label = [f"I-{line['label'].upper()}"] * len(bbox)
|
190 |
+
label[0] = f"B-{line['label'].upper()}"
|
191 |
+
tokenized_inputs.update({"bbox": bbox, "labels": label})
|
192 |
+
if label[0] != "O":
|
193 |
+
entity_id_to_index_map[line["id"]] = len(entities)
|
194 |
+
entities.append(
|
195 |
+
{
|
196 |
+
"start": len(tokenized_doc["input_ids"]),
|
197 |
+
"end": len(tokenized_doc["input_ids"]) + len(tokenized_inputs["input_ids"]),
|
198 |
+
"label": line["label"].upper(),
|
199 |
+
}
|
200 |
+
)
|
201 |
+
for i in tokenized_doc:
|
202 |
+
tokenized_doc[i] = tokenized_doc[i] + tokenized_inputs[i]
|
203 |
+
relations = list(set(relations))
|
204 |
+
relations = [rel for rel in relations if rel[0] not in empty_entity and rel[1] not in empty_entity]
|
205 |
+
kvrelations = []
|
206 |
+
for rel in relations:
|
207 |
+
pair = [id2label[rel[0]], id2label[rel[1]]]
|
208 |
+
if pair == ["question", "answer"]:
|
209 |
+
kvrelations.append(
|
210 |
+
{"head": entity_id_to_index_map[rel[0]], "tail": entity_id_to_index_map[rel[1]]}
|
211 |
+
)
|
212 |
+
elif pair == ["answer", "question"]:
|
213 |
+
kvrelations.append(
|
214 |
+
{"head": entity_id_to_index_map[rel[1]], "tail": entity_id_to_index_map[rel[0]]}
|
215 |
+
)
|
216 |
+
else:
|
217 |
+
continue
|
218 |
+
|
219 |
+
def get_relation_span(rel):
|
220 |
+
bound = []
|
221 |
+
for entity_index in [rel["head"], rel["tail"]]:
|
222 |
+
bound.append(entities[entity_index]["start"])
|
223 |
+
bound.append(entities[entity_index]["end"])
|
224 |
+
return min(bound), max(bound)
|
225 |
+
|
226 |
+
relations = sorted(
|
227 |
+
[
|
228 |
+
{
|
229 |
+
"head": rel["head"],
|
230 |
+
"tail": rel["tail"],
|
231 |
+
"start_index": get_relation_span(rel)[0],
|
232 |
+
"end_index": get_relation_span(rel)[1],
|
233 |
+
}
|
234 |
+
for rel in kvrelations
|
235 |
+
],
|
236 |
+
key=lambda x: x["head"],
|
237 |
+
)
|
238 |
+
chunk_size = 512
|
239 |
+
for chunk_id, index in enumerate(range(0, len(tokenized_doc["input_ids"]), chunk_size)):
|
240 |
+
item = {}
|
241 |
+
for k in tokenized_doc:
|
242 |
+
item[k] = tokenized_doc[k][index : index + chunk_size]
|
243 |
+
entities_in_this_span = []
|
244 |
+
global_to_local_map = {}
|
245 |
+
for entity_id, entity in enumerate(entities):
|
246 |
+
if (
|
247 |
+
index <= entity["start"] < index + chunk_size
|
248 |
+
and index <= entity["end"] < index + chunk_size
|
249 |
+
):
|
250 |
+
entity["start"] = entity["start"] - index
|
251 |
+
entity["end"] = entity["end"] - index
|
252 |
+
global_to_local_map[entity_id] = len(entities_in_this_span)
|
253 |
+
entities_in_this_span.append(entity)
|
254 |
+
relations_in_this_span = []
|
255 |
+
for relation in relations:
|
256 |
+
if (
|
257 |
+
index <= relation["start_index"] < index + chunk_size
|
258 |
+
and index <= relation["end_index"] < index + chunk_size
|
259 |
+
):
|
260 |
+
relations_in_this_span.append(
|
261 |
+
{
|
262 |
+
"head": global_to_local_map[relation["head"]],
|
263 |
+
"tail": global_to_local_map[relation["tail"]],
|
264 |
+
"start_index": relation["start_index"] - index,
|
265 |
+
"end_index": relation["end_index"] - index,
|
266 |
+
}
|
267 |
+
)
|
268 |
+
item.update(
|
269 |
+
{
|
270 |
+
"id": f"{doc['id']}_{chunk_id}",
|
271 |
+
"image": image,
|
272 |
+
"entities": entities_in_this_span,
|
273 |
+
"relations": relations_in_this_span,
|
274 |
+
}
|
275 |
+
)
|
276 |
+
yield f"{doc['id']}_{chunk_id}", item
|