コード例 #1
0
ファイル: gmusic.py プロジェクト: arogl/beets
    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]
コード例 #2
0
ファイル: play.py プロジェクト: Brainversation/beets
 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]
コード例 #3
0
ファイル: __init__.py プロジェクト: Lugoues/beets-lyrics
    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]
コード例 #4
0
 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]
コード例 #5
0
ファイル: play.py プロジェクト: 15502119602/beets
 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]
コード例 #6
0
ファイル: mbcollection.py プロジェクト: bheadwhite/beets
 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]
コード例 #7
0
ファイル: badfiles.py プロジェクト: beetbox/beets
 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]
コード例 #8
0
    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]
コード例 #9
0
ファイル: play.py プロジェクト: suthanthirarajan/beets
 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]
コード例 #10
0
 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]
コード例 #11
0
ファイル: play.py プロジェクト: Dietr1ch/beets
 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]
コード例 #12
0
ファイル: zero.py プロジェクト: JDLH/beets
    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]
コード例 #13
0
ファイル: wlg.py プロジェクト: samdoshi/whatlastgenre
 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]
コード例 #14
0
ファイル: thumbnails.py プロジェクト: hiro-sumi1888/beets
    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]
コード例 #15
0
ファイル: wlg.py プロジェクト: YetAnotherNerd/whatlastgenre
 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]
コード例 #16
0
ファイル: play.py プロジェクト: agittins/beets
 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]
コード例 #17
0
    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]
コード例 #18
0
    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]
コード例 #19
0
ファイル: play.py プロジェクト: RobbeeUA/Music
 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]
コード例 #20
0
ファイル: play.py プロジェクト: arogl/beets
 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]
コード例 #21
0
ファイル: subsonicplaylist.py プロジェクト: zyj3421/beets
    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]
コード例 #22
0
ファイル: thumbnails.py プロジェクト: angelsanz/beets
    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]
コード例 #23
0
ファイル: unimported.py プロジェクト: landonb/beets
    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]
コード例 #24
0
ファイル: alias.py プロジェクト: kergoth/beets-kergoth
    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()
コード例 #25
0
ファイル: __init__.py プロジェクト: sdrik/beetsonic
    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]
コード例 #26
0
ファイル: freedesktop.py プロジェクト: scztt/beets
 def commands(self):
     freedesktop_command = Subcommand("freedesktop",
                                      help="Create .directory files")
     freedesktop_command.func = self.process_query
     return [freedesktop_command]
コード例 #27
0
ファイル: genrelist.py プロジェクト: michl/beets
		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.
コード例 #28
0
ファイル: blackbird.py プロジェクト: digideskio/blackbird
    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]
コード例 #29
0
ファイル: fuzzy_search.py プロジェクト: sashaseifollahi/beets
        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)
コード例 #30
0
    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]
コード例 #31
0
ファイル: random.py プロジェクト: madjar/beets
        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]
コード例 #32
0
ファイル: freedesktop.py プロジェクト: jbaginski/beets
 def commands(self):
     freedesktop_command = Subcommand("freedesktop",
                                      help="Create .directory files")
     freedesktop_command.func = process_query
     return [freedesktop_command]
コード例 #33
0
			# 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)
コード例 #34
0
ファイル: lastimport.py プロジェクト: zhelezov/beetsplug
 def commands(self):
     cmd = Subcommand('lastimport', help=u'list last imported items')
     cmd.parser.add_path_option()
     cmd.func = list_items
     return [cmd]
コード例 #35
0
ファイル: limit.py プロジェクト: adamjakab/Beets

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
コード例 #36
0
ファイル: gmusic-sync.py プロジェクト: brannon/gmusic-sync
def make_command(name, func, **kwargs):
    c = Subcommand(name, **kwargs)
    c.func = func
    return c
コード例 #37
0
            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]

コード例 #38
0
ファイル: random.py プロジェクト: adamjakab/Beets
    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]
コード例 #39
0
            # 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]
コード例 #40
0
 def commands(self):
     bad_command = Subcommand('bad',
                              help='check for corrupt or missing files')
     bad_command.func = self.check_bad
     return [bad_command]
コード例 #41
0
ファイル: beetsync.py プロジェクト: evanc577/beetsync
 def commands(self):
     cmds = Subcommand('sync')
     cmds.func = self.sync
     return [cmds]
コード例 #42
0
ファイル: play.py プロジェクト: christophernhill/beets
 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]
コード例 #43
0
ファイル: fuzzy.py プロジェクト: flz/beets
        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]
コード例 #44
0
 def commands(self):
     mbupdate = Subcommand('mbupdate', help='Update MusicBrainz collection')
     mbupdate.func = self.update_collection
     return [mbupdate]
コード例 #45
0
ファイル: txt-import.py プロジェクト: stoits/beets-plugins
                        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]
コード例 #46
0
ファイル: cmus.py プロジェクト: coolkehon/beets
        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]

コード例 #47
0
            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]
コード例 #48
0
                               ]):  # 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]
コード例 #49
0
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]
コード例 #50
0
ファイル: mbcollection.py プロジェクト: jbaginski/beets
            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]
コード例 #51
0
 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]
コード例 #52
0
ファイル: beetFs.py プロジェクト: jbaiter/beetfs
        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)

コード例 #53
0
ファイル: usertag.py プロジェクト: igordertigor/beets-usertag
            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)
コード例 #54
0
 def commands(self):
     pastan = Subcommand('pastan', help='Hello, my name is pastan.')
     pastan.func = self.pastan
     return [pastan]
コード例 #55
0
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
コード例 #56
0
ファイル: mbcollection.py プロジェクト: steinitzu/beets
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]
コード例 #57
0
 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]