cc100-samples / sample.py
eson's picture
add data
970bf82
"""
https://github.com/pytorch/data/blob/main/examples/text/CC100.ipynb
Sample from multi-gigabyte-size compressed dataset without downloading the whole thing
This executes very fast
"""
import time
import os
from functools import partial
from operator import itemgetter
from torchdata.datapipes.iter import (
FileOpener,
HttpReader,
)
ROOT_DIR = os.path.expanduser('~/.torchdata/CC100') # This directory needs to be crated and set
def _path_fn(root, x):
return os.path.join(root, os.path.basename(x).rstrip(".xz"))
def _process_tuple(language_code, t):
return language_code, t[1].decode()
# CC100 support (http://data.statmt.org/cc-100/)
URL = "http://data.statmt.org/cc-100/%s.txt.xz"
VALID_CODES = [
"am", "ar", "as", "az", "be", "bg", "bn", "bn_rom", "br", "bs", "ca", "cs", "cy", "da", "de",
"el", "en", "eo", "es", "et", "eu", "fa", "ff", "fi", "fr", "fy", "ga", "gd", "gl", "gn", "gu",
"ha", "he", "hi", "hi_rom", "hr", "ht", "hu", "hy", "id", "ig", "is", "it", "ja", "jv", "ka",
"kk", "km", "kn", "ko", "ku", "ky", "la", "lg", "li", "ln", "lo", "lt", "lv", "mg", "mk", "ml",
"mn", "mr", "ms", "my", "my_zaw", "ne", "nl", "no", "ns", "om", "or", "pa", "pl", "ps", "pt",
"qu", "rm", "ro", "ru", "sa", "si", "sc", "sd", "sk", "sl", "so", "sq", "sr", "ss", "su", "sv",
"sw", "ta", "ta_rom", "te", "te_rom", "th", "tl", "tn", "tr", "ug", "uk", "ur", "ur_rom", "uz",
"vi", "wo", "xh", "yi", "yo", "zh-Hans", "zh-Hant", "zu",
]
def CC100(root, language_code, use_caching=True):
if language_code not in VALID_CODES:
raise ValueError(f"Invalid language code {language_code}")
url = URL % language_code
if use_caching:
cache_compressed_dp = HttpReader([url]).map(itemgetter(0))
cache_compressed_dp = cache_compressed_dp.end_caching(mode="wb", same_filepath_fn=True)
cache_decompressed_dp = cache_compressed_dp.on_disk_cache(filepath_fn=partial(_path_fn, root))
cache_decompressed_dp = FileOpener(cache_decompressed_dp).read_from_xz()
cache_decompressed_dp = cache_decompressed_dp.end_caching(mode="wb")
data_dp = FileOpener(cache_decompressed_dp)
else:
data_dp = HttpReader([url]).load_from_xz()
units_dp = data_dp.readlines().map(partial(_process_tuple, language_code))
return units_dp
def download_head_10000():
for lang in VALID_CODES:
start_time = time.time()
f_out = open(f"{lang}.txt", "w", encoding="utf-8")
for i, x in enumerate(CC100(ROOT_DIR, lang, use_caching=False)):
if i >= 10000:
break
f_out.write(x[1] + "\n")
print(f"Execution time - {lang} - {(time.time() - start_time):.2f} secs")
f_out.close()
if __name__ == "__main__":
download_head_10000()