pierre-si commited on
Commit
25d5a53
1 Parent(s): cc7a893

first commit

Browse files

Files changed (1) hide show
  1. cord.py +171 -0
cord.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ import json
3
+ import os
4
+ from pathlib import Path
5
+
6
+ import datasets
7
+ from PIL import Image
8
+ # import torch
9
+ # from detectron2.data.transforms import ResizeTransform, TransformList
10
+
11
+ logger = datasets.logging.get_logger(__name__)
12
+
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 = """\
24
+ https://github.com/clovaai/cord/
25
+ """
26
+
27
+ # def load_image(image_path):
28
+ # image = read_image(image_path, format="BGR")
29
+ # h = image.shape[0]
30
+ # w = image.shape[1]
31
+ # img_trans = TransformList([ResizeTransform(h=h, w=w, new_h=224, new_w=224)])
32
+ # image = torch.tensor(img_trans.apply_image(image).copy()).permute(2, 0, 1) # copy to make it writeable
33
+ # return image, (w, h)
34
+
35
+ def load_image(image_path):
36
+ image = Image.open(image_path)
37
+ w, h = image.size
38
+ return image, (w, h)
39
+
40
+ def normalize_bbox(bbox, size):
41
+ return [
42
+ int(1000 * bbox[0] / size[0]),
43
+ int(1000 * bbox[1] / size[1]),
44
+ int(1000 * bbox[2] / size[0]),
45
+ int(1000 * bbox[3] / size[1]),
46
+ ]
47
+
48
+ def quad_to_box(quad):
49
+ # test 87 is wrongly annotated
50
+ box = (
51
+ max(0, quad["x1"]),
52
+ max(0, quad["y1"]),
53
+ quad["x3"],
54
+ quad["y3"]
55
+ )
56
+
57
+ return box
58
+
59
+ def _get_drive_url(url):
60
+ base_url = 'https://drive.google.com/uc?id='
61
+ split_url = url.split('/')
62
+ return base_url + split_url[5]
63
+
64
+ _URLS = [
65
+ _get_drive_url("https://drive.google.com/file/d/1MqhTbcj-AHXOqYoeoh12aRUwIprzTJYI/"),
66
+ _get_drive_url("https://drive.google.com/file/d/1wYdp5nC9LnHQZ2FcmOoC0eClyWvcuARU/")
67
+ ]
68
+
69
+ class CordConfig(datasets.BuilderConfig):
70
+ """BuilderConfig for CORD"""
71
+
72
+ def __init__(self, **kwargs):
73
+ """BuilderConfig for CORD.
74
+
75
+ Args:
76
+ **kwargs: keyword arguments forwarded to super.
77
+ """
78
+ super(CordConfig, self).__init__(**kwargs)
79
+
80
+
81
+ class Cord(datasets.GeneratorBasedBuilder):
82
+
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.Array3D(shape=(3, 224, 224), dtype="uint8"),
101
+ "image_path": datasets.Value("string"),
102
+ }
103
+ ),
104
+ supervised_keys=None,
105
+ citation=_CITATION,
106
+ homepage="https://github.com/clovaai/cord/",
107
+ )
108
+
109
+ def _split_generators(self, dl_manager):
110
+ """Returns SplitGenerators."""
111
+ """Uses local files located with data_dir"""
112
+ downloaded_file = dl_manager.download_and_extract(_URLS)
113
+ # move files from the second URL together with files from the first one.
114
+ dest = Path(downloaded_file[0])/"CORD"
115
+ for split in ["train", "dev", "test"]:
116
+ for file_type in ["image", "json"]:
117
+ if split == "test" and file_type == "json":
118
+ continue
119
+ files = (Path(downloaded_file[1])/"CORD"/split/file_type).iterdir()
120
+ for f in files:
121
+ os.rename(f, dest/split/file_type/f.name)
122
+ return [
123
+ datasets.SplitGenerator(
124
+ name=datasets.Split.TRAIN, gen_kwargs={"filepath": dest/"train"}
125
+ ),
126
+ datasets.SplitGenerator(
127
+ name=datasets.Split.VALIDATION, gen_kwargs={"filepath": dest/"dev"}
128
+ ),
129
+ datasets.SplitGenerator(
130
+ name=datasets.Split.TEST, gen_kwargs={"filepath": dest/"test"}
131
+ ),
132
+ ]
133
+
134
+ def _generate_examples(self, filepath):
135
+ logger.info("⏳ Generating examples from = %s", filepath)
136
+ ann_dir = os.path.join(filepath, "json")
137
+ img_dir = os.path.join(filepath, "image")
138
+ for guid, file in enumerate(sorted(os.listdir(ann_dir))):
139
+ words = []
140
+ bboxes = []
141
+ ner_tags = []
142
+
143
+ file_path = os.path.join(ann_dir, file)
144
+ with open(file_path, "r", encoding="utf8") as f:
145
+ data = json.load(f)
146
+ image_path = os.path.join(img_dir, file)
147
+ image_path = image_path.replace("json", "png")
148
+ image, size = load_image(image_path)
149
+
150
+ for item in data["valid_line"]:
151
+ line_words, label = item["words"], item["category"]
152
+ line_words = [w for w in line_words if w["text"].strip() != ""]
153
+ if len(line_words) == 0:
154
+ continue
155
+ if label == "other":
156
+ for w in line_words:
157
+ words.append(w["text"])
158
+ ner_tags.append("O")
159
+ bboxes.append(normalize_bbox(quad_to_box(w["quad"]), size))
160
+ else:
161
+ words.append(line_words[0]["text"])
162
+ ner_tags.append("B-" + label.upper())
163
+ bboxes.append(normalize_bbox(quad_to_box(line_words[0]["quad"]), size))
164
+ for w in line_words[1:]:
165
+ words.append(w["text"])
166
+ ner_tags.append("I-" + label.upper())
167
+ bboxes.append(normalize_bbox(quad_to_box(w["quad"]), size))
168
+
169
+ # yield guid, {"id": str(guid), "words": words, "bboxes": bboxes, "ner_tags": ner_tags, "image": image}
170
+ yield guid, {"id": str(guid), "words": words, "bboxes": bboxes, "ner_tags": ner_tags, "image_path": image_path}
171
+