Create funsds.py
Browse files
funsds.py
ADDED
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
import json
|
3 |
+
import os
|
4 |
+
import datasets
|
5 |
+
from PIL import Image
|
6 |
+
import numpy as np
|
7 |
+
logger = datasets.logging.get_logger(__name__)
|
8 |
+
_CITATION = """\\n@article{Jaume2019FUNSDAD,
|
9 |
+
title={FUNSD: A Dataset for Form Understanding in Noisy Scanned Documents},
|
10 |
+
author={Guillaume Jaume and H. K. Ekenel and J. Thiran},
|
11 |
+
journal={2019 International Conference on Document Analysis and Recognition Workshops (ICDARW)},
|
12 |
+
year={2019},
|
13 |
+
volume={2},
|
14 |
+
pages={1-6}
|
15 |
+
}
|
16 |
+
"""
|
17 |
+
_DESCRIPTION = """\\nhttps://guillaumejaume.github.io/FUNSD/
|
18 |
+
"""
|
19 |
+
def load_image(image_path):
|
20 |
+
image = Image.open(image_path).convert("RGB")
|
21 |
+
w, h = image.size
|
22 |
+
# resize image to 224x224
|
23 |
+
image = image.resize((224, 224))
|
24 |
+
image = np.asarray(image)
|
25 |
+
image = image[:, :, ::-1] # flip color channels from RGB to BGR
|
26 |
+
image = image.transpose(2, 0, 1) # move channels to first dimension
|
27 |
+
return image, (w, h)
|
28 |
+
def normalize_bbox(bbox, size):
|
29 |
+
return [
|
30 |
+
int(1000 * bbox[0] / size[0]),
|
31 |
+
int(1000 * bbox[1] / size[1]),
|
32 |
+
int(1000 * bbox[2] / size[0]),
|
33 |
+
int(1000 * bbox[3] / size[1]),
|
34 |
+
]
|
35 |
+
class FunsdConfig(datasets.BuilderConfig):
|
36 |
+
"""BuilderConfig for FUNSD"""
|
37 |
+
def __init__(self, **kwargs):
|
38 |
+
"""BuilderConfig for FUNSD.
|
39 |
+
Args:
|
40 |
+
**kwargs: keyword arguments forwarded to super.
|
41 |
+
"""
|
42 |
+
super(FunsdConfig, self).__init__(**kwargs)
|
43 |
+
class Funsd(datasets.GeneratorBasedBuilder):
|
44 |
+
"""FUNSD dataset."""
|
45 |
+
BUILDER_CONFIGS = [
|
46 |
+
FunsdConfig(name="funsd", version=datasets.Version("1.0.0"), description="FUNSD dataset"),
|
47 |
+
]
|
48 |
+
def _info(self):
|
49 |
+
return datasets.DatasetInfo(
|
50 |
+
description=_DESCRIPTION,
|
51 |
+
features=datasets.Features(
|
52 |
+
{
|
53 |
+
"id": datasets.Value("string"),
|
54 |
+
"tokens": datasets.Sequence(datasets.Value("string")),
|
55 |
+
"bboxes": datasets.Sequence(datasets.Sequence(datasets.Value("int64"))),
|
56 |
+
"ner_tags": datasets.Sequence(
|
57 |
+
datasets.features.ClassLabel(
|
58 |
+
names=["O", "B-HEADER", "I-HEADER", "B-QUESTION", "I-QUESTION", "B-ANSWER", "I-ANSWER"]
|
59 |
+
)
|
60 |
+
),
|
61 |
+
"image": datasets.Array3D(shape=(3, 224, 224), dtype="uint8"),
|
62 |
+
}
|
63 |
+
),
|
64 |
+
supervised_keys=None,
|
65 |
+
homepage="https://guillaumejaume.github.io/FUNSD/",
|
66 |
+
citation=_CITATION,
|
67 |
+
)
|
68 |
+
def _split_generators(self, dl_manager):
|
69 |
+
"""Returns SplitGenerators."""
|
70 |
+
return [
|
71 |
+
datasets.SplitGenerator(
|
72 |
+
name=datasets.Split.TRAIN, gen_kwargs={"filepath": "training_data/"}
|
73 |
+
),
|
74 |
+
datasets.SplitGenerator(
|
75 |
+
name=datasets.Split.TEST, gen_kwargs={"filepath": "testing_data/"}
|
76 |
+
),
|
77 |
+
]
|
78 |
+
def _generate_examples(self, filepath):
|
79 |
+
logger.info("⏳ Generating examples from = %s", filepath)
|
80 |
+
ann_dir = os.path.join(filepath, "annotations")
|
81 |
+
img_dir = os.path.join(filepath, "images")
|
82 |
+
for guid, file in enumerate(sorted(os.listdir(ann_dir))):
|
83 |
+
tokens = []
|
84 |
+
bboxes = []
|
85 |
+
ner_tags = []
|
86 |
+
file_path = os.path.join(ann_dir, file)
|
87 |
+
with open(file_path, "r", encoding="utf8") as f:
|
88 |
+
data = json.load(f)
|
89 |
+
image_path = os.path.join(img_dir, file)
|
90 |
+
image_path = image_path.replace("json", "png")
|
91 |
+
image, size = load_image(image_path)
|
92 |
+
for item in data["form"]:
|
93 |
+
words, label = item["words"], item["label"]
|
94 |
+
words = [w for w in words if w["text"].strip() != ""]
|
95 |
+
if len(words) == 0:
|
96 |
+
continue
|
97 |
+
if label == "other":
|
98 |
+
for w in words:
|
99 |
+
tokens.append(w["text"])
|
100 |
+
ner_tags.append("O")
|
101 |
+
bboxes.append(normalize_bbox(w["box"], size))
|
102 |
+
else:
|
103 |
+
tokens.append(words[0]["text"])
|
104 |
+
ner_tags.append("B-" + label.upper())
|
105 |
+
bboxes.append(normalize_bbox(words[0]["box"], size))
|
106 |
+
for w in words[1:]:
|
107 |
+
tokens.append(w["text"])
|
108 |
+
ner_tags.append("I-" + label.upper())
|
109 |
+
bboxes.append(normalize_bbox(w["box"], size))
|
110 |
+
yield guid, {"id": str(guid), "tokens": tokens, "bboxes": bboxes, "ner_tags": ner_tags, "image": image}
|