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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
//! Python spectrogram result class.
use numpy::PyArray2;
use pyo3::prelude::*;
use crate::{AmpScaleSpec, Spectrogram, SpectrogramParams};
use super::params::PySpectrogramParams;
/// Spectrogram computation result.
///
/// Contains the spectrogram data as a `NumPy` array along with frequency and time axes and the parameters used to create it.
///
#[pyclass(name = "Spectrogram", skip_from_py_object)]
pub struct PySpectrogram {
py_data: Py<PyArray2<f64>>,
// Extracted metadata (no longer storing full Spectrogram to avoid duplication)
frequencies: Vec<f64>,
times: Vec<f64>,
params: SpectrogramParams,
db_range: Option<(f64, f64)>,
}
impl PySpectrogram {
/// Create a PySpectrogram from computed Rust spectrogram.
/// Extracts metadata and transfers data ownership to Python (!).
pub(crate) fn from_spectrogram<FreqScale, AmpScale>(
py: Python<'_>,
spec: Spectrogram<FreqScale, AmpScale>,
) -> Self
where
FreqScale: Copy + Clone + 'static,
AmpScale: AmpScaleSpec + 'static,
{
// Extract metadata before consuming spectrogram
let frequencies = spec.frequencies().to_vec();
let times = spec.times().to_vec();
let params = spec.params().clone();
let db_range = spec.db_range();
// Transfer ownership of Array2 to Python (NO COPY!)
let array = spec.into_data();
let py_data = PyArray2::from_owned_array(py, array).unbind();
Self {
py_data,
frequencies,
times,
params,
db_range,
}
}
}
#[pymethods]
impl PySpectrogram {
/// Get the spectrogram data as a `NumPy` array.
///
/// Returns
/// -------
/// numpy.typing.NDArray[numpy.float64]
/// 2D `NumPy` array with shape (`n_bins`, `n_frames`)
#[getter]
fn data<'py>(&'py self, py: Python<'py>) -> Bound<'py, PyArray2<f64>> {
// Return the Python-allocated array (no copy!)
self.py_data.bind(py).clone()
}
/// Get the frequency axis values.
///
/// Returns
/// -------
/// list[float]
/// List of frequency values (Hz or scale-specific units)
#[getter]
fn frequencies(&self) -> &[f64] {
&self.frequencies
}
/// Get the time axis values.
///
/// Returns
/// -------
/// list[float]
/// List of time values in seconds
#[getter]
fn times(&self) -> &[f64] {
&self.times
}
/// Get the number of frequency bins.
///
/// Returns
/// -------
/// int
/// Number of frequency bins
#[getter]
const fn n_bins(&self) -> usize {
self.frequencies.len()
}
/// Get the number of time frames.
///
/// Returns
/// -------
/// int
/// Number of time frames
#[getter]
const fn n_frames(&self) -> usize {
self.times.len()
}
/// Get the shape of the spectrogram.
///
/// Returns
/// -------
/// tuple[int, int]
/// Tuple of (`n_bins`, `n_frames`)
#[getter]
const fn shape(&self) -> (usize, usize) {
(self.n_bins(), self.n_frames())
}
/// Get the frequency range.
///
/// Returns
/// -------
/// tuple[float, float]
/// Tuple of (`f_min`, `f_max`) in Hz or scale-specific units
fn frequency_range(&self) -> (f64, f64) {
if self.frequencies.is_empty() {
(0.0, 0.0)
} else {
(
self.frequencies[0],
self.frequencies[self.frequencies.len() - 1],
)
}
}
/// Get the total duration.
///
/// Returns
/// -------
/// float
/// Duration in seconds
fn duration(&self) -> f64 {
if self.times.is_empty() {
0.0
} else {
self.times[self.times.len() - 1]
}
}
/// Get the decibel range if applicable.
///
/// Returns
/// -------
/// tuple[float, float] or None
/// Tuple of (`min_db`, `max_db`) for decibel-scaled spectrograms, None otherwise
const fn db_range(&self) -> Option<(f64, f64)> {
self.db_range
}
/// Get the computation parameters.
///
/// Returns
/// -------
/// SpectrogramParams
/// The `SpectrogramParams` used to compute this spectrogram
#[getter]
fn params(&self) -> PySpectrogramParams {
self.params.clone().into()
}
fn __repr__(&self) -> String {
format!(
"Spectrogram(shape=({}, {}))",
self.n_bins(),
self.n_frames()
)
}
fn __str__(&self) -> String {
self.__repr__()
}
const fn __len__(&self) -> usize {
self.n_frames()
}
/// Get the transpose of the spectrogram data.
///
/// Returns
/// -------
/// numpy.typing.NDArray[numpy.float64]
/// Transposed 2D `NumPy` array with shape (`n_frames`, `n_bins`)
#[getter]
#[allow(non_snake_case)]
fn T<'py>(&'py self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
let arr = self.py_data.bind(py);
// Use numpy's .T property for transpose
arr.getattr("T").map(|t| t.clone().into_any())
}
#[pyo3(signature = (dtype), text_signature = "($self, dtype)")]
fn astype<'py>(
&'py self,
py: Python<'py>,
dtype: &Bound<'py, PyAny>,
) -> PyResult<Bound<'py, PyAny>> {
let arr = self.py_data.bind(py);
arr.call_method1("astype", (dtype,))
.map(pyo3::Bound::into_any)
}
#[pyo3(signature = (dtype=None), text_signature = "($self, dtype=None)")]
fn __array__<'py>(
&self,
py: Python<'py>,
dtype: Option<&Bound<'py, PyAny>>,
) -> PyResult<Bound<'py, PyAny>> {
let arr = self.py_data.bind(py);
if let Some(dt) = dtype {
// Convert to requested dtype
let casted = arr.call_method1("astype", (dt,))?;
Ok(casted)
} else {
// Return as-is (f64)
Ok(arr.clone().into_any())
}
}
fn __getitem__<'py>(
&'py self,
py: Python<'py>,
idx: &Bound<'py, PyAny>,
) -> PyResult<Py<PyAny>> {
let arr = self.py_data.bind(py);
let sliced: Bound<'py, PyAny> = arr.get_item(idx)?;
Ok(sliced.unbind())
}
/// Return the device type and device ID for DLPack protocol.
///
/// Returns
/// -------
/// tuple[int, int]
/// A tuple of (device_type, device_id). Always returns (1, 0) for CPU.
///
/// Notes
/// -----
/// This method is part of the DLPack protocol for tensor exchange.
/// Device type 1 indicates CPU. This library only supports CPU tensors.
#[staticmethod]
const fn __dlpack_device__() -> (i32, i32) {
(1, 0) // (kDLCPU, device_id=0)
}
/// Export the spectrogram data as a DLPack capsule for tensor exchange.
///
/// This method implements the DLPack protocol, enabling efficient data sharing with
/// deep learning frameworks like PyTorch, JAX, and TensorFlow without copying data.
///
/// Parameters
/// ----------
/// stream : int, optional
/// Must be None for CPU tensors. Provided for protocol compatibility.
/// max_version : tuple[int, int], optional
/// Maximum DLPack version supported by the consumer. Must be >= (1, 0).
/// dl_device : tuple[int, int], optional
/// Target device (device_type, device_id). If specified, must be (1, 0) for CPU.
/// copy : bool, optional
/// If True, create a copy of the data. If False or None (default), return
/// a view when possible.
///
/// Returns
/// -------
/// PyCapsule
/// A DLPack capsule named "dltensor" containing the tensor data.
///
/// Raises
/// ------
/// BufferError
/// If stream is not None, if the requested device is not CPU, or if the
/// requested DLPack version is not supported.
///
/// Examples
/// --------
/// >>> import spectrograms as sg
/// >>> import torch
/// >>> import numpy as np
/// >>>
/// >>> samples = np.random.randn(16000)
/// >>> stft = sg.StftParams(n_fft=512, hop_size=256, window= sg.WindowType.hanning)
/// >>> params = sg.SpectrogramParams(stft, sample_rate=16000.0)
/// >>> spec = sg.compute_mel_power_spectrogram(samples, params, n_mels=128)
/// >>>
/// >>> # conversion to PyTorch
/// >>> tensor = torch.from_dlpack(spec)
/// >>> print(tensor.shape, tensor.dtype)
///
/// Notes
/// -----
/// The DLPack protocol enables data exchange between Python array libraries.
/// The returned capsule can be consumed by frameworks supporting DLPack (PyTorch, JAX,
/// TensorFlow, etc.) using their respective `from_dlpack()` functions.
///
/// The data remains owned by the Python array until all consumers release it.
#[pyo3(signature = (*, stream=None, max_version=None, dl_device=None, copy=None))]
fn __dlpack__<'py>(
&self,
py: Python<'py>,
stream: Option<&Bound<'py, PyAny>>,
max_version: Option<(u32, u32)>,
dl_device: Option<(i32, i32)>,
copy: Option<bool>,
) -> PyResult<Bound<'py, pyo3::types::PyCapsule>> {
use crate::python::dlpack::{DLPACK_FLAG_BITMASK_IS_COPIED, create_dlpack_capsule};
// Validate: stream must be None for CPU
if stream.is_some() {
return Err(pyo3::exceptions::PyBufferError::new_err(
"stream must be None for CPU tensors",
));
}
// Validate: version must be >= 1.0
if let Some((major, minor)) = max_version {
if major < 1 {
return Err(pyo3::exceptions::PyBufferError::new_err(format!(
"Unsupported DLPack version: {major}.{minor}"
)));
}
}
// Validate: only CPU device supported
if let Some((dev_type, dev_id)) = dl_device {
if dev_type != 1 || dev_id != 0 {
return Err(pyo3::exceptions::PyBufferError::new_err(
"Only CPU device (1, 0) is supported",
));
}
}
// Handle copy parameter
let mut flags = 0u64;
if copy == Some(true) {
flags |= DLPACK_FLAG_BITMASK_IS_COPIED;
}
// Use the Python-allocated array directly (true !)
let arr = self.py_data.bind(py).clone();
create_dlpack_capsule(py, &arr, flags)
}
}
/// Register the spectrogram class with the Python module.
pub fn register(_py: Python, parent: &Bound<'_, PyModule>) -> PyResult<()> {
parent.add_class::<PySpectrogram>()?;
Ok(())
}