File size: 5,716 Bytes
14190bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
"""CORD: A Consolidated Receipt Dataset for Post-OCR Parsing"""


import json
import os
from pathlib import Path
from typing import Any, Generator

import datasets
from PIL import Image

logger = datasets.logging.get_logger(__name__)


_CITATION = """\
@article{park2019cord,
  title={CORD: A Consolidated Receipt Dataset for Post-OCR Parsing},
  author={Park, Seunghyun and Shin, Seung and Lee, Bado and Lee, Junyeop and Surh, Jaeheung and Seo, Minjoon and Lee, Hwalsuk}
  booktitle={Document Intelligence Workshop at Neural Information Processing Systems}
  year={2019}
}
"""

_DESCRIPTION = """\
CORD (Consolidated Receipt Dataset) with normalized bounding boxes.
"""

_URLS = [
    "https://drive.google.com/uc?id=1MqhTbcj-AHXOqYoeoh12aRUwIprzTJYI",
    "https://drive.google.com/uc?id=1wYdp5nC9LnHQZ2FcmOoC0eClyWvcuARU",
]

_LABELS = [
    "menu.cnt",
    "menu.discountprice",
    "menu.etc",
    "menu.itemsubtotal",
    "menu.nm",
    "menu.num",
    "menu.price",
    "menu.sub_cnt",
    "menu.sub_etc",
    "menu.sub_nm",
    "menu.sub_price",
    "menu.sub_unitprice",
    "menu.unitprice",
    "menu.vatyn",
    "sub_total.discount_price",
    "sub_total.etc",
    "sub_total.othersvc_price",
    "sub_total.service_price",
    "sub_total.subtotal_price",
    "sub_total.tax_price",
    "total.cashprice",
    "total.changeprice",
    "total.creditcardprice",
    "total.emoneyprice",
    "total.menuqty_cnt",
    "total.menutype_cnt",
    "total.total_etc",
    "total.total_price",
    "void_menu.nm",
    "void_menu.price",
]


def load_image(image_path: str) -> tuple:
    image = Image.open(image_path).convert("RGB")
    return image, image.size


def quad_to_bbox(quad: dict) -> list:
    return [
        quad["x3"],
        quad["y1"],
        quad["x1"],
        quad["y3"],
    ]


def normalize_bbox(bbox: list, width: int, height: int) -> list:
    return [
        int(1000 * (bbox[0] / width)),
        int(1000 * (bbox[1] / height)),
        int(1000 * (bbox[2] / width)),
        int(1000 * (bbox[3] / height)),
    ]


class CORDConfig(datasets.BuilderConfig):
    """BuilderConfig for CORD."""

    def __init__(self, **kwargs) -> None:
        """BuilderConfig for CORD.
        Args:
          **kwargs: keyword arguments forwarded to super.
        """
        super(CORDConfig, self).__init__(**kwargs)


class CORD(datasets.GeneratorBasedBuilder):
    BUILDER_CONFIGS = [
        CORDConfig(
            name="CORD",
            version=datasets.Version("1.0.0"),
            description="CORD (Consolidated Receipt Dataset)",
        ),
    ]

    def _info(self) -> datasets.DatasetInfo:
        return datasets.DatasetInfo(
            description=_DESCRIPTION,
            features=datasets.Features(
                {
                    "id": datasets.Value("string"),
                    "words": datasets.Sequence(datasets.Value("string")),
                    "bboxes": datasets.Sequence(
                        datasets.Sequence(datasets.Value("int64"))
                    ),
                    "labels": datasets.Sequence(
                        datasets.features.ClassLabel(names=_LABELS)
                    ),
                    "images": datasets.features.Image(),
                }
            ),
            citation=_CITATION,
            homepage="https://github.com/clovaai/cord/",
        )

    def _split_generators(self, dl_manager) -> list:
        base_dir_v1, base_dir_v2 = dl_manager.download_and_extract(_URLS)
        dest_dir = Path(base_dir_v1) / "CORD"

        for split_dir in ["train", "dev", "test"]:
            for type_dir in ["image", "json"]:
                if split_dir == "test" and type_dir == "json":
                    continue
                files = (Path(base_dir_v2) / "CORD" / split_dir / type_dir).iterdir()
                for f in files:
                    os.rename(f, dest_dir / split_dir / type_dir / f.name)

        return [
            datasets.SplitGenerator(
                name=str(datasets.Split.TRAIN), gen_kwargs={"filepath": dest_dir / "train"}
            ),
            datasets.SplitGenerator(
                name=str(datasets.Split.VALIDATION), gen_kwargs={"filepath": dest_dir / "dev"},
            ),
            datasets.SplitGenerator(
                name=str(datasets.Split.TEST), gen_kwargs={"filepath": dest_dir / "test"}
            ),
        ]

    def _generate_examples(self, **kwargs: Any) -> Generator:
        filepath = kwargs["filepath"]
        logger.info("generating examples from = %s", filepath)
        ann_dir = os.path.join(filepath, "json")
        img_dir = os.path.join(filepath, "image")

        for guid, file in enumerate(sorted(os.listdir(ann_dir))):
            WORDS, BBOXES, LABELS = [], [], []
            file_path = os.path.join(ann_dir, file)
            f = open(file_path)
            data = json.load(f)

            image_path = os.path.join(img_dir, file).replace("json", "png")
            image, (width, height) = load_image(image_path)

            for annotation in data["valid_line"]:
                label, words = annotation["category"], annotation["words"]
                for word in words:
                    bbox = normalize_bbox(
                        quad_to_bbox(word["quad"]), width=width, height=height
                    )
                    if min(bbox) >= 0 and max(bbox) <= 1000:
                        WORDS.append(word["text"])
                        BBOXES.append(bbox)
                        LABELS.append(label)

            yield guid, {
                "id": str(guid),
                "images": image,
                "words": WORDS,
                "bboxes": BBOXES,
                "labels": LABELS,
            }