diff --git a/changelog.d/dl-physionet.rst b/changelog.d/dl-physionet.rst new file mode 100644 index 00000000..0c758fa3 --- /dev/null +++ b/changelog.d/dl-physionet.rst @@ -0,0 +1,2 @@ +**Download databases with the physionet package** + ``dl_database`` and ``dl_files`` now download files with the ``physionet`` package (0.7.1 or later). Each file is checked against the database's checksum list, a file that is already saved with the right content is skipped, a partly downloaded one is completed, ``overwrite=True`` replaces each saved file only once its new copy is complete and checked, and restricted databases can be downloaded after ``physionet login``. ``dl_database`` finds which annotation files there are from the checksum list instead of requesting each one, which makes downloading three MIT-BIH records with their annotations take 20 requests instead of 38. ``dl_files`` reports a file that the database does not have before downloading anything. With a database index URL set by ``set_db_index_url``, files are downloaded from that server as before. diff --git a/pyproject.toml b/pyproject.toml index e2c55df7..e4e4b202 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -20,7 +20,7 @@ dependencies = [ "requests >= 2.31.0", "fsspec >= 2025.7.0", "aiohttp >= 3.10.11", - "physionet >= 0.6.0", + "physionet >= 0.7.1", ] [project.urls] diff --git a/src/wfdb/io/download.py b/src/wfdb/io/download.py index 324b6431..1d64473b 100644 --- a/src/wfdb/io/download.py +++ b/src/wfdb/io/download.py @@ -340,18 +340,16 @@ def get_record_list(db_dir, records="all"): >>> wfdb.get_record_list('mitdb') """ - # Full url PhysioNet database if "/" not in db_dir: - db_url = posixpath.join(config.db_index_url, db_dir, get_version(db_dir)) - else: - db_url = posixpath.join(config.db_index_url, db_dir) + db_dir = posixpath.join(db_dir, get_version(db_dir)) # Check for a RECORDS file if records == "all": try: - with _url.openurl(posixpath.join(db_url, "RECORDS"), "rb") as f: + with _open_pn_file(db_dir, "RECORDS") as f: content = f.read() except FileNotFoundError: + db_url = posixpath.join(config.db_index_url, db_dir) raise ValueError("The database %s has no WFDB files to download" % db_url) # Get each line as a string @@ -391,7 +389,7 @@ def get_annotators(db_dir, annotators): if annotators is not None: # Check for an ANNOTATORS file try: - with _url.openurl(posixpath.join(db_url, "ANNOTATORS"), "rb") as f: + with _open_pn_file(db_dir, "ANNOTATORS") as f: content = f.read() except FileNotFoundError: if annotators == "all": @@ -423,6 +421,82 @@ def get_annotators(db_dir, annotators): return annotators +def _project_files(db_dir): + """List the files in a PhysioNet database directory, from its checksum list. + + Parameters + ---------- + db_dir : str + The PhysioNet database directory, including its version, such as + 'mitdb/1.0.0'. + + Returns + ------- + set of str or None + The paths of the files, relative to `db_dir`, or None if the database + index URL has been set to a server other than PhysioNet. + + """ + if _physionet_uri(db_dir, "") is None: + return None + fs = fsspec.filesystem("physionet", **PHYSIONET_OPEN_OPTIONS) + prefix = db_dir.rstrip("/") + "/" + return {path[len(prefix) :] for path in fs.find(db_dir) if path.startswith(prefix)} + + +def _download_files(db_dir, dl_dir, files, keep_subdirs, overwrite): + """Download files from a PhysioNet database with the physionet package. + + Each file is checked against the database's checksum list. A file that is + already saved with the right content is skipped, and one that was partly + downloaded is completed. + + Parameters + ---------- + db_dir : str + The PhysioNet database directory, including its version, such as + 'mitdb/1.0.0' or 'mimic3wdb/1.0/30'. + dl_dir : str + The local directory to save the files in. + files : list of str + The paths of the files to download, relative to `db_dir`. + keep_subdirs : bool + Whether to save the files in the same subdirectories as on PhysioNet + (True), or all in `dl_dir` (False). + overwrite : bool + Whether to download files again even if they are already saved. + + Returns + ------- + N/A + + """ + import physionet + + slug, version, *subdirs = db_dir.strip("/").split("/") + saved_as = {} + for file in files: + path = posixpath.join(*subdirs, file) + saved_as[path] = file if keep_subdirs else posixpath.basename(file) + + if not os.path.isdir(dl_dir): + os.makedirs(dl_dir) + print("Created local base download directory: %s" % dl_dir) + # Two files at a time, as before, to avoid overloading the server. With + # overwrite, physionet replaces each saved file only after checking every + # requested file and destination, and once the new copy is complete. + physionet.download( + slug, + version, + output_dir=dl_dir, + files=saved_as, + verbose=False, + show_progress=False, + jobs=2, + overwrite=overwrite, + ) + + def make_local_dirs(dl_dir, dl_inputs, keep_subdirs): """Make any required local directories to prepare for downloading. @@ -561,18 +635,27 @@ def dl_files(db, dl_dir, files, keep_subdirs=True, overwrite=False): are organized in PhysioNet (True), or to download all files into the same base directory (False). overwrite : bool, optional - If True, all files will be redownloaded regardless. If False, existing - files with the same name and relative subdirectory will be checked. - If the local file is the same size as the online file, the download is - skipped. If the local file is larger, it will be deleted and the file - will be redownloaded. If the local file is smaller, the file will be - assumed to be partially downloaded and the remaining bytes will be - downloaded and appended. + If True, all files are downloaded again, and each saved file is only + replaced once its new copy is complete and checked. If False, a file + that is already saved with the right content (checked against the + database's checksum list) is skipped, a partly downloaded file is + completed, and any other saved file is downloaded again in its place, + which removes the saved file if the new download fails its checksum. Returns ------- N/A + Notes + ----- + Files are downloaded with the `physionet` package, two at a time, from the + AWS open data mirror for open databases, and from PhysioNet for restricted + ones, which can be downloaded after signing in with `physionet login`. + Each file is checked against the database's checksum list. If the database + index URL has been set to another server with `set_db_index_url`, files are + downloaded from that server instead, comparing only their sizes when they + are already saved. + Examples -------- >>> wfdb.dl_files('ahadb', os.getcwd(), @@ -582,9 +665,17 @@ def dl_files(db, dl_dir, files, keep_subdirs=True, overwrite=False): """ # Full url PhysioNet database db_dir = posixpath.join(db, get_version(db)) - db_url = posixpath.join(PN_CONTENT_URL, db_dir) + "/" + + # The physionet package reports a missing database, version or file + # before downloading anything + if _physionet_uri(db_dir, "") is not None: + print("Downloading files...") + _download_files(db_dir, dl_dir, files, keep_subdirs, overwrite) + print("Finished downloading files") + return # Check if the database is valid + db_url = posixpath.join(PN_CONTENT_URL, db_dir) + "/" _url.openurl(db_url, check_access=True) # Construct the urls to download diff --git a/src/wfdb/io/record.py b/src/wfdb/io/record.py index 9d0768ca..ff80b4ec 100644 --- a/src/wfdb/io/record.py +++ b/src/wfdb/io/record.py @@ -3326,19 +3326,28 @@ def dl_database( as they are organized in PhysioNet (True), or to download all files into the same base directory (False). overwrite : bool, optional - If True, all files will be redownloaded regardless. If False, - existing files with the same name and relative subdirectory will - be checked. If the local file is the same size as the online - file, the download is skipped. If the local file is larger, it - will be deleted and the file will be redownloaded. If the local - file is smaller, the file will be assumed to be partially - downloaded and the remaining bytes will be downloaded and - appended. + If True, all files are downloaded again, and each saved file is only + replaced once its new copy is complete and checked. If False, a file + that is already saved with the right content (checked against the + database's checksum list) is skipped, a partly downloaded file is + completed, and any other saved file is downloaded again in its place, + which removes the saved file if the new download fails its checksum. Returns ------- N/A + Notes + ----- + Files are downloaded with the `physionet` package, two at a time, from the + AWS open data mirror for open databases, and from PhysioNet for restricted + ones, which can be downloaded after signing in with `physionet login`. + Each file is checked against the database's checksum list, and which + annotation files there are is found from that list. If the database index + URL has been set to another server with `set_db_index_url`, files are + downloaded from that server instead, comparing only their sizes when they + are already saved. + Examples -------- >>> wfdb.dl_database('ahadb', os.getcwd()) @@ -3360,6 +3369,9 @@ def dl_database( record_list = download.get_record_list(db_dir, records) # Get the annotator extensions annotators = download.get_annotators(db_dir, annotators) + # The files in the database, to check which annotation files there are + # (None if the database index URL is not PhysioNet's) + project_files = download._project_files(db_dir) if annotators else None # All files to download (relative to the database's home directory) all_files = [] @@ -3409,6 +3421,10 @@ def dl_database( if annotators is not None: for a in annotators: ann_file = rec + "." + a + if project_files is not None: + if ann_file in project_files: + all_files.append(ann_file) + continue url = posixpath.join(download.config.db_index_url, db_dir, ann_file) try: _url.openurl(url, check_access=True) @@ -3416,6 +3432,12 @@ def dl_database( except FileNotFoundError: pass + if download._physionet_uri(db_dir, "") is not None: + print("Downloading files...") + download._download_files(db_dir, dl_dir, all_files, keep_subdirs, overwrite) + print("Finished downloading files") + return + dl_inputs = [ ( os.path.split(file)[1], diff --git a/tests/test_physionet_uri.py b/tests/test_physionet_uri.py index 24a6f91f..6c7ea850 100644 --- a/tests/test_physionet_uri.py +++ b/tests/test_physionet_uri.py @@ -1,5 +1,6 @@ """Tests for reading records and annotations with physionet:// URIs.""" +import importlib import io import shutil from pathlib import Path @@ -250,3 +251,168 @@ def openurl(url, mode="r", **kwargs): wfdb.io.download._physionet_uri("mitdb/1.0.0", "100.hea") == "physionet://mitdb/1.0.0/100.hea" ) + + +@pytest.fixture +def demo_database(physionet_cache, offline, versions, monkeypatch): + """A database 'demo', version 1.0, in the physionet cache, with downloads recorded. + + Returns the list of keyword arguments that physionet.download was called with. + """ + import physionet + + _, results = versions + results["demo"] = "1.0" + project = physionet_cache / "physionet.org" / "demo" / "1.0" + (project / "sub").mkdir(parents=True) + (project / "RECORDS").write_text("100\n041s\n") + (project / "ANNOTATORS").write_text("atr\tReference beat annotations\n") + (project / "sub" / "RECORDS").write_text("200\n") + (project / "sub" / "200.hea").write_text( + "200 1 360 10\n200.dat 16 200 16 0 0 0 0 ECG\n" + ) + shutil.copy(SAMPLE_DATA / "100.hea", project) + for path in (SAMPLE_DATA / "multi-segment" / "041s").glob("*.hea"): + shutil.copy(path, project) + + # The checksum list: 100 has annotations, 041s does not + manifest = physionet_cache / "physionet.org" / ".manifests" / "demo" / "1.0" + manifest.mkdir(parents=True) + names = ["RECORDS", "ANNOTATORS", "100.hea", "100.dat", "100.atr", "041s.hea"] + names += ["041s01.hea", "041s01.dat", "041s02.hea", "041s02.dat"] + names += ["sub/RECORDS", "sub/200.hea", "sub/200.dat", "sub/200.atr"] + (manifest / "SHA256SUMS.txt").write_text( + "".join(f"{'0' * 64} {n}\n" for n in names) + ) + (manifest / "ACCESS").write_text("open\n") + + calls = [] + monkeypatch.setattr(physionet, "download", lambda *a, **kw: calls.append((a, kw))) + # dl_database checks that the database's web page exists + monkeypatch.setattr(wfdb.io._url, "openurl", lambda url, *a, **kw: io.BytesIO()) + return calls + + +def test_dl_database_downloads_with_physionet(demo_database, tmp_path): + wfdb.dl_database("demo", str(tmp_path / "out"), annotators=["atr"]) + + [(args, kwargs)] = demo_database + assert args == ("demo", "1.0") + files = kwargs.pop("files") + assert kwargs == { + "output_dir": str(tmp_path / "out"), + "verbose": False, + "show_progress": False, + "jobs": 2, + "overwrite": False, + } + # Each record's header and signal files, and the annotation files there are + expected = ["100.hea", "100.dat", "100.atr", "041s.hea", "041s01.hea"] + expected += ["041s01.dat", "041s02.hea", "041s02.dat"] + assert files == {name: name for name in expected} + + +def test_dl_database_subdirectory_and_flat_layout(demo_database, tmp_path): + out = tmp_path / "out" + wfdb.dl_database("demo/sub", str(out), annotators=None) + wfdb.dl_database( + "demo", str(out), records=["100"], annotators=None, keep_subdirs=False + ) + + # Files are saved relative to the subdirectory, as before + assert demo_database[0][1]["files"] == { + "sub/200.hea": "200.hea", + "sub/200.dat": "200.dat", + } + assert demo_database[1][1]["files"] == {"100.hea": "100.hea", "100.dat": "100.dat"} + + +@pytest.mark.parametrize("overwrite", [False, True]) +def test_dl_database_overwrite(demo_database, tmp_path, overwrite): + out = tmp_path / "out" + out.mkdir() + (out / "100.dat").write_bytes(b"saved before") + wfdb.dl_database( + "demo", str(out), records=["100"], annotators=None, overwrite=overwrite + ) + + # physionet replaces saved files itself, after checking every file and + # destination, so wfdb removes nothing + assert demo_database[0][1]["overwrite"] is overwrite + assert (out / "100.dat").read_bytes() == b"saved before" + + +@pytest.mark.parametrize("keep_subdirs", [True, False]) +def test_dl_files_downloads_with_physionet(demo_database, tmp_path, keep_subdirs): + out = tmp_path / "out" + wfdb.dl_files( + "demo", str(out), ["100.hea", "sub/200.hea"], keep_subdirs=keep_subdirs + ) + + [(args, kwargs)] = demo_database + assert args == ("demo", "1.0") + expected = "sub/200.hea" if keep_subdirs else "200.hea" + assert kwargs["files"] == {"100.hea": "100.hea", "sub/200.hea": expected} + assert out.is_dir() + + +def test_dl_files_from_another_server(demo_database, monkeypatch, tmp_path): + """With set_db_index_url, files are downloaded from that server, as before.""" + downloaded = [] + monkeypatch.setattr(wfdb.io.download, "dl_pn_file", downloaded.append) + wfdb.io.download.set_db_index_url("https://mirror.example.org/files/") + try: + wfdb.dl_files("demo", str(tmp_path / "out"), ["100.hea"]) + finally: + wfdb.io.download.set_db_index_url() + assert demo_database == [] + assert [(name, subdir, db) for name, subdir, db, *_ in downloaded] == [ + ("100.hea", "", "demo/1.0") + ] + + +@pytest.mark.parametrize( + ("files", "keep_subdirs", "saved"), + [ + # A path outside dl_dir + (["../victim.dat"], True, "../victim.dat"), + # Two files with one name, without their subdirectories + (["RECORDS", "sub/RECORDS"], False, "RECORDS"), + # Names that differ only in case, which are one file on macOS and Windows + (["100.hea", "sub/100.HEA"], False, "100.hea"), + ], + ids=["outside", "same-name", "case"], +) +def test_dl_files_overwrite_replaces_nothing_for_an_unsafe_request( + demo_database, monkeypatch, tmp_path, files, keep_subdirs, saved +): + """physionet refuses these requests before replacing or downloading anything.""" + import physionet + + # The real physionet.download, which checks the request before any request + monkeypatch.setattr( + physionet, "download", importlib.import_module("physionet.download").download + ) + out = tmp_path / "out" + out.mkdir() + (out / saved).write_bytes(b"saved before") + + with pytest.raises(ValueError): + wfdb.dl_files( + "demo", str(out), files, keep_subdirs=keep_subdirs, overwrite=True + ) + assert (out / saved).read_bytes() == b"saved before" + + +def test_dl_files_overwrite_removes_nothing_itself(demo_database, tmp_path): + """wfdb leaves replacing saved files to physionet, which checks them first.""" + out = tmp_path / "out" + out.mkdir() + (out / "100.hea").write_bytes(b"saved before") + + wfdb.dl_files("demo", str(out), ["100.hea", "999.hea"], overwrite=True) + + assert (out / "100.hea").read_bytes() == b"saved before" + [(args, kwargs)] = demo_database + assert kwargs["overwrite"] is True + assert kwargs["files"] == {"100.hea": "100.hea", "999.hea": "999.hea"}