File size: 6,856 Bytes
09ef168
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4baed46
09ef168
 
 
816a97f
09ef168
 
7ea460a
 
 
09ef168
 
 
 
 
 
 
 
 
 
 
4baed46
09ef168
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4baed46
09ef168
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2772f07
 
 
 
 
 
09ef168
 
 
 
4baed46
 
09ef168
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4baed46
09ef168
 
 
 
 
 
 
 
 
 
 
 
 
4baed46
 
 
816a97f
4baed46
816a97f
4baed46
 
 
09ef168
4baed46
816a97f
4baed46
816a97f
09ef168
816a97f
09ef168
 
 
816a97f
09ef168
 
 
 
 
 
 
 
 
 
 
 
7ea460a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# Copyright 2020 The HuggingFace Datasets Authors and the current dataset
# script contributor.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Carolina Corpus"""

from collections import defaultdict
from lxml import etree
import os
import datasets
import gzip


logger = datasets.logging.get_logger(__name__)


_HOMEPAGE = "https://sites.usp.br/corpuscarolina/"


_DESCRIPTION = """
Carolina is an Open Corpus for Linguistics and Artificial Intelligence with a
robust volume of texts of varied typology in contemporary Brazilian Portuguese
(1970-2021).
"""


_CITATION = r"""
@misc{corpusCarolinaV1.2,
    title={
        Carolina:
        The Open Corpus for Linguistics and Artificial Intelligence},
    author={
        Finger, Marcelo and
        Paixão de Sousa, Maria Clara and
        Namiuti, Cristiane and
        Martins do Monte, Vanessa and
        Costa, Aline Silva and
        Serras, Felipe Ribas and
        Sturzeneker, Mariana Lourenço and
        Guets, Raquel de Paula and
        Mesquita, Renata Morais and
        Mello, Guilherme Lamartine de and
        Crespo, Maria Clara Ramos Morales and
        Rocha, Maria Lina de Souza Jeannine and
        Brasil, Patrícia and
        Silva, Mariana Marques da and
        Palma, Mayara Feliciano},
    howpublished={\url{https://sites.usp.br/corpuscarolina/corpus}},
    year={2022},
    note={Version 1.2 (Ada)},
}
"""


_LICENSE = """
The Open Corpus for Linguistics and Artificial Intelligence (Carolina) was
compiled for academic purposes, namely linguistic and computational analysis.
It is composed of texts assembled in various digital repositories, whose
licenses are multiple and therefore should be observed when making use of the
corpus. The Carolina headers are licensed under Creative Commons
Attribution-NonCommercial-ShareAlike 4.0 International."
"""


def _taxonomies():
    """Creates a map between taxonomy code and name

    Returns
    -------
    dict
        The dictionary of codes and names.
    """
    return dict(
        dat="datasets_and_other_corpora",
        jud="judicial_branch",
        leg="legislative_branch",
        pub="public_domain_works",
        soc="social_media",
        uni="university_domains",
        wik="wikis",
    )


_VERSION = "1.2.0"
_CORPUS_URL = "corpus/{tax}/"
_CHECKSUM_FNAME = _CORPUS_URL + "checksum.sha256"


class CarolinaConfig(datasets.BuilderConfig):
    """Carolina Configuration."""
    def __init__(self, taxonomy: str = None, **kwargs):
        """BuilderConfig for Carolina

        Parameters
        ----------
        taxonomy : str
            The taxonomy code (3 letters). The code defines the taxonomy
            to download. If `None`, all taxonomies will be downloaded.
        **kwargs
            Arguments passed to super.
        """
        # validates taxonomy
        if taxonomy is None:
            taxonomy = "all"
        elif taxonomy != "all" and taxonomy not in _taxonomies():
            raise ValueError(f"Invalid taxonomy: {taxonomy}")

        # custom name and description
        description = "Carolina corpus."
        if taxonomy == "all":
            name = "carolina"
            description += " Using all taxonomies."
        else:
            name = _taxonomies()[taxonomy]
            description += f" Using taxonomy {taxonomy}"

        super(CarolinaConfig, self).__init__(
            name=name, description=description, **kwargs)

        # Carolina attributes
        self.taxonomy = taxonomy
        self.version = datasets.Version(_VERSION)


class Carolina(datasets.GeneratorBasedBuilder):
    """Carolina Downloader and Builder"""

    BUILDER_CONFIG_CLASS = CarolinaConfig

    def _info(self):
        features = datasets.Features({
            "meta": datasets.Value("string"),
            "text": datasets.Value("string")
        })

        return datasets.DatasetInfo(
            description=_DESCRIPTION,
            supervised_keys=None,
            homepage=_HOMEPAGE,
            citation=_CITATION,
            features=features,
            license=_LICENSE
        )

    def _split_generators(self, dl_manager):
        # list taxonomies to download
        if self.config.taxonomy == "all":
            taxonomies = _taxonomies().values()
        else:
            taxonomies = [_taxonomies()[self.config.taxonomy]]

        # download checksum files
        checksum_urls = {t: _CHECKSUM_FNAME.format(tax=t) for t in taxonomies}
        checksum_paths = dl_manager.download(checksum_urls)

        # prepare xml file name and zip urls
        gzip_urls = list()
        for tax, cpath in checksum_paths.items():
            tax_path = _CORPUS_URL.format(tax=tax)
            with open(cpath, encoding="utf-8") as cfile:
                for line in cfile:
                    xml_tax_path = line.split()[1]                  # xml file inside taxonomy
                    zip_fname = xml_tax_path + ".gz"                # zip file inside taxonomy
                    zip_fpath = os.path.join(tax_path, zip_fname)   # path inside corpus
                    gzip_urls.append(zip_fpath)

        gzip_files = dl_manager.download(gzip_urls)
        return [
            datasets.SplitGenerator(
                name="corpus",
                gen_kwargs={"filepaths": gzip_files}
            )
        ]

    def _generate_examples(self, filepaths):
        TEI_NS = "{http://www.tei-c.org/ns/1.0}"
        parser_params = dict(
            huge_tree=True,
            encoding="utf-8",
            tag=f"{TEI_NS}TEI"
        )

        _key = 0
        for doc_path in filepaths:
            logger.info("generating examples from = %s", doc_path)
            with gzip.open(open(doc_path, "rb"), "rb") as gzip_file:
                for _, tei in etree.iterparse(gzip_file, **parser_params):
                    header = tei.find(f"{TEI_NS}teiHeader")

                    meta = etree.tostring(
                        header, encoding="utf-8").decode("utf-8")
                    text = ' '.join([e.text
                        for e in tei.findall(f".//{TEI_NS}body/{TEI_NS}p")
                        if e.text is not None
                    ])

                    yield _key, {
                        "meta": meta,
                        "text": text
                    }
                    _key += 1

                gzip_file.close()