File size: 7,440 Bytes
5657d2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# coding=utf-8
# Copyright 2020 The TensorFlow Datasets Authors and the HuggingFace Datasets Authors.
#
# 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.

# Lint as: python3
"""Crowdflower datasets"""

from __future__ import absolute_import, division, print_function

import csv
import os
import textwrap

import six

import datasets


_crowdflower_CITATION = r"""
@inproceedings{van2012designing,
  title={Designing a scalable crowdsourcing platform},
  author={Van Pelt, Chris and Sorokin, Alex},
  booktitle={Proceedings of the 2012 ACM SIGMOD International Conference on Management of Data},
  pages={765--766},
  year={2012}
}
"""

_crowdflower_DESCRIPTION = """
Collection of crowdflower classification datasets
"""

DATA_URL = "https://www.dropbox.com/s/ldrcdsv8d9qiwg0/crowdflower.zip?dl=1"

TASK_TO_LABELS = {'airline-sentiment': ['neutral', 'positive', 'negative'],
 'corporate-messaging': ['Information', 'Action', 'Exclude', 'Dialogue'],
 'economic-news': ['not sure', 'yes', 'no'],
 'political-media-audience': ['constituency', 'national'],
 'political-media-bias': ['partisan', 'neutral'],
 'political-media-message': ['information',
  'support',
  'policy',
  'constituency',
  'personal',
  'other',
  'media',
  'mobilization',
  'attack'],
 'sentiment_nuclear_power': ['Neutral / author is just sharing information',
  'Negative',
  'Tweet NOT related to nuclear energy',
  'Positive'],
 'text_emotion': ['sadness',
  'empty',
  'relief',
  'hate',
  'worry',
  'enthusiasm',
  'happiness',
  'neutral',
  'love',
  'fun',
  'anger',
  'surprise',
  'boredom'],
 'tweet_global_warming': ['Yes', 'No']}

def get_labels(task):
    return TASK_TO_LABELS[task]

class crowdflowerConfig(datasets.BuilderConfig):
    """BuilderConfig for crowdflower."""

    def __init__(
        self,
        text_features,
        label_classes=None,
        process_label=lambda x: x,
        **kwargs,
    ):
        """BuilderConfig for crowdflower.
        Args:
          text_features: `dict[string, string]`, map from the name of the feature
            dict for each text field to the name of the column in the tsv file
          label_column: `string`, name of the column in the tsv file corresponding
            to the label
          data_url: `string`, url to download the zip file from
          data_dir: `string`, the path to the folder containing the tsv files in the
            downloaded zip
          citation: `string`, citation for the data set
          url: `string`, url for information about the data set
          label_classes: `list[string]`, the list of classes if the label is
            categorical. If not provided, then the label will be of type
            `datasets.Value('float32')`.
          process_label: `Function[string, any]`, function  taking in the raw value
            of the label and processing it to the form required by the label feature
          **kwargs: keyword arguments forwarded to super.
        """

        super(crowdflowerConfig, self).__init__(version=datasets.Version("1.0.0", ""), **kwargs)

        self.text_features = text_features
        self.label_column = "label"
        self.label_classes = get_labels(self.name)
        self.data_url = DATA_URL
        self.data_dir = os.path.join("crowdflower", self.name)
        self.citation = textwrap.dedent(_crowdflower_CITATION)
        def process_label(x):
            x=str(x)
            if x=="Y":
                return "Yes"
            if x=="N":
                return "No"
            return x
        self.process_label = process_label
        self.description = ""
        self.url = ""


class crowdflower(datasets.GeneratorBasedBuilder):

    """The General Language Understanding Evaluation (crowdflower) benchmark."""

    BUILDER_CONFIG_CLASS = crowdflowerConfig

    BUILDER_CONFIGS = [
    crowdflowerConfig(name="sentiment_nuclear_power",
                        text_features={"text": "text"},),
    crowdflowerConfig(name="tweet_global_warming",
                        text_features={"text": "text"},),
    crowdflowerConfig(name="airline-sentiment",
                        text_features={"text": "text"},),
    crowdflowerConfig(name="corporate-messaging",
                        text_features={"text": "text"},),
    crowdflowerConfig(name="economic-news",
                        text_features={"text": "text"},),
    crowdflowerConfig(name="political-media-audience",
                        text_features={"text": "text"},),
    crowdflowerConfig(name="political-media-bias",
                        text_features={"text": "text"},),
    crowdflowerConfig(name="political-media-message",
                        text_features={"text": "text"},),
    crowdflowerConfig(name="text_emotion",
                        text_features={"text": "text"},),
    ]

    def _info(self):
        features = {text_feature: datasets.Value("string") for text_feature in six.iterkeys(self.config.text_features)}
        if self.config.label_classes:
            features["label"] = datasets.features.ClassLabel(names=self.config.label_classes)
        else:
            features["label"] = datasets.Value("float32")
        features["idx"] = datasets.Value("int32")
        return datasets.DatasetInfo(
            description=_crowdflower_DESCRIPTION,
            features=datasets.Features(features),
            homepage=self.config.url,
            citation=self.config.citation + "\n" + _crowdflower_CITATION,
        )

    def _split_generators(self, dl_manager):
        dl_dir = dl_manager.download_and_extract(self.config.data_url)
        data_dir = os.path.join(dl_dir, self.config.data_dir)

        return [
            datasets.SplitGenerator(
                name=datasets.Split.TRAIN,
                gen_kwargs={
                    "data_file": os.path.join(data_dir or "", "train.tsv"),
                    "split": "train",
                },
            ),
        ]

    def _generate_examples(self, data_file, split):

        process_label = self.config.process_label
        label_classes = self.config.label_classes

        with open(data_file, encoding="latin-1") as f:
            reader = csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE)

            for n, row in enumerate(reader):

                example = {feat: row[col] for feat, col in six.iteritems(self.config.text_features)}
                example["idx"] = n
                #print(row)

                if self.config.label_column in row:
                    label = row[self.config.label_column]
                    label = process_label(label)
                    if label_classes and label not in label_classes:
                        continue
                    example["label"] = label
                else:
                    example["label"] = process_label(-1)
                if not example["label"] or not example["text"]:
                    continue
                yield example["idx"], example