nielsr HF staff commited on
Commit
9ef0b48
1 Parent(s): 30c1a23

Create cord-layoutlmv3.py

Browse files
Files changed (1) hide show
  1. cord-layoutlmv3.py +182 -0
cord-layoutlmv3.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ Reference: https://huggingface.co/datasets/pierresi/cord/blob/main/cord.py
3
+ '''
4
+
5
+
6
+ import json
7
+ import os
8
+ from pathlib import Path
9
+ import datasets
10
+ logger = datasets.logging.get_logger(__name__)
11
+ _CITATION = """\
12
+ @article{park2019cord,
13
+ title={CORD: A Consolidated Receipt Dataset for Post-OCR Parsing},
14
+ author={Park, Seunghyun and Shin, Seung and Lee, Bado and Lee, Junyeop and Surh, Jaeheung and Seo, Minjoon and Lee, Hwalsuk}
15
+ booktitle={Document Intelligence Workshop at Neural Information Processing Systems}
16
+ year={2019}
17
+ }
18
+ """
19
+ _DESCRIPTION = """\
20
+ https://github.com/clovaai/cord/
21
+ """
22
+
23
+ def load_image(image_path):
24
+ image = Image.open(image_path).convert("RGB")
25
+ w, h = image.size
26
+ return image, (w, h)
27
+
28
+ def normalize_bbox(bbox, size):
29
+ return [
30
+ int(1000 * bbox[0] / size[0]),
31
+ int(1000 * bbox[1] / size[1]),
32
+ int(1000 * bbox[2] / size[0]),
33
+ int(1000 * bbox[3] / size[1]),
34
+ ]
35
+
36
+ def quad_to_box(quad):
37
+ # test 87 is wrongly annotated
38
+ box = (
39
+ max(0, quad["x1"]),
40
+ max(0, quad["y1"]),
41
+ quad["x3"],
42
+ quad["y3"]
43
+ )
44
+ if box[3] < box[1]:
45
+ bbox = list(box)
46
+ tmp = bbox[3]
47
+ bbox[3] = bbox[1]
48
+ bbox[1] = tmp
49
+ box = tuple(bbox)
50
+ if box[2] < box[0]:
51
+ bbox = list(box)
52
+ tmp = bbox[2]
53
+ bbox[2] = bbox[0]
54
+ bbox[0] = tmp
55
+ box = tuple(bbox)
56
+ return box
57
+
58
+ def _get_drive_url(url):
59
+ base_url = 'https://drive.google.com/uc?id='
60
+ split_url = url.split('/')
61
+ return base_url + split_url[5]
62
+
63
+ _URLS = [
64
+ _get_drive_url("https://drive.google.com/file/d/1MqhTbcj-AHXOqYoeoh12aRUwIprzTJYI/"),
65
+ _get_drive_url("https://drive.google.com/file/d/1wYdp5nC9LnHQZ2FcmOoC0eClyWvcuARU/")
66
+ # If you failed to download the dataset through the automatic downloader,
67
+ # you can download it manually and modify the code to get the local dataset.
68
+ # Or you can use the following links. Please follow the original LICENSE of CORD for usage.
69
+ # "https://layoutlm.blob.core.windows.net/cord/CORD-1k-001.zip",
70
+ # "https://layoutlm.blob.core.windows.net/cord/CORD-1k-002.zip"
71
+ ]
72
+
73
+ class CordConfig(datasets.BuilderConfig):
74
+ """BuilderConfig for CORD"""
75
+ def __init__(self, **kwargs):
76
+ """BuilderConfig for CORD.
77
+ Args:
78
+ **kwargs: keyword arguments forwarded to super.
79
+ """
80
+ super(CordConfig, self).__init__(**kwargs)
81
+
82
+ class Cord(datasets.GeneratorBasedBuilder):
83
+ BUILDER_CONFIGS = [
84
+ CordConfig(name="cord", version=datasets.Version("1.0.0"), description="CORD dataset"),
85
+ ]
86
+
87
+ def _info(self):
88
+ return datasets.DatasetInfo(
89
+ description=_DESCRIPTION,
90
+ features=datasets.Features(
91
+ {
92
+ "id": datasets.Value("string"),
93
+ "words": datasets.Sequence(datasets.Value("string")),
94
+ "bboxes": datasets.Sequence(datasets.Sequence(datasets.Value("int64"))),
95
+ "ner_tags": datasets.Sequence(
96
+ datasets.features.ClassLabel(
97
+ names=["O","B-MENU.NM","B-MENU.NUM","B-MENU.UNITPRICE","B-MENU.CNT","B-MENU.DISCOUNTPRICE","B-MENU.PRICE","B-MENU.ITEMSUBTOTAL","B-MENU.VATYN","B-MENU.ETC","B-MENU.SUB_NM","B-MENU.SUB_UNITPRICE","B-MENU.SUB_CNT","B-MENU.SUB_PRICE","B-MENU.SUB_ETC","B-VOID_MENU.NM","B-VOID_MENU.PRICE","B-SUB_TOTAL.SUBTOTAL_PRICE","B-SUB_TOTAL.DISCOUNT_PRICE","B-SUB_TOTAL.SERVICE_PRICE","B-SUB_TOTAL.OTHERSVC_PRICE","B-SUB_TOTAL.TAX_PRICE","B-SUB_TOTAL.ETC","B-TOTAL.TOTAL_PRICE","B-TOTAL.TOTAL_ETC","B-TOTAL.CASHPRICE","B-TOTAL.CHANGEPRICE","B-TOTAL.CREDITCARDPRICE","B-TOTAL.EMONEYPRICE","B-TOTAL.MENUTYPE_CNT","B-TOTAL.MENUQTY_CNT","I-MENU.NM","I-MENU.NUM","I-MENU.UNITPRICE","I-MENU.CNT","I-MENU.DISCOUNTPRICE","I-MENU.PRICE","I-MENU.ITEMSUBTOTAL","I-MENU.VATYN","I-MENU.ETC","I-MENU.SUB_NM","I-MENU.SUB_UNITPRICE","I-MENU.SUB_CNT","I-MENU.SUB_PRICE","I-MENU.SUB_ETC","I-VOID_MENU.NM","I-VOID_MENU.PRICE","I-SUB_TOTAL.SUBTOTAL_PRICE","I-SUB_TOTAL.DISCOUNT_PRICE","I-SUB_TOTAL.SERVICE_PRICE","I-SUB_TOTAL.OTHERSVC_PRICE","I-SUB_TOTAL.TAX_PRICE","I-SUB_TOTAL.ETC","I-TOTAL.TOTAL_PRICE","I-TOTAL.TOTAL_ETC","I-TOTAL.CASHPRICE","I-TOTAL.CHANGEPRICE","I-TOTAL.CREDITCARDPRICE","I-TOTAL.EMONEYPRICE","I-TOTAL.MENUTYPE_CNT","I-TOTAL.MENUQTY_CNT"]
98
+ )
99
+ ),
100
+ "image": datasets.features.Image(),
101
+ }
102
+ ),
103
+ supervised_keys=None,
104
+ citation=_CITATION,
105
+ homepage="https://github.com/clovaai/cord/",
106
+ )
107
+
108
+ def _split_generators(self, dl_manager):
109
+ """Returns SplitGenerators."""
110
+ """Uses local files located with data_dir"""
111
+ downloaded_file = dl_manager.download_and_extract(_URLS)
112
+ # move files from the second URL together with files from the first one.
113
+ dest = Path(downloaded_file[0])/"CORD"
114
+ for split in ["train", "dev", "test"]:
115
+ for file_type in ["image", "json"]:
116
+ if split == "test" and file_type == "json":
117
+ continue
118
+ files = (Path(downloaded_file[1])/"CORD"/split/file_type).iterdir()
119
+ for f in files:
120
+ os.rename(f, dest/split/file_type/f.name)
121
+ return [
122
+ datasets.SplitGenerator(
123
+ name=datasets.Split.TRAIN, gen_kwargs={"filepath": dest/"train"}
124
+ ),
125
+ datasets.SplitGenerator(
126
+ name=datasets.Split.VALIDATION, gen_kwargs={"filepath": dest/"dev"}
127
+ ),
128
+ datasets.SplitGenerator(
129
+ name=datasets.Split.TEST, gen_kwargs={"filepath": dest/"test"}
130
+ ),
131
+ ]
132
+
133
+ def get_line_bbox(self, bboxs):
134
+ x = [bboxs[i][j] for i in range(len(bboxs)) for j in range(0, len(bboxs[i]), 2)]
135
+ y = [bboxs[i][j] for i in range(len(bboxs)) for j in range(1, len(bboxs[i]), 2)]
136
+
137
+ x0, y0, x1, y1 = min(x), min(y), max(x), max(y)
138
+
139
+ assert x1 >= x0 and y1 >= y0
140
+ bbox = [[x0, y0, x1, y1] for _ in range(len(bboxs))]
141
+ return bbox
142
+
143
+ def _generate_examples(self, filepath):
144
+ logger.info("⏳ Generating examples from = %s", filepath)
145
+ ann_dir = os.path.join(filepath, "json")
146
+ img_dir = os.path.join(filepath, "image")
147
+ for guid, file in enumerate(sorted(os.listdir(ann_dir))):
148
+ words = []
149
+ bboxes = []
150
+ ner_tags = []
151
+ file_path = os.path.join(ann_dir, file)
152
+ with open(file_path, "r", encoding="utf8") as f:
153
+ data = json.load(f)
154
+ image_path = os.path.join(img_dir, file)
155
+ image_path = image_path.replace("json", "png")
156
+ image, size = load_image(image_path)
157
+ for item in data["valid_line"]:
158
+ cur_line_bboxes = []
159
+ line_words, label = item["words"], item["category"]
160
+ line_words = [w for w in line_words if w["text"].strip() != ""]
161
+ if len(line_words) == 0:
162
+ continue
163
+ if label == "other":
164
+ for w in line_words:
165
+ words.append(w["text"])
166
+ ner_tags.append("O")
167
+ cur_line_bboxes.append(normalize_bbox(quad_to_box(w["quad"]), size))
168
+ else:
169
+ words.append(line_words[0]["text"])
170
+ ner_tags.append("B-" + label.upper())
171
+ cur_line_bboxes.append(normalize_bbox(quad_to_box(line_words[0]["quad"]), size))
172
+ for w in line_words[1:]:
173
+ words.append(w["text"])
174
+ ner_tags.append("I-" + label.upper())
175
+ cur_line_bboxes.append(normalize_bbox(quad_to_box(w["quad"]), size))
176
+ # by default: --segment_level_layout 1
177
+ # if do not want to use segment_level_layout, comment the following line
178
+ cur_line_bboxes = self.get_line_bbox(cur_line_bboxes)
179
+ bboxes.extend(cur_line_bboxes)
180
+ # yield guid, {"id": str(guid), "words": words, "bboxes": bboxes, "ner_tags": ner_tags, "image": image}
181
+ yield guid, {"id": str(guid), "words": words, "bboxes": bboxes, "ner_tags": ner_tags,
182
+ "image": image}