File size: 13,083 Bytes
cdeab22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2be6a42
cdeab22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5d652a2
 
 
 
 
 
cdeab22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5d652a2
 
cdeab22
 
5d652a2
cdeab22
 
 
5d652a2
 
 
 
 
 
cdeab22
5d652a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cdeab22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5d652a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cdeab22
 
 
 
2be6a42
cdeab22
 
 
 
 
 
 
 
fee3330
cdeab22
 
 
 
 
 
2be6a42
cdeab22
 
 
 
2be6a42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5d652a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
# coding=utf-8
# Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor.
#
# 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.
"""Data Loader for Turku Hockey Data2Text corpus"""


import csv
import json
import os
import re

import datasets


# Find for instance the citation on arxiv or on the dataset repo/website
_CITATION = """\
@inproceedings{kanerva2019newsgen,
  Title = {Template-free Data-to-Text Generation of Finnish Sports News},
  Author = {Jenna Kanerva and Samuel R{\"o}nnqvist and Riina Kekki and Tapio Salakoski and Filip Ginter},
  booktitle = {Proceedings of the 22nd Nordic Conference on Computational Linguistics (NoDaLiDa’19)},
  year={2019}
}
"""


# You can copy an official description
_DESCRIPTION = """\
The Turku Hockey Data2Text corpus was developed as a benchmark for evaluating template-free, machine learning methods on Finnish news generation in the area of ice hockey reporting. This dataset is a collection of 3,454 ice hockey games, each including game statistics and a news article describing the game. Each game includes manual alignment of events (such as goals or penalties) and sentences describing the specific event in natural language extracted from the news article. The corpus includes 12,827 annotated events. The natural language passages are manually curated not to include any information not derivable from the input data or world knowledge.
"""

_HOMEPAGE = "https://github.com/TurkuNLP/Turku-hockey-data2text"

_LICENSE = "Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0)"


# The HuggingFace dataset library don't host the datasets but only point to the original files
# This can be an arbitrary nested dict/list of URLs (see below in `_split_generators` method)
_URLs = {
  'train': 'train.json',
  'validation': 'validation.json',
  'test': 'test.json'
}


# relevant keys in input representation for different event types (text and event_id skipped as not being relevant for the input)
relevant_keys = {"game result": ["event_type", "home_team", "guest_team", "score", "periods", "features"],\
                 "goal": ["event_type", "score", "features", "player", "assist", "team", "team_name", "time"],\
                 "penalty": ["event_type", "player", "team", "team_name", "time", "penalty_minutes"],\
                 "saves": ["event_type", "player", "team", "team_name", "saves"]}


class TurkuHockeyData2Text(datasets.GeneratorBasedBuilder):
    """The Turky Hockey Data2Text is a manually curated corpus for Finnish news generation in the area of ice hockey reporting."""

    VERSION = datasets.Version("1.1.0")

    # This is an example of a dataset with multiple configurations.
    # If you don't want/need to define several sub-sets in your dataset,
    # just remove the BUILDER_CONFIG_CLASS and the BUILDER_CONFIGS attributes.

    # If you need to make complex sub-parts in the datasets with configurable options
    # You can create your own builder configuration class to store attribute, inheriting from datasets.BuilderConfig
    # BUILDER_CONFIG_CLASS = MyBuilderConfig

    # You will be able to load one or the other configurations in the following list with
    # data = datasets.load_dataset('my_dataset', 'first_domain')
    # data = datasets.load_dataset('my_dataset', 'second_domain')
    BUILDER_CONFIGS = [
        datasets.BuilderConfig(name="event-generation", version=VERSION, description="This loads the dataset in its event generation mode, where an output description is generated for each game event separately. The full game information is not availbale."),
        datasets.BuilderConfig(name="game-generation", version=VERSION, description="This loads the dataset in its game generation mode, where the full game information is provided, but the actual input–output pairs must be created by the user."),
    ]

    DEFAULT_CONFIG_NAME = "event-generation"  # It's not mandatory to have a default configuration. Just use one if it make sense.

    def _info(self):
        # This method specifies the datasets.DatasetInfo object which contains informations and typings for the dataset
        if self.config.name == "event-generation":  # This is the name of the configuration selected in BUILDER_CONFIGS above
            features = datasets.Features(
                {
                
                    "gem_id": datasets.Value("string"),
                    "game_id": datasets.Value("string"),
                    "event_id": datasets.Value("string"),
                    "input": datasets.Value("string"),
                    "target": datasets.Value("string"),
                    "references": [datasets.Value("string")]
                }
            )
                
        else: # game-generation
            features = datasets.Features(
                {
                    "gem_id": datasets.Value("string"),
                    "id": datasets.Value("string"),
                    "news_article": datasets.Value("string"),
                    "events": datasets.features.Sequence(
                        {
                        "event_id": datasets.Value("string"),
                        "event_type": datasets.Value("string"),
                        "text": datasets.Value("string"),
                        "home_team": datasets.Value("string"),
                        "guest_team": datasets.Value("string"),
                        "score": datasets.Value("string"),
                        "periods": datasets.features.Sequence(datasets.Value("string")),
                        "features": datasets.features.Sequence(datasets.Value("string")),
                        "player": datasets.Value("string"),
                        "assist": datasets.features.Sequence(datasets.Value("string")),
                        "team": datasets.Value("string"),
                        "team_name": datasets.Value("string"),
                        "time": datasets.Value("string"),
                        "penalty_minutes": datasets.Value("string"),
                        "saves": datasets.Value("string"),
                        "multi_reference": datasets.Value("bool")
                        }
                    ),
                }
            )
            
        # define other configs
        return datasets.DatasetInfo(
            description=_DESCRIPTION,
            features=features,
            # If there's a common (input, target) tuple from the features,
            # specify them here. They'll be used if as_supervised=True in
            # builder.as_dataset.
            supervised_keys=None,
            homepage=_HOMEPAGE,
            license=_LICENSE,
            citation=_CITATION,
        )

    def _split_generators(self, dl_manager):
        """Returns SplitGenerators."""
        # If several configurations are possible (listed in BUILDER_CONFIGS), the configuration selected by the user is in self.config.name

        # dl_manager is a datasets.download.DownloadManager that can be used to download and extract URLs
        # It can accept any type or nested list/dict and will give back the same structure with the url replaced with path to local files.
        # By default the archives will be extracted and a path to a cached folder where they are extracted is returned instead of the archive
        
        my_urls = _URLs
        data_dir = dl_manager.download_and_extract(my_urls)
        return [
            datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={"filepath": data_dir["train"], "split": "train"}),
            datasets.SplitGenerator(name=datasets.Split.VALIDATION, gen_kwargs={"filepath": data_dir["validation"], "split": "validation"}),
            datasets.SplitGenerator(name=datasets.Split.TEST, gen_kwargs={"filepath": data_dir["test"], "split": "test"})
        ]

    def _generate_examples(self, filepath, split):
        """ Yields examples as (key, example) tuples. """
        # This method handles input defined in _split_generators to yield (key, example) tuples from the dataset.
        # The `key` is here for legacy reason (tfds) and is not important in itself.

        with open(filepath, "rt", encoding="utf-8") as f:
            data = json.load(f)
        idx = 0
        for i, example in enumerate(data): # one game
            if self.config.name == "game-generation":
                example["gem_id"] = f"gem-turku_hockey_data2text-{split}-{idx}" # fill in gem_id
                idx += 1
                example = self._generate_features(example)
                yield idx, example
            else:
                game_data = self._generate_features(example)
                events = self.create_event_data(game_data["events"])
                for e in events:
                    e["gem_id"] = f"gem-turku_hockey_data2text-{split}-{idx}" # fill in gem_id
                    idx += 1
                    e["game_id"] = game_data["id"]
                    yield idx, e

                    
                    
    def _generate_features(self, example):
        _events = []
        for i, e in enumerate(example["events"]):
            d = {"event_id": e["event_id"],
                 "event_type": e["event_type"],
                 "text": e["text"] if e["text"] != None else "",
                 "home_team": e.get("home_team", ""),
                 "guest_team": e.get("guest_team", ""),
                 "score": e.get("score", ""),
                 "periods": e.get("periods", []),
                 "features": e.get("features", []),
                 "player": e.get("player", ""),
                 "assist": e.get("assist", []),
                 "team": e.get("team", ""),
                 "team_name": e.get("team_name", ""),
                 "time": e.get("time", ""),
                 "penalty_minutes": e.get("penalty_minutes", ""),
                 "saves": e.get("saves", ""),
                 "multi_reference": self._is_multireference(i, example["events"])
                }
            _events.append(d)
        example["events"] = _events
        return example
        
    def _is_multireference(self, i, events):
      """ Return True if this event is one of the multireference events (multiple events refer to the same text passage)
          Otherwise, return False.
      """
      if events[i]["text"] == None:
          return False
      multireference = re.compile("E[0-9]+")
      if multireference.match(events[i]["text"]):
          return True
      # can be first of the multireference events (the one including the actual text passage)
      multi_events = []
      for event in events:
          if event["text"] == None:
              continue
          if multireference.match(event["text"]):
              multi_events.append(event["text"])
      if events[i]["event_id"] in multi_events:
          return True
      return False
      
      


    def create_event_data(self, events):
        simplified_events = []
        for i, event in enumerate(events):
            e_idx, event_input, event_output = self.event2string(i, events)
            if not event_input: # skip empty annotations and multi-reference events
                continue 
            simplified_events.append({"gem_id": "", "game_id": "", "event_id": e_idx, "input": event_input, "target": event_output, "references": [event_output]})
        return simplified_events
      
    def event2string(self, i, events):
        """Featurize i:th event into string input.
        Example:
        input: "event_type: saves [SEP] player: Jani Hurme [SEP] team: home [SEP] team_name: TPS [SEP] saves: 25"
        output: "TPS:n maalissa Jani Hurme ehti 25 kiekon tielle."
        """
        if events[i]["text"] == "": # skip, event is not annotated
            return None, None, None
        if events[i]["multi_reference"] == True: # skip multireference events in simple representation
            return None, None, None
        event_type = events[i]["event_type"] # use only relevant features for this event type
        
        e_data = []
        for key in relevant_keys[event_type]:
            if isinstance(events[i][key], str) or isinstance(events[i][key], float):
                s = f"{key} = {events[i][key]}"
                e_data.append(s)
            if isinstance(events[i][key], list) and len(events[i][key]) > 0:
                s = f'{key} = {" , ".join(events[i][key])}'
                e_data.append(s)
        event_input = " [SEP] ".join(e_data)
        
        e_idx = events[i]["event_id"]
        return e_idx, event_input, events[i]["text"]