File size: 8,543 Bytes
1494cea
 
7c0cdc2
1494cea
 
 
 
b27b1aa
1494cea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7c0cdc2
1494cea
 
 
 
7c0cdc2
1494cea
 
 
7c0cdc2
 
1494cea
 
7c0cdc2
1494cea
 
 
7c0cdc2
1494cea
 
 
7c0cdc2
1494cea
 
 
7c0cdc2
1494cea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7c0cdc2
1494cea
 
 
 
 
b27b1aa
 
1494cea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b27b1aa
1494cea
 
 
b27b1aa
1494cea
 
 
 
 
 
 
 
 
 
b27b1aa
 
 
1494cea
b27b1aa
 
 
1494cea
 
b27b1aa
 
 
1494cea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7c0cdc2
1494cea
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
# coding=utf-8
'''
Reference: https://huggingface.co/datasets/nielsr/funsd-layoutlmv3/blob/main/funsd-layoutlmv3.py
'''
import ast
import os
import random
import re

import datasets
import matplotlib.pyplot as plt
import pandas as pd
from pdf2image import convert_from_path
from PIL import Image


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]),
    ]

logger = datasets.logging.get_logger(__name__)


_CITATION = """\

}
"""

_DESCRIPTION = """\

"""


class DireitoDigitalConfig(datasets.BuilderConfig):
    """BuilderConfig for DIREITO DIGITAL"""

    def __init__(self, **kwargs):
        """BuilderConfig for DIREITODIGITAL.
        Args:
          **kwargs: keyword arguments forwarded to super.
        """
        super(DireitoDigitalConfig, self).__init__(**kwargs)



class DireitoDigital(datasets.GeneratorBasedBuilder):
    """Conll2003 dataset."""

    BUILDER_CONFIGS = [
        DireitoDigitalConfig(name="direitodigital", version=datasets.Version("1.0.0"), description="DIREITO DIGITAL dataset"),
    ]


    def _info(self):
        return datasets.DatasetInfo(
            description=_DESCRIPTION,
            features=datasets.Features(
                {
                    "id": datasets.Value("string"),
                    "tokens": datasets.Sequence(datasets.Value("string")),
                    "bboxes": datasets.Sequence(datasets.Sequence(datasets.Value("int64"))),
                    "segment_class": datasets.Sequence(
                        datasets.features.ClassLabel(
                            names=["O", "B-PARTES","I-PARTES", "B-EMENTA","I-EMENTA", "B-ACORDAO","I-ACORDAO", "B-RELATORIO","I-RELATORIO", "B-VOTO", "I-VOTO"]
                        )
                    ),
                    "image": datasets.features.Image(),
                }
            ),
            supervised_keys=None,
            #homepage="https://direitodigital.ufms.br/direitodigital/",
            citation=_CITATION,
        )

    def _split_generators(self, dl_manager):
        """Returns SplitGenerators."""
        downloaded_file = dl_manager.download_and_extract("http://direitodigital.ufms.br:8000/direitodigital.zip")
        
        return [
             datasets.SplitGenerator(
                name=datasets.NamedSplit('trainmini_stf'), gen_kwargs={"filepath": f"{downloaded_file}/trainmini/stf"}
            ),
            datasets.SplitGenerator(
                name=datasets.NamedSplit('dev_stf'), gen_kwargs={"filepath": f"{downloaded_file}/dev/stf"}
            ),
             datasets.SplitGenerator(
                name=datasets.NamedSplit('trainmini_stj'), gen_kwargs={"filepath": f"{downloaded_file}/trainmini/stj"}
            ),
            datasets.SplitGenerator(
                name=datasets.NamedSplit('dev_stj'), gen_kwargs={"filepath": f"{downloaded_file}/dev/stj"}
            ),
             datasets.SplitGenerator(
                name=datasets.NamedSplit('trainmini_trf2'), gen_kwargs={"filepath": f"{downloaded_file}/trainmini/trf2"}
            ),
            datasets.SplitGenerator(
                name=datasets.NamedSplit('dev_trf2'), gen_kwargs={"filepath": f"{downloaded_file}/dev/trf2"}
            ),
             datasets.SplitGenerator(
                name=datasets.NamedSplit('trainmini_tjpb'), gen_kwargs={"filepath": f"{downloaded_file}/trainmini/tjpb"}
            ),
            datasets.SplitGenerator(
                name=datasets.NamedSplit('dev_tjpb'), gen_kwargs={"filepath": f"{downloaded_file}/dev/tjpb"}
            ),
            datasets.SplitGenerator(
                name=datasets.NamedSplit('trainmini_tjmg'), gen_kwargs={"filepath": f"{downloaded_file}/trainmini/tjmg"}
            ),
            datasets.SplitGenerator(
                name=datasets.NamedSplit('dev_tjmg'), gen_kwargs={"filepath": f"{downloaded_file}/dev/tjmg"}
            )
        ]

    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):
        guid = 0
        file_paths = [
            os.path.join(root, filename)
            for root, dirs, files in os.walk(filepath)
            for filename in files
            if filename.endswith('.tsv')
        ]
        random.shuffle(file_paths)
        
        
        #for dir_path, _, file_names in os.walk(filepath):
        for tsv_name in file_paths:
            #for file in file_names:
                #tsv_name = os.path.join(dir_path, file)
                #print(file_paths)
                base_path = os.path.dirname(os.path.dirname(filepath))
                pdf_base_path = os.path.join(base_path, 'pdf')
                
                pdf_name = tsv_name.replace('.tsv', '.pdf')
                pdf_name = pdf_name.replace(base_path,pdf_base_path)

                
                img_path = tsv_name.replace('.tsv','')
                print(pdf_name)
                
                pages_img = convert_from_path(pdf_name, size=(595,840),fmt="png")

                dataframe = pd.read_csv(tsv_name ,delimiter='\t', keep_default_na=False).replace(["None","SUMULA","CERTIDAO_DE_JULGAMENTO","AUTUACAO","CERTIDAO","EXTRATO_DE_ATA"], 'OUTROS')
                for page in dataframe['page'].unique():
                    #image, size = load_image(os.path.join(img_path, str(page-1)+'.png'))
                    image, size = pages_img[page-1], pages_img[page-1].size
                    
                    data = (dataframe[dataframe["page"] == page])
                    form = []
                    for index,  row in data.iterrows():
                        tokens = []
                        for token in ast.literal_eval(row['tokens']):

                            tokens.append({
                                    'box' : 
                                        [token['x'], token['y'], token['x']+token['width'], token['y'] + token['height']],
                                    'text' : token['text']
                            })
                        line_dict = {
                            'text': row['text'],
                            'box': [row['x'], row['y'], row['x']+row['width'], row['y'] + row['height']],
                            'label': row['label'],
                            'words': tokens
                        }
                        form.append(line_dict)
                    yield from self.get_form(guid, image, size, form)
                    guid += 1   
        
    
    def get_form(self, guid, image, size, form):
        tokens = []
        bboxes = []
        segment_class = []

        for item in form:
            cur_line_bboxes = []
            words, label = item["words"], item["label"]
            words = [w for w in words if w["text"].strip() != ""]
            if len(words) == 0:
                continue
            if label == "OUTROS":
                for w in words:
                    tokens.append(w["text"])
                    segment_class.append("O")
                    #segment_class.append(label)
                    cur_line_bboxes.append(normalize_bbox(w["box"], size))
            else:
                tokens.append(words[0]["text"])
                segment_class.append("B-" + label.upper())
                cur_line_bboxes.append(normalize_bbox(words[0]["box"], size))
                for w in words[1:]:
                    tokens.append(w["text"])
                    segment_class.append("I-" + label.upper())
                    cur_line_bboxes.append(normalize_bbox(w["box"], size))
            cur_line_bboxes = self.get_line_bbox(cur_line_bboxes)
            bboxes.extend(cur_line_bboxes)
        yield guid, {"id": str(guid), "tokens": tokens, "bboxes": bboxes, "segment_class": segment_class,
                         "image": image}

def main():
    dataset = DireitoDigital()
    for example in dataset._generate_examples('/home/marlon/LayoutLM_dataset/trainmini'):
        print(example)
        




if __name__ == '__main__':
    main()