afrospeech-recipes 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 AfriModal AI
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,102 @@
1
+ Metadata-Version: 2.4
2
+ Name: afrospeech-recipes
3
+ Version: 0.1.0
4
+ Summary: Load the speech data a recipe describes, from wherever it lives.
5
+ Author-email: AfriModal AI <kaykola.olaleye@gmail.com>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://afrimodal-ai.github.io/
8
+ Keywords: speech,asr,african-languages,datasets,streaming
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Intended Audience :: Science/Research
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Topic :: Multimedia :: Sound/Audio :: Speech
13
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
14
+ Requires-Python: >=3.10
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Requires-Dist: requests>=2.28
18
+ Requires-Dist: numpy>=1.23
19
+ Requires-Dist: soundfile>=0.12
20
+ Requires-Dist: scipy>=1.10
21
+ Provides-Extra: huggingface
22
+ Requires-Dist: datasets>=2.18; extra == "huggingface"
23
+ Dynamic: license-file
24
+
25
+ # The recipe loader
26
+
27
+ One call that loads exactly the speech a recipe describes, wherever the data
28
+ lives. The recipe comes from the builder page; paste it into a notebook and
29
+ run it.
30
+
31
+ ```python
32
+ from afrospeech_recipes import load_recipe
33
+
34
+ ds = load_recipe(recipe, split="train", sample_rate=16_000, stream=True)
35
+ for ex in ds.take(3):
36
+ print(ex["source"], round(ex["duration"], 1), "s", ex["text"])
37
+ print(ds.report())
38
+ ```
39
+
40
+ Install it:
41
+
42
+ ```
43
+ pip install "afrospeech-recipes[huggingface]==0.1.0"
44
+ ```
45
+
46
+ The extra brings `datasets`, which only a Hugging Face source needs; a
47
+ recipe that reads a tar archive runs without it. Every script the builder
48
+ page hands out pins the version it was written against, because a recipe is
49
+ a record of what was fetched and a loader that changed under it is a
50
+ different answer.
51
+
52
+ ## The data keeps its own terms
53
+
54
+ This licence covers the loader, not one second of audio. Every dataset keeps
55
+ the terms its publisher set: attribution, share-alike, no redistribution, an
56
+ access request, a non-commercial clause. A recipe carries the permission
57
+ answers that were recorded for each source and this loader checks them again
58
+ before it fetches, but a check in code is not a licence review, and a
59
+ permission nobody has read is not permission. Read each publisher's terms
60
+ before you train on their audio, and before you publish anything you trained.
61
+
62
+ ## What version 1 does
63
+
64
+ - Hugging Face repositories, streamed: parquet, webdataset and audio folders.
65
+ - Tar archives over HTTP, read as a stream and never written to disk.
66
+ - Filters whole datasets, which is what the catalogue records today.
67
+ - Shares an hour budget over the sources using each dataset's recorded
68
+ hours, so a budget is met to within one clip and `report()` says what was
69
+ actually delivered.
70
+ - Resamples to one rate and returns one record shape whatever the source:
71
+ `audio, text, duration, language, split, source, clip_id, speaker_id`.
72
+
73
+ ## What it refuses to do
74
+
75
+ - Mix splits. A training recipe reads train splits only, and asking it for a
76
+ test split raises rather than returning the audio.
77
+ - Read a source whose recorded terms do not allow the recipe's purpose. The
78
+ permission answers travel inside the recipe and are checked again here, at
79
+ the point the data is fetched.
80
+ - Keep audio. Clips are decoded, handed over and dropped.
81
+
82
+ ## What is not here yet
83
+
84
+ - Per clip selection: length, speaker, topic and an exact hour budget all
85
+ need the clip index, which is the next step.
86
+ - Adapters for zip archives, GitHub releases, cloud buckets, Dataverse and
87
+ Zenodo, and for local copies of datasets that need a signed agreement.
88
+ - Writing shards or a NeMo manifest instead of streaming.
89
+
90
+ A dataset this loader cannot yet fetch correctly is never written into a
91
+ script. The builder page counts its hours, names it under the script, and
92
+ says why it is not in the code.
93
+
94
+ ## Which datasets it can fetch
95
+
96
+ The loader fetches whatever a recipe names, and a recipe is written by the
97
+ builder page, which only writes a source it has checked: it asks each
98
+ publisher's repository what configs and splits it really has and which
99
+ columns a row carries, and records the date it asked. Nothing there is
100
+ inferred from a naming convention, and a dataset whose train and test split
101
+ is recorded somewhere other than the data itself is left out with that as
102
+ the stated reason, rather than loaded on a guess.
@@ -0,0 +1,78 @@
1
+ # The recipe loader
2
+
3
+ One call that loads exactly the speech a recipe describes, wherever the data
4
+ lives. The recipe comes from the builder page; paste it into a notebook and
5
+ run it.
6
+
7
+ ```python
8
+ from afrospeech_recipes import load_recipe
9
+
10
+ ds = load_recipe(recipe, split="train", sample_rate=16_000, stream=True)
11
+ for ex in ds.take(3):
12
+ print(ex["source"], round(ex["duration"], 1), "s", ex["text"])
13
+ print(ds.report())
14
+ ```
15
+
16
+ Install it:
17
+
18
+ ```
19
+ pip install "afrospeech-recipes[huggingface]==0.1.0"
20
+ ```
21
+
22
+ The extra brings `datasets`, which only a Hugging Face source needs; a
23
+ recipe that reads a tar archive runs without it. Every script the builder
24
+ page hands out pins the version it was written against, because a recipe is
25
+ a record of what was fetched and a loader that changed under it is a
26
+ different answer.
27
+
28
+ ## The data keeps its own terms
29
+
30
+ This licence covers the loader, not one second of audio. Every dataset keeps
31
+ the terms its publisher set: attribution, share-alike, no redistribution, an
32
+ access request, a non-commercial clause. A recipe carries the permission
33
+ answers that were recorded for each source and this loader checks them again
34
+ before it fetches, but a check in code is not a licence review, and a
35
+ permission nobody has read is not permission. Read each publisher's terms
36
+ before you train on their audio, and before you publish anything you trained.
37
+
38
+ ## What version 1 does
39
+
40
+ - Hugging Face repositories, streamed: parquet, webdataset and audio folders.
41
+ - Tar archives over HTTP, read as a stream and never written to disk.
42
+ - Filters whole datasets, which is what the catalogue records today.
43
+ - Shares an hour budget over the sources using each dataset's recorded
44
+ hours, so a budget is met to within one clip and `report()` says what was
45
+ actually delivered.
46
+ - Resamples to one rate and returns one record shape whatever the source:
47
+ `audio, text, duration, language, split, source, clip_id, speaker_id`.
48
+
49
+ ## What it refuses to do
50
+
51
+ - Mix splits. A training recipe reads train splits only, and asking it for a
52
+ test split raises rather than returning the audio.
53
+ - Read a source whose recorded terms do not allow the recipe's purpose. The
54
+ permission answers travel inside the recipe and are checked again here, at
55
+ the point the data is fetched.
56
+ - Keep audio. Clips are decoded, handed over and dropped.
57
+
58
+ ## What is not here yet
59
+
60
+ - Per clip selection: length, speaker, topic and an exact hour budget all
61
+ need the clip index, which is the next step.
62
+ - Adapters for zip archives, GitHub releases, cloud buckets, Dataverse and
63
+ Zenodo, and for local copies of datasets that need a signed agreement.
64
+ - Writing shards or a NeMo manifest instead of streaming.
65
+
66
+ A dataset this loader cannot yet fetch correctly is never written into a
67
+ script. The builder page counts its hours, names it under the script, and
68
+ says why it is not in the code.
69
+
70
+ ## Which datasets it can fetch
71
+
72
+ The loader fetches whatever a recipe names, and a recipe is written by the
73
+ builder page, which only writes a source it has checked: it asks each
74
+ publisher's repository what configs and splits it really has and which
75
+ columns a row carries, and records the date it asked. Nothing there is
76
+ inferred from a naming convention, and a dataset whose train and test split
77
+ is recorded somewhere other than the data itself is left out with that as
78
+ the stated reason, rather than loaded on a guess.
@@ -0,0 +1,251 @@
1
+ """Load exactly the speech data a recipe describes, from wherever it lives.
2
+
3
+ from afrospeech_recipes import load_recipe
4
+
5
+ ds = load_recipe(recipe, split="train", sample_rate=16_000, stream=True)
6
+ print(ds.plan()) # what it will ask each publisher for
7
+ for ex in ds.take(3):
8
+ print(ex["source"], round(ex["duration"], 1), "s", ex["text"])
9
+ print(ds.report()) # what actually arrived
10
+
11
+ One call, many sources underneath. The recipe comes from the builder page and
12
+ carries everything needed, so this package reads no catalogue and contacts no
13
+ site of ours: only the dataset publishers themselves.
14
+
15
+ Version 1 handles Hugging Face repositories and tar archives, filters whole
16
+ datasets, and shares an hour budget using each dataset's recorded hours, so a
17
+ budget is met to within a clip rather than exactly. Per clip filters (length,
18
+ speaker, topic) and exact budgets arrive with the clip index.
19
+
20
+ What it will not do:
21
+
22
+ - Mix splits. A training recipe reads train splits only, and asking it for
23
+ a test split raises instead.
24
+ - Load a source whose recorded terms do not allow the recipe's purpose,
25
+ even if the recipe lists it. The answers travel with the recipe and are
26
+ checked again here, where the fetching happens.
27
+ - Keep audio. Clips are decoded, handed over and dropped. Nothing is
28
+ written to disk unless `stream=False`, which turns on the publisher's own
29
+ caching.
30
+ """
31
+
32
+ from __future__ import annotations
33
+
34
+ import itertools
35
+ from typing import Iterator
36
+
37
+ from .recipe import Recipe, RecipeError, Source, budget, parse, role_for, usable
38
+ from .sources import adapter
39
+
40
+ __all__ = ["load_recipe", "RecipeStream", "RecipeError", "Recipe", "Source"]
41
+
42
+ DEFAULT_SAMPLE_RATE = 16000
43
+
44
+
45
+ def span(hours: float) -> str:
46
+ """An amount of audio, in the unit it is actually in.
47
+
48
+ A three clip check delivers six seconds, and "0.0 h" reads as nothing
49
+ delivered when three clips did arrive. Below a tenth of an hour this says
50
+ seconds instead.
51
+ """
52
+ if hours >= 0.1:
53
+ return f"{hours:.1f} h"
54
+ return f"{hours * 3600:.0f} s"
55
+
56
+
57
+ class RecipeStream:
58
+ """The clips a recipe asks for, in a mix of its sources.
59
+
60
+ Iterable once per pass, like any stream. `take(n)` is the short form the
61
+ site's snippet uses. `report()` says what was actually delivered, which
62
+ is the only honest way to state an approximate budget.
63
+ """
64
+
65
+ def __init__(self, recipe: Recipe, role: str, sample_rate: int, streaming: bool,
66
+ on_source_error: str = "stop"):
67
+ self.recipe = recipe
68
+ self.role = role
69
+ self.sample_rate = sample_rate
70
+ self.streaming = streaming
71
+ self.on_source_error = on_source_error
72
+ self.delivered: dict[str, float] = {}
73
+ self.clips: dict[str, int] = {}
74
+ self.skipped: dict[str, str] = {}
75
+ self.failed: dict[str, str] = {}
76
+
77
+ self.sources: list[Source] = []
78
+ for source in recipe.sources:
79
+ why = usable(recipe, source, role)
80
+ if why:
81
+ self.skipped[f"{source.name} ({source.language})"] = why
82
+ else:
83
+ self.sources.append(source)
84
+ if not self.sources:
85
+ raise RecipeError(
86
+ "no source in this recipe can be read for "
87
+ f"{recipe.purpose}: " + "; ".join(
88
+ f"{k}: {v}" for k, v in self.skipped.items()))
89
+ self.budget = budget(recipe, self.sources)
90
+
91
+ # -- the records -------------------------------------------------------
92
+
93
+ def _labelled_out(self, source: Source, row: dict) -> bool:
94
+ """Whether this clip's own labels put it outside the recipe.
95
+
96
+ A source whose publisher records no such column cannot be filtered
97
+ clip by clip: the site has already decided whether to include it
98
+ whole, so nothing is dropped here on a guess.
99
+ """
100
+ for field_name in ("speech_style", "topic"):
101
+ column = source.labels.get(field_name)
102
+ if not column:
103
+ continue
104
+ value = row.get(column)
105
+ value = None if value is None else str(value).strip()
106
+ if not value:
107
+ if field_name in self.recipe.require_labels:
108
+ return True
109
+ continue
110
+ for unwanted in self.recipe.excluded(field_name):
111
+ if value.casefold() == str(unwanted).casefold():
112
+ return True
113
+ return False
114
+
115
+ def _record(self, source: Source, row: dict) -> dict | None:
116
+ if self._labelled_out(source, row):
117
+ return None
118
+ audio = row.get(source.audio)
119
+ if not isinstance(audio, dict) or audio.get("array") is None:
120
+ return None
121
+ rate = audio.get("sampling_rate") or self.sample_rate
122
+ seconds = len(audio["array"]) / rate if rate else None
123
+ if source.duration and row.get(source.duration) is not None:
124
+ try:
125
+ seconds = float(row[source.duration])
126
+ except (TypeError, ValueError):
127
+ pass
128
+ if seconds is None:
129
+ return None
130
+ if self.recipe.max_clip_seconds and seconds > self.recipe.max_clip_seconds:
131
+ return None
132
+ text = row.get(source.text)
133
+ if text is None or str(text).strip() == "":
134
+ return None
135
+ return {
136
+ "audio": audio,
137
+ "text": str(text),
138
+ "duration": seconds,
139
+ "language": source.language,
140
+ "split": self.role,
141
+ "source": source.name,
142
+ "clip_id": audio.get("path") or row.get("id"),
143
+ "speaker_id": row.get(source.speaker) if source.speaker else None,
144
+ }
145
+
146
+ def _one(self, source: Source) -> Iterator[dict]:
147
+ """One source's clips, stopping at its share of the budget."""
148
+ name = f"{source.name}/{source.language}"
149
+ allowance = self.budget.get(name)
150
+ taken = 0.0
151
+ try:
152
+ rows = adapter(source.loader)(source, self.role, self.sample_rate,
153
+ self.streaming)
154
+ for row in rows:
155
+ record = self._record(source, row)
156
+ if record is None:
157
+ continue
158
+ if allowance is not None and taken + record["duration"] > allowance * 3600:
159
+ break
160
+ taken += record["duration"]
161
+ self.delivered[name] = taken / 3600
162
+ self.clips[name] = self.clips.get(name, 0) + 1
163
+ yield record
164
+ except Exception as exc: # one source being down is not the run's end
165
+ self.failed[name] = f"{type(exc).__name__}: {exc}"
166
+ if self.on_source_error == "stop":
167
+ raise RuntimeError(
168
+ f"{name} could not be read: {exc}. Pass "
169
+ "on_source_error='skip' to carry on without it.") from exc
170
+
171
+ def __iter__(self) -> Iterator[dict]:
172
+ """Sources interleaved, one clip at a time round the mix, so a short
173
+ run holds the same mixture as a long one."""
174
+ streams = [self._one(source) for source in self.sources]
175
+ while streams:
176
+ for stream in list(streams):
177
+ try:
178
+ yield next(stream)
179
+ except StopIteration:
180
+ streams.remove(stream)
181
+
182
+ def take(self, n: int) -> Iterator[dict]:
183
+ return itertools.islice(iter(self), n)
184
+
185
+ # -- what happened -----------------------------------------------------
186
+
187
+ def plan(self) -> str:
188
+ """What this stream will ask each publisher for, before it asks.
189
+
190
+ Printed by the script the site hands out, because the hours on the
191
+ page are a plan and this is the same plan as the code holds it: the
192
+ share per source, the split each share is read from, and the sources
193
+ the recipe named that this run will not read.
194
+ """
195
+ asked = 0.0
196
+ for hours in self.budget.values():
197
+ asked += hours or 0.0
198
+ total = f"{asked:.0f} h" if asked else "every hour on offer"
199
+ lines = [f"Asking for {total} of {'/'.join(self.recipe.languages)} "
200
+ f"for {self.recipe.purpose}, from the {self.role} split of "
201
+ f"{len(self.sources)} source"
202
+ f"{'' if len(self.sources) == 1 else 's'}:"]
203
+ for source in self.sources:
204
+ name = f"{source.name}/{source.language}"
205
+ share = self.budget.get(name)
206
+ lines.append(f" {name}: "
207
+ + (f"up to {share:.1f} h" if share else "everything")
208
+ + f', split "{source.split_name(self.role)}"')
209
+ for name, why in sorted(self.skipped.items()):
210
+ lines.append(f" not read: {name}: {why}")
211
+ if self.recipe.max_clip_seconds:
212
+ lines.append(f" clips longer than {self.recipe.max_clip_seconds:g} s "
213
+ "are dropped as they arrive")
214
+ return "\n".join(lines)
215
+
216
+ def report(self) -> str:
217
+ total = 0.0
218
+ for hours in self.delivered.values():
219
+ total += hours
220
+ clips = 0
221
+ for count in self.clips.values():
222
+ clips += count
223
+ lines = [f"Delivered {span(total)} in {clips} clip{'' if clips == 1 else 's'} from "
224
+ f"{len(self.delivered)} source{'' if len(self.delivered) == 1 else 's'}, "
225
+ "measured from the audio as it streamed."]
226
+ for name in sorted(self.delivered):
227
+ share = self.budget.get(name)
228
+ count = self.clips.get(name, 0)
229
+ lines.append(f" {name}: {span(self.delivered[name])} "
230
+ f"in {count} clip{'' if count == 1 else 's'}"
231
+ + (f" of up to {share:.1f} h asked for" if share else ""))
232
+ for name, why in sorted(self.skipped.items()):
233
+ lines.append(f" not read: {name}: {why}")
234
+ for name, why in sorted(self.failed.items()):
235
+ lines.append(f" failed: {name}: {why}")
236
+ return "\n".join(lines)
237
+
238
+
239
+ def load_recipe(recipe, split: str | None = None,
240
+ sample_rate: int = DEFAULT_SAMPLE_RATE, stream: bool = True,
241
+ on_source_error: str = "stop") -> RecipeStream:
242
+ """Open a recipe as a stream of clips.
243
+
244
+ `split` names the role to read, and must agree with the recipe's purpose;
245
+ left out, the purpose decides. `stream=False` lets the publisher's own
246
+ library cache to disk, which is for a machine with room, never for a free
247
+ tier.
248
+ """
249
+ parsed = parse(recipe)
250
+ return RecipeStream(parsed, role_for(parsed, split), sample_rate, stream,
251
+ on_source_error)
@@ -0,0 +1,184 @@
1
+ """A recipe, checked before anything is fetched.
2
+
3
+ A recipe is a plain dict, written by the builder page and pasted into a
4
+ notebook. It carries everything the loader needs, so the loader asks no
5
+ website anything: no catalogue lookup, no index download, no account.
6
+
7
+ The rules are kept here rather than in the adapters, because every one of
8
+ them is about the recipe as a whole: a split role a source does not publish is refused, a source whose
9
+ recorded answer does not allow the recipe's purpose is refused, and a budget
10
+ is shared over the sources before a single clip is read.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from dataclasses import dataclass, field
16
+
17
+ # What a recipe may ask for, and the split role each one reads.
18
+ PURPOSES = {
19
+ "asr_training": "train",
20
+ "asr_evaluation": "test",
21
+ # Quantising audio into discrete units for language model pretraining.
22
+ # Deliberately its own answer and never a synonym for asr_training:
23
+ # config/licences.yaml says why, and a corpus that forbids voice cloning
24
+ # may well forbid this while allowing recognition.
25
+ "speech_lm_pretraining": "train",
26
+ "tts_training": "train",
27
+ }
28
+ USES = ("research", "commercial")
29
+ ROLES = ("train", "dev", "test")
30
+
31
+
32
+ class RecipeError(ValueError):
33
+ """A recipe that cannot be run, said plainly enough to fix."""
34
+
35
+
36
+ @dataclass
37
+ class Source:
38
+ """One dataset, in one language, as the recipe names it."""
39
+
40
+ name: str
41
+ language: str
42
+ repo: str
43
+ splits: dict[str, str]
44
+ revision: str | None = None
45
+ where: dict | None = None
46
+ hours: float | None = None
47
+ audio: str = "audio"
48
+ text: str = "text"
49
+ duration: str | None = None
50
+ speaker: str | None = None
51
+ allows: list[str] = field(default_factory=list)
52
+ loader: str = "huggingface"
53
+ url: str | None = None
54
+ # Which of this repository's own columns says what a clip is: the same
55
+ # columns the hours on the site were counted from.
56
+ labels: dict[str, str] = field(default_factory=dict)
57
+
58
+ def split_name(self, role: str) -> str | None:
59
+ return self.splits.get(role)
60
+
61
+
62
+ @dataclass
63
+ class Recipe:
64
+ languages: list[str]
65
+ purpose: str
66
+ use: str
67
+ sources: list[Source]
68
+ hours: float | None = None
69
+ seed: int = 42
70
+ max_clip_seconds: float | None = None
71
+ # Values the visitor turned off, as the publishers spell them, and the
72
+ # fields whose unlabelled clips they also turned off.
73
+ exclude_speech_style: list[str] = field(default_factory=list)
74
+ exclude_topics: list[str] = field(default_factory=list)
75
+ require_labels: list[str] = field(default_factory=list)
76
+ split_hours: str = "proportional"
77
+ recipe_version: int = 1
78
+
79
+ def excluded(self, field_name: str) -> list[str]:
80
+ return (self.exclude_speech_style if field_name == "speech_style"
81
+ else self.exclude_topics)
82
+
83
+
84
+ def parse(recipe: dict) -> Recipe:
85
+ if not isinstance(recipe, dict):
86
+ raise RecipeError("a recipe is a dict, as the site writes it")
87
+ for required in ("languages", "purpose", "use", "sources"):
88
+ if required not in recipe:
89
+ raise RecipeError(f"the recipe has no {required!r}")
90
+ purpose = recipe["purpose"]
91
+ if purpose not in PURPOSES:
92
+ raise RecipeError(f"purpose {purpose!r} is not one of {sorted(PURPOSES)}")
93
+ if recipe["use"] not in USES:
94
+ raise RecipeError(f"use {recipe['use']!r} is not one of {list(USES)}")
95
+ if not recipe["sources"]:
96
+ raise RecipeError("the recipe has no sources, so there is nothing to load")
97
+
98
+ sources = []
99
+ for entry in recipe["sources"]:
100
+ known = {f: entry[f] for f in Source.__dataclass_fields__ if f in entry}
101
+ for required in ("name", "language", "repo", "splits"):
102
+ if required not in known:
103
+ raise RecipeError(f"a source has no {required!r}: {entry.get('name', entry)}")
104
+ sources.append(Source(**known))
105
+
106
+ return Recipe(
107
+ languages=list(recipe["languages"]),
108
+ purpose=purpose,
109
+ use=recipe["use"],
110
+ sources=sources,
111
+ hours=recipe.get("hours"),
112
+ seed=recipe.get("seed", 42),
113
+ max_clip_seconds=recipe.get("max_clip_seconds"),
114
+ exclude_speech_style=list(recipe.get("exclude_speech_style") or []),
115
+ exclude_topics=list(recipe.get("exclude_topics") or []),
116
+ require_labels=list(recipe.get("require_labels") or []),
117
+ split_hours=recipe.get("split_hours", "proportional"),
118
+ recipe_version=recipe.get("recipe_version", 1),
119
+ )
120
+
121
+
122
+ def role_for(recipe: Recipe, split: str | None) -> str:
123
+ """Which split role this run reads.
124
+
125
+ `split` may be given explicitly, but it must agree with the purpose: a
126
+ training recipe never reads a test split, whatever the caller passes
127
+ Train and test never mix.
128
+ """
129
+ wanted = PURPOSES[recipe.purpose]
130
+ if split is None:
131
+ return wanted
132
+ if split not in ROLES:
133
+ raise RecipeError(f"split {split!r} is not one of {list(ROLES)}")
134
+ if split == "test" and wanted != "test":
135
+ raise RecipeError(
136
+ f"this recipe's purpose is {recipe.purpose}, which trains on the train "
137
+ "split. Loading the test split for it would train on test audio, so the "
138
+ "loader refuses. Build an evaluation recipe instead.")
139
+ if split != "test" and wanted == "test":
140
+ raise RecipeError(
141
+ f"this recipe's purpose is {recipe.purpose}, which reads the test split.")
142
+ return split
143
+
144
+
145
+ def usable(recipe: Recipe, source: Source, role: str) -> str | None:
146
+ """Why this source cannot be read for this recipe, or None if it can.
147
+
148
+ The permission answers the site recorded travel with the recipe, so the
149
+ check happens again here, at run time, where the data is actually
150
+ fetched.
151
+ """
152
+ if source.split_name(role) is None:
153
+ return f"publishes no {role} split"
154
+ if source.allows:
155
+ if recipe.purpose not in source.allows:
156
+ return f"its recorded terms do not allow {recipe.purpose}"
157
+ if recipe.use == "commercial" and "commercial" not in source.allows:
158
+ return "its recorded terms do not allow commercial use"
159
+ return None
160
+
161
+
162
+ def budget(recipe: Recipe, sources: list[Source]) -> dict[str, float | None]:
163
+ """How many hours to take from each source, keyed by name and language.
164
+
165
+ The site already shared the budget out and wrote each share into the
166
+ recipe, so that is what is used. Without one, the recipe's total is
167
+ shared in proportion to what each source offers, and a recipe with no
168
+ total at all takes everything.
169
+ """
170
+ out: dict[str, float | None] = {}
171
+ stated = [s for s in sources if s.hours]
172
+ if len(stated) == len(sources) and stated:
173
+ for source in sources:
174
+ out[f"{source.name}/{source.language}"] = source.hours
175
+ return out
176
+ if recipe.hours is None:
177
+ return {f"{s.name}/{s.language}": None for s in sources}
178
+ offered = 0.0
179
+ for source in sources:
180
+ offered += source.hours or 0.0
181
+ for source in sources:
182
+ share = (source.hours or 0.0) / offered if offered else 1 / len(sources)
183
+ out[f"{source.name}/{source.language}"] = recipe.hours * share
184
+ return out
@@ -0,0 +1,20 @@
1
+ """One adapter per kind of source. Each one yields the repository's own rows;
2
+ turning a row into the common record is the loader's job, not theirs."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from . import huggingface, tarball
7
+
8
+ ADAPTERS = {
9
+ "huggingface": huggingface.stream,
10
+ "tar": tarball.stream,
11
+ }
12
+
13
+
14
+ def adapter(name: str):
15
+ if name not in ADAPTERS:
16
+ raise RuntimeError(
17
+ f"no adapter for a {name!r} source. The loader can fetch "
18
+ f"{sorted(ADAPTERS)} so far; the site never writes a recipe that "
19
+ "names anything else.")
20
+ return ADAPTERS[name]
@@ -0,0 +1,53 @@
1
+ """Turning a clip's bytes into samples, once, for every adapter.
2
+
3
+ Decoding is done here rather than left to the publisher's own library on
4
+ purpose. The `datasets` library decodes audio through torchcodec, which
5
+ means installing torch to read a wav file; on a free tier that is most of
6
+ the disk allowance spent before any data arrives. soundfile reads what the
7
+ catalogued datasets actually ship, and scipy resamples, and both are small.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import io
13
+ from math import gcd
14
+
15
+
16
+ def decode(payload: bytes, sample_rate: int):
17
+ """One clip's samples at the rate asked for, mono, as float32."""
18
+ import numpy
19
+ import soundfile
20
+
21
+ array, rate = soundfile.read(io.BytesIO(payload), dtype="float32", always_2d=True)
22
+ array = array.mean(axis=1)
23
+ if rate != sample_rate:
24
+ from scipy.signal import resample_poly
25
+
26
+ divisor = gcd(int(rate), int(sample_rate))
27
+ array = resample_poly(array, int(sample_rate) // divisor, int(rate) // divisor)
28
+ return numpy.asarray(array, dtype="float32"), sample_rate
29
+
30
+
31
+ def as_clip(value, sample_rate: int) -> dict | None:
32
+ """An audio column's value, however the source gives it, as one clip.
33
+
34
+ A row may carry the bytes (what a parquet repository holds), a path to a
35
+ file, or samples a library has already decoded. Anything else is not
36
+ audio this adapter understands, and the caller reports it rather than
37
+ guessing.
38
+ """
39
+ if not isinstance(value, dict):
40
+ return None
41
+ if value.get("array") is not None:
42
+ return value
43
+ payload = value.get("bytes")
44
+ if payload is None and value.get("path"):
45
+ try:
46
+ with open(value["path"], "rb") as handle:
47
+ payload = handle.read()
48
+ except OSError:
49
+ return None
50
+ if payload is None:
51
+ return None
52
+ array, rate = decode(payload, sample_rate)
53
+ return {"array": array, "sampling_rate": rate, "path": value.get("path")}
@@ -0,0 +1,67 @@
1
+ """Hugging Face: parquet, webdataset and audio folders, streamed.
2
+
3
+ The one thing this adapter is careful about is which rows belong to the
4
+ split the recipe asked for. A repo says that in one of two ways, and the
5
+ recipe says which: the split is a split the repo publishes, or the language
6
+ is a config the repo publishes and the split is inside it. Anything else
7
+ (a split recorded in a file beside the data, say) is not something this
8
+ adapter can tell apart, so the site does not offer those datasets yet
9
+ rather than guessing and mixing test audio into a training run.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import os
15
+ from typing import Any, Iterator
16
+
17
+ from .audio import as_clip
18
+
19
+
20
+ def _datasets():
21
+ try:
22
+ import datasets
23
+ except ImportError as exc: # pragma: no cover - a missing dependency
24
+ raise RuntimeError(
25
+ "this recipe loads a Hugging Face dataset, so it needs the "
26
+ "`datasets` package: pip install datasets") from exc
27
+ return datasets
28
+
29
+
30
+ def stream(source, role: str, sample_rate: int, streaming: bool = True) -> Iterator[dict]:
31
+ """Yield one dict per clip, as the repo stores it, audio decoded and
32
+ resampled. Rows the recipe's language filter rejects are skipped here,
33
+ so the caller only ever sees the language it asked for."""
34
+ datasets = _datasets()
35
+ where = source.where or {}
36
+ split = source.split_name(role)
37
+ kwargs: dict[str, Any] = {"split": split, "streaming": streaming}
38
+ if source.revision:
39
+ kwargs["revision"] = source.revision
40
+ token = os.environ.get("HF_TOKEN")
41
+ if token:
42
+ kwargs["token"] = token
43
+
44
+ if where.get("config"):
45
+ dataset = datasets.load_dataset(source.repo, where["config"], **kwargs)
46
+ elif where.get("data_dir"):
47
+ dataset = datasets.load_dataset(source.repo, data_dir=where["data_dir"], **kwargs)
48
+ else:
49
+ dataset = datasets.load_dataset(source.repo, **kwargs)
50
+
51
+ # Hand back the clip's bytes rather than letting `datasets` decode them.
52
+ # Its decoder is torchcodec, which means installing torch to read a wav
53
+ # file: most of a free tier's disk spent before any audio arrives. The
54
+ # bytes are decoded in sources/audio.py with soundfile instead.
55
+ try:
56
+ dataset = dataset.cast_column(source.audio, datasets.Audio(decode=False))
57
+ except (ValueError, TypeError):
58
+ pass
59
+
60
+ column, value = where.get("column"), where.get("value")
61
+ for row in dataset:
62
+ if column and row.get(column) != value:
63
+ continue
64
+ clip = as_clip(row.get(source.audio), sample_rate)
65
+ if clip is None:
66
+ continue
67
+ yield dict(row, **{source.audio: clip})
@@ -0,0 +1,69 @@
1
+ """A .tar or .tar.gz of audio, read as a stream.
2
+
3
+ OpenSLR and several university mirrors publish a corpus as one archive. The
4
+ honest limit, which the site states next to any dataset that uses this
5
+ adapter: the whole archive travels down the wire even when the recipe wants
6
+ a small part of it, because a gzipped tar cannot be read out of order. The
7
+ archive is never written to disk. Members are read one at a time and
8
+ dropped as soon as the clip has been handed over.
9
+
10
+ Transcripts come from a separate index the recipe points at, mapping a
11
+ member path to its text. An archive member with no entry in that index is
12
+ skipped rather than returned with an empty transcript.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import tarfile
18
+ from typing import Iterator
19
+
20
+ from .audio import decode
21
+
22
+
23
+ def _open_stream(url: str, token: str | None = None):
24
+ import requests
25
+
26
+ headers = {"Authorization": f"Bearer {token}"} if token else {}
27
+ response = requests.get(url, stream=True, timeout=120, headers=headers)
28
+ response.raise_for_status()
29
+ response.raw.decode_content = False
30
+ return response.raw
31
+
32
+
33
+ def members(url: str, suffixes=(".wav", ".flac", ".mp3", ".ogg"),
34
+ token: str | None = None, fileobj=None) -> Iterator[tuple[str, bytes]]:
35
+ """Every audio member of the archive, in the order it was written.
36
+
37
+ `fileobj` is for tests and for a local archive: anything the tarfile
38
+ module can read in stream mode. `r|*` is the streaming mode, which never
39
+ seeks, so it works on a socket.
40
+ """
41
+ handle = fileobj if fileobj is not None else _open_stream(url, token)
42
+ with tarfile.open(fileobj=handle, mode="r|*") as archive:
43
+ for member in archive:
44
+ if not member.isfile():
45
+ continue
46
+ if suffixes and not member.name.lower().endswith(tuple(suffixes)):
47
+ continue
48
+ extracted = archive.extractfile(member)
49
+ if extracted is None:
50
+ continue
51
+ yield member.name, extracted.read()
52
+
53
+
54
+ def stream(source, role: str, sample_rate: int, streaming: bool = True) -> Iterator[dict]:
55
+ """Yield one row per archive member that the transcript index names."""
56
+ import os
57
+
58
+ index = (source.where or {}).get("transcripts") or {}
59
+ url = source.url or (source.where or {}).get("url")
60
+ if not url:
61
+ raise RuntimeError(f"{source.name}: the recipe gives no archive URL")
62
+ token = os.environ.get("HF_TOKEN")
63
+ for name, payload in members(url, token=token):
64
+ text = index.get(name)
65
+ if text is None:
66
+ continue
67
+ array, rate = decode(payload, sample_rate)
68
+ yield {source.audio: {"array": array, "sampling_rate": rate, "path": name},
69
+ source.text: text}
@@ -0,0 +1,102 @@
1
+ Metadata-Version: 2.4
2
+ Name: afrospeech-recipes
3
+ Version: 0.1.0
4
+ Summary: Load the speech data a recipe describes, from wherever it lives.
5
+ Author-email: AfriModal AI <kaykola.olaleye@gmail.com>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://afrimodal-ai.github.io/
8
+ Keywords: speech,asr,african-languages,datasets,streaming
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Intended Audience :: Science/Research
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Topic :: Multimedia :: Sound/Audio :: Speech
13
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
14
+ Requires-Python: >=3.10
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Requires-Dist: requests>=2.28
18
+ Requires-Dist: numpy>=1.23
19
+ Requires-Dist: soundfile>=0.12
20
+ Requires-Dist: scipy>=1.10
21
+ Provides-Extra: huggingface
22
+ Requires-Dist: datasets>=2.18; extra == "huggingface"
23
+ Dynamic: license-file
24
+
25
+ # The recipe loader
26
+
27
+ One call that loads exactly the speech a recipe describes, wherever the data
28
+ lives. The recipe comes from the builder page; paste it into a notebook and
29
+ run it.
30
+
31
+ ```python
32
+ from afrospeech_recipes import load_recipe
33
+
34
+ ds = load_recipe(recipe, split="train", sample_rate=16_000, stream=True)
35
+ for ex in ds.take(3):
36
+ print(ex["source"], round(ex["duration"], 1), "s", ex["text"])
37
+ print(ds.report())
38
+ ```
39
+
40
+ Install it:
41
+
42
+ ```
43
+ pip install "afrospeech-recipes[huggingface]==0.1.0"
44
+ ```
45
+
46
+ The extra brings `datasets`, which only a Hugging Face source needs; a
47
+ recipe that reads a tar archive runs without it. Every script the builder
48
+ page hands out pins the version it was written against, because a recipe is
49
+ a record of what was fetched and a loader that changed under it is a
50
+ different answer.
51
+
52
+ ## The data keeps its own terms
53
+
54
+ This licence covers the loader, not one second of audio. Every dataset keeps
55
+ the terms its publisher set: attribution, share-alike, no redistribution, an
56
+ access request, a non-commercial clause. A recipe carries the permission
57
+ answers that were recorded for each source and this loader checks them again
58
+ before it fetches, but a check in code is not a licence review, and a
59
+ permission nobody has read is not permission. Read each publisher's terms
60
+ before you train on their audio, and before you publish anything you trained.
61
+
62
+ ## What version 1 does
63
+
64
+ - Hugging Face repositories, streamed: parquet, webdataset and audio folders.
65
+ - Tar archives over HTTP, read as a stream and never written to disk.
66
+ - Filters whole datasets, which is what the catalogue records today.
67
+ - Shares an hour budget over the sources using each dataset's recorded
68
+ hours, so a budget is met to within one clip and `report()` says what was
69
+ actually delivered.
70
+ - Resamples to one rate and returns one record shape whatever the source:
71
+ `audio, text, duration, language, split, source, clip_id, speaker_id`.
72
+
73
+ ## What it refuses to do
74
+
75
+ - Mix splits. A training recipe reads train splits only, and asking it for a
76
+ test split raises rather than returning the audio.
77
+ - Read a source whose recorded terms do not allow the recipe's purpose. The
78
+ permission answers travel inside the recipe and are checked again here, at
79
+ the point the data is fetched.
80
+ - Keep audio. Clips are decoded, handed over and dropped.
81
+
82
+ ## What is not here yet
83
+
84
+ - Per clip selection: length, speaker, topic and an exact hour budget all
85
+ need the clip index, which is the next step.
86
+ - Adapters for zip archives, GitHub releases, cloud buckets, Dataverse and
87
+ Zenodo, and for local copies of datasets that need a signed agreement.
88
+ - Writing shards or a NeMo manifest instead of streaming.
89
+
90
+ A dataset this loader cannot yet fetch correctly is never written into a
91
+ script. The builder page counts its hours, names it under the script, and
92
+ says why it is not in the code.
93
+
94
+ ## Which datasets it can fetch
95
+
96
+ The loader fetches whatever a recipe names, and a recipe is written by the
97
+ builder page, which only writes a source it has checked: it asks each
98
+ publisher's repository what configs and splits it really has and which
99
+ columns a row carries, and records the date it asked. Nothing there is
100
+ inferred from a naming convention, and a dataset whose train and test split
101
+ is recorded somewhere other than the data itself is left out with that as
102
+ the stated reason, rather than loaded on a guess.
@@ -0,0 +1,14 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ afrospeech_recipes/__init__.py
5
+ afrospeech_recipes/recipe.py
6
+ afrospeech_recipes.egg-info/PKG-INFO
7
+ afrospeech_recipes.egg-info/SOURCES.txt
8
+ afrospeech_recipes.egg-info/dependency_links.txt
9
+ afrospeech_recipes.egg-info/requires.txt
10
+ afrospeech_recipes.egg-info/top_level.txt
11
+ afrospeech_recipes/sources/__init__.py
12
+ afrospeech_recipes/sources/audio.py
13
+ afrospeech_recipes/sources/huggingface.py
14
+ afrospeech_recipes/sources/tarball.py
@@ -0,0 +1,7 @@
1
+ requests>=2.28
2
+ numpy>=1.23
3
+ soundfile>=0.12
4
+ scipy>=1.10
5
+
6
+ [huggingface]
7
+ datasets>=2.18
@@ -0,0 +1 @@
1
+ afrospeech_recipes
@@ -0,0 +1,54 @@
1
+ # The recipe loader, as published. The name, the licence and the metadata
2
+ # below are the owner's decisions, recorded in
3
+ # docs/decisions/2026-10-28-publishing-the-loader.md.
4
+ #
5
+ # pip install "afrospeech-recipes[huggingface]"
6
+ # pip install -e "loader/[huggingface]" # from a clone of this repo
7
+ #
8
+ # `datasets` is an extra rather than a dependency so the recipe rules and the
9
+ # tar adapter can be tested, and a tar-only recipe run, without it.
10
+ #
11
+ # Versions are pinned to ranges, not exact releases: a free session installs
12
+ # this beside whatever the host already has, and an exact pin would fight
13
+ # Kaggle's and Colab's own numpy.
14
+
15
+ [build-system]
16
+ requires = ["setuptools>=68"]
17
+ build-backend = "setuptools.build_meta"
18
+
19
+ [project]
20
+ name = "afrospeech-recipes"
21
+ version = "0.1.0"
22
+ description = "Load the speech data a recipe describes, from wherever it lives."
23
+ readme = "README.md"
24
+ requires-python = ">=3.10"
25
+ license = "Apache-2.0"
26
+ license-files = ["LICENSE"]
27
+ authors = [{ name = "AfriModal AI", email = "kaykola.olaleye@gmail.com" }]
28
+ keywords = ["speech", "asr", "african-languages", "datasets", "streaming"]
29
+ classifiers = [
30
+ "Development Status :: 3 - Alpha",
31
+ "Intended Audience :: Science/Research",
32
+ "Programming Language :: Python :: 3",
33
+ "Topic :: Multimedia :: Sound/Audio :: Speech",
34
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
35
+ ]
36
+ dependencies = [
37
+ "requests>=2.28",
38
+ "numpy>=1.23",
39
+ "soundfile>=0.12",
40
+ "scipy>=1.10",
41
+ ]
42
+
43
+ # The one address that is public and will stay public. The source repository
44
+ # is private, so a Source or Issues link would hand visitors a 404; both can
45
+ # be added in a later release once there is something behind them.
46
+ [project.urls]
47
+ Homepage = "https://afrimodal-ai.github.io/"
48
+
49
+ [project.optional-dependencies]
50
+ huggingface = ["datasets>=2.18"]
51
+
52
+ [tool.setuptools.packages.find]
53
+ where = ["."]
54
+ include = ["afrospeech_recipes*"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+