File size: 8,282 Bytes
81aded6
 
 
9e84715
 
 
 
 
 
28b05c7
 
 
9e84715
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81aded6
9e84715
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81aded6
9e84715
 
 
 
 
81aded6
9e84715
81aded6
9e84715
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81aded6
9e84715
81aded6
9e84715
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81aded6
9e84715
 
 
 
 
 
 
 
 
 
f3619fc
9e84715
 
81aded6
9e84715
 
 
 
 
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
# WARNING: Please, do not use the code in this script as a template to create another script:
# - It is a bad practice to use `datasets.load_dataset` inside a loading script. Please, avoid doing it.

import json
import math

import datasets


logger = datasets.logging.get_logger(__name__)


_CITATION = """\
@ONLINE {wikidump,
    author = {Wikimedia Foundation},
    title  = {Wikimedia Downloads},
    url    = {https://dumps.wikimedia.org}
}
"""

_DESCRIPTION = """\
Wikipedia version split into plain text snippets for dense semantic indexing.
"""

_LICENSE = (
    "This work is licensed under the Creative Commons Attribution-ShareAlike "
    "3.0 Unported License. To view a copy of this license, visit "
    "http://creativecommons.org/licenses/by-sa/3.0/ or send a letter to "
    "Creative Commons, PO Box 1866, Mountain View, CA 94042, USA."
)


def wiki40b_article_snippets(article, passage_len=100, overlap=0):
    paragraphs = article["text"].split("\n")
    aticle_idx = paragraphs.index("_START_ARTICLE_") + 1
    article_title = paragraphs[aticle_idx] if aticle_idx < len(paragraphs) else ""
    section_indices = [i + 1 for i, par in enumerate(paragraphs[:-1]) if par == "_START_SECTION_"]
    par_tabs = [par.split(" ") for par in paragraphs]
    word_map = [
        (i, len(" ".join(par[:j])), w)
        for i, par in enumerate(par_tabs)
        if not par[0].startswith("_START_")
        for j, w in enumerate(par)
        if i > 0
    ]
    step_size = passage_len - overlap
    passages = []
    for i in range(math.ceil(len(word_map) / step_size)):
        pre_toks = word_map[i * step_size : i * step_size + passage_len]
        start_section_id = max([0] + [j for j in section_indices if j <= pre_toks[0][0]])
        section_ids = [j for j in section_indices if j >= start_section_id and j <= pre_toks[-1][0]]
        section_ids = section_ids if len(section_ids) > 0 else [0]
        passage_text = " ".join([w for p_id, s_id, w in pre_toks])
        passages += [
            {
                "article_title": article_title,
                "section_title": " & ".join([paragraphs[j] for j in section_ids]),
                "wiki_id": article["wikidata_id"],
                "start_paragraph": pre_toks[0][0],
                "start_character": pre_toks[0][1],
                "end_paragraph": pre_toks[-1][0],
                "end_character": pre_toks[-1][1] + len(pre_toks[-1][2]) + 1,
                "passage_text": passage_text.replace("_NEWLINE_", "\n"),
            }
        ]
    return passages


def wikipedia_article_snippets(article, passage_len=100, overlap=0):
    paragraphs = [par for par in article["text"].split("\n") if not par.startswith("Category:")]
    if "References" in paragraphs:
        paragraphs = paragraphs[: paragraphs.index("References")]
    article_title = article["title"]
    section_indices = [
        i + 1
        for i, par in enumerate(paragraphs[:-2])
        if paragraphs[i] == "" and paragraphs[i + 1] != "" and paragraphs[i + 2] != ""
    ]
    par_tabs = [par.split(" ") for par in paragraphs]
    word_map = [(i, len(" ".join(par[:j])), w) for i, par in enumerate(par_tabs) for j, w in enumerate(par)]
    step_size = passage_len - overlap
    passages = []
    for i in range(math.ceil(len(word_map) / step_size)):
        pre_toks = word_map[i * step_size : i * step_size + passage_len]
        start_section_id = max([0] + [j for j in section_indices if j <= pre_toks[0][0]])
        section_ids = [j for j in section_indices if start_section_id <= j <= pre_toks[-1][0]]
        section_ids = section_ids if len(section_ids) > 0 else [-1]
        passage_text = " ".join([w for p_id, s_id, w in pre_toks])
        passages += [
            {
                "article_title": article_title,
                "section_title": " & ".join(["Start" if j == -1 else paragraphs[j].strip() for j in section_ids]),
                "wiki_id": article_title.replace(" ", "_"),
                "start_paragraph": pre_toks[0][0],
                "start_character": pre_toks[0][1],
                "end_paragraph": pre_toks[-1][0],
                "end_character": pre_toks[-1][1] + len(pre_toks[-1][2]) + 1,
                "passage_text": passage_text,
            }
        ]
    return passages


_SPLIT_FUNCTION_MAP = {
    "wikipedia": wikipedia_article_snippets,
    "wiki40b": wiki40b_article_snippets,
}


def generate_snippets(wikipedia, split_function, passage_len=100, overlap=0):
    for i, article in enumerate(wikipedia):
        for doc in split_function(article, passage_len, overlap):
            part_id = json.dumps(
                {
                    "datasets_id": i,
                    "wiki_id": doc["wiki_id"],
                    "sp": doc["start_paragraph"],
                    "sc": doc["start_character"],
                    "ep": doc["end_paragraph"],
                    "ec": doc["end_character"],
                }
            )
            doc["_id"] = part_id
            doc["datasets_id"] = i
            yield doc


class WikiSnippetsConfig(datasets.BuilderConfig):
    """BuilderConfig for WikiSnippets."""

    def __init__(
        self, wikipedia_name="wiki40b", wikipedia_version_name="en", snippets_length=100, snippets_overlap=0, **kwargs
    ):
        """BuilderConfig for WikiSnippets.
        Args:
          **kwargs: keyword arguments forwarded to super.
        """
        super(WikiSnippetsConfig, self).__init__(**kwargs)
        self.wikipedia_name = wikipedia_name
        self.wikipedia_version_name = wikipedia_version_name
        self.snippets_length = snippets_length
        self.snippets_overlap = snippets_overlap


class WikiSnippets(datasets.GeneratorBasedBuilder):
    BUILDER_CONFIG_CLASS = WikiSnippetsConfig
    BUILDER_CONFIGS = [
        WikiSnippetsConfig(
            name="wiki40b_en_100_0",
            version=datasets.Version("1.0.0"),
            wikipedia_name="wiki40b",
            wikipedia_version_name="en",
            snippets_length=100,
            snippets_overlap=0,
        ),
        WikiSnippetsConfig(
            name="wikipedia_en_100_0",
            version=datasets.Version("2.0.0"),
            wikipedia_name="wikipedia",
            wikipedia_version_name="20220301.en",
            snippets_length=100,
            snippets_overlap=0,
        ),
    ]

    test_dummy_data = False

    def _info(self):
        return datasets.DatasetInfo(
            description=_DESCRIPTION,
            features=datasets.Features(
                {
                    "_id": datasets.Value("string"),
                    "datasets_id": datasets.Value("int32"),
                    "wiki_id": datasets.Value("string"),
                    "start_paragraph": datasets.Value("int32"),
                    "start_character": datasets.Value("int32"),
                    "end_paragraph": datasets.Value("int32"),
                    "end_character": datasets.Value("int32"),
                    "article_title": datasets.Value("string"),
                    "section_title": datasets.Value("string"),
                    "passage_text": datasets.Value("string"),
                }
            ),
            supervised_keys=None,
            homepage="https://dumps.wikimedia.org",
            citation=_CITATION,
        )

    def _split_generators(self, dl_manager):
        # WARNING: It is a bad practice to use `datasets.load_dataset` inside a loading script. Please, avoid doing it.
        wikipedia = datasets.load_dataset(
            path=self.config.wikipedia_name,
            name=self.config.wikipedia_version_name,
        )

        return [
            datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={"wikipedia": wikipedia}),
        ]

    def _generate_examples(self, wikipedia):
        logger.info(f"generating examples from = {self.config.wikipedia_name} {self.config.wikipedia_version_name}")
        for split in wikipedia:
            dset = wikipedia[split]
            split_function = _SPLIT_FUNCTION_MAP[self.config.wikipedia_name]
            for doc in generate_snippets(
                dset, split_function, passage_len=self.config.snippets_length, overlap=self.config.snippets_overlap
            ):
                id_ = doc["_id"]
                yield id_, doc