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ding=utf-8
|
2 |
+
'''
|
3 |
+
Reference: https://huggingface.co/datasets/nielsr/funsd/blob/main/funsd.py
|
4 |
+
'''
|
5 |
+
import ast
|
6 |
+
import os
|
7 |
+
import random
|
8 |
+
|
9 |
+
import datasets
|
10 |
+
import matplotlib.pyplot as plt
|
11 |
+
import pandas as pd
|
12 |
+
from pdf2image import convert_from_path
|
13 |
+
from PIL import Image
|
14 |
+
|
15 |
+
|
16 |
+
def load_image(image_path):
|
17 |
+
image = Image.open(image_path).convert("RGB")
|
18 |
+
w, h = image.size
|
19 |
+
return image, (w, h)
|
20 |
+
|
21 |
+
def normalize_bbox(bbox, size):
|
22 |
+
return [
|
23 |
+
int(1000 * bbox[0] / size[0]),
|
24 |
+
int(1000 * bbox[1] / size[1]),
|
25 |
+
int(1000 * bbox[2] / size[0]),
|
26 |
+
int(1000 * bbox[3] / size[1]),
|
27 |
+
]
|
28 |
+
|
29 |
+
logger = datasets.logging.get_logger(__name__)
|
30 |
+
|
31 |
+
|
32 |
+
_CITATION = """\
|
33 |
+
@article{Jaume2019FUNSDAD,
|
34 |
+
title={FUNSD: A Dataset for Form Understanding in Noisy Scanned Documents},
|
35 |
+
author={Guillaume Jaume and H. K. Ekenel and J. Thiran},
|
36 |
+
journal={2019 International Conference on Document Analysis and Recognition Workshops (ICDARW)},
|
37 |
+
year={2019},
|
38 |
+
volume={2},
|
39 |
+
pages={1-6}
|
40 |
+
}
|
41 |
+
"""
|
42 |
+
|
43 |
+
_DESCRIPTION = """\
|
44 |
+
https://guillaumejaume.github.io/FUNSD/
|
45 |
+
"""
|
46 |
+
|
47 |
+
|
48 |
+
class FunsdConfig(datasets.BuilderConfig):
|
49 |
+
"""BuilderConfig for FUNSD"""
|
50 |
+
|
51 |
+
def __init__(self, **kwargs):
|
52 |
+
"""BuilderConfig for FUNSD.
|
53 |
+
Args:
|
54 |
+
**kwargs: keyword arguments forwarded to super.
|
55 |
+
"""
|
56 |
+
super(FunsdConfig, self).__init__(**kwargs)
|
57 |
+
|
58 |
+
|
59 |
+
|
60 |
+
class Funsd(datasets.GeneratorBasedBuilder):
|
61 |
+
"""Conll2003 dataset."""
|
62 |
+
|
63 |
+
BUILDER_CONFIGS = [
|
64 |
+
FunsdConfig(name="funsd", version=datasets.Version("1.0.0"), description="FUNSD dataset"),
|
65 |
+
]
|
66 |
+
|
67 |
+
|
68 |
+
def _info(self):
|
69 |
+
return datasets.DatasetInfo(
|
70 |
+
description=_DESCRIPTION,
|
71 |
+
features=datasets.Features(
|
72 |
+
{
|
73 |
+
"id": datasets.Value("string"),
|
74 |
+
"tokens": datasets.Sequence(datasets.Value("string")),
|
75 |
+
"bboxes": datasets.Sequence(datasets.Sequence(datasets.Value("int64"))),
|
76 |
+
"segment_class": datasets.Sequence(
|
77 |
+
datasets.features.ClassLabel(
|
78 |
+
names=["O", "B-PARTES","I-PARTES", "B-EMENTA","I-EMENTA", "B-ACORDAO","I-ACORDAO", "B-RELATORIO","I-RELATORIO", "B-VOTO", "I-VOTO"]
|
79 |
+
#names=["OUTROS", "PARTES", "EMENTA","ACORDAO","RELATORIO", "VOTO"]
|
80 |
+
)
|
81 |
+
),
|
82 |
+
"image": datasets.features.Image(),
|
83 |
+
}
|
84 |
+
),
|
85 |
+
supervised_keys=None,
|
86 |
+
#homepage="https://guillaumejaume.github.io/FUNSD/",
|
87 |
+
citation=_CITATION,
|
88 |
+
)
|
89 |
+
|
90 |
+
def _split_generators(self, dl_manager):
|
91 |
+
downloaded_file = dl_manager.download_and_extract("http://direitodigital.ufms.br:8000/direitodigital_dev.zip")
|
92 |
+
"""Returns SplitGenerators."""
|
93 |
+
return [
|
94 |
+
datasets.SplitGenerator(
|
95 |
+
name=datasets.NamedSplit('trainmini_stf'), gen_kwargs={"filepath": f"{downloaded_file}/trainmini/stf"}
|
96 |
+
),
|
97 |
+
datasets.SplitGenerator(
|
98 |
+
name=datasets.NamedSplit('dev_stf'), gen_kwargs={"filepath": f"{downloaded_file}/dev/stf"}
|
99 |
+
),
|
100 |
+
datasets.SplitGenerator(
|
101 |
+
name=datasets.NamedSplit('trainmini_stj'), gen_kwargs={"filepath": f"{downloaded_file}/trainmini/stj"}
|
102 |
+
),
|
103 |
+
datasets.SplitGenerator(
|
104 |
+
name=datasets.NamedSplit('dev_stj'), gen_kwargs={"filepath": f"{downloaded_file}/dev/stj"}
|
105 |
+
),
|
106 |
+
datasets.SplitGenerator(
|
107 |
+
name=datasets.NamedSplit('trainmini_trf2'), gen_kwargs={"filepath": f"{downloaded_file}/trainmini/trf2"}
|
108 |
+
),
|
109 |
+
datasets.SplitGenerator(
|
110 |
+
name=datasets.NamedSplit('dev_trf2'), gen_kwargs={"filepath": f"{downloaded_file}/dev/trf2"}
|
111 |
+
),
|
112 |
+
datasets.SplitGenerator(
|
113 |
+
name=datasets.NamedSplit('trainmini_tjpb'), gen_kwargs={"filepath": f"{downloaded_file}/trainmini/tjpb"}
|
114 |
+
),
|
115 |
+
datasets.SplitGenerator(
|
116 |
+
name=datasets.NamedSplit('dev_tjpb'), gen_kwargs={"filepath": f"{downloaded_file}/dev/tjpb"}
|
117 |
+
),
|
118 |
+
datasets.SplitGenerator(
|
119 |
+
name=datasets.NamedSplit('trainmini_tjmg'), gen_kwargs={"filepath": f"{downloaded_file}/trainmini/tjmg"}
|
120 |
+
),
|
121 |
+
datasets.SplitGenerator(
|
122 |
+
name=datasets.NamedSplit('dev_tjmg'), gen_kwargs={"filepath": f"{downloaded_file}/dev/tjmg"}
|
123 |
+
)
|
124 |
+
]
|
125 |
+
|
126 |
+
def get_line_bbox(self, bboxs):
|
127 |
+
x = [bboxs[i][j] for i in range(len(bboxs)) for j in range(0, len(bboxs[i]), 2)]
|
128 |
+
y = [bboxs[i][j] for i in range(len(bboxs)) for j in range(1, len(bboxs[i]), 2)]
|
129 |
+
|
130 |
+
x0, y0, x1, y1 = min(x), min(y), max(x), max(y)
|
131 |
+
|
132 |
+
assert x1 >= x0 and y1 >= y0
|
133 |
+
bbox = [[x0, y0, x1, y1] for _ in range(len(bboxs))]
|
134 |
+
return bbox
|
135 |
+
|
136 |
+
def _generate_examples():
|
137 |
+
guid = 0
|
138 |
+
|
139 |
+
file_paths = [
|
140 |
+
os.path.join(root, filename)
|
141 |
+
for root, dirs, files in os.walk(dataset_path)
|
142 |
+
for filename in files
|
143 |
+
if filename.endswith('.tsv')
|
144 |
+
]
|
145 |
+
random.shuffle(file_paths)
|
146 |
+
|
147 |
+
|
148 |
+
#for dir_path, _, file_names in os.walk(filepath):
|
149 |
+
for tsv_name in file_paths:
|
150 |
+
#for file in file_names:
|
151 |
+
#tsv_name = os.path.join(dir_path, file)
|
152 |
+
|
153 |
+
pdf_name = tsv_name.replace('/LayoutLM_dataset/', '/pdfs/').replace('.tsv', '.pdf')
|
154 |
+
|
155 |
+
img_path = tsv_name.replace('.tsv','')
|
156 |
+
pages_img = convert_from_path(pdf_name, size=(762,1000),fmt="png")
|
157 |
+
|
158 |
+
dataframe = pd.read_csv(tsv_name ,delimiter='\t', keep_default_na=False).replace(["None","SUMULA","CERTIDAO_DE_JULGAMENTO","AUTUACAO","CERTIDAO","EXTRATO_DE_ATA"], 'OUTROS')
|
159 |
+
for page in dataframe['page'].unique():
|
160 |
+
#image, size = load_image(os.path.join(img_path, str(page-1)+'.png'))
|
161 |
+
image, size = pages_img[page-1], pages_img[page-1].size
|
162 |
+
|
163 |
+
data = (dataframe[dataframe["page"] == page])
|
164 |
+
form = []
|
165 |
+
for index, row in data.iterrows():
|
166 |
+
tokens = []
|
167 |
+
for token in ast.literal_eval(row['tokens']):
|
168 |
+
|
169 |
+
tokens.append({
|
170 |
+
'box' :
|
171 |
+
[token['x'], token['y'], token['x']+token['width'], token['y'] + token['height']],
|
172 |
+
'text' : token['text']
|
173 |
+
})
|
174 |
+
line_dict = {
|
175 |
+
'text': row['text'],
|
176 |
+
'box': [row['x'], row['y'], row['x']+row['width'], row['y'] + row['height']],
|
177 |
+
'label': row['label'],
|
178 |
+
'words': tokens
|
179 |
+
}
|
180 |
+
form.append(line_dict)
|
181 |
+
yield from self.get_form(guid, image, size, form)
|
182 |
+
guid += 1
|
183 |
+
|
184 |
+
|
185 |
+
def get_form(self, guid, image, size, form):
|
186 |
+
tokens = []
|
187 |
+
bboxes = []
|
188 |
+
segment_class = []
|
189 |
+
|
190 |
+
for item in form:
|
191 |
+
cur_line_bboxes = []
|
192 |
+
words, label = item["words"], item["label"]
|
193 |
+
words = [w for w in words if w["text"].strip() != ""]
|
194 |
+
if len(words) == 0:
|
195 |
+
continue
|
196 |
+
if label == "OUTROS":
|
197 |
+
for w in words:
|
198 |
+
tokens.append(w["text"])
|
199 |
+
segment_class.append("O")
|
200 |
+
#segment_class.append(label)
|
201 |
+
cur_line_bboxes.append(normalize_bbox(w["box"], size))
|
202 |
+
else:
|
203 |
+
tokens.append(words[0]["text"])
|
204 |
+
segment_class.append("B-" + label.upper())
|
205 |
+
cur_line_bboxes.append(normalize_bbox(words[0]["box"], size))
|
206 |
+
for w in words[1:]:
|
207 |
+
tokens.append(w["text"])
|
208 |
+
segment_class.append("I-" + label.upper())
|
209 |
+
cur_line_bboxes.append(normalize_bbox(w["box"], size))
|
210 |
+
cur_line_bboxes = self.get_line_bbox(cur_line_bboxes)
|
211 |
+
bboxes.extend(cur_line_bboxes)
|
212 |
+
yield guid, {"id": str(guid), "tokens": tokens, "bboxes": bboxes, "segment_class": segment_class,
|
213 |
+
"image": image}
|
214 |
+
|
215 |
+
def main():
|
216 |
+
dataset = Funsd()
|
217 |
+
for example in dataset._generate_examples('/home/marlon/LayoutLM_dataset/trainmini'):
|
218 |
+
print(example)
|
219 |
+
|
220 |
+
|
221 |
+
|
222 |
+
|
223 |
+
|
224 |
+
if __name__ == '__main__':
|
225 |
+
main()
|