File size: 6,238 Bytes
83dd897
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# Copyright 2023 The Inseq Team. All rights reserved.
#
# 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.
"""DiscEvalMT: Contrastive test sets for the evaluation of discourse in machine translation (v2)"""

from typing import Dict

import datasets
from datasets.utils.download_manager import DownloadManager

_CITATION = """\
@inproceedings{bawden-etal-2018-evaluating,
    title = "Evaluating Discourse Phenomena in Neural Machine Translation",
    author = "Bawden, Rachel and Sennrich, Rico and Birch, Alexandra and Haddow, Barry",
    booktitle = {{Proceedings of the 2018 Conference of the North {A}merican Chapter of the Association for Computational Linguistics: Human Language Technologies, Volume 1 (Long Papers)}},
    month = jun,
    year = "2018",
    address = "New Orleans, Louisiana",
    publisher = "Association for Computational Linguistics",
    url = "https://www.aclweb.org/anthology/N18-1118",
    doi = "10.18653/v1/N18-1118",
    pages = "1304--1313"
}
"""

_DESCRIPTION = """\
The test sets comprise hand-crafted examples that are inspired by similar examples in the parallel corpus OpenSubtitles2016 (in terms of vocabulary usage, style and syntactic formulation)
for the evaluation of discourse in English-to-French machine translation.
"""

_URL = "https://huggingface.co/datasets/inseq/disc_eval_mt/raw/main/examples"

_HOMEPAGE = "https://github.com/rbawden/discourse-mt-test-sets"

_LICENSE = "CC-BY-SA-4.0"

_CONFIGS = ["anaphora", "lexical-choice"]


class DiscEvalMTConfig(datasets.BuilderConfig):
    def __init__(self, source_language: str, target_language: str, **kwargs):
        """BuilderConfig for DiscEvalMT.
        Args:
            source_language: `str`, source language for translation.
            target_language: `str`, translation language.
            **kwargs: keyword arguments forwarded to super.
        """
        super().__init__(**kwargs)
        self.source_language = source_language
        self.target_language = target_language


class DiscEvalMT(datasets.GeneratorBasedBuilder):
    VERSION = datasets.Version("1.0.0")

    BUILDER_CONFIGS = [
        DiscEvalMTConfig(
            name=cfg,
            source_language="en",
            target_language="fr",
        )
        for cfg in _CONFIGS
    ]

    DEFAULT_CONFIG_NAME = "anaphora"

    def _info(self):
        features = datasets.Features(
            {
                "id": datasets.Value("int32"),
                "context_en": datasets.Value("string"),
                "en": datasets.Value("string"),
                "context_fr": datasets.Value("string"),
                "fr": datasets.Value("string"),
                "contrast_fr": datasets.Value("string"),
                "context_en_with_tags": datasets.Value("string"),
                "en_with_tags": datasets.Value("string"),
                "context_fr_with_tags": datasets.Value("string"),
                "fr_with_tags": datasets.Value("string"),
                "contrast_fr_with_tags": datasets.Value("string"),
                "type": datasets.Value("string"),
            }
        )
        return datasets.DatasetInfo(
            description=_DESCRIPTION,
            features=features,
            homepage=_HOMEPAGE,
            license=_LICENSE,
            citation=_CITATION,
        )

    @staticmethod
    def clean_string(txt: str):
        return txt.replace("<p>", "").replace("</p>", "").replace("<hon>", "").replace("<hoff>", "")

    def _split_generators(self, dl_manager: DownloadManager):
        """Returns SplitGenerators."""
        filepaths = {}
        for lang in ["en", "fr"]:
            for ftype in ["context", "current"]:
                fname = f"{self.config.name}.{ftype}.{lang}"
                filepaths[f"{ftype}_{lang}"] = dl_manager.download_and_extract(f"{_URL}/{fname}")
        filepaths["contrast_fr"] = dl_manager.download_and_extract(f"{_URL}/{self.config.name}.contrast.fr")
        filepaths["type"] = dl_manager.download_and_extract(f"{_URL}/{self.config.name}.type")
        return [
            datasets.SplitGenerator(
                name=datasets.Split.TEST,
                gen_kwargs={
                    "filepaths": filepaths,
                    "cfg_name": self.config.name,
                },
            )
        ]

    def _generate_examples(self, filepaths: Dict[str, str], cfg_name: str):
        """Yields examples as (key, example) tuples."""

        with open(filepaths["current_en"]) as f:
            current_en = f.read().splitlines()
        with open(filepaths["current_fr"]) as f:
            current_fr = f.read().splitlines()
        with open(filepaths["context_en"]) as f:
            context_en = f.read().splitlines()
        with open(filepaths["context_fr"]) as f:
            context_fr = f.read().splitlines()
        with open(filepaths["contrast_fr"]) as f:
            contrast_fr = f.read().splitlines()
        with open(filepaths["type"]) as f:
            alltyp = f.read().splitlines()
        for i, (curr_en, curr_fr, ctx_en, ctx_fr, con_fr, typ) in enumerate(
            zip(current_en, current_fr, context_en, context_fr, contrast_fr, alltyp)
        ):
            yield i, {
                "id": i,
                "context_en": self.clean_string(ctx_en),
                "en": self.clean_string(curr_en),
                "context_fr": self.clean_string(ctx_fr),
                "fr": self.clean_string(curr_fr),
                "contrast_fr": self.clean_string(con_fr),
                "context_en_with_tags": ctx_en,
                "en_with_tags": curr_en,
                "context_fr_with_tags": ctx_fr,
                "fr_with_tags": curr_fr,
                "contrast_fr_with_tags": con_fr,
                "type": typ,
            }