File size: 3,532 Bytes
3ffddfd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cb1a1bb
3ffddfd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cb1a1bb
3ffddfd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
# 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