|
| 1 | +# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. |
| 2 | +# Copyright 2020 The TensorFlow Datasets Authors and the HuggingFace Datasets Authors. |
| 3 | +# |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +# you may not use this file except in compliance with the License. |
| 6 | +# You may obtain a copy of the License at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | + |
| 16 | +import collections |
| 17 | +import os |
| 18 | +import hashlib |
| 19 | + |
| 20 | +from paddle.dataset.common import md5file |
| 21 | +from paddlenlp.utils.downloader import get_path_from_url, _decompress |
| 22 | +from paddlenlp.utils.env import DATA_HOME |
| 23 | +from paddlenlp.utils.log import logger |
| 24 | +from . import DatasetBuilder |
| 25 | + |
| 26 | + |
| 27 | +class CnnDailymail(DatasetBuilder): |
| 28 | + """ |
| 29 | + CNN/DailyMail non-anonymized summarization dataset. |
| 30 | + The CNN / DailyMail Dataset is an English-language dataset containing |
| 31 | + just over 300k unique news articles as written by journalists at CNN |
| 32 | + nd the Daily Mail. The current version supports both extractive and |
| 33 | + abstractive summarization, though the original version was created |
| 34 | + for machine reading and comprehension and abstractive question answering. |
| 35 | +
|
| 36 | + Version 1.0.0 aimed to support supervised neural methodologies for machine |
| 37 | + reading and question answering with a large amount of real natural language |
| 38 | + training data and released about 313k unique articles and nearly 1M Cloze |
| 39 | + style questions to go with the articles. |
| 40 | + Versions 2.0.0 and 3.0.0 changed the structure of the dataset to support |
| 41 | + summarization rather than question answering. Version 3.0.0 provided a |
| 42 | + non-anonymized version of the data, whereas both the previous versions were |
| 43 | + preprocessed to replace named entities with unique identifier labels. |
| 44 | +
|
| 45 | + An updated version of the code that does not anonymize the data is available |
| 46 | + at https://github.com/abisee/cnn-dailymail. |
| 47 | + """ |
| 48 | + lazy = False |
| 49 | + META_INFO = collections.namedtuple("META_INFO", ("file", "url", "md5")) |
| 50 | + SPLITS = { |
| 51 | + "train": META_INFO( |
| 52 | + "all_train.txt", |
| 53 | + "https://paddlenlp.bj.bcebos.com/datasets/cnn_dailymail/all_train.txt", |
| 54 | + "c8ca98cfcb6cf3f99a404552568490bc"), |
| 55 | + "dev": META_INFO( |
| 56 | + "all_val.txt", |
| 57 | + "https://paddlenlp.bj.bcebos.com/datasets/cnn_dailymail/all_val.txt", |
| 58 | + "83a3c483b3ed38b1392285bed668bfee"), |
| 59 | + "test": META_INFO( |
| 60 | + "all_test.txt", |
| 61 | + "https://paddlenlp.bj.bcebos.com/datasets/cnn_dailymail/all_test.txt", |
| 62 | + "4f3ac04669934dbc746b7061e68a0258") |
| 63 | + } |
| 64 | + cnn_dailymail = { |
| 65 | + "cnn": { |
| 66 | + "url": |
| 67 | + "https://paddlenlp.bj.bcebos.com/datasets/cnn_dailymail/cnn_stories.tgz", |
| 68 | + "md5": "85ac23a1926a831e8f46a6b8eaf57263", |
| 69 | + "file_num": 92579 |
| 70 | + }, |
| 71 | + "dailymail": { |
| 72 | + "url": |
| 73 | + "https://paddlenlp.bj.bcebos.com/datasets/cnn_dailymail/dailymail_stories.tgz", |
| 74 | + "md5": "f9c5f565e8abe86c38bfa4ae8f96fd72", |
| 75 | + "file_num": 219506 |
| 76 | + } |
| 77 | + } |
| 78 | + |
| 79 | + def _read_text_file(self, text_file): |
| 80 | + lines = [] |
| 81 | + with open(text_file, "r", encoding="utf8") as f: |
| 82 | + for line in f: |
| 83 | + lines.append(line.strip()) |
| 84 | + return lines |
| 85 | + |
| 86 | + def _get_url_hashes(self, path): |
| 87 | + """Get hashes of urls in file.""" |
| 88 | + urls = self._read_text_file(path) |
| 89 | + |
| 90 | + def url_hash(u): |
| 91 | + h = hashlib.sha1() |
| 92 | + try: |
| 93 | + u = u.encode("utf-8") |
| 94 | + except UnicodeDecodeError: |
| 95 | + logger.error("Cannot hash url: %s", u) |
| 96 | + h.update(u) |
| 97 | + return h.hexdigest() |
| 98 | + |
| 99 | + return {url_hash(u): True for u in urls} |
| 100 | + |
| 101 | + def _get_hash_from_path(self, p): |
| 102 | + """Extract hash from path.""" |
| 103 | + basename = os.path.basename(p) |
| 104 | + return basename[0:basename.find(".story")] |
| 105 | + |
| 106 | + def _find_files(self, dl_paths, publisher, url_dict): |
| 107 | + """Find files corresponding to urls.""" |
| 108 | + if publisher == "cnn": |
| 109 | + top_dir = os.path.join(dl_paths["cnn"], "stories") |
| 110 | + elif publisher == "dailymail": |
| 111 | + top_dir = os.path.join(dl_paths["dailymail"], "stories") |
| 112 | + else: |
| 113 | + logger.error("Unsupported publisher: %s", publisher) |
| 114 | + files = sorted(os.listdir(top_dir)) |
| 115 | + |
| 116 | + ret_files = [] |
| 117 | + for p in files: |
| 118 | + if self._get_hash_from_path(p) in url_dict: |
| 119 | + ret_files.append(os.path.join(top_dir, p)) |
| 120 | + return ret_files |
| 121 | + |
| 122 | + def _subset_filenames(self, dl_paths, split): |
| 123 | + """Get filenames for a particular split.""" |
| 124 | + # Get filenames for a split. |
| 125 | + urls = self._get_url_hashes(dl_paths[split]) |
| 126 | + cnn = self._find_files(dl_paths, "cnn", urls) |
| 127 | + dm = self._find_files(dl_paths, "dailymail", urls) |
| 128 | + return cnn + dm |
| 129 | + |
| 130 | + def _get_art_abs(self, story_file, version): |
| 131 | + """Get abstract (highlights) and article from a story file path.""" |
| 132 | + # Based on https://github.com/abisee/cnn-dailymail/blob/master/ |
| 133 | + # make_datafiles.py |
| 134 | + |
| 135 | + lines = self._read_text_file(story_file) |
| 136 | + |
| 137 | + # The github code lowercase the text and we removed it in 3.0.0. |
| 138 | + |
| 139 | + # Put periods on the ends of lines that are missing them |
| 140 | + # (this is a problem in the dataset because many image captions don't end in |
| 141 | + # periods; consequently they end up in the body of the article as run-on |
| 142 | + # sentences) |
| 143 | + def fix_missing_period(line): |
| 144 | + """Adds a period to a line that is missing a period.""" |
| 145 | + if "@highlight" in line: |
| 146 | + return line |
| 147 | + if not line: |
| 148 | + return line |
| 149 | + if line[-1] in [ |
| 150 | + ".", "!", "?", "...", "'", "`", '"', "\u2019", "\u201d", ")" |
| 151 | + ]: |
| 152 | + return line |
| 153 | + return line + " ." |
| 154 | + |
| 155 | + lines = [fix_missing_period(line) for line in lines] |
| 156 | + |
| 157 | + # Separate out article and abstract sentences |
| 158 | + article_lines = [] |
| 159 | + highlights = [] |
| 160 | + next_is_highlight = False |
| 161 | + for line in lines: |
| 162 | + if not line: |
| 163 | + continue # empty line |
| 164 | + elif line.startswith("@highlight"): |
| 165 | + next_is_highlight = True |
| 166 | + elif next_is_highlight: |
| 167 | + highlights.append(line) |
| 168 | + else: |
| 169 | + article_lines.append(line) |
| 170 | + |
| 171 | + # Make article into a single string |
| 172 | + article = " ".join(article_lines) |
| 173 | + |
| 174 | + if version >= "2.0.0": |
| 175 | + abstract = "\n".join(highlights) |
| 176 | + else: |
| 177 | + abstract = " ".join(highlights) |
| 178 | + |
| 179 | + return article, abstract |
| 180 | + |
| 181 | + def _get_data(self, mode): |
| 182 | + """ Check and download Dataset """ |
| 183 | + dl_paths = {} |
| 184 | + version = self.config.get("version", "3.0.0") |
| 185 | + if version not in ["1.0.0", "2.0.0", "3.0.0"]: |
| 186 | + raise ValueError("Unsupported version: %s" % version) |
| 187 | + dl_paths["version"] = version |
| 188 | + default_root = os.path.join(DATA_HOME, self.__class__.__name__) |
| 189 | + for k, v in self.cnn_dailymail.items(): |
| 190 | + dir_path = os.path.join(default_root, k) |
| 191 | + if not os.path.exists(dir_path): |
| 192 | + get_path_from_url(v["url"], default_root, v["md5"]) |
| 193 | + file_num = len(os.listdir(os.path.join(dir_path, "stories"))) |
| 194 | + if file_num != v["file_num"]: |
| 195 | + logger.warning( |
| 196 | + "Number of %s stories is %d != %d, decompress again." % |
| 197 | + (k, file_num, v["file_num"])) |
| 198 | + _decompress( |
| 199 | + os.path.join(default_root, os.path.basename(v["url"]))) |
| 200 | + dl_paths[k] = dir_path |
| 201 | + filename, url, data_hash = self.SPLITS[mode] |
| 202 | + fullname = os.path.join(default_root, filename) |
| 203 | + if not os.path.exists(fullname) or (data_hash and |
| 204 | + not md5file(fullname) == data_hash): |
| 205 | + get_path_from_url(url, default_root, data_hash) |
| 206 | + dl_paths[mode] = fullname |
| 207 | + return dl_paths |
| 208 | + |
| 209 | + def _read(self, dl_paths, split): |
| 210 | + files = self._subset_filenames(dl_paths, split) |
| 211 | + for p in files: |
| 212 | + article, highlights = self._get_art_abs(p, dl_paths["version"]) |
| 213 | + if not article or not highlights: |
| 214 | + continue |
| 215 | + yield { |
| 216 | + "article": article, |
| 217 | + "highlights": highlights, |
| 218 | + "id": self._get_hash_from_path(p), |
| 219 | + } |
0 commit comments