cooleel commited on
Commit
09f741e
1 Parent(s): 5552928

Upload xfund.py

Browse files
Files changed (1) hide show
  1. xfund.py +158 -0
xfund.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ import json
4
+ import os
5
+
6
+ from PIL import Image
7
+
8
+ import datasets
9
+
10
+ def load_image(image_path):
11
+ image = Image.open(image_path).convert("RGB")
12
+ w, h = image.size
13
+ return image, (w, h)
14
+
15
+ def normalize_bbox(bbox, size):
16
+ width, height = size
17
+ def clip(min_num, num, max_num):
18
+ return min(max(num, min_num), max_num)
19
+
20
+ x0, y0, x1, y1 = bbox
21
+ x0 = clip(0, int((x0 / width) * 1000), 1000)
22
+ y0 = clip(0, int((y0 / height) * 1000), 1000)
23
+ x1 = clip(0, int((x1 / width) * 1000), 1000)
24
+ y1 = clip(0, int((y1 / height) * 1000), 1000)
25
+ assert x1 >= x0
26
+ assert y1 >= y0
27
+ return [x0, y0, x1, y1]
28
+
29
+ logger = datasets.logging.get_logger(__name__)
30
+
31
+
32
+ _CITATION = """\
33
+ @inproceedings{xu-etal-2022-xfund,
34
+ title = "{XFUND}: A Benchmark Dataset for Multilingual Visually Rich Form Understanding",
35
+ author = "Xu, Yiheng and
36
+ Lv, Tengchao and
37
+ Cui, Lei and
38
+ Wang, Guoxin and
39
+ Lu, Yijuan and
40
+ Florencio, Dinei and
41
+ Zhang, Cha and
42
+ Wei, Furu",
43
+ booktitle = "Findings of the Association for Computational Linguistics: ACL 2022",
44
+ month = may,
45
+ year = "2022",
46
+ address = "Dublin, Ireland",
47
+ publisher = "Association for Computational Linguistics",
48
+ url = "https://aclanthology.org/2022.findings-acl.253",
49
+ doi = "10.18653/v1/2022.findings-acl.253",
50
+ pages = "3214--3224",
51
+ abstract = "Multimodal pre-training with text, layout, and image has achieved SOTA performance for visually rich document understanding tasks recently, which demonstrates the great potential for joint learning across different modalities. However, the existed research work has focused only on the English domain while neglecting the importance of multilingual generalization. In this paper, we introduce a human-annotated multilingual form understanding benchmark dataset named XFUND, which includes form understanding samples in 7 languages (Chinese, Japanese, Spanish, French, Italian, German, Portuguese). Meanwhile, we present LayoutXLM, a multimodal pre-trained model for multilingual document understanding, which aims to bridge the language barriers for visually rich document understanding. Experimental results show that the LayoutXLM model has significantly outperformed the existing SOTA cross-lingual pre-trained models on the XFUND dataset. The XFUND dataset and the pre-trained LayoutXLM model have been publicly available at https://aka.ms/layoutxlm.",
52
+ }
53
+ """
54
+
55
+ _DESCRIPTION = """\
56
+ https://github.com/doc-analysis/XFUND
57
+ """
58
+
59
+
60
+ _LANG = ["de", "es", "fr", "it", "ja", "pt", "zh"]
61
+ _URL = "https://github.com/doc-analysis/XFUND/releases/download/v1.0"
62
+
63
+
64
+ class XFund(datasets.GeneratorBasedBuilder):
65
+ """XFund dataset."""
66
+
67
+ BUILDER_CONFIGS = [
68
+ datasets.BuilderConfig(name=f"{lang}", version=datasets.Version("1.0.0"), description=f"XFUND {lang} dataset") for lang in _LANG
69
+ ]
70
+
71
+ def _info(self):
72
+ return datasets.DatasetInfo(
73
+ description=_DESCRIPTION,
74
+ features=datasets.Features(
75
+ {
76
+ "id": datasets.Value("string"),
77
+ "tokens": datasets.Sequence(datasets.Value("string")),
78
+ "bboxes": datasets.Sequence(datasets.Sequence(datasets.Value("int64"))),
79
+ "tags": datasets.Sequence(
80
+ datasets.features.ClassLabel(
81
+ # names=["O", "HEADER", "QUESTION", "ANSWER"]
82
+ names=["O", "B-HEADER", "I-HEADER", "B-QUESTION", "I-QUESTION", "B-ANSWER", "I-ANSWER"]
83
+ )
84
+ ),
85
+ "image": datasets.features.Image(),
86
+ }
87
+ ),
88
+ supervised_keys=None,
89
+ homepage="https://github.com/doc-analysis/XFUND",
90
+ citation=_CITATION,
91
+ )
92
+
93
+ def _split_generators(self, dl_manager):
94
+ """Returns SplitGenerators."""
95
+ lang = self.config.name
96
+ fileinfos = dl_manager.download_and_extract({
97
+ "train_image": f"{_URL}/{lang}.train.zip",
98
+ "train_annotation": f"{_URL}/{lang}.train.json",
99
+ "valid_image": f"{_URL}/{lang}.val.zip",
100
+ "valid_annotation": f"{_URL}/{lang}.val.json",
101
+ })
102
+ logger.info(f"file infos: {fileinfos}")
103
+ return [
104
+ datasets.SplitGenerator(
105
+ name=datasets.Split.TRAIN, gen_kwargs={"image_path": fileinfos['train_image'], "annotation_path": fileinfos["train_annotation"]}
106
+ ),
107
+ datasets.SplitGenerator(
108
+ name=datasets.Split.TEST, gen_kwargs={"image_path": fileinfos["valid_image"], "annotation_path": fileinfos["valid_annotation"]}
109
+ ),
110
+ ]
111
+
112
+ # def get_line_bbox(self, bboxs):
113
+ # x = [bboxs[i][j] for i in range(len(bboxs)) for j in range(0, len(bboxs[i]), 2)]
114
+ # y = [bboxs[i][j] for i in range(len(bboxs)) for j in range(1, len(bboxs[i]), 2)]
115
+
116
+ # x0, y0, x1, y1 = min(x), min(y), max(x), max(y)
117
+
118
+ # assert x1 >= x0 and y1 >= y0
119
+ # bbox = [[x0, y0, x1, y1] for _ in range(len(bboxs))]
120
+ # return bbox
121
+
122
+ def _generate_examples(self, image_path, annotation_path):
123
+ logger.info("⏳ Generating examples from = %s %s", image_path, annotation_path)
124
+ with open(annotation_path) as fi:
125
+ ann_infos = json.load(fi)
126
+ document_list = ann_infos["documents"]
127
+ for guid, doc in enumerate(document_list):
128
+ tokens, bboxes, tags = list(), list(), list()
129
+ image_file = os.path.join(image_path, doc["img"]["fname"])
130
+ # cannot load image when submit code to huggingface
131
+ # image, size = load_image(image_file)
132
+ # assert size[0] == doc["img"]["width"]
133
+ # assert size[1] == doc["img"]["height"]
134
+ size = [doc["img"]["width"], doc["img"]["height"]]
135
+
136
+ for item in doc["document"]:
137
+ # cur_line_bboxes = list()
138
+ # text, label = item["text"], item["label"]
139
+ # bbox = normalize_bbox(item["box"], size)
140
+ # if len(text) == 0:
141
+ # continue
142
+
143
+ word_box_list_raw = [w['box'] for w in item['words']]
144
+ word_box_list = [normalize_bbox(w, size) for w in word_box_list_raw]
145
+
146
+ word_text_list = [w['text'] for w in item['words']]
147
+
148
+ if item['label'] == 'other':
149
+ label_list = ['O'] * len(item['words'])
150
+
151
+ else:
152
+ label_list = [f'B-{item["label"].upper()}'] + ['I-' + item['label'].upper()] * (len(item['words']) - 1)
153
+
154
+ tokens.append(word_text_list)
155
+ bboxes.append(word_box_list)
156
+ tags.append(label_list)
157
+
158
+ yield guid, {"id": doc["id"], "tokens": tokens, "bboxes": bboxes, "tags": tags, "image": Image.open(image_file)}