hcsun commited on
Commit
2a2bbe3
·
verified ·
1 Parent(s): fe12f39

Upload cord.py

Browse files
Files changed (1) hide show
  1. cord.py +166 -0
cord.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ Reference: https://huggingface.co/datasets/pierresi/cord/blob/main/cord.py
3
+ '''
4
+
5
+ import json
6
+ import os
7
+ from pathlib import Path
8
+
9
+ import datasets
10
+ from PIL import Image
11
+
12
+ logger = datasets.logging.get_logger(__name__)
13
+
14
+ _CITATION = """\
15
+ @article{park2019cord,
16
+ title={CORD: A Consolidated Receipt Dataset for Post-OCR Parsing},
17
+ author={Park, Seunghyun and Shin, Seung and Lee, Bado and Lee, Junyeop and Surh, Jaeheung and Seo, Minjoon and Lee, Hwalsuk}
18
+ booktitle={Document Intelligence Workshop at Neural Information Processing Systems}
19
+ year={2019}
20
+ }
21
+ """
22
+
23
+ _DESCRIPTION = "https://github.com/clovaai/cord/"
24
+
25
+ _URLS = [
26
+ "https://hcsun.net/assets/files/CORD-1k-001.zip",
27
+ "https://hcsun.net/assets/files/CORD-1k-002.zip"
28
+ ]
29
+
30
+ class Cord(datasets.GeneratorBasedBuilder):
31
+ BUILDER_CONFIGS = [
32
+ datasets.BuilderConfig(
33
+ name="cord",
34
+ version=datasets.Version("1.0.0"),
35
+ description="CORD dataset"
36
+ ),
37
+ ]
38
+
39
+ def _info(self):
40
+ return datasets.DatasetInfo(
41
+ description=_DESCRIPTION,
42
+ features=datasets.Features(
43
+ {
44
+ "id": datasets.Value("string"),
45
+ "words": datasets.Sequence(datasets.Value("string")),
46
+ "bboxes": datasets.Sequence(datasets.Sequence(datasets.Value("int64"))),
47
+ "ner_tags": datasets.Sequence(
48
+ datasets.features.ClassLabel(
49
+ 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"]
50
+ )
51
+ ),
52
+ "image": datasets.features.Image(),
53
+ }
54
+ ),
55
+ supervised_keys=None,
56
+ citation=_CITATION,
57
+ homepage="https://github.com/clovaai/cord/",
58
+ )
59
+
60
+ def _split_generators(self, dl_manager):
61
+ downloaded_file = dl_manager.download_and_extract(_URLS)
62
+ dest = Path(downloaded_file[0])/"CORD"
63
+ self._move_files_to_dest(downloaded_file, dest)
64
+ return [
65
+ datasets.SplitGenerator(
66
+ name=datasets.Split.TRAIN, gen_kwargs={"filepath": dest/"train"}
67
+ ),
68
+ datasets.SplitGenerator(
69
+ name=datasets.Split.VALIDATION, gen_kwargs={"filepath": dest/"dev"}
70
+ ),
71
+ datasets.SplitGenerator(
72
+ name=datasets.Split.TEST, gen_kwargs={"filepath": dest/"test"}
73
+ ),
74
+ ]
75
+
76
+ def _move_files_to_dest(self, downloaded_file, dest):
77
+ for split in ["train", "dev", "test"]:
78
+ for file_type in ["image", "json"]:
79
+ if split == "test" and file_type == "json":
80
+ continue
81
+ files = (Path(downloaded_file[1])/"CORD"/split/file_type).iterdir()
82
+ for f in files:
83
+ os.rename(f, dest/split/file_type/f.name)
84
+
85
+ def _generate_examples(self, filepath):
86
+ logger.info("⏳ Generating examples from = %s", filepath)
87
+ ann_dir = os.path.join(filepath, "json")
88
+ img_dir = os.path.join(filepath, "image")
89
+ for guid, file in enumerate(sorted(os.listdir(ann_dir))):
90
+ file_path = os.path.join(ann_dir, file)
91
+ with open(file_path, "r", encoding="utf8") as f:
92
+ data = json.load(f)
93
+ image_path = os.path.join(img_dir, file).replace("json", "png")
94
+ image, size = self._load_image(image_path)
95
+ words, bboxes, ner_tags = self._process_data(data, size)
96
+ yield guid, {"id": str(guid), "words": words, "bboxes": bboxes, "ner_tags": ner_tags, "image": image}
97
+
98
+ def _load_image(self, image_path):
99
+ image = Image.open(image_path).convert("RGB")
100
+ w, h = image.size
101
+ return image, (w, h)
102
+
103
+ def _process_data(self, data, size):
104
+ words = []
105
+ bboxes = []
106
+ ner_tags = []
107
+ for item in data["valid_line"]:
108
+ line_words, label = item["words"], item["category"]
109
+ line_words = [w for w in line_words if w["text"].strip() != ""]
110
+ if len(line_words) == 0:
111
+ continue
112
+ cur_line_bboxes = self._process_line_words(line_words, label, size, words, ner_tags)
113
+ bboxes.extend(cur_line_bboxes)
114
+ return words, bboxes, ner_tags
115
+
116
+ def _process_line_words(self, line_words, label, size, words, ner_tags):
117
+ cur_line_bboxes = []
118
+ if label == "other":
119
+ for w in line_words:
120
+ words.append(w["text"])
121
+ ner_tags.append("O")
122
+ cur_line_bboxes.append(self._normalize_bbox(self._quad_to_box(w["quad"]), size))
123
+ else:
124
+ words.append(line_words[0]["text"])
125
+ ner_tags.append("B-" + label.upper())
126
+ cur_line_bboxes.append(self._normalize_bbox(self._quad_to_box(line_words[0]["quad"]), size))
127
+ for w in line_words[1:]:
128
+ words.append(w["text"])
129
+ ner_tags.append("I-" + label.upper())
130
+ cur_line_bboxes.append(self._normalize_bbox(self._quad_to_box(w["quad"]), size))
131
+ cur_line_bboxes = self._get_line_bbox(cur_line_bboxes)
132
+ return cur_line_bboxes
133
+
134
+ def _normalize_bbox(self, bbox, size):
135
+ return [
136
+ int(1000 * bbox[0] / size[0]),
137
+ int(1000 * bbox[1] / size[1]),
138
+ int(1000 * bbox[2] / size[0]),
139
+ int(1000 * bbox[3] / size[1]),
140
+ ]
141
+
142
+ def _quad_to_box(self, quad):
143
+ box = (
144
+ max(0, quad["x1"]),
145
+ max(0, quad["y1"]),
146
+ quad["x3"],
147
+ quad["y3"]
148
+ )
149
+ if box[3] < box[1] or box[2] < box[0]:
150
+ box = self._fix_box(box)
151
+ return box
152
+
153
+ def _fix_box(self, box):
154
+ bbox = list(box)
155
+ if box[3] < box[1]:
156
+ bbox[1], bbox[3] = bbox[3], bbox[1]
157
+ if box[2] < box[0]:
158
+ bbox[0], bbox[2] = bbox[2], bbox[0]
159
+ return tuple(bbox)
160
+
161
+ def _get_line_bbox(self, bboxs):
162
+ x = [bboxs[i][j] for i in range(len(bboxs)) for j in range(0, len(bboxs[i]), 2)]
163
+ y = [bboxs[i][j] for i in range(len(bboxs)) for j in range(1, len(bboxs[i]), 2)]
164
+ x0, y0, x1, y1 = min(x), min(y), max(x), max(y)
165
+ assert x1 >= x0 and y1 >= y0
166
+ return [[x0, y0, x1, y1] for _ in range(len(bboxs))]