From f49bfeba32b4b3c978e552ff82bef80ed3e3adb2 Mon Sep 17 00:00:00 2001 From: Tom Pollard Date: Mon, 23 Nov 2026 09:47:29 -0500 Subject: [PATCH 1/5] Download databases with the physionet package dl_database and dl_files now download files with physionet.download(), from physionet 0.7.0, which takes the exact files to download and where to save each one (files=). wfdb still chooses the files, from RECORDS, ANNOTATORS and each record's header, and saves them in the same layout as before: relative to the database directory (or its subdirectory), or all in dl_dir with keep_subdirs=False. Downloads run two at a time, as before, without progress bars or messages from physionet. Each file is now 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, and any other saved file is downloaded again, instead of comparing only sizes. overwrite=True removes the saved files first. Restricted databases can be downloaded after `physionet login`, and the RECORDS and ANNOTATORS files are read through physionet:// too. dl_database finds which annotation files there are from the checksum list, instead of requesting each one: downloading three MIT-BIH records with their annotations takes 20 requests and 4.9 s instead of 38 requests and 11.2 s. dl_files no longer checks the database's web page first, since physionet reports a missing database, version or file before downloading anything. With a database index URL set by set_db_index_url, files are downloaded from that server as before. --- changelog.d/dl-physionet.rst | 2 + pyproject.toml | 2 +- src/wfdb/io/download.py | 120 +++++++++++++++++++++++++++++++---- src/wfdb/io/record.py | 36 ++++++++--- tests/test_physionet_uri.py | 116 +++++++++++++++++++++++++++++++++ 5 files changed, 253 insertions(+), 23 deletions(-) create mode 100644 changelog.d/dl-physionet.rst diff --git a/changelog.d/dl-physionet.rst b/changelog.d/dl-physionet.rst new file mode 100644 index 00000000..b3b46515 --- /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.0 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, 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..c2513738 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.0", ] [project.urls] diff --git a/src/wfdb/io/download.py b/src/wfdb/io/download.py index 324b6431..24de0824 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,85 @@ 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) + if overwrite: + for local in saved_as.values(): + local_file = os.path.join(dl_dir, *local.split("/")) + if os.path.isfile(local_file): + os.remove(local_file) + + # Two files at a time, as before, to avoid overloading the server + physionet.download( + slug, + version, + output_dir=dl_dir, + files=saved_as, + verbose=False, + show_progress=False, + jobs=2, + ) + + def make_local_dirs(dl_dir, dl_inputs, keep_subdirs): """Make any required local directories to prepare for downloading. @@ -561,18 +638,25 @@ 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. 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. 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 +666,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..65f3f10b 100644 --- a/src/wfdb/io/record.py +++ b/src/wfdb/io/record.py @@ -3326,19 +3326,26 @@ 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. 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. 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 +3367,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 +3419,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 +3430,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..f2e82a97 100644 --- a/tests/test_physionet_uri.py +++ b/tests/test_physionet_uri.py @@ -250,3 +250,119 @@ 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, + } + # 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 + ) + + # With overwrite, the saved file is removed, so that it is downloaded again. + # Otherwise physionet keeps it if its checksum matches, and replaces it if not. + assert (out / "100.dat").exists() == (not overwrite) + + +@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") + ] From 0af51fbd233a0956755e0a6df1782b7a658b518c Mon Sep 17 00:00:00 2001 From: Tom Pollard Date: Mon, 23 Nov 2026 11:38:26 -0500 Subject: [PATCH 2/5] Check files before removing them for overwrite=True With overwrite=True, _download_files removed the saved copies before physionet.download checked the requested paths, so a path such as "../victim.dat", or one through a symbolic link inside dl_dir, removed a file outside dl_dir, and then raised ValueError. Before removing anything, check that every file would be saved inside dl_dir, as a plain relative path and after following symbolic links, and that the database has every requested file. If not, raise ValueError or FileNotFoundError without removing any file. --- src/wfdb/io/download.py | 66 +++++++++++++++++++++++++++++++++++-- tests/test_physionet_uri.py | 40 ++++++++++++++++++++++ 2 files changed, 104 insertions(+), 2 deletions(-) diff --git a/src/wfdb/io/download.py b/src/wfdb/io/download.py index 24de0824..96ac6ca6 100644 --- a/src/wfdb/io/download.py +++ b/src/wfdb/io/download.py @@ -483,8 +483,10 @@ def _download_files(db_dir, dl_dir, files, keep_subdirs, overwrite): os.makedirs(dl_dir) print("Created local base download directory: %s" % dl_dir) if overwrite: - for local in saved_as.values(): - local_file = os.path.join(dl_dir, *local.split("/")) + # Remove the saved files, so that they are downloaded again, but only + # once every file is known to exist and to be saved inside dl_dir + local_files = _check_files_to_replace(db_dir, dl_dir, files, saved_as.values()) + for local_file in local_files: if os.path.isfile(local_file): os.remove(local_file) @@ -500,6 +502,66 @@ def _download_files(db_dir, dl_dir, files, keep_subdirs, overwrite): ) +def _check_files_to_replace(db_dir, dl_dir, files, saved_as): + """Check the files that _download_files would replace, before removing any. + + Parameters + ---------- + db_dir : str + The PhysioNet database directory, including its version. + dl_dir : str + The local directory that the files are saved in. + files : list of str + The paths of the files to download, relative to `db_dir`. + saved_as : iterable of str + The paths that the files are saved as, relative to `dl_dir`. + + Returns + ------- + list of str + The local path of each file. + + Raises + ------ + ValueError + If a file would be saved outside `dl_dir`, because its path is not a + plain relative path (for example "../a.dat"), or through a symbolic + link. + FileNotFoundError + If the database has no such file. + + """ + root = os.path.realpath(dl_dir) + local_files = [] + for local in saved_as: + parts = local.split("/") + if ( + "\\" in local + or local.startswith("/") + or any(part in ("", ".", "..") for part in parts) + ): + raise ValueError( + f"Files can only be saved inside dl_dir, as plain relative paths: " + f"{local!r}" + ) + local_file = os.path.join(dl_dir, *parts) + if os.path.commonpath([root, os.path.realpath(local_file)]) != root: + raise ValueError( + f"{local!r} would be saved outside dl_dir, through a symbolic link" + ) + local_files.append(local_file) + + available = _project_files(db_dir) + missing = [file for file in files if file not in available] + if missing: + raise FileNotFoundError( + f"{db_dir} has no file " + + ", ".join(repr(file) for file in missing[:5]) + + (f" and {len(missing) - 5} more" if len(missing) > 5 else "") + ) + return local_files + + def make_local_dirs(dl_dir, dl_inputs, keep_subdirs): """Make any required local directories to prepare for downloading. diff --git a/tests/test_physionet_uri.py b/tests/test_physionet_uri.py index f2e82a97..ea4434f1 100644 --- a/tests/test_physionet_uri.py +++ b/tests/test_physionet_uri.py @@ -366,3 +366,43 @@ def test_dl_files_from_another_server(demo_database, monkeypatch, tmp_path): assert [(name, subdir, db) for name, subdir, db, *_ in downloaded] == [ ("100.hea", "", "demo/1.0") ] + + +def test_dl_files_overwrite_never_removes_files_outside_dl_dir(demo_database, tmp_path): + out = tmp_path / "out" + out.mkdir() + victim = tmp_path / "victim.dat" + victim.write_bytes(b"keep me") + + with pytest.raises(ValueError, match="only be saved inside dl_dir"): + wfdb.dl_files("demo", str(out), ["../victim.dat"], overwrite=True) + assert victim.read_bytes() == b"keep me" + assert demo_database == [] + + +def test_dl_files_overwrite_through_a_symbolic_link(demo_database, tmp_path): + out = tmp_path / "out" + out.mkdir() + outside = tmp_path / "outside" + outside.mkdir() + (outside / "100.hea").write_bytes(b"keep me") + try: + (out / "link").symlink_to(outside, target_is_directory=True) + except (OSError, NotImplementedError): + pytest.skip("symbolic links are not available") + + with pytest.raises(ValueError, match="through a symbolic link"): + wfdb.dl_files("demo", str(out), ["link/100.hea"], overwrite=True) + assert (outside / "100.hea").read_bytes() == b"keep me" + assert demo_database == [] + + +def test_dl_files_overwrite_with_a_missing_file(demo_database, tmp_path): + out = tmp_path / "out" + out.mkdir() + (out / "100.hea").write_bytes(b"saved before") + + with pytest.raises(FileNotFoundError, match="no file '999.hea'"): + wfdb.dl_files("demo", str(out), ["100.hea", "999.hea"], overwrite=True) + assert (out / "100.hea").read_bytes() == b"saved before" + assert demo_database == [] From 8fcc6e4375fea36a54ce37d8d1fd40b2d3b41125 Mon Sep 17 00:00:00 2001 From: Tom Pollard Date: Mon, 23 Nov 2026 11:52:27 -0500 Subject: [PATCH 3/5] Refuse two files with one destination before removing any With keep_subdirs=False, two files in different subdirectories, such as sub1/100.hea and sub2/100.hea, are saved under one name. With overwrite=True, _download_files removed the saved file before physionet.download refused the clash. _check_files_to_replace now also checks that no two files would be saved as one before anything is removed: after following symbolic links, and ignoring case, since names that differ only in case are one file on macOS and Windows. --- src/wfdb/io/download.py | 26 ++++++++++++++++++++------ tests/test_physionet_uri.py | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 6 deletions(-) diff --git a/src/wfdb/io/download.py b/src/wfdb/io/download.py index 96ac6ca6..cc59457e 100644 --- a/src/wfdb/io/download.py +++ b/src/wfdb/io/download.py @@ -485,7 +485,7 @@ def _download_files(db_dir, dl_dir, files, keep_subdirs, overwrite): if overwrite: # Remove the saved files, so that they are downloaded again, but only # once every file is known to exist and to be saved inside dl_dir - local_files = _check_files_to_replace(db_dir, dl_dir, files, saved_as.values()) + local_files = _check_files_to_replace(db_dir, dl_dir, files, saved_as) for local_file in local_files: if os.path.isfile(local_file): os.remove(local_file) @@ -513,8 +513,9 @@ def _check_files_to_replace(db_dir, dl_dir, files, saved_as): The local directory that the files are saved in. files : list of str The paths of the files to download, relative to `db_dir`. - saved_as : iterable of str - The paths that the files are saved as, relative to `dl_dir`. + saved_as : dict + The path that each file is saved as, relative to `dl_dir`, by its path + within the database. Returns ------- @@ -526,14 +527,19 @@ def _check_files_to_replace(db_dir, dl_dir, files, saved_as): ValueError If a file would be saved outside `dl_dir`, because its path is not a plain relative path (for example "../a.dat"), or through a symbolic - link. + link, or if two files would be saved as one, including as names that + differ only in case (one file on macOS and Windows), or through a + symbolic link. FileNotFoundError If the database has no such file. """ root = os.path.realpath(dl_dir) local_files = [] - for local in saved_as: + # Each destination, after following symbolic links and ignoring case, and + # the file saved there + destinations = {} + for path, local in saved_as.items(): parts = local.split("/") if ( "\\" in local @@ -545,10 +551,18 @@ def _check_files_to_replace(db_dir, dl_dir, files, saved_as): f"{local!r}" ) local_file = os.path.join(dl_dir, *parts) - if os.path.commonpath([root, os.path.realpath(local_file)]) != root: + resolved = os.path.realpath(local_file) + if os.path.commonpath([root, resolved]) != root: raise ValueError( f"{local!r} would be saved outside dl_dir, through a symbolic link" ) + key = os.path.normcase(resolved).casefold() + if key in destinations: + raise ValueError( + f"{destinations[key]!r} and {path!r} would both be saved as " + f"{local!r} (or as the same file) in dl_dir" + ) + destinations[key] = path local_files.append(local_file) available = _project_files(db_dir) diff --git a/tests/test_physionet_uri.py b/tests/test_physionet_uri.py index ea4434f1..ed4f9262 100644 --- a/tests/test_physionet_uri.py +++ b/tests/test_physionet_uri.py @@ -406,3 +406,35 @@ def test_dl_files_overwrite_with_a_missing_file(demo_database, tmp_path): wfdb.dl_files("demo", str(out), ["100.hea", "999.hea"], overwrite=True) assert (out / "100.hea").read_bytes() == b"saved before" assert demo_database == [] + + +@pytest.mark.parametrize( + ("files", "keep_subdirs", "saved"), + [ + # 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"), + # One file through a symbolic link + (["a/100.hea", "b/100.hea"], True, "b/100.hea"), + ], + ids=["same-name", "case", "symbolic-link"], +) +def test_dl_files_overwrite_with_two_files_saved_as_one( + demo_database, tmp_path, files, keep_subdirs, saved +): + out = tmp_path / "out" + (out / "b").mkdir(parents=True) + try: + (out / "a").symlink_to(out / "b", target_is_directory=True) + except (OSError, NotImplementedError): + if "a/100.hea" in files: + pytest.skip("symbolic links are not available") + (out / saved).write_bytes(b"saved before") + + with pytest.raises(ValueError, match="would both be saved as"): + wfdb.dl_files( + "demo", str(out), files, keep_subdirs=keep_subdirs, overwrite=True + ) + assert (out / saved).read_bytes() == b"saved before" + assert demo_database == [] From 94bf24956186c7119d42c9f80e123358d419265a Mon Sep 17 00:00:00 2001 From: Tom Pollard Date: Mon, 23 Nov 2026 13:15:18 -0500 Subject: [PATCH 4/5] Let physionet replace saved files for overwrite=True physionet 0.7.1 adds overwrite to download(), applied after all of its checks of the requested files and destinations, and replacing each saved file only once its new copy is complete and its checksum matches. Pass overwrite through to it, and remove wfdb's own removal of saved files and the checks that had to come before it (_check_files_to_replace). This also keeps a saved file when its new download fails, which removing it first did not. The tests now check that overwrite is passed through and that wfdb removes nothing itself, and run a path outside dl_dir, two files with one name and names that differ only in case through the real physionet.download, which refuses them before replacing anything. --- changelog.d/dl-physionet.rst | 2 +- pyproject.toml | 2 +- src/wfdb/io/download.py | 90 +++--------------------------------- src/wfdb/io/record.py | 3 +- tests/test_physionet_uri.py | 90 ++++++++++++++---------------------- 5 files changed, 44 insertions(+), 143 deletions(-) diff --git a/changelog.d/dl-physionet.rst b/changelog.d/dl-physionet.rst index b3b46515..0c758fa3 100644 --- a/changelog.d/dl-physionet.rst +++ b/changelog.d/dl-physionet.rst @@ -1,2 +1,2 @@ **Download databases with the physionet package** - ``dl_database`` and ``dl_files`` now download files with the ``physionet`` package (0.7.0 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, 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. + ``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 c2513738..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.7.0", + "physionet >= 0.7.1", ] [project.urls] diff --git a/src/wfdb/io/download.py b/src/wfdb/io/download.py index cc59457e..91f9ff0f 100644 --- a/src/wfdb/io/download.py +++ b/src/wfdb/io/download.py @@ -482,15 +482,9 @@ def _download_files(db_dir, dl_dir, files, keep_subdirs, overwrite): if not os.path.isdir(dl_dir): os.makedirs(dl_dir) print("Created local base download directory: %s" % dl_dir) - if overwrite: - # Remove the saved files, so that they are downloaded again, but only - # once every file is known to exist and to be saved inside dl_dir - local_files = _check_files_to_replace(db_dir, dl_dir, files, saved_as) - for local_file in local_files: - if os.path.isfile(local_file): - os.remove(local_file) - - # Two files at a time, as before, to avoid overloading the server + # 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, @@ -499,83 +493,10 @@ def _download_files(db_dir, dl_dir, files, keep_subdirs, overwrite): verbose=False, show_progress=False, jobs=2, + overwrite=overwrite, ) -def _check_files_to_replace(db_dir, dl_dir, files, saved_as): - """Check the files that _download_files would replace, before removing any. - - Parameters - ---------- - db_dir : str - The PhysioNet database directory, including its version. - dl_dir : str - The local directory that the files are saved in. - files : list of str - The paths of the files to download, relative to `db_dir`. - saved_as : dict - The path that each file is saved as, relative to `dl_dir`, by its path - within the database. - - Returns - ------- - list of str - The local path of each file. - - Raises - ------ - ValueError - If a file would be saved outside `dl_dir`, because its path is not a - plain relative path (for example "../a.dat"), or through a symbolic - link, or if two files would be saved as one, including as names that - differ only in case (one file on macOS and Windows), or through a - symbolic link. - FileNotFoundError - If the database has no such file. - - """ - root = os.path.realpath(dl_dir) - local_files = [] - # Each destination, after following symbolic links and ignoring case, and - # the file saved there - destinations = {} - for path, local in saved_as.items(): - parts = local.split("/") - if ( - "\\" in local - or local.startswith("/") - or any(part in ("", ".", "..") for part in parts) - ): - raise ValueError( - f"Files can only be saved inside dl_dir, as plain relative paths: " - f"{local!r}" - ) - local_file = os.path.join(dl_dir, *parts) - resolved = os.path.realpath(local_file) - if os.path.commonpath([root, resolved]) != root: - raise ValueError( - f"{local!r} would be saved outside dl_dir, through a symbolic link" - ) - key = os.path.normcase(resolved).casefold() - if key in destinations: - raise ValueError( - f"{destinations[key]!r} and {path!r} would both be saved as " - f"{local!r} (or as the same file) in dl_dir" - ) - destinations[key] = path - local_files.append(local_file) - - available = _project_files(db_dir) - missing = [file for file in files if file not in available] - if missing: - raise FileNotFoundError( - f"{db_dir} has no file " - + ", ".join(repr(file) for file in missing[:5]) - + (f" and {len(missing) - 5} more" if len(missing) > 5 else "") - ) - return local_files - - def make_local_dirs(dl_dir, dl_inputs, keep_subdirs): """Make any required local directories to prepare for downloading. @@ -717,7 +638,8 @@ def dl_files(db, dl_dir, files, keep_subdirs=True, overwrite=False): If True, all files are downloaded again. 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. + any other saved file is downloaded again. A saved file is only + replaced once its new copy is complete and checked. Returns ------- diff --git a/src/wfdb/io/record.py b/src/wfdb/io/record.py index 65f3f10b..3b6ddd88 100644 --- a/src/wfdb/io/record.py +++ b/src/wfdb/io/record.py @@ -3329,7 +3329,8 @@ def dl_database( If True, all files are downloaded again. 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. + any other saved file is downloaded again. A saved file is only + replaced once its new copy is complete and checked. Returns ------- diff --git a/tests/test_physionet_uri.py b/tests/test_physionet_uri.py index ed4f9262..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 @@ -303,6 +304,7 @@ def test_dl_database_downloads_with_physionet(demo_database, tmp_path): "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"] @@ -334,9 +336,10 @@ def test_dl_database_overwrite(demo_database, tmp_path, overwrite): "demo", str(out), records=["100"], annotators=None, overwrite=overwrite ) - # With overwrite, the saved file is removed, so that it is downloaded again. - # Otherwise physionet keeps it if its checksum matches, and replaces it if not. - assert (out / "100.dat").exists() == (not 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]) @@ -368,73 +371,48 @@ def test_dl_files_from_another_server(demo_database, monkeypatch, tmp_path): ] -def test_dl_files_overwrite_never_removes_files_outside_dl_dir(demo_database, tmp_path): - out = tmp_path / "out" - out.mkdir() - victim = tmp_path / "victim.dat" - victim.write_bytes(b"keep me") - - with pytest.raises(ValueError, match="only be saved inside dl_dir"): - wfdb.dl_files("demo", str(out), ["../victim.dat"], overwrite=True) - assert victim.read_bytes() == b"keep me" - assert demo_database == [] - - -def test_dl_files_overwrite_through_a_symbolic_link(demo_database, tmp_path): - out = tmp_path / "out" - out.mkdir() - outside = tmp_path / "outside" - outside.mkdir() - (outside / "100.hea").write_bytes(b"keep me") - try: - (out / "link").symlink_to(outside, target_is_directory=True) - except (OSError, NotImplementedError): - pytest.skip("symbolic links are not available") - - with pytest.raises(ValueError, match="through a symbolic link"): - wfdb.dl_files("demo", str(out), ["link/100.hea"], overwrite=True) - assert (outside / "100.hea").read_bytes() == b"keep me" - assert demo_database == [] - - -def test_dl_files_overwrite_with_a_missing_file(demo_database, tmp_path): - out = tmp_path / "out" - out.mkdir() - (out / "100.hea").write_bytes(b"saved before") - - with pytest.raises(FileNotFoundError, match="no file '999.hea'"): - wfdb.dl_files("demo", str(out), ["100.hea", "999.hea"], overwrite=True) - assert (out / "100.hea").read_bytes() == b"saved before" - assert demo_database == [] - - @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"), - # One file through a symbolic link - (["a/100.hea", "b/100.hea"], True, "b/100.hea"), ], - ids=["same-name", "case", "symbolic-link"], + ids=["outside", "same-name", "case"], ) -def test_dl_files_overwrite_with_two_files_saved_as_one( - demo_database, tmp_path, files, keep_subdirs, saved +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 / "b").mkdir(parents=True) - try: - (out / "a").symlink_to(out / "b", target_is_directory=True) - except (OSError, NotImplementedError): - if "a/100.hea" in files: - pytest.skip("symbolic links are not available") + out.mkdir() (out / saved).write_bytes(b"saved before") - with pytest.raises(ValueError, match="would both be saved as"): + 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" - assert demo_database == [] + + +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"} From 054127238a7760a0726bbaa1f0c8ad25c404828b Mon Sep 17 00:00:00 2001 From: Tom Pollard Date: Mon, 23 Nov 2026 13:21:27 -0500 Subject: [PATCH 5/5] Say that only overwrite=True keeps a saved file until its new copy is checked --- src/wfdb/io/download.py | 11 ++++++----- src/wfdb/io/record.py | 11 ++++++----- 2 files changed, 12 insertions(+), 10 deletions(-) diff --git a/src/wfdb/io/download.py b/src/wfdb/io/download.py index 91f9ff0f..1d64473b 100644 --- a/src/wfdb/io/download.py +++ b/src/wfdb/io/download.py @@ -635,11 +635,12 @@ 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 are downloaded again. 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. A saved file is only - replaced once its new copy is complete and checked. + 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 ------- diff --git a/src/wfdb/io/record.py b/src/wfdb/io/record.py index 3b6ddd88..ff80b4ec 100644 --- a/src/wfdb/io/record.py +++ b/src/wfdb/io/record.py @@ -3326,11 +3326,12 @@ 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 are downloaded again. 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. A saved file is only - replaced once its new copy is complete and checked. + 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 -------