File size: 7,741 Bytes
435e59c
 
bbe15cd
 
 
c504717
bbe15cd
c504717
 
 
bbe15cd
db25197
bbe15cd
 
4d92144
 
 
bbe15cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5a4d8f1
1479bb7
8784b66
29ed392
cf60671
 
3e6bd1e
435e59c
c504717
5a4d8f1
 
c504717
 
 
 
 
 
 
 
3461cbf
c504717
bbe15cd
435e59c
 
bbe15cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd3e40b
bbe15cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92464de
bbe15cd
6297149
6a25200
2681be9
bbe15cd
 
 
c504717
 
 
ddc19d2
bbe15cd
 
 
 
 
 
 
 
 
 
 
 
 
92464de
bbe15cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e85bf76
 
 
 
bbe15cd
 
 
 
 
 
 
 
 
 
 
c504717
 
5a4d8f1
f688a6e
523fa94
4dcc370
34672f2
c504717
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
188
189
190
191
192
193
194
### Data loader script uploaded to huggingface hub

import json
import os
from pathlib import Path
import uuid
import datasets
import imgaug.augmenters as iaa
from imgaug.augmentables.bbs import BoundingBox, BoundingBoxesOnImage
import imageio
from PIL import Image
import re

logger = datasets.logging.get_logger(__name__)
_DESCRIPTION = """\
Created for IntellectAI Hackathon!
"""
def load_image(image_path):
    image = Image.open(image_path).convert("RGB")
    w, h = image.size
    return image, (w, h)

def _get_drive_url(url):
    base_url = 'https://drive.google.com/uc?id='
    split_url = url.split('/')
    return base_url + split_url[5]

def quad_to_box(quad):
    x1, y1 = quad[0].values()
    x3, y3 = quad[2].values()
    box = [x1, y1, x3, y3]
    if box[3] < box[1]:
        bbox = list(box)
        tmp = bbox[3]
        bbox[3] = bbox[1]
        bbox[1] = tmp
        box = tuple(bbox)
    if box[2] < box[0]:
        bbox = list(box)
        tmp = bbox[2]
        bbox[2] = bbox[0]
        bbox[0] = tmp
        box = tuple(bbox)
    return box

def augment_image(file_path, file, bboxes):
    aug = iaa.SomeOf(2,[
        iaa.ElasticTransformation(alpha=(0, 2.0), sigma=0.25),
        # iaa.imgcorruptlike.GaussianBlur(severity=1),
        iaa.imgcorruptlike.Pixelate(severity=2),
        iaa.imgcorruptlike.Contrast(severity=2),
        # iaa.PerspectiveTransform(scale=(0.01, 0.15)),
        iaa.imgcorruptlike.Brightness(severity=1),
    ])
    image = imageio.imread(os.path.join(file_path, file))
    bbs = BoundingBoxesOnImage.from_xyxy_array(bboxes, shape=image.shape)
    image_aug, bbs_aug = aug(image=image, bounding_boxes=bbs)
    bbs_aug = bbs_aug.remove_out_of_image()
    bbs_aug = bbs_aug.clip_out_of_image()

    if re.findall('Image...', str(bbs_aug)) == ['Image([]']:
        return None, None
    else:
        aug_bboxes = bbs_aug.to_xyxy_array()
        return Image.fromarray(image_aug, 'L').convert("RGB"), aug_bboxes

_URLS = {
"image_files": _get_drive_url("https://drive.google.com/file/d/1bVc6xIAYO22RpehEkmuihaGsZ_VoOH2E"), #URL to zip file containing images
"metadata_file": _get_drive_url("https://drive.google.com/file/d/1dgH6LiEPc2xuj0y7NcUyp6IDCELdwuqe") #URL to metadata.json from UBIAI annotation
}

class IntellectConfig(datasets.BuilderConfig):
    """BuilderConfig for IntellectAI"""
    def __init__(self, **kwargs):
        """BuilderConfig for IntellectAI.
        Args:
          **kwargs: keyword arguments forwarded to super.
        """
        super(IntellectConfig, self).__init__(**kwargs)

class IntellectAI(datasets.GeneratorBasedBuilder):
    BUILDER_CONFIGS = [
        IntellectConfig(name="intellectai", version=datasets.Version("1.0.0"), description="IntellectAI Hackathon dataset"),
    ]
    def _info(self):
        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"))),
                    "ner_tags": datasets.Sequence(
                        datasets.features.ClassLabel(
                            names=[
                            'O',
                            'B-BILL_TO_NAME',
                            'B-BILL_TO_ADDRESS',
                            'B-SHIP_TO_NAME',
                            'B-SHIP_TO_ADDRESS',
                            'B-INVOICE_NUMBER',
                            'B-INVOICE_DATE',
                            'B-PAYMENT_INFO',
                            'B-DUE_DATE',
                            'B-TOTAL_TAX_AMOUNT',
                            'B-TOTAL_AMOUNT',
                            'I-BILL_TO_NAME',
                            'I-BILL_TO_ADDRESS',
                            'I-SHIP_TO_NAME',
                            'I-SHIP_TO_ADDRESS',
                            'I-INVOICE_NUMBER',
                            'I-INVOICE_DATE',
                            'I-PAYMENT_INFO',
                            'I-DUE_DATE',
                            'I-TOTAL_TAX_AMOUNT',
                            'I-TOTAL_AMOUNT',
                         ]
                        )
                    ),
                    "image": datasets.features.Image(),
                }
            ),
            supervised_keys=None,
        )

    def _split_generators(self, dl_manager):
        """Returns SplitGenerators."""
        """Uses local files located with data_dir"""
        self.metadata_file = dl_manager.download(_URLS["metadata_file"])
        downloaded_file = dl_manager.download_and_extract(_URLS["image_files"])
        print(downloaded_file)
        print(os.listdir(downloaded_file))
        dest = Path(downloaded_file)/"invoice_data"
        return [
            datasets.SplitGenerator(
                name=datasets.Split.TRAIN, gen_kwargs={"filepath": dest/"inv_train"}
            ),
            datasets.SplitGenerator(
                name=datasets.Split.VALIDATION, gen_kwargs={"filepath": dest/"inv_dev"}
            )
        ]

    def get_line_bbox(self, bboxs):
        x = [bboxs[i][j] for i in range(len(bboxs)) for j in range(0, len(bboxs[i]), 2)]
        y = [bboxs[i][j] for i in range(len(bboxs)) for j in range(1, len(bboxs[i]), 2)]

        x0, y0, x1, y1 = min(x), min(y), max(x), max(y)

        assert x1 >= x0 and y1 >= y0
        bbox = [[x0, y0, x1, y1] for _ in range(len(bboxs))]
        return bbox

    def _generate_examples(self, filepath):
        with open(self.metadata_file, "r", encoding="utf8") as f:
            metadata = json.load(f)
        logger.info("Generating examples from = %s", filepath)
        for guid, file in enumerate(sorted(os.listdir(filepath))):
            words = []
            bboxes = []
            ner_tags = []
            image_path = os.path.join(filepath, file)
            image, size = load_image(image_path)
            data = [obj for obj in metadata if obj["documentName"]==file][0]
            for item in data["annotation"]:
                cur_line_bboxes = []
                line_words, label = item["boundingBoxes"], item["label"]
                line_words = [w for w in line_words if w["word"].strip() != ""]
                if len(line_words) == 0:
                    continue
                if label == "OTHER":
                    for w in line_words:
                        words.append(w["word"])
                        ner_tags.append("O")
                        cur_line_bboxes.append(quad_to_box(w["normalizedVertices"]))
                else:
                    words.append(line_words[0]["word"])
                    ner_tags.append("B-" + label.upper())
                    cur_line_bboxes.append(quad_to_box(line_words[0]["normalizedVertices"]))
                    for w in line_words[1:]:
                        words.append(w["word"])
                        ner_tags.append("I-" + label.upper())
                        cur_line_bboxes.append(quad_to_box(w["normalizedVertices"]))

                cur_line_bboxes = self.get_line_bbox(cur_line_bboxes)
                bboxes.extend(cur_line_bboxes)
            image_variants = [(image, bboxes)]
            for _ in range(4):
                aug_image, aug_bboxes = augment_image(filepath, file, bboxes)
                if aug_image is not None and aug_bboxes is not None:
                    image_variants.append((aug_image, aug_bboxes))
            for img, bbs in image_variants:
                yield str(uuid.uuid4()), {"id": str(uuid.uuid4()), "words": words, "bboxes": bbs, "ner_tags": ner_tags,
                         "image": img}