From 185e919e46a297e6bab1a6c09f8074b282a40974 Mon Sep 17 00:00:00 2001 From: Tom Pollard Date: Mon, 23 Nov 2026 19:50:22 -0500 Subject: [PATCH 1/2] Read EDF and WAV files from physionet:// and other URIs read_edf, rdedfann and read_wav opened record_name with open(), so they could not read a physionet:// (or s3://, memory://) URI, although every other function that takes pn_dir can. Open the file with a new helper, _open_input_file, which reads a URI into memory, and read the samples with np.frombuffer and the file size with seek, instead of np.fromfile and os.path.getsize, which need a local file. Name output files after the last part of a URI on every platform. Local files and pn_dir are read as before. Part of #534. --- changelog.d/converters-read-uris.rst | 7 ++++ src/wfdb/io/_coreio.py | 25 ++++++++++++ src/wfdb/io/convert/edf.py | 25 +++++++----- src/wfdb/io/convert/wav.py | 26 +++++++----- tests/test_physionet_uri.py | 59 ++++++++++++++++++++++++++++ 5 files changed, 124 insertions(+), 18 deletions(-) create mode 100644 changelog.d/converters-read-uris.rst diff --git a/changelog.d/converters-read-uris.rst b/changelog.d/converters-read-uris.rst new file mode 100644 index 00000000..72cf31a7 --- /dev/null +++ b/changelog.d/converters-read-uris.rst @@ -0,0 +1,7 @@ +**Read EDF and WAV files from physionet:// and other URIs** + ``read_edf``, ``rdedfann`` and ``read_wav`` now take a cloud URI as + ``record_name``, such as ``physionet://chbmit/1.0.0/chb01/chb01_01.edf``, + ``s3://`` or ``memory://``, as ``rdrecord`` and ``rdann`` do, and read the + file without saving a copy. All of the functions that take ``pn_dir`` now + also take a ``physionet://`` URI. Output files written by ``wfdb_to_edf`` + and ``wfdb_to_wav`` for a URI are named after the record, on every platform. diff --git a/src/wfdb/io/_coreio.py b/src/wfdb/io/_coreio.py index d258c865..70483691 100644 --- a/src/wfdb/io/_coreio.py +++ b/src/wfdb/io/_coreio.py @@ -1,3 +1,4 @@ +import io import os import posixpath @@ -63,6 +64,30 @@ def _split_path(record_name): return os.path.split(path) +def _open_input_file(path): + """Open a local file, or a file at a cloud URI, to read in binary mode. + + A file at a cloud URI, such as a `physionet://` URI, is read into memory, + so that it can be read, sought and sized like a local file. + + Parameters + ---------- + path : str or os.PathLike + The path of a local file, or a cloud URI. + + Returns + ------- + file + The open file. + + """ + path = os.fspath(path) + if any(path.startswith(proto) for proto in CLOUD_PROTOCOLS): + with _fsspec_open(path, "rb") as f: + return io.BytesIO(f.read()) + return open(path, "rb") + + def _join_path(dir_name, file_name): """Join a local directory or cloud URI with a file name. diff --git a/src/wfdb/io/convert/edf.py b/src/wfdb/io/convert/edf.py index 5e74366c..fe3c8725 100644 --- a/src/wfdb/io/convert/edf.py +++ b/src/wfdb/io/convert/edf.py @@ -9,6 +9,7 @@ import pandas as pd from wfdb.io import download +from wfdb.io._coreio import _open_input_file, _split_path from wfdb.io._signal import _checksums from wfdb.io.annotation import Annotation, format_ann_from_df, wrann from wfdb.io.record import SIG_UNITS, Record, rdrecord @@ -43,7 +44,10 @@ def read_edf( Parameters ---------- record_name : str - The name of the input EDF record to be read. + The path of the input EDF file to be read, including its + extension. This can also be a cloud URI, such as + 'physionet://chbmit/1.0.0/chb01/chb01_01.edf' or 's3://...', which + is read without saving a copy of the file. pn_dir : str, optional Option used to stream data from Physionet. The Physionet database directory from which to find the required record files. @@ -142,7 +146,7 @@ def read_edf( open(record_name, "wb").write(f.read()) # Open the desired file - edf_file = open(record_name, mode="rb") + edf_file = _open_input_file(record_name) # Version of this data format (8 bytes) version = struct.unpack("<8s", edf_file.read(8))[0].decode(encoding) @@ -323,9 +327,7 @@ def read_edf( struct.unpack("<32s", edf_file.read(32))[0].decode(encoding) # Pre-process the acquired data before creating the record - record_name_out = ( - record_name.split(os.sep)[-1].replace("-", "_").replace(".edf", "") - ) + record_name_out = _split_path(record_name)[1].replace("-", "_").replace(".edf", "") sample_rate = [int(i / block_duration) for i in samps_per_block] fs = functools.reduce(math.gcd, sample_rate) samps_per_frame = [int(s / min(samps_per_block)) for s in samps_per_block] @@ -386,7 +388,9 @@ def read_edf( } sig_data = np.empty((sig_len, n_sig)) - temp_sig_data = np.fromfile(edf_file, dtype=np.int16) + # Read the rest of the file, ignoring a final odd byte + data = edf_file.read() + temp_sig_data = np.frombuffer(data, dtype=np.int16, count=len(data) // 2) temp_sig_data = temp_sig_data.reshape((-1, sum(samps_per_block))) temp_all_sigs = np.hsplit(temp_sig_data, np.cumsum(samps_per_block)[:-1]) @@ -578,7 +582,7 @@ def wfdb_to_edf( smooth_frames=False, channels=channels, ) - record_name_out = record_name.split(os.sep)[-1].replace("-", "_") + record_name_out = _split_path(record_name)[1].replace("-", "_") # Maximum data block length, in bytes edf_max_block = 61440 @@ -1000,7 +1004,10 @@ def rdedfann( Parameters ---------- record_name : str - The name of the input EDF record to be read. + The path of the input EDF file to be read, including its + extension. This can also be a cloud URI, such as + 'physionet://chbmit/1.0.0/chb01/chb01_01.edf' or 's3://...', which + is read without saving a copy of the file. pn_dir : str, optional Option used to stream data from Physionet. The Physionet database directory from which to find the required record files. @@ -1152,7 +1159,7 @@ def rdedfann( ) df_out = format_ann_from_df(df_in) # Remove extension from input file name - record_name = record_name.split(os.sep)[-1].split(".")[0] + record_name = _split_path(record_name)[1].split(".")[0] extension = "atr" fs = rec.fs sample = (df_out["onset"].to_numpy() * fs).astype(np.int64) diff --git a/src/wfdb/io/convert/wav.py b/src/wfdb/io/convert/wav.py index de704d8f..6455dddb 100644 --- a/src/wfdb/io/convert/wav.py +++ b/src/wfdb/io/convert/wav.py @@ -5,6 +5,7 @@ import numpy as np from wfdb.io import Record, download +from wfdb.io._coreio import _open_input_file, _split_path from wfdb.io._signal import _checksums, _digi_nan from wfdb.io.record import rdrecord @@ -67,7 +68,7 @@ def wfdb_to_wav( physical=False, smooth_frames=True, ) - record_name_out = record_name.split(os.sep)[-1].replace("-", "_") + record_name_out = _split_path(record_name)[1].replace("-", "_") # Get information needed for the header and format chunks num_samps = record.sig_len @@ -159,7 +160,10 @@ def read_wav(record_name, pn_dir=None, delete_file=True, record_only=False): Parameters ---------- record_name : str - The name of the input .wav record to be read. + The path of the input .wav file to be read, including its + extension. This can also be a cloud URI, such as + 'physionet:////.wav' or 's3://...', which + is read without saving a copy of the file. pn_dir : str, optional Option used to stream data from Physionet. The Physionet database directory from which to find the required record files. @@ -232,16 +236,16 @@ def read_wav(record_name, pn_dir=None, delete_file=True, record_only=False): with download._open_pn_file(pn_dir, record_name) as f: open(record_name, "wb").write(f.read()) - wave_file = open(record_name, mode="rb") - record_name_out = ( - record_name.split(os.sep)[-1].replace("-", "_").replace(".wav", "") - ) + wave_file = _open_input_file(record_name) + file_size = wave_file.seek(0, os.SEEK_END) + wave_file.seek(0) + record_name_out = _split_path(record_name)[1].replace("-", "_").replace(".wav", "") chunk_ID = "".join([s.decode() for s in struct.unpack(">4s", wave_file.read(4))]) if chunk_ID != "RIFF": raise Exception(f"{record_name} is not a .wav-format file") - correct_chunk_size = os.path.getsize(record_name) - 8 + correct_chunk_size = file_size - 8 chunk_size = struct.unpack(" Date: Mon, 23 Nov 2026 19:57:14 -0500 Subject: [PATCH 2/2] Read URIs as needed rather than in full first _open_input_file read the whole file at a URI into memory before read_edf could look at the header, so read_edf(uri, header_only=True) fetched the whole file. Return the open fsspec file instead, which reads as needed (with range requests for physionet://) and can be sought and sized without fetching the file. Close the file when read_edf returns only the header, which it did not do for local files either. --- src/wfdb/io/_coreio.py | 10 +++---- src/wfdb/io/convert/edf.py | 4 ++- tests/test_physionet_uri.py | 56 +++++++++++++++++++++++++++++++++++++ 3 files changed, 64 insertions(+), 6 deletions(-) diff --git a/src/wfdb/io/_coreio.py b/src/wfdb/io/_coreio.py index 70483691..e99aca23 100644 --- a/src/wfdb/io/_coreio.py +++ b/src/wfdb/io/_coreio.py @@ -1,4 +1,3 @@ -import io import os import posixpath @@ -67,8 +66,10 @@ def _split_path(record_name): def _open_input_file(path): """Open a local file, or a file at a cloud URI, to read in binary mode. - A file at a cloud URI, such as a `physionet://` URI, is read into memory, - so that it can be read, sought and sized like a local file. + A file at a cloud URI, such as a `physionet://` URI, is read as it is + needed (for `physionet://`, with HTTP range requests), so that reading + only the start of a file does not fetch the rest. It can be sought and + sized like a local file. Parameters ---------- @@ -83,8 +84,7 @@ def _open_input_file(path): """ path = os.fspath(path) if any(path.startswith(proto) for proto in CLOUD_PROTOCOLS): - with _fsspec_open(path, "rb") as f: - return io.BytesIO(f.read()) + return _fsspec_open(path, "rb").open() return open(path, "rb") diff --git a/src/wfdb/io/convert/edf.py b/src/wfdb/io/convert/edf.py index fe3c8725..a6c6458d 100644 --- a/src/wfdb/io/convert/edf.py +++ b/src/wfdb/io/convert/edf.py @@ -47,7 +47,8 @@ def read_edf( The path of the input EDF file to be read, including its extension. This can also be a cloud URI, such as 'physionet://chbmit/1.0.0/chb01/chb01_01.edf' or 's3://...', which - is read without saving a copy of the file. + is read without saving a copy of the file. With `header_only`, + only the header is read. pn_dir : str, optional Option used to stream data from Physionet. The Physionet database directory from which to find the required record files. @@ -376,6 +377,7 @@ def read_edf( ) if header_only: + edf_file.close() return { "fs": fs, "sig_len": sig_len, diff --git a/tests/test_physionet_uri.py b/tests/test_physionet_uri.py index 99cc30dc..4072b336 100644 --- a/tests/test_physionet_uri.py +++ b/tests/test_physionet_uri.py @@ -580,3 +580,59 @@ def test_record_converters_read_physionet_uris( assert sorted(p.name for p in workdir.iterdir()) == ["100m.hea", "100m.mat"] expected = sigavg(str(local), "atr", stop_range=1, return_df=True) assert averaged.equals(expected) + + +class CountingFile: + """A file that counts the bytes read from it.""" + + def __init__(self, f, counts): + self._f = f + self._counts = counts + + def read(self, *args): + data = self._f.read(*args) + self._counts.append(len(data)) + return data + + def __getattr__(self, name): + return getattr(self._f, name) + + def __enter__(self): + return self + + def __exit__(self, *exc): + self._f.close() + + +@pytest.mark.parametrize("protocol", ["physionet", "memory"]) +def test_read_edf_header_only_reads_only_the_header( + physionet_cache, offline, monkeypatch, protocol +): + """A URI is read as needed, so header_only does not fetch the signals.""" + from wfdb.io.convert.edf import read_edf + + if protocol == "physionet": + cache_sample_files(physionet_cache, "demo", ["n16.edf"]) + uri = "physionet://demo/1.0/n16.edf" + else: + fsspec.filesystem("memory").pipe( + "/header-only/n16.edf", (SAMPLE_DATA / "n16.edf").read_bytes() + ) + uri = "memory://header-only/n16.edf" + filesystem = type(fsspec.filesystem(protocol)) + real_open = filesystem._open + counts = [] + monkeypatch.setattr( + filesystem, + "_open", + lambda self, *args, **kwargs: CountingFile( + real_open(self, *args, **kwargs), counts + ), + ) + + header = read_edf(uri, header_only=True) + + assert sum(counts) == 256 * (header["n_sig"] + 1) + assert sum(counts) < (SAMPLE_DATA / "n16.edf").stat().st_size + if protocol == "memory": + fsspec.filesystem("memory").rm("/header-only", recursive=True)