File size: 9,230 Bytes
ffe643a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import json
import re
from typing import List, Dict
import html

import datasets
import pyarrow as pa

logger = datasets.logging.get_logger(__name__)


class RedialConfig(datasets.BuilderConfig):
    """BuilderConfig for ReDIAL."""

    def __init__(self, features, **kwargs):
        """BuilderConfig for ReDIAL (used in UniCRS).

        Args:
        features: *list[string]*, list of the features that will appear in the
            feature dict. Should not include "label".
        **kwargs: keyword arguments forwarded to super.
        """
        super().__init__(version=datasets.Version("0.0.1"), **kwargs)
        self.features = features


_URL = "./"
_URLS = {
    "train": _URL + "train_data_dbpedia.jsonl",
    "valid": _URL + "valid_data_dbpedia.jsonl",
    "test": _URL + "test_data_dbpedia.jsonl",
    "entity2id": _URL + "entity2id.json"
}


class ReDIAL(datasets.GeneratorBasedBuilder):
    DEFAULT_CONFIG_NAME = "multiturn"
    BUILDER_CONFIGS = [
        RedialConfig(
            name="multiturn",
            description="The processed ReDIAL dataset in UniCRS. Each conversation yields multiple samples",
            features={
                "context": datasets.Sequence(datasets.Value("string")),
                "resp": datasets.Value("string"),
                "rec": datasets.Sequence(datasets.Value("int32")),
                "entity": datasets.Sequence(datasets.Value("int32")),
            },
        ),
        RedialConfig(
            name="multiturn_masked",
            description="",
            features={
                "context": datasets.Sequence(datasets.Value("string")),
                "resp": datasets.Value("string"),
                "rec": datasets.Sequence(datasets.Value("int32")),
                "entity": datasets.Sequence(datasets.Value("int32")),
            },
        ),
        RedialConfig(
            name="compact",
            description="Each conversation is one sample",
            features={
                "movieIds": datasets.Sequence(datasets.Value("string")),
                "movieNames": datasets.Sequence(datasets.Value("string")),
                "initiatorWorkerId": datasets.Value("int32"),
                "messages": datasets.Sequence(datasets.Value("string")),
                "senders": datasets.Sequence(datasets.Value("int32")),
                "entities": datasets.Sequence(datasets.Sequence(datasets.Value("string"))),
                "movies": datasets.Sequence(datasets.Sequence(datasets.Value("string")))
            },
        ),
    ]
    movie_pattern = re.compile(r'@\d+')

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

    def _info(self):
        return datasets.DatasetInfo(
            description=self.config.description,
            features=datasets.Features(self.config.features),
        )

    def _split_generators(self, dl_manager: datasets.DownloadManager) -> List[datasets.SplitGenerator]:
        urls_to_download = _URLS
        downloaded_files = dl_manager.download_and_extract(urls_to_download)
        entity2id_file = downloaded_files["entity2id"]
        return [
            datasets.SplitGenerator(name=datasets.Split.TRAIN,
                                    gen_kwargs={"filepath": downloaded_files["train"], "entity2id": entity2id_file}),
            datasets.SplitGenerator(name=datasets.Split.VALIDATION,
                                    gen_kwargs={"filepath": downloaded_files["valid"], "entity2id": entity2id_file}),
            datasets.SplitGenerator(name=datasets.Split.TEST,
                                    gen_kwargs={"filepath": downloaded_files["test"], "entity2id": entity2id_file}),
        ]

    def _process_utt(self, utt, movieid2name, replace_movieId, remove_movie=False):
        def convert(match):
            movieid = match.group(0)[1:]
            if movieid in movieid2name:
                if remove_movie:
                    return '<movie>'
                movie_name = movieid2name[movieid]
                movie_name = ' '.join(movie_name.split())
                return movie_name
            else:
                return match.group(0)

        if replace_movieId:
            utt = re.sub(self.movie_pattern, convert, utt)
        utt = ' '.join(utt.split())
        utt = html.unescape(utt)

        return utt

    def _generate_examples(self, filepath, entity2id):
        """This function returns the examples in the raw (text) form."""
        logger.info("generating examples from = %s", filepath)

        with open(entity2id, 'r', encoding='utf-8') as f:
            entity2id = json.load(f)
        if "multiturn" in self.config.name:
            mask_flag = "mask" in self.config.name
            Idx = 0
            with open(filepath, encoding="utf-8") as f:
                for line in f:
                    dialog = json.loads(line)
                    if len(dialog['messages']) == 0:
                        continue

                    movieid2name = dialog['movieMentions']
                    user_id, resp_id = dialog['initiatorWorkerId'], dialog['respondentWorkerId']
                    context, resp = [], ''
                    entity_list = []
                    messages = dialog['messages']
                    turn_i = 0
                    while turn_i < len(messages):
                        worker_id = messages[turn_i]['senderWorkerId']
                        utt_turn = []
                        entity_turn = []
                        movie_turn = []
                        mask_utt_turn = []

                        turn_j = turn_i
                        while turn_j < len(messages) and messages[turn_j]['senderWorkerId'] == worker_id:
                            utt = self._process_utt(messages[turn_j]['text'], movieid2name, replace_movieId=True)
                            utt_turn.append(utt)

                            if mask_flag:
                                mask_utt = self._process_utt(messages[turn_j]['text'], movieid2name,
                                                             replace_movieId=True,
                                                             remove_movie=True)
                                mask_utt_turn.append(mask_utt)

                            entity_ids = [entity2id[entity] for entity in messages[turn_j]['entity'] if
                                          entity in entity2id]
                            entity_turn.extend(entity_ids)

                            movie_ids = [entity2id[movie] for movie in messages[turn_j]['movie'] if movie in entity2id]
                            movie_turn.extend(movie_ids)

                            turn_j += 1

                        utt = ' '.join(utt_turn)
                        mask_utt = ' '.join(mask_utt_turn)

                        if mask_flag and worker_id == user_id:
                            context.append(utt)
                            entity_list.append(entity_turn + movie_turn)
                        else:
                            resp = utt

                            context_entity_list = [entity for entity_l in entity_list for entity in entity_l]
                            context_entity_list_extend = []

                            context_entity_list_extend += context_entity_list
                            context_entity_list_extend = list(set(context_entity_list_extend))

                            if len(context) == 0:
                                context.append('')
                            yield Idx, {
                                'context': context,
                                'resp': mask_utt if mask_flag else resp,
                                'rec': movie_turn if mask_flag else list(set(movie_turn + entity_turn)),
                                'entity': context_entity_list_extend,
                            }
                            Idx += 1

                            context.append(resp)
                            entity_list.append(movie_turn + entity_turn)

                        turn_i = turn_j
        elif self.config.name == "compact":
            Idx = 0
            with open(filepath, encoding="utf-8") as f:
                for line in f:
                    dialog = json.loads(line)
                    if len(dialog['messages']) == 0:
                        continue
                    messages = dialog['messages']

                    movieIds = [movieId for movieId in dialog["movieMentions"]]
                    yield Idx, {
                        "movieIds": movieIds,
                        "movieNames": [dialog["movieMentions"][id] for id in movieIds],
                        "initiatorWorkerId": dialog["initiatorWorkerId"],
                        "messages": [turn['text'] for turn in messages],
                        "senders": [turn["senderWorkerId"] for turn in messages],
                        "entities": [[entity2id[entity] for entity in turn['entity'] if entity in entity2id] for turn in
                                     messages],
                        "movies": [[entity2id[entity] for entity in turn['movie'] if entity in entity2id] for turn in
                                   messages]
                    }

                    Idx += 1