IO Module / 入出力モジュール¶
The wandas.io module provides readers for external data and persistence for
WDF artifacts. Input, output, units, and compatibility contracts live in the
generated docstrings.
wandas.ioは外部データのreaderとWDF artifactの永続化を提供します。入力、出力、単位、
互換性の契約は生成されたdocstringを正本とします。
wandas.inspect(source, *, file_type=None, source_name=None)
¶
Inspect an audio header before constructing a Frame or decoding samples.
This synchronous preflight supports the built-in SoundFile audio reader
(WAV, W64, RF64, FLAC, OGG/OGA, Opus, MP3, AIFF/AIF, SND/AU and CAF). It neither constructs a Dask graph nor
decodes PCM. CSV, WDF, URL downloads and custom readers are deliberately
unsupported: CSV metadata requires parsing the sampled table, while custom
readers cannot guarantee header-only inspection. Use read or load
for those workflows.
In-memory format inference matches read: explicit file_type, then
a stream's .name suffix, then source_name, then anonymous WAV.
Local paths use their suffix unless file_type is explicit. A seekable
binary stream is inspected from position zero and its original position is
restored on success or failure. A borrowed stream is never closed. Local
handles opened internally are closed by the reader. This is a snapshot;
reading the source later inspects it again and does not reuse this result.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str | Path | bytes | bytearray | memoryview | BinaryIO
|
Local path, bytes-like value, or seekable readable binary stream. |
required |
file_type
|
str | None
|
Optional audio extension, case-insensitive with or without a dot. |
None
|
source_name
|
str | None
|
Optional in-memory format hint; never another resource to open. |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
A dictionary with |
dict[str, Any]
|
|
dict[str, Any]
|
describe the complete original recording, without channel or time slicing. |
Raises:
| Type | Description |
|---|---|
TypeError
|
The source type is unsupported or the stream is text. |
ValueError
|
The format is unsupported, a URL is supplied, or a stream cannot be rewound and restored without consuming input. |
FileNotFoundError
|
A local path does not exist. |
OSError
|
A filesystem operation fails for an inaccessible local source. |
RuntimeError
|
SoundFile raises |
Examples:
>>> import wandas as wd
>>> info = wd.inspect("recording.wav")
>>> if info["channels"] <= 8 and info["duration"] <= 180:
... recording = wd.read("recording.wav")
Source code in wandas/io/inspect.py
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 | |
wandas.io.readers
¶
Attributes¶
logger = logging.getLogger(__name__)
module-attribute
¶
Classes¶
DownloadedTemporaryFile
dataclass
¶
Temporary file created for streamed URL downloads.
Source code in wandas/io/readers.py
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | |
Attributes¶
path
instance-attribute
¶
temp_dir
instance-attribute
¶
Functions¶
__init__(path, temp_dir)
¶
__post_init__()
¶
Source code in wandas/io/readers.py
29 30 31 32 33 34 | |
__enter__()
¶
Source code in wandas/io/readers.py
36 37 | |
__exit__(exc_type, exc, tb)
¶
Source code in wandas/io/readers.py
39 40 | |
cleanup()
¶
Source code in wandas/io/readers.py
42 43 44 | |
CSVFileInfoParams
¶
Bases: TypedDict
Type definition for CSV file reader parameters in get_file_info.
Attributes:
| Name | Type | Description |
|---|---|---|
delimiter |
str
|
Delimiter character. Defaults to |
header |
Optional[int]
|
Row number to use as header. Defaults to 0
(first row); use |
time_column |
Union[int, str]
|
Index or name of the time column. Defaults to 0. |
Source code in wandas/io/readers.py
47 48 49 50 51 52 53 54 55 56 57 58 59 60 | |
CSVGetDataParams
¶
Bases: TypedDict
Type definition for CSV file reader parameters in get_data.
Attributes:
| Name | Type | Description |
|---|---|---|
delimiter |
str
|
Delimiter character. Defaults to |
header |
Optional[int]
|
Row number to use as header. Defaults to 0
(first row); use |
time_column |
Union[int, str]
|
Index or name of the time column. Defaults to 0. |
Source code in wandas/io/readers.py
63 64 65 66 67 68 69 70 71 72 73 74 75 76 | |
FileReader
¶
Bases: ABC
Base class for external data readers.
Implementations return real channel-first arrays. Audio readers must apply full-scale decoding before returning values.
Source code in wandas/io/readers.py
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 | |
Attributes¶
supported_extensions = []
class-attribute
¶
Functions¶
get_file_info(path, **kwargs)
abstractmethod
classmethod
¶
Get basic information about the audio file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path | bytes | bytearray | memoryview | BinaryIO
|
Path to the file. |
required |
**kwargs
|
Any
|
Additional parameters specific to the file reader. |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary containing file information including: - samplerate: Sampling rate in Hz - channels: Number of channels - frames: Total number of frames - format: File format - duration: Duration in seconds |
Source code in wandas/io/readers.py
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 | |
get_data(path, channels, start_idx, frames, **kwargs)
abstractmethod
classmethod
¶
Read audio data from the file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path | bytes | bytearray | memoryview | BinaryIO
|
Path to the file. |
required |
channels
|
list[int]
|
List of channel indices to read. |
required |
start_idx
|
int
|
Starting frame index. |
required |
frames
|
int
|
Number of frames to read. |
required |
**kwargs
|
Any
|
Additional parameters specific to the file reader. |
{}
|
Returns:
| Type | Description |
|---|---|
ArrayLike
|
Array of shape (channels, frames) containing the audio data. |
Source code in wandas/io/readers.py
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 | |
can_read(path)
classmethod
¶
Check if this reader can handle the file based on extension.
Source code in wandas/io/readers.py
146 147 148 149 150 151 152 | |
SoundFileReader
¶
Bases: FileReader
Audio file reader using SoundFile library.
Source code in wandas/io/readers.py
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 | |
Attributes¶
supported_extensions = _soundfile_extensions()
class-attribute
¶
Functions¶
get_file_info(path, **kwargs)
classmethod
¶
Get basic information about the audio file.
Source code in wandas/io/readers.py
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 | |
get_data(path, channels, start_idx, frames, **kwargs)
classmethod
¶
Read full-scale audio data from the file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path | bytes | bytearray | memoryview | BinaryIO
|
Path, bytes or binary stream of the audio file. |
required |
channels
|
list[int]
|
Channel indices to read. |
required |
start_idx
|
int
|
First frame to read. |
required |
frames
|
int
|
Number of frames, or a negative value for all remaining frames. |
required |
**kwargs
|
Any
|
|
{}
|
Source code in wandas/io/readers.py
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 | |
CSVFileReader
¶
Bases: FileReader
CSV file reader for time series data.
Metadata inspection eagerly parses the complete table to determine its exact
shape and sampling rate. Sample values in the public Frame remain Dask-backed,
and get_data() parses the table again when that graph is computed.
Rates are estimated from the mean positive time interval without rounding
fractional rates to integers. Only integer-near floating-point roundoff is
corrected. Unusable time coordinates report rate zero, which the public
Frame reader rejects before indexing samples. Increasing times that deviate
by more than a quarter of the mean interval from the uniform grid starting
at the first time raise ValueError. When the times show the pattern of
rounding to a decimal step, they are instead compared with their
best-fitting uniform grid and may deviate by up to half that step, so times
printed with few decimals are accepted. When the printed intervals are one
and two steps, the two-step interval must occur at least twice for the times
to count as rounded, because a single one marks a dropped sample in exact
times; a short rounded file with only one (for example 20 rows of 96 kHz
times printed with 5 decimals) is rejected. Both limits add a few float64
spacings at the times' magnitude. When that step or float64 resolution
approaches an interval, some dropped samples match a rounded grid of a
slightly lower rate and go undetected; for example, a 1 kHz logger with
millisecond times and two evenly spaced missing rows reads as about 998 Hz.
Source code in wandas/io/readers.py
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 | |
Attributes¶
supported_extensions = ['.csv']
class-attribute
¶
Functions¶
get_file_info(path, **kwargs)
classmethod
¶
Get basic information about the CSV file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path | bytes | bytearray | memoryview | BinaryIO
|
Union[str, Path]. Path to the CSV file. |
required |
**kwargs
|
Any
|
Any. Additional parameters for CSV reading. Supported parameters:
|
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict[str, Any]: Dictionary containing file information including: - samplerate: Estimated sampling rate in Hz - channels: Number of data channels (excluding time column) - frames: Total number of frames - format: "CSV" - duration: Duration in seconds (or None if cannot be calculated) - ch_labels: List of channel labels |
Notes
This method accepts CSV-specific parameters through kwargs. See CSVFileInfoParams for supported parameter types.
Source code in wandas/io/readers.py
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 | |
get_data(path, channels, start_idx, frames, **kwargs)
classmethod
¶
Read data from the CSV file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path | bytes | bytearray | memoryview | BinaryIO
|
Union[str, Path]. Path to the CSV file. |
required |
channels
|
list[int]
|
list[int]. List of channel indices to read. |
required |
start_idx
|
int
|
int. Starting frame index. |
required |
frames
|
int
|
int. Number of frames to read. |
required |
**kwargs
|
Any
|
Any. Additional parameters for CSV reading. Supported parameters:
|
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
ArrayLike |
ArrayLike
|
Array of shape (channels, frames) containing the data. |
Notes
This method accepts CSV-specific parameters through kwargs. See CSVGetDataParams for supported parameter types.
Source code in wandas/io/readers.py
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 | |
Functions¶
download_url_to_temporary_file(url, *, timeout, suffix=None, resource_name='file', max_bytes=None, chunk_size=None)
¶
Source code in wandas/io/readers.py
606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 | |
supported_formats()
¶
Return file extensions supported by the registered readers.
Source code in wandas/io/readers.py
698 699 700 701 702 703 | |
get_file_reader(path, *, file_type=None)
¶
Return the registered reader selected by an explicit type or path suffix.
file_type is case-insensitive and may include or omit the leading dot.
This lower-level registry boundary does not guess a format from file
contents. The public :func:wandas.read entry point owns the additional
name-based inference and anonymous-WAV compatibility default.
Raises:
| Type | Description |
|---|---|
ValueError
|
If neither a type nor suffix is available, or if the normalized extension has no registered reader. |
Source code in wandas/io/readers.py
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 | |
register_file_reader(reader_class)
¶
Register a new file reader.
Source code in wandas/io/readers.py
763 764 765 766 767 | |
wandas.io.wav_io
¶
Attributes¶
logger = logging.getLogger(__name__)
module-attribute
¶
Classes¶
Functions¶
write_wav(filename, target, format=None)
¶
Write a ChannelFrame object to a WAV file.
Floating-point samples use IEEE FLOAT regardless of amplitude, preserving values outside [-1, 1] without normalization or PCM clipping. Values are stored at float32 precision. Integer input retains the format's default subtype. Writing computes the calibrated samples synchronously.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
str | PathLike[str] | BinaryIO
|
Path or writable binary stream. Caller-owned streams remain open. Stream output is encoded in memory and written once at the current position, so non-seekable streams and streams with existing content are supported. |
required |
target
|
ChannelFrame
|
ChannelFrame. ChannelFrame object containing the data to write. |
required |
format
|
str | None
|
Required for streams. Paths infer the format from their extension. |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If target is not a ChannelFrame or a stream has no format. |
Source code in wandas/io/wav_io.py
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 | |
wandas.io.wdf_io
¶
Strict xarray-backed persistence for typed WDF 0.4/0.5/0.6 artifacts.
Attributes¶
WDF_FORMAT_VERSION = '0.4'
module-attribute
¶
__all__ = ['WDF_FORMAT_VERSION', 'load', 'save']
module-attribute
¶
Classes¶
Functions¶
save(frame, path, *, compress='gzip', overwrite=False)
¶
Save an exact built-in Frame as WDF 0.4, 0.5 or sparse 0.6.
A time-frequency Frame with a known physical frame origin uses WDF 0.5. Sparse time-frequency results use WDF 0.6 with explicit sparse state. All other Frames retain WDF 0.4. Older readers reject new versions explicitly; this preserves placement instead of silently discarding its additional state.
The artifact retains the Frame label, user metadata, channel labels and
metadata (units, references, calibration, and channel extras), source-time
offsets, analysis coordinates, and the derived operation_history view.
Metadata fields use strict JSON encoding and therefore follow JSON value
semantics (for example, a tuple is loaded as a list).
It stores the concrete Frame result; previous references and replayable
Recipe intent are not persisted.
Dask data is handed directly to xarray and is written synchronously; Wandas does
not first materialize the complete tensor with frame._data.compute().
The frame is written to a temporary file first, so a failure while computing
or writing it leaves an existing file unchanged and creates no partial file.
A new file is then moved into place. An existing file is overwritten in place
by copying the finished temporary file into it, so it keeps its hard links,
owner, group, permission bits and ACLs, and a symlinked path updates the file
it points to. Overwriting a file that is not writable, or an HDF5 file that is
open or locked, raises OSError before anything is computed. An
interruption of that final copy (for example a full disk or a power loss), or
another process opening the file between that check and the copy, can still
leave the existing file incomplete.
Saving needs the io extra (pip install "wandas[io]"); without it,
ImportError names that install command.
Source code in wandas/io/wdf_io.py
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 | |
load(path)
¶
Load a local WDF 0.4, 0.5 or 0.6 artifact as its exact built-in Frame type.
WDF 0.4 time-frequency Frames have unknown physical center times; their existing zero-based time axes remain available. WDF 0.5 restores the explicit physical origin without inferring it from history. WDF 0.6 also restores the sparse-window permission, retaining gaps in the time axis.
The returned Frame restores the saved label, user metadata, channel labels
and metadata (units, references, calibration, and channel extras),
source-time offsets, analysis coordinates, and derived
operation_history view. Metadata follows strict JSON value semantics;
for example, a tuple saved in metadata is loaded as a list. WDF does not
restore a previous reference or replayable Recipe intent.
The returned Frame owns access to its source internally. Keep the source path
unchanged while that Frame or Frames derived from it are in use. Obtain NumPy
values through frame.data without managing the storage backend directly.
Loading needs the io extra (pip install "wandas[io]"); without it,
ImportError names that install command.
Source code in wandas/io/wdf_io.py
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 | |