File size: 6,576 Bytes
cb132d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
# 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.
"""
This file provides a HuggingFace dataset loader implementation for
the ParaDocs dataset
ParaDocs is a multilingual machine translation dataset that has
labelled document annotations for ParaCrawl, NewsCommentary, and
Europarl data which can be used to create parallel document 
datasets for training of context-aware machine translation models.
"""

# https://huggingface.co/docs/datasets/dataset_script

import csv
import json
import os
import re
import pathlib
from pathlib import Path
import yaml
from ast import literal_eval

import datasets

import gzip
try:
    import lzma as xz
except ImportError:
    import pylzma as xz


# TODO: Add BibTeX citation
# Find for instance the citation on arxiv or on the dataset repo/website
_CITATION = """\
"""

# TODO: Add description of the dataset here
# You can copy an official description
_DESCRIPTION = """\
ParaDocs is a multilingual machine translation dataset that has
labelled document annotations for ParaCrawl, NewsCommentary, and
Europarl data which can be used to create parallel document 
datasets for training of context-aware machine translation models.
"""

_HOMEPAGE = "https://huggingface.co/datasets/rewicks/paradocs"

_LICENSE = "cc-by-sa-4.0"

_URL = "https://huggingface.co/datasets/rewicks/paradocs"

# Load the file paths for all the splits (per language currently)

file_list_url = "https://huggingface.co/datasets/rewicks/paradocs/raw/main/files.yml"
import urllib.request
with urllib.request.urlopen(file_list_url) as f:
    try:
        fnames = yaml.safe_load(f)
    except yaml.YAMLError as exc:
        print("Error loading the file paths for the dataset splits. Aborting.")
        exit(1)

_DATA_URL = fnames['fnames']

_VARIANTS = list(_DATA_URL.keys())


class ParaDocs(datasets.GeneratorBasedBuilder):
    BUILDER_CONFIGS = [datasets.BuilderConfig(name) for name in _VARIANTS]

    def _info(self):
        return datasets.DatasetInfo(
            description=_DESCRIPTION,
            features=datasets.Features(
                {
                    "src": datasets.Value("string"),
                    "tgt": datasets.Value("string"),
                    "sim_score_one" : datasets.Value("float32"),
                    "sim_score_two": datasets.Value("float32"),
                    "collection": datasets.Value("string"),
                    "src_paragraph_id": datasets.Value("string"),
                    "tgt_paragraph_id": datasets.Value("string"),
                    "src_sentence_id": datasets.Value("string"),
                    "tgt_sentence_id": datasets.Value("string"),
                    "src_start_id": datasets.Value("string"),
                    "src_end_id": datasets.Value("string"),
                    "tgt_start_id": datasets.Value("string"),
                    "tgt_end_id": datasets.Value("string"),
                    "src_lid_prob": datasets.Value("float32"),
                    "tgt_lid_prob": datasets.Value("float32"),
                    "src_docid": datasets.Value("string"),
                    "tgt_docid": datasets.Value("string")
                }
            ),
            supervised_keys=None,
            homepage=_URL,
            citation=_CITATION,
        )

    def _split_generators(self, dl_manager):
        data_sources = {self.config.name: _DATA_URL[self.config.name]}

        return [
            datasets.SplitGenerator(
                name=lang,
                gen_kwargs={
                    "filepaths": dl_manager.download(data_sources[lang])
                }
            )
            for lang
            in data_sources
        ]

    def _get_qa_pair_list_features(self, qa_pair, feature_name):
        res = []

        if feature_name in qa_pair:
            if qa_pair[feature_name]:
                return qa_pair[feature_name]  
        else:
            if feature_name.startswith('en'):
                feature_name = '_'.join(feature_name.split('_')[1:])
                return self._get_qa_pair_list_features(qa_pair, feature_name)

        return res
    
    def _generate_examples(self, filepaths):
        """This function returns the examples in the raw (text) form by iterating on all the files."""
        id_ = 0
        for filepath in filepaths:
            # logger.info("Generating examples from = %s", filepath)
            try:
                with open(filepath, "r", encoding="utf-8") as f:
                    rstream = csv.DictReader(f,
                                                delimiter='\t',
                                                fieldnames = [
                                                    "src",
                                                    "tgt",
                                                    "sim_score_one",
                                                    "sim_score_two",
                                                    "collection",
                                                    "src_paragraph_id",
                                                    "tgt_paragraph_id",
                                                    "src_sentence_id",
                                                    "tgt_sentence_id",
                                                    "src_start_id",
                                                    "src_end_id",
                                                    "tgt_start_id",
                                                    "tgt_end_id",
                                                    "src_lid_prob",
                                                    "tgt_lid_prob",
                                                    "src_docid",
                                                    "tgt_docid"
                                                ],
                                                quoting=csv.QUOTE_NONE
                    )
                    for example in rstream:
                        yield id_, example
                        id_ += 1
            except:
                print("Error reading file:", filepath)