nvm472001 commited on
Commit
ce861db
·
1 Parent(s): c4bcf1d

first commit with init v1 xfun cv dataset

Browse files
Files changed (1) hide show
  1. xfun-layoutxlm-cvdataset.py +199 -0
xfun-layoutxlm-cvdataset.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ from pathlib import Path
4
+ import pandas as pd
5
+
6
+ import datasets
7
+ from PIL import Image
8
+ import numpy as np
9
+
10
+ from transformers import AutoTokenizer
11
+
12
+ logger = datasets.logging.get_logger(__name__)
13
+ _CITATION = """\
14
+ @article{LayoutXLM for CV extractions,
15
+ title={LayoutXLM for Key Information Extraction},
16
+ author={Liharding Nguyen},
17
+ year={2023},
18
+ }
19
+ """
20
+ _DESCRIPTION = """\
21
+ CV is a collection of receipts. It contains, for each photo about cv personal, a list of OCRs - with the bounding box, text, and class. The goal is to benchmark "key information extraction" - extracting key information from documents
22
+ """
23
+
24
+ def load_image(image_path, size=None):
25
+ image = Image.open(image_path).convert("RGB")
26
+ w, h = image.size
27
+
28
+ if size is not None:
29
+ image = image.resize((size, size))
30
+ image = np.asarray(image)
31
+ image = image[:, :, ::-1]
32
+ image = image.transpose(2, 0, 1)
33
+
34
+ return image, (w, h)
35
+
36
+ def normalize_bbox(bbox, size):
37
+ return [
38
+ int(1000 * bbox[0] / size[0]),
39
+ int(1000 * bbox[1] / size[1]),
40
+ int(1000 * bbox[2] / size[0]),
41
+ int(1000 * bbox[3] / size[1]),
42
+ ]
43
+
44
+
45
+ def simplify_bbox(bbox):
46
+ return [
47
+ min(bbox[0::2]),
48
+ min(bbox[1::2]),
49
+ max(bbox[2::2]),
50
+ max(bbox[3::2]),
51
+ ]
52
+
53
+
54
+ def merge_bbox(bbox_list):
55
+ x0, y0, x1, y1 = list(zip(*bbox_list))
56
+ return [min(x0), min(y0), max(x1), max(y1)]
57
+
58
+
59
+ def _get_drive_url(url):
60
+ base_url = 'https://drive.google.com/uc?id='
61
+ split_url = url.split('/')
62
+
63
+ return base_url + split_url[5]
64
+
65
+
66
+ _URLS = [
67
+ _get_drive_url("https://drive.google.com/file/d/11SRDeRKUr8XacB7tauiGjkw1PXDGFKUx/"),
68
+ _get_drive_url("https://drive.google.com/file/d/1KdDBmGP96lFc7jv2Bf4eqrO121ST-TCh/"),
69
+ ]
70
+
71
+
72
+ class DatasetConfig(datasets.BuilderConfig):
73
+ """BuilderConfig for WildReceipt Dataset"""
74
+ def __init__(self, **kwargs):
75
+ """BuilderConfig for WildReceipt Dataset.
76
+ Args:
77
+ **kwargs: keyword arguments forwarded to super.
78
+ """
79
+ super(DatasetConfig, self).__init__(**kwargs)
80
+
81
+
82
+
83
+ class XFUN_CV(datasets.GeneratorBasedBuilder):
84
+
85
+ BUILDER_CONFIGS = [
86
+ DatasetConfig(name="CV Extractions", version=datasets.Version("1.0.0"), description="CV dataset"),
87
+ ]
88
+
89
+ tokenizer = AutoTokenizer.from_pretrained("xlm-roberta-base")\
90
+
91
+
92
+ def _info(self):
93
+ return datasets.DatasetInfo(
94
+ features=datasets.Features({
95
+ "id": datasets.Value("string"),
96
+ "input_ids": datasets.Sequence(datasets.Value("int64")),
97
+ "bbox": datasets.Sequence(datasets.Sequence(datasets.Value("int64"))),
98
+ "labels": datasets.Sequence(
99
+ datasets.ClassLabel(
100
+ names=['person_name', 'dob_key', 'dob_value', 'gender_key', 'gender_value', 'phonenumber_key', 'phonenumber_value', 'email_key', 'email_value', 'address_key', 'address_value', 'socical_address_value', 'education', 'education_name', 'education_time', 'experience', 'experience_name', 'experience_time', 'information', 'undefined']
101
+ )
102
+ ),
103
+ "image": datasets.Array3D(shape=(3, 224, 224), dtype="uint8"),
104
+ "original_image": datasets.features.Image()
105
+ }),
106
+ supervised_keys=None,
107
+ citation=_CITATION,
108
+ homepage="")
109
+
110
+ def _split_generators(self, dl_manager):
111
+ downloaded_file = dl_manager.download_and_extract(_URLS)
112
+ dest = Path(downloaded_file[0])/'data1'
113
+
114
+ return [
115
+ datasets.SplitGenerator(
116
+ name=datasets.Split.TRAIN, gen_kwargs={"filepath": dest/"train.txt", "dest": dest}
117
+ ),
118
+ datasets.SplitGenerator(
119
+ name=datasets.Split.TEST, gen_kwargs={"filepath": dest/"test.txt", "dest": dest}
120
+ ),
121
+ ]
122
+
123
+ def _generate_examples(self, filepath, dest):
124
+ df = pd.read_csv(dest/'class_list.txt', delimiter='\s', header=None)
125
+ id2labels = dict(zip(df[0].tolist(), df[1].tolist()))
126
+
127
+
128
+ logger.info("⏳ Generating examples from = %s", filepath)
129
+
130
+ data = []
131
+ with open(filepath, 'r') as f:
132
+ for line in f:
133
+ data.append(line.rstrip('\n\r'))
134
+
135
+ for guid, line in enumerate(data):
136
+ docs = json.loads(line)
137
+ image_path = dest/data['file_name']
138
+ image, size = load_image(image_path, size=224)
139
+ original_image, _ = load_image(image_path)
140
+ document = docs["annotations"]
141
+ tokenized_doc = {"input_ids": [], "bbox": [], "labels": []}
142
+
143
+ for annotation in document:
144
+ tokenized_inputs = self.tokenizer(
145
+ annotation["text"],
146
+ add_special_tokens=False,
147
+ return_offsets_mapping=True,
148
+ return_attention_mask=False,
149
+ )
150
+
151
+ text_length = 0
152
+ ocr_length = 0
153
+ bbox = []
154
+
155
+ for token_id, offset in zip(tokenized_inputs["input_ids"], tokenized_inputs["offset_mapping"]):
156
+ if token_id == 6:
157
+ bbox.append(None)
158
+ continue
159
+
160
+ text_length += offset[1] - offset[0]
161
+ tmp_box = []
162
+
163
+ while ocr_length < text_length:
164
+ ocr_word = annotation["text"]
165
+ ocr_length += len(
166
+ self.tokenizer._tokenizer.normalizer.normalize_str(ocr_word.strip())
167
+ )
168
+ tmp_box.append(simplify_bbox(annotation["box"]))
169
+
170
+ if len(tmp_box) == 0:
171
+ tmp_box = last_box
172
+
173
+ bbox.append(normalize_bbox(merge_bbox(tmp_box), size))
174
+ last_box = tmp_box
175
+
176
+ bbox = [
177
+ [bbox[i + 1][0], bbox[i + 1][1], bbox[i + 1][0], bbox[i + 1][1]] if b is None else b
178
+ for i, b in enumerate(bbox)
179
+ ]
180
+
181
+ label = annotation["label"] * len(bbox)
182
+ tokenized_inputs.update({"bbox": bbox, "labels": label})
183
+
184
+ for i in tokenized_doc:
185
+ tokenized_doc[i] = tokenized_doc[i] + tokenized_inputs[i]
186
+
187
+ chunk_size = 512
188
+ for chunk_id, index in enumerate(range(0, len(tokenized_doc["input_ids"]), chunk_size)):
189
+ item = {}
190
+ for k in tokenized_doc:
191
+ item[k] = tokenized_doc[k][index : index + chunk_size]
192
+
193
+ item.update({
194
+ "id": str(guid),
195
+ "image": image,
196
+ "original_image": original_image,
197
+ })
198
+
199
+ yield guid, item