djstrong commited on
Commit
fc47ed5
1 Parent(s): 09606cc

Upload oscar-small.py

Browse files
Files changed (1) hide show
  1. oscar-small.py +300 -0
oscar-small.py ADDED
@@ -0,0 +1,300 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2020 The TensorFlow Datasets Authors and the HuggingFace NLP Authors.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ # Lint as: python3
17
+ """OSCAR The Open Super-large Crawled ALMAnaCH coRpus."""
18
+
19
+
20
+ import collections
21
+ import gzip
22
+
23
+ import datasets
24
+
25
+
26
+ logger = datasets.logging.get_logger(__name__)
27
+
28
+
29
+ _DESCRIPTION = """\
30
+ The Open Super-large Crawled ALMAnaCH coRpus is a huge multilingual corpus \
31
+ obtained by language classification and filtering of the Common Crawl corpus \
32
+ using the goclassy architecture.\
33
+ """
34
+
35
+ _URL = "https://oscar-corpus.com"
36
+
37
+ _LICENSE = """
38
+ These data are released under this licensing scheme
39
+ We do not own any of the text from which these data has been extracted.
40
+ We license the actual packaging of these data under the Creative Commons CC0 license \
41
+ (\"no rights reserved\") http://creativecommons.org/publicdomain/zero/1.0/
42
+ To the extent possible under law, Inria has waived all copyright \
43
+ and related or neighboring rights to OSCAR
44
+ This work is published from: France.
45
+ Should you consider that our data contains material that is owned by you \
46
+ and should therefore not be reproduced here, please:
47
+ * Clearly identify yourself, with detailed contact data such as an address, \
48
+ telephone number or email address at which you can be contacted.
49
+ * Clearly identify the copyrighted work claimed to be infringed.
50
+ * Clearly identify the material that is claimed to be infringing and \
51
+ information reasonably sufficient to allow us to locate the material.
52
+ We will comply to legitimate requests by removing the affected sources \
53
+ from the next release of the corpus. \
54
+ """
55
+
56
+ _CITATION = """\
57
+ @inproceedings{ortiz-suarez-etal-2020-monolingual,
58
+ title = "A Monolingual Approach to Contextualized Word Embeddings for Mid-Resource Languages",
59
+ author = "Ortiz Su{\'a}rez, Pedro Javier and
60
+ Romary, Laurent and
61
+ Sagot, Benoit",
62
+ booktitle = "Proceedings of the 58th Annual Meeting of the Association for Computational Linguistics",
63
+ month = jul,
64
+ year = "2020",
65
+ address = "Online",
66
+ publisher = "Association for Computational Linguistics",
67
+ url = "https://www.aclweb.org/anthology/2020.acl-main.156",
68
+ pages = "1703--1714",
69
+ abstract = "We use the multilingual OSCAR corpus, extracted from Common Crawl via language classification, filtering and cleaning, to train monolingual contextualized word embeddings (ELMo) for five mid-resource languages. We then compare the performance of OSCAR-based and Wikipedia-based ELMo embeddings for these languages on the part-of-speech tagging and parsing tasks. We show that, despite the noise in the Common-Crawl-based OSCAR data, embeddings trained on OSCAR perform much better than monolingual embeddings trained on Wikipedia. They actually equal or improve the current state of the art in tagging and parsing for all five languages. In particular, they also improve over multilingual Wikipedia-based contextual embeddings (multilingual BERT), which almost always constitutes the previous state of the art, thereby showing that the benefit of a larger, more diverse corpus surpasses the cross-lingual benefit of multilingual embedding architectures.",
70
+ }
71
+ @inproceedings{OrtizSuarezSagotRomary2019,
72
+ author = {Pedro Javier {Ortiz Su{\'a}rez} and Benoit Sagot and Laurent Romary},
73
+ title = {Asynchronous pipelines for processing huge corpora on medium to low resource infrastructures},
74
+ series = {Proceedings of the Workshop on Challenges in the Management of Large Corpora (CMLC-7) 2019. Cardiff, 22nd July 2019},
75
+ editor = {Piotr Bański and Adrien Barbaresi and Hanno Biber and Evelyn Breiteneder and Simon Clematide and Marc Kupietz and Harald L{\"u}ngen and Caroline Iliadi},
76
+ publisher = {Leibniz-Institut f{\"u}r Deutsche Sprache},
77
+ address = {Mannheim},
78
+ doi = {10.14618/ids-pub-9021},
79
+ url = {http://nbn-resolving.de/urn:nbn:de:bsz:mh39-90215},
80
+ pages = {9 -- 16},
81
+ year = {2019},
82
+ abstract = {Common Crawl is a considerably large, heterogeneous multilingual corpus comprised of crawled documents from the internet, surpassing 20TB of data and distributed as a set of more than 50 thousand plain text files where each contains many documents written in a wide variety of languages. Even though each document has a metadata block associated to it, this data lacks any information about the language in which each document is written, making it extremely difficult to use Common Crawl for monolingual applications. We propose a general, highly parallel, multithreaded pipeline to clean and classify Common Crawl by language; we specifically design it so that it runs efficiently on medium to low resource infrastructures where I/O speeds are the main constraint. We develop the pipeline so that it can be easily reapplied to any kind of heterogeneous corpus and so that it can be parameterised to a wide range of infrastructures. We also distribute a 6.3TB version of Common Crawl, filtered, classified by language, shuffled at line level in order to avoid copyright issues, and ready to be used for NLP applications.},
83
+ language = {en}
84
+ }
85
+ """
86
+
87
+ _BASE_DATA_URL_FORMAT_STR = (
88
+ "https://huggingface.co/datasets/nthngdy/oscar-small/resolve/main/data/{language}.gz"
89
+ )
90
+
91
+ def _languages():
92
+ """Create the sorted dictionary of language codes, and language names.
93
+ Returns:
94
+ The sorted dictionary as an instance of `collections.OrderedDict`.
95
+ """
96
+ langs = {
97
+ "af": "Afrikaans",
98
+ "am": "Amharic",
99
+ "ar": "Arabic",
100
+ "arz": "Egyptian Arabic",
101
+ "as": "Assamese",
102
+ "az": "Azerbaijani",
103
+ "ba": "Bashkir",
104
+ "be": "Belarusian",
105
+ "bg": "Bulgarian",
106
+ "bn": "Bengali",
107
+ "bo": "Tibetan",
108
+ "br": "Breton",
109
+ "ca": "Catalan",
110
+ "ceb": "Cebuano",
111
+ "ce": "Chechen",
112
+ "ckb": "Central Kurdish",
113
+ "cs": "Czech",
114
+ "cv": "Chuvash",
115
+ "cy": "Welsh",
116
+ "da": "Danish",
117
+ "de": "German",
118
+ "dv": "Dhivehi",
119
+ "el": "Modern Greek",
120
+ "en": "English",
121
+ "eo": "Esperanto",
122
+ "es": "Spanish",
123
+ "et": "Estonian",
124
+ "eu": "Basque",
125
+ "fa": "Persian",
126
+ "fi": "Finnish",
127
+ "fr": "French",
128
+ "fy": "Western Frisian",
129
+ "ga": "Irish",
130
+ "gl": "Galician",
131
+ "gu": "Gujarati",
132
+ "he": "Hebrew",
133
+ "hi": "Hindi",
134
+ "hr": "Croatian",
135
+ "hu": "Hungarian",
136
+ "hy": "Armenian",
137
+ "id": "Indonesian",
138
+ "is": "Icelandic",
139
+ "it": "Italian",
140
+ "ja": "Japanese",
141
+ "ka": "Georgian",
142
+ "kk": "Kazakh",
143
+ "km": "Central Khmer",
144
+ "kn": "Kannada",
145
+ "ko": "Korean",
146
+ "ku": "Kurdish",
147
+ "ky": "Kirghiz",
148
+ "la": "Latin",
149
+ "lb": "Luxembourgish",
150
+ "lo": "Lao",
151
+ "lt": "Lithuanian",
152
+ "lv": "Latvian",
153
+ "mg": "Malagasy",
154
+ "mhr": "Eastern Mari",
155
+ "mk": "Macedonian",
156
+ "ml": "Malayalam",
157
+ "mn": "Mongolian",
158
+ "mr": "Marathi",
159
+ "ms": "Malay",
160
+ "mt": "Maltese",
161
+ "my": "Burmese",
162
+ "nds": "Low German",
163
+ "ne": "Nepali",
164
+ "nl": "Dutch",
165
+ "nn": "Norwegian Nynorsk",
166
+ "no": "Norwegian",
167
+ "or": "Oriya",
168
+ "os": "Ossetian",
169
+ "pa": "Panjabi",
170
+ "pl": "Polish",
171
+ "pnb": "Western Panjabi",
172
+ "ps": "Pushto",
173
+ "pt": "Portuguese",
174
+ "ro": "Romanian",
175
+ "ru": "Russian",
176
+ "sah": "Yakut",
177
+ "sa": "Sanskrit",
178
+ "sd": "Sindhi",
179
+ "sh": "Serbo-Croatian",
180
+ "si": "Sinhala",
181
+ "sk": "Slovak",
182
+ "sl": "Slovenian",
183
+ "sq": "Albanian",
184
+ "sr": "Serbian",
185
+ "sv": "Swedish",
186
+ "sw": "Swahili",
187
+ "ta": "Tamil",
188
+ "te": "Telugu",
189
+ "tg": "Tajik",
190
+ "th": "Thai",
191
+ "tk": "Turkmen",
192
+ "tl": "Tagalog",
193
+ "tr": "Turkish",
194
+ "tt": "Tatar",
195
+ "ug": "Uighur",
196
+ "uk": "Ukrainian",
197
+ "ur": "Urdu",
198
+ "uz": "Uzbek",
199
+ "vi": "Vietnamese",
200
+ "yi": "Yiddish",
201
+ "zh": "Chinese",
202
+ }
203
+ return collections.OrderedDict(sorted(langs.items()))
204
+
205
+
206
+ class OscarConfig(datasets.BuilderConfig):
207
+ """OSCAR corpus."""
208
+
209
+ def __init__(self, language: str, shuffled=False, deduplicated=True, **kwargs):
210
+ """BuilderConfig for OSCAR.
211
+ Args:
212
+ language (str): It has to contain 2-letter or 3-letter coded strings. For example: "se", "hu", "eml"
213
+ shuffled (bool): shuffled dataset or not. Currently only shuffled=False is supported.
214
+ deduplicated (bool): deduplicated dataset or not.
215
+ **kwargs: Keyword arguments forwarded to super.
216
+ """
217
+ # Validate the language.
218
+ if language not in _languages():
219
+ raise ValueError("Invalid language: %s " % language)
220
+
221
+ shuffled_str = "shuffled" if shuffled else "unshuffled"
222
+ deduplicated_str = "deduplicated" if deduplicated else "original"
223
+
224
+ # Initialize the base class.
225
+ name = f"{shuffled_str}_{deduplicated_str}_{language}"
226
+ description = f"{shuffled_str.capitalize()} and {deduplicated_str}, {_languages()[language]} OSCAR-Small dataset"
227
+ super(OscarConfig, self).__init__(name=name, description=description, **kwargs)
228
+
229
+ # Additional attributes
230
+ self.language = language
231
+ self.shuffled = shuffled
232
+ self.deduplicated = deduplicated
233
+ self.base_data_url = _BASE_DATA_URL_FORMAT_STR.format(
234
+ language=language
235
+ )
236
+
237
+
238
+ class Oscar(datasets.GeneratorBasedBuilder):
239
+ """OSCAR The Open Super-large Crawled ALMAnaCH coRpus."""
240
+
241
+ # Version history:
242
+ # 1.0.0: S3 (new shuffling, sharding and slicing mechanism).
243
+ # 0.1.0: Initial version.
244
+ BUILDER_CONFIGS = [
245
+ OscarConfig( # pylint: disable=g-complex-comprehension
246
+ language=language,
247
+ shuffled=False,
248
+ deduplicated=True,
249
+ version=datasets.Version("1.0.0"),
250
+ )
251
+ for language in _languages()
252
+ ] + [
253
+ OscarConfig( # pylint: disable=g-complex-comprehension
254
+ language=language,
255
+ shuffled=False,
256
+ deduplicated=False,
257
+ version=datasets.Version("1.0.0"),
258
+ )
259
+ for language in _languages()
260
+ ]
261
+ BUILDER_CONFIG_CLASS = OscarConfig
262
+
263
+ def _info(self):
264
+ return datasets.DatasetInfo(
265
+ description=_DESCRIPTION,
266
+ features=datasets.Features({"id": datasets.Value("int64"), "text": datasets.Value("string")}),
267
+ supervised_keys=None,
268
+ homepage=_URL,
269
+ citation=_CITATION,
270
+ license=_LICENSE,
271
+ )
272
+
273
+ def _split_generators(self, dl_manager):
274
+ data_url = self.config.base_data_url
275
+ downloaded_files = [dl_manager.download(data_url)]
276
+ return [
277
+ datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={"filepaths": downloaded_files}),
278
+ ]
279
+
280
+ def _generate_examples(self, filepaths):
281
+ """This function returns the examples in the raw (text) form by iterating on all the files."""
282
+ id_ = 0
283
+ current_lines = []
284
+ for filepath in filepaths:
285
+ logger.info("generating examples from = %s", filepath)
286
+ with gzip.open(open(filepath, "rb"), "rt", encoding="utf-8") as f:
287
+ for line in f:
288
+ if len(line.strip()) > 0:
289
+ current_lines.append(line)
290
+ elif current_lines:
291
+ feature = id_, {"id": id_, "text": "".join(current_lines).rstrip()}
292
+ yield feature
293
+ id_ += 1
294
+ current_lines = []
295
+ # last paragraph
296
+ if current_lines:
297
+ feature = id_, {"id": id_, "text": "".join(current_lines).rstrip()}
298
+ yield feature
299
+ id_ += 1
300
+ current_lines = []