File size: 7,260 Bytes
f04268a
1baae2e
a4ee508
6344f8a
 
 
 
f04268a
6344f8a
ad76541
 
 
 
 
 
 
 
 
 
a4ee508
 
f04268a
 
 
 
a4ee508
ad76541
6344f8a
17c8294
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6344f8a
 
 
 
 
 
 
 
 
 
 
 
 
17c8294
62be3ab
ad76541
 
 
 
 
 
 
 
 
 
f04268a
 
 
 
 
6344f8a
 
 
 
 
 
 
 
 
 
 
62be3ab
 
 
6344f8a
 
 
 
 
62be3ab
ad76541
 
f04268a
ad76541
 
 
11bd71b
ad76541
 
 
f04268a
ad76541
a4ee508
ad76541
11bd71b
62be3ab
6344f8a
f04268a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62be3ab
a4ee508
 
 
 
 
 
 
 
 
 
 
 
 
 
30ca378
 
f04268a
c06e3bd
 
a4ee508
f04268a
 
 
 
30ca378
 
 
c06e3bd
 
30ca378
f04268a
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
import json
import os
import zipfile
from typing import List

import datasets
import pandas as pd
from datasets import ClassLabel, Value

_URLS = {
    "go_emotions": {
        "urls": [
            "https://storage.googleapis.com/gresearch/goemotions/data/full_dataset/goemotions_1.csv",
            "https://storage.googleapis.com/gresearch/goemotions/data/full_dataset/goemotions_2.csv",
            "https://storage.googleapis.com/gresearch/goemotions/data/full_dataset/goemotions_3.csv",
        ],
        "license": "apache license 2.0"
    },
    "daily_dialog": {
        "urls": ["http://yanran.li/files/ijcnlp_dailydialog.zip"],
        "license": "CC BY-NC-SA 4.0"
    },
    "emotion": {
        "data": ["data/data.jsonl.gz"],
        "license": "educational/research"
    }
}

_CLASS_NAMES = [
    "no emotion",
    "happiness",
    "admiration",
    "amusement",
    "anger",
    "annoyance",
    "approval",
    "caring",
    "confusion",
    "curiosity",
    "desire",
    "disappointment",
    "disapproval",
    "disgust",
    "embarrassment",
    "excitement",
    "fear",
    "gratitude",
    "grief",
    "joy",
    "love",
    "nervousness",
    "optimism",
    "pride",
    "realization",
    "relief",
    "remorse",
    "sadness",
    "surprise",
    "neutral",
]


class EmotionsDatasetConfig(datasets.BuilderConfig):

    def __init__(self, features, label_classes, **kwargs):
        super().__init__(**kwargs)
        self.features = features
        self.label_classes = label_classes


class EmotionsDataset(datasets.GeneratorBasedBuilder):
    BUILDER_CONFIGS = [
        EmotionsDatasetConfig(
            name="all",
            label_classes=_CLASS_NAMES,
            features=["text", "label", "dataset", "license"]
        ),
        EmotionsDatasetConfig(
            name="go_emotions",
            label_classes=_CLASS_NAMES,
            features=["text", "label", "dataset", "license"]
        ),
        EmotionsDatasetConfig(
            name="daily_dialog",
            label_classes=_CLASS_NAMES,
            features=["text", "label", "dataset", "license"]
        ),
        EmotionsDatasetConfig(
            name="emotion",
            label_classes=_CLASS_NAMES,
            features=["text", "label", "dataset", "license"]
        )
    ]

    DEFAULT_CONFIG_NAME = "all"

    def _info(self):
        return datasets.DatasetInfo(
            features=datasets.Features(
                {
                    "id": datasets.Value("string"),
                    'text': Value(dtype='string', id=None),
                    'label': ClassLabel(names=_CLASS_NAMES, id=None),
                    'dataset': Value(dtype='string', id=None),
                    'license': Value(dtype='string', id=None)
                }
            )
        )

    def _split_generators(self, dl_manager: datasets.DownloadManager) -> List[datasets.SplitGenerator]:
        splits = []
        if self.config.name == "all":
            for k, v in _URLS.items():
                downloaded_files = dl_manager.download_and_extract(v.get("urls", v.get("data")))
                splits.append(datasets.SplitGenerator(name=k,
                                                      gen_kwargs={"filepaths": downloaded_files,
                                                                  "dataset": k,
                                                                  "license": v.get("license")}))
        else:
            k = self.config.name
            v = _URLS.get(k)
            downloaded_files = dl_manager.download_and_extract(v.get("urls", v.get("data")))
            splits.append(datasets.SplitGenerator(name=k,
                                                  gen_kwargs={"filepaths": downloaded_files,
                                                              "dataset": k,
                                                              "license": v.get("license")}))
        return splits

    def process_daily_dialog(self, filepaths, dataset):
        # TODO move outside
        emo_mapping = {0: "no emotion", 1: "anger", 2: "disgust",
                       3: "fear", 4: "happiness", 5: "sadness", 6: "surprise"}
        for i, filepath in enumerate(filepaths):
            if os.path.isdir(filepath):
                emotions = open(os.path.join(filepath, "ijcnlp_dailydialog/dialogues_emotion.txt"), "r").read()
                text = open(os.path.join(filepath, "ijcnlp_dailydialog/dialogues_text.txt"), "r").read()
            else:
                # TODO check if this can be removed
                archive = zipfile.ZipFile(filepath, 'r')
                emotions = archive.open("ijcnlp_dailydialog/dialogues_emotion.txt", "r").read().decode()
                text = archive.open("ijcnlp_dailydialog/dialogues_text.txt", "r").read().decode()
            emotions = emotions.split("\n")
            text = text.split("\n")

            for idx_out, (e, t) in enumerate(zip(emotions, text)):
                if len(t.strip()) > 0:
                    cast_emotions = [int(j) for j in e.strip().split(" ")]
                    cast_dialog = [d.strip() for d in t.split("__eou__") if len(d)]
                    for idx_in, (ce, ct) in enumerate(zip(cast_emotions, cast_dialog)):
                        uid = f"daily_dialog_{i}_{idx_out}_{idx_in}"
                        yield uid, {"text": ct,
                                    "id": uid,
                                    "dataset": dataset,
                                    "license": license,
                                    "label": emo_mapping[ce]}

    def _generate_examples(self, filepaths, dataset, license):
        if dataset == "go_emotions":
            for i, filepath in enumerate(filepaths):
                df = pd.read_csv(filepath)
                current_classes = list(set(df.columns).intersection(set(_CLASS_NAMES)))
                df = df[["text"] + current_classes]
                df = df[df[current_classes].sum(axis=1) == 1].reset_index(drop=True)
                for row_idx, row in df.iterrows():
                    uid = f"go_emotions_{i}_{row_idx}"
                    yield uid, {"text": row["text"],
                                "id": uid,
                                "dataset": dataset,
                                "license": license,
                                "label": row[current_classes][row == 1].index.item()}
        elif dataset == "daily_dialog":
            for d in self.process_daily_dialog(filepaths, dataset):
                yield d
        elif dataset == "emotion":
            emo_mapping = {0: "sadness", 1: "joy", 2: "love",
                           3: "anger", 4: "fear", 5: "surprise"}
            for i, filepath in enumerate(filepaths):
                with open(filepath, encoding="utf-8") as f:
                    for idx, line in enumerate(f):
                        uid = f"{dataset}_{idx}"
                        example = json.loads(line)
                        example.update({
                            "id": uid,
                            "dataset": dataset,
                            "license": license,
                            "label": emo_mapping[example["label"]]
                        })
                        yield uid, example