RotoWire_English-German / RotoWire_English-German.py
ratishsp
support for handling N/A in player name
c8abf86
raw
history blame
22.5 kB
# 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.
"""Dataloader for RotoWire English-German dataset."""
import json
import os
import datasets
import re
# Find for instance the citation on arxiv or on the dataset repo/website
_CITATION = """\
@article{hayashi2019findings,
title={Findings of the Third Workshop on Neural Generation and Translation},
author={Hayashi, Hiroaki and Oda, Yusuke and Birch, Alexandra and Konstas, Ioannis and Finch, Andrew and Luong, Minh-Thang and Neubig, Graham and Sudoh, Katsuhito},
journal={EMNLP-IJCNLP 2019},
pages={1},
year={2019}
}
"""
# You can copy an official description
_DESCRIPTION = """\
Dataset for the WNGT 2019 DGT shared task on "Document-Level Generation and Translation”.
"""
_HOMEPAGE = "https://sites.google.com/view/wngt19/dgt-task"
_LICENSE = "CC-BY 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"
}
NUM_PLAYERS = 13
player_line = "<PLAYER> %s <TEAM> %s <POS> %s <RANK> %s <MIN> %d <PTS> %d <FG> %d %d %d <FG3> %d %d %d " \
"<FT> %d %d %d <REB> %d <AST> %d <STL> %s " \
"<BLK> %d <DREB> %d <OREB> %d <TO> %d"
team_line = "%s <TEAM> %s <CITY> %s <TEAM-RESULT> %s <TEAM-PTS> %d <WINS-LOSSES> %d %d <QTRS> %d %d %d %d " \
"<TEAM-AST> %d <3PT> %d <TEAM-FG> %d <TEAM-FT> %d <TEAM-REB> %d <TEAM-TO> %d"
class RotowireEnglishGerman(datasets.GeneratorBasedBuilder):
"""Dataset for WNGT2019 shared task on Document-level Generation and Translation."""
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="nlg_en", version=VERSION, description="NLG: Data-to-English text."),
# datasets.BuilderConfig(name="nlg_de", version=VERSION, description="NLG: Data-to-German text."),
# datasets.BuilderConfig(name="mt_en-de", version=VERSION, description="MT: English-to-German text."),
# datasets.BuilderConfig(name="mt_de-en", version=VERSION, description="MT: German-to-English text."),
# datasets.BuilderConfig(name="nlg+mt_en-de", version=VERSION, description="NLG+MT: Data+English-to-German text."),
# datasets.BuilderConfig(name="nlg+mt_de-en", version=VERSION, description="NLG+MT: Data+German-to-English text."),
# ]
def _info(self):
# max 26 entries in each box_score field.
box_score_entry = {str(i): datasets.Value("string") for i in range(26)}
box_score_features = {
"FIRST_NAME": box_score_entry,
"MIN": box_score_entry,
"FGM": box_score_entry,
"REB": box_score_entry,
"FG3A": box_score_entry,
"PLAYER_NAME": box_score_entry,
"AST": box_score_entry,
"FG3M": box_score_entry,
"OREB": box_score_entry,
"TO": box_score_entry,
"START_POSITION": box_score_entry,
"PF": box_score_entry,
"PTS": box_score_entry,
"FGA": box_score_entry,
"STL": box_score_entry,
"FTA": box_score_entry,
"BLK": box_score_entry,
"DREB": box_score_entry,
"FTM": box_score_entry,
"FT_PCT": box_score_entry,
"FG_PCT": box_score_entry,
"FG3_PCT": box_score_entry,
"SECOND_NAME": box_score_entry,
"TEAM_CITY": box_score_entry,
}
line_features = {
"TEAM-PTS_QTR2": datasets.Value("string"),
"TEAM-FT_PCT": datasets.Value("string"),
"TEAM-PTS_QTR1": datasets.Value("string"),
"TEAM-PTS_QTR4": datasets.Value("string"),
"TEAM-PTS_QTR3": datasets.Value("string"),
"TEAM-CITY": datasets.Value("string"),
"TEAM-PTS": datasets.Value("string"),
"TEAM-AST": datasets.Value("string"),
"TEAM-LOSSES": datasets.Value("string"),
"TEAM-NAME": datasets.Value("string"),
"TEAM-WINS": datasets.Value("string"),
"TEAM-REB": datasets.Value("string"),
"TEAM-TOV": datasets.Value("string"),
"TEAM-FG3_PCT": datasets.Value("string"),
"TEAM-FG_PCT": datasets.Value("string")
}
features = datasets.Features(
{
"id":datasets.Value("string"),
"gem_id":datasets.Value("string"),
"home_name": datasets.Value("string"),
"box_score": box_score_features,
"vis_name": datasets.Value("string"),
"summary": datasets.Sequence(datasets.Value("string")),
"home_line": line_features,
"home_city": datasets.Value("string"),
"vis_line": line_features,
"vis_city": datasets.Value("string"),
"day": datasets.Value("string"),
"detok_summary_org": datasets.Value("string"),
"detok_summary": datasets.Value("string"),
"summary_en": datasets.Sequence(datasets.Value("string")),
"sentence_end_index_en": datasets.Sequence(datasets.Value("int32")),
"summary_de": datasets.Sequence(datasets.Value("string")),
"sentence_end_index_de": datasets.Sequence(datasets.Value("int32")),
"linearized_input": datasets.Value("string")
}
)
return datasets.DatasetInfo(
# This is the description that will appear on the datasets page.
description=_DESCRIPTION,
# This defines the different columns of the dataset and their types
features=features, # Here we define them above because they are different between the two configurations
# 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 of the dataset for documentation
homepage=_HOMEPAGE,
# License for the dataset if available
license=_LICENSE,
# Citation for the dataset
citation=_CITATION,
)
def _split_generators(self, dl_manager):
"""Returns SplitGenerators."""
# TODO: This method is tasked with downloading/extracting the data and defining the splits depending on the configuration
# 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
data_dir = dl_manager.download_and_extract(_URLs)
return [
datasets.SplitGenerator(
name=datasets.Split.TRAIN,
# These kwargs will be passed to _generate_examples
gen_kwargs={
"filepath": data_dir["train"],
"split": "train",
},
),
datasets.SplitGenerator(
name=datasets.Split.TEST,
# These kwargs will be passed to _generate_examples
gen_kwargs={
"filepath": data_dir["test"],
"split": "test"
},
),
datasets.SplitGenerator(
name=datasets.Split.VALIDATION,
# These kwargs will be passed to _generate_examples
gen_kwargs={
"filepath": data_dir["validation"],
"split": "validation",
},
),
]
def handle_na(self, value):
return "0" if value == "N/A" else value
def tokenize_initials(self, value):
attrib_value = re.sub(r"(\w)\.(\w)\.", r"\g<1>. \g<2>.", value)
return attrib_value
def sort_points(self, entry):
home_team_map = {}
vis_team_map = {}
bs = entry["box_score"]
nplayers = 0
for k, v in bs["PTS"].items():
nplayers += 1
num_home, num_vis = 0, 0
home_pts = []
vis_pts = []
for i in range(nplayers):
player_city = entry["box_score"]["TEAM_CITY"][str(i)]
player_name = bs["PLAYER_NAME"][str(i)]
if player_city == entry["home_city"]:
if num_home < NUM_PLAYERS:
home_team_map[player_name] = bs["PTS"][str(i)]
if bs["PTS"][str(i)] != "N/A":
home_pts.append(int(bs["PTS"][str(i)]))
num_home += 1
else:
if num_vis < NUM_PLAYERS:
vis_team_map[player_name] = bs["PTS"][str(i)]
if bs["PTS"][str(i)] != "N/A":
vis_pts.append(int(bs["PTS"][str(i)]))
num_vis += 1
if entry["home_city"] == entry["vis_city"] and entry["home_city"] == "Los Angeles":
num_home, num_vis = 0, 0
for i in range(nplayers):
player_name = bs["PLAYER_NAME"][str(i)]
if num_vis < NUM_PLAYERS:
vis_team_map[player_name] = bs["PTS"][str(i)]
if bs["PTS"][str(i)] != "N/A":
vis_pts.append(int(bs["PTS"][str(i)]))
num_vis += 1
elif num_home < NUM_PLAYERS:
home_team_map[player_name] = bs["PTS"][str(i)]
if bs["PTS"][str(i)] != "N/A":
home_pts.append(int(bs["PTS"][str(i)]))
num_home += 1
home_seq = sorted(home_pts, reverse=True)
vis_seq = sorted(vis_pts, reverse=True)
return home_team_map, vis_team_map, home_seq, vis_seq
def sort_player_and_points(self, entry):
bs = entry["box_score"]
nplayers = 0
for k, v in bs["PTS"].items():
nplayers += 1
num_home, num_vis = 0, 0
home_pts = []
vis_pts = []
for i in range(nplayers):
player_city = entry["box_score"]["TEAM_CITY"][str(i)]
player_name = bs["PLAYER_NAME"][str(i)]
if player_city == entry["home_city"]:
if num_home < NUM_PLAYERS:
if bs["PTS"][str(i)] != "N/A":
home_pts.append((player_name, int(bs["PTS"][str(i)])))
else:
home_pts.append((player_name, -1))
num_home += 1
else:
if num_vis < NUM_PLAYERS:
if bs["PTS"][str(i)] != "N/A":
vis_pts.append((player_name, int(bs["PTS"][str(i)])))
else:
vis_pts.append((player_name, -1))
num_vis += 1
if entry["home_city"] == entry["vis_city"] and entry["home_city"] == "Los Angeles":
num_home, num_vis = 0, 0
for i in range(nplayers):
player_name = bs["PLAYER_NAME"][str(i)]
if num_vis < NUM_PLAYERS:
if bs["PTS"][str(i)] != "N/A":
vis_pts.append((player_name, int(bs["PTS"][str(i)])))
else:
vis_pts.append((player_name, -1))
num_vis += 1
elif num_home < NUM_PLAYERS:
if bs["PTS"][str(i)] != "N/A":
home_pts.append((player_name, int(bs["PTS"][str(i)])))
else:
home_pts.append((player_name, -1))
num_home += 1
home_seq = sorted(home_pts, key=lambda x: -x[1])
vis_seq = sorted(vis_pts, key=lambda x: -x[1])
return home_seq, vis_seq
def get_players(self, entry):
player_team_map = {}
bs = entry["box_score"]
nplayers = 0
home_players, vis_players = [], []
for k, v in entry["box_score"]["PTS"].items():
nplayers += 1
num_home, num_vis = 0, 0
for i in range(nplayers):
player_city = entry["box_score"]["TEAM_CITY"][str(i)]
player_name = bs["PLAYER_NAME"][str(i)]
second_name = bs["SECOND_NAME"][str(i)]
first_name = bs["FIRST_NAME"][str(i)]
if player_city == entry["home_city"]:
if len(home_players) < NUM_PLAYERS:
home_players.append((player_name, second_name,
first_name))
player_team_map[player_name] = " ".join(
[player_city, entry["home_line"]["TEAM-NAME"]])
num_home += 1
else:
if len(vis_players) < NUM_PLAYERS:
vis_players.append((player_name, second_name,
first_name))
player_team_map[player_name] = " ".join(
[player_city, entry["vis_line"]["TEAM-NAME"]])
num_vis += 1
if entry["home_city"] == entry["vis_city"] and entry["home_city"] == "Los Angeles":
home_players, vis_players = [], []
num_home, num_vis = 0, 0
for i in range(nplayers):
player_name = bs["PLAYER_NAME"][str(i)]
second_name = bs["SECOND_NAME"][str(i)]
first_name = bs["FIRST_NAME"][str(i)]
if len(vis_players) < NUM_PLAYERS:
vis_players.append((player_name, second_name,
first_name))
player_team_map[player_name] = " ".join(
["Los Angeles", entry["vis_line"]["TEAM-NAME"]])
num_vis += 1
elif len(home_players) < NUM_PLAYERS:
home_players.append((player_name, second_name,
first_name))
player_team_map[player_name] = " ".join(
["Los Angeles", entry["home_line"]["TEAM-NAME"]])
num_home += 1
players = []
for ii, player_list in enumerate([home_players, vis_players]):
for j in range(NUM_PLAYERS):
players.append(player_list[j] if j < len(player_list) else ("N/A", "N/A", "N/A"))
return players, player_team_map
def get_result_player(self, player_name, home_name, vis_name, home_won, player_team_map):
if player_team_map[player_name] == home_name:
result = "won" if home_won else "lost"
elif player_team_map[player_name] == vis_name:
result = "lost" if home_won else "won"
else:
assert False
return result
def get_box_score(self, entry):
box_score_ = entry["box_score"]
if int(entry["home_line"]["TEAM-PTS"]) > int(entry["vis_line"]["TEAM-PTS"]):
home_won = True
else:
home_won = False
descs = []
desc = []
if home_won:
home_line = self.get_team_line(entry["home_line"], "won", "home")
vis_line = self.get_team_line(entry["vis_line"], "lost", "vis")
else:
home_line = self.get_team_line(entry["home_line"], "lost", "home")
vis_line = self.get_team_line(entry["vis_line"], "won", "vis")
descs.append(home_line)
descs.append(vis_line)
players_list, player_team_map = self.get_players(entry)
home_team_map, vis_team_map, home_player_pts, vis_player_pts = self.sort_points(entry)
home_player_seq, vis_player_seq = self.sort_player_and_points(entry)
desc = []
for player_name, _ in home_player_seq + vis_player_seq:
if player_name == "N/A":
continue
result = self.get_result_player(player_name, entry["home_city"] + " " + entry["home_line"]["TEAM-NAME"],
entry["vis_city"] + " " + entry["vis_line"]["TEAM-NAME"], home_won,
player_team_map)
player_line = self.get_player_line(box_score_, player_name, player_team_map, home_player_pts,
vis_player_pts, home_team_map, vis_team_map, result)
desc.append(player_line)
descs.extend(desc)
return descs
def get_rank(self, player_name, home_seq, vis_seq, home_team_map, vis_team_map, result):
if player_name in home_team_map:
if home_team_map[player_name] == 'N/A':
rank = 'HOME-DIDNTPLAY'
else:
rank = 'HOME-' + str(home_seq.index(int(home_team_map[player_name])))
elif player_name in vis_team_map:
if vis_team_map[player_name] == 'N/A':
rank = 'VIS-DIDNTPLAY'
else:
rank = 'VIS-' + str(vis_seq.index(int(vis_team_map[player_name])))
else:
print("player_name", player_name)
assert False
return rank
def get_player_line(self, bs, input_player_name, player_team_map, home_player_pts, vis_player_pts, home_team_map,
vis_team_map, result):
rank = self.get_rank(input_player_name, home_player_pts, vis_player_pts, home_team_map, vis_team_map, result)
player_names = list(bs["PLAYER_NAME"].items())
player_found = False
player_tup = None
for (pid, name) in player_names:
if name == input_player_name:
player_tup = (self.tokenize_initials(name), player_team_map[input_player_name],
bs["START_POSITION"][pid],
rank,
int(self.handle_na(bs["MIN"][pid])),
int(self.handle_na(bs["PTS"][pid])),
int(self.handle_na(bs["FGM"][pid])),
int(self.handle_na(bs["FGA"][pid])), int(self.handle_na(bs["FG_PCT"][pid])),
int(self.handle_na(bs["FG3M"][pid])), int(self.handle_na(bs["FG3A"][pid])),
int(self.handle_na(bs["FG3_PCT"][pid])),
int(self.handle_na(bs["FTM"][pid])), int(self.handle_na(bs["FTA"][pid])),
int(self.handle_na(bs["FT_PCT"][pid])),
int(self.handle_na(bs["REB"][pid])), int(self.handle_na(bs["AST"][pid])),
int(self.handle_na(bs["STL"][pid])),
int(self.handle_na(bs["BLK"][pid])), int(self.handle_na(bs["DREB"][pid])),
int(self.handle_na(bs["OREB"][pid])), int(self.handle_na(bs["TO"][pid])))
player_found = True
break
assert player_found
return player_line % (player_tup)
def get_team_line(self, line, result, type):
city = line["TEAM-CITY"]
name = line["TEAM-NAME"]
wins = int(line["TEAM-WINS"])
losses = int(line["TEAM-LOSSES"])
pts = int(line["TEAM-PTS"])
ast = int(line["TEAM-AST"])
three_pointers_pct = int(line["TEAM-FG3_PCT"])
field_goals_pct = int(line["TEAM-FG_PCT"])
free_throws_pct = int(line["TEAM-FT_PCT"])
pts_qtr1 = int(line["TEAM-PTS_QTR1"])
pts_qtr2 = int(line["TEAM-PTS_QTR2"])
pts_qtr3 = int(line["TEAM-PTS_QTR3"])
pts_qtr4 = int(line["TEAM-PTS_QTR4"])
reb = int(line["TEAM-REB"])
tov = int(line["TEAM-TOV"])
updated_type = "<" + type.upper() + ">"
team_tup = (updated_type, name, city, result, pts, wins, losses, pts_qtr1, pts_qtr2, pts_qtr3, pts_qtr4, ast,
three_pointers_pct, field_goals_pct, free_throws_pct, reb, tov)
return team_line % (team_tup)
def linearize_input(self, entry):
output = self.get_box_score(entry)
linearized_input = " ".join(output)
linearized_input = linearized_input.replace(" ", " ")
return linearized_input
def _generate_examples(
self, filepath, split # method parameters are unpacked from `gen_kwargs` as given in `_split_generators`
):
""" 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, encoding="utf-8") as f:
all_data = json.load(f)
for id_, data in enumerate(all_data):
data['linearized_input'] = self.linearize_input(data)
yield id_, data