File size: 8,686 Bytes
a5937e9 d12b04f 3076328 d12b04f 8b1ffd9 d12b04f 8b1ffd9 d12b04f 8b1ffd9 d12b04f 8b1ffd9 d12b04f a5937e9 a4a1947 a5937e9 8b1ffd9 a5937e9 3076328 |
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 |
import glob
import json
import os
import zipfile
from typing import List
import datasets
import pandas as pd
from datasets import ClassLabel, Value, load_dataset
_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="multilingual",
label_classes=_CLASS_NAMES,
features=["text", "label", "dataset", "license"]
)
]
DEFAULT_CONFIG_NAME = "all"
def _info(self):
if self.config.name == "all":
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)
}
)
)
else:
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:
downloaded_files = dl_manager.download_and_extract(["data/many_emotions.tar.xz"])
for lang in ["en", "fr", "it", "es", "de"]:
splits.append(datasets.SplitGenerator(name=lang,
gen_kwargs={"filepaths": downloaded_files,
"language": lang,
"dataset": "many_emotions"}))
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=None, language=None):
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
elif dataset == "many_emotions":
for _, folder in enumerate(filepaths):
for filepath in glob.glob(f"{folder}/*"):
with open(filepath, encoding="utf-8") as f:
for idx, line in enumerate(f):
example = json.loads(line)
if language != "all":
example = {
"id": example["id"],
'text': example["text" if language == "en" else language],
'label': example["label"],
'dataset': example["dataset"],
'license': example["license"]
}
example.update({
"label": _CLASS_NAMES[example["label"]]
})
yield example["id"], example
if __name__ == "__main__":
dataset = load_dataset("ma2za/many_emotions", name="all", split="emotion")
print()
|