Coverage for src/scixplorer/data/__init__.py: 99%

237 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-18 23:06 +0000

1"""Reference data held locally: journals, affiliations and two controlled vocabularies. 

2 

3Each dataset is read from the user's cache if :func:`refresh` has downloaded it, 

4otherwise from the snapshot packaged with this library (journals and 

5affiliations only). The Unified Astronomy Thesaurus and the planetary 

6nomenclature gazetteer are not packaged: run ``refresh("uat")`` or 

7``refresh("planetary_features")`` once to use them. 

8 

9Nothing is downloaded implicitly. :func:`refresh` uses a plain HTTP client that 

10never sends the SciX API token, because the sources are third-party hosts. 

11Downloads are checked by the same parser the model uses before they replace 

12the data in use, and are written atomically. 

13 

14The packaged data files are not covered by this package's MIT licence: the 

15affiliation files are GPL-3.0. :func:`notices` returns the details. 

16 

17The cache directory is ``$SCIX_CACHE_DIR`` if set, else 

18``$XDG_CACHE_HOME/scixplorer``, else ``~/Library/Caches/scixplorer`` on macOS 

19and ``~/.cache/scixplorer`` elsewhere. 

20""" 

21 

22from __future__ import annotations 

23 

24import html 

25import importlib 

26import json 

27import os 

28import re 

29import sys 

30import tempfile 

31import warnings 

32from collections.abc import Callable, Mapping, Sized 

33from dataclasses import dataclass 

34from datetime import datetime, timezone 

35from importlib import resources 

36from pathlib import Path 

37from types import MappingProxyType 

38from typing import Literal, TypeVar 

39 

40import httpx 

41 

42from .. import __version__ 

43from ..exceptions import DataNotAvailable, DataWarning 

44 

45__all__ = [ 

46 "DATASETS", 

47 "Dataset", 

48 "DatasetStatus", 

49 "Reader", 

50 "RefreshResult", 

51 "RemoteFile", 

52 "cache_dir", 

53 "clear", 

54 "load", 

55 "notices", 

56 "read_text", 

57 "refresh", 

58 "register", 

59 "status", 

60] 

61 

62#: Reads one file of a dataset by name and returns its text. 

63Reader = Callable[[str], str] 

64 

65S = TypeVar("S", bound=Sized) 

66 

67USER_AGENT = f"scixplorer/{__version__}" 

68_PACKAGE = __name__.rpartition(".")[0] 

69 

70 

71@dataclass(frozen=True) 

72class RemoteFile: 

73 """One file of a dataset: where it is published and its name in the cache. 

74 

75 The cached file always has the packaged format. ``convert``, if given, 

76 turns the published text into that format. 

77 """ 

78 

79 url: str 

80 filename: str 

81 convert: Callable[[str], str] | None = None 

82 

83 

84@dataclass(frozen=True) 

85class Dataset: 

86 """A collection of reference data and where it comes from. 

87 

88 ``files`` is empty if there is no public source to refresh it from. 

89 ``packaged`` says whether a snapshot ships with this library. ``licence`` 

90 is the data's licence, as :func:`notices` states it. 

91 """ 

92 

93 name: str 

94 files: tuple[RemoteFile, ...] 

95 packaged: bool 

96 licence: str 

97 description: str 

98 

99 

100@dataclass(frozen=True) 

101class RefreshResult: 

102 """The outcome of refreshing one dataset. ``files`` are the cache files written.""" 

103 

104 name: str 

105 ok: bool 

106 files: tuple[Path, ...] 

107 message: str 

108 

109 

110@dataclass(frozen=True) 

111class DatasetStatus: 

112 """Which copy of a dataset is in use. 

113 

114 ``source`` is ``"cache"`` (downloaded by :func:`refresh`), ``"packaged"`` 

115 or ``"missing"``. ``modified`` (UTC) and ``size`` (bytes) cover all the 

116 files in ``paths``; they are ``None`` when nothing can be inspected. The 

117 cached files are not parsed here, so an unreadable cache still shows as 

118 ``"cache"`` (the models then fall back to the packaged snapshot, with a 

119 :class:`~scixplorer.exceptions.DataWarning`). 

120 """ 

121 

122 name: str 

123 source: Literal["cache", "packaged", "missing"] 

124 paths: tuple[Path, ...] 

125 modified: datetime | None 

126 size: int | None 

127 

128 

129_ROW = re.compile(r"""<a href="#" onClick="setfields\('[^']*'\);">([^<]*)</a>(.*)""") 

130 

131 

132def _journal_list_to_json(page: str) -> str: 

133 """Convert the ADS journal abbreviation page to ``journals.json`` (``{abbreviation: title}``). 

134 

135 Each entry is a line ``<a ... setfields('ApJ..');"> ApJ </a> The Astrophysical Journal``; 

136 the abbreviation is the link text, as in the packaged snapshot. The first 

137 title wins if an abbreviation is listed twice. 

138 """ 

139 titles: dict[str, str] = {} 

140 for line in page.splitlines(): 

141 match = _ROW.search(line) 

142 if match is not None: 

143 abbreviation = html.unescape(match.group(1)).strip() 

144 title = html.unescape(match.group(2)).strip() 

145 if abbreviation and title: 145 ↛ 140line 145 didn't jump to line 140 because the condition on line 145 was always true

146 titles.setdefault(abbreviation, title) 

147 if not titles: 

148 raise ValueError("no journal entries found in the page") 

149 return json.dumps(titles, ensure_ascii=False, indent=0) 

150 

151 

152_AFFILIATIONS = "https://raw.githubusercontent.com/adsabs/CanonicalAffiliations/master/" 

153 

154DATASETS: Mapping[str, Dataset] = MappingProxyType( 

155 { 

156 "journals": Dataset( 

157 name="journals", 

158 files=( 

159 RemoteFile( 

160 "https://adsabs.harvard.edu/abs_doc/journals.html", 

161 "journals.json", 

162 convert=_journal_list_to_json, 

163 ), 

164 ), 

165 packaged=True, 

166 licence="No licence stated (ADS bibliographic code list)", 

167 description="Journal abbreviations (bibstems) and titles, from the ADS journal list.", 

168 ), 

169 "affiliations": Dataset( 

170 name="affiliations", 

171 files=( 

172 RemoteFile(_AFFILIATIONS + "parent_child.tsv", "affiliations.tsv"), 

173 RemoteFile(_AFFILIATIONS + "country_parent_child.tsv", "affiliations_country.tsv"), 

174 ), 

175 packaged=True, 

176 licence="GPL-3.0 (adsabs/CanonicalAffiliations)", 

177 description="Canonical institutions, their hierarchy and countries, from adsabs/CanonicalAffiliations.", 

178 ), 

179 "uat": Dataset( 

180 name="uat", 

181 files=( 

182 RemoteFile( 

183 "https://raw.githubusercontent.com/astrothesaurus/UAT/master/UAT_list.json", 

184 "uat.json", 

185 ), 

186 ), 

187 packaged=False, 

188 licence="CC BY-SA 3.0 (American Astronomical Society)", 

189 description="The Unified Astronomy Thesaurus, from astrothesaurus/UAT (about 1.5 MB).", 

190 ), 

191 "planetary_features": Dataset( 

192 name="planetary_features", 

193 files=( 

194 RemoteFile( 

195 "https://raw.githubusercontent.com/adsabs/ADSPlanetaryNamesPipeline/main/docs/" 

196 "Gazetteer_of_Planetary_Nomenclature_Exported_Nov_7_2024.csv", 

197 "planetary_features.csv", 

198 ), 

199 ), 

200 packaged=False, 

201 licence="Public domain (USGS Gazetteer of Planetary Nomenclature), via an MIT-licensed adsabs repository", 

202 description="Named planetary surface features (IAU/USGS gazetteer export used by ADS, about 0.9 MB).", 

203 ), 

204 } 

205) 

206 

207#: The module that registers each dataset's parser, relative to this package's parent. 

208_OWNERS = { 

209 "journals": "models.journal", 

210 "affiliations": "models.affiliation", 

211 "uat": "models.uat", 

212 "planetary_features": "models.planetary", 

213} 

214 

215 

216@dataclass(frozen=True) 

217class _Registration: 

218 parse: Callable[[Reader], Sized] 

219 reset: Callable[[], None] 

220 

221 

222_registry: dict[str, _Registration] = {} 

223 

224 

225def register(name: str, parse: Callable[[Reader], Sized], reset: Callable[[], None]) -> None: 

226 """Register how a model reads dataset ``name``; models call this when imported. 

227 

228 :param parse: builds the model's records from a :data:`Reader`; it raises on 

229 malformed data. :func:`load` and :func:`refresh` both use it. 

230 :param reset: forgets everything the model has cached from the data, so the 

231 next query reads it again. Called after :func:`refresh` or :func:`clear`. 

232 """ 

233 _dataset(name) 

234 _registry[name] = _Registration(parse, reset) 

235 

236 

237def _registration(name: str) -> _Registration: 

238 if name not in _registry: 

239 importlib.import_module(f"{_PACKAGE}.{_OWNERS[name]}") 

240 return _registry[name] 

241 

242 

243def _dataset(name: str) -> Dataset: 

244 try: 

245 return DATASETS[name] 

246 except KeyError: 

247 raise ValueError(f"Unknown dataset {name!r}; datasets are: {', '.join(DATASETS)}") from None 

248 

249 

250def _call(function: str, name: str) -> str: 

251 return f'{__name__}.{function}("{name}")' 

252 

253 

254def cache_dir() -> Path: 

255 """The directory holding downloaded data. It is created only when something is written.""" 

256 explicit = os.environ.get("SCIX_CACHE_DIR") 

257 if explicit: 

258 return Path(explicit).expanduser() 

259 xdg = os.environ.get("XDG_CACHE_HOME") 

260 if xdg: 

261 return Path(xdg).expanduser() / "scixplorer" 

262 if sys.platform == "darwin": 

263 return Path.home() / "Library" / "Caches" / "scixplorer" 

264 return Path.home() / ".cache" / "scixplorer" 

265 

266 

267def _cached_paths(dataset: Dataset, directory: Path) -> tuple[Path, ...] | None: 

268 """The dataset's files in ``directory``, or ``None`` unless every one exists.""" 

269 paths = tuple(directory / remote.filename for remote in dataset.files) 

270 if paths and all(path.is_file() for path in paths): 

271 return paths 

272 return None 

273 

274 

275def _read_packaged(filename: str) -> str: 

276 return (resources.files(__name__) / filename).read_text(encoding="utf-8") 

277 

278 

279def notices() -> str: 

280 """The licence notice for the data files packaged with this library (``NOTICE.md``). 

281 

282 It says where each file comes from and under which licence; the packaged 

283 data is not covered by the package's MIT licence. The GPL-3.0 text it 

284 refers to is the package resource ``LICENSE-GPL-3.0.txt`` beside it. 

285 """ 

286 return _read_packaged("NOTICE.md") 

287 

288 

289def read_text(dataset: str, filename: str) -> str: 

290 """The text of one file of a dataset: the cached copy if every file of the 

291 dataset is cached (as :func:`load` and :func:`status` decide), else the packaged one. 

292 

293 Raises :class:`~scixplorer.exceptions.DataNotAvailable` if neither exists. The 

294 text is not checked; :func:`load` checks it and falls back if it is bad. 

295 """ 

296 found = _dataset(dataset) 

297 if filename not in {remote.filename for remote in found.files}: 

298 names = ", ".join(remote.filename for remote in found.files) 

299 raise ValueError(f"{dataset!r} has no file {filename!r}; its files are: {names}") 

300 directory = cache_dir() 

301 if _cached_paths(found, directory) is not None: 

302 return (directory / filename).read_text(encoding="utf-8") 

303 if found.packaged: 

304 return _read_packaged(filename) 

305 raise _not_available(found) 

306 

307 

308def _not_available(dataset: Dataset, problem: str = "") -> DataNotAvailable: 

309 reason = problem or f"The {dataset.name!r} data has not been downloaded" 

310 return DataNotAvailable( 

311 f"{reason}. {dataset.description} Download it once with {_call('refresh', dataset.name)}; " 

312 f"it is stored in {cache_dir()}." 

313 ) 

314 

315 

316class _TrackingReader: 

317 """A :data:`Reader` over one directory that remembers the last file it read.""" 

318 

319 def __init__(self, directory: Path) -> None: 

320 self.directory = directory 

321 self.last: Path | None = None 

322 

323 def __call__(self, filename: str) -> str: 

324 self.last = self.directory / filename 

325 return self.last.read_text(encoding="utf-8") 

326 

327 

328def _parse_cache(dataset: Dataset, parse: Callable[[Reader], S]) -> tuple[S | None, str | None]: 

329 """Parse the cached copy: ``(records, None)``, ``(None, None)`` if there is none, 

330 or ``(None, problem)`` if it cannot be read.""" 

331 directory = cache_dir() 

332 paths = _cached_paths(dataset, directory) 

333 if paths is None: 

334 return None, None 

335 reader = _TrackingReader(directory) 

336 try: 

337 records = parse(reader) 

338 if len(records) == 0: 

339 raise ValueError("it holds no records") 

340 # The cache is outside our control: any failure to parse it means "unusable", 

341 # whatever exception the parser raised. 

342 except Exception as exc: 

343 culprit = reader.last or paths[0] 

344 return None, f"The cached file {culprit} could not be used ({type(exc).__name__}: {exc})" 

345 return records, None 

346 

347 

348def load(name: str, parse: Callable[[Reader], S]) -> S: 

349 """Parse dataset ``name`` with ``parse``: the cached copy if usable, else the packaged one. 

350 

351 An unusable cached copy is skipped with a :class:`~scixplorer.exceptions.DataWarning`. 

352 Raises :class:`~scixplorer.exceptions.DataNotAvailable` if there is no usable copy 

353 and nothing is packaged. 

354 """ 

355 dataset = _dataset(name) 

356 records, problem = _parse_cache(dataset, parse) 

357 if records is not None: 

358 return records 

359 if problem is not None: 

360 fallback = "using the packaged snapshot instead" if dataset.packaged else "it is ignored" 

361 warnings.warn( 

362 f"{problem}; {fallback}. Download a fresh copy with {_call('refresh', name)} " 

363 f"or delete it with {_call('clear', name)}.", 

364 DataWarning, 

365 stacklevel=2, 

366 ) 

367 if dataset.packaged: 

368 return parse(_read_packaged) 

369 raise _not_available(dataset, problem or "") 

370 

371 

372def _records_in_use(dataset: Dataset, registration: _Registration) -> int: 

373 """How many records the data currently in use holds (0 if there is none).""" 

374 records, _ = _parse_cache(dataset, registration.parse) 

375 if records is not None: 

376 return len(records) 

377 return len(registration.parse(_read_packaged)) if dataset.packaged else 0 

378 

379 

380def refresh( 

381 *names: str, transport: httpx.BaseTransport | None = None, timeout: float = 60.0 

382) -> list[RefreshResult]: 

383 """Download datasets into the cache, replacing the copies in use if the downloads are good. 

384 

385 With no names, every dataset with a public source is refreshed. Each 

386 download is parsed by its model before anything is written, and rejected 

387 (leaving the data in use untouched) if it does not parse, is empty, or has 

388 fewer than half as many records as the data in use. A dataset's files are 

389 replaced together or not at all. One dataset failing does not stop the 

390 others: check ``ok`` on each result. 

391 

392 Requests carry only a generic User-Agent; the SciX API token is never sent. 

393 

394 :param transport: an ``httpx`` transport, e.g. for testing or a proxy setup. 

395 :param timeout: seconds allowed for each request. 

396 """ 

397 datasets = [_dataset(name) for name in names] or [d for d in DATASETS.values() if d.files] 

398 with httpx.Client( 

399 transport=transport, 

400 timeout=timeout, 

401 follow_redirects=True, 

402 headers={"User-Agent": USER_AGENT}, 

403 ) as client: 

404 return [_refresh_one(client, dataset) for dataset in datasets] 

405 

406 

407def _refresh_one(client: httpx.Client, dataset: Dataset) -> RefreshResult: 

408 def failed(message: str) -> RefreshResult: 

409 return RefreshResult(dataset.name, False, (), f"{message}; the data in use is unchanged") 

410 

411 if not dataset.files: 

412 return failed("no public source") 

413 registration = _registration(dataset.name) 

414 texts: dict[str, str] = {} 

415 for remote in dataset.files: 

416 try: 

417 response = client.get(remote.url) 

418 except httpx.HTTPError as exc: 

419 return failed(f"could not download {remote.url} ({type(exc).__name__}: {exc})") 

420 if response.status_code != 200: 

421 return failed(f"{remote.url} returned HTTP {response.status_code}") 

422 text = response.text.removeprefix("") 

423 try: 

424 texts[remote.filename] = remote.convert(text) if remote.convert else text 

425 except ValueError as exc: 

426 return failed(f"{remote.url} is not in the expected format ({exc})") 

427 

428 try: 

429 count = len(registration.parse(texts.__getitem__)) 

430 # Downloads are untrusted input: any parser failure means "reject". 

431 except Exception as exc: 

432 return failed(f"the download could not be parsed ({type(exc).__name__}: {exc})") 

433 in_use = _records_in_use(dataset, registration) 

434 if count == 0: 

435 return failed("the download holds no records") 

436 if count * 2 < in_use: 

437 return failed(f"the download holds {count} records, fewer than half of the {in_use} in use") 

438 

439 try: 

440 paths = _write(cache_dir(), texts) 

441 except OSError as exc: 

442 return failed(f"could not write to the cache ({exc})") 

443 registration.reset() 

444 change = f" (was {in_use})" if in_use else "" 

445 return RefreshResult(dataset.name, True, paths, f"{count} records{change}") 

446 

447 

448def _write(directory: Path, texts: Mapping[str, str]) -> tuple[Path, ...]: 

449 """Write every file atomically, replacing all of them only once all are staged.""" 

450 directory.mkdir(parents=True, exist_ok=True) 

451 staged: list[tuple[Path, Path]] = [] 

452 try: 

453 for filename, text in texts.items(): 

454 handle, name = tempfile.mkstemp(dir=directory, prefix=f".{filename}.", suffix=".tmp") 

455 staged.append((Path(name), directory / filename)) 

456 with os.fdopen(handle, "w", encoding="utf-8", newline="") as stream: 

457 stream.write(text) 

458 stream.flush() 

459 os.fsync(stream.fileno()) 

460 for temporary, target in staged: 

461 os.replace(temporary, target) 

462 finally: 

463 for temporary, _ in staged: 

464 temporary.unlink(missing_ok=True) 

465 return tuple(target for _, target in staged) 

466 

467 

468def clear(*names: str) -> None: 

469 """Delete the cached copies of datasets (all if no names); packaged snapshots are kept. 

470 

471 Models then read their packaged snapshot, or raise 

472 :class:`~scixplorer.exceptions.DataNotAvailable` if there is none. 

473 """ 

474 datasets = [_dataset(name) for name in names] or list(DATASETS.values()) 

475 directory = cache_dir() 

476 for dataset in datasets: 

477 for remote in dataset.files: 

478 (directory / remote.filename).unlink(missing_ok=True) 

479 registration = _registry.get(dataset.name) 

480 if registration is not None: 480 ↛ 476line 480 didn't jump to line 476 because the condition on line 480 was always true

481 registration.reset() 

482 

483 

484def status() -> list[DatasetStatus]: 

485 """Which copy of each dataset is in use, where it is, when it was modified and its size.""" 

486 directory = cache_dir() 

487 result = [] 

488 for dataset in DATASETS.values(): 

489 cached = _cached_paths(dataset, directory) 

490 if cached is not None: 

491 result.append(_describe(dataset.name, "cache", cached)) 

492 elif dataset.packaged: 

493 packaged = [resources.files(__name__) / remote.filename for remote in dataset.files] 

494 paths = tuple(path for path in packaged if isinstance(path, Path)) 

495 result.append(_describe(dataset.name, "packaged", paths)) 

496 else: 

497 result.append(DatasetStatus(dataset.name, "missing", (), None, None)) 

498 return result 

499 

500 

501def _describe(name: str, source: Literal["cache", "packaged"], paths: tuple[Path, ...]) -> DatasetStatus: 

502 if not paths: 502 ↛ 503line 502 didn't jump to line 503 because the condition on line 502 was never true

503 return DatasetStatus(name, source, paths, None, None) 

504 stats = [path.stat() for path in paths] 

505 modified = datetime.fromtimestamp(max(stat.st_mtime for stat in stats), tz=timezone.utc) 

506 return DatasetStatus(name, source, paths, modified, sum(stat.st_size for stat in stats))