|
|
|
|
|
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.Pixelate(severity=2), |
|
iaa.imgcorruptlike.Contrast(severity=2), |
|
|
|
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"), |
|
"metadata_file": _get_drive_url("https://drive.google.com/file/d/1dgH6LiEPc2xuj0y7NcUyp6IDCELdwuqe") |
|
} |
|
|
|
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} |
|
|