File size: 7,306 Bytes
4cef980 |
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 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Utility functions for dealing with files"""
import os
import glob
import json
from pathlib import Path
from pkg_resources import resource_filename
import pooch
from .exceptions import ParameterError
from .decorators import deprecate_positional_args
__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
)
__GOODBOY.load_registry(
resource_filename(__name__, str(Path("example_data") / "registry.txt"))
)
with open(
resource_filename(__name__, str(Path("example_data") / "index.json")), "r"
) as fdesc:
__TRACKMAP = json.load(fdesc)
@deprecate_positional_args
def example(key, *, hq=False):
"""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("Unknown example key: {}".format(key))
if hq:
ext = ".hq.ogg"
else:
ext = ".ogg"
return __GOODBOY.fetch(__TRACKMAP[key]["path"] + ext)
ex = example
"""Alias for example"""
def list_examples():
"""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()):
print("{:10}\t{}".format(key, __TRACKMAP[key]["desc"]))
def example_info(key):
"""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("Unknown example key: {}".format(key))
license = __GOODBOY.fetch(__TRACKMAP[key]["path"] + ".txt")
with open(license, "r") as fdesc:
print("{:10s}\t{:s}".format(key, __TRACKMAP[key]["desc"]))
print("-" * 68)
for line in fdesc:
print(line)
@deprecate_positional_args
def find_files(
directory, *, ext=None, recurse=True, case_sensitive=False, limit=None, offset=0
):
"""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 = set([e.lower() for e in ext])
# Add in upper-case versions
ext |= set([e.upper() for e in ext])
files = set()
if recurse:
for walk in os.walk(directory):
files |= __get_files(walk[0], ext)
else:
files = __get_files(directory, ext)
files = list(files)
files.sort()
files = files[offset:]
if limit is not None:
files = files[:limit]
return files
def __get_files(dir_name, extensions):
"""Helper function to get 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
|