forked from openslide/openslide.github.io
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtestdata_fetch.py
More file actions
executable file
·165 lines (143 loc) · 4.62 KB
/
testdata_fetch.py
File metadata and controls
executable file
·165 lines (143 loc) · 4.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
#!/usr/bin/env python3
#
# testdata_fetch - Fetch openslide-testdata to local directory
#
# Copyright (c) 2010-2015, 2022 Carnegie Mellon University
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of version 2.1 of the GNU Lesser General Public License
# as published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
# License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
from __future__ import annotations
import argparse
import calendar
from hashlib import sha256
import json
import os
from pathlib import Path, PurePath
from typing import cast
from urllib.parse import urljoin
import dateutil.parser
import requests
TESTDATA_BASEURL = 'https://openslide.cs.cmu.edu/download/openslide-testdata/'
BUFSIZE = 10 << 20
IGNORE_FILENAMES = frozenset(
(
'index.html',
'index.json',
'index.yaml',
)
)
def fetch_file(
baseurl: str,
basepath: Path,
relpath: PurePath,
expected_sha256: str | None = None,
) -> Path:
path = basepath / relpath
count = 0
sha = sha256()
r = requests.get(urljoin(baseurl, relpath.as_posix()), stream=True)
r.raise_for_status()
path.parent.mkdir(parents=True, exist_ok=True)
try:
with path.open('wb') as fh:
for buf in r.iter_content(BUFSIZE):
fh.write(buf)
if expected_sha256 is not None:
sha.update(buf)
count += len(buf)
if count != int(r.headers['Content-Length']):
raise OSError(f"Short read fetching {relpath}")
if expected_sha256 is not None and expected_sha256 != sha.hexdigest():
raise OSError(f'Hash mismatch fetching {relpath}')
except Exception:
path.unlink()
raise
try:
dt = dateutil.parser.parse(r.headers['Last-Modified'])
stamp = calendar.timegm(dt.utctimetuple())
os.utime(path, (stamp, stamp))
except KeyError:
pass
return path
def fetch_slide(
baseurl: str,
basepath: Path,
relpath: PurePath,
info: dict[str, str | int],
check_hashes: bool = False,
) -> Path:
path = basepath / relpath
try:
if path.stat().st_size == info['size']:
# File already exists and is the right size
if not check_hashes:
# Assume identical to remote
return path
with path.open('rb') as fh:
sha = sha256()
while True:
buf = fh.read(BUFSIZE)
if not buf:
break
sha.update(buf)
if sha.hexdigest() == info['sha256']:
# Identical to remote
return path
except OSError:
# No local copy
pass
print(f'Fetching {relpath}...')
return fetch_file(baseurl, basepath, relpath, cast(str, info['sha256']))
def fetch_repo(
basepath: Path, baseurl: str = TESTDATA_BASEURL, check_hashes: bool = False
) -> None:
# Fetch JSON index
jsonpath = fetch_file(baseurl, basepath, PurePath('index.json'))
with jsonpath.open() as fh:
slides = json.load(fh)
# Fetch slides
dirpaths = set()
for rp, info in sorted(slides.items()):
relpath = PurePath(rp)
fetch_slide(
baseurl, basepath, relpath, info, check_hashes=check_hashes
)
dirpaths.add(relpath.parent)
# Fetch YAML metadata
for dirpath in sorted(dirpaths):
fetch_file(baseurl, basepath, dirpath / 'index.yaml')
# Check for extra files in local repo
for filepath in basepath.rglob('*'):
if (
filepath.is_file()
and filepath.relative_to(basepath).as_posix() not in slides
and filepath.name not in IGNORE_FILENAMES
):
print(f'Unexpected file: {filepath}')
def _main() -> None:
parser = argparse.ArgumentParser(
description='Fetch openslide-testdata to local directory.'
)
parser.add_argument(
'path', type=Path, help='path to destination directory'
)
parser.add_argument(
'-c',
'--check-hashes',
action='store_true',
help='check SHA-256 digests of existing files',
)
args = parser.parse_args()
fetch_repo(args.path, check_hashes=args.check_hashes)
if __name__ == '__main__':
_main()