def commands(self): gupload = Subcommand('gmusic-upload', help=u'upload your tracks to Google Play Music') gupload.func = self.upload search = Subcommand('gmusic-songs', help=u'list of songs in Google Play Music library') search.parser.add_option('-t', '--track', dest='track', action='store_true', help='Search by track name') search.parser.add_option('-a', '--artist', dest='artist', action='store_true', help='Search by artist') search.func = self.search return [gupload, search]
def commands(self): play_command = Subcommand("play", help="send music to a player as a playlist") play_command.parser.add_option( "-a", "--album", action="store_true", default=False, help="query and load albums rather than tracks" ) play_command.func = play_music return [play_command]
def commands(self): lyrics_cmd = Subcommand('lyrics', help='fetch lyrics') lyrics_cmd.func = self.lyrics_func lyrics_cmd.parser.add_option('-f', '--force', action='store_true', default=None, help='overwrite tag updates') lyrics_cmd.parser.add_option('-p', '--processes', dest='processes', help='number of concurrent threads to run') return [lyrics_cmd]
def commands(self): play_command = Subcommand('play', help='send query results to music player as playlist.') play_command.parser.add_option('-a', '--album', action='store_true', default=False, help='query and load albums(folders) rather then tracks.') play_command.func = play_music return [play_command]
def commands(self): play_command = Subcommand( 'play', help='send music to a player as a playlist' ) play_command.parser.add_album_option() play_command.func = self.play_music return [play_command]
def commands(self): mbupdate = Subcommand('mbupdate', help=u'Update MusicBrainz collection') mbupdate.parser.add_option('-r', '--remove', action='store_true', default=None, dest='remove', help='Remove albums not in beets library') mbupdate.func = self.update_collection return [mbupdate]
def commands(self): bad_command = Subcommand('bad', help=u'check for corrupt or missing files') bad_command.parser.add_option( u'-v', u'--verbose', action='store_true', default=False, dest='verbose', help=u'view results for both the bad and uncorrupted files' ) bad_command.func = self.command return [bad_command]
def commands(self): zero_command = Subcommand('zero', help='set fields to null') def zero_fields(lib, opts, args): if not decargs(args) and not input_yn( u"Remove fields for all items? (Y/n)", True): return for item in lib.items(decargs(args)): self.process_item(item) zero_command.func = zero_fields return [zero_command]
def commands(self): play_command = Subcommand('play', help='send music to a player as a playlist') play_command.parser.add_album_option() play_command.parser.add_option( '-A', '--args', action='store', help='add additional arguments to the command', ) play_command.func = self.play_music return [play_command]
def commands(self): play_command = Subcommand( 'play', help='send music to a player as a playlist' ) play_command.parser.add_option( '-a', '--album', action='store_true', default=False, help='query and load albums rather than tracks' ) play_command.func = partial(play_music, log=self._log) return [play_command]
def commands(self): play_command = Subcommand( 'play', help='send music to a player as a playlist' ) play_command.parser.add_option( '-a', '--album', action='store_true', default=False, help='query and load albums rather than tracks' ) play_command.func = play_music return [play_command]
def commands(self): cmds = Subcommand('wlg', help='get genres with whatlastgenre') cmds.parser.add_option( '-v', '--verbose', dest='verbose', action='count', default=0, help='verbose output (-vv for debug)') cmds.parser.add_option( '-f', '--force', dest='force', action='store_true', default=False, help='force overwrite existing genres') cmds.parser.add_option( '-u', '--update-cache', dest='cache', action='store_true', default=False, help='force update cache') cmds.func = self.commanded return [cmds]
def commands(self): thumbnails_command = Subcommand("thumbnails", help="Create album thumbnails") thumbnails_command.parser.add_option( '-f', '--force', dest='force', action='store_true', default=False, help='force regeneration of thumbnails deemed fine (existing & ' 'recent enough)') thumbnails_command.parser.add_option( '--dolphin', dest='dolphin', action='store_true', default=False, help="create Dolphin-compatible thumbnail information (for KDE)") thumbnails_command.func = self.process_query return [thumbnails_command]
def commands(self): play_command = Subcommand( 'play', help=u'send music to a player as a playlist' ) play_command.parser.add_album_option() play_command.parser.add_option( u'-A', u'--args', action='store', help=u'add additional arguments to the command', ) play_command.func = self.play_music return [play_command]
def commands(self): thumbnails_command = Subcommand("thumbnails", help=u"Create album thumbnails") thumbnails_command.parser.add_option( u'-f', u'--force', dest='force', action='store_true', default=False, help=u'force regeneration of thumbnails deemed fine (existing & ' u'recent enough)') thumbnails_command.parser.add_option( u'--dolphin', dest='dolphin', action='store_true', default=False, help=u"create Dolphin-compatible thumbnail information (for KDE)") thumbnails_command.func = self.process_query return [thumbnails_command]
def commands(self): tag_copy_command = Subcommand( 'tagcopy', help='copy the contents of one tag to another', aliases=['tc']) def copy_tags(lib, opts, args): items = list(lib.items(decargs(args))) for item in items: item = self.process_item(item) item.store() item.write() tag_copy_command.func = copy_tags return [tag_copy_command]
def commands(self): play_command = Subcommand('play', help=u'send music to a player as a playlist') play_command.parser.add_album_option() play_command.parser.add_option( u'-A', u'--args', action='store', help=u'add additional arguments to the command', ) play_command.parser.add_option( u'-y', u'--yes', action="store_true", help=u'skip the warning threshold', ) play_command.func = self._play_command return [play_command]
def commands(self): play_command = Subcommand( 'play', help=u'send music to a player as a playlist' ) play_command.parser.add_album_option() play_command.parser.add_option( u'-A', u'--args', action='store', help=u'add additional arguments to the command', ) play_command.parser.add_option( u'-y', u'--yes', action="store_true", help=u'skip the warning threshold', ) play_command.func = self._play_command return [play_command]
def commands(self): def build_playlist(lib, opts, args): self.config.set_args(opts) ids = self.config['playlist_ids'].as_str_seq() if self.config['playlist_names'].as_str_seq(): playlists = ElementTree.fromstring( self.send('getPlaylists').text)[0] if playlists.attrib.get('code', '200') != '200': alt_error = 'error getting playlists,' \ ' but no error message found' self._log.warn( playlists.attrib.get('message', alt_error)) return for name in self.config['playlist_names'].as_str_seq(): for playlist in playlists: if name == playlist.attrib['name']: ids.append(playlist.attrib['id']) playlist_dict = self.get_playlists(ids) # delete old tags if self.config['delete']: existing = list(lib.items('subsonic_playlist:";"')) to_be_removed = filter_to_be_removed( existing, playlist_dict.keys()) for item in to_be_removed: item['subsonic_playlist'] = '' with lib.transaction(): item.try_sync(write=True, move=False) self.update_tags(playlist_dict, lib) subsonicplaylist_cmds = Subcommand( 'subsonicplaylist', help=u'import a subsonic playlist' ) subsonicplaylist_cmds.parser.add_option( u'-d', u'--delete', action='store_true', help=u'delete tag from items not in any playlist anymore', ) subsonicplaylist_cmds.func = build_playlist return [subsonicplaylist_cmds]
def commands(self): thumbnails_command = Subcommand("thumbnails", help=u"Create album thumbnails") thumbnails_command.parser.add_option( u"-f", u"--force", dest="force", action="store_true", default=False, help=u"force regeneration of thumbnails deemed fine (existing & " u"recent enough)", ) thumbnails_command.parser.add_option( u"--dolphin", dest="dolphin", action="store_true", default=False, help=u"create Dolphin-compatible thumbnail information (for KDE)", ) thumbnails_command.func = self.process_query return [thumbnails_command]
def commands(self): def print_unimported(lib, opts, args): ignore_exts = [ ('.' + x).encode() for x in self.config['ignore_extensions'].as_str_seq() ] in_folder = set( (os.path.join(r, file) for r, d, f in os.walk(lib.directory) for file in f if not any( [file.endswith(extension) for extension in ignore_exts]))) in_library = set(x.path for x in lib.items()) art_files = set(x.artpath for x in lib.albums()) for f in in_folder - in_library - art_files: print_(util.displayable_path(f)) unimported = Subcommand( 'unimported', help='list all files in the library folder which are not listed' ' in the beets library database') unimported.func = print_unimported return [unimported]
def commands(self): """Add the alias commands.""" if self.config['from_path'].get(bool): commands = dict(self.get_path_commands()) else: commands = {} for alias in self.config['aliases'].keys(): if alias in commands: raise confuse.ConfigError( u'alias.aliases.{0} was specified multiple times'.format( alias)) command = self.config['aliases'][alias].get() if isinstance(command, six.text_type): commands[alias] = self.get_command(alias, command) elif isinstance(command, abc.Mapping): command_text = command.get('command') if not command_text: raise confuse.ConfigError( u'alias.aliases.{0}.command not found'.format(alias)) help_text = command.get('help', command_text) commands[alias] = self.get_command(alias, command_text, help_text) else: raise confuse.ConfigError( u'alias.aliases.{0} must be a string or single-element mapping' .format(alias)) if 'alias' in commands: raise ui.UserError( u'alias `alias` is reserved for the alias plugin') alias = Subcommand('alias', help=u'Print the available alias commands.') alias_commands = dict((a, c.command) for a, c in commands.items()) alias.func = lambda lib, opts, args: self.cmd_alias( lib, opts, args, alias_commands) commands['alias'] = alias return commands.values()
def commands(self): def init_server(lib, opts, args): model = BeetsModel(lib) if opts.username is None: raise KeyError('Username is required') if opts.password is None: raise KeyError('Password is required') # Get all the args and opts into one variable configs = { u'host': self.config['host'].as_str(), u'port': self.config['port'].get(int), u'cors': self.config['cors'].as_str(), u'playlist_dir': self.config['playlist_dir'].as_filename(), u'debug': opts.debug, u'username': opts.username, u'password': opts.password, u'ignoredArticles': self.config['ignoredArticles'].as_str(), } app = SubsonicServer(model, configs, __name__) app.run( host=configs[u'host'], port=configs[u'port'], debug=configs[u'debug'], ) cmd = Subcommand('sonic', help='Run Subsonic server interface for beets') cmd.parser.add_option(u'-u', u'--username', action='store', help=u'username') cmd.parser.add_option(u'-p', u'--password', action='store', help=u'password') cmd.parser.add_option(u'-d', u'--debug', action='store_true', default=False, help=u'debug mode') cmd.func = init_server return [cmd]
def commands(self): freedesktop_command = Subcommand("freedesktop", help="Create .directory files") freedesktop_command.func = self.process_query return [freedesktop_command]
item.genre = genre lib.store(item) item.write() for album in lib.albums(): genre = get_genre(album.albumartist, genres) if (genre is None) and (fallback_str is not None): genre = fallback_str log.warn(u'no genre for %s in list: fallback to %s' % (album.albumartist, genre)) if genre is not None: log.warn(u'adding genre for %s from list: %s' % (album.albumartist, genre)) bluo='' album.genre = genre for item in album.items(): item.write() update_cmd.func=update_genres class GenreListPlugin(plugins.BeetsPlugin): def __init__(self): super(GenreListPlugin, self).__init__() self.import_stages = [self.imported] def commands(self): return [update_cmd] def configure(self, config): global fallback_str global genres gl_filename = ui.config_val(config, 'genrelist', 'listfile', None) # Read the genres tree for canonicalization if enabled.
def commands(self): """ Commands for generating and importing features """ def get_mfcc(song): # Deferred import (librosa was messing up general beet output) import librosa y, sr = librosa.load(song.encode(sys.getfilesystemencoding())) mfcc = librosa.feature.mfcc(y=y, sr=sr, n_mfcc=20) return block_reduce(mfcc, (1, 100), np.mean) # Generate sequential features features_cmd = Subcommand( "features", help="Generate sequential acoustic features [blackbird]") def features_func(lib, opts, args): filtered_items = lib.items(decargs(args)) if len(filtered_items) == 0: print("Query didn't match any item") return seq_features_file = config["blackbird"]["features"].get("unicode") seq_features = cPickle.load(open(seq_features_file, "rb")) print("Finding features...") bar = pyprind.ProgBar(len(filtered_items)) for item in filtered_items: if item.id not in features: try: data = get_mfcc(item.path) seq_features[item.id] = data except Exception as e: print(e) bar.update() print("Saving data...") cPickle.dump(seq_features, open(seq_features_file, "wb"), protocol=cPickle.HIGHEST_PROTOCOL) # Import features as coordinates coords_cmd = Subcommand( "coords", help= "Generate coordinates based on calculated features [blackbird]") coords_cmd.parser.add_option( "-t", "--type", help="Type of vectorization [mean (default), lstm]") def coords_func(lib, opts, args): if opts.type: seq_features_file = config["blackbird"]["features"].get( "unicode") seq_features = cPickle.load(open(seq_features_file, "rb")) keys = seq_features.keys() if opts.type == "mean": features = np.empty((len(seq_features), 20)) for idx, key in enumerate(seq_features): length = seq_features[key].shape[1] features[idx, :] = seq_features[key][:, int( 0.1 * length):int(0.9 * length)].mean(axis=1) elif opts.type == "lstm": print("Loading network...") model = LSTMSeq2Seq( config["blackbird"]["model"]["arch"].get("unicode"), config["blackbird"]["model"]["weights"].get("unicode"), config["blackbird"]["model"]["output"].get()) # Pad sequences maxlen = 150 padded_seq_features = np.empty((len(seq_features), maxlen, 20)) for idx, key in enumerate(seq_features): padded_seq_features[ idx, :, :] = sequence.pad_sequences( seq_features[key], maxlen=maxlen, dtype="float32").T print("Getting vectors...") features = model.predict([padded_seq_features, 0]) else: print("Provide a valid --type [mean, lstm]") sys.exit(1) print("Reducing dimensions...") features_2d = TSNE(n_components=2).fit_transform(features) print("Writing to db...") conn = sqlite3.connect(config["blackbird"]["db"].get( "unicode")) cur = conn.cursor() cur.execute("DELETE FROM coords") to_insert = [] for idx in xrange(features_2d.shape[0]): to_insert.append((keys[idx], features_2d[idx, 0], features_2d[idx, 1])) cur.executemany("INSERT INTO coords VALUES (?, ?, ?)", to_insert) conn.commit() conn.close() # Fill leftovers ids_to_fill = [] for item in lib.items(): if item.id not in keys: ids_to_fill.append(item.id) self.fill(ids_to_fill, features_2d.min(axis=0), features_2d.max(axis=0)) else: print("Provide a valid --type [mean, lstm]") coords_cmd.func = coords_func features_cmd.func = features_func return [features_cmd, coords_cmd]
print_obj(item, lib, config, template) if opts.verbose: print(is_match(queryMatcher, i, album=opts.album, verbose=True)[1]) fuzzy_cmd = Subcommand('fuzzy', help='list items using fuzzy matching') fuzzy_cmd.parser.add_option('-a', '--album', action='store_true', help='choose an album instead of track') fuzzy_cmd.parser.add_option('-p', '--path', action='store_true', help='print the path of the matched item') fuzzy_cmd.parser.add_option('-f', '--format', action='store', help='print with custom format', default=None) fuzzy_cmd.parser.add_option('-v', '--verbose', action='store_true', help='output scores for matches') fuzzy_cmd.parser.add_option('-t', '--threshold', action='store', help='return result with a fuzzy score above threshold. \ (default is 0.7)', default=None) fuzzy_cmd.func = fuzzy_list conf = {} class Fuzzy(BeetsPlugin): def commands(self): return [fuzzy_cmd] def configure(self, config): conf['threshold'] = beets.ui.config_val(config, 'fuzzy', 'threshold', 0.7)
items = lib.items(query) stats = parse_stats(stats) sort_stat = list(stats.keys())[0] for stat in stats.values(): set_str_converter(stat, type(getattr(items[0], stat["field"]))) groups = group_by(category, items) stat_dct = {} for g, items in groups.items(): stat_dct[g] = {} for nm, stat in stats.items(): stat_dct[g][nm] = get_items_stat(items, stat) print_results(stat_dct, category, sort_stat, reverse) def summarize(lib, opts, args): show_summary(lib, decargs(args), opts.group_by, opts.stats, not opts.not_reverse) summarize_command.func = summarize class SuperPlug(BeetsPlugin): def commands(self): return [summarize_command]
objs = [] for artist, count in selected_artists.items(): objs_from_artist = objs_by_artists[artist] number = min(count, len(objs_from_artist)) objs.extend(random.sample(objs_from_artist, number)) else: number = min(len(objs), opts.number) objs = random.sample(objs, number) for item in objs: print_obj(item, lib, template) random_cmd = Subcommand('random', help='chose a random track or album') random_cmd.parser.add_option('-a', '--album', action='store_true', help='choose an album instead of track') random_cmd.parser.add_option('-p', '--path', action='store_true', help='print the path of the matched item') random_cmd.parser.add_option('-f', '--format', action='store', help='print with custom format', default=None) random_cmd.parser.add_option('-n', '--number', action='store', type="int", help='number of objects to choose', default=1) random_cmd.parser.add_option('-e', '--equal-chance', action='store_true', help='each artist has the same chance') random_cmd.func = random_item class Random(BeetsPlugin): def commands(self): return [random_cmd]
def commands(self): freedesktop_command = Subcommand("freedesktop", help="Create .directory files") freedesktop_command.func = process_query return [freedesktop_command]
# do the actual add directory_structure.addfile(sub_elements, level_subbed[structure_depth-1], item.id) server = beetFileSystem(version="%prog " + fuse.__version__, usage="", dash_s_do='setsingle') server.parse(errex=1) server.multithreaded = 0 try: server.main() pass except fuse.FuseError, e: log.error(str(e)) beetFs_command.func = mount class beetFs(BeetsPlugin): """ The beets plugin hook """ def commands(self): return [beetFs_command] import mutagen from mutagen import flac from mutagen.flac import FLAC, Padding, MetadataBlock def to_int_be(string): """Convert an arbitrarily-long string to a long using big-endian byte order.""" return reduce(lambda a, b: (a << 8) + ord(b), string, 0L)
def commands(self): cmd = Subcommand('lastimport', help=u'list last imported items') cmd.parser.add_path_option() cmd.func = list_items return [cmd]
lslimit_cmd = Subcommand("lslimit", help="query with optional head or tail") lslimit_cmd.parser.add_option("--head", action="store", type="int", default=None) lslimit_cmd.parser.add_option("--tail", action="store", type="int", default=None) lslimit_cmd.parser.add_all_common_options() lslimit_cmd.func = lslimit class LimitPlugin(BeetsPlugin): """Query limit functionality via command and query prefix.""" def commands(self): """Expose `lslimit` subcommand.""" return [lslimit_cmd] def queries(self): class HeadQuery(FieldQuery): """This inner class pattern allows the query to track state.""" n = 0 N = None @classmethod
def make_command(name, func, **kwargs): c = Subcommand(name, **kwargs) c.func = func return c
subprocess.call(cmd + cmd_args + [item.path]) if opts.stop: subprocess.call(cmd + ['--stop']) elif opts.play: subprocess.call(cmd + ['--play']) elif opts.pause: subprocess.call(cmd + ['--pause']) if opts.next: subprocess.call(cmd + ['--next']) elif opts.prev: subprocess.call(cmd + ['--prev']) if opts.repeat: subprocess.call(cmd + ['--repeat']) if opts.shuffle: subprocess.call(cmd + ['--shuffle']) if opts.status: subprocess.call(cmd + ['--status']) cmus_cmd.func = cmus_remote class CmusRemote(BeetsPlugin): def commands(self): return [cmus_cmd]
objs = random_objs(objs, opts.album, opts.number, opts.time, opts.equal_chance) for obj in objs: print_(format(obj)) random_cmd = Subcommand('random', help='choose a random track or album') random_cmd.parser.add_option('-n', '--number', action='store', type="int", help='number of objects to choose', default=1) random_cmd.parser.add_option('-e', '--equal-chance', action='store_true', help='each artist has the same chance') random_cmd.parser.add_option( '-t', '--time', action='store', type="float", help='total length in minutes of objects to choose') random_cmd.parser.add_all_common_options() random_cmd.func = random_func class Random(BeetsPlugin): def commands(self): return [random_cmd]
# found duplicates if opts["output_count"]: print_obj(match_list[0], lib, fmt=fmt.format(num)) else: for match in match_list: print_obj(match, lib, fmt=fmt.format(num)) print "" ####################### # Command Declaration # ####################### find_command = Subcommand( 'find_duplicates', help = 'Lists all duplicates for given query', aliases = ["fdup"] ) find_command.func = dupl_finder gen_parser(find_command) ##################### # Plugin Definition # ##################### class ExtendedDuplicateFinder(BeetsPlugin): def commands(self): return [find_command]
def commands(self): bad_command = Subcommand('bad', help='check for corrupt or missing files') bad_command.func = self.check_bad return [bad_command]
def commands(self): cmds = Subcommand('sync') cmds.func = self.sync return [cmds]
def commands(self): play_command = Subcommand("play", help="send music to a player as a playlist") play_command.parser.add_album_option() play_command.parser.add_option("-A", "--args", action="store", help="add additional arguments to the command") play_command.func = self.play_music return [play_command]
if opts.verbose: print(is_match(queryMatcher, item, album=opts.album, verbose=True)[1]) fuzzy_cmd = Subcommand('fuzzy', help='list items using fuzzy matching') fuzzy_cmd.parser.add_option('-a', '--album', action='store_true', help='choose an album instead of track') fuzzy_cmd.parser.add_option('-p', '--path', action='store_true', help='print the path of the matched item') fuzzy_cmd.parser.add_option('-f', '--format', action='store', help='print with custom format', default=None) fuzzy_cmd.parser.add_option('-v', '--verbose', action='store_true', help='output scores for matches') fuzzy_cmd.parser.add_option('-t', '--threshold', action='store', help='return result with a fuzzy score above threshold. \ (default is 0.7)', default=None) fuzzy_cmd.func = fuzzy_list class Fuzzy(BeetsPlugin): def __init__(self): super(Fuzzy, self).__init__() self.config.add({ 'threshold': 0.7, }) def commands(self): return [fuzzy_cmd]
def commands(self): mbupdate = Subcommand('mbupdate', help='Update MusicBrainz collection') mbupdate.func = self.update_collection return [mbupdate]
sys.exit() if duo[0] not in ITEM_TAGS: print("ERROR:", duo[0], "is not a valid tag value!") print("Run 'beet fields' to see all valid tag values!") keys[duo[0]] = duo[1] item = lib.items(query=keys['title']) if keys['id'] != None: item = lib.get_item(keys['id']) print("\n\nPrevious File Info:\n") for k, v in item.items(): if k in keys: print(k, ":", v) print("\n\nNew File Info:\n") for k, v in keys.items(): item.set_parse(k, v) print(k, ":", v) st = input("\n\nDo you want to save these new tags? [Y/n] ") if st == 'Y' or st == 'y': item.store() print("Saved!") import_txt.func = txt_in class TagImport(BeetsPlugin): def commands(self): return [import_txt]
for item in lib.items( args ): subprocess.call(cmd + cmd_args + [item.path]) if opts.stop: subprocess.call(cmd + ['--stop']) elif opts.play: subprocess.call(cmd + ['--play']) elif opts.pause: subprocess.call(cmd + ['--pause']) if opts.next: subprocess.call(cmd + ['--next']) elif opts.prev: subprocess.call(cmd + ['--prev']) if opts.repeat: subprocess.call(cmd + ['--repeat']) if opts.shuffle: subprocess.call(cmd + ['--shuffle']) if opts.status: subprocess.call(cmd + ['--status']) cmus_cmd.func = cmus_remote class CmusRemote(BeetsPlugin): def commands(self): return [cmus_cmd]
objs.append(objs_from_artist.pop(i)) # Remove the artist if we've used up all of its objects. if not objs_from_artist: del objs_by_artists[artist] else: number = min(len(objs), opts.number) objs = random.sample(objs, number) for item in objs: print_obj(item, lib, template) random_cmd = Subcommand('random', help='chose a random track or album') random_cmd.parser.add_option('-a', '--album', action='store_true', help='choose an album instead of track') random_cmd.parser.add_option('-p', '--path', action='store_true', help='print the path of the matched item') random_cmd.parser.add_option('-f', '--format', action='store', help='print with custom format', default=None) random_cmd.parser.add_option('-n', '--number', action='store', type="int", help='number of objects to choose', default=1) random_cmd.parser.add_option('-e', '--equal-chance', action='store_true', help='each artist has the same chance') random_cmd.func = random_item class Random(BeetsPlugin): def commands(self): return [random_cmd]
]): # this list is almost certainly incomplete non_lossless += 1 continue bit_depth = item.bitdepth sample_rate = round(float(item["samplerate"]) / 1000, 1) key = f"{sample_rate}kHz/{bit_depth} bit" try: info[key] += 1 except KeyError: info[key] = 1 if len(items) == 0: return if non_lossless != 0: print( f"{non_lossless} items are not lossless ({(non_lossless / len(items)) * 100:.2f}%)." ) for key, count in sorted(info.items(), key=lambda item: item[1])[::-1]: print(f"{count} items are {key} ({(count / len(items)) * 100:.2f}%)") fileinfo_cmd.func = base class FileInfo(BeetsPlugin): def __init__(self, name=None): self.early_import_stages = [] self.import_stages = [] def commands(self): return [fileinfo_cmd]
import urllib import urllib2 def sendAlbums(username, password, albumIds): url = 'http://musicbrainz.org/ws/1/collection/' #Where to send them data = urllib.urlencode({ 'add': ",".join(albumIds) }) #Post it pm = urllib2.HTTPPasswordMgrWithDefaultRealm() pm.add_password(None, url, username, password) urllib2.install_opener(urllib2.build_opener( urllib2.HTTPDigestAuthHandler(pm))) resp = urllib2.urlopen(url, data).read() return resp update_mb_collection = Subcommand('mbupdate', help='Update MusicBrainz collection') def updateCollection(lib, config, opts, args): username = beets.ui.config_val(config, 'musicbrainz', 'user', '') password = beets.ui.config_val(config, 'musicbrainz', 'pass', '') #Get a list of all the albums albums = map(lambda a: a.mb_albumid, lib.albums()) print 'Updating MusicBrainz collection...' sendAlbums(username, password, albums) print '...MusicBrainz collection updated' update_mb_collection.func = updateCollection class MusicbrainzCollection(BeetsPlugin): def commands(self): return [update_mb_collection]
else: log.info(u'skipping invalid MBID: {0}', aid) # Submit to MusicBrainz. print('Updating MusicBrainz collection {0}...'.format(collection_id)) submit_albums(collection_id, album_ids) print('...MusicBrainz collection updated.') def update_collection(lib, opts, args): update_album_list(lib.albums()) update_mb_collection_cmd = Subcommand('mbupdate', help='Update MusicBrainz collection') update_mb_collection_cmd.func = update_collection class MusicBrainzCollectionPlugin(BeetsPlugin): def __init__(self): super(MusicBrainzCollectionPlugin, self).__init__() musicbrainzngs.auth( config['musicbrainz']['user'].get(unicode), config['musicbrainz']['pass'].get(unicode), ) self.config.add({'auto': False}) if self.config['auto']: self.import_stages = [self.imported] def commands(self): return [update_mb_collection_cmd]
def commands(self): play_command = Subcommand('play', help='send music to a player as a playlist') play_command.parser.add_album_option() play_command.func = self.play_music return [play_command]
sub_elements.append(level_subbed[structure_depth - 2]) # do the actual add directory_structure.addfile(sub_elements, level_subbed[structure_depth - 1], item.id) server = beetFileSystem(version="%prog " + fuse.__version__, usage="", dash_s_do="setsingle") server.parse(errex=1) server.multithreaded = 0 try: server.main() except fuse.FuseError, e: log.error(str(e)) beetFs_command.func = mount class beetFs(BeetsPlugin): """ The beets plugin hook.""" def commands(self): return [beetFs_command] def to_int_be(string): """Convert an arbitrarily-long string to a long using big-endian byte order.""" return reduce(lambda a, b: (a << 8) + ord(b), string, 0L)
usertags = [] else: usertags = usertags.split('|') # usertags.append(' '.join(newtags)) usertags.extend(newtags) usertags = list(set(usertags)) if '' in usertags: usertags.pop(usertags.index('')) item.update({'usertags': '|'.join(usertags)}) item.store() print('Added tags\n {}'.format(item)) add_tag_command = Subcommand( 'addtag', help='Add user defined tags.', aliases=('adt',)) add_tag_command.func = add_usertag add_tag_command.parser.add_option( '--tag', '-t', action='append', dest='tags', help='Tag to add. ' 'Combine multiple tags by specifiing this option repeatedly.') add_tag_command.parser.usage += '\n'\ 'Example: beet addtag artist:beatles -t favourites' def remove_usertag(lib, opts, args): """Remove a usertag""" items = lib.items(args) deltags = opts.tags for item in items: usertags = item.get('usertags', None)
def commands(self): pastan = Subcommand('pastan', help='Hello, my name is pastan.') pastan.func = self.pastan return [pastan]
from beets.plugins import BeetsPlugin import os import socket from beets import config from beets.ui import Subcommand missedLogFile = '/home/travis/Apps/BeetsPlugin/beetsplug/missed.txt' importMissedAlbums = Subcommand('importmissed', help='Import the album listed in the "missed" file') def reImportMissed(lib, opts, args): print "Reimported files/albums we missed the first time" with open(missedLogFile) as f: albums = f.readlines() importMissedAlbums.func = reImportMissedAlbums class MissedOnImport(BeetsPlugin): def __init__(self): print 'Init of new plugin!!' @MissedOnImport.listen('import_task_choice') def importmissed(session,task): albumpath = task.paths if task.choice_flag.name!='APPLY': # Album was not auto-corrected :( with open(missedLogFile, "a") as myfile: myfile.write(albumpath[0]+'\n') # Added to log print task['path']#purposely kill import, so we can reimport for testing hehe
def update_collection(lib, opts, args): # Get the collection to modify. collections = mb_request('collection', 'GET', True, True) if not collections['collection-list']: raise ui.UserError('no collections exist for user') collection_id = collections['collection-list'][0]['id'] # Get a list of all the albums. albums = [a.mb_albumid for a in lib.albums() if a.mb_albumid] # Submit to MusicBrainz. print('Updating MusicBrainz collection {0}...'.format(collection_id)) submit_albums(collection_id, albums) print('...MusicBrainz collection updated.') update_mb_collection_cmd = Subcommand('mbupdate', help='Update MusicBrainz collection') update_mb_collection_cmd.func = update_collection class MusicBrainzCollectionPlugin(BeetsPlugin): def __init__(self): super(MusicBrainzCollectionPlugin, self).__init__() musicbrainzngs.auth( config['musicbrainz']['user'].get(unicode), config['musicbrainz']['pass'].get(unicode), ) def commands(self): return [update_mb_collection_cmd]
def commands(self): import_mtags = Subcommand('import-mtags', help="Import a directory of m-tag files") import_mtags.func = self._import_mtags return [import_mtags]