AzadDjan commited on
Commit
1d397fe
1 Parent(s): b3ef950

Create cord.py

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