Datasets:

License:
File size: 13,981 Bytes
c53e100
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dee3130
c53e100
 
 
 
 
 
1ffc506
 
 
c53e100
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b9595f
 
c53e100
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dee3130
 
 
 
 
c53e100
 
 
6daa6a8
c53e100
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dee3130
 
 
c53e100
 
dee3130
 
 
c53e100
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dee3130
 
 
c53e100
 
 
 
e38e23b
c53e100
 
dee3130
 
 
c53e100
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dee3130
c53e100
 
 
 
 
dee3130
c53e100
 
 
 
dee3130
6daa6a8
dee3130
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c53e100
 
 
 
 
 
 
 
dee3130
 
 
 
 
 
 
 
 
 
 
 
c53e100
 
 
 
 
 
 
dee3130
 
 
 
 
 
 
c53e100
 
 
dee3130
 
 
c53e100
 
dee3130
 
 
c53e100
 
 
dee3130
 
 
 
 
 
 
c53e100
 
 
 
 
 
dee3130
 
 
 
 
 
 
 
 
c53e100
 
 
dee3130
 
 
 
 
c53e100
 
 
 
 
 
 
 
 
 
 
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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
# coding=utf-8
# Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor.
#
# 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.
"""TED TALKS IWSLT: Web Inventory of Transcribed and Translated Ted Talks in 109 languages."""


import io
import xml.etree.ElementTree as ET
import zipfile
from collections import defaultdict

import datasets

logger = datasets.logging.get_logger(__name__)


# TODO: Add BibTeX citation
# Find for instance the citation on arxiv or on the dataset repo/website
_CITATION = """\
@inproceedings{cettolo-etal-2012-wit3,
    title = "{WIT}3: Web Inventory of Transcribed and Translated Talks",
    author = "Cettolo, Mauro  and
      Girardi, Christian  and
      Federico, Marcello",
    booktitle = "Proceedings of the 16th Annual conference of the European Association for Machine Translation",
    month = may # " 28{--}30",
    year = "2012",
    address = "Trento, Italy",
    publisher = "European Association for Machine Translation",
    url = "https://www.aclweb.org/anthology/2012.eamt-1.60",
    pages = "261--268",
}
"""

# TODO: Add description of the dataset here
# You can copy an official description
_DESCRIPTION = """\
The core of WIT3 is the TED Talks corpus, that basically redistributes the original content published by the TED Conference website (http://www.ted.com). Since 2007,
the TED Conference, based in California, has been posting all video recordings of its talks together with subtitles in English
and their translations in more than 80 languages. Aside from its cultural and social relevance, this content, which is published under the Creative Commons BYNC-ND license, also represents a precious
language resource for the machine translation research community, thanks to its size, variety of topics, and covered languages.
This effort repurposes the original content in a way which is more convenient for machine translation researchers.
"""

# TODO: Add a link to an official homepage for the dataset here
_HOMEPAGE = "https://wit3.fbk.eu/"

# TODO: Add the licence for the dataset here if you can find it
_LICENSE = "CC-BY-NC-4.0"

# TODO: Add link to the official dataset URLs here
# The HuggingFace dataset library don't host the datasets but only point to the original files
# This can be an arbitrary nested dict/list of URLs (see below in `_split_generators` method)
_URL = "data/XML_releases.tgz"


_LANGUAGES = (
    "mr",
    "eu",
    "hr",
    "rup",
    "szl",
    "lo",
    "ms",
    "ht",
    "hy",
    "mg",
    "arq",
    "uk",
    "ku",
    "ig",
    "sr",
    "ug",
    "ne",
    "pt-br",
    "sq",
    "af",
    "km",
    "en",
    "tt",
    "ja",
    "inh",
    "mn",
    "eo",
    "ka",
    "nb",
    "fil",
    "uz",
    "fi",
    "tl",
    "el",
    "tg",
    "bn",
    "si",
    "gu",
    "sk",
    "kn",
    "ar",
    "hup",
    "zh-tw",
    "sl",
    "be",
    "bo",
    "fr",
    "ps",
    "tr",
    "ltg",
    "la",
    "ko",
    "lv",
    "nl",
    "fa",
    "ru",
    "et",
    "vi",
    "pa",
    "my",
    "sw",
    "az",
    "sv",
    "ga",
    "sh",
    "it",
    "da",
    "lt",
    "kk",
    "mk",
    "tlh",
    "he",
    "ceb",
    "bg",
    "fr-ca",
    "ha",
    "ml",
    "mt",
    "as",
    "pt",
    "zh-cn",
    "cnh",
    "ro",
    "hi",
    "es",
    "id",
    "bs",
    "so",
    "cs",
    "te",
    "ky",
    "hu",
    "th",
    "pl",
    "nn",
    "ca",
    "is",
    "ta",
    "de",
    "srp",
    "ast",
    "bi",
    "lb",
    "art-x-bork",
    "am",
    "oc",
    "zh",
    "ur",
    "gl",
)

# Please note that only few pairs are shown here. You can use config to generate data for all language pairs
_LANGUAGE_PAIRS = [
    ("eu", "ca"),
    ("nl", "en"),
    ("nl", "hi"),
    ("de", "ja"),
    ("fr-ca", "hi"),
]

# Year subscripts for the specific folder
_YEAR = {"2014": "-20140120", "2015": "-20150530", "2016": "-20160408"}

_YEAR_FOLDER = {
    "2014": "XML_releases/xml-20140120",
    "2015": "XML_releases/xml-20150616",
    "2016": "XML_releases/xml",
}


class TedTalksIWSLTConfig(datasets.BuilderConfig):
    """ "Builder Config for the TedTalks IWSLT dataset"""

    def __init__(self, language_pair=(None, None), year=None, **kwargs):
        """BuilderConfig for TedTalks IWSLT dataset.
        Args:
            for the `datasets.features.text.TextEncoder` used for the features feature.
            language_pair: pair of languages that will be used for translation. Should
            contain 2-letter coded strings. First will be used at source and second
            as target in supervised mode. For example: ("pl", "en").
          **kwargs: keyword arguments forwarded to super.
        """
        # Validate language pair.
        name = "%s_%s_%s" % (language_pair[0], language_pair[1], year)
        source, target = language_pair
        assert source in _LANGUAGES, f"Invalid source code in language pair: {source}"
        assert target in _LANGUAGES, f"Invalid target code in language pair: {target}"
        assert (
            source != target
        ), f"Source::{source} and Target::{target} language pairs cannot be the same!"
        assert year in _YEAR.keys()

        description = (
            f"Translation Ted Talks dataset (WIT3) between {source} and {target}"
        )
        super(TedTalksIWSLTConfig, self).__init__(
            name=name,
            description=description,
            **kwargs,
        )

        self.language_pair = language_pair
        self.year = year


# TODO: Name of the dataset usually match the script name with CamelCase instead of snake_case
class TedTalksIWSLT(datasets.GeneratorBasedBuilder):
    """TED TALKS IWSLT: Web Inventory of Transcribed and Translated Ted Talks in 109 languages."""

    VERSION = datasets.Version("1.1.0")

    BUILDER_CONFIG_CLASS = TedTalksIWSLTConfig

    BUILDER_CONFIGS = [
        TedTalksIWSLTConfig(
            language_pair=language_pair, year=year, version=datasets.Version("1.1.0")
        )
        for language_pair in _LANGUAGE_PAIRS
        for year in _YEAR.keys()
    ]

    def _info(self):
        features = datasets.Features(
            {
                "translation": datasets.features.Translation(
                    languages=self.config.language_pair
                ),
            },
        )

        return datasets.DatasetInfo(
            # This is the description that will appear on the datasets page.
            description=_DESCRIPTION,
            # This defines the different columns of the dataset and their types
            features=features,  # Here we define them above because they are different between the two configurations
            # If there's a common (input, target) tuple from the features,
            # specify them here. They'll be used if as_supervised=True in
            # builder.as_dataset.
            supervised_keys=None,
            # Homepage of the dataset for documentation
            homepage=_HOMEPAGE,
            # License for the dataset if available
            license=_LICENSE,
            # Citation for the dataset
            citation=_CITATION,
        )

    def _split_generators(self, dl_manager):
        """Returns SplitGenerators."""
        data_dir = dl_manager.download(_URL)

        return [
            datasets.SplitGenerator(
                name=datasets.Split.TRAIN,
                gen_kwargs={
                    "files": dl_manager.iter_archive(data_dir),
                },
            ),
        ]

    def _generate_examples(self, files):
        """Yields examples."""

        def parse_zip_file(path, file):
            def et_to_dict(tree):
                """This is used to convert the xml to a list of dicts"""

                dct = {tree.tag: {} if tree.attrib else None}
                children = list(tree)
                if children:
                    dd = defaultdict(list)
                    for dc in map(et_to_dict, children):
                        for k, v in dc.items():
                            dd[k].append(v)
                    dct = {tree.tag: dd}
                if tree.attrib:
                    dct[tree.tag].update((k, v) for k, v in tree.attrib.items())
                if tree.text:
                    text = tree.text.strip()
                    if children or tree.attrib:
                        if text:
                            dct[tree.tag]["text"] = text
                    else:
                        dct[tree.tag] = text
                return dct

            with zipfile.ZipFile(io.BytesIO(file)) as zf:
                try:
                    tree = ET.parse(zf.open(path.split("/")[-1][:-3] + "xml"))
                    root = tree.getroot()
                    talks = et_to_dict(root).get("xml").get("file")
                    ids = [talk.get("head")[0].get("talkid") for talk in talks]
                except Exception as pe:
                    logger.warning(f"ERROR: {pe}")
                    logger.warning(
                        "This likely means that you have a malformed XML file!"
                    )
                    ids = []
            return talks, ids

        language_pair = self.config.language_pair
        year = self.config.year

        source_file_path = (
            _YEAR_FOLDER[year] + "/ted_" + language_pair[0] + _YEAR[year] + ".zip"
        )
        target_file_path = (
            _YEAR_FOLDER[year] + "/ted_" + language_pair[1] + _YEAR[year] + ".zip"
        )

        source_talks, source_ids = None, None
        target_talks, target_ids = None, None
        for path, file in files:
            if source_ids is not None and target_ids is not None:
                break

            if source_ids is None and path.endswith(source_file_path):
                source_talks, source_ids = parse_zip_file(path, file.read())
            elif target_ids is None and path.endswith(target_file_path):
                target_talks, target_ids = parse_zip_file(path, file.read())

        if source_ids is None or target_ids is None:
            source_ids = list()
            target_ids = list()

        comm_talkids = [talkid for talkid in target_ids if talkid in source_ids]

        translation = list()

        for talkid in comm_talkids:
            source = list(
                filter(
                    lambda talk: talk.get("head")[0].get("talkid") == talkid,
                    source_talks,
                )
            )
            target = list(
                filter(
                    lambda talk: talk.get("head")[0].get("talkid") == talkid,
                    target_talks,
                )
            )

            if len(source) == 0 or len(target) == 0:
                pass
            else:
                source = source[0]
                target = target[0]

            if source.get("head")[0].get("description") and target.get("head")[0].get(
                "description"
            ):
                if (
                    source.get("head")[0].get("description")[0]
                    and target.get("head")[0].get("description")[0]
                ):
                    temp_dict = dict()
                    temp_dict["id"] = source.get("head")[0].get("talkid")[0] + "_1"
                    temp_dict[language_pair[0]] = (
                        source.get("head")[0]
                        .get("description")[0]
                        .replace("TED Talk Subtitles and Transcript: ", "")
                    )
                    temp_dict[language_pair[1]] = (
                        target.get("head")[0]
                        .get("description")[0]
                        .replace("TED Talk Subtitles and Transcript: ", "")
                    )
                    translation.append(temp_dict)

            if source.get("head")[0].get("title") and target.get("head")[0].get(
                "title"
            ):
                if (
                    source.get("head")[0].get("title")[0]
                    and target.get("head")[0].get("title")[0]
                ):
                    temp_dict = dict()
                    temp_dict["id"] = source.get("head")[0].get("talkid")[0] + "_2"
                    temp_dict[language_pair[0]] = source.get("head")[0].get("title")[0]
                    temp_dict[language_pair[1]] = target.get("head")[0].get("title")[0]
                    translation.append(temp_dict)

            if source.get("head")[0].get("seekvideo") and target.get("head")[0].get(
                "seekvideo"
            ):
                source_transc = (
                    source.get("head")[0].get("transcription")[0].get("seekvideo")
                )
                target_transc = (
                    target.get("head")[0].get("transcription")[0].get("seekvideo")
                )

                transc = zip(source_transc, target_transc)
                transcriptions = [
                    {
                        "id": s.get("id"),
                        language_pair[0]: s.get("text"),
                        language_pair[1]: t.get("text"),
                    }
                    for s, t in transc
                ]
                translation.extend(transcriptions)
        for talk_segment in translation:
            result = {
                "translation": {
                    language_pair[0]: talk_segment[language_pair[0]],
                    language_pair[1]: talk_segment[language_pair[1]],
                }
            }
            yield talk_segment["id"], result