Datasets:

Modalities:
Text
Languages:
English
Libraries:
Datasets
License:
File size: 13,349 Bytes
e16adeb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f94a939
e16adeb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
"""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))