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..e99aca23 100644 --- a/src/wfdb/io/_coreio.py +++ b/src/wfdb/io/_coreio.py @@ -63,6 +63,31 @@ 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 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 + ---------- + 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): + return _fsspec_open(path, "rb").open() + 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..a6c6458d 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,11 @@ 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. 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. @@ -142,7 +147,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 +328,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] @@ -374,6 +377,7 @@ def read_edf( ) if header_only: + edf_file.close() return { "fs": fs, "sig_len": sig_len, @@ -386,7 +390,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 +584,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 +1006,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 +1161,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("