jspaulsen commited on
Commit
478e2dc
·
verified ·
1 Parent(s): 8fb4fa6

Upload folder using huggingface_hub

Browse files
Files changed (4) hide show
  1. README.md +50 -19
  2. pyproject.toml +13 -0
  3. transform_wikipedia.py +189 -0
  4. uv.lock +0 -0
README.md CHANGED
@@ -1,21 +1,52 @@
1
  ---
2
- dataset_info:
3
- features:
4
- - name: title
5
- dtype: string
6
- - name: text
7
- dtype: string
8
- - name: duration
9
- dtype: float64
10
- splits:
11
- - name: train
12
- num_bytes: 12569709929
13
- num_examples: 41360289
14
- download_size: 6851688816
15
- dataset_size: 12569709929
16
- configs:
17
- - config_name: default
18
- data_files:
19
- - split: train
20
- path: data/train-*
21
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ license: cc-by-sa-4.0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  ---
4
+
5
+ # Wikipedia Utterances
6
+
7
+ Text segments extracted from English Wikipedia, segmented into utterance-length chunks suitable for text-to-speech synthesis.
8
+
9
+ ## Dataset Description
10
+
11
+ This dataset contains ~41M text utterances derived from the [wikimedia/wikipedia](https://huggingface.co/datasets/wikimedia/wikipedia) dataset (20231101.en snapshot). Each row contains:
12
+
13
+ | Field | Type | Description |
14
+ |-------|------|-------------|
15
+ | `title` | string | The Wikipedia article title |
16
+ | `text` | string | A text segment (10-4,880 characters) |
17
+ | `duration` | float | Estimated speech duration in seconds (at 150 WPM) |
18
+
19
+ ## Processing
20
+
21
+ The transformation pipeline:
22
+
23
+ 1. Tokenizes Wikipedia articles into paragraphs and sentences using NLTK
24
+ 2. Combines consecutive sentences targeting 15-30 second utterances
25
+ 3. Strips bracketed content (parentheses, braces, square brackets)
26
+ 4. Filters for valid utterances ending in sentence-final punctuation
27
+
28
+ See `transform_wikipedia.py` in this repository for the full implementation.
29
+
30
+ ## Usage
31
+
32
+ ```python
33
+ from datasets import load_dataset
34
+
35
+ dataset = load_dataset("jspaulsen/wikipedia-utterances", split="train")
36
+ ```
37
+
38
+ ## License
39
+
40
+ This dataset is released under [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/), consistent with the original Wikipedia content license.
41
+
42
+ ## Citation
43
+
44
+ If you use this dataset, please cite the original Wikimedia source:
45
+
46
+ ```bibtex
47
+ @ONLINE{wikidump,
48
+ author = "Wikimedia Foundation",
49
+ title = "Wikimedia Downloads",
50
+ url = "https://dumps.wikimedia.org"
51
+ }
52
+ ```
pyproject.toml ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [project]
2
+ name = "wikipedia-transform"
3
+ version = "0.1.0"
4
+ description = "Add your description here"
5
+ readme = "README.md"
6
+ requires-python = ">=3.12"
7
+ dependencies = [
8
+ "datasets>=4.4.1",
9
+ "huggingface>=0.0.1",
10
+ "huggingface-hub>=1.2.3",
11
+ "nltk>=3.9.2",
12
+ "numpy>=2.3.5",
13
+ ]
transform_wikipedia.py ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import nltk
2
+ from nltk.tokenize import sent_tokenize, BlanklineTokenizer
3
+ from datasets import load_dataset
4
+ import pyarrow as pa
5
+ import pyarrow.parquet as pq
6
+ import re
7
+ from pathlib import Path
8
+
9
+
10
+ nltk.download('punkt')
11
+ nltk.download('punkt_tab')
12
+
13
+
14
+ def strip_brackets(text: str) -> str:
15
+ """
16
+ Remove parentheses (), braces {}, and brackets [] along with their contents.
17
+ """
18
+ text = re.sub(r'\([^)]*\)', '', text)
19
+ text = re.sub(r'\{[^}]*\}', '', text)
20
+ text = re.sub(r'\[[^\]]*\]', '', text)
21
+ text = re.sub(r'\s+', ' ', text).strip()
22
+ return text
23
+
24
+
25
+ def is_valid_utterance(
26
+ utterance: str,
27
+ minimum_utterance_length: int = 10,
28
+ ) -> bool:
29
+ utterance = utterance.strip(' ').strip('\n')
30
+
31
+ if utterance.count('\n') > 1:
32
+ return False
33
+
34
+ if len(utterance) < minimum_utterance_length:
35
+ return False
36
+
37
+ if not utterance.endswith(('.', '!', '?')):
38
+ if not utterance.endswith(('"', "'")):
39
+ return False
40
+ if len(utterance) >= 2:
41
+ if utterance[-2] not in ('.', '!', '?'):
42
+ return False
43
+
44
+ if any(char in utterance for char in '(){}[]'):
45
+ return False
46
+
47
+ return True
48
+
49
+
50
+ def estimate_speech_duration(text: str, wpm: int = 150) -> float:
51
+ """
52
+ Estimate speech duration in seconds.
53
+ Average speaking rate is ~150 words per minute.
54
+ """
55
+ words = text.split()
56
+ return (len(words) / wpm) * 60
57
+
58
+
59
+ def combine_sentences_in_paragraph(
60
+ sentences: list[str],
61
+ min_duration: float = 15.0,
62
+ max_duration: float = 30.0,
63
+ ) -> list[str]:
64
+ """
65
+ Combine consecutive sentences within a paragraph if the combined duration
66
+ falls between min_duration and max_duration seconds.
67
+ """
68
+ if not sentences:
69
+ return []
70
+
71
+ result = []
72
+ current_chunk = []
73
+ current_duration = 0.0
74
+
75
+ for sentence in sentences:
76
+ sentence_duration = estimate_speech_duration(sentence)
77
+ potential_duration = current_duration + sentence_duration
78
+
79
+ if potential_duration <= max_duration:
80
+ current_chunk.append(sentence)
81
+ current_duration = potential_duration
82
+ else:
83
+ if current_chunk:
84
+ result.append(' '.join(current_chunk))
85
+ current_chunk = [sentence]
86
+ current_duration = sentence_duration
87
+
88
+ if current_chunk:
89
+ result.append(' '.join(current_chunk))
90
+
91
+ return result
92
+
93
+
94
+ def transform_text(text: str) -> list[str]:
95
+ """
96
+ Transform Wikipedia text into valid utterances.
97
+ Returns a list of valid utterance strings.
98
+ """
99
+ paragraph_tokenizer = BlanklineTokenizer()
100
+ paragraphs = paragraph_tokenizer.tokenize(text)
101
+
102
+ valid_utterances = []
103
+
104
+ for segment in paragraphs:
105
+ sentences = sent_tokenize(segment)
106
+ combined_sentences = combine_sentences_in_paragraph(sentences)
107
+
108
+ for sentence in combined_sentences:
109
+ if is_valid_utterance(sentence):
110
+ valid_utterances.append(sentence)
111
+
112
+ return valid_utterances
113
+
114
+
115
+ def process_example(example: dict) -> list[dict]:
116
+ """
117
+ Process a single Wikipedia example, transforming the 'text' field
118
+ into individual utterance rows.
119
+ """
120
+ utterances = transform_text(example['text'])
121
+ return [
122
+ {
123
+ 'title': example['title'],
124
+ 'text': utterance,
125
+ 'duration': estimate_speech_duration(utterance),
126
+ }
127
+ for utterance in utterances
128
+ ]
129
+
130
+
131
+ def flush_batch(rows: list[dict], output_dir: Path, shard_index: int) -> None:
132
+ """Write a batch of rows to a Parquet shard."""
133
+ if not rows:
134
+ return
135
+
136
+ table = pa.Table.from_pydict({
137
+ 'title': [r['title'] for r in rows],
138
+ 'text': [r['text'] for r in rows],
139
+ 'duration': [r['duration'] for r in rows],
140
+ })
141
+
142
+ shard_path = output_dir / f"shard_{shard_index:05d}.parquet"
143
+ pq.write_table(table, shard_path)
144
+ print(f" Wrote shard {shard_index} with {len(rows)} utterances")
145
+
146
+
147
+ def main():
148
+ output_dir = Path('wikipedia_utterances')
149
+ output_dir.mkdir(exist_ok=True)
150
+
151
+ batch_size = 100_000 # Flush to disk every 100k utterances
152
+
153
+ print("Loading Wikipedia dataset...")
154
+ dataset = load_dataset(
155
+ 'wikimedia/wikipedia',
156
+ '20231101.en',
157
+ split='train',
158
+ streaming=True,
159
+ )
160
+
161
+ print("Processing dataset...")
162
+ rows = []
163
+ shard_index = 0
164
+ total_utterances = 0
165
+
166
+ for i, example in enumerate(dataset):
167
+ utterance_rows = process_example(example)
168
+ rows.extend(utterance_rows)
169
+
170
+ if len(rows) >= batch_size:
171
+ flush_batch(rows, output_dir, shard_index)
172
+ total_utterances += len(rows)
173
+ shard_index += 1
174
+ rows = []
175
+
176
+ if (i + 1) % 10_000 == 0:
177
+ print(f"Processed {i + 1} articles, {total_utterances + len(rows)} utterances so far")
178
+
179
+ # Flush remaining rows
180
+ if rows:
181
+ flush_batch(rows, output_dir, shard_index)
182
+ total_utterances += len(rows)
183
+
184
+ print(f"\nDone! Saved {total_utterances} utterances across {shard_index + 1} shards to '{output_dir}/'")
185
+ print(f"Load with: load_dataset('parquet', data_files='{output_dir}/*.parquet')")
186
+
187
+
188
+ if __name__ == "__main__":
189
+ main()
uv.lock ADDED
The diff for this file is too large to render. See raw diff