Skip to content

Download databases with the physionet package - #659

Open
tompollard wants to merge 3 commits into
mainfrom
dl-via-physionet
Open

tompollard wants to merge 3 commits into
mainfrom
dl-via-physionet

Conversation

@tompollard

Copy link
Copy Markdown
Member

Follows #657 and #658. dl_database and dl_files now download files with physionet.download(), using the files= and verbose= arguments added in physionet 0.7.0 (MIT-LCP/physionet#218), so they keep their arguments and folder layout.

Downloading the same files on main and on this branch against PhysioNet gave identical files (13, including a file in a subfolder and the keep_subdirs=False layout):

main This PR
dl_database("mitdb", records=["100", "101", "102"], annotators=["atr"]) 38 requests, 11.2 s 20 requests, 4.9 s
dl_files("mitdb", [...]) with 2 files 4 requests, about 0.7 s 6 requests, 1.7 s

dl_database is faster mainly because it finds which annotation files there are from the checksum list, rather than requesting each one. A small dl_files call costs a little more, since physionet.download() looks up the version, the checksum list and the source first.

Changes

  • A new download._download_files(db_dir, dl_dir, files, keep_subdirs, overwrite) maps each file (relative to db_dir, which may include a subdirectory) to where it is saved (the same path relative to dl_dir, or its name with keep_subdirs=False), and calls physionet.download(slug, version, files=..., verbose=False, show_progress=False, jobs=2). Two files at a time, no progress bars and wfdb's own messages, as before.
  • 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 any other saved file is downloaded again. Before, only sizes were compared, so a saved file of the right size but different content was kept. overwrite=True removes the saved files first.
  • Restricted databases can be downloaded after physionet login. get_record_list and get_annotators read RECORDS and ANNOTATORS with _open_pn_file, so through physionet:// too.
  • dl_database finds annotation files with a new download._project_files(db_dir), which lists the files from the checksum list through the physionet:// filesystem, instead of a request for each record and annotator.
  • dl_files no longer requests the database's web page first: physionet reports a missing database, version or file before downloading anything. Before, the files listed before a missing one were downloaded first.
  • With keep_subdirs=False, two files with the same name now raise a ValueError from physionet, instead of one silently replacing the other.
  • With a database index URL set by set_db_index_url, both functions download from that server with the existing code.
  • physionet >= 0.7.0 is now required. The overwrite docs and a new Notes section describe the behaviour, and a changelog entry is added.

Testing

  • New tests in tests/test_physionet_uri.py build a database in a temporary physionet cache (RECORDS, ANNOTATORS, a single-segment, a multi-segment and a subdirectory record, and a checksum list), make every request fail, and replace physionet.download to record its arguments. They check the files and where they are saved, a subdirectory in db_dir, keep_subdirs=False, overwrite, dl_files with both layouts and without a web page request, and dl_files with set_db_index_url. Five of the seven fail on main; the other two describe behaviour that is unchanged.
  • uv run pytest -m "not network": 496 passed, also with --python 3.11 --resolution lowest-direct.
  • uv run pytest -m network: 18 passed, including the existing dl_database tests that download from PhysioNet's afdb.
  • ruff format --check, ruff check and the docs build pass.

@tompollard 🟥 red 🦥 sloth

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.
@tompollard

Copy link
Copy Markdown
Member Author

Reviewed f49bfeb. I found one issue to fix before merging:

overwrite=True can delete files outside the download directory before the requested paths are validated. _download_files() removes existing paths first, then calls physionet.download(), which rejects unsafe destinations. I reproduced this through the public API: with victim.dat beside out/, wfdb.dl_files("demo", "out", ["../victim.dat"], overwrite=True) removed victim.dat and then raised ValueError. A directory symlink inside out/ can likewise make a plain-looking path target a file outside it.

Please validate the requested paths and their resolved destinations before removing anything. Ideally, let physionet.download() handle forced replacement after its manifest and destination checks, so invalid or missing requests cannot delete existing files.

The 496 offline tests and all PR checks pass; they do not cover this case.

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.
@tompollard

Copy link
Copy Markdown
Member Author

Thanks, that was a real problem. Fixed in the latest commit.

With overwrite=True, _download_files() now checks every requested file before removing any saved copies:

  1. Each path it would be saved as must be a plain relative path, without .., . or empty parts, a leading / or a backslash. Otherwise it raises ValueError.
  2. Each resolved destination, after following symbolic links, must be inside dl_dir. Otherwise it raises ValueError.
  3. Each requested file must be in the database's checksum list. Otherwise it raises FileNotFoundError naming the missing files.

Only then are the saved copies removed and physionet.download() called. Your example, wfdb.dl_files("demo", "out", ["../victim.dat"], overwrite=True), now raises ValueError with victim.dat left in place. The same check covers dl_database, where the file names come from the record headers.

I kept this in wfdb rather than adding forced replacement to physionet.download(), since that would need another physionet release first. It also matters less now: download() already downloads again any saved file whose checksum does not match, so overwrite=True only makes a difference for files that are already correct. If you'd still prefer it in physionet, I can add it there as a follow-up.

New tests, each checking that no file is removed and physionet.download is not called: test_dl_files_overwrite_never_removes_files_outside_dl_dir (your ../victim.dat case), test_dl_files_overwrite_through_a_symbolic_link and test_dl_files_overwrite_with_a_missing_file. All three fail on f49bfeb. Offline tests: 499 passed. Network tests: 17 passed, 1 skipped because PhysioNet was briefly unreachable. Against PhysioNet, dl_files(..., overwrite=True) still replaces a damaged saved copy.

@tompollard

Copy link
Copy Markdown
Member Author

Re-reviewed 0af51fb. The earlier ../victim.dat, outside-directory symlink, and missing-file cases are now checked before deletion. One data-loss case remains to fix before merging:

With keep_subdirs=False, two valid source files can map to one destination. For example, with sub1/100.hea and sub2/100.hea present in the checksum list, wfdb.dl_files("demo", out, ["sub1/100.hea", "sub2/100.hea"], keep_subdirs=False, overwrite=True) passes _check_files_to_replace(). _download_files() then removes an existing out/100.hea; only afterward does physionet.download() reject the duplicate destination with ValueError. I reproduced the existing file being removed.

Please check that resolved destinations are distinct before removing saved files, including names that differ only by case or resolve through a symlink. The 24 focused tests pass; CI was still running when I checked.

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.
@tompollard

Copy link
Copy Markdown
Member Author

Thanks, fixed in the latest commit.

Before removing anything for overwrite=True, _check_files_to_replace() now also checks that no two requested files would be saved as one, and raises ValueError naming both if so. It compares the destinations after following symbolic links and ignoring case, since names that differ only in case are one file on macOS and Windows. With your example, dl_files("demo", out, ["sub1/100.hea", "sub2/100.hea"], keep_subdirs=False, overwrite=True) now raises with out/100.hea left in place.

New test_dl_files_overwrite_with_two_files_saved_as_one covers the three ways this can happen: two files with one name without their subdirectories, names that differ only in case, and two paths that are one file through a symbolic link inside dl_dir. Each checks that the saved file is kept and that physionet.download is not called. All three fail on 0af51fb. Offline tests: 502 passed. Network tests: 17 passed, 1 skipped because PhysioNet was briefly unreachable.

MIT-LCP/physionet#221 adds overwrite to physionet.download() itself, applied after all of its checks and replacing each file only once the new download is verified. Once that is released, wfdb can pass overwrite through and drop its own removal step and these checks, so they are only needed until then.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant