desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'All.'
def test_001_all(self):
method = 'getAll()' print 'INFO: [TEST_001] Connection test' print ('XML-RPC request: %s' % method) req = json.loads(client.getAll()) self.assertIsInstance(req, dict)
'Plugins list.'
def test_002_pluginslist(self):
method = 'getAllPlugins()' print 'INFO: [TEST_002] Get plugins list' print ('XML-RPC request: %s' % method) req = json.loads(client.getAllPlugins()) self.assertIsInstance(req, list)
'System.'
def test_003_system(self):
method = 'getSystem()' print ('INFO: [TEST_003] Method: %s' % method) req = json.loads(client.getSystem()) self.assertIsInstance(req, dict)
'CPU.'
def test_004_cpu(self):
method = 'getCpu(), getPerCpu(), getLoad() and getCore()' print ('INFO: [TEST_004] Method: %s' % method) req = json.loads(client.getCpu()) self.assertIsInstance(req, dict) req = json.loads(client.getPerCpu()) self.assertIsInstance(req, list) req = json.loads(client.getLo...
'MEM.'
def test_005_mem(self):
method = 'getMem() and getMemSwap()' print ('INFO: [TEST_005] Method: %s' % method) req = json.loads(client.getMem()) self.assertIsInstance(req, dict) req = json.loads(client.getMemSwap()) self.assertIsInstance(req, dict)
'NETWORK.'
def test_006_net(self):
method = 'getNetwork()' print ('INFO: [TEST_006] Method: %s' % method) req = json.loads(client.getNetwork()) self.assertIsInstance(req, list)
'DISK.'
def test_007_disk(self):
method = 'getFs(), getFolders() and getDiskIO()' print ('INFO: [TEST_007] Method: %s' % method) req = json.loads(client.getFs()) self.assertIsInstance(req, list) req = json.loads(client.getFolders()) self.assertIsInstance(req, list) req = json.loads(client.getDiskIO()) ...
'SENSORS.'
def test_008_sensors(self):
method = 'getSensors()' print ('INFO: [TEST_008] Method: %s' % method) req = json.loads(client.getSensors()) self.assertIsInstance(req, list)
'PROCESS.'
def test_009_process(self):
method = 'getProcessCount() and getProcessList()' print ('INFO: [TEST_009] Method: %s' % method) req = json.loads(client.getProcessCount()) self.assertIsInstance(req, dict) req = json.loads(client.getProcessList()) self.assertIsInstance(req, list)
'All limits.'
def test_010_all_limits(self):
method = 'getAllLimits()' print ('INFO: [TEST_010] Method: %s' % method) req = json.loads(client.getAllLimits()) self.assertIsInstance(req, dict) self.assertIsInstance(req['cpu'], dict)
'All views.'
def test_011_all_views(self):
method = 'getAllViews()' print ('INFO: [TEST_011] Method: %s' % method) req = json.loads(client.getAllViews()) self.assertIsInstance(req, dict) self.assertIsInstance(req['cpu'], dict)
'IRQS'
def test_012_irq(self):
method = 'getIrqs()' print ('INFO: [TEST_012] Method: %s' % method) req = json.loads(client.getIrq()) self.assertIsInstance(req, list)
'Plugin views.'
def test_013_plugin_views(self):
method = 'getViewsCpu()' print ('INFO: [TEST_013] Method: %s' % method) req = json.loads(client.getViewsCpu()) self.assertIsInstance(req, dict)
'Stop the Glances Web Server.'
def test_999_stop_server(self):
print 'INFO: [TEST_999] Stop the Glances Server' print 'Stop the Glances Server' pid.terminate() time.sleep(1) self.assertTrue(True)
'Print tag info or library data for each file referenced by args. Main entry point for the `beet info ARGS...` command. If an argument is a path pointing to an existing file, then the tags of that file are printed. All other arguments are considered queries, and for each item matching all those queries the tags from th...
def run(self, lib, opts, args):
if opts.library: data_collector = library_data else: data_collector = tag_data included_keys = [] for keys in opts.included_keys: included_keys.extend(keys.split(',')) key_filter = make_key_filter(included_keys) first = True summary = {} for data_emitter in data_c...
'Add each imported album to the collection.'
def imported(self, session, task):
if task.is_album: self.update_album_list([task.album])
'Update the MusicBrainz collection from a list of Beets albums'
def update_album_list(self, album_list):
collections = mb_call(musicbrainzngs.get_collections) if (not collections['collection-list']): raise ui.UserError(u'no collections exist for user') for collection in collections['collection-list']: if ('release-count' in collection): collection_id = collection['id'] ...
'Create the `discogs_client` field. Authenticate if necessary.'
def setup(self, session=None):
c_key = self.config['apikey'].as_str() c_secret = self.config['apisecret'].as_str() user_token = self.config['user_token'].as_str() if user_token: self.discogs_client = Client(USER_AGENT, user_token=user_token) return try: with open(self._tokenfile()) as f: tokend...
'Delete token file & redo the auth steps.'
def reset_auth(self):
os.remove(self._tokenfile()) self.setup()
'Get the path to the JSON file for storing the OAuth token.'
def _tokenfile(self):
return self.config['tokenfile'].get(confit.Filename(in_app_dir=True))
'Returns the album distance.'
def album_distance(self, items, album_info, mapping):
dist = Distance() if (album_info.data_source == 'Discogs'): dist.add('source', self.config['source_weight'].as_number()) return dist
'Returns a list of AlbumInfo objects for discogs search results matching an album and artist (if not various).'
def candidates(self, items, artist, album, va_likely):
if (not self.discogs_client): return if va_likely: query = album else: query = ('%s %s' % (artist, album)) try: return self.get_albums(query) except DiscogsAPIError as e: self._log.debug(u'API Error: {0} (query: {1})', e, query) if (e.st...
'Fetches an album by its Discogs ID and returns an AlbumInfo object or None if the album is not found.'
def album_for_id(self, album_id):
if (not self.discogs_client): return self._log.debug(u'Searching for release {0}', album_id) match = re.search('(^|\\[*r|discogs\\.com/.+/release/)(\\d+)($|\\])', album_id) if (not match): return None result = Release(self.discogs_client, {'id': int(match.group(2))}) try...
'Returns a list of AlbumInfo objects for a discogs search query.'
def get_albums(self, query):
query = re.sub('(?u)\\W+', ' ', query).encode('ascii', 'replace') query = re.sub('(?i)\\b(CD|disc)\\s*\\d+', '', query) try: releases = self.discogs_client.search(query, type='release').page(1) except CONNECTION_ERRORS: self._log.debug(u'Communication error while searching ...
'Returns an AlbumInfo object for a discogs Release object.'
def get_album_info(self, result):
if (not result.data.get('artists')): result.refresh() if (not all([result.data.get(k) for k in ['artists', 'title', 'id', 'tracklist']])): self._log.warn(u'Release does not contain the required fields') return None (artist, artist_id) = self.get_artist([a.data for a...
'Returns an artist string (all artists) and an artist_id (the main artist) for a list of discogs album or track artists.'
def get_artist(self, artists):
artist_id = None bits = [] for (i, artist) in enumerate(artists): if (not artist_id): artist_id = artist['id'] name = artist['name'] name = re.sub(' \\(\\d+\\)$', '', name) name = re.sub('(?i)^(.*?), (a|an|the)$', '\\2 \\1', name) bits.append(name...
'Returns a list of TrackInfo objects for a discogs tracklist.'
def get_tracks(self, tracklist):
try: clean_tracklist = self.coalesce_tracks(tracklist) except Exception as exc: self._log.debug(u'{}', traceback.format_exc()) self._log.error(u'uncaught exception in coalesce_tracks: {}', exc) clean_tracklist = tracklist tracks = [] index_tracks = {} inde...
'Pre-process a tracklist, merging subtracks into a single track. The title for the merged track is the one from the previous index track, if present; otherwise it is a combination of the subtracks titles.'
def coalesce_tracks(self, raw_tracklist):
def add_merged_subtracks(tracklist, subtracks): 'Modify `tracklist` in place, merging a list of `subtracks` into\n a single track into `tracklist`.' (idx, medium_idx, sub_idx) = self.get_track_index(subtracks[0]['p...
'Returns a TrackInfo object for a discogs track.'
def get_track_info(self, track, index):
title = track['title'] track_id = None (medium, medium_index, _) = self.get_track_index(track['position']) (artist, artist_id) = self.get_artist(track.get('artists', [])) length = self.get_track_length(track['duration']) return TrackInfo(title, track_id, artist, artist_id, length, index, medium,...
'Returns the medium, medium index and subtrack index for a discogs track position.'
def get_track_index(self, position):
match = re.match('^(.*?)(\\d*?)((?<=\\w)\\.[\\w]+|(?<=\\d)[A-Z]+)?$', position.upper()) if match: (medium, index, subindex) = match.groups() if (subindex and subindex.startswith('.')): subindex = subindex[1:] else: self._log.debug(u'Invalid position: {0}', position)...
'Returns the track length in seconds for a discogs duration.'
def get_track_length(self, duration):
try: length = time.strptime(duration, '%M:%S') except ValueError: return None return ((length.tm_min * 60) + length.tm_sec)
'Encode the string for inclusion in a URL'
@staticmethod def _encode(s):
if isinstance(s, six.text_type): for (char, repl) in URL_CHARACTERS.items(): s = s.replace(char, repl) s = s.encode('utf-8', 'ignore') return urllib.parse.quote(s)
'Retrieve the content at a given URL, or return None if the source is unreachable.'
def fetch_url(self, url):
try: with warnings.catch_warnings(): warnings.simplefilter('ignore') r = requests.get(url, verify=False, headers={'User-Agent': USER_AGENT}) except requests.RequestException as exc: self._log.debug(u'lyrics request failed: {0}', exc) return if (r.stat...
'Determine whether the text seems to be valid lyrics.'
def is_lyrics(self, text, artist=None):
if (not text): return False bad_triggers_occ = [] nb_lines = text.count('\n') if (nb_lines <= 1): self._log.debug(u"Ignoring too short lyrics '{0}'", text) return False elif (nb_lines < 5): bad_triggers_occ.append('too_short') else: text = remo...
'Normalize a string and remove non-alphanumeric characters.'
def slugify(self, text):
text = re.sub("[-'_\\s]", '_', text) text = re.sub('_+', '_', text).strip('_') pat = '([^,\\(]*)\\((.*?)\\)' text = re.sub(pat, '\\g<1>', text).strip() try: text = unicodedata.normalize('NFKD', text).encode('ascii', 'ignore') text = six.text_type(re.sub('[-\\s]+', ' ', text.decode...
'Return True if the URL title makes it a good candidate to be a page that contains lyrics of title by artist.'
def is_page_candidate(self, url_link, url_title, title, artist):
title = self.slugify(title.lower()) artist = self.slugify(artist.lower()) sitename = re.search(u'//([^/]+)/.*', self.slugify(url_link.lower())).group(1) url_title = self.slugify(url_title.lower()) if (url_title.find(title) != (-1)): return True tokens = (([((by + '_') + artist) for by in...
'Write the item to an ReST file This will keep state (in the `rest` variable) in order to avoid writing continuously to the same files.'
def writerest(self, directory, item):
if ((item is None) or (slug(self.artist) != slug(item.artist))): if (self.rest is not None): path = os.path.join(directory, 'artists', (slug(self.artist) + u'.rst')) with open(path, 'wb') as output: output.write(self.rest.encode('utf-8')) self.rest = None ...
'Write conf.py and index.rst files necessary for Sphinx We write minimal configurations that are necessary for Sphinx to operate. We do not overwrite existing files so that customizations are respected.'
def writerest_indexes(self, directory):
try: os.makedirs(os.path.join(directory, 'artists')) except OSError as e: if (e.errno == errno.EEXIST): pass else: raise indexfile = os.path.join(directory, 'index.rst') if (not os.path.exists(indexfile)): with open(indexfile, 'w') as output: ...
'Import hook for fetching lyrics automatically.'
def imported(self, session, task):
if self.config['auto']: for item in task.imported_items(): self.fetch_item_lyrics(session.lib, item, False, self.config['force'])
'Fetch and store lyrics for a single item. If ``write``, then the lyrics will also be written to the file itself.'
def fetch_item_lyrics(self, lib, item, write, force):
if ((not force) and item.lyrics): self._log.info(u'lyrics already present: {0}', item) return lyrics = None for (artist, titles) in search_pairs(item): lyrics = [self.get_lyrics(artist, title) for title in titles] if any(lyrics): break lyrics = u'\n\n...
'Fetch lyrics, trying each source in turn. Return a string or None if no lyrics were found.'
def get_lyrics(self, artist, title):
for backend in self.backends: lyrics = backend.fetch(artist, title) if lyrics: self._log.debug(u'got lyrics from backend: {0}', backend.__class__.__name__) return _scrape_strip_cruft(lyrics, True)
'The CLI command function for `beet play`. Create a list of paths from query, determine if tracks or albums are to be played.'
def _play_command(self, lib, opts, args):
use_folders = config['play']['use_folders'].get(bool) relative_to = config['play']['relative_to'].get() if relative_to: relative_to = util.normpath(relative_to) if opts.album: selection = lib.albums(ui.decargs(args)) paths = [] sort = lib.get_default_album_sort() ...
'Create a command string from the config command and optional args.'
def _command_str(self, args=None):
command_str = config['play']['command'].get() if (not command_str): return util.open_anything() if args: if (ARGS_MARKER in command_str): return command_str.replace(ARGS_MARKER, args) else: return u'{} {}'.format(command_str, args) else: return ...
'Return either the raw paths of items or a playlist of the items.'
def _playlist_or_paths(self, paths):
if config['play']['raw']: return paths else: return [self._create_tmp_playlist(paths)]
'Prompt user whether to abort if playlist exceeds threshold. If True, cancel playback. If False, execute play command.'
def _exceeds_threshold(self, selection, command_str, open_args, item_type='track'):
warning_threshold = config['play']['warning_threshold'].get(int) if (warning_threshold and (len(selection) > warning_threshold)): if (len(selection) > 1): item_type += 's' ui.print_(ui.colorize('text_warning', u'You are about to queue {0} {1}.'.format(len(selection)...
'Create a temporary .m3u file. Return the filename.'
def _create_tmp_playlist(self, paths_list):
m3u = NamedTemporaryFile('wb', suffix='.m3u', delete=False) for item in paths_list: m3u.write((item + '\n')) m3u.close() return m3u.name
'Append a "Play" choice to the interactive importer prompt.'
def before_choose_candidate_listener(self, session, task):
return [PromptChoice('y', 'plaY', self.importer_play)]
'Get items from current import task and send to play function.'
def importer_play(self, session, task):
selection = task.items paths = [item.path for item in selection] open_args = self._playlist_or_paths(paths) command_str = self._command_str() if (not self._exceeds_threshold(selection, command_str, open_args)): play(command_str, selection, paths, open_args, self._log, keep_open=True)
'Checks if the configured regular expressions allow the import of the file given in full_path.'
def file_filter(self, full_path):
import_config = dict(config['import']) full_path = bytestring_path(full_path) if (('singletons' not in import_config) or (not import_config['singletons'])): return (self.path_album_regex.match(full_path) is not None) else: return (self.path_singleton_regex.match(full_path) is not None)
'Setup plugin from config options'
def setup(self):
self.year_spans = build_year_spans(self.config['bucket_year'].get()) if (self.year_spans and self.config['extrapolate']): [self.ys_len_mode, self.ys_repr_mode] = extract_modes(self.year_spans) self.year_spans = extend_year_spans(self.year_spans, self.ys_len_mode) self.alpha_spans = build_alp...
'Return bucket that matches given year or return the year if no matching bucket.'
def find_bucket_year(self, year):
for ys in self.year_spans: if (ys['from'] <= int(year) <= ys['to']): if ('str' in ys): return ys['str'] else: return format_span(self.ys_repr_mode['fmt'], ys['from'], ys['to'], self.ys_repr_mode['fromnchars'], self.ys_repr_mode['tonchars']) return ...
'Return alpha-range bucket that matches given string or return the string initial if no matching bucket.'
def find_bucket_alpha(self, s):
for (i, span) in enumerate(self.alpha_spans): if span.match(s): return self.config['bucket_alpha'].get()[i] return s[0].upper()
'Moves pattern in the path format string or strips it text -- text to handle pattern -- regexp pattern (case ignore is already on) strip -- if True, pattern will be removed'
def unthe(self, text, pattern):
if text: r = re.compile(pattern, flags=re.IGNORECASE) try: t = r.findall(text)[0] except IndexError: return text else: r = re.sub(r, '', text).strip() if self.config['strip']: return r else: f...
'Check that\'s everythings ready: - local capability to resize images - thumbnail dirs exist (create them if needed) - detect whether we\'ll use PIL or IM - detect whether we\'ll use GIO or Python to get URIs'
def _check_local_ok(self):
if (not ArtResizer.shared.local): self._log.warning(u'No local image resizing capabilities, cannot generate thumbnails') return False for dir in (NORMAL_DIR, LARGE_DIR): if (not os.path.exists(dir)): os.makedirs(dir) if get_im_version(): self....
'Produce thumbnails for the album folder.'
def process_album(self, album):
self._log.debug(u'generating thumbnail for {0}', album) if (not album.artpath): self._log.info(u'album {0} has no art', album) return if self.config['dolphin']: self.make_dolphin_cover_thumbnail(album) size = ArtResizer.shared.get_size(album.artpath) if (...
'Make a thumbnail of given size for `album` and put it in `target_dir`.'
def make_cover_thumbnail(self, album, size, target_dir):
target = os.path.join(target_dir, self.thumbnail_file_name(album.path)) if (os.path.exists(target) and (os.stat(target).st_mtime > os.stat(album.artpath).st_mtime)): if self.config['force']: self._log.debug(u'found a suitable {1}x{1} thumbnail for {0}, forcing regener...
'Compute the thumbnail file name See http://standards.freedesktop.org/thumbnail-spec/latest/x227.html'
def thumbnail_file_name(self, path):
uri = self.get_uri(path) hash = md5(uri.encode('utf-8')).hexdigest() return util.bytestring_path('{0}.png'.format(hash))
'Write required metadata to the thumbnail See http://standards.freedesktop.org/thumbnail-spec/latest/x142.html'
def add_tags(self, album, image_path):
mtime = os.stat(album.artpath).st_mtime metadata = {'Thumb::URI': self.get_uri(album.artpath), 'Thumb::MTime': six.text_type(mtime)} try: self.write_metadata(image_path, metadata) except Exception: self._log.exception(u'could not write metadata to {0}', util.displayable_pa...
'Returns a list of the most played thing_types by this thing, in a tuple with the total number of pages of results. Includes an MBID, if found.'
def _get_things(self, method, thing, thing_type, params=None, cacheable=True):
doc = self._request(((self.ws_prefix + '.') + method), cacheable, params) toptracks_node = doc.getElementsByTagName('toptracks')[0] total_pages = int(toptracks_node.getAttribute('totalPages')) seq = [] for node in doc.getElementsByTagName(thing): title = _extract(node, 'name') artist...
'Returns the top tracks played by a user, in a tuple with the total number of pages of results. * period: The period of time. Possible values: o PERIOD_OVERALL o PERIOD_7DAYS o PERIOD_1MONTH o PERIOD_3MONTHS o PERIOD_6MONTHS o PERIOD_12MONTHS'
def get_top_tracks_by_page(self, period=pylast.PERIOD_OVERALL, limit=None, page=1, cacheable=True):
params = self._get_params() params['period'] = period params['page'] = page if limit: params['limit'] = limit return self._get_things('getTopTracks', 'track', pylast.Track, params, cacheable)
'Initialize the backend with the configuration view for the plugin.'
def __init__(self, config, log):
self._log = log
'Computes the track gain of the given tracks, returns a list of TrackGain objects.'
def compute_track_gain(self, items):
output = self.compute_gain(items, False) return output
'Computes the album gain of the given album, returns an AlbumGain object.'
def compute_album_gain(self, album):
supported_items = album.items() output = self.compute_gain(supported_items, True) if (not output): raise ReplayGainError(u'no output from bs1770gain') return AlbumGain(output[(-1)], output[:(-1)])
'Break an iterable into chunks of at most size `chunk_at`, generating lists for each chunk.'
def isplitter(self, items, chunk_at):
iterable = iter(items) while True: result = [] for i in range(chunk_at): try: a = next(iterable) except StopIteration: break else: result.append(a) if result: (yield result) else: ...
'Computes the track or album gain of a list of items, returns a list of TrackGain objects. When computing album gain, the last TrackGain object returned is the album gain'
def compute_gain(self, items, is_album):
if (len(items) == 0): return [] albumgaintot = 0.0 albumpeaktot = 0.0 returnchunks = [] if (len(items) > self.chunk_at): i = 0 for chunk in self.isplitter(items, self.chunk_at): i += 1 returnchunk = self.compute_chunk_gain(chunk, is_album) ...
'Compute ReplayGain values and return a list of results dictionaries as given by `parse_tool_output`.'
def compute_chunk_gain(self, items, is_album):
cmd = [self.command] cmd += [self.method] cmd += ['-p'] args = (cmd + [syspath(i.path, prefix=False) for i in items]) self._log.debug(u'executing {0}', u' '.join(map(displayable_path, args))) output = call(args) self._log.debug(u'analysis finished: {0}', output) results = sel...
'Given the output from bs1770gain, parse the text and return a list of dictionaries containing information about each analyzed file.'
def parse_tool_output(self, text, num_lines):
out = [] data = text.decode('utf-8', errors='ignore') regex = re.compile(u'(\\s{2,2}\\[\\d+\\/\\d+\\].*?|\\[ALBUM\\].*?)(?=\\s{2,2}\\[\\d+\\/\\d+\\]|\\s{2,2}\\[ALBUM\\]:|done\\.\\s)', (re.DOTALL | re.UNICODE)) results = re.findall(regex, data) for parts in results[0:num_lines]: part = parts....
'Computes the track gain of the given tracks, returns a list of TrackGain objects.'
def compute_track_gain(self, items):
supported_items = list(filter(self.format_supported, items)) output = self.compute_gain(supported_items, False) return output
'Computes the album gain of the given album, returns an AlbumGain object.'
def compute_album_gain(self, album):
supported_items = list(filter(self.format_supported, album.items())) if (len(supported_items) != len(album.items())): self._log.debug(u'tracks are of unsupported format') return AlbumGain(None, []) output = self.compute_gain(supported_items, True) return AlbumGain(output[(-1)...
'Checks whether the given item is supported by the selected tool.'
def format_supported(self, item):
if (('mp3gain' in self.command) and (item.format != 'MP3')): return False elif (('aacgain' in self.command) and (item.format not in ('MP3', 'AAC'))): return False return True
'Computes the track or album gain of a list of items, returns a list of TrackGain objects. When computing album gain, the last TrackGain object returned is the album gain'
def compute_gain(self, items, is_album):
if (len(items) == 0): self._log.debug(u'no supported tracks to analyze') return [] 'Compute ReplayGain values and return a list of results\n dictionaries as given by `parse_tool_output`.\n ...
'Given the tab-delimited output from an invocation of mp3gain or aacgain, parse the text and return a list of dictionaries containing information about each analyzed file.'
def parse_tool_output(self, text, num_lines):
out = [] for line in text.split('\n')[1:(num_lines + 1)]: parts = line.split(' DCTB ') if ((len(parts) != 6) or (parts[0] == 'File')): self._log.debug(u'bad tool output: {0}', text) raise ReplayGainError(u'mp3gain failed') d = {'file': parts[0], 'mp3ga...
'Import the necessary GObject-related modules and assign `Gst` and `GObject` fields on this object.'
def _import_gst(self):
try: import gi except ImportError: raise FatalReplayGainError(u'Failed to load GStreamer: python-gi not found') try: gi.require_version('Gst', '1.0') except ValueError as e: raise FatalReplayGainError(u'Failed to load GStreamer 1.0: {0}'.f...
'Initialize the filesrc element with the next file to be analyzed.'
def _set_file(self):
if (len(self._files) == 0): return False self._file = self._files.pop(0) self._decbin.unlink(self._conv) self._decbin.set_state(self.Gst.State.READY) self._src.set_state(self.Gst.State.READY) self._src.set_property('location', py3_path(syspath(self._file.path))) self._src.sync_state_...
'Set the next file to be analyzed while keeping the pipeline in the PAUSED state so that the rganalysis element can correctly handle album gain.'
def _set_next_file(self):
self._pipe.set_state(self.Gst.State.PAUSED) self._pipe.get_state(self.Gst.CLOCK_TIME_NONE) ret = self._set_file() if ret: self._pipe.seek_simple(self.Gst.Format.TIME, self.Gst.SeekFlags.FLUSH, 0) self._pipe.set_state(self.Gst.State.PLAYING) return ret
'Check whether it\'s possible to import the necessary modules. There is no check on the file formats at runtime. :raises :exc:`ReplayGainError`: if the modules cannot be imported'
def _import_audiotools(self):
try: import audiotools import audiotools.replaygain except ImportError: raise FatalReplayGainError(u'Failed to load audiotools: audiotools not found') self._mod_audiotools = audiotools self._mod_replaygain = audiotools.replaygain
'Open the file to read the PCM stream from the using ``item.path``. :return: the audiofile instance :rtype: :class:`audiotools.AudioFile` :raises :exc:`ReplayGainError`: if the file is not found or the file format is not supported'
def open_audio_file(self, item):
try: audiofile = self._mod_audiotools.open(item.path) except IOError: raise ReplayGainError(u'File {} was not found'.format(item.path)) except self._mod_audiotools.UnsupportedFile: raise ReplayGainError(u'Unsupported file type {}'.format(item.format)) return ...
'Return an initialized :class:`audiotools.replaygain.ReplayGain` instance, which requires the sample rate of the song(s) on which the ReplayGain values will be computed. The item is passed in case the sample rate is invalid to log the stored item sample rate. :return: initialized replagain object :rtype: :class:`audiot...
def init_replaygain(self, audiofile, item):
try: rg = self._mod_replaygain.ReplayGain(audiofile.sample_rate()) except ValueError: raise ReplayGainError(u'Unsupported sample rate {}'.format(item.samplerate)) return return rg
'Compute ReplayGain values for the requested items. :return list: list of :class:`Gain` objects'
def compute_track_gain(self, items):
return [self._compute_track_gain(item) for item in items]
'Get the gain result pair from PyAudioTools using the `ReplayGain` instance `rg` for the given `audiofile`. Wraps `rg.title_gain(audiofile.to_pcm())` and throws a `ReplayGainError` when the library fails.'
def _title_gain(self, rg, audiofile):
try: return rg.title_gain(audiofile.to_pcm()) except ValueError as exc: self._log.debug(u'error in rg.title_gain() call: {}', exc) raise ReplayGainError(u'audiotools audio data error')
'Compute ReplayGain value for the requested item. :rtype: :class:`Gain`'
def _compute_track_gain(self, item):
audiofile = self.open_audio_file(item) rg = self.init_replaygain(audiofile, item) (rg_track_gain, rg_track_peak) = self._title_gain(rg, audiofile) self._log.debug(u'ReplayGain for track {0} - {1}: {2:.2f}, {3:.2f}', item.artist, item.title, rg_track_gain, rg_track_peak) return G...
'Compute ReplayGain values for the requested album and its items. :rtype: :class:`AlbumGain`'
def compute_album_gain(self, album):
self._log.debug(u'Analysing album {0}', album) item = list(album.items())[0] audiofile = self.open_audio_file(item) rg = self.init_replaygain(audiofile, item) track_gains = [] for item in album.items(): audiofile = self.open_audio_file(item) (rg_track_gain, rg_track_peak) =...
'Checks the plugin setting to decide whether the calculation should be done using the EBU R128 standard and use R128_ tags instead.'
def should_use_r128(self, item):
return (item.format in self.r128_whitelist)
'Compute album and track replay gain store it in all of the album\'s items. If ``write`` is truthy then ``item.write()`` is called for each item. If replay gain information is already present in all items, nothing is done.'
def handle_album(self, album, write):
if (not self.album_requires_gain(album)): self._log.info(u'Skipping album {0}', album) return self._log.info(u'analyzing {0}', album) if (any([self.should_use_r128(item) for item in album.items()]) and (not all([self.should_use_r128(item) for item in album.items()]))): raise...
'Compute track replay gain and store it in the item. If ``write`` is truthy then ``item.write()`` is called to write the data to disk. If replay gain information is already present in the item, nothing is done.'
def handle_track(self, item, write):
if (not self.track_requires_gain(item)): self._log.info(u'Skipping track {0}', item) return self._log.info(u'analyzing {0}', item) if self.should_use_r128(item): if (self.r128_backend_instance == ''): self.init_r128_backend() backend_instance = self.r128_...
'Add replay gain info to items or albums of ``task``.'
def imported(self, session, task):
if task.is_album: self.handle_album(task.album, False) else: self.handle_track(task.item, False)
'Return the "replaygain" ui subcommand.'
def commands(self):
def func(lib, opts, args): write = ui.should_write() if opts.album: for album in lib.albums(ui.decargs(args)): self.handle_album(album, write) else: for item in lib.items(ui.decargs(args)): self.handle_track(item, write) cmd = ui.Su...
'Determine whether the candidate artwork is valid based on its dimensions (width and ratio). Return `CANDIDATE_BAD` if the file is unusable. Return `CANDIDATE_EXACT` if the file is usable as-is. Return `CANDIDATE_DOWNSCALE` if the file must be resized.'
def _validate(self, plugin):
if (not self.path): return self.CANDIDATE_BAD if (not (plugin.enforce_ratio or plugin.minwidth or plugin.maxwidth)): return self.CANDIDATE_EXACT if (not self.size): self.size = ArtResizer.shared.get_size(self.path) self._log.debug(u'image size: {}', self.size) if (not s...
'Like `requests.get`, but uses the logger `self._log`. See also `_logged_get`.'
def request(self, *args, **kwargs):
return _logged_get(self._log, *args, **kwargs)
'Downloads an image from a URL and checks whether it seems to actually be an image. If so, returns a path to the downloaded image. Otherwise, returns None.'
def fetch_image(self, candidate, plugin):
if plugin.maxwidth: candidate.url = ArtResizer.shared.proxy_url(plugin.maxwidth, candidate.url) try: with closing(self.request(candidate.url, stream=True, message=u'downloading image')) as resp: ct = resp.headers.get('Content-Type', None) data = resp.iter_content(chunk...
'Return the Cover Art Archive and Cover Art Archive release group URLs using album MusicBrainz release ID and release group ID.'
def get(self, album, plugin, paths):
if album.mb_albumid: (yield self._candidate(url=self.URL.format(mbid=album.mb_albumid), match=Candidate.MATCH_EXACT)) if album.mb_releasegroupid: (yield self._candidate(url=self.GROUP_URL.format(mbid=album.mb_releasegroupid), match=Candidate.MATCH_FALLBACK))
'Generate URLs using Amazon ID (ASIN) string.'
def get(self, album, plugin, paths):
if album.asin: for index in self.INDICES: (yield self._candidate(url=(self.URL % (album.asin, index)), match=Candidate.MATCH_EXACT))
'Return art URL from AlbumArt.org using album ASIN.'
def get(self, album, plugin, paths):
if (not album.asin): return try: resp = self.request(self.URL, params={'asin': album.asin}) self._log.debug(u'scraped art URL: {0}', resp.url) except requests.RequestException: self._log.debug(u'error scraping art page') return m = re.search(self...
'Return art URL from google custom search engine given an album title and interpreter.'
def get(self, album, plugin, paths):
if (not (album.albumartist and album.album)): return search_string = ((album.albumartist + ',') + album.album).encode('utf-8') response = self.request(self.URL, params={'key': self.key, 'cx': self.cx, 'q': search_string, 'searchType': 'image'}) try: data = response.json() except Valu...
'Return art URL from iTunes Store given an album title.'
def get(self, album, plugin, paths):
if (not (album.albumartist and album.album)): return search_string = ((album.albumartist + ' ') + album.album).encode('utf-8') try: try: results = itunes.search_album(search_string) except Exception as exc: self._log.debug(u'iTunes search failed: {...
'Sort order for image names. Return indexes of cover names found in the image filename. This means that images with lower-numbered and more keywords will have higher priority.'
@staticmethod def filename_priority(filename, cover_names):
return [idx for (idx, x) in enumerate(cover_names) if (x in filename)]
'Look for album art files in the specified directories.'
def get(self, album, plugin, paths):
if (not paths): return cover_names = list(map(util.bytestring_path, plugin.cover_names)) cover_names_str = '|'.join(cover_names) cover_pat = ''.join(['(\\b|_)(', cover_names_str, ')(\\b|_)']) for path in paths: if (not os.path.isdir(syspath(path))): continue image...
'Find art for the album being imported.'
def fetch_art(self, session, task):
if task.is_album: if (task.album.artpath and os.path.isfile(task.album.artpath)): return if (task.choice_flag == importer.action.ASIS): local = True elif (task.choice_flag == importer.action.APPLY): local = False else: return ca...
'Place the discovered art in the filesystem.'
def assign_art(self, session, task):
if (task in self.art_candidates): candidate = self.art_candidates.pop(task) self._set_art(task.album, candidate, (not self.src_removed)) if self.src_removed: task.prune(candidate.path)
'Given an Album object, returns a path to downloaded art for the album (or None if no art is found). If `maxwidth`, then images are resized to this maximum pixel size. If `local_only`, then only local image files from the filesystem are returned; no network requests are made.'
def art_for_album(self, album, paths, local_only=False):
out = None for source in self.sources: if (source.IS_LOCAL or (not local_only)): self._log.debug(u'trying source {0} for album {1.albumartist} - {1.album}', SOURCE_NAMES[type(source)], album) for candidate in source.get(album, self, paths): so...