Utilities Module / ユーティリティモジュール¶
The wandas.utils module contains dataset, sample-generation, type, and helper
APIs used by Wandas. Parameters, return values, exceptions, and examples are
maintained in the generated docstrings.
wandas.utilsはdataset、sample生成、型、helper APIを提供します。引数、戻り値、例外、
使用例は生成されたdocstringで管理します。
wandas.utils.frame_dataset
¶
Attributes¶
logger = logging.getLogger(__name__)
module-attribute
¶
FrameType = ChannelFrame | SpectrogramFrame
module-attribute
¶
F = TypeVar('F', bound=FrameType)
module-attribute
¶
F_out = TypeVar('F_out', bound=FrameType)
module-attribute
¶
MetadataResolver = Callable[[Path], Mapping[str, object]]
module-attribute
¶
Classes¶
LazyFrame
dataclass
¶
Bases: Generic[F]
A class that encapsulates a frame and its loading state.
Attributes:
| Name | Type | Description |
|---|---|---|
file_path |
Path
|
File path associated with the frame |
frame |
F | None
|
Loaded frame object (None if not loaded) |
is_loaded |
bool
|
Flag indicating if the frame is loaded |
load_attempted |
bool
|
Flag indicating if loading was attempted (for error detection) |
Source code in wandas/utils/frame_dataset.py
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 | |
Attributes¶
file_path
instance-attribute
¶
metadata = field(default_factory=dict)
class-attribute
instance-attribute
¶
frame = None
class-attribute
instance-attribute
¶
is_loaded = False
class-attribute
instance-attribute
¶
load_attempted = False
class-attribute
instance-attribute
¶
Functions¶
__init__(file_path, metadata=dict(), frame=None, is_loaded=False, load_attempted=False)
¶
ensure_loaded(loader)
¶
Ensures the frame is loaded, loading it if necessary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
loader
|
Callable[[Path], F | None]
|
Function to load a frame from a file path |
required |
Returns:
| Type | Description |
|---|---|
F | None
|
The loaded frame, or None if loading failed |
Source code in wandas/utils/frame_dataset.py
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 | |
reset()
¶
Reset the frame state.
Source code in wandas/utils/frame_dataset.py
79 80 81 82 83 84 85 | |
FrameDataset
¶
Bases: Generic[F], ABC
Abstract folder-backed collection of lazily loaded Frames.
File discovery does not create Frames. Integer access creates and caches the
requested Frame, while its Dask-backed sample data remains lazy until a Frame
materialization API such as frame.data is used. A load or transform failure
is cached as an attempted item and represented by None; exceptions are also
logged.
Dataset transforms create a new dataset and leave the source dataset unchanged.
apply(), resample(), trim(), and normalize() preserve the dataset
subtype; stft() intentionally returns SpectrogramFrameDataset. Discovered
file metadata is deep-copied into derived datasets and attached to each
successfully loaded or transformed Frame.
get_metadata() returns current summary state. It does not expose a
processing-history or lineage API for the dataset.
Source code in wandas/utils/frame_dataset.py
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 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 | |
Attributes¶
folder_path = Path(folder_path)
instance-attribute
¶
sampling_rate = sampling_rate
instance-attribute
¶
signal_length = signal_length
instance-attribute
¶
file_extensions = file_extensions or ['.wav']
instance-attribute
¶
Functions¶
__init__(folder_path, sampling_rate=None, signal_length=None, file_extensions=None, lazy_loading=True, recursive=False, source_dataset=None, transform=None, metadata_resolver=None, path_metadata=False)
¶
Source code in wandas/utils/frame_dataset.py
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 | |
__len__()
¶
Return the number of files in the dataset.
Source code in wandas/utils/frame_dataset.py
320 321 322 | |
get_by_label(label)
¶
Get a frame by its label (filename).
Deprecated since 0.2.0. Use get_all_by_label() instead. The
first-match behavior is planned for removal no earlier than version
0.7.0.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
label
|
str
|
Filename (label) to search for, such as
|
required |
Returns:
| Type | Description |
|---|---|
F | None
|
F | None: Matching frame, or |
Examples:
>>> frame = dataset.get_by_label("sample_1.wav")
>>> if frame:
... print(frame.label)
Source code in wandas/utils/frame_dataset.py
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 | |
get_all_by_label(label)
¶
Get all frames matching the given label (filename).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
label
|
str
|
str. The filename (label) to search for (e.g., 'sample_1.wav'). |
required |
Returns:
| Type | Description |
|---|---|
list[F]
|
list[F]: A list of frames matching the label. If none are found, returns an empty list. |
Notes
- Search is performed against the filename portion only (i.e. Path.name).
- Each matched frame will be loaded (triggering lazy load) via
_ensure_loaded.
Source code in wandas/utils/frame_dataset.py
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 | |
__getitem__(key)
¶
__getitem__(key: int) -> F | None
__getitem__(key: str) -> list[F]
Get the frame by index (int) or label (str).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
int | str
|
int or str. Index (int) or filename/label (str). |
required |
Returns:
| Type | Description |
|---|---|
F | None | list[F]
|
F | None or list[F]: If |
Raises:
| Type | Description |
|---|---|
IndexError
|
If an integer index is outside |
TypeError
|
If |
Notes
A None result is cached as an attempted item and is not retried
automatically. Exceptions are also logged. Frame creation may inspect a file
header, but sample values remain Dask-lazy until a Frame materialization API
is used.
Examples:
>>> frame = dataset[0] # by index
>>> frames = dataset["sample_1.wav"] # list of matches by filename
Source code in wandas/utils/frame_dataset.py
385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 | |
apply(func)
¶
apply(func: Callable[[F], F_out | None]) -> FrameDataset[F_out]
apply(func: Callable[[F], Any | None]) -> FrameDataset[Any]
Create a lazy transformed dataset without changing this dataset.
The returned dataset has the same runtime dataset subtype. The callable runs
once per item when that item is first accessed. Returning None or raising
an exception represents a failed/filtered item as None; exceptions are
logged and do not abort access to other items.
Discovered file metadata is deep-copied to the derived dataset and attached
to every successfully transformed Frame. The metadata attached at discovery
takes precedence over same-named keys returned by func.
Source code in wandas/utils/frame_dataset.py
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 | |
save(output_folder, filename_prefix='')
¶
Unsupported: dataset-level persistence is not implemented.
Saving individual Frames is supported through the Frame API. This method is retained only to fail explicitly and must not be used as a persistence path.
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
Always raised because |
Source code in wandas/utils/frame_dataset.py
449 450 451 452 453 454 455 456 457 458 | |
sample(n=None, ratio=None, seed=None)
¶
Return a lazy random subset without loading Frames.
When both n and ratio are omitted, the requested size is
max(1, min(10, int(len(self) * 0.1))) and is then capped at
len(self). An empty dataset therefore returns an empty subset. When
ratio is provided, the requested size is
max(1, int(len(self) * ratio)); an explicit n takes precedence over
ratio. Explicit sizes are also clamped to the inclusive range from one
to the dataset length for non-empty datasets.
Sampling preserves file metadata and lazy Frame loading. seed makes the
selected file indices reproducible.
Source code in wandas/utils/frame_dataset.py
460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 | |
select(**criteria)
¶
Select files by exact-match resolver metadata without loading frames.
Source code in wandas/utils/frame_dataset.py
502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 | |
get_metadata()
¶
Return current dataset configuration and load-summary state.
This call does not load any Frames. loaded_count counts items whose Frame
load or transform has been attempted, including failed items cached as
None. has_transform reports whether this dataset has one lazy
transform from a source dataset. The result is a summary, not a dataset
processing history or Frame lineage.
Source code in wandas/utils/frame_dataset.py
531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 | |
ChannelFrameDataset
¶
Bases: FrameDataset[ChannelFrame]
Dataset class for handling audio files as ChannelFrames in a folder.
Source code in wandas/utils/frame_dataset.py
688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 | |
Functions¶
__init__(folder_path, sampling_rate=None, signal_length=None, file_extensions=None, lazy_loading=True, recursive=False, source_dataset=None, transform=None, metadata_resolver=None, path_metadata=False)
¶
Source code in wandas/utils/frame_dataset.py
693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 | |
select(**criteria)
¶
Select files while preserving ChannelFrameDataset processing methods.
Source code in wandas/utils/frame_dataset.py
736 737 738 | |
resample(target_sr)
¶
Resample all frames in the dataset.
Source code in wandas/utils/frame_dataset.py
740 741 742 743 744 745 746 747 748 749 750 751 752 753 | |
trim(start, end)
¶
Trim all frames in the dataset.
Source code in wandas/utils/frame_dataset.py
755 756 757 758 759 760 761 762 763 764 765 766 767 768 | |
normalize(**kwargs)
¶
Normalize all frames in the dataset.
Source code in wandas/utils/frame_dataset.py
770 771 772 773 774 775 776 777 778 779 780 781 782 783 | |
stft(n_fft=2048, hop_length=None, win_length=None, window='hann')
¶
Apply STFT to all frames in the dataset.
Source code in wandas/utils/frame_dataset.py
785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 | |
from_folder(folder_path, sampling_rate=None, file_extensions=None, recursive=False, lazy_loading=True, metadata_resolver=None, path_metadata=False)
classmethod
¶
Create a dataset, optionally inferring metadata from parent paths.
Source code in wandas/utils/frame_dataset.py
818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 | |
SpectrogramFrameDataset
¶
Bases: FrameDataset[SpectrogramFrame]
Dataset class for handling spectrogram data as SpectrogramFrames. Expected to be generated mainly as a result of ChannelFrameDataset.stft().
Source code in wandas/utils/frame_dataset.py
843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 | |
Functions¶
__init__(folder_path, sampling_rate=None, signal_length=None, file_extensions=None, lazy_loading=True, recursive=False, source_dataset=None, transform=None)
¶
Source code in wandas/utils/frame_dataset.py
849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 | |
plot(index, **kwargs)
¶
Plot the spectrogram at the specified index.
Source code in wandas/utils/frame_dataset.py
879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 | |
Functions¶
wandas.utils.generate_sample
¶
Attributes¶
Frequency = int | float | np.integer[Any] | np.floating[Any]
module-attribute
¶
Frequencies = Frequency | list[Any]
module-attribute
¶
Classes¶
Functions¶
generate_sin(freqs=1000.0, sampling_rate=16000, duration=1.0, label=None)
¶
Generate sample sine wave signals.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
freqs
|
Frequencies
|
real number or list of real numbers, default=1000.0. Positive
finite frequency of each sine wave in Hz. A scalar creates one
channel; a list creates one channel per element. Python and NumPy integer
and floating scalars are accepted and normalized to |
1000.0
|
sampling_rate
|
int
|
int, default=16000. Sampling rate in Hz. |
16000
|
duration
|
float
|
float, default=1.0. Duration of the signal in seconds. |
1.0
|
label
|
str | None
|
str, optional. Label for the entire signal. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
ChannelFrame |
ChannelFrame
|
Dask-backed ChannelFrame containing the sine wave(s). |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ValueError
|
If a frequency list is empty or a frequency is non-finite or not positive. |
Examples:
>>> import wandas as wd
>>> signal = wd.generate_sin()
>>> signal.sampling_rate
16000
Source code in wandas/utils/generate_sample.py
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 | |
generate_sin_lazy(freqs=1000.0, sampling_rate=16000, duration=1.0, label=None)
¶
Generate sample sine wave signals using lazy computation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
freqs
|
Frequencies
|
real number or list of real numbers, default=1000.0. Positive
finite frequency of each sine wave in Hz. A scalar creates one
channel; a list creates one channel per element. Python and NumPy integer
and floating scalars are accepted and normalized to |
1000.0
|
sampling_rate
|
int
|
int, default=16000. Sampling rate in Hz. |
16000
|
duration
|
float
|
float, default=1.0. Duration of the signal in seconds. |
1.0
|
label
|
str | None
|
str, optional. Label for the entire signal. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
ChannelFrame |
ChannelFrame
|
Dask-backed ChannelFrame containing the sine wave(s). |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ValueError
|
If a frequency list is empty or a frequency is non-finite or not positive. |
Notes
This is the low-level implementation name used by generate_sin. It is not
exported from the top-level wandas namespace.
Source code in wandas/utils/generate_sample.py
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 | |
wandas.utils.types
¶
wandas.utils.util
¶
Attributes¶
DB_FLOOR = 1e-12
module-attribute
¶
PA_REFERENCE = 2e-05
module-attribute
¶
DB_AMIN = 1e-15
module-attribute
¶
Functions¶
ref_weighted_dB(data, channel_metadata, ndim)
¶
Compute dB level relative to per-channel reference values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
NDArrayReal
|
NDArrayReal. Non-negative amplitude data (already absolute-valued if complex). |
required |
channel_metadata
|
list[Any]
|
list. Objects with a |
required |
ndim
|
int
|
int. Number of dimensions in the underlying dask array. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
NDArrayReal |
NDArrayReal
|
Decibel values: |
Source code in wandas/utils/util.py
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | |
validate_sampling_rate(sampling_rate, param_name='sampling_rate')
¶
Validate that sampling rate is positive.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sampling_rate
|
float
|
float. Sampling rate in Hz to validate. |
required |
param_name
|
str
|
str, default="sampling_rate". Name of the parameter being validated (for error messages). |
'sampling_rate'
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If sampling_rate is not positive (i.e., <= 0). |
Examples:
>>> validate_sampling_rate(44100) # No error
>>> validate_sampling_rate(0) # Raises ValueError
>>> validate_sampling_rate(-100) # Raises ValueError
Source code in wandas/utils/util.py
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 | |
unit_to_ref(unit)
¶
Convert unit to reference value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
unit
|
str
|
str. Unit string. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
Reference value for the unit. For 'Pa', returns 2e-5 (20 μPa). For other units, returns 1.0. |
Source code in wandas/utils/util.py
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 | |
calculate_rms(wave)
¶
Calculate the root mean square of the wave.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
wave
|
NDArrayReal
|
NDArrayReal. Input waveform data. Can be multi-channel (shape: [channels, samples]) or single channel (shape: [samples]). |
required |
Returns:
| Type | Description |
|---|---|
NDArrayReal
|
Union[float, NDArray[np.float64]]: RMS value(s). For multi-channel input, returns an array of RMS values, one per channel. For single-channel input, returns a single RMS value. |
Source code in wandas/utils/util.py
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 | |
calculate_desired_noise_rms(clean_rms, snr)
¶
Calculate the desired noise RMS based on clean signal RMS and target SNR.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
clean_rms
|
NDArrayReal
|
"NDArrayReal". RMS value(s) of the clean signal. Can be a single value or an array for multi-channel. |
required |
snr
|
float
|
float. Target Signal-to-Noise Ratio in dB. |
required |
Returns:
| Type | Description |
|---|---|
NDArrayReal
|
"NDArrayReal": Desired noise RMS value(s) to achieve the target SNR. |
Source code in wandas/utils/util.py
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 | |
amplitude_to_db(amplitude, ref)
¶
Convert amplitude to decibel.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
amplitude
|
NDArrayReal
|
NDArrayReal. Input amplitude data. |
required |
ref
|
float
|
float. Reference value for conversion. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
NDArrayReal |
NDArrayReal
|
Amplitude data converted to decibels. |
Source code in wandas/utils/util.py
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 | |
level_trigger(data, level, offset=0, hold=1)
¶
Find points where the signal crosses the specified level from below.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
NDArrayReal
|
NDArrayReal. Input signal data. |
required |
level
|
float
|
float. Threshold level for triggering. |
required |
offset
|
int
|
int, default=0. Offset to add to trigger points. |
0
|
hold
|
int
|
int, default=1. Minimum number of samples between successive trigger points. |
1
|
Returns:
| Type | Description |
|---|---|
list[int]
|
list of int: List of sample indices where the signal crosses the level. |
Source code in wandas/utils/util.py
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 | |
cut_sig(data, point_list, cut_len, taper_rate=0, dc_cut=False)
¶
Cut segments from signal at specified points.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
NDArrayReal
|
NDArrayReal. Input signal data. |
required |
point_list
|
list[int]
|
list of int. List of starting points for cutting. |
required |
cut_len
|
int
|
int. Length of each segment to cut. |
required |
taper_rate
|
float
|
float, default=0. Taper rate for Tukey window applied to segments. A value of 0 means no tapering, 1 means full tapering. |
0
|
dc_cut
|
bool
|
bool, default=False. Whether to remove DC component (mean) from segments. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
NDArrayReal |
NDArrayReal
|
Array containing cut segments with shape (n_segments, cut_len). |
Source code in wandas/utils/util.py
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 | |