# coding=utf-8
# Lint as: python3
"""The ZeroSCROLLS benchmark."""

import json
import os
import datasets

_ZERO_SCROLLS_CITATION = """
@inproceedings{shaham-etal-2023-zeroscrolls,
    title = "{Z}ero{SCROLLS}: A Zero-Shot Benchmark for Long Text Understanding",
    author = "Shaham, Uri  and
      Ivgi, Maor  and
      Efrat, Avia  and
      Berant, Jonathan  and
      Levy, Omer",
    editor = "Bouamor, Houda  and
      Pino, Juan  and
      Bali, Kalika",
    booktitle = "Findings of the Association for Computational Linguistics: EMNLP 2023",
    month = dec,
    year = "2023",
    address = "Singapore",
    publisher = "Association for Computational Linguistics",
    url = "https://aclanthology.org/2023.findings-emnlp.536",
    doi = "10.18653/v1/2023.findings-emnlp.536",
    pages = "7977--7989"
}
Note that each ZeroSCROLLS task has its own citation. Please see the source to
get the correct citation for each one.
"""

_ZERO_SCROLLS_DESCRIPTION = """
ZeroSCROLLS: Zero-Shot CompaRison Over Long Language Sequences.
A zero shot benchmark for long text reasoning.
https://zero.scrolls-benchmark.com/
"""

_SCROLLS_CITATION = """
@inproceedings{shaham-etal-2022-scrolls,
    title = "{SCROLLS}: Standardized {C}ompa{R}ison Over Long Language Sequences",
    author = "Shaham, Uri  and
      Segal, Elad  and
      Ivgi, Maor  and
      Efrat, Avia  and
      Yoran, Ori  and
      Haviv, Adi  and
      Gupta, Ankit  and
      Xiong, Wenhan  and
      Geva, Mor  and
      Berant, Jonathan  and
      Levy, Omer",
    booktitle = "Proceedings of the 2022 Conference on Empirical Methods in Natural Language Processing",
    month = dec,
    year = "2022",
    address = "Abu Dhabi, United Arab Emirates",
    publisher = "Association for Computational Linguistics",
    url = "https://aclanthology.org/2022.emnlp-main.823",
    pages = "12007--12021",
}
"""

_SCROLLS_DESCRIPTION = """
SCROLLS: Standardized CompaRison Over Long Language Sequences.
A suite of natural language datasets that require reasoning over long texts.
https://scrolls-benchmark.com/
"""

_SUMM_SCREEN_DESCRIPTION = """
SummScreenFD (Chen  et al., 2022) is a summarization dataset in the domain of TV shows (e.g. Friends, Game of Thrones).
Given a transcript of a specific episode, the goal is to produce the episode's recap.
The original dataset is divided into two complementary subsets, based on the source of its community contributed transcripts. 
For SCROLLS, we use the ForeverDreaming (FD) subset, as it incorporates 88 different shows, 
making it a more diverse alternative to the TV MegaSite (TMS) subset, which has only 10 shows. 
Community-authored recaps for the ForeverDreaming transcripts were collected from English Wikipedia and TVMaze."""

_QASPER_DESCRIPTION = """
Qasper (Dasigi et al., 2021) is a question answering dataset over NLP papers filtered from the Semantic Scholar Open Research Corpus (S2ORC).
Questions were written by NLP practitioners after reading only the title and abstract of the papers, 
while another set of NLP practitioners annotated the answers given the entire document.
Qasper contains abstractive, extractive, and yes/no questions, as well as unanswerable ones."""

_QMSUM_DESCRIPTION = """
QMSum (Zhong et al., 2021) is a query-based summarization dataset, consisting of 232 meetings transcripts from multiple domains. 
The corpus covers academic group meetings at the International Computer Science Institute and their summaries, industrial product meetings for designing a remote control, 
and committee meetings of the Welsh and Canadian Parliaments, dealing with a variety of public policy issues.
Annotators were tasked with writing queries about the broad contents of the meetings, as well as specific questions about certain topics or decisions, 
while ensuring that the relevant text for answering each query spans at least 200 words or 10 turns."""

_NARRATIVE_QA_DESCRIPTION = """
NarrativeQA (Kočiský et al., 2018) is an established question answering dataset over entire books from Project Gutenberg and movie scripts from different websites.
Annotators were given summaries of the books and scripts obtained from Wikipedia, and asked to generate question-answer pairs, 
resulting in about 30 questions and answers for each of the 1,567 books and scripts.
They were encouraged to use their own words rather then copying, and avoid asking yes/no questions or ones about the cast.
Each question was then answered by an additional annotator, providing each question with two reference answers (unless both answers are identical).."""

_GOV_REPORT_DESCRIPTION = """
GovReport (Huang et al., 2021) is a summarization dataset of reports addressing various national policy issues published by the 
Congressional Research Service and the U.S. Government Accountability Office, where each document is paired with a hand-written executive summary.
The reports and their summaries are longer than their equivalents in other popular long-document summarization datasets; 
for example, GovReport's documents are approximately 1.5 and 2.5 times longer than the documents in Arxiv and PubMed, respectively."""

_QUALITY_DESCRIPTION = """
QuALITY (Pang et al., 2022) is a multiple-choice question answering dataset over articles and stories sourced from Project Gutenberg, 
the Open American National Corpus, and more.
Experienced writers wrote questions and distractors, and were incentivized to write answerable, unambiguous questions such that in order to correctly answer them, 
human annotators must read large portions of the given document. 
Reference answers were then calculated using the majority vote between of the annotators and writer's answers.
To measure the difficulty of their questions, Pang et al. conducted a speed validation process, 
where another set of annotators were asked to answer questions given only a short period of time to skim through the document.
As a result, 50% of the questions in QuALITY are labeled as hard, i.e. the majority of the annotators in the speed validation setting chose the wrong answer."""

_SQUALITY_DESCRIPTION = """
SQuALITY (Wang et al., 2022) is a question-focused summarization dataset, where given a story from Project Gutenberg, 
the task is to produce a summary of the story or aspects of it based on a guiding question.
The questions and summaries are original and crowdsourced; experienced writers were guided to design questions that require reading significant parts of the story to answer correctly.
"""

_MUSIQUE_DESCRIPTION = """
MuSiQue (Trivedi et al,. 2022) is a multi-hop question answering dataset, where the inputs are 20 Wikipedia paragraphs and a question that requires multiple hops between different paragraphs.
In the original dataset, each question also has an unanswerable twin question, where the correct answer is not present in the paragraphs.
"""

_SPACE_DIGEST_DESCRIPTION = """
SpaceDigest is a new sentiment aggregation task.
Given 50 hotel reviews (without their ratings) from the Space dataset (Angelidis et al., 2021), the task is to determine the percentage of positive reviews.
"""

_BOOK_SUM_DESCRIPTION = """
BookSumSort is a new task based on the BookSum dataset (Kry ́sci ́nski et al., 2022), which contains summaries of chapters (or parts) of novels, plays, and long poems from various sources. 
Given a shuffled list of chapter summaries, the task is to reorder them according to the original order of summaries in BookSum.
"""

_SUMM_SCREEN_CITATION = r"""
@inproceedings{chen-etal-2022-summscreen,
    title = "{S}umm{S}creen: A Dataset for Abstractive Screenplay Summarization",
    author = "Chen, Mingda  and
      Chu, Zewei  and
      Wiseman, Sam  and
      Gimpel, Kevin",
    booktitle = "Proceedings of the 60th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)",
    month = may,
    year = "2022",
    address = "Dublin, Ireland",
    publisher = "Association for Computational Linguistics",
    url = "https://aclanthology.org/2022.acl-long.589",
    doi = "10.18653/v1/2022.acl-long.589",
    pages = "8602--8615",
    abstract = "We introduce SummScreen, a summarization dataset comprised of pairs of TV series transcripts and human written recaps. The dataset provides a challenging testbed for abstractive summarization for several reasons. Plot details are often expressed indirectly in character dialogues and may be scattered across the entirety of the transcript. These details must be found and integrated to form the succinct plot descriptions in the recaps. Also, TV scripts contain content that does not directly pertain to the central plot but rather serves to develop characters or provide comic relief. This information is rarely contained in recaps. Since characters are fundamental to TV series, we also propose two entity-centric evaluation metrics. Empirically, we characterize the dataset by evaluating several methods, including neural models and those based on nearest neighbors. An oracle extractive approach outperforms all benchmarked models according to automatic metrics, showing that the neural models are unable to fully exploit the input transcripts. Human evaluation and qualitative analysis reveal that our non-oracle models are competitive with their oracle counterparts in terms of generating faithful plot events and can benefit from better content selectors. Both oracle and non-oracle models generate unfaithful facts, suggesting future research directions.",
}"""

_QASPER_CITATION = r"""
@inproceedings{dasigi-etal-2021-dataset,
    title = "A Dataset of Information-Seeking Questions and Answers Anchored in Research Papers",
    author = "Dasigi, Pradeep  and
      Lo, Kyle  and
      Beltagy, Iz  and
      Cohan, Arman  and
      Smith, Noah A.  and
      Gardner, Matt",
    booktitle = "Proceedings of the 2021 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies",
    month = jun,
    year = "2021",
    address = "Online",
    publisher = "Association for Computational Linguistics",
    url = "https://aclanthology.org/2021.naacl-main.365",
    doi = "10.18653/v1/2021.naacl-main.365",
    pages = "4599--4610"
    }"""

_QMSUM_CITATION = r"""@inproceedings{zhong-etal-2021-qmsum,
    title = "{QMS}um: A New Benchmark for Query-based Multi-domain Meeting Summarization",
    author = "Zhong, Ming  and
      Yin, Da  and
      Yu, Tao  and
      Zaidi, Ahmad  and
      Mutuma, Mutethia  and
      Jha, Rahul  and
      Awadallah, Ahmed Hassan  and
      Celikyilmaz, Asli  and
      Liu, Yang  and
      Qiu, Xipeng  and
      Radev, Dragomir",
    booktitle = "Proceedings of the 2021 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies",
    month = jun,
    year = "2021",
    address = "Online",
    publisher = "Association for Computational Linguistics",
    url = "https://aclanthology.org/2021.naacl-main.472",
    doi = "10.18653/v1/2021.naacl-main.472",
    pages = "5905--5921"
}"""

_NARRATIVE_QA_CITATION = r"""
@article{kocisky-etal-2018-narrativeqa,
    title = "The {N}arrative{QA} Reading Comprehension Challenge",
    author = "Ko{\v{c}}isk{\'y}, Tom{\'a}{\v{s}}  and
      Schwarz, Jonathan  and
      Blunsom, Phil  and
      Dyer, Chris  and
      Hermann, Karl Moritz  and
      Melis, G{\'a}bor  and
      Grefenstette, Edward",
    journal = "Transactions of the Association for Computational Linguistics",
    volume = "6",
    year = "2018",
    address = "Cambridge, MA",
    publisher = "MIT Press",
    url = "https://aclanthology.org/Q18-1023",
    doi = "10.1162/tacl_a_00023",
    pages = "317--328"
}"""

_GOV_REPORT_CITATION = r"""
@inproceedings{huang-etal-2021-efficient,
    title = "Efficient Attentions for Long Document Summarization",
    author = "Huang, Luyang  and
      Cao, Shuyang  and
      Parulian, Nikolaus  and
      Ji, Heng  and
      Wang, Lu",
    booktitle = "Proceedings of the 2021 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies",
    month = jun,
    year = "2021",
    address = "Online",
    publisher = "Association for Computational Linguistics",
    url = "https://aclanthology.org/2021.naacl-main.112",
    doi = "10.18653/v1/2021.naacl-main.112",
    pages = "1419--1436"
}"""

_QUALITY_CITATION = """\
@inproceedings{pang-etal-2022-quality,
    title = "{Q}u{ALITY}: Question Answering with Long Input Texts, Yes!",
    author = "Pang, Richard Yuanzhe  and
      Parrish, Alicia  and
      Joshi, Nitish  and
      Nangia, Nikita  and
      Phang, Jason  and
      Chen, Angelica  and
      Padmakumar, Vishakh  and
      Ma, Johnny  and
      Thompson, Jana  and
      He, He  and
      Bowman, Samuel",
    booktitle = "Proceedings of the 2022 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies",
    month = jul,
    year = "2022",
    address = "Seattle, United States",
    publisher = "Association for Computational Linguistics",
    url = "https://aclanthology.org/2022.naacl-main.391",
    doi = "10.18653/v1/2022.naacl-main.391",
    pages = "5336--5358"
}
"""
_SQUALITY_CITATION = """\
@inproceedings{wang-etal-2022-squality,
    title = "{SQ}u{ALITY}: Building a Long-Document Summarization Dataset the Hard Way",
    author = "Wang, Alex  and
      Pang, Richard Yuanzhe  and
      Chen, Angelica  and
      Phang, Jason  and
      Bowman, Samuel R.",
    booktitle = "Proceedings of the 2022 Conference on Empirical Methods in Natural Language Processing",
    month = dec,
    year = "2022",
    address = "Abu Dhabi, United Arab Emirates",
    publisher = "Association for Computational Linguistics",
    url = "https://aclanthology.org/2022.emnlp-main.75",
    pages = "1139--1156"
}
"""
_MUSIQUE_CITATION = """\
@article{trivedi-etal-2022-musique,
    title = "♫ {M}u{S}i{Q}ue: Multihop Questions via Single-hop Question Composition",
    author = "Trivedi, Harsh  and
      Balasubramanian, Niranjan  and
      Khot, Tushar  and
      Sabharwal, Ashish",
    journal = "Transactions of the Association for Computational Linguistics",
    volume = "10",
    year = "2022",
    address = "Cambridge, MA",
    publisher = "MIT Press",
    url = "https://aclanthology.org/2022.tacl-1.31",
    doi = "10.1162/tacl_a_00475",
    pages = "539--554"
}
"""

_SPACE_CITATION = """\
@article{angelidis-etal-2021-extractive,
    title = "Extractive Opinion Summarization in Quantized Transformer Spaces",
    author = "Angelidis, Stefanos  and
      Amplayo, Reinald Kim  and
      Suhara, Yoshihiko  and
      Wang, Xiaolan  and
      Lapata, Mirella",
    journal = "Transactions of the Association for Computational Linguistics",
    volume = "9",
    year = "2021",
    address = "Cambridge, MA",
    publisher = "MIT Press",
    url = "https://aclanthology.org/2021.tacl-1.17",
    doi = "10.1162/tacl_a_00366",
    pages = "277--293"
}
"""
_BOOK_SUM_CITATION = """\
@inproceedings{kryscinski-etal-2022-booksum,
    title = "{BOOKSUM}: A Collection of Datasets for Long-form Narrative Summarization",
    author = "Kryscinski, Wojciech  and
      Rajani, Nazneen  and
      Agarwal, Divyansh  and
      Xiong, Caiming  and
      Radev, Dragomir",
    booktitle = "Findings of the Association for Computational Linguistics: EMNLP 2022",
    month = dec,
    year = "2022",
    address = "Abu Dhabi, United Arab Emirates",
    publisher = "Association for Computational Linguistics",
    url = "https://aclanthology.org/2022.findings-emnlp.488",
    pages = "6536--6558"
}
"""

FEATURE_TO_TYPE = {
    "id": "string",
    "pid": "string",
    "input": "string",
    "output": "string",
    "document_start_index": "int32",
    "document_end_index": "int32",
    "query_start_index": "int32",
    "query_end_index": "int32",
    "truncation_seperator": "string"
}


class ZeroScrollsConfig(datasets.BuilderConfig):
    """BuilderConfig for SCROLLS."""

    def __init__(self, features, data_url, citation, url, **kwargs):
        """BuilderConfig for SCROLLS.
        Args:
          features: `list[string]`, list of the features that will appear in the
            feature dict. Should not include "label".
          data_url: `string`, url to download the zip file from.
          citation: `string`, citation for the data set.
          url: `string`, url for information about the data set.
          label_classes: `list[string]`, the list of classes for the label if the
            label is present as a string. Non-string labels will be cast to either
            'False' or 'True'.
          **kwargs: keyword arguments forwarded to super.
        """
        super(ZeroScrollsConfig, self).__init__(version=datasets.Version("1.0.0"), **kwargs)
        self.features = features
        self.data_url = data_url
        self.citation = citation
        self.url = url


class QualityConfig(ZeroScrollsConfig):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.hard_only = False


class ZeroScrolls(datasets.GeneratorBasedBuilder):
    """The ZerpSCROLLS benchmark."""

    features = list(FEATURE_TO_TYPE.keys())
    features_with_multiple_inder_docs = features + ["inner_docs_start_indices"]
    DEFAULT_WRITER_BATCH_SIZE = 1000  # because Narrative QA is a rather large dataset
    BUILDER_CONFIGS = [
        ZeroScrollsConfig(
            name="summ_screen_fd",
            description=_SUMM_SCREEN_DESCRIPTION,
            features=features,
            data_url="https://huggingface.co/datasets/tau/zero_scrolls/resolve/main/summ_screen_fd.zip",
            citation=_SUMM_SCREEN_CITATION,
            url="https://github.com/mingdachen/SummScreen",
        ),
        ZeroScrollsConfig(
            name="qasper",
            description=_QASPER_DESCRIPTION,
            features=features,
            data_url="https://huggingface.co/datasets/tau/zero_scrolls/resolve/main/qasper.zip",
            citation=_QASPER_CITATION,
            url="https://allenai.org/project/qasper",
        ),
        ZeroScrollsConfig(
            name="qmsum",
            description=_QMSUM_DESCRIPTION,
            features=features,
            data_url="https://huggingface.co/datasets/tau/zero_scrolls/resolve/main/qmsum.zip",
            citation=_QMSUM_CITATION,
            url="https://github.com/Yale-LILY/QMSum",
        ),
        ZeroScrollsConfig(
            name="narrative_qa",
            description=_NARRATIVE_QA_DESCRIPTION,
            features=features,
            data_url="https://huggingface.co/datasets/tau/zero_scrolls/resolve/main/narrative_qa.zip",
            citation=_NARRATIVE_QA_CITATION,
            url="https://deepmind.com/research/publications/narrativeqa-reading-comprehension-challenge",
        ),
        ZeroScrollsConfig(
            name="gov_report",
            description=_GOV_REPORT_DESCRIPTION,
            features=features,
            data_url="https://huggingface.co/datasets/tau/zero_scrolls/resolve/main/gov_report.zip",
            citation=_GOV_REPORT_CITATION,
            url="https://gov-report-data.github.io/",
        ),
        QualityConfig(
            name="quality",
            description=_QUALITY_DESCRIPTION,
            features=features,
            data_url="https://huggingface.co/datasets/tau/zero_scrolls/resolve/main/quality.zip",
            citation=_QUALITY_CITATION,
            url="https://github.com/nyu-mll/quality",
        ),
        ZeroScrollsConfig(
            name="squality",
            description=_SQUALITY_DESCRIPTION,
            features=features,
            data_url="https://huggingface.co/datasets/tau/zero_scrolls/resolve/main/squality.zip",
            citation=_SQUALITY_CITATION,
            url="https://github.com/nyu-mll/SQuALITY",
        ),
        ZeroScrollsConfig(
            name="musique",
            description=_MUSIQUE_DESCRIPTION,
            features=features_with_multiple_inder_docs,
            data_url="https://huggingface.co/datasets/tau/zero_scrolls/resolve/main/musique.zip",
            citation=_MUSIQUE_CITATION,
            url="https://github.com/stonybrooknlp/musique",
        ),
        ZeroScrollsConfig(
            name="space_digest",
            description=_SPACE_DIGEST_DESCRIPTION,
            features=features_with_multiple_inder_docs,
            data_url="https://huggingface.co/datasets/tau/zero_scrolls/resolve/main/space_digest.zip",
            citation=_SPACE_CITATION,
            url="https://github.com/stangelid/qt",
        ),
        ZeroScrollsConfig(
            name="book_sum_sort",
            description=_BOOK_SUM_DESCRIPTION,
            features=features_with_multiple_inder_docs,
            data_url="https://huggingface.co/datasets/tau/zero_scrolls/resolve/main/book_sum_sort.zip",
            citation=_BOOK_SUM_CITATION,
            url="https://github.com/salesforce/booksum",
        ),
    ]

    def _info(self):

        features = {feature: datasets.Value(FEATURE_TO_TYPE[feature]) for feature in self.config.features if
                    feature != "inner_docs_start_indices"}
        if "inner_docs_start_indices" in self.config.features:
            features["inner_docs_start_indices"] = datasets.Sequence(datasets.Value("int32"))

        return datasets.DatasetInfo(
            description=_ZERO_SCROLLS_DESCRIPTION + self.config.description,
            features=datasets.Features(features),
            homepage=self.config.url,
            citation=self.config.citation + "\n" + _SCROLLS_CITATION + "\n" + _ZERO_SCROLLS_CITATION,
        )

    def _split_generators(self, dl_manager):
        dl_dir = dl_manager.download_and_extract(self.config.data_url)
        task_name = _get_task_name_from_data_url(self.config.data_url)
        dl_dir = os.path.join(dl_dir, task_name)

        data_files = {} if self.config.data_files is not None else None
        if data_files is not None:
            for split, paths in self.config.data_files.items():
                data_files[split] = paths[0]

        return [
            datasets.SplitGenerator(
                name=datasets.Split.VALIDATION,
                gen_kwargs={
                    "data_file": os.path.join(dl_dir, "validation.jsonl"),
                    "split": datasets.Split.VALIDATION,
                },
            ),
            datasets.SplitGenerator(
                name=datasets.Split.TEST,
                gen_kwargs={
                    "data_file": os.path.join(dl_dir, "test.jsonl") if data_files is None else data_files["test"],
                    "split": datasets.Split.TEST,
                },
            ),
        ]

    def _generate_examples(self, data_file, split):
        with open(data_file, encoding="utf-8") as f:
            for line in f:
                row = json.loads(line)

                if self.config.name == "quality":
                    is_hard = row.pop("is_hard", False)
                    if self.config.hard_only and not is_hard:
                        continue

                yield row["pid"], row


def _get_task_name_from_data_url(data_url):
    return data_url.split("/")[-1].split(".")[0]