|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
import json |
|
import os |
|
from typing import List |
|
import datasets |
|
import pandas as pd |
|
import opustools |
|
|
|
_DESCRIPTION = """\ |
|
Downloads OPUS data using `opustools`. |
|
""" |
|
|
|
_VERSION = "1.0.0" |
|
_URL = "https://opus.nlpl.eu/" |
|
|
|
class OpusConfig(datasets.BuilderConfig): |
|
"""BuilderConfig for Opus Dataset.""" |
|
|
|
def __init__(self, *args, src=None, tgt=None, corpus=None, download_dir="data", **kwargs): |
|
""" BuilderConfig for Opus Dataset. |
|
The following args follows `opustools`: https://pypi.org/project/opustools/ |
|
|
|
Args: |
|
src: str, source language |
|
tgt: str, target language |
|
corpus: str, corpus name. Leave as `None` to download all available corpus for the src-tgt pair. |
|
download_dir: str, dir to save downloaded files |
|
|
|
""" |
|
|
|
super(OpusConfig, self).__init__( |
|
*args, |
|
name=f"{src}-{tgt}", |
|
description=f"Translating {src} to {tgt} or vice versa", |
|
**kwargs) |
|
self.src = src |
|
self.tgt = tgt |
|
self.opus_get = opustools.OpusGet(source=src, target=tgt, list_resources=True, directory=corpus) |
|
self.download_dir = download_dir |
|
|
|
def get_corpora_data(self): |
|
""" Returns corpora, number of files, and total size. """ |
|
return self.opus_get.get_corpora_data() |
|
|
|
|
|
class Opus(datasets.GeneratorBasedBuilder): |
|
""" Opus dataset. |
|
See: https://huggingface.co/docs/datasets/dataset_script#create-a-dataset-loading-script""" |
|
|
|
BUILDER_CONFIG_CLASS = OpusConfig |
|
|
|
def _info(self): |
|
features = { |
|
"src": datasets.Value("string"), |
|
"tgt": datasets.Value("string"), |
|
} |
|
|
|
return datasets.DatasetInfo( |
|
description=_DESCRIPTION, |
|
features=datasets.Features(features), |
|
homepage=_URL, |
|
) |
|
|
|
def _split_generators(self, dl_manager: datasets.DownloadManager) -> List[datasets.SplitGenerator]: |
|
return [ |
|
datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={}), |
|
] |
|
|
|
def _generate_examples(self): |
|
|
|
id_ = 0 |
|
|
|
data = self.config.opus_get.get_corpora_data() |
|
self.config.opus_get.print_files(*data) |
|
|
|
for d in data[0]: |
|
opus_reader = opustools.OpusRead( |
|
directory=d["corpus"], |
|
source=self.config.src, |
|
target=self.config.tgt, |
|
write_mode="yield_tuple", |
|
leave_non_alignments_out=True, |
|
download_dir=self.config.download_dir, |
|
suppress_prompts=True, |
|
) |
|
gen = opus_reader.printPairs() |
|
for src, tgt in gen: |
|
yield id_, {"src": src, "tgt": tgt} |
|
id_ += 1 |
|
|