Create funsd-layoutlmv3.py
Browse files- funsd-layoutlmv3.py +132 -0
funsd-layoutlmv3.py
ADDED
@@ -0,0 +1,132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
'''
|
3 |
+
Reference: https://huggingface.co/datasets/nielsr/funsd/blob/main/funsd.py
|
4 |
+
'''
|
5 |
+
import json
|
6 |
+
import os
|
7 |
+
|
8 |
+
import datasets
|
9 |
+
|
10 |
+
from layoutlmft.data.image_utils import load_image, normalize_bbox
|
11 |
+
|
12 |
+
|
13 |
+
logger = datasets.logging.get_logger(__name__)
|
14 |
+
|
15 |
+
|
16 |
+
_CITATION = """\
|
17 |
+
@article{Jaume2019FUNSDAD,
|
18 |
+
title={FUNSD: A Dataset for Form Understanding in Noisy Scanned Documents},
|
19 |
+
author={Guillaume Jaume and H. K. Ekenel and J. Thiran},
|
20 |
+
journal={2019 International Conference on Document Analysis and Recognition Workshops (ICDARW)},
|
21 |
+
year={2019},
|
22 |
+
volume={2},
|
23 |
+
pages={1-6}
|
24 |
+
}
|
25 |
+
"""
|
26 |
+
|
27 |
+
_DESCRIPTION = """\
|
28 |
+
https://guillaumejaume.github.io/FUNSD/
|
29 |
+
"""
|
30 |
+
|
31 |
+
|
32 |
+
class FunsdConfig(datasets.BuilderConfig):
|
33 |
+
"""BuilderConfig for FUNSD"""
|
34 |
+
|
35 |
+
def __init__(self, **kwargs):
|
36 |
+
"""BuilderConfig for FUNSD.
|
37 |
+
|
38 |
+
Args:
|
39 |
+
**kwargs: keyword arguments forwarded to super.
|
40 |
+
"""
|
41 |
+
super(FunsdConfig, self).__init__(**kwargs)
|
42 |
+
|
43 |
+
|
44 |
+
class Funsd(datasets.GeneratorBasedBuilder):
|
45 |
+
"""Conll2003 dataset."""
|
46 |
+
|
47 |
+
BUILDER_CONFIGS = [
|
48 |
+
FunsdConfig(name="funsd", version=datasets.Version("1.0.0"), description="FUNSD dataset"),
|
49 |
+
]
|
50 |
+
|
51 |
+
def _info(self):
|
52 |
+
return datasets.DatasetInfo(
|
53 |
+
description=_DESCRIPTION,
|
54 |
+
features=datasets.Features(
|
55 |
+
{
|
56 |
+
"id": datasets.Value("string"),
|
57 |
+
"tokens": datasets.Sequence(datasets.Value("string")),
|
58 |
+
"bboxes": datasets.Sequence(datasets.Sequence(datasets.Value("int64"))),
|
59 |
+
"ner_tags": datasets.Sequence(
|
60 |
+
datasets.features.ClassLabel(
|
61 |
+
names=["O", "B-HEADER", "I-HEADER", "B-QUESTION", "I-QUESTION", "B-ANSWER", "I-ANSWER"]
|
62 |
+
)
|
63 |
+
),
|
64 |
+
"image": datasets.Array3D(shape=(3, 224, 224), dtype="uint8"),
|
65 |
+
"image_path": datasets.Value("string"),
|
66 |
+
}
|
67 |
+
),
|
68 |
+
supervised_keys=None,
|
69 |
+
homepage="https://guillaumejaume.github.io/FUNSD/",
|
70 |
+
citation=_CITATION,
|
71 |
+
)
|
72 |
+
|
73 |
+
def _split_generators(self, dl_manager):
|
74 |
+
"""Returns SplitGenerators."""
|
75 |
+
downloaded_file = dl_manager.download_and_extract("https://guillaumejaume.github.io/FUNSD/dataset.zip")
|
76 |
+
return [
|
77 |
+
datasets.SplitGenerator(
|
78 |
+
name=datasets.Split.TRAIN, gen_kwargs={"filepath": f"{downloaded_file}/dataset/training_data/"}
|
79 |
+
),
|
80 |
+
datasets.SplitGenerator(
|
81 |
+
name=datasets.Split.TEST, gen_kwargs={"filepath": f"{downloaded_file}/dataset/testing_data/"}
|
82 |
+
),
|
83 |
+
]
|
84 |
+
|
85 |
+
def get_line_bbox(self, bboxs):
|
86 |
+
x = [bboxs[i][j] for i in range(len(bboxs)) for j in range(0, len(bboxs[i]), 2)]
|
87 |
+
y = [bboxs[i][j] for i in range(len(bboxs)) for j in range(1, len(bboxs[i]), 2)]
|
88 |
+
|
89 |
+
x0, y0, x1, y1 = min(x), min(y), max(x), max(y)
|
90 |
+
|
91 |
+
assert x1 >= x0 and y1 >= y0
|
92 |
+
bbox = [[x0, y0, x1, y1] for _ in range(len(bboxs))]
|
93 |
+
return bbox
|
94 |
+
|
95 |
+
def _generate_examples(self, filepath):
|
96 |
+
logger.info("⏳ Generating examples from = %s", filepath)
|
97 |
+
ann_dir = os.path.join(filepath, "annotations")
|
98 |
+
img_dir = os.path.join(filepath, "images")
|
99 |
+
for guid, file in enumerate(sorted(os.listdir(ann_dir))):
|
100 |
+
tokens = []
|
101 |
+
bboxes = []
|
102 |
+
ner_tags = []
|
103 |
+
|
104 |
+
file_path = os.path.join(ann_dir, file)
|
105 |
+
with open(file_path, "r", encoding="utf8") as f:
|
106 |
+
data = json.load(f)
|
107 |
+
image_path = os.path.join(img_dir, file)
|
108 |
+
image_path = image_path.replace("json", "png")
|
109 |
+
image, size = load_image(image_path)
|
110 |
+
for item in data["form"]:
|
111 |
+
cur_line_bboxes = []
|
112 |
+
words, label = item["words"], item["label"]
|
113 |
+
words = [w for w in words if w["text"].strip() != ""]
|
114 |
+
if len(words) == 0:
|
115 |
+
continue
|
116 |
+
if label == "other":
|
117 |
+
for w in words:
|
118 |
+
tokens.append(w["text"])
|
119 |
+
ner_tags.append("O")
|
120 |
+
cur_line_bboxes.append(normalize_bbox(w["box"], size))
|
121 |
+
else:
|
122 |
+
tokens.append(words[0]["text"])
|
123 |
+
ner_tags.append("B-" + label.upper())
|
124 |
+
cur_line_bboxes.append(normalize_bbox(words[0]["box"], size))
|
125 |
+
for w in words[1:]:
|
126 |
+
tokens.append(w["text"])
|
127 |
+
ner_tags.append("I-" + label.upper())
|
128 |
+
cur_line_bboxes.append(normalize_bbox(w["box"], size))
|
129 |
+
cur_line_bboxes = self.get_line_bbox(cur_line_bboxes)
|
130 |
+
bboxes.extend(cur_line_bboxes)
|
131 |
+
yield guid, {"id": str(guid), "tokens": tokens, "bboxes": bboxes, "ner_tags": ner_tags,
|
132 |
+
"image": image, "image_path": image_path}
|