|
| 1 | +"""Access built-in data files shipped with Python packages. |
| 2 | +
|
| 3 | +Provides a simple API to load YAML, JSON, and other data files from a |
| 4 | +package's ``data/`` or ``_data/`` subdirectory. |
| 5 | +
|
| 6 | +Example:: |
| 7 | +
|
| 8 | + from pkg_infra.data import load |
| 9 | +
|
| 10 | + # Load data from the calling package's data/ directory |
| 11 | + config = load('default_config.yaml') |
| 12 | +
|
| 13 | + # Load data from a specific package |
| 14 | + ids = load('id_types.json', module='omnipath_utils') |
| 15 | +""" |
| 16 | + |
| 17 | +from __future__ import annotations |
| 18 | + |
| 19 | +from typing import Any, Callable |
| 20 | +import os |
| 21 | +import json |
| 22 | +import pathlib as pl |
| 23 | +import functools |
| 24 | +import collections |
| 25 | +import logging |
| 26 | + |
| 27 | +import yaml |
| 28 | + |
| 29 | +__all__ = ['builtins', 'load', 'path'] |
| 30 | + |
| 31 | +_logger = logging.getLogger(__name__) |
| 32 | + |
| 33 | +_FORMATS = { |
| 34 | + 'json': functools.partial( |
| 35 | + json.load, |
| 36 | + object_pairs_hook=collections.OrderedDict, |
| 37 | + ), |
| 38 | + 'yaml': functools.partial(yaml.load, Loader=yaml.FullLoader), |
| 39 | + 'txt': None, |
| 40 | + '': None, |
| 41 | +} |
| 42 | + |
| 43 | + |
| 44 | +def _caller_module() -> str: |
| 45 | + """Get the name of the module that called this function.""" |
| 46 | + |
| 47 | + import inspect |
| 48 | + |
| 49 | + frame = inspect.currentframe() |
| 50 | + |
| 51 | + try: |
| 52 | + caller = frame.f_back.f_back |
| 53 | + return caller.f_globals.get('__name__', '__main__').split('.')[0] |
| 54 | + finally: |
| 55 | + del frame |
| 56 | + |
| 57 | + |
| 58 | +def _module_datadir(module: str) -> pl.Path | None: |
| 59 | + """Find the data directory for a module.""" |
| 60 | + |
| 61 | + import importlib |
| 62 | + |
| 63 | + try: |
| 64 | + mod = importlib.import_module(module) |
| 65 | + except ModuleNotFoundError: |
| 66 | + return None |
| 67 | + |
| 68 | + if mod_path := getattr(mod, '__path__', None): |
| 69 | + base = pl.Path(mod_path[0]) |
| 70 | + elif mod_file := getattr(mod, '__file__', None): |
| 71 | + base = pl.Path(mod_file).parent |
| 72 | + else: |
| 73 | + return None |
| 74 | + |
| 75 | + for dirname in ('data', '_data'): |
| 76 | + datadir = base / dirname |
| 77 | + if datadir.is_dir(): |
| 78 | + return datadir |
| 79 | + |
| 80 | + return None |
| 81 | + |
| 82 | + |
| 83 | +def path(label: str, module: str | None = None) -> pl.Path | None: |
| 84 | + """Find path to a data file shipped with a package. |
| 85 | +
|
| 86 | + Args: |
| 87 | + label: Filename or label of a built-in dataset. |
| 88 | + module: Package name. Defaults to the calling package. |
| 89 | +
|
| 90 | + Returns: |
| 91 | + Path to the file, or None if not found. |
| 92 | + """ |
| 93 | + |
| 94 | + if os.path.exists(label): |
| 95 | + return pl.Path(label).absolute() |
| 96 | + |
| 97 | + available = builtins(module or _caller_module()) |
| 98 | + stem = label.rsplit('.', maxsplit=1)[0] if '.' in label else label |
| 99 | + return available.get(label) or available.get(stem) |
| 100 | + |
| 101 | + |
| 102 | +def load( |
| 103 | + label: str, |
| 104 | + module: str | None = None, |
| 105 | + reader: Callable | None = None, |
| 106 | + **kwargs, |
| 107 | +) -> Any: |
| 108 | + """Load a data file shipped with a package. |
| 109 | +
|
| 110 | + Args: |
| 111 | + label: Filename or label of a built-in dataset. |
| 112 | + module: Package name. Defaults to the calling package. |
| 113 | + reader: Custom reader function. Auto-detected from extension if None. |
| 114 | + kwargs: Extra arguments passed to the reader. |
| 115 | +
|
| 116 | + Returns: |
| 117 | + The loaded data (typically dict or list). |
| 118 | + """ |
| 119 | + |
| 120 | + module = module or _caller_module() |
| 121 | + |
| 122 | + if _path := path(label, module): |
| 123 | + |
| 124 | + if not reader: |
| 125 | + ext = _path.name.rsplit('.', maxsplit=1)[-1].lower() |
| 126 | + if ext == 'tsv': |
| 127 | + kwargs['sep'] = '\t' |
| 128 | + reader = _FORMATS.get(ext, lambda x: x.readlines()) |
| 129 | + |
| 130 | + _logger.debug( |
| 131 | + 'Loading built-in data `%s` from module `%s`; path: `%s`.', |
| 132 | + label, module, _path, |
| 133 | + ) |
| 134 | + |
| 135 | + with open(_path) as fp: |
| 136 | + return reader(fp, **kwargs) |
| 137 | + |
| 138 | + else: |
| 139 | + _logger.debug( |
| 140 | + 'Could not find built-in data `%s` in module `%s`.', label, module, |
| 141 | + ) |
| 142 | + |
| 143 | + |
| 144 | +def builtins(module: str | None = None) -> dict[str, pl.Path]: |
| 145 | + """List built-in data files available in a package. |
| 146 | +
|
| 147 | + Args: |
| 148 | + module: Package name. Defaults to the calling package. |
| 149 | +
|
| 150 | + Returns: |
| 151 | + Dict mapping filenames (without extension) to full paths. |
| 152 | + """ |
| 153 | + |
| 154 | + module = module or _caller_module() |
| 155 | + datadir = _module_datadir(module) |
| 156 | + |
| 157 | + if not datadir or not datadir.is_dir(): |
| 158 | + return {} |
| 159 | + |
| 160 | + return { |
| 161 | + str((pl.Path(d) / pl.Path(f).stem).relative_to(datadir)): pl.Path(d) / f |
| 162 | + for d, dirs, files in os.walk(datadir) |
| 163 | + for f in files |
| 164 | + if pl.Path(f).suffix[1:].lower() in _FORMATS |
| 165 | + } |
0 commit comments