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 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Utility functions for dealing with files"""
from __future__ import annotations
from typing import List, Optional, Union, Any, Set
import os
import glob
import json
import msgpack
import contextlib
import sys
from importlib import resources
import pooch
from .exceptions import ParameterError
from ..version import version as librosa_version
__all__ = [
"find_files",
"example",
"ex",
"list_examples",
"example_info",
]
# Instantiate the pooch
__data_path = os.environ.get("LIBROSA_DATA_DIR", pooch.os_cache("librosa"))
__GOODBOY = pooch.create(
__data_path, base_url="https://librosa.org/data/audio/", registry=None
)
@contextlib.contextmanager
def _resource_file(package: str, resource: str):
"""Provide a context manager for accessing resources in a package.
It acts as a shim to provide a consistent interface for accessing resources
since the 3.9 series deprecated the "path" method in favor of the "files" method.
"""
if sys.version_info < (3, 9):
with resources.path(package, resource) as path:
yield path
else:
with resources.as_file(resources.files(package).joinpath(resource)) as path:
yield path
with _resource_file("librosa.util.example_data", "registry.txt") as reg:
__GOODBOY.load_registry(str(reg))
# We want to bypass version checks here to allow asynchronous updates for new releases
__GOODBOY.registry['version_index.msgpack'] = None
with _resource_file("librosa.util.example_data", "index.json") as index:
with index.open("r") as _fdesc:
__TRACKMAP = json.load(_fdesc)
def example(key: str, *, hq: bool = False) -> str:
"""Retrieve the example recording identified by 'key'.
The first time an example is requested, it will be downloaded from
the remote repository over HTTPS.
All subsequent requests will use a locally cached copy of the recording.
For a list of examples (and their keys), see `librosa.util.list_examples`.
By default, local files will be cached in the directory given by
`pooch.os_cache('librosa')`. You can override this by setting
an environment variable ``LIBROSA_DATA_DIR`` prior to importing librosa:
>>> import os
>>> os.environ['LIBROSA_DATA_DIR'] = '/path/to/store/data'
>>> import librosa
Parameters
----------
key : str
The identifier for the track to load
hq : bool
If ``True``, return the high-quality version of the recording.
If ``False``, return the 22KHz mono version of the recording.
Returns
-------
path : str
The path to the requested example file
Examples
--------
Load "Hungarian Dance #5" by Johannes Brahms
>>> y, sr = librosa.load(librosa.example('brahms'))
Load "Vibe Ace" by Kevin MacLeod (the example previously packaged with librosa)
in high-quality mode
>>> y, sr = librosa.load(librosa.example('vibeace', hq=True))
See Also
--------
librosa.util.list_examples
pooch.os_cache
"""
if key not in __TRACKMAP:
raise ParameterError(f"Unknown example key: {key}")
if hq:
ext = ".hq.ogg"
else:
ext = ".ogg"
return str(__GOODBOY.fetch(__TRACKMAP[key]["path"] + ext))
ex = example
"""Alias for example"""
def list_examples() -> None:
"""List the available audio recordings included with librosa.
Each recording is given a unique identifier (e.g., "brahms" or "nutcracker"),
listed in the first column of the output.
A brief description is provided in the second column.
See Also
--------
util.example
util.example_info
"""
print("AVAILABLE EXAMPLES")
print("-" * 68)
for key in sorted(__TRACKMAP.keys()):
if key == "pibble":
# Shh... she's sleeping
continue
print(f"{key:10}\t{__TRACKMAP[key]['desc']}")
def example_info(key: str) -> None:
"""Display licensing and metadata information for the given example recording.
The first time an example is requested, it will be downloaded from
the remote repository over HTTPS.
All subsequent requests will use a locally cached copy of the recording.
For a list of examples (and their keys), see `librosa.util.list_examples`.
By default, local files will be cached in the directory given by
`pooch.os_cache('librosa')`. You can override this by setting
an environment variable ``LIBROSA_DATA_DIR`` prior to importing librosa.
Parameters
----------
key : str
The identifier for the recording (see `list_examples`)
See Also
--------
librosa.util.example
librosa.util.list_examples
pooch.os_cache
"""
if key not in __TRACKMAP:
raise ParameterError(f"Unknown example key: {key}")
license_file = __GOODBOY.fetch(__TRACKMAP[key]["path"] + ".txt")
with open(license_file, "r") as fdesc:
print(f"{key:10s}\t{__TRACKMAP[key]['desc']:s}")
print("-" * 68)
for line in fdesc:
print(line)
def find_files(
directory: Union[str, os.PathLike[Any]],
*,
ext: Optional[Union[str, List[str]]] = None,
recurse: bool = True,
case_sensitive: bool = False,
limit: Optional[int] = None,
offset: int = 0,
) -> List[str]:
"""Get a sorted list of (audio) files in a directory or directory sub-tree.
Examples
--------
>>> # Get all audio files in a directory sub-tree
>>> files = librosa.util.find_files('~/Music')
>>> # Look only within a specific directory, not the sub-tree
>>> files = librosa.util.find_files('~/Music', recurse=False)
>>> # Only look for mp3 files
>>> files = librosa.util.find_files('~/Music', ext='mp3')
>>> # Or just mp3 and ogg
>>> files = librosa.util.find_files('~/Music', ext=['mp3', 'ogg'])
>>> # Only get the first 10 files
>>> files = librosa.util.find_files('~/Music', limit=10)
>>> # Or last 10 files
>>> files = librosa.util.find_files('~/Music', offset=-10)
>>> # Avoid including search patterns in the path string
>>> import glob
>>> directory = '~/[202206] Music'
>>> directory = glob.escape(directory) # Escape the special characters
>>> files = librosa.util.find_files(directory)
Parameters
----------
directory : str
Path to look for files
ext : str or list of str
A file extension or list of file extensions to include in the search.
Default: ``['aac', 'au', 'flac', 'm4a', 'mp3', 'ogg', 'wav']``
recurse : boolean
If ``True``, then all subfolders of ``directory`` will be searched.
Otherwise, only ``directory`` will be searched.
case_sensitive : boolean
If ``False``, files matching upper-case version of
extensions will be included.
limit : int > 0 or None
Return at most ``limit`` files. If ``None``, all files are returned.
offset : int
Return files starting at ``offset`` within the list.
Use negative values to offset from the end of the list.
Returns
-------
files : list of str
The list of audio files.
"""
if ext is None:
ext = ["aac", "au", "flac", "m4a", "mp3", "ogg", "wav"]
elif isinstance(ext, str):
ext = [ext]
# Cast into a set
ext = set(ext)
# Generate upper-case versions
if not case_sensitive:
# Force to lower-case
ext = {e.lower() for e in ext}
# Add in upper-case versions
ext |= {e.upper() for e in ext}
fileset = set()
if recurse:
for walk in os.walk(directory): # type: ignore
fileset |= __get_files(walk[0], ext)
else:
fileset = __get_files(directory, ext)
files = list(fileset)
files.sort()
files = files[offset:]
if limit is not None:
files = files[:limit]
return files
def __get_files(dir_name: Union[str, os.PathLike[Any]], extensions: Set[str]):
"""Get a list of files in a single directory"""
# Expand out the directory
dir_name = os.path.abspath(os.path.expanduser(dir_name))
myfiles = set()
for sub_ext in extensions:
globstr = os.path.join(dir_name, "*" + os.path.extsep + sub_ext)
myfiles |= set(glob.glob(globstr))
return myfiles
def cite(version: Optional[str]=None) -> str:
"""Print the citation information for librosa.
Parameters
----------
version : str or None
The version of librosa to cite. If None, the current version is used.
Returns
-------
doi : str
The DOI for the given version of librosa.
Raises
------
ParameterError
If the requested version is not found in the citation index.
Examples
--------
>>> librosa.cite("0.10.1")
"https://doi.org/10.5281/zenodo.8252662"
"""
if version is None:
version = librosa_version
version_data = __GOODBOY.fetch("version_index.msgpack")
with open(version_data, "rb") as fdesc:
version_index = msgpack.load(fdesc)
if version not in version_index:
if "dev" in version:
raise ParameterError(f"Version {version} is not yet released and therefore does not yet have a citable DOI.")
else:
raise ParameterError(f"Version {version} not found in the citation index")
return f"https://doi.org/{version_index[version]}"
|