"""GovReport: The Government Report Hierarchical Question-summary Generation Dataset.""" import json import datasets logger = datasets.logging.get_logger(__name__) _CITATION = """\ @inproceedings{cao-wang-2022-hibrids, title = "{HIBRIDS}: Attention with Hierarchical Biases for Structure-aware Long Document Summarization", author = "Cao, Shuyang and Wang, Lu", 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.58", pages = "786--807", abstract = "Document structure is critical for efficient information consumption. However, it is challenging to encode it efficiently into the modern Transformer architecture. In this work, we present HIBRIDS, which injects Hierarchical Biases foR Incorporating Document Structure into attention score calculation. We further present a new task, hierarchical question-summary generation, for summarizing salient content in the source document into a hierarchy of questions and summaries, where each follow-up question inquires about the content of its parent question-summary pair. We also annotate a new dataset with 6,153 question-summary hierarchies labeled on government reports. Experiment results show that our model produces better question-summary hierarchies than comparisons on both hierarchy quality and content coverage, a finding also echoed by human judges. Additionally, our model improves the generation of long-form summaries from long government reports and Wikipedia articles, as measured by ROUGE scores.", } """ _DESCRIPTION = """\ GovReport-QS hierarchical question-summary generation dataset. There are two configs: - paragraph: paragraph-level annotated data - document: aggregated paragraph-level annotated data for the same document """ _URL = "https://huggingface.co/datasets/launch/gov_report_qs/resolve/main/data/" _URLS = { "train": _URL + "train.jsonl", "valid": _URL + "valid.jsonl", "test": _URL + "test.jsonl", } def _recursive_load(section, keep_letter=False, depth=0, section_title_list=None, aligned_section_titles=None): aligned_hierarchies = set() alignment = set() sections = [] if section["section_title"] != "Letter" or (section["section_title"] == "Letter" and keep_letter): section_title = " ".join(section["section_title"].strip().split()) section_paragraphs = "\n".join([" ".join(paragraph.strip().split()) for paragraph in section["paragraphs"]]) if section_title: section_title_list = section_title_list + (section_title,) child_sections = [] for subsection in section["subsections"]: child_section, child_aligned_hierarchies = _recursive_load(subsection, keep_letter, depth + 1, section_title_list, aligned_section_titles) child_sections.extend(child_section) aligned_hierarchies.update(child_aligned_hierarchies) for hierarchy_id, aligned_section_title in enumerate(aligned_section_titles): if section_title_list in aligned_section_title: aligned_hierarchies.add(hierarchy_id) alignment.add(f'h{hierarchy_id}_full') for hierarchy_id in aligned_hierarchies: if f'h{hierarchy_id}_full' not in alignment: alignment.add(f'h{hierarchy_id}_title') sections.append({ "title": section_title, "paragraphs": section_paragraphs, "depth": depth, "alignment": " ".join(alignment), }) sections.extend(child_sections) else: for subsection in section["subsections"]: child_sections, child_aligned_hierarchies = _recursive_load(subsection, keep_letter, depth, section_title_list, aligned_section_titles) sections.extend(child_sections) aligned_hierarchies.update(child_aligned_hierarchies) return sections, aligned_hierarchies def _recursive_load_qs_pairs(qs_pair, current_id=0, parent_id=-1): qs_pairs = [] qs_pairs.append({ "question": qs_pair["question"], "summary": qs_pair["answer"], "parent_pair_index": parent_id, }) child_id = current_id + 1 for child_qs_pair in qs_pair["child_questions"]: child_qs_pairs, current_child_id = _recursive_load_qs_pairs(child_qs_pair, child_id, current_id) qs_pairs.extend(child_qs_pairs) child_id = current_child_id return qs_pairs, child_id class GovReportQSConfig(datasets.BuilderConfig): """BuilderConfig for GovReport.""" def __init__(self, **kwargs): """BuilderConfig for GovReport. Args: **kwargs: keyword arguments forwarded to super. """ super(GovReportQSConfig, self).__init__(**kwargs) class GovReportQS(datasets.GeneratorBasedBuilder): VERSION = datasets.Version("1.0.0") DEFAULT_CONFIG_NAME = "paragraph" BUILDER_CONFIGS = [ GovReportQSConfig( name="paragraph", version=VERSION, description="paragraph-level annotated data", ), GovReportQSConfig( name="document", version=VERSION, description="aggregated paragraph-level annotated data for the same document", ), ] def _info(self): if self.config.name == "paragraph": features = datasets.Features( { "doc_id": datasets.Value("string"), "summary_paragraph_index": datasets.Value("int32"), "document_sections": datasets.features.Sequence( { "title": datasets.Value("string"), "paragraphs": datasets.Value("string"), "depth": datasets.Value("int32"), } ), "question_summary_pairs": datasets.features.Sequence( { "question": datasets.Value("string"), "summary": datasets.Value("string"), "parent_pair_index": datasets.Value("int32"), } ), } ) elif self.config.name == "document": features = datasets.Features( { "doc_id": datasets.Value("string"), "document_sections": datasets.features.Sequence( { "title": datasets.Value("string"), "paragraphs": datasets.Value("string"), "depth": datasets.Value("int32"), "alignment": datasets.Value("string") } ), "question_summary_pairs": datasets.features.Sequence( { "question": datasets.Value("string"), "summary": datasets.Value("string"), "parent_pair_index": datasets.Value("int32"), "summary_paragraph_index": datasets.Value("int32"), } ), } ) else: raise ValueError("Unsupported config name {}".format(self.config.name)) return datasets.DatasetInfo( description=_DESCRIPTION, features=features, supervised_keys=None, homepage="", citation=_CITATION, ) def _split_generators(self, dl_manager): downloaded_files = dl_manager.download_and_extract(_URLS) return [ datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={"filepath": downloaded_files["train"]}), datasets.SplitGenerator(name=datasets.Split.VALIDATION, gen_kwargs={"filepath": downloaded_files["valid"]}), datasets.SplitGenerator(name=datasets.Split.TEST, gen_kwargs={"filepath": downloaded_files["test"]}), ] def _generate_examples(self, filepath): """This function returns the examples in the raw (text) form.""" logger.info(f"generating examples from = {filepath}") with open(filepath) as f: key = 0 for line in f: line = line.strip() if not line: continue data = json.loads(line) doc_id = data["id"] annotated_hierarchies = data["annotated_hierarchies"] aligned_section_titles = [set([tuple([" ".join(title.strip().split()) for title in section]) for section in hierarchy["aligned_sections"]]) for hierarchy in annotated_hierarchies] if doc_id.startswith("GAO"): document_sections = [] for lv1_section in data["report"]: document_sections.extend(_recursive_load(lv1_section, keep_letter=False, depth=1, section_title_list=tuple(), aligned_section_titles=aligned_section_titles)[0]) elif doc_id.startswith("CRS"): document_sections = _recursive_load(data["reports"], keep_letter=True, depth=0, section_title_list=tuple(), aligned_section_titles=aligned_section_titles)[0] else: raise ValueError("Invalid document id {}".format(doc_id)) annotated_qs_pairs = [] for hierarchy_id, annotated_hierarchy in enumerate(annotated_hierarchies): summary_paragraph_index = annotated_hierarchy["paragraph_index"] qs_pairs = [] current_id = 0 for lv1_qs_pair in annotated_hierarchy["questions"]: child_qs_pairs, current_id = _recursive_load_qs_pairs(lv1_qs_pair, current_id=current_id, parent_id=-1) qs_pairs.extend(child_qs_pairs) annotated_qs_pairs.append({ "hierarchy_id": hierarchy_id, "summary_paragraph_index": summary_paragraph_index, "question_summary_pairs": qs_pairs, }) if self.config.name == "paragraph": for annotated_qs_pair in annotated_qs_pairs: _id = f"{doc_id}_{annotated_qs_pair['summary_paragraph_index']}_{key}" aligned_sections = [] for section in document_sections: if f"h{annotated_qs_pair['hierarchy_id']}_full" in section["alignment"]: # both title and paragraphs aligned_sections.append({ "title": section["title"], "paragraphs": section["paragraphs"], "depth": section["depth"], }) elif f"f{annotated_qs_pair['hierarchy_id']}_title" in section["alignment"]: # only title aligned_sections.append({ "title": section["title"], "paragraphs": "", "depth": section["depth"], }) if aligned_sections: yield _id, { "doc_id": doc_id, "summary_paragraph_index": annotated_qs_pair["summary_paragraph_index"], "document_sections": aligned_sections, "question_summary_pairs": annotated_qs_pair["question_summary_pairs"], } else: print(f"{doc_id}_{key} has no aligned sections") key += 1 elif self.config.name == "document": _id = f"{doc_id}" question_summary_pairs = [] for annotated_qs_pair in annotated_qs_pairs: summary_paragraph_index = annotated_qs_pair["summary_paragraph_index"] for qs_pair in annotated_qs_pair["question_summary_pairs"]: question_summary_pairs.append({ "question": qs_pair["question"], "summary": qs_pair["summary"], "parent_pair_index": qs_pair["parent_pair_index"], "summary_paragraph_index": summary_paragraph_index, }) yield _id, { "doc_id": doc_id, "document_sections": document_sections, "question_summary_pairs": question_summary_pairs, } else: raise ValueError("Unsupported config name {}".format(self.config.name))