# coding=utf-8 import json import os import datasets from PIL import Image import numpy as np logger = datasets.logging.get_logger(__name__) _CITATION = """\ @article{vu2020revising, title={Revising FUNSD dataset for key-value detection in document images}, author={Vu, Hieu M and Nguyen, Diep Thi-Ngoc}, journal={arXiv preprint arXiv:2010.05322}, year={2020} } """ _DESCRIPTION = """\ FUNSD is one of the limited publicly available datasets for information extraction from document images. The information in the FUNSD dataset is defined by text areas of four categories ("key", "value", "header", "other", and "background") and connectivity between areas as key-value relations. Inspecting FUNSD, we found several inconsistency in labeling, which impeded its applicability to the key-value extraction problem. In this report, we described some labeling issues in FUNSD and the revision we made to the dataset. """ _URL = """\ https://drive.google.com/drive/folders/1HjJyoKqAh-pvtg3eQAmrbfzPccQZ48rz """ def load_image(image_path): image = Image.open(image_path).convert("RGB") w, h = image.size return image, (w, h) def normalize_bbox(bbox, size): return [ int(1000 * bbox[0] / size[0]), int(1000 * bbox[1] / size[1]), int(1000 * bbox[2] / size[0]), int(1000 * bbox[3] / size[1]), ] class FunsdConfig(datasets.BuilderConfig): """BuilderConfig for FUNSD""" def __init__(self, **kwargs): """BuilderConfig for FUNSD. Args: **kwargs: keyword arguments forwarded to super. """ super(FunsdConfig, self).__init__(**kwargs) class Funsd(datasets.GeneratorBasedBuilder): """FUNSD: Form Understanding in Noisy Scanned Documents.""" BUILDER_CONFIGS = [ FunsdConfig( name="funsd_vu2020revising", version=datasets.Version("1.0.0"), description="Revised FUNSD 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-HEADER", "I-HEADER", "B-QUESTION", "I-QUESTION", "B-ANSWER", "I-ANSWER", ] ) ), "image_path": datasets.Value("string"), } ), supervised_keys=None, homepage="https://guillaumejaume.github.io/FUNSD/", citation=_CITATION, ) def _split_generators(self, dl_manager): """Returns SplitGenerators.""" downloaded_file = dl_manager.download_and_extract( "https://drive.google.com/uc?export=download&id=1wdJJQgRIb1c404SJnX1dyBSi7U2mVduI" ) return [ datasets.SplitGenerator( name=datasets.Split.TRAIN, gen_kwargs={"filepath": f"{downloaded_file}/FUNSD/training_data/"}, ), datasets.SplitGenerator( name=datasets.Split.TEST, gen_kwargs={"filepath": f"{downloaded_file}/FUNSD/testing_data/"}, ), ] def _generate_examples(self, filepath): logger.info("⏳ Generating examples from = %s", filepath) ann_dir = os.path.join(filepath, "adjusted_annotations") img_dir = os.path.join(filepath, "images") for guid, file in enumerate(sorted(os.listdir(ann_dir))): words = [] bboxes = [] ner_tags = [] file_path = os.path.join(ann_dir, file) with open(file_path, "r", encoding="utf8") as f: data = json.load(f) image_path = os.path.join(img_dir, file) image_path = image_path.replace("json", "png") _, size = load_image(image_path) for item in data["form"]: words_example, label = item["words"], item["label"] words_example = [w for w in words_example if w["text"].strip() != ""] if len(words_example) == 0: continue if label == "other": for w in words_example: words.append(w["text"]) ner_tags.append("O") bboxes.append(normalize_bbox(w["box"], size)) else: words.append(words_example[0]["text"]) ner_tags.append("B-" + label.upper()) bboxes.append(normalize_bbox(words_example[0]["box"], size)) for w in words_example[1:]: words.append(w["text"]) ner_tags.append("I-" + label.upper()) bboxes.append(normalize_bbox(w["box"], size)) yield guid, { "id": str(guid), "words": words, "bboxes": bboxes, "ner_tags": ner_tags, "image_path": image_path, }