diff --git a/changelog.d/cloud-writing.rst b/changelog.d/cloud-writing.rst new file mode 100644 index 00000000..77065db6 --- /dev/null +++ b/changelog.d/cloud-writing.rst @@ -0,0 +1,3 @@ +**Write WFDB records and annotations to cloud storage** + ``wrsamp`` and ``wrann`` now accept cloud URIs in ``write_dir``, including + S3, Google Cloud Storage, Azure Blob Storage, and in-memory filesystems. diff --git a/docs/io.rst b/docs/io.rst index a0def6bc..fafa95a4 100644 --- a/docs/io.rst +++ b/docs/io.rst @@ -88,12 +88,13 @@ yet. Cloud Storage Access -------------------- -WFDB-Python supports reading records and annotations directly from cloud -storage via the ``fsspec`` library. Pass a cloud URI as the -``record_name`` argument instead of a local path. +WFDB-Python supports reading and writing records and annotations in cloud +storage via the ``fsspec`` library. Pass a cloud URI as ``record_name`` when +reading, or as ``write_dir`` when writing. **Supported protocols:** ``s3://`` (Amazon S3), ``gs://`` (Google Cloud -Storage), ``az://`` (Azure Blob Storage), and ``azureml://`` (Azure ML). +Storage), ``az://`` (Azure Blob Storage), ``azureml://`` (Azure ML), and +``memory://`` (in-memory filesystems, useful for testing). **Prerequisites:** Install the ``fsspec`` backend for your cloud provider: @@ -120,6 +121,10 @@ Storage), ``az://`` (Azure Blob Storage), and ``azureml://`` (Azure ML). # Read annotations from S3 ann = wfdb.rdann("s3://my-bucket/wfdb-data/100", "atr") + # Write a record and its annotations to S3 + record.wrsamp(write_dir="s3://my-bucket/wfdb-data") + ann.wrann(write_dir="s3://my-bucket/wfdb-data") + # For PhysioNet databases, use pn_dir with the database name: record = wfdb.rdrecord("100", pn_dir="mitdb") ann = wfdb.rdann("100", "atr", pn_dir="mitdb") @@ -129,9 +134,17 @@ provider-specific mechanism (e.g., ``~/.aws/credentials`` for S3, ``GOOGLE_APPLICATION_CREDENTIALS`` for GCS). The ``fsspec`` library handles credential discovery automatically. +Cloud writing also works with ``wfdb.wrsamp``, ``MultiRecord.wrsamp``, and +``wfdb.wrann``. WFDB-Python first writes the files to a temporary local +directory, then uploads them. A write needs enough local space for the +complete record. The main header is uploaded last, but replacing a record +with multiple files is not atomic: readers may see a mix of old and new +files while an upload is in progress. ``physionet://`` destinations and +``.wfdb`` archives in cloud storage are not supported. + .. note:: - Cloud URIs must be passed as ``record_name``, not ``pn_dir``. + When reading, pass cloud URIs as ``record_name``, not ``pn_dir``. The ``pn_dir`` parameter is reserved for PhysioNet database names (e.g., ``"mitdb"`` or ``"mimic4wdb/0.1.0"``), which are resolved against the configured PhysioNet index URL. diff --git a/src/wfdb/io/_cloud.py b/src/wfdb/io/_cloud.py new file mode 100644 index 00000000..43604c46 --- /dev/null +++ b/src/wfdb/io/_cloud.py @@ -0,0 +1,60 @@ +"""Write WFDB files to cloud filesystems through fsspec.""" + +import os +import shutil +import tempfile +from contextlib import contextmanager + +from wfdb.io._coreio import CLOUD_PROTOCOLS, _fsspec_open, _join_path +from wfdb.io.archive import WFDBArchive + + +def is_cloud_path(path): + """Return whether a path uses one of the supported cloud protocols.""" + return os.fspath(path).startswith(tuple(CLOUD_PROTOCOLS)) + + +def check_cloud_write(write_dir, wfdb_archive=None): + """Reject unsupported cloud destinations before any remote lookup.""" + if os.fspath(write_dir).startswith("physionet://"): + raise ValueError("Writing to physionet:// is not supported") + if isinstance(wfdb_archive, (str, os.PathLike)) and is_cloud_path(wfdb_archive): + raise ValueError("Writing .wfdb archives to cloud storage is unsupported") + if is_cloud_path(write_dir) and wfdb_archive is not None: + if isinstance(wfdb_archive, WFDBArchive): + raise ValueError("A cloud write_dir is unused with an open WFDBArchive") + raise ValueError("Writing .wfdb archives to cloud storage is unsupported") + + +@contextmanager +def staged_cloud_write(write_dir, header_name=None): + """Stage files locally and upload them to a cloud directory on success. + + Signal and annotation files are uploaded before headers. The main record + header, if supplied, is uploaded last so readers do not discover an + incomplete new record while its files are still being uploaded. + + """ + with tempfile.TemporaryDirectory(prefix="wfdb-cloud-") as staging: + yield staging + paths = [] + for root, _, names in os.walk(staging): + for name in names: + local_path = os.path.join(root, name) + relative_path = os.path.relpath(local_path, staging).replace( + os.sep, "/" + ) + paths.append((relative_path, local_path)) + + paths.sort( + key=lambda item: ( + item[0] == header_name, + item[0].endswith(".hea"), + item[0], + ) + ) + for relative_path, local_path in paths: + remote_path = _join_path(os.fspath(write_dir), relative_path) + with open(local_path, "rb") as source: + with _fsspec_open(remote_path, "wb") as destination: + shutil.copyfileobj(source, destination) diff --git a/src/wfdb/io/annotation.py b/src/wfdb/io/annotation.py index 4044de34..2a5e96f5 100644 --- a/src/wfdb/io/annotation.py +++ b/src/wfdb/io/annotation.py @@ -7,6 +7,7 @@ import pandas as pd from wfdb.io import _header, download, record, util +from wfdb.io._cloud import check_cloud_write, is_cloud_path, staged_cloud_write from wfdb.io._coreio import _fsspec_open from wfdb.io.archive import WFDBArchive, is_archive_path @@ -290,13 +291,19 @@ def wrann(self, write_fs=False, write_dir=""): write_fs : bool, optional Whether to write the `fs` attribute to the file. write_dir : str, optional - The output directory in which the header is written. + The local directory or cloud URI in which to write the file. Returns ------- N/A """ + if is_cloud_path(write_dir): + check_cloud_write(write_dir) + with staged_cloud_write(write_dir) as staging: + self.wrann(write_fs=write_fs, write_dir=staging) + return + for field in ["record_name", "extension"]: if getattr(self, field) is None: raise Exception( @@ -1837,7 +1844,7 @@ def wrann( `custom_labels` is defined, `custom_labels` must contain `label_store` in its mapping. ie. it must come in format 1 or 3 above. write_dir : str, optional - The directory in which to write the annotation file + The local directory or cloud URI in which to write the annotation file. Returns ------- diff --git a/src/wfdb/io/record.py b/src/wfdb/io/record.py index 6eda917e..f2ed5a72 100644 --- a/src/wfdb/io/record.py +++ b/src/wfdb/io/record.py @@ -12,6 +12,7 @@ import pandas as pd from wfdb.io import _header, _signal, _url, download, header, util +from wfdb.io._cloud import check_cloud_write, is_cloud_path, staged_cloud_write from wfdb.io._coreio import CLOUD_PROTOCOLS, _fsspec_open, _join_path, _split_path from wfdb.io.archive import WFDBArchive, archive_for_writing, is_archive_path @@ -914,7 +915,7 @@ def wrsamp(self, expanded=False, write_dir="", wfdb_archive=None): Whether to write the expanded signal (e_d_signal) instead of the uniform signal (d_signal). write_dir : str, optional - The directory in which to write the files. + The local directory or cloud URI in which to write the files. wfdb_archive : str, os.PathLike or WFDBArchive, optional Write the record into a .wfdb archive instead of writing separate files to `write_dir`. A path creates a new archive, replacing any @@ -938,6 +939,14 @@ def wrsamp(self, expanded=False, write_dir="", wfdb_archive=None): >>> record.wrsamp() """ + check_cloud_write(write_dir, wfdb_archive) + if is_cloud_path(write_dir): + if self.n_sig and self.file_name: + self._warn_about_replacing_other_files(write_dir) + with staged_cloud_write(write_dir, self.record_name + ".hea") as staging: + self.wrsamp(expanded=expanded, write_dir=staging) + return + converted = None if not expanded and self.d_signal is None and self.p_signal is not None: self.d_signal = self.adc() @@ -1023,17 +1032,23 @@ def _warn_about_replacing_other_files(self, write_dir): """ record_name = self.record_name or "" + + def file_exists(file_name): + path = _join_path(os.fspath(write_dir), file_name) + if is_cloud_path(write_dir): + opened = _fsspec_open(path) + return opened.fs.exists(opened.path) + return os.path.exists(path) + existing = [ file_name for file_name in dict.fromkeys(self.file_name) - if file_name - and file_name != "~" - and os.path.exists(os.path.join(write_dir, file_name)) + if file_name and file_name != "~" and file_exists(file_name) ] if not existing: return try: - header = rdheader(os.path.join(write_dir, record_name)) + header = rdheader(_join_path(os.fspath(write_dir), record_name)) own = set(getattr(header, "file_name", None) or []) except Exception: # No readable header of this record, so no file is its own yet @@ -1323,7 +1338,7 @@ def wrsamp(self, expanded=False, write_dir="", wfdb_archive=None): instead of the uniform signal (`d_signal`). This flag is passed through to each segment's `Record.wrsamp()` call. write_dir : str, optional - The directory in which to write the files. + The local directory or cloud URI in which to write the files. wfdb_archive : str, os.PathLike or WFDBArchive, optional Write the record, including all its segments, into a .wfdb archive instead of writing separate files to `write_dir`. A @@ -1336,6 +1351,12 @@ def wrsamp(self, expanded=False, write_dir="", wfdb_archive=None): N/A """ + check_cloud_write(write_dir, wfdb_archive) + if is_cloud_path(write_dir): + with staged_cloud_write(write_dir, self.record_name + ".hea") as staging: + self.wrsamp(expanded=expanded, write_dir=staging) + return + # Validate the segments before writing anything. self._check_segment_cohesion() self._check_segment_signals(expanded) @@ -3388,7 +3409,7 @@ def wrsamp( The date and time at the beginning of the record, equivalent to setting both `base_date` and `base_time`. write_dir : str, optional - The directory in which to write the files. + The local directory or cloud URI in which to write the files. wfdb_archive : str, os.PathLike or WFDBArchive, optional Write the record into a .wfdb archive instead of writing separate files to `write_dir`. A path creates a new archive, replacing any diff --git a/tests/test_memory.py b/tests/test_memory.py index 68890bc4..9f0de9aa 100644 --- a/tests/test_memory.py +++ b/tests/test_memory.py @@ -5,6 +5,8 @@ import pytest import wfdb +from wfdb.io import _cloud +from wfdb.io.archive import WFDBArchive SAMPLE_DATA = Path("sample-data") @@ -99,3 +101,138 @@ def test_missing_file(memory_fs): with pytest.raises(FileNotFoundError): wfdb.rdrecord("memory://wfdb-test/nonexistent") + + +def test_wrsamp_to_cloud(memory_fs): + signal = np.array([[0], [1], [-1], [2]], dtype=np.int16) + wfdb.wrsamp( + "cloud_record", + fs=100, + units=["mV"], + sig_name=["ECG"], + d_signal=signal, + fmt=["16"], + adc_gain=[200], + baseline=[0], + write_dir="memory://wfdb-test/subdir", + ) + + assert memory_fs.exists("/wfdb-test/subdir/cloud_record.hea") + assert memory_fs.exists("/wfdb-test/subdir/cloud_record.dat") + result = wfdb.rdrecord("memory://wfdb-test/subdir/cloud_record", physical=False) + np.testing.assert_array_equal(result.d_signal, signal) + + +def test_record_wrsamp_to_cloud(memory_fs): + record = wfdb.rdrecord("sample-data/100", sampto=100, physical=False) + record.record_name = "cloud_copy" + record.file_name = ["cloud_copy.dat"] * record.n_sig + record.wrsamp(write_dir="memory://wfdb-test") + + result = wfdb.rdrecord("memory://wfdb-test/cloud_copy", physical=False) + np.testing.assert_array_equal(result.d_signal, record.d_signal) + + +def test_multi_record_wrsamp_to_cloud(memory_fs, monkeypatch): + source = "sample-data/multi-segment/fixed1/v102s" + record = wfdb.rdrecord(source, sampto=1000, m2s=False, physical=False) + uploaded = [] + open_file = _cloud._fsspec_open + + def record_upload(path, mode="rb", **kwargs): + if mode == "wb": + uploaded.append(path) + return open_file(path, mode, **kwargs) + + monkeypatch.setattr(_cloud, "_fsspec_open", record_upload) + record.wrsamp(write_dir="memory://wfdb-test/multi") + + assert set(uploaded) == { + "memory://wfdb-test/multi/v102s.dat", + "memory://wfdb-test/multi/v102s_1.hea", + "memory://wfdb-test/multi/v102s.hea", + } + assert uploaded[-1] == "memory://wfdb-test/multi/v102s.hea" + assert memory_fs.exists("/wfdb-test/multi/v102s.hea") + assert memory_fs.exists("/wfdb-test/multi/v102s_1.hea") + result = wfdb.rdrecord("memory://wfdb-test/multi/v102s", physical=False) + expected = wfdb.rdrecord(source, sampto=1000, physical=False) + np.testing.assert_array_equal(result.d_signal, expected.d_signal) + + +def test_wrann_to_cloud(memory_fs): + annotation = wfdb.rdann("sample-data/100", "atr") + annotation.record_name = "cloud_annotation" + annotation.wrann(write_fs=True, write_dir="memory://wfdb-test/annotations") + + result = wfdb.rdann("memory://wfdb-test/annotations/cloud_annotation", "atr") + np.testing.assert_array_equal(result.sample, annotation.sample) + assert result.symbol == annotation.symbol + assert result.fs == annotation.fs + + +def test_wrann_gateway_to_cloud(memory_fs): + wfdb.wrann( + "gateway", + "atr", + np.array([10, 20]), + symbol=["N", "V"], + write_dir="memory://wfdb-test", + ) + + result = wfdb.rdann("memory://wfdb-test/gateway", "atr") + assert result.sample.tolist() == [10, 20] + assert result.symbol == ["N", "V"] + + +def test_cloud_write_validation_does_not_publish(memory_fs): + record = wfdb.rdrecord("sample-data/100", sampto=10, physical=False) + record.record_name = "invalid" + record.fmt = ["invalid"] * record.n_sig + + with pytest.raises((ValueError, TypeError)): + record.wrsamp(write_dir="memory://wfdb-test") + + assert not memory_fs.exists("/wfdb-test/invalid.hea") + + +def test_cloud_write_warns_when_replacing_another_records_signal(memory_fs): + record = wfdb.rdrecord("sample-data/100", sampto=10, physical=False) + record.record_name = "copy" + memory_fs.pipe("/wfdb-test/100.dat", b"original") + + with pytest.warns(UserWarning, match="replaces existing signal files"): + record.wrsamp(write_dir="memory://wfdb-test") + + +def test_physionet_write_is_rejected(monkeypatch): + with pytest.raises(ValueError, match="physionet://"): + wfdb.wrann( + "test", + "atr", + np.array([1]), + symbol=["N"], + write_dir="physionet://mitdb", + ) + + record = wfdb.rdrecord("sample-data/100", sampto=10, physical=False) + + def unexpected_lookup(write_dir): + pytest.fail("PhysioNet was queried before the write was rejected") + + monkeypatch.setattr(record, "_warn_about_replacing_other_files", unexpected_lookup) + with pytest.raises(ValueError, match="physionet://"): + record.wrsamp(write_dir="physionet://mitdb") + + +def test_cloud_archive_write_is_rejected(memory_fs): + record = wfdb.rdrecord("sample-data/100", sampto=10, physical=False) + with pytest.raises(ValueError, match="archives to cloud storage"): + record.wrsamp(wfdb_archive="memory://wfdb-test/100.wfdb") + + +def test_cloud_write_dir_with_open_archive_is_rejected(tmp_path): + record = wfdb.rdrecord("sample-data/100", sampto=10, physical=False) + with pytest.raises(ValueError, match="cloud write_dir is unused"): + with WFDBArchive(tmp_path / "100.wfdb", mode="w") as archive: + record.wrsamp(write_dir="memory://wfdb-test", wfdb_archive=archive)