frwiki_el / frwiki_el.py
Gaëtan Caillaut
Initial Commit
579e126
raw
history blame
7.68 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.
"""TODO: Add a description here."""
import re
import gzip
import json
import datasets
from pathlib import Path
# TODO: Add BibTeX citation
# Find for instance the citation on arxiv or on the dataset repo/website
_CITATION = ""
_DESCRIPTION = """\
French Wikipedia dataset for Entity Linking
"""
_HOMEPAGE = "https://github.com/GaaH/frwiki_el"
_LICENSE = "WTFPL"
_URLs = {
"frwiki": "data/corpus.jsonl.gz",
"entities": "data/entities.jsonl.gz",
}
_NER_CLASS_LABELS = [
"B",
"I",
"O",
]
_ENTITY_TYPES = [
"DATE",
"PERSON",
"GEOLOC",
"ORG",
"OTHER",
]
def item_to_el_features(item, title2qid):
res = {
"title": item['name'].replace("_", " "),
"wikidata_id": item['wikidata_id'],
"wikipedia_id": item['wikipedia_id'],
"wikidata_url": item['wikidata_url'],
"wikipedia_url": item['wikipedia_url'],
}
text_dict = {
"words": [],
"ner": [],
"el": [],
}
entity_pattern = r"\[E=(.+?)\](.+?)\[/E\]"
# start index of the previous text
i = 0
text = item['text']
for m in re.finditer(entity_pattern, text):
mention_title = m.group(1)
mention = m.group(2)
mention_qid = title2qid.get(mention_title.replace("_", " "), "unknown")
mention_words = mention.split()
j = m.start(0)
prev_text = text[i:j].split()
len_prev_text = len(prev_text)
text_dict["words"].extend(prev_text)
text_dict["ner"].extend(["O"] * len_prev_text)
text_dict["el"].extend([None] * len_prev_text)
text_dict["words"].extend(mention_words)
len_mention_tail = len(mention_words) - 1
text_dict["ner"].extend(["B"] + ["I"] * len_mention_tail)
text_dict["el"].extend([mention_qid] + [mention_qid] * len_mention_tail)
i = m.end(0)
tail = text[i:].split()
len_tail = len(tail)
text_dict["words"].extend(tail)
text_dict["ner"].extend(["O"] * len_tail)
text_dict["el"].extend([None] * len_tail)
res.update(text_dict)
return res
class FrwikiElDataset(datasets.GeneratorBasedBuilder):
"""
"""
VERSION = datasets.Version("0.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="frwiki", version=VERSION,
description="The frwiki dataset for Entity Linking"),
datasets.BuilderConfig(name="entities", version=VERSION,
description="Entities and their descriptions"),
]
# It's not mandatory to have a default configuration. Just use one if it make sense.
DEFAULT_CONFIG_NAME = "frwiki"
def _info(self):
if self.config.name == "frwiki":
features = datasets.Features({
"name": datasets.Value("string"),
"wikidata_id": datasets.Value("string"),
"wikipedia_id": datasets.Value("string"),
"wikipedia_url": datasets.Value("string"),
"wikidata_url": datasets.Value("string"),
"words": [datasets.Value("string")],
"ner": [datasets.ClassLabel(names=_NER_CLASS_LABELS)],
"el": [datasets.Value("string")],
})
elif self.config.name == "entities":
features = datasets.Features({
"name": datasets.Value("string"),
"wikidata_id": datasets.Value("string"),
"wikipedia_id": datasets.Value("string"),
"wikipedia_url": datasets.Value("string"),
"wikidata_url": datasets.Value("string"),
"description": 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
# Here we define them above because they are different between the two configurations
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 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
filepath = _URLs[self.config.name]
# data_dir = dl_manager.download_and_extract(my_urls)
return [
datasets.SplitGenerator(
name=datasets.Split.TRAIN,
# These kwargs will be passed to _generate_examples
gen_kwargs={
"path": filepath,
}
)
]
def _generate_examples(self, path):
""" 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.
# entities_path = Path(data_dir, "entities.jsonl.gz")
# corpus_path = Path(data_dir, "corpus.jsonl.gz")
def _identiy(x):
return x
with gzip.open(path, "rt", encoding="UTF-8") as crps_file:
for id, line in enumerate(crps_file):
item = json.loads(line, parse_int=_identiy, parse_float=_identiy, parse_constant=_identiy)
yield id, item