Datasets:
Sub-tasks:
semantic-similarity-classification
Languages:
English
Size:
100K<n<1M
Tags:
text segmentation
document segmentation
topic segmentation
topic shift detection
semantic chunking
chunking
License:
# 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: Address all TODOs and remove all explanatory comments | |
""" | |
Wiki-727K dataset loading script responsible for downloading and extracting raw data files, followed by parsing the articles into lists of setnences and their binary text segmentation labels. | |
See https://github.com/koomri/text-segmentation for more information. | |
Usage: | |
>>> from datasets import load_dataset | |
>>> dataset = load_dataset('saeedabc/wiki727k', num_proc=8, trust_remote_code=True) | |
""" | |
import os | |
import datasets | |
from dataclasses import dataclass | |
from typing import Optional | |
from .preprocess_util import parse_split_files | |
# TODO: Add BibTeX citation | |
# Find for instance the citation on arxiv or on the dataset repo/website | |
_CITATION = """\ | |
@inproceedings{koshorek-etal-2018-text, | |
title = "Text Segmentation as a Supervised Learning Task", | |
author = "Koshorek, Omri and | |
Cohen, Adir and | |
Mor, Noam and | |
Rotman, Michael and | |
Berant, Jonathan", | |
editor = "Walker, Marilyn and | |
Ji, Heng and | |
Stent, Amanda", | |
booktitle = "Proceedings of the 2018 Conference of the North {A}merican Chapter of the Association for Computational Linguistics: Human Language Technologies, Volume 2 (Short Papers)", | |
month = jun, | |
year = "2018", | |
address = "New Orleans, Louisiana", | |
publisher = "Association for Computational Linguistics", | |
url = "https://aclanthology.org/N18-2075", | |
doi = "10.18653/v1/N18-2075", | |
pages = "469--473", | |
abstract = "Text segmentation, the task of dividing a document into contiguous segments based on its semantic structure, is a longstanding challenge in language understanding. Previous work on text segmentation focused on unsupervised methods such as clustering or graph search, due to the paucity in labeled data. In this work, we formulate text segmentation as a supervised learning problem, and present a large new dataset for text segmentation that is automatically extracted and labeled from Wikipedia. Moreover, we develop a segmentation model based on this dataset and show that it generalizes well to unseen natural text.", | |
} | |
""" | |
# TODO: Add description of the dataset here | |
# You can copy an official description | |
_DESCRIPTION = """\ | |
Wiki-727K is a large dataset for text segmentation that is automatically extracted and labeled from Wikipedia. | |
This dataset is formulated as a sentence-level sequence labelling task for text segmentation. | |
""" | |
# TODO: Add a link to an official homepage for the dataset here | |
_HOMEPAGE = "https://github.com/koomri/text-segmentation" | |
# TODO: Add the licence for the dataset here if you can find it | |
_LICENSE = "MIT License" | |
# TODO: Add link to the official dataset URLs here | |
# The HuggingFace Datasets library doesn't host the datasets but only points to the original files. | |
# This can be an arbitrary nested dict/list of URLs (see below in `_split_generators` method) | |
_URL = "https://www.dropbox.com/sh/k3jh0fjbyr0gw0a/AACKW_gsxUf282QqrfH3yD10a/wiki_727K.tar.bz2?dl=1" | |
class Wiki727kBuilderConfig(datasets.BuilderConfig): | |
"""BuilderConfig for Wiki-727K dataset.""" | |
drop_titles: Optional[bool] = False | |
prepend_title_stack: Optional[bool] = False | |
def __post_init__(self): | |
if self.drop_titles and self.prepend_title_stack: | |
raise ValueError("Prepend title stack is not compatible with drop titles.") | |
super(Wiki727kBuilderConfig, self).__post_init__() | |
# TODO: Name of the dataset usually matches the script name with CamelCase instead of snake_case | |
class Wiki727k(datasets.GeneratorBasedBuilder): | |
"""Wiki-727K dataset formulated as a sentence-level sequence labelling task for text segmentation.""" | |
VERSION = datasets.Version("1.0.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 = Wiki727kBuilderConfig | |
# You will be able to load one or the other configurations in the following list with | |
# data = datasets.load_dataset('name', 'config1') | |
BUILDER_CONFIGS = [ | |
Wiki727kBuilderConfig(name="default", version=VERSION, description="Default configuration of Wiki727K dataset."), | |
] | |
DEFAULT_CONFIG_NAME = "default" # It's not mandatory to have a default configuration. Just use one if it make sense. | |
# BUILDER_CONFIGS = [ | |
# datasets.BuilderConfig(name="titled", version=VERSION, description="Article titles are kept alongside regular sentences in `sentences` attribute, but differentiated with positive values (i.e. 1 as opposed to 0) in `titles_mask` attribute. (Default configuration with all attributes)"), | |
# datasets.BuilderConfig(name="untitled", version=VERSION, description="Article titles are droped, therefore `sentences` attribute consists of only regular sentences, and `titles_mask` attribute is not present. (Alternative configuration ready for Document Segmentation task)"), | |
# ] | |
# DEFAULT_CONFIG_NAME = "titled" # It's not mandatory to have a default configuration. Just use one if it make sense. | |
def _info(self): | |
# TODO: This method specifies the datasets.DatasetInfo object which contains informations and typings for the dataset | |
# if self.config.name == "config1": ... # This is the name of the configuration selected in BUILDER_CONFIGS above | |
features = datasets.Features( | |
{ | |
"id": datasets.Value("string"), # document id --> [doc0, doc1, ...] | |
"ids": datasets.Sequence( # document sentence ids --> [[doc0_sent0, doc0_sent1, ...], ...] | |
datasets.Value("string") | |
), | |
"sentences": datasets.Sequence( | |
datasets.Value("string") | |
), | |
"titles_mask": datasets.Sequence( | |
datasets.Value("uint8") | |
), | |
"levels": datasets.Sequence( | |
datasets.Value("uint8") | |
), | |
"labels": datasets.Sequence( | |
datasets.ClassLabel(num_classes=2, names=['semantic-continuity', 'semantic-shift']) | |
), | |
} | |
) | |
if self.config.drop_titles: | |
features.pop("titles_mask") | |
features.pop("levels") | |
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, uncomment supervised_keys line below and | |
# specify them. They'll be used if as_supervised=True in builder.as_dataset. | |
# supervised_keys=("sentence", "label"), | |
# 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): | |
# 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 | |
splits = {'train': datasets.Split.TRAIN, 'dev': datasets.Split.VALIDATION, 'test': datasets.Split.TEST} | |
data_dir = dl_manager.download_and_extract(_URL) | |
data_dir = os.path.join(data_dir, "wiki_727") | |
out = [] | |
for split in splits: | |
split_path = os.path.join(data_dir, split) | |
split_shard_paths = [ssp for f in os.listdir(split_path) if os.path.isdir(ssp := os.path.join(split_path, f))] | |
out.append( | |
datasets.SplitGenerator( | |
name=splits[split], | |
# These kwargs will be passed to _generate_examples | |
gen_kwargs={"filepaths": split_shard_paths, "split": split} | |
) | |
) | |
return out | |
# method parameters are unpacked from `gen_kwargs` as given in `_split_generators` | |
def _generate_examples(self, filepaths: list, split: str): | |
for filepath in filepaths: | |
for doc in parse_split_files(filepath, | |
drop_titles = self.config.drop_titles, | |
prepend_title_stack = self.config.prepend_title_stack): | |
yield doc['id'], doc | |