From 78a694ddcd2a6ecc8b2b1fd3c74ee2d938707305 Mon Sep 17 00:00:00 2001 From: kaliko Date: Sat, 15 Feb 2014 20:08:07 +0100 Subject: [PATCH] Some clean-up (pylint audit) --- sima/core.py | 3 ++- sima/launch.py | 9 +++++--- sima/lib/daemon.py | 5 ++--- sima/lib/logger.py | 3 +-- sima/lib/meta.py | 23 +++++++++++++++++++ sima/lib/player.py | 1 - sima/lib/plugin.py | 26 +++++++++++++++++++-- sima/lib/simadb.py | 30 ++++++++++++++++--------- sima/lib/simaecho.py | 13 +++++------ sima/lib/simafm.py | 14 ++++++------ sima/lib/simastr.py | 16 ++++++------- sima/lib/track.py | 12 ++-------- sima/lib/webserv.py | 9 +++++--- sima/plugins/internal/randomfallback.py | 3 ++- sima/utils/config.py | 4 ++-- sima/utils/leven.py | 2 +- sima/utils/startopt.py | 4 ++-- sima/utils/utils.py | 10 +++++++-- 18 files changed, 120 insertions(+), 67 deletions(-) diff --git a/sima/core.py b/sima/core.py index 0aaebec..31111fc 100644 --- a/sima/core.py +++ b/sima/core.py @@ -20,7 +20,6 @@ """Core Object dealing with plugins and player client """ -import sys import time from collections import deque @@ -60,6 +59,7 @@ class Sima(Daemon): return PlayerClient(host, port, pswd) def add_history(self): + """Handle local short history""" self.short_history.appendleft(self.player.current) def register_plugin(self, plugin_class): @@ -73,6 +73,7 @@ class Sima(Daemon): getattr(plugin, method)(*args, **kwds) def need_tracks(self): + """Is the player in need for tracks""" if not self.enabled: self.log.debug('Queueing disabled!') return False diff --git a/sima/launch.py b/sima/launch.py index a25b313..e1bd744 100644 --- a/sima/launch.py +++ b/sima/launch.py @@ -58,7 +58,8 @@ def load_plugins(sima, source): try: mod_obj = __import__(module, fromlist=[plugin]) except ImportError as err: - logger.error('Failed to load plugin\'s module: {0} ({1})'.format(module, err)) + logger.error('Failed to load plugin\'s module: ' + + '{0} ({1})'.format(module, err)) sima.shutdown() sys.exit(1) try: @@ -67,7 +68,8 @@ def load_plugins(sima, source): logger.error('Failed to load plugin {0} ({1})'.format(plugin, err)) sima.shutdown() sys.exit(1) - logger.info('Loading {0} plugin: {name} ({doc})'.format(source, **plugin_obj.info())) + logger.info('Loading {0} plugin: {name} ({doc})'.format( + source, **plugin_obj.info())) sima.register_plugin(plugin_obj) @@ -133,13 +135,14 @@ def run(sopt, restart=False): # pylint: disable=broad-except try: start(sopt, restart) - except SigHup as err: # SigHup inherit from Exception + except SigHup: # SigHup inherit from Exception run(sopt, True) except Exception: # Unhandled exception exception_log() # Script starts here def main(): + """Entry point""" nfo = dict({'version': info.__version__, 'prog': 'sima'}) # StartOpt gathers options from command line call (in StartOpt().options) diff --git a/sima/lib/daemon.py b/sima/lib/daemon.py index 06f7bee..fa09976 100644 --- a/sima/lib/daemon.py +++ b/sima/lib/daemon.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Public Domain # # Copyright 2007, 2009 Sander Marechal @@ -62,8 +61,8 @@ class Daemon(object): for details (ISBN 0201563177) Short explanation: - Unix processes belong to "process group" which in turn lies within a "session". - A session can have a controlling tty. + Unix processes belong to "process group" which in turn lies within a + "session". A session can have a controlling tty. Forking twice allows to detach the session from a possible tty. The process lives then within the init process. """ diff --git a/sima/lib/logger.py b/sima/lib/logger.py index a4ed23d..3b287e2 100644 --- a/sima/lib/logger.py +++ b/sima/lib/logger.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright (c) 2009, 2010, 2013, 2014 Jack Kaliko # # This file is part of sima @@ -29,7 +28,7 @@ import sys LOG_FORMATS = { - logging.DEBUG: '{asctime} {filename: >11}:{lineno: <3} {levelname: <7}: {message}', + logging.DEBUG: '{asctime} {filename: >11}:{lineno: <3} {levelname: <7}: {message}', logging.INFO: '{asctime} {levelname: <7}: {message}', #logging.DEBUG: '{asctime} {filename}:{lineno}({funcName}) ' #'{levelname}: {message}', diff --git a/sima/lib/meta.py b/sima/lib/meta.py index d589051..4e481e6 100644 --- a/sima/lib/meta.py +++ b/sima/lib/meta.py @@ -1,9 +1,31 @@ # -*- coding: utf-8 -*- +# Copyright (c) 2013, 2014 Jack Kaliko +# +# This file is part of sima +# +# sima is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# sima is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with sima. If not, see . +# +# +""" +Defines some object to handle audio file metadata +""" from .simastr import SimaStr from .track import Track class MetaException(Exception): + """Generic Meta Exception""" pass class NotSameArtist(MetaException): @@ -11,6 +33,7 @@ class NotSameArtist(MetaException): class Meta: + """Generic Class for Meta object""" def __init__(self, **kwargs): self.name = None diff --git a/sima/lib/player.py b/sima/lib/player.py index ddba0a9..6b6d2cb 100644 --- a/sima/lib/player.py +++ b/sima/lib/player.py @@ -29,7 +29,6 @@ import logging class Player(object): - """Player interface to inherit from. When querying player music library for tracks, Player instance *must* return diff --git a/sima/lib/plugin.py b/sima/lib/plugin.py index 0e80ae5..1188d45 100644 --- a/sima/lib/plugin.py +++ b/sima/lib/plugin.py @@ -1,6 +1,27 @@ # -*- coding: utf-8 -*- - -class Plugin(): +# Copyright (c) 2013, 2014 Jack Kaliko +# +# This file is part of sima +# +# sima is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# sima is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with sima. If not, see . +# +# +""" +Plugin object to derive from +""" + +class Plugin: """ First non-empty line of the docstring is used as description Rest of the docstring at your convenience. @@ -81,6 +102,7 @@ class Plugin(): pass def shutdown(self): + """Called on application shutdown""" pass diff --git a/sima/lib/simadb.py b/sima/lib/simadb.py index 284f115..6f88144 100644 --- a/sima/lib/simadb.py +++ b/sima/lib/simadb.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- - +# # Copyright (c) 2009-2013 Jack Kaliko # Copyright (c) 2009, Eric Casteleijn # Copyright (c) 2008 Rick van Hattem @@ -20,6 +20,8 @@ # along with sima. If not, see . # # +"""SQlite database library +""" # DOC: # MuscicBrainz ID: @@ -27,7 +29,7 @@ # __DB_VERSION__ = 2 -__HIST_DURATION__ = int(7 * 24) # in hours +__HIST_DURATION__ = int(30 * 24) # in hours import sqlite3 @@ -67,6 +69,7 @@ class SimaDB(object): self.db_path_mod_control() def db_path_mod_control(self): + """Controls DB path access & write permissions""" db_path = self._db_path # Controls directory access if not isdir(dirname(db_path)): @@ -347,7 +350,7 @@ class SimaDB(object): """Retrieve complete play history, most recent tracks first artist : filter history for specific artist artists : filter history for specific artists list - """ + """ # pylint: disable=C0301 date = datetime.utcnow() - timedelta(hours=duration) connection = self.get_database_connection() if artist: @@ -380,7 +383,8 @@ class SimaDB(object): yield ('Row ID', 'Artist',) for row in rows: yield row - rows = connection.execute('SELECT black_list.rowid, albums.name, artists.name' + rows = connection.execute( + 'SELECT black_list.rowid, albums.name, artists.name' ' FROM artists, albums INNER JOIN black_list' ' ON albums.id = black_list.album' ' WHERE artists.id = albums.artist') @@ -388,7 +392,8 @@ class SimaDB(object): yield ('Row ID', 'Album', 'Artist name') for row in rows: yield row - rows = connection.execute('SELECT black_list.rowid, tracks.name, artists.name' + rows = connection.execute( + 'SELECT black_list.rowid, tracks.name, artists.name' ' FROM artists, tracks INNER JOIN black_list' ' ON tracks.id = black_list.track' ' WHERE tracks.artist = artists.id') @@ -522,9 +527,11 @@ class SimaDB(object): """Add to history""" connection = self.get_database_connection() track_id = self.get_track(track, with_connection=connection)[0] - rows = connection.execute("SELECT * FROM history WHERE track = ? ", (track_id,)) + rows = connection.execute("SELECT * FROM history WHERE track = ? ", + (track_id,)) if not rows.fetchone(): - connection.execute("INSERT INTO history (track) VALUES (?)", (track_id,)) + connection.execute("INSERT INTO history (track) VALUES (?)", + (track_id,)) connection.execute("UPDATE history SET last_play = DATETIME('now') " " WHERE track = ?", (track_id,)) connection.commit() @@ -668,6 +675,7 @@ class SimaDB(object): self.close_database_connection(connection) def _set_dbversion(self): + """Add db version""" connection = self.get_database_connection() connection.execute('INSERT INTO db_info (version, name) VALUES (?, ?)', (__DB_VERSION__, 'Sima DB')) @@ -704,13 +712,13 @@ class SimaDB(object): 'CREATE TABLE IF NOT EXISTS history (last_play DATE,' ' track integer)') connection.execute( - "CREATE INDEX IF NOT EXISTS a2aa1x ON usr_artist_2_artist (artist1)") + "CREATE INDEX IF NOT EXISTS a2aa1x ON usr_artist_2_artist (artist1)") connection.execute( - "CREATE INDEX IF NOT EXISTS a2aa2x ON usr_artist_2_artist (artist2)") + "CREATE INDEX IF NOT EXISTS a2aa2x ON usr_artist_2_artist (artist2)") connection.execute( - "CREATE INDEX IF NOT EXISTS lfma2aa1x ON lfm_artist_2_artist (artist1)") + "CREATE INDEX IF NOT EXISTS lfma2aa1x ON lfm_artist_2_artist (artist1)") connection.execute( - "CREATE INDEX IF NOT EXISTS lfma2aa2x ON lfm_artist_2_artist (artist2)") + "CREATE INDEX IF NOT EXISTS lfma2aa2x ON lfm_artist_2_artist (artist2)") connection.commit() self.close_database_connection(connection) self._set_dbversion() diff --git a/sima/lib/simaecho.py b/sima/lib/simaecho.py index ff9782a..1462303 100644 --- a/sima/lib/simaecho.py +++ b/sima/lib/simaecho.py @@ -25,10 +25,7 @@ __version__ = '0.0.1' __author__ = 'Jack Kaliko' -import logging - from datetime import datetime, timedelta -from time import sleep from requests import get, Request, Timeout, ConnectionError @@ -44,8 +41,8 @@ WAIT_BETWEEN_REQUESTS = timedelta(0, 1) SOCKET_TIMEOUT = 4 -class SimaEch(): - """ +class SimaEch: + """EchoNest http client """ root_url = 'http://{host}/api/{version}'.format(**ECH) cache = {} @@ -100,7 +97,7 @@ class SimaEch(): raise WSError(status.get('message')) def _forge_payload(self, artist): - """ + """Build payload """ payload = {'api_key': ECH.get('apikey')} if not isinstance(artist, Artist): @@ -110,13 +107,13 @@ class SimaEch(): payload.update( id='musicbrainz:artist:{0}'.format(artist.mbid)) else: - payload.update(name=artist.name) + payload.update(name=artist.name) payload.update(bucket='id:musicbrainz') payload.update(results=100) return payload def get_similar(self, artist=None): - """ + """Fetch similar artists """ payload = self._forge_payload(artist) # Construct URL diff --git a/sima/lib/simafm.py b/sima/lib/simafm.py index 3457016..3210fdc 100644 --- a/sima/lib/simafm.py +++ b/sima/lib/simafm.py @@ -17,7 +17,7 @@ # """ -Consume EchoNest web service +Consume Last.fm web service """ __version__ = '0.5.0' @@ -40,8 +40,8 @@ WAIT_BETWEEN_REQUESTS = timedelta(0, 1) SOCKET_TIMEOUT = 6 -class SimaFM(): - """ +class SimaFM: + """Last.fm http client """ root_url = 'http://{host}/{version}/'.format(**LFM) cache = {} @@ -96,7 +96,7 @@ class SimaFM(): return True def _forge_payload(self, artist, method='similar', track=None): - """ + """Build payload """ payloads = dict({'similar': {'method':'artist.getsimilar',}, 'top': {'method':'artist.gettoptracks',}, @@ -111,15 +111,15 @@ class SimaFM(): if artist.mbid: payload.update(mbid='{0}'.format(artist.mbid)) else: - payload.update(artist=artist.name, - autocorrect=1) + payload.update(artist=artist.name, + autocorrect=1) payload.update(results=100) if method == 'track': payload.update(track=track) return payload def get_similar(self, artist=None): - """ + """Fetch similar artists """ payload = self._forge_payload(artist) # Construct URL diff --git a/sima/lib/simastr.py b/sima/lib/simastr.py index 9dacc45..56edbb4 100644 --- a/sima/lib/simastr.py +++ b/sima/lib/simastr.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # # Copyright (c) 2009, 2010, 2013 Jack Kaliko # @@ -18,7 +17,7 @@ # If not, see . # -""" +r""" SimaStr Special unicode() subclass to perform fuzzy match on specific strings with @@ -70,7 +69,7 @@ __version__ = '0.4' # IMPORTS import unicodedata -from re import (compile, U, I) +from re import compile as re_compile, U, I from ..utils.leven import levenshtein_ratio @@ -94,11 +93,11 @@ class SimaStr(str): # Trailing patterns: ! ? live # TODO: add "concert" key word # add "Live at " - regexp_dict.update({'trail': '([- !?\.]|\(? ?[Ll]ive ?\)?)'}) + regexp_dict.update({'trail': r'([- !?\.]|\(? ?[Ll]ive ?\)?)'}) - reg_lead = compile('^(?P%(lead)s )(?P.*)$' % regexp_dict, I | U) - reg_midl = compile('^(?P.*)(?P %(mid)s )(?P.*)' % regexp_dict, U) - reg_trail = compile('^(?P.*?)(?P%(trail)s+$)' % regexp_dict, U) + reg_lead = re_compile('^(?P%(lead)s )(?P.*)$' % regexp_dict, I | U) + reg_midl = re_compile('^(?P.*)(?P %(mid)s )(?P.*)' % regexp_dict, U) + reg_trail = re_compile('^(?P.*?)(?P%(trail)s+$)' % regexp_dict, U) def __init__(self, fuzzstr): """ @@ -108,7 +107,7 @@ class SimaStr(str): # fuzzy computation self._get_root() if self.__class__.diafilter: - self.remove_diacritics() + self.remove_diacritics() def __new__(cls, fuzzstr): return super(SimaStr, cls).__new__(cls, fuzzstr) @@ -134,6 +133,7 @@ class SimaStr(str): self.stripped = sea.group('root0') def remove_diacritics(self): + """converting diacritics""" self.stripped = ''.join(x for x in unicodedata.normalize('NFKD', self.stripped) if unicodedata.category(x) != 'Mn') diff --git a/sima/lib/track.py b/sima/lib/track.py index 93904c8..5a01e17 100644 --- a/sima/lib/track.py +++ b/sima/lib/track.py @@ -24,7 +24,7 @@ import time -class Track(object): +class Track: """ Track object. Instanciate with Player replies. @@ -37,7 +37,7 @@ class Track(object): self._file = file if not kwargs: self._empty = True - self.time = time + self._time = time self.__dict__.update(**kwargs) self.tags_to_collapse = ['artist', 'album', 'title', 'date', 'genre', 'albumartist'] @@ -124,13 +124,5 @@ class Track(object): fmt = '%M:%S' return time.strftime(fmt, temps) - -def main(): - pass - -# Script starts here -if __name__ == '__main__': - main() - # VIM MODLINE # vim: ai ts=4 sw=4 sts=4 expandtab diff --git a/sima/lib/webserv.py b/sima/lib/webserv.py index cc4b2b5..291c4c4 100644 --- a/sima/lib/webserv.py +++ b/sima/lib/webserv.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright (c) 2009, 2010, 2011, 2012, 2013, 2014 Jack Kaliko +# Copyright (c) 2009-2014 Jack Kaliko # # This file is part of sima # @@ -227,7 +227,9 @@ class WebService(Plugin): self.log.info('EXTRA ARTS: {}'.format( '/'.join([trk.artist for trk in extra_arts]))) for artist in extra_arts: - self.log.debug('Looking for artist similar to "{0.artist}" as well'.format(artist)) + self.log.debug( + 'Looking for artist similar to "{0.artist}" as well'.format( + artist)) similar = self.lfm_similar_artists(artist=artist) if not similar: return ret_extra @@ -285,7 +287,8 @@ class WebService(Plugin): # str conversion while Album type is not propagated albums = [ str(album) for album in albums] if albums: - self.log.debug('Albums candidate: {0:s}'.format(' / '.join(albums))) + self.log.debug('Albums candidate: {0:s}'.format( + ' / '.join(albums))) else: continue # albums yet in history for this artist albums = set(albums) diff --git a/sima/plugins/internal/randomfallback.py b/sima/plugins/internal/randomfallback.py index cb19f49..845a41a 100644 --- a/sima/plugins/internal/randomfallback.py +++ b/sima/plugins/internal/randomfallback.py @@ -28,7 +28,6 @@ import random # local import from ...lib.plugin import Plugin -from ...lib.track import Track class RandomFallBack(Plugin): @@ -62,6 +61,8 @@ class RandomFallBack(Plugin): return trks def get_trk(self): + """Get a single track acording to random flavour + """ artists = list(self.player.artists) if self.mode == 'sensitive': played_art = self.get_played_artist() diff --git a/sima/utils/config.py b/sima/utils/config.py index da66366..439f4a5 100644 --- a/sima/utils/config.py +++ b/sima/utils/config.py @@ -189,8 +189,8 @@ class ConfMan(object): # CONFIG MANAGER CLASS self.log.debug('[%s] present in conf file' % section) for option in self.defaults[section]: if self.config.has_option(section, option): - #self.log.debug(u'option "%s" set to "%s" in conf. file' % - # (option, self.config.get(section, option))) + #self.log.debug('option "%s" set to "%s" in conf. file'% + # (option, self.config.get(section, option))) pass else: self.log.debug( diff --git a/sima/utils/leven.py b/sima/utils/leven.py index 9b269df..ab6fc35 100644 --- a/sima/utils/leven.py +++ b/sima/utils/leven.py @@ -16,7 +16,7 @@ # You should have received a copy of the GNU General Public License # along with sima. If not, see . # -# +"""Computes levenshtein distance/ratio""" def levenshtein(a_st, b_st): """Computes the Levenshtein distance between two strings.""" diff --git a/sima/utils/startopt.py b/sima/utils/startopt.py index 33e89b1..ef2032c 100644 --- a/sima/utils/startopt.py +++ b/sima/utils/startopt.py @@ -19,11 +19,10 @@ # # -import sys from argparse import (ArgumentParser, SUPPRESS) -from .utils import Obsolete, Wfile, Rfile, Wdir +from .utils import Wfile, Rfile, Wdir USAGE = """USAGE: %prog [--help] [options]""" DESCRIPTION = """ @@ -115,6 +114,7 @@ class StartOpt(object): """ def __init__(self, script_info,): + self.parser = None self.info = dict(script_info) self.options = dict() self.main() diff --git a/sima/utils/utils.py b/sima/utils/utils.py index d0edcd4..475a548 100644 --- a/sima/utils/utils.py +++ b/sima/utils/utils.py @@ -20,6 +20,7 @@ # """generic tools and utilities for sima """ +# pylint: disable=C0111 import traceback import sys @@ -79,6 +80,8 @@ def exception_log(): sys.exit(1) def purge_cache(obj, age=4): + """purge old entries in http client cache + """ now = datetime.utcnow() if now.hour == obj.timestamp.hour: return @@ -92,6 +95,7 @@ def purge_cache(obj, age=4): class SigHup(Exception): + """SIGHUP raises this Exception""" pass # ArgParse Callbacks @@ -158,7 +162,8 @@ class Wdir(FileAction): if not access(self._file, W_OK): self.parser.error('no write access to "{0}"'.format(self._file)) -class Throttle(): +class Throttle: + """throttle decorator""" def __init__(self, wait): self.wait = wait self.last_called = datetime.now() @@ -172,7 +177,8 @@ class Throttle(): return result return wrapper -class Cache(): +class Cache: + """Plain cache object""" def __init__(self, elem, last=None): self.elem = elem self.requestdate = last -- 2.39.2