File size: 7,018 Bytes
c340c6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff54d11
 
 
c340c6d
 
 
 
 
 
 
 
 
 
 
 
14f512c
c340c6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14f512c
c340c6d
 
 
 
14f512c
c340c6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import json
import re
from typing import List

import datasets

logger = datasets.logging.get_logger(__name__)

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

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

        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.jsonl",
    "valid": _URL + "valid.jsonl",
    "test": _URL + "test.jsonl",
}




class ReDIAL(datasets.GeneratorBasedBuilder):
    DEFAULT_CONFIG_NAME = "rec"
    BUILDER_CONFIGS = [
        RedialConfig(
            name="SA",
            description="For using the ReDIAL dataset to train sentiment analysis on movies in sentences",
            features={
                "movieId": datasets.Value("int32"),
                "movieName": datasets.Value("string"),
                "messages": datasets.features.Sequence(datasets.Value("string")),
                "senders": datasets.features.Sequence(datasets.Value("int32")),
                "form": datasets.features.Sequence(
                    datasets.Value("int32"), length=6
                )
            },
        ),
        RedialConfig(
            name="autorec",
            description="For training autorec model on ReDIAL data",
            features=datasets.Features({
                "movieIds": datasets.Sequence(datasets.Value("int32")),
                "ratings": datasets.Sequence(datasets.Value("float"))
            }),
        ),
        RedialConfig(
            name="rec",
            description="For using the ReDIAL dataset to train recommender",
            features={
                "movieIds": datasets.Sequence(datasets.Value("int32")),
                "messages": datasets.features.Sequence(datasets.Value("string")),
                "senders": datasets.features.Sequence(datasets.Value("int32")),
            },
        ),

    ]

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.last_sender = None


    def _processMessage(self, msg, initialId):
        """
        msg example:     {
          "timeOffset": 0,
          "text": "Hi I am looking for a movie like @111776",
          "senderWorkerId": 956,
          "messageId": 204171
        },
        """
        res =  {
            "text": msg["text"],
            "sender": 1 if msg["senderWorkerId"] == initialId else -1
        }
        return res

    def _flattenMessages(self, conversation):
        messages = []
        senders = []
        for message in conversation["messages"]:
            role = 1 if message["senderWorkerId"] == conversation["initiatorWorkerId"] else -1
            text = message["text"]
            if len(senders) > 0 and senders[-1] == role:
                messages[-1] += "\n" + text
            else:
                senders.append(role)
                messages.append(text)
        return messages, senders

    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)
        return [
            datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={"filepath": downloaded_files["train"]}),
            datasets.SplitGenerator(name=datasets.Split.VALIDATION, gen_kwargs={"filepath": downloaded_files["valid"]}),
            datasets.SplitGenerator(name=datasets.Split.TEST, gen_kwargs={"filepath": downloaded_files["test"]}),
        ]

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

        if self.config.name == "autorec":
            with open(filepath, encoding="utf-8") as f:
                idx = 0
                for line in f:
                    conversation = json.loads(line)
                    movieIds = []
                    ratings = []
                    if len(conversation["initiatorQuestions"]) == 0:
                        continue
                    for id, form in conversation["initiatorQuestions"].items():
                        rating = int(form["liked"])
                        if rating < 2:
                            movieIds.append(id)
                            ratings.append(rating)
                    if len(movieIds) > 0:
                        yield idx, {
                            "movieIds": movieIds,
                            "ratings": ratings
                        }
                        idx += 1

        elif "SA" in self.config.name:
            Idx = 0
            date_pattern = re.compile(r'\(\d{4}\)') # To match e.g. "(2009)"
            with open(filepath, encoding="utf-8") as f:
                for line in f:
                    conversation = json.loads(line)
                    init_q = conversation["initiatorQuestions"]
                    resp_q = conversation["respondentQuestions"]
                    msgs, senders = self._flattenMessages(conversation)
                    # get movies that are in both forms.
                    gen = [key for key in init_q if key in resp_q]
                    for id in gen:
                        # remove date from movie name
                        movieName = date_pattern.sub('', conversation["movieMentions"][id]).strip(" ")
                        if len(movieName) == 0:
                            continue
                        yield Idx, {
                            "movieId": int(id),
                            "movieName": movieName,
                            "messages": msgs,
                            "senders": senders,
                            "form": [init_q[id]["suggested"], init_q[id]["seen"], init_q[id]["liked"],
                                     resp_q[id]["suggested"], resp_q[id]["seen"], resp_q[id]["liked"], ]
                        }
                        Idx += 1
                    if Idx > 100 and "debug" in self.config.name:
                        break
        elif "rec" in self.config.name:
            Idx = 0
            with open(filepath, encoding="utf-8") as f:
                for line in f:
                    conversation = json.loads(line)
                    msgs, senders = self._flattenMessages(conversation)

                    yield Idx, {
                        "messages": msgs,
                        "senders": senders,
                        "movieIds": [int(movieId) for movieId in conversation["movieMentions"]]
                    }
                    Idx += 1