opus / opus.py
lannliat
Fix imports, filename, README.
cb1a1bb
raw
history blame
3.53 kB
# coding=utf-8
# Copyright 2020 The TensorFlow Datasets Authors and the HuggingFace Datasets 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,
# 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.
# Lint as: python3
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):
# read from specific corpus
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