# coding=utf-8
# Copyright 2022 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.

"""The Google-IISc Distant Supervision (GIDS) dataset for distantly-supervised relation extraction"""

import csv
import datasets

_CITATION = """\
@inproceedings{bassignana-plank-2022-crossre,
    title = "Cross{RE}: A {C}ross-{D}omain {D}ataset for {R}elation {E}xtraction",
    author = "Bassignana, Elisa and Plank, Barbara",
    booktitle = "Findings of the Association for Computational Linguistics: EMNLP 2022",
    year = "2022",
    publisher = "Association for Computational Linguistics"
}
"""

_DESCRIPTION = """\
Google-IISc Distant Supervision (GIDS) is a new dataset for distantly-supervised relation extraction.
GIDS is seeded from the human-judged Google relation extraction corpus.
"""

_HOMEPAGE = ""

_LICENSE = ""

# 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": "https://raw.githubusercontent.com/SharmisthaJat/RE-DS-Word-Attention-Models/master/Data/GIDS/train.tsv",
    "validation": "https://raw.githubusercontent.com/SharmisthaJat/RE-DS-Word-Attention-Models/master/Data/GIDS/dev.tsv",
    "test": "https://raw.githubusercontent.com/SharmisthaJat/RE-DS-Word-Attention-Models/master/Data/GIDS/test.tsv",
}
_VERSION = datasets.Version("1.0.0")

_CLASS_LABELS = [
    "NA",
    "/people/person/education./education/education/institution",
    "/people/person/education./education/education/degree",
    "/people/person/place_of_birth",
    "/people/deceased_person/place_of_death"
]


def replace_underscore_in_span(text, start, end):
    cleaned_text = text[:start] + text[start:end].replace("_", " ") + text[end:]
    return cleaned_text


class GIDS(datasets.GeneratorBasedBuilder):
    """Google-IISc Distant Supervision (GIDS) is a new dataset for distantly-supervised relation extraction."""

    BUILDER_CONFIGS = [
        datasets.BuilderConfig(
            name="gids", version=_VERSION, description="GIDS dataset."
        ),
        datasets.BuilderConfig(
            name="gids_formatted", version=_VERSION, description="Formatted GIDS dataset."
        ),
    ]

    DEFAULT_CONFIG_NAME = "gids"  # type: ignore

    def _info(self):
        if self.config.name == "gids_formatted":
            features = datasets.Features(
                {
                    "token": datasets.Sequence(datasets.Value("string")),
                    "subj_start": datasets.Value("int32"),
                    "subj_end": datasets.Value("int32"),
                    "obj_start": datasets.Value("int32"),
                    "obj_end": datasets.Value("int32"),
                    "relation": datasets.ClassLabel(names=_CLASS_LABELS),
                }
            )
        else:
            features = datasets.Features(
                {
                    "sentence": datasets.Value("string"),
                    "subj_id": datasets.Value("string"),
                    "obj_id": datasets.Value("string"),
                    "subj_text": datasets.Value("string"),
                    "obj_text": datasets.Value("string"),
                    "relation": datasets.ClassLabel(names=_CLASS_LABELS)
                }
            )

        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."""
        # 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

        downloaded_files = dl_manager.download_and_extract(_URLs)

        return [datasets.SplitGenerator(name=i, gen_kwargs={"filepath": downloaded_files[str(i)]})
                for i in [datasets.Split.TRAIN, datasets.Split.VALIDATION, datasets.Split.TEST]]

    def _generate_examples(self, filepath):
        """Yields examples."""
        # This method will receive as arguments the `gen_kwargs` defined in the previous `_split_generators` method.
        # It is in charge of opening the given file and yielding (key, example) tuples from the dataset
        # The key is not important, it's more here for legacy reason (legacy from tfds)
        if self.config.name == "gids_formatted":
            from spacy.lang.en import English
            word_splitter = English()
        else:
            word_splitter = None
        with open(filepath, encoding="utf-8") as f:
            data = csv.reader(f, delimiter="\t")
            for id_, example in enumerate(data):
                text = example[5].strip()[:-9].strip()  # remove '###END###' from text,
                subj_text = example[2]
                obj_text = example[3]
                rel_type = example[4]

                if self.config.name == "gids_formatted":
                    subj_char_start = text.find(subj_text)
                    assert subj_char_start != -1, f"Did not find <{subj_text}> in the text"
                    subj_char_end = subj_char_start + len(subj_text)
                    obj_char_start = text.find(obj_text)
                    assert obj_char_start != -1, f"Did not find <{obj_text}> in the text"
                    obj_char_end = obj_char_start + len(obj_text)
                    text = replace_underscore_in_span(text, subj_char_start, subj_char_end)
                    text = replace_underscore_in_span(text, obj_char_start, obj_char_end)
                    doc = word_splitter(text)
                    word_tokens = [t.text for t in doc]
                    subj_span = doc.char_span(subj_char_start, subj_char_end, alignment_mode="expand")
                    obj_span = doc.char_span(obj_char_start, obj_char_end, alignment_mode="expand")

                    yield id_, {
                        "token": word_tokens,
                        "subj_start": subj_span.start,
                        "subj_end": subj_span.end,
                        "obj_start": obj_span.start,
                        "obj_end": obj_span.end,
                        "relation": rel_type,
                    }
                else:
                    yield id_, {
                        "sentence": text,
                        "subj_id": example[0],
                        "obj_id": example[1],
                        "subj_text": subj_text,
                        "obj_text": obj_text,
                        "relation": rel_type,
                    }