File size: 5,306 Bytes
a687d50
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# coding=utf-8
# 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.
"""SCAT: Supporting Context for Ambiguous Translations"""

import re
from pathlib import Path
from typing import Dict

import datasets
from datasets.utils.download_manager import DownloadManager


_CITATION = """\
@inproceedings{yin-etal-2021-context,
    title = "Do Context-Aware Translation Models Pay the Right Attention?",
    author = "Yin, Kayo  and
      Fernandes, Patrick  and
      Pruthi, Danish  and
      Chaudhary, Aditi  and
      Martins, Andr{\'e} F. T.  and
      Neubig, Graham",
    booktitle = "Proceedings of the 59th Annual Meeting of the Association for Computational Linguistics and the 11th International Joint Conference on Natural Language Processing (Volume 1: Long Papers)",
    month = aug,
    year = "2021",
    address = "Online",
    publisher = "Association for Computational Linguistics",
    url = "https://aclanthology.org/2021.acl-long.65",
    doi = "10.18653/v1/2021.acl-long.65",
    pages = "788--801",
}
"""

_DESCRIPTION = """\
The Supporting Context for Ambiguous Translations corpus (SCAT) is a dataset 
of English-to-French translations annotated with human rationales used for resolving ambiguity 
in pronoun anaphora resolution for multi-sentence translation.
"""

_URL = "https://huggingface.co/datasets/inseq/scat/resolve/main/filtered_scat"

_HOMEPAGE = "https://github.com/neulab/contextual-mt/tree/master/data/scat"

_LICENSE = "Unknown"

class ScatConfig(datasets.BuilderConfig):
    def __init__(
        self,
        source_language: str, 
        target_language: str,
        **kwargs
    ):
        """BuilderConfig for MT-GenEval.
        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 WmtVat(datasets.GeneratorBasedBuilder):

    VERSION = datasets.Version("1.0.0")

    BUILDER_CONFIGS = [ScatConfig(name="sentences", source_language="en", target_language="fr")]

    DEFAULT_CONFIG_NAME = "sentences"

    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"),
                "has_supporting_context": datasets.Value("bool"),
            }
        )
        return datasets.DatasetInfo(
            description=_DESCRIPTION,
            features=features,
            homepage=_HOMEPAGE,
            license=_LICENSE,
            citation=_CITATION,
        )

    def _split_generators(self, dl_manager: DownloadManager):
        """Returns SplitGenerators."""
        base_path = Path(_URL)
        filepaths = {}
        splits = ["train", "valid", "test"]
        for split in splits:
            filepaths[split] = {}
            for lang in ["en", "fr"]:
                for ftype in ["context", ""]:
                    fname = f"filtered.{split}{'.' + ftype if ftype else ''}.{lang}"
                    name = f"{ftype}_{lang}" if ftype else lang
                    filepaths[split][name] = dl_manager.download_and_extract(base_path / fname)
        return [
            datasets.SplitGenerator(
                name=split_name,
                gen_kwargs={
                    "filepaths": filepaths[split],
                },
            )
            for split, split_name in zip(splits, ["train", "validation", "test"])
        ]


    def _generate_examples(
        self, filepaths: Dict[str, str]
    ):
        """ Yields examples as (key, example) tuples. """
        with open(filepaths["en"]) as f:
            en = f.read().splitlines()
        with open(filepaths["fr"]) as f:
            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()
        for i, (e, f, ce, cf) in enumerate(zip(en, fr, context_en, context_fr)):
            allfields = " ".join([e, f, ce, cf])
            has_supporting_context = False
            if "<hon>" in allfields and "<hoff>" in allfields:
                has_supporting_context = True
            yield i, {
                "id": i,
                "context_en": ce,
                "en": e,
                "context_fr": cf,
                "fr": f,
                "has_supporting_context": has_supporting_context,
            }