oscar-mini / oscar-mini.py
nthngdy's picture
Create oscar-mini.py
# coding=utf-8
# Copyright 2020 The TensorFlow Datasets Authors and the HuggingFace NLP Authors.
# 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,
# See the License for the specific language governing permissions and
# limitations under the License.
# Lint as: python3
"""OSCAR The Open Super-large Crawled ALMAnaCH coRpus."""
import collections
import gzip
import datasets
logger = datasets.logging.get_logger(__name__)
The Open Super-large Crawled ALMAnaCH coRpus is a huge multilingual corpus \
obtained by language classification and filtering of the Common Crawl corpus \
using the goclassy architecture.\
_URL = "https://oscar-corpus.com"
_LICENSE = """
These data are released under this licensing scheme
We do not own any of the text from which these data has been extracted.
We license the actual packaging of these data under the Creative Commons CC0 license \
(\"no rights reserved\") http://creativecommons.org/publicdomain/zero/1.0/
To the extent possible under law, Inria has waived all copyright \
and related or neighboring rights to OSCAR
This work is published from: France.
Should you consider that our data contains material that is owned by you \
and should therefore not be reproduced here, please:
* Clearly identify yourself, with detailed contact data such as an address, \
telephone number or email address at which you can be contacted.
* Clearly identify the copyrighted work claimed to be infringed.
* Clearly identify the material that is claimed to be infringing and \
information reasonably sufficient to allow us to locate the material.
We will comply to legitimate requests by removing the affected sources \
from the next release of the corpus. \
_CITATION = """\
title = "A Monolingual Approach to Contextualized Word Embeddings for Mid-Resource Languages",
author = "Ortiz Su{\'a}rez, Pedro Javier and
Romary, Laurent and
Sagot, Benoit",
booktitle = "Proceedings of the 58th Annual Meeting of the Association for Computational Linguistics",
month = jul,
year = "2020",
address = "Online",
publisher = "Association for Computational Linguistics",
url = "https://www.aclweb.org/anthology/2020.acl-main.156",
pages = "1703--1714",
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.",
author = {Pedro Javier {Ortiz Su{\'a}rez} and Benoit Sagot and Laurent Romary},
title = {Asynchronous pipelines for processing huge corpora on medium to low resource infrastructures},
series = {Proceedings of the Workshop on Challenges in the Management of Large Corpora (CMLC-7) 2019. Cardiff, 22nd July 2019},
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},
publisher = {Leibniz-Institut f{\"u}r Deutsche Sprache},
address = {Mannheim},
doi = {10.14618/ids-pub-9021},
url = {http://nbn-resolving.de/urn:nbn:de:bsz:mh39-90215},
pages = {9 -- 16},
year = {2019},
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.},
language = {en}
def _languages():
"""Create the sorted dictionary of language codes, and language names.
The sorted dictionary as an instance of `collections.OrderedDict`.
langs = {
"af": "Afrikaans",
"als": "Tosk Albanian",
"am": "Amharic",
"ar": "Arabic",
"arz": "Egyptian Arabic",
"as": "Assamese",
"azb": "South Azerbaijani",
"az": "Azerbaijani",
"ba": "Bashkir",
"be": "Belarusian",
"bg": "Bulgarian",
"bh": "Bihari",
"bn": "Bengali",
"bo": "Tibetan",
"br": "Breton",
"ca": "Catalan",
"ceb": "Cebuano",
"ce": "Chechen",
"ckb": "Central Kurdish",
"cs": "Czech",
"cv": "Chuvash",
"cy": "Welsh",
"da": "Danish",
"de": "German",
"dv": "Dhivehi",
"el": "Modern Greek",
"en": "English",
"eo": "Esperanto",
"es": "Spanish",
"et": "Estonian",
"eu": "Basque",
"fa": "Persian",
"fi": "Finnish",
"fr": "French",
"fy": "Western Frisian",
"ga": "Irish",
"gl": "Galician",
"gn": "Guarani",
"gu": "Gujarati",
"he": "Hebrew",
"hi": "Hindi",
"hr": "Croatian",
"hsb": "Upper Sorbian",
"hu": "Hungarian",
"hy": "Armenian",
"id": "Indonesian",
"is": "Icelandic",
"it": "Italian",
"ja": "Japanese",
"ka": "Georgian",
"kk": "Kazakh",
"km": "Central Khmer",
"kn": "Kannada",
"ko": "Korean",
"ku": "Kurdish",
"ky": "Kirghiz",
"la": "Latin",
"lb": "Luxembourgish",
"lo": "Lao",
"lt": "Lithuanian",
"lv": "Latvian",
"mg": "Malagasy",
"mhr": "Eastern Mari",
"mk": "Macedonian",
"ml": "Malayalam",
"mn": "Mongolian",
"mr": "Marathi",
"ms": "Malay",
"mt": "Maltese",
"my": "Burmese",
"nds": "Low German",
"ne": "Nepali",
"new": "Newari",
"nl": "Dutch",
"nn": "Norwegian Nynorsk",
"no": "Norwegian",
"oc": "Occitan",
"or": "Oriya",
"os": "Ossetian",
"pa": "Panjabi",
"pl": "Polish",
"pnb": "Western Panjabi",
"ps": "Pushto",
"pt": "Portuguese",
"ro": "Romanian",
"ru": "Russian",
"sah": "Yakut",
"sa": "Sanskrit",
"scn": "Sicilian",
"sd": "Sindhi",
"sh": "Serbo-Croatian",
"si": "Sinhala",
"sk": "Slovak",
"sl": "Slovenian",
"sq": "Albanian",
"sr": "Serbian",
"sv": "Swedish",
"sw": "Swahili",
"ta": "Tamil",
"te": "Telugu",
"tg": "Tajik",
"th": "Thai",
"tk": "Turkmen",
"tl": "Tagalog",
"tr": "Turkish",
"tt": "Tatar",
"ug": "Uighur",
"uk": "Ukrainian",
"ur": "Urdu",
"uz": "Uzbek",
"vi": "Vietnamese",
"xal": "Kalmyk",
"xmf": "Mingrelian",
"yi": "Yiddish",
"zh": "Chinese",
return collections.OrderedDict(sorted(langs.items()))
class OscarConfig(datasets.BuilderConfig):
"""OSCAR corpus."""
def __init__(self, language: str, shuffled=False, deduplicated=True, **kwargs):
"""BuilderConfig for OSCAR.
language (str): It has to contain 2-letter or 3-letter coded strings. For example: "se", "hu", "eml"
shuffled (bool): shuffled dataset or not. Currently only shuffled=False is supported.
deduplicated (bool): deduplicated dataset or not.
**kwargs: Keyword arguments forwarded to super.
# Validate the language.
if language not in _languages():
raise ValueError("Invalid language: %s " % language)
shuffled_str = "shuffled" if shuffled else "unshuffled"
deduplicated_str = "deduplicated" if deduplicated else "original"
# Initialize the base class.
name = f"{shuffled_str}_{deduplicated_str}_{language}"
description = f"{shuffled_str.capitalize()} and {deduplicated_str}, {_languages()[language]} OSCAR-Mini dataset"
super(OscarConfig, self).__init__(name=name, description=description, **kwargs)
# Additional attributes
self.language = language
self.shuffled = shuffled
self.deduplicated = deduplicated
self.base_data_url = _BASE_DATA_URL_FORMAT_STR.format(
class Oscar(datasets.GeneratorBasedBuilder):
"""OSCAR The Open Super-large Crawled ALMAnaCH coRpus."""
# Version history:
# 1.0.0: S3 (new shuffling, sharding and slicing mechanism).
# 0.1.0: Initial version.
OscarConfig( # pylint: disable=g-complex-comprehension
for language in _languages()
] + [
OscarConfig( # pylint: disable=g-complex-comprehension
for language in _languages()
def _info(self):
return datasets.DatasetInfo(
features=datasets.Features({"id": datasets.Value("int64"), "text": datasets.Value("string")}),
def _split_generators(self, dl_manager):
data_url = self.config.base_data_url
downloaded_file = dl_manager.download(data_url)
return [
datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={"filepaths": downloaded_files}),
def _generate_examples(self, filepaths):
"""This function returns the examples in the raw (text) form by iterating on all the files."""
id_ = 0
current_lines = []
for filepath in filepaths:
logger.info("generating examples from = %s", filepath)
with gzip.open(open(filepath, "rb"), "rt", encoding="utf-8") as f:
for line in f:
if len(line.strip()) > 0:
elif current_lines:
feature = id_, {"id": id_, "text": "".join(current_lines).rstrip()}
yield feature
id_ += 1
current_lines = []
# last paragraph
if current_lines:
feature = id_, {"id": id_, "text": "".join(current_lines).rstrip()}
yield feature
id_ += 1
current_lines = []