sonarch 0.1.0.dev0__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,14 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ *.egg-info/
4
+ build/
5
+ dist/
6
+ .venv/
7
+ .pytest_cache/
8
+ .mypy_cache/
9
+ .ruff_cache/
10
+ .coverage
11
+ htmlcov/
12
+ .DS_Store
13
+ .idea/
14
+ .vscode/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Aman Trivedi
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,368 @@
1
+ Metadata-Version: 2.5
2
+ Name: sonarch
3
+ Version: 0.1.0.dev0
4
+ Summary: The one import you need for audio work: loading, preprocessing, features, codecs and datasets, ready for ML.
5
+ Project-URL: Homepage, https://github.com/trivedi-aman/sonarch
6
+ Project-URL: Issues, https://github.com/trivedi-aman/sonarch/issues
7
+ Author: Aman Trivedi
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: audio,codec,machine-learning,preprocessing,pytorch,spectrogram
11
+ Classifier: Development Status :: 2 - Pre-Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Topic :: Multimedia :: Sound/Audio :: Analysis
20
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
21
+ Classifier: Typing :: Typed
22
+ Requires-Python: >=3.10
23
+ Requires-Dist: av>=12.0
24
+ Requires-Dist: numpy>=1.24
25
+ Requires-Dist: torch>=2.1
26
+ Provides-Extra: dev
27
+ Requires-Dist: librosa>=0.10; extra == 'dev'
28
+ Requires-Dist: mypy>=1.11; extra == 'dev'
29
+ Requires-Dist: pytest>=8.0; extra == 'dev'
30
+ Requires-Dist: ruff>=0.6; extra == 'dev'
31
+ Requires-Dist: soundfile>=0.12; extra == 'dev'
32
+ Description-Content-Type: text/markdown
33
+
34
+ # sonarch
35
+
36
+ **The one import you need for audio work: loading, preprocessing, features, codecs and datasets, ready for ML.**
37
+
38
+ ```python
39
+ import sonarch as sa
40
+
41
+ audio = sa.load("anything.mp3") # any format, any source; no system FFmpeg needed
42
+ audio = audio.resample(16_000).to_mono()
43
+ mel = sa.MelSpectrogram(n_mels=80)(audio) # CPU or GPU, matches librosa within tolerance
44
+ ```
45
+
46
+ > ⚠️ **Status: early development.** This README describes the design target. Every feature section is tagged:
47
+ > βœ… available Β· 🚧 in progress Β· πŸ“‹ planned. See the [Roadmap](#roadmap).
48
+
49
+ ---
50
+
51
+ ## Why sonarch?
52
+
53
+ Working with audio today means juggling several libraries:
54
+
55
+ - `librosa` for features (CPU-only, slow at scale)
56
+ - `torchaudio` for loading and transforms (loading is being deprecated in favour of `torchcodec`)
57
+ - `audiomentations` / `torch-audiomentations` for augmentation
58
+ - `ffmpeg` / `sox` for format conversion
59
+ - A separate repo for every neural codec (EnCodec, DAC, Mimi, SNAC…)
60
+
61
+ The glue code between them is where bugs live: **silent sample-rate mismatches**, **preprocessing that differs between training and inference**, and **data pipelines stuck on the CPU**.
62
+
63
+ sonarch gives you **one consistent API** for all of it. Where a great tool already exists, sonarch wraps it behind that API instead of reinventing it, so you get one `Audio` object, one style and one install.
64
+
65
+ | Problem | sonarch's answer |
66
+ |---|---|
67
+ | "Which library do I even use to load audio now?" | `sa.load()`: every common format, local or remote, with bundled decoders |
68
+ | Sample-rate / channel mismatch bugs | `Audio` objects carry their own metadata and check it at every step |
69
+ | Train/inference preprocessing drift | Pipelines save to YAML, so you ship the exact same steps with your model |
70
+ | Slow CPU preprocessing | Core ops run on CPU, CUDA or MPS, on single clips or batches |
71
+ | Fragmented neural codecs | One `Codec` interface over EnCodec, DAC, Mimi, SNAC |
72
+ | Huge raw datasets | Pack audio into compressed (FLAC / Opus) shards and stream them |
73
+ | "How much did compression hurt?" | Quality metrics: PESQ, STOI, SI-SDR, mel distance |
74
+
75
+ ---
76
+
77
+ ## Design principles
78
+
79
+ 1. **Easy by default, powerful on demand.** One-liners and presets for common cases; every setting is exposed for advanced users.
80
+ 2. **Metadata travels with data.** Sample rate, channels and loudness are never "assumed".
81
+ 3. **Reproducible.** A saved pipeline reloads with exactly the same configuration. Outputs match across CPU, CUDA and MPS within a tested numerical tolerance.
82
+ 4. **Device-agnostic.** The same code runs on CPU, CUDA or MPS. NumPy arrays and PyTorch tensors are both accepted.
83
+ 5. **Small core, optional extras.** The core needs only PyTorch, NumPy and a bundled decoder. Codecs, augmentation and metrics are opt-in extras.
84
+ 6. **Fail loudly.** Invalid shapes, sample rates or configs raise clear errors, never silent corruption.
85
+ 7. **Wrap first, replace later.** sonarch builds on proven libraries where they exist and only reimplements where it can be clearly faster or more correct.
86
+
87
+ ---
88
+
89
+ ## Installation
90
+
91
+ ```bash
92
+ pip install sonarch # core: load/save, resample, normalize, trim, features
93
+ pip install sonarch[augment] # augmentation ops
94
+ pip install sonarch[codecs] # neural codecs (EnCodec, DAC, Mimi, SNAC)
95
+ pip install sonarch[metrics] # PESQ, STOI, SI-SDR
96
+ pip install sonarch[cloud] # S3 / GCS / HTTP reading via fsspec
97
+ pip install sonarch[all] # everything
98
+ ```
99
+
100
+ Requires Python 3.10+ and PyTorch 2.x. Decoding uses bundled FFmpeg libraries (via PyAV), so **no system FFmpeg install is needed** on Linux, macOS or Windows.
101
+
102
+ ---
103
+
104
+ ## Quickstart
105
+
106
+ ### Load, inspect, convert 🚧
107
+
108
+ ```python
109
+ import sonarch as sa
110
+
111
+ audio = sa.load("clip.flac")
112
+ audio.sample_rate # 44100
113
+ audio.channels # 2
114
+ audio.duration # 12.4 (seconds)
115
+ audio.loudness # -18.2 (LUFS, computed on first access)
116
+
117
+ audio = audio.resample(16_000).to_mono().to("cuda")
118
+ audio.tensor # torch.Tensor, shape (channels, samples)
119
+ audio.numpy() # np.ndarray
120
+
121
+ sa.info("clip.flac") # fast metadata probe, no decoding
122
+ audio.save("clip_16k.wav")
123
+ ```
124
+
125
+ Mismatches fail loudly:
126
+
127
+ ```python
128
+ a, b = sa.load("a.wav"), sa.load("b_48k.wav")
129
+ a + b # ❌ SampleRateMismatchError: 16000 Hz vs 48000 Hz
130
+ sa.mix(a, b.resample(16_000), align="pad") # βœ… explicit, pads the shorter clip
131
+ ```
132
+
133
+ ### Build a pipeline 🚧
134
+
135
+ ```python
136
+ pipe = sa.Pipeline([
137
+ sa.Resample(16_000),
138
+ sa.ToMono(),
139
+ sa.LoudnessNorm(target_lufs=-23),
140
+ sa.TrimSilence(top_db=30),
141
+ sa.FixLength(seconds=10, mode="pad_or_crop"),
142
+ sa.MelSpectrogram(n_mels=80, n_fft=400, hop_length=160),
143
+ ])
144
+
145
+ mel = pipe("clip.wav") # path, Audio, tensor or array
146
+
147
+ pipe.save("preprocess.yaml") # ship this with your model
148
+ pipe = sa.Pipeline.load("preprocess.yaml")
149
+ ```
150
+
151
+ ### Batches on GPU πŸ“‹
152
+
153
+ ```python
154
+ pipe = pipe.to("cuda")
155
+ batch = pipe(["a.wav", "b.flac", "c.mp3"])
156
+ batch.tensor # (batch, n_mels, frames), padded to the longest item
157
+ batch.lengths # true length of each item, in frames
158
+ batch.mask # bool mask, True where values are real
159
+ ```
160
+
161
+ If the pipeline ends in `FixLength`, every item has the same length and no padding is added.
162
+
163
+ ### Presets πŸ“‹
164
+
165
+ ```python
166
+ pipe = sa.preset("whisper") # 16 kHz mono, 80-bin log-mel, 30 s (Whisper up to large-v2)
167
+ pipe = sa.preset("whisper-v3") # same, but 128 bins (Whisper large-v3)
168
+ features = pipe("speech.mp3")
169
+ ```
170
+
171
+ ---
172
+
173
+ ## Coming from another library?
174
+
175
+ | You used to write | In sonarch |
176
+ |---|---|
177
+ | `librosa.load(path, sr=16000, mono=True)` | `sa.load(path).resample(16_000).to_mono()` |
178
+ | `librosa.feature.melspectrogram(y=y, sr=sr, n_mels=80)` | `sa.MelSpectrogram(n_mels=80)(audio)` |
179
+ | `librosa.feature.mfcc(y=y, sr=sr, n_mfcc=13)` | `sa.MFCC(n_mfcc=13)(audio)` |
180
+ | `librosa.effects.trim(y, top_db=30)` | `audio.trim_silence(top_db=30)` |
181
+ | `torchaudio.load(path)` | `sa.load(path)` |
182
+ | `torchaudio.functional.resample(x, 44100, 16000)` | `audio.resample(16_000)` |
183
+ | `torchaudio.compliance.kaldi.fbank(x, ...)` | `sa.Fbank(...)(audio)` |
184
+ | `WhisperFeatureExtractor(...)(x)` | `sa.preset("whisper")(audio)` |
185
+
186
+ Numerical ops are tested against librosa / torchaudio so outputs match within tolerance. Full migration guides: πŸ“‹ `docs/migrate-librosa.md`, `docs/migrate-torchaudio.md`.
187
+
188
+ ---
189
+
190
+ ## Features
191
+
192
+ ### 1. Loading & I/O 🚧
193
+ - Decode WAV, FLAC, MP3, OGG/Opus, M4A/AAC, and audio tracks from video files
194
+ - Save to WAV, FLAC and Opus
195
+ - Fast metadata probing without decoding
196
+ - Streaming / chunked reads for long files πŸ“‹
197
+ - Read from URLs, S3 and GCS via `fsspec` (`sonarch[cloud]`) πŸ“‹
198
+
199
+ ### 2. Preprocessing ops
200
+ | Category | Ops | Status |
201
+ |---|---|---|
202
+ | Format | `Resample`, `ToMono`, `ToStereo`, `ChangeDtype` | 🚧 |
203
+ | Level | `PeakNorm`, `RMSNorm`, `LoudnessNorm` (EBU R128 / LUFS), `DCRemove` | 🚧 |
204
+ | Time | `TrimSilence`, `FixLength`, `Pad`, `Crop`, `Chunk` | 🚧 |
205
+ | Time | `VAD` | πŸ“‹ |
206
+ | Filters | `HighPass`, `LowPass`, `BandPass`, `PreEmphasis` | πŸ“‹ |
207
+ | Features | `STFT`, `MelSpectrogram`, `LogMel`, `MFCC` | 🚧 |
208
+ | Features | `Fbank` (Kaldi-compatible), `CQT`, `Chroma` | πŸ“‹ |
209
+
210
+ ### 3. Neural codecs and tokenization (`sonarch[codecs]`) πŸ“‹
211
+ One interface for discrete audio tokens, for audio language models and compression.
212
+
213
+ ```python
214
+ codec = sa.Codec("dac", bitrate="6kbps", device="cuda")
215
+ codec.sample_rate # 44100: the rate the model expects
216
+
217
+ tokens = codec.encode(audio) # (codebooks, frames) int tensor
218
+ recon = codec.decode(tokens) # Audio object
219
+
220
+ codec.encode(audio_16k) # ❌ SampleRateMismatchError: codec expects 44100 Hz
221
+ codec.encode(audio_16k, resample=True) # βœ… explicit
222
+
223
+ sa.Codec.available() # ["encodec", "dac", "mimi", "snac", ...]
224
+ ```
225
+
226
+ > **Model licenses:** sonarch is MIT, but pretrained codec weights come from their original authors and may carry different licenses. `sa.Codec.info("dac")` shows the license for each model; check it before commercial use.
227
+
228
+ ### 4. Datasets: compressed shards and streaming πŸ“‹
229
+ Turn large folders of WAV files into compact, streamable shards. Built on WebDataset-style tar shards, so they also work with existing tooling.
230
+
231
+ ```python
232
+ sa.dataset.pack(
233
+ source="raw_wavs/",
234
+ dest="shards/",
235
+ format="flac", # lossless; or "opus" with bitrate="64kbps"
236
+ shard_size="1GB",
237
+ preprocess=pipe, # optionally store preprocessed audio
238
+ )
239
+
240
+ ds = sa.dataset.stream("shards/", pipeline=pipe) # PyTorch IterableDataset
241
+ ```
242
+
243
+ Also reads Hugging Face `datasets` audio columns directly.
244
+
245
+ ### 5. Augmentation (`sonarch[augment]`) πŸ“‹
246
+ `AddNoise`, `AddReverb` (RIR), `GainJitter`, `PitchShift`, `TimeStretch`, `SpecAugment`, `Mixup`, `CodecAugment` (simulate MP3/Opus artifacts). All are probabilistic and seedable. Most run batched on GPU. `CodecAugment` and high-quality `PitchShift` / `TimeStretch` run on CPU.
247
+
248
+ ```python
249
+ train_pipe = pipe.with_augment([
250
+ sa.AddNoise(snr_db=(5, 20), p=0.5), # waveform op: placed before MelSpectrogram
251
+ sa.SpecAugment(time_masks=2, freq_masks=2), # spectrogram op: placed after it
252
+ ], seed=42)
253
+ ```
254
+
255
+ Each op declares whether it works on waveforms or spectrograms, and `with_augment` puts it in the right place automatically. `train_pipe.describe()` prints the final order.
256
+
257
+ ### 6. Quality evaluation (`sonarch[metrics]`) πŸ“‹
258
+ Know what a compression setting costs *before* you train on it.
259
+
260
+ ```python
261
+ report = sa.evaluate(original, recon, metrics=["pesq", "stoi", "si_sdr", "mel_distance"])
262
+ print(report)
263
+
264
+ sa.compare_codecs(
265
+ "eval_clips/",
266
+ codecs=[("opus", "24kbps"), ("dac", "6kbps"), ("encodec", "3kbps")],
267
+ ) # β†’ table of bitrate vs. quality
268
+ ```
269
+
270
+ PESQ only supports 8 kHz and 16 kHz audio; sonarch resamples for it and says so in the report.
271
+
272
+ ### 7. Feature caching πŸ“‹
273
+ Compute features once and store them compactly.
274
+
275
+ ```python
276
+ sa.cache.build(dataset="shards/", pipeline=pipe, dest="mel_cache/", dtype="float16")
277
+ ```
278
+
279
+ ---
280
+
281
+ ## Writing a custom op
282
+
283
+ Every op subclasses `sa.Op` and declares what kind of data it takes and returns. sonarch uses this to validate pipelines and place augmentations.
284
+
285
+ ```python
286
+ class Invert(sa.Op):
287
+ input = "wave" # "wave" or "spec"
288
+ output = "wave"
289
+
290
+ def __call__(self, audio: sa.Audio) -> sa.Audio:
291
+ return audio.replace(tensor=-audio.tensor)
292
+ ```
293
+
294
+ Ops are automatically saved to YAML if their constructor arguments are plain types (numbers, strings, lists, dicts).
295
+
296
+ ---
297
+
298
+ ## Roadmap
299
+
300
+ | Milestone | Scope | Status |
301
+ |---|---|---|
302
+ | **v0.1: Core** | `sa.load` / `save` / `info`, `Audio` object, resample, mono/stereo, normalization, trim, pad/crop, STFT / mel / MFCC matched to librosa, migration guides | 🚧 In progress |
303
+ | **v0.2: ML-ready** | `Pipeline` + YAML, batched GPU execution with padding and masks, `whisper` / `wav2vec2` presets matched to Hugging Face feature extractors, benchmarks vs. librosa / torchaudio | πŸ“‹ Planned |
304
+ | **v0.3: Codecs** | Unified `Codec` API: EnCodec, DAC, Mimi, SNAC | πŸ“‹ Planned |
305
+ | **v0.4: Data** | `dataset.pack` / `stream`, FLAC/Opus shards, HF `datasets` support, cloud reading | πŸ“‹ Planned |
306
+ | **v0.5: Augment & metrics** | Augmentation suite, `evaluate`, `compare_codecs` | πŸ“‹ Planned |
307
+ | **v1.0** | Remaining features (filters, VAD, Fbank, CQT, caching), full docs, stable API | πŸ“‹ Planned |
308
+
309
+ ---
310
+
311
+ ## Project structure
312
+
313
+ ```
314
+ sonarch/
315
+ β”œβ”€β”€ src/sonarch/
316
+ β”‚ β”œβ”€β”€ __init__.py
317
+ β”‚ β”œβ”€β”€ core/
318
+ β”‚ β”‚ β”œβ”€β”€ audio.py # Audio object + metadata validation
319
+ β”‚ β”‚ β”œβ”€β”€ pipeline.py # Pipeline, YAML save/load
320
+ β”‚ β”‚ β”œβ”€β”€ op.py # Base class for all ops
321
+ β”‚ β”‚ └── errors.py
322
+ β”‚ β”œβ”€β”€ io/ # load, save, info, decoding backends
323
+ β”‚ β”œβ”€β”€ ops/
324
+ β”‚ β”‚ β”œβ”€β”€ format.py # resample, channels, dtype
325
+ β”‚ β”‚ β”œβ”€β”€ level.py # normalization, loudness
326
+ β”‚ β”‚ β”œβ”€β”€ time.py # trim, pad/crop, chunk
327
+ β”‚ β”‚ β”œβ”€β”€ filters.py
328
+ β”‚ β”‚ └── features.py # STFT, mel, MFCC
329
+ β”‚ β”œβ”€β”€ codecs/ # Codec interface + backends
330
+ β”‚ β”œβ”€β”€ dataset/ # pack, stream, shards
331
+ β”‚ β”œβ”€β”€ augment/
332
+ β”‚ β”œβ”€β”€ metrics/
333
+ β”‚ β”œβ”€β”€ cache/
334
+ β”‚ └── presets/ # YAML preset definitions
335
+ β”œβ”€β”€ tests/
336
+ β”œβ”€β”€ benchmarks/ # speed vs. librosa / torchaudio
337
+ β”œβ”€β”€ docs/
338
+ β”œβ”€β”€ examples/
339
+ β”œβ”€β”€ pyproject.toml
340
+ └── README.md
341
+ ```
342
+
343
+ ---
344
+
345
+ ## Development
346
+
347
+ ```bash
348
+ git clone https://github.com/trivedi-aman/sonarch.git
349
+ cd sonarch
350
+ pip install -e ".[dev,all]"
351
+ pytest
352
+ ```
353
+
354
+ Conventions:
355
+ - Type hints everywhere; `mypy --strict` on `sonarch/core`
356
+ - Formatting and linting with `ruff`
357
+ - Every op needs: a unit test, a CPU/GPU parity test, and a YAML save/load round-trip test
358
+ - Numerical ops are tested against a reference (librosa / torchaudio) within tolerance
359
+
360
+ ---
361
+
362
+ ## Contributing
363
+
364
+ Contributions are welcome. Open an issue to discuss new ops, codecs or presets before sending a large PR.
365
+
366
+ ## License
367
+
368
+ MIT for the sonarch code. Pretrained model weights used by `sonarch[codecs]` keep their original licenses.