fixing pep8 and pylint recomendations

This commit is contained in:
2013-07-11 00:30:00 +10:00
parent 29388ba43f
commit ca4c95219a
5 changed files with 200 additions and 134 deletions

View File

@@ -9,7 +9,7 @@ import sys
import getopt import getopt
from libfilemanager import FileManager from libfilemanager import FileManager
from libsettings import Settings from libsettings import Settings
from libhandbrake import Encoder import libhandbrake
from libtvdatasource import TVData from libtvdatasource import TVData
from collections import namedtuple from collections import namedtuple
@@ -106,8 +106,9 @@ def main(argv):
print "File {0} already exists. Cannot process." \ print "File {0} already exists. Cannot process." \
.format(show.outputFile) .format(show.outputFile)
else: else:
encoder = Encoder(settings.HandbrakeCommand()) result = libhandbrake.encode(settings.handbrakecommand(),
result = encoder.Encode(show.inputFile, show.outputFile) show.inputFile,
show.outputFile)
# TODO do something with the result # TODO do something with the result
filemanager.performpostencodefileoperations( filemanager.performpostencodefileoperations(
show.inputFile, show.outputFile) show.inputFile, show.outputFile)

View File

@@ -7,37 +7,30 @@ Created on Fri Jul 5 14:11:00 2013
Library to interface with handbrake to encode video files Library to interface with handbrake to encode video files
""" """
import logging
import subprocess import subprocess
#==============================================================================
# HANDBRAKECOMMAND = ['HandBrakeCLI', '--verbose', '-i',
# "SUBSTITUTE WITH INPUT FILE", '-o',
# "SUBSTITUDE WITH OUTPUT FILE", '-f', 'mkv', '-e', 'x264',
# '-x264-preset', 'slower', '-x264-tune', 'animation', '-q',
# '20', '--loose-anamorphic', '--decomb', '--detelecine',
# '--denoise="2:1:2:3"', '--deblock']
#==============================================================================
class Encoder: def encode(handbrakecommand, inputfile, outputfile, waitforcompletion=True,
def __init__(self, handbrakeCommand): logger=None):
self.handbrakeCommand = handbrakeCommand """
Encode inputfile and save the result to outputfile. handbrakecommand is
a list of strings containing the arguments to handbrakecli.
"""
def Encode(self, input, output, waitForCompletion=True, logger=None): handbrakecommand[3] = inputfile
self.handbrakeCommand[3] = input handbrakecommand[5] = outputfile
self.handbrakeCommand[5] = output
if logger: if logger:
logger.debug("Handbrake command is: {0}".format(self.handbrakeCommand)) logger.debug("Handbrake command is: {0}".format(handbrakecommand))
process = subprocess.Popen(self.handbrakeCommand) process = subprocess.Popen(handbrakecommand)
if waitForCompletion: if waitforcompletion:
process.wait() process.wait()
if logger is not None: if logger is not None:
logger.info("Handbrake completed with return code {0}".format(process.returncode)) logger.info("Handbrake completed with return code {0}".format(
process.returncode))
return process.returncode return process.returncode
return None return None

View File

@@ -8,25 +8,46 @@ Created on Fri Jul 5 14:10:47 2013
import MySQLdb as mdb import MySQLdb as mdb
from libtvshow import TVShow from libtvshow import TVShow
class MythTV: class MythTV:
"""
Contains methods used for interacting with mythtv
"""
def __init__(self, settings): def __init__(self, settings):
self.settings = settings self.settings = settings
def RetrieveEpisodeData(self, inputFile): def retrieveepisodedata(self, inputfile):
con = mdb.connect(self.settings.MythTVAddress(), self.settings.MythTVUser(), self.settings.MythTVPassword(), self.settings.MythTVDatabase()) """
Retrieve the data that mythtv knows about the recorded file.
"""
con = mdb.connect(self.settings.MythTVAddress(),
self.settings.MythTVUser(),
self.settings.MythTVPassword(),
self.settings.MythTVDatabase())
with con: with con:
cur = con.cursor(mdb.cursors.DictCursor) cur = con.cursor(mdb.cursors.DictCursor)
cur.execute("select episode, season, title, subtitle, description from mythconverg.recorded where basename = '{0}'".format(inputFile)) cur.execute("select episode, season, title, subtitle, "
"description from mythconverg.recorded where "
"basename = '{0}'".format(inputfile))
result = cur.fetchone() result = cur.fetchone()
#print result
return TVShow(result['episode'], result['season'], result['title'], result['subtitle'], result['description']) return TVShow(result['episode'], result['season'],
result['title'], result['subtitle'],
result['description'])
def FixMythTVEpisodeName(self, showName, episodeTitle): def fixmythtvepisodename(self, showname, episodetitle):
for prefix in self.settings.GetShowMythTVEpisodePrefix(showName): """
if episodeTitle.lower().startswith(prefix.lower()): Look for any prefixes listed in the configuration file. If there are
return episodeTitle[len(prefix):] any and the episide title starts with the prefix, remove the prefix
from the episode title. The searching is done in the order that the
prefixes are listed in the configuration file.
"""
return episodeTitle #didn't find anything so return the episode title for prefix in self.settings.GetShowMythTVEpisodePrefix(showname):
if episodetitle.lower().startswith(prefix.lower()):
return episodetitle[len(prefix):]
#didn't find anything so return the episode title
return episodetitle

View File

@@ -7,111 +7,122 @@ Created on Fri Jul 5 20:14:15 2013
from configobj import ConfigObj from configobj import ConfigObj
class ShowSettings:
def __init__(self, name, inputDirectory, outputDirectory): #==============================================================================
self.name = name # class ShowSettings:
self.inputDirectory = inputDirectory # """
self.outputDirectory = outputDirectory # Container for the settings for a show
# """
#
# def __init__(self, name, inputdirectory, outputdirectory):
# self.name = name
# self.inputdirectory = inputdirectory
# self.outputdirectory = outputdirectory
#==============================================================================
class Settings: class Settings:
def __init__(self, settingsFile): """
self.__config = ConfigObj(settingsFile) Accessor for the configuration file
"""
def TVRecordingDirectory(self): def __init__(self, settingsfile):
self.__config = ConfigObj(settingsfile)
def tvrecordingdirectory(self):
return self.__config["TVRecordings"] return self.__config["TVRecordings"]
def HandbrakeCommand(self): def handbrakecommand(self):
return self.__config["HandbrakeCommand"] return self.__config["HandbrakeCommand"]
def MythTVAddress(self): def mythtvaddress(self):
return self.__config["MythTV"]["address"] return self.__config["MythTV"]["address"]
def MythTVUser(self): def mythtvuser(self):
return self.__config["MythTV"]["user"] return self.__config["MythTV"]["user"]
def MythTVPassword(self): def mythtvpassword(self):
return self.__config["MythTV"]["password"] return self.__config["MythTV"]["password"]
def MythTVDatabase(self): def mythtvdatabase(self):
return self.__config["MythTV"]["database"] return self.__config["MythTV"]["database"]
def SickbeardAddress(self): def sickbeardaddress(self):
return self.__config["Sickbeard"]["address"] return self.__config["Sickbeard"]["address"]
def SickbeardPort(self): def sickbeardport(self):
return int(self.__config["Sickbeard"]["port"]) return int(self.__config["Sickbeard"]["port"])
def SickbeardAPIKey(self): def sickbeardapikey(self):
return self.__config["Sickbeard"]["APIKey"] return self.__config["Sickbeard"]["APIKey"]
def UnknownDirectory(self): def unknowndirectory(self):
return self.__config["Shows"]["UnknownInput"] return self.__config["Shows"]["UnknownInput"]
def GetShowNames(self, includeAlias=False): def getshownames(self, includealias=False):
shows = self.__config["Shows"].sections shows = self.__config["Shows"].sections
result = shows[:] result = shows[:]
if includeAlias: if includealias:
for show in shows: for show in shows:
for alias in self.__config["Shows"][show]["alias"]: for alias in self.__config["Shows"][show]["alias"]:
result.append(alias) result.append(alias)
return result return result
def GetShowInputDirectory(self, showName): def getshowinputdirectory(self, showname):
show = self.__GetShowSubsection(showName) show = self.__getshowsubsection(showname)
if show is None: if show is None:
return "" return ""
else: else:
return show["InputDirectory"] return show["InputDirectory"]
def GetShowUnknownDirectory(self, showName): def getshowunknowndirectory(self, showname):
show = self.__GetShowSubsection(showName) show = self.__getshowsubsection(showname)
if show is None: if show is None:
return "" return ""
else: else:
return show["UnknownDirectory"] return show["UnknownDirectory"]
def GetShowOutputDirectory(self, showName): def getshowoutputdirectory(self, showname):
show = self.__GetShowSubsection(showName) show = self.__getshowsubsection(showname)
if show is None: if show is None:
return "" return ""
else: else:
return show["OutputDirectory"] return show["OutputDirectory"]
def GetShowAlias(self, showName): def getshowalias(self, showname):
show = self.__GetShowSubsection(showName) show = self.__getshowsubsection(showname)
if show is None: if show is None:
return "" return ""
else: else:
return show["alias"] return show["alias"]
def GetShowMythTVEpisodePrefix(self, showName): def getshowmythtvepisodeprefix(self, showname):
show = self.__GetShowSubsection(showName) show = self.__getshowsubsection(showname)
if show is None: if show is None:
return "" return ""
else: else:
return show["MythTvEpisodePrefix"] return show["MythTvEpisodePrefix"]
def GetShowSickbeardEpisodePrefix(self, showName): def getshowsickbearsepisodeprefix(self, showname):
show = self.__GetShowSubsection(showName) show = self.__getshowsubsection(showname)
if show is None: if show is None:
return "" return ""
else: else:
return show["SickbeardPrefix"] return show["SickbeardPrefix"]
def GetShow(self, showName): def getshow(self, showname):
showSection = self.__GetShowSubsection(showName) showsection = self.__getshowsubsection(showname)
if showSection is None: if showsection is None:
return None return None
else: else:
return showSection.name return showsection.name
def __GetShowSubsection(self, showName): def __getshowsubsection(self, showname):
if showName in self.GetShowNames(): if showname in self.getshownames():
return self.__config["Shows"][showName] return self.__config["Shows"][showname]
else: # check liases else: # check liases
for show in self.GetShowNames(): for show in self.getshownames():
if showName in self.__config["Shows"][show]["alias"]: if showname in self.__config["Shows"][show]["alias"]:
return self.__config["Shows"][show] return self.__config["Shows"][show]
return None return None

View File

@@ -5,12 +5,12 @@ Created on Fri Jul 5 14:10:37 2013
@author: shanef @author: shanef
""" """
from libtvshow import TVShow
import json import json
from urllib import urlopen from urllib import urlopen
from fuzzywuzzy import fuzz from fuzzywuzzy import fuzz
from operator import itemgetter from operator import itemgetter
class Sickbeard: class Sickbeard:
def __init__(self, settings): def __init__(self, settings):
self.__settings = settings self.__settings = settings
@@ -19,7 +19,8 @@ class Sickbeard:
self.__apikey = settings.SickbeardAPIKey() self.__apikey = settings.SickbeardAPIKey()
def __GetApiURL(self): def __GetApiURL(self):
return "http://{0}:{1}/api/{2}/".format(self.__address, self.__port, self.__apikey) return "http://{0}:{1}/api/{2}/".format(self.__address, self.__port,
self.__apikey)
def FindShowId(self, showName): def FindShowId(self, showName):
jsonurl = urlopen(self.__GetApiURL()+"?cmd=shows") jsonurl = urlopen(self.__GetApiURL()+"?cmd=shows")
@@ -33,7 +34,9 @@ class Sickbeard:
shows = [] shows = []
for show in result['data']: for show in result['data']:
shows.append((show, fuzz.partial_ratio(showName.lower(), result['data'][show]['show_name'].lower()))) shows.append((show, fuzz.partial_ratio(showName.lower(),
result['data'][show]
['show_name'].lower())))
shows = sorted(shows, key=itemgetter(1), reverse=True) shows = sorted(shows, key=itemgetter(1), reverse=True)
@@ -41,17 +44,22 @@ class Sickbeard:
return shows[0][0] return shows[0][0]
def FindEpisodeByDescription(self, showId, season, episode, description): def FindEpisodeByDescription(self, showId, season, episode, description):
jsonEpisodeUrl = urlopen("{0}?cmd=episode&tvdbid={1}&season={2}&episode={3}".format(self.__GetApiURL(), showId, season, episode)) jsonepisodeurl = urlopen("{0}?cmd=episode&tvdbid={1}&season={2}"
episodeResult = json.loads(jsonEpisodeUrl.read()) "&episode={3}".format(self.__GetApiURL(),
showId, season, episode))
episoderesult = json.loads(jsonepisodeurl.read())
sickbeardDescription = episodeResult['data']['description'] sickbearddescription = episoderesult['data']['description']
if fuzz.ratio(sickbeardDescription.lower(), description.lower()) > 85 or fuzz.ratio(sickbeardDescription.lower()[:len(description)], description.lower()) > 85 or fuzz.ratio(sickbeardDescription.lower(), description.lower()[:len(sickbeardDescription)]) > 85:
return (season, episode, episodeResult['data']['name']) if fuzzystringcompare(sickbearddescription, description):
return (season, episode, episoderesult['data']['name'])
return None return None
def FindEpisodeName(self, showId, season, episode): def FindEpisodeName(self, showId, season, episode):
jsonurl = urlopen("{0}?cmd=episode&tvdbid={1}&season={2}&episode={3}".format(self.__GetApiURL(), showId, int(season), int(episode))) jsonurl = urlopen("{0}?cmd=episode&tvdbid={1}&season={2}"
"&episode={3}".format(self.__GetApiURL(), showId,
int(season), int(episode)))
result = json.loads(jsonurl.read()) result = json.loads(jsonurl.read())
if result['result'] == 'error': if result['result'] == 'error':
return "" return ""
@@ -59,15 +67,20 @@ class Sickbeard:
return result['data']['name'] return result['data']['name']
def FindEpisode(self, showId, name=None, description=None): def FindEpisode(self, showId, name=None, description=None):
jsonurl = urlopen("{0}?cmd=show.seasons&tvdbid={1}".format(self.__GetApiURL(), showId)) jsonurl = urlopen("{0}?cmd=show.seasons&tvdbid={1}".format(
self.__GetApiURL(), showId))
result = json.loads(jsonurl.read()) result = json.loads(jsonurl.read())
for season in result['data']: for season in result['data']:
for episode in result['data'][season]: for episode in result['data'][season]:
if name is not None and fuzz.partial_ratio(name.lower(), result['data'][season][episode]['name'].lower()) > 90: episodename = result['data'][season][episode]['name']
return (season, episode, result['data'][season][episode]['name']) if name is not None and fuzz.partial_ratio(name.lower(),
episodename) > 90:
return (season, episode, episodename)
elif description is not None: elif description is not None:
descriptionQueryResult = self.FindEpisodeByDescription(showId, season, episode, description) descriptionQueryResult = \
self.FindEpisodeByDescription(showId, season,
episode, description)
if descriptionQueryResult is not None: if descriptionQueryResult is not None:
return descriptionQueryResult return descriptionQueryResult
@@ -82,9 +95,36 @@ class Sickbeard:
#============================================================================== #==============================================================================
def FixEpisodeTitle(self, showName, episodeTitle): def FixEpisodeTitle(self, showName, episodeTitle):
sickbeardPrefix = self.__settings.GetShowSickbeardEpisodePrefix(showName) sickbeardPrefix = \
self.__settings.GetShowSickbeardEpisodePrefix(showName)
if sickbeardPrefix != "": if sickbeardPrefix != "":
if not episodeTitle.lower.startswith(sickbeardPrefix.lower()): if not episodeTitle.lower.startswith(sickbeardPrefix.lower()):
return "{0} {1}".format(sickbeardPrefix.rstrip(), episodeTitle.lstrip()) return "{0} {1}".format(sickbeardPrefix.rstrip(),
episodeTitle.lstrip())
return episodeTitle return episodeTitle
def fuzzystringcompare(string1, string2, matchvalue=85, casesensitive=False):
"""
Compare two strings to see if they match it first does a straight
comparison. Secondly, it concatenates the longer string to the length of
the shorter one, and tries to compare them again.
"""
if not casesensitive:
string1 = string1.lower()
string2 = string2.lower()
if fuzz.ratio(string1, string2) > matchvalue:
return True
if len(string1) > len(string2):
if fuzz.ratio(string1[:len(string2)], string2) > matchvalue:
return True
elif len(string2) > len(string1):
if fuzz.ratio(string1, string2[:len(string1)]) > matchvalue:
return True
return False