File size: 15,955 Bytes
1de8de7
 
88bda97
 
1de8de7
7fcc229
88bda97
1de8de7
7fcc229
1de8de7
7fcc229
 
 
 
1de8de7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88bda97
1de8de7
 
 
7fcc229
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1de8de7
 
 
 
7fcc229
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88bda97
7fcc229
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41b694a
 
 
 
 
7fcc229
88bda97
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7fcc229
1de8de7
 
 
 
 
88bda97
 
 
 
 
 
 
 
1de8de7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88bda97
 
 
 
 
 
 
 
 
 
 
 
1de8de7
88bda97
1de8de7
 
 
 
88bda97
 
 
 
 
 
 
 
 
1de8de7
88bda97
 
 
 
 
 
 
 
 
7fcc229
88bda97
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41b694a
1de8de7
 
 
 
 
 
 
 
 
 
 
41b694a
1de8de7
 
 
 
 
 
 
 
 
 
 
 
 
41b694a
1de8de7
 
 
 
41b694a
7fcc229
 
 
 
 
 
 
 
 
 
41b694a
 
7fcc229
41b694a
7fcc229
41b694a
 
 
 
7fcc229
41b694a
7fcc229
 
1de8de7
 
 
 
 
7fcc229
 
 
41b694a
 
 
88bda97
 
 
1de8de7
 
 
 
88bda97
 
 
 
 
7fcc229
88bda97
41b694a
88bda97
 
 
 
 
 
 
 
 
1de8de7
 
88bda97
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1de8de7
 
 
88bda97
 
 
1de8de7
 
88bda97
 
 
 
 
 
 
 
 
1de8de7
7fcc229
 
41b694a
 
 
 
 
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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
import datasets
from typing import Dict, List, Optional, Union
import json
import textwrap

import xml.etree.ElementTree as ET
import pandas as pd

logger = datasets.logging.get_logger(__name__)

# Extracted from: 
# - https://huggingface.co/datasets/lener_br
# - https://github.com/peluz/lener-br
# - https://teodecampos.github.io/LeNER-Br/
_LENERBR_KWARGS = dict(
    name = "LeNER-Br",
    description=textwrap.dedent(
            """\
        LeNER-Br is a Portuguese language dataset for named entity recognition applied to legal documents. 
        LeNER-Br consists entirely of manually annotated legislation and legal cases texts and contains tags 
        for persons, locations, time entities, organizations, legislation and legal cases. To compose the dataset, 
        66 legal documents from several Brazilian Courts were collected. Courts of superior and state levels were considered, 
        such as Supremo Tribunal Federal, Superior Tribunal de Justiça, Tribunal de Justiça de Minas Gerais and Tribunal de Contas da União. 
        In addition, four legislation documents were collected, such as "Lei Maria da Penha", giving a total of 70 documents."""
    ),
    task_type="ner",
    label_classes=["ORGANIZACAO", "PESSOA", "TEMPO", "LOCAL", "LEGISLACAO", "JURISPRUDENCIA"],
    data_urls={
        "train": "https://raw.githubusercontent.com/peluz/lener-br/master/leNER-Br/train/train.conll",
        "validation": "https://raw.githubusercontent.com/peluz/lener-br/master/leNER-Br/dev/dev.conll",
        "test": "https://raw.githubusercontent.com/peluz/lener-br/master/leNER-Br/test/test.conll",
    },  
    citation=textwrap.dedent(
            """\
        @InProceedings{luz_etal_propor2018,
            author = {Pedro H. {Luz de Araujo} and Te\'{o}filo E. {de Campos} and
                    Renato R. R. {de Oliveira} and Matheus Stauffer and
                    Samuel Couto and Paulo Bermejo},
            title = {{LeNER-Br}: a Dataset for Named Entity Recognition in {Brazilian} Legal Text},
            booktitle = {International Conference on the Computational Processing of Portuguese ({PROPOR})},
            publisher = {Springer},
            series = {Lecture Notes on Computer Science ({LNCS})},
            pages = {313--323},
            year = {2018},
            month = {September 24-26},
            address = {Canela, RS, Brazil},	  
            doi = {10.1007/978-3-319-99722-3_32},
            url = {https://teodecampos.github.io/LeNER-Br/},
        }"""
    ),
    url="https://teodecampos.github.io/LeNER-Br/",
)

# Extracted from: 
# - https://huggingface.co/datasets/assin2
# - https://sites.google.com/view/assin2
# - https://github.com/ruanchaves/assin
_ASSIN2_BASE_KWARGS = dict(
    description=textwrap.dedent(
            """\
        The ASSIN 2 corpus is composed of rather simple sentences. Following the procedures of SemEval 2014 Task 1.
        The training and validation data are composed, respectively, of 6,500 and 500 sentence pairs in Brazilian Portuguese,
        annotated for entailment and semantic similarity. Semantic similarity values range from 1 to 5, and text entailment
        classes are either entailment or none. The test data are composed of approximately 3,000 sentence pairs with the same
        annotation. All data were manually annotated."""
    ),
    data_urls={
        "train": "https://github.com/ruanchaves/assin/raw/master/sources/assin2-train-only.xml",
        "validation": "https://github.com/ruanchaves/assin/raw/master/sources/assin2-dev.xml",
        "test": "https://github.com/ruanchaves/assin/raw/master/sources/assin2-test.xml",
    },  
    citation=textwrap.dedent(
            """\
        @inproceedings{real2020assin,
            title={The assin 2 shared task: a quick overview},
            author={Real, Livy and Fonseca, Erick and Oliveira, Hugo Goncalo},
            booktitle={International Conference on Computational Processing of the Portuguese Language},
            pages={406--412},
            year={2020},
            organization={Springer}
        }"""
    ),
    url="https://sites.google.com/view/assin2",
)
_ASSIN2_RTE_KWARGS = dict(
    name = "assin2-rte",
    task_type="rte",
    label_classes=["NONE", "ENTAILMENT"],
    **_ASSIN2_BASE_KWARGS
)
_ASSIN2_STS_KWARGS = dict(
    name = "assin2-sts",
    task_type="sts",
    **_ASSIN2_BASE_KWARGS
)

# Extracted from: 
# - https://huggingface.co/datasets/ruanchaves/hatebr
# - https://github.com/franciellevargas/HateBR
_HATEBR_KWARGS = dict(
    name = "HateBR",
    description=textwrap.dedent(
            """\
        HateBR is the first large-scale expert annotated dataset of Brazilian Instagram comments for abusive language detection 
        on the web and social media. The HateBR was collected from Brazilian Instagram comments of politicians and manually annotated 
        by specialists. It is composed of 7,000 documents annotated according to three different layers: a binary classification (offensive 
        versus non-offensive comments), offensiveness-level (highly, moderately, and slightly offensive messages), and nine hate speech 
        groups (xenophobia, racism, homophobia, sexism, religious intolerance, partyism, apology for the dictatorship, antisemitism, 
        and fatphobia). Each comment was annotated by three different annotators and achieved high inter-annotator agreement. Furthermore, 
        baseline experiments were implemented reaching 85% of F1-score outperforming the current literature dataset baselines for 
        the Portuguese language. We hope that the proposed expert annotated dataset may foster research on hate speech detection in the 
        Natural Language Processing area."""
    ),
    task_type="classification",
    file_type="csv",
    label_classes=[0, 1, 2, 3],
    data_urls={
        "train": "https://raw.githubusercontent.com/franciellevargas/HateBR/2d18c5b9410c2dfdd6d5394caa54d608857dae7c/dataset/HateBR.csv"
    },
    citation=textwrap.dedent(
            """\
        @inproceedings{vargas2022hatebr,
            title={HateBR: A Large Expert Annotated Corpus of Brazilian Instagram Comments for Offensive Language and Hate Speech Detection},
            author={Vargas, Francielle and Carvalho, Isabelle and de G{\'o}es, Fabiana Rodrigues and Pardo, Thiago and Benevenuto, Fabr{\'\i}cio},
            booktitle={Proceedings of the Thirteenth Language Resources and Evaluation Conference},
            pages={7174--7183},
            year={2022}
        }"""
    ),
    url="https://github.com/franciellevargas/HateBR",
    text_and_label_columns=["instagram_comments", "offensiveness_levels"],
    indexes_url="https://huggingface.co/datasets/ruanchaves/hatebr/raw/main/indexes.json"
)

class PTBenchmarkConfig(datasets.BuilderConfig):
    """BuilderConfig for PTBenchmark."""

    def __init__(
        self,
        task_type: str,
        data_urls: Dict[str, str],
        citation: str,
        url: str,
        label_classes: Optional[List[Union[str, int]]] = None,
        file_type: Optional[str] = None, #filetype (csv, tsc, jsonl)
        text_and_label_columns: Optional[List[str]] = None, #columns for train, dev and test for csv datasets
        indexes_url=None, #indexes for train, dev and test for single file datasets
        **kwargs,
    ):
        """BuilderConfig for GLUE.
        Args:
          text_features: `dict[string, string]`, map from the name of the feature
            dict for each text field to the name of the column in the tsv file
          label_column: `string`, name of the column in the tsv file corresponding
            to the label
          data_url: `string`, url to download the zip file from
          data_dir: `string`, the path to the folder containing the tsv files in the
            downloaded zip
          citation: `string`, citation for the data set
          url: `string`, url for information about the data set
          label_classes: `list[string]`, the list of classes if the label is
            categorical. If not provided, then the label will be of type
            `datasets.Value('float32')`.
          process_label: `Function[string, any]`, function  taking in the raw value
            of the label and processing it to the form required by the label feature
          **kwargs: keyword arguments forwarded to super.
        """
        super(PTBenchmarkConfig, self).__init__(version=datasets.Version("1.0.3", ""), **kwargs)
        self.label_classes = label_classes
        self.task_type = task_type
        self.data_urls = data_urls
        self.citation = citation
        self.url = url
        self.file_type = file_type
        self.text_and_label_columns = text_and_label_columns
        self.indexes_url = indexes_url

def _get_classification_features(config):
    return datasets.Features(
        {
            "idx": datasets.Value("int32"),
            "sentence": datasets.Value("string"),
            "label": datasets.features.ClassLabel(names=config.label_classes),
        }
    )

def _get_ner_features(config):
    bio_labels = ["O"]
    for label_name in config.label_classes:
        bio_labels.append("B-" + label_name)
        bio_labels.append("I-" + label_name)
    return datasets.Features(
        {
            "idx": datasets.Value("int32"),
            "tokens": datasets.Sequence(datasets.Value("string")),
            "ner_tags": datasets.Sequence(
                datasets.features.ClassLabel(names=bio_labels)
            ),
        }
    )

def _get_rte_features(config):
    return datasets.Features(
        {
            "idx": datasets.Value("int32"),
            "sentence1": datasets.Value("string"),
            "sentence2": datasets.Value("string"),
            "label": datasets.features.ClassLabel(names=config.label_classes),
        }
    )

def _get_sts_features(config):
    return datasets.Features(
        {
            "idx": datasets.Value("int32"),
            "sentence1": datasets.Value("string"),
            "sentence2": datasets.Value("string"),
            "label": datasets.Value("float32"),
        }
    )

def _csv_generator(file_path: str,
                   columns: List[str],
                   indexes_path: Optional[str] = None,
                   split: Optional[str] = None):
    """Yields examples."""
    df = pd.read_csv(file_path)
    df = df[columns]

    with open(indexes_path, "r") as f:
        indexes= json.load(f)
    split_indexes = indexes[split]
    df_split = df.iloc[split_indexes]

    for id_, row in df_split.iterrows():
        example = {
            "idx": id_,
            "sentence": str(row[columns[0]]),
            "label": int(row[columns[-1]])
        }
        yield id_, example

def _conll_ner_generator(file_path):
    with open(file_path, encoding="utf-8") as f:

        guid = 0
        tokens = []
        ner_tags = []

        for line in f:
            if line == "" or line == "\n":
                if tokens:
                    yield guid, {
                        "idx": guid,
                        "tokens": tokens,
                        "ner_tags": ner_tags,
                    }
                    guid += 1
                    tokens = []
                    ner_tags = []
            else:
                splits = line.split(" ")
                tokens.append(splits[0])
                ner_tags.append(splits[1].rstrip())

        # last example
        yield guid, {
            "idx": guid,
            "tokens": tokens,
            "ner_tags": ner_tags,
        }

def _assin2_generator(file_path, type):
    """Yields examples."""
    id_ = 0

    with open(file_path, "rb") as f:

        tree = ET.parse(f)
        root = tree.getroot()

        for pair in root:

            example = {
                "idx": int(pair.attrib.get("id")),
                "sentence1": pair.find(".//t").text,
                "sentence2": pair.find(".//h").text
            }
            if type == "rte":
                example["label"] = pair.attrib.get("entailment").upper()
            elif type == "sts":
                example["label"] = float(pair.attrib.get("similarity"))

            yield id_, example
            id_ += 1


class PTBenchmark(datasets.GeneratorBasedBuilder):
    BUILDER_CONFIGS = [
        PTBenchmarkConfig(
            **_LENERBR_KWARGS
        ),
        PTBenchmarkConfig(
            **_ASSIN2_RTE_KWARGS
        ),
        PTBenchmarkConfig(
            **_ASSIN2_STS_KWARGS
        ),
        PTBenchmarkConfig(
            **_HATEBR_KWARGS
        )
    ]

    def _info(self) -> datasets.DatasetInfo:
        features = None
        if self.config.task_type == "classification":
            features = _get_classification_features(self.config)
        elif self.config.task_type == "ner":
            features = _get_ner_features(self.config)
        elif self.config.task_type == "rte":
            features = _get_rte_features(self.config)
        elif self.config.task_type == "sts":
            features = _get_sts_features(self.config)
        
        return datasets.DatasetInfo(
            description=self.config.description,
            homepage=self.config.url,
            citation=self.config.citation,
            supervised_keys=None,
            features=features
        )
        
    def _split_generators(self, dl_manager: datasets.DownloadManager):
        data_urls = self.config.data_urls.copy()
        if self.config.indexes_url is not None:
            data_urls['indexes'] = self.config.indexes_url
        file_paths = dl_manager.download_and_extract(data_urls)

        if self.config.indexes_url is None:
            return [
                datasets.SplitGenerator(
                    name=datasets.Split.TRAIN,
                    gen_kwargs={"file_path": file_paths["train"]},
                ),
                datasets.SplitGenerator(
                    name=datasets.Split.VALIDATION,
                    gen_kwargs={"file_path": file_paths["validation"]},
                ),
                datasets.SplitGenerator(
                    name=datasets.Split.TEST,
                    gen_kwargs={"file_path": file_paths["test"]},
                )
            ]
        else:
            return [
                datasets.SplitGenerator(
                    name=datasets.Split.TRAIN,
                    gen_kwargs={"file_path": file_paths["train"], "indexes_path": file_paths["indexes"], "split": "train"},
                ),
                datasets.SplitGenerator(
                    name=datasets.Split.VALIDATION,
                    gen_kwargs={"file_path": file_paths["train"], "indexes_path": file_paths["indexes"], "split": "validation"},
                ),
                datasets.SplitGenerator(
                    name=datasets.Split.TEST,
                    gen_kwargs={"file_path": file_paths["train"], "indexes_path": file_paths["indexes"], "split": "test"},
                )
            ]
    
    def _generate_examples(
        self,
        file_path: Optional[str] = None,
        indexes_path: Optional[str] = None,
        split: Optional[str] = None
    ):
        logger.info("⏳ Generating examples from = %s", file_path)
        if self.config.task_type == "classification":
            if self.config.file_type == "csv":
                yield from _csv_generator(
                    file_path, 
                    self.config.text_and_label_columns,
                    indexes_path=indexes_path,
                    split=split
                )
        elif self.config.task_type == "ner":
            yield from _conll_ner_generator(file_path)
        elif self.config.task_type == "rte":
            if "assin2" in self.config.name:
                yield from _assin2_generator(file_path, "rte")
        elif self.config.task_type == "sts":
            if "assin2" in self.config.name:
                yield from _assin2_generator(file_path, "sts")