From 48b1ba48b3a364f97a1e77b3cd8644de74565908 Mon Sep 17 00:00:00 2001 From: sfrischkorn Date: Thu, 4 Jul 2013 11:05:20 +1000 Subject: [PATCH] Added scripts --- DoEncode.py | 125 +++++++++++++++++++++++++++++++++++++++++++++++++++ README.md | 2 - sickbeard.py | 68 ++++++++++++++++++++++++++++ 3 files changed, 193 insertions(+), 2 deletions(-) create mode 100755 DoEncode.py delete mode 100644 README.md create mode 100755 sickbeard.py diff --git a/DoEncode.py b/DoEncode.py new file mode 100755 index 0000000..846a726 --- /dev/null +++ b/DoEncode.py @@ -0,0 +1,125 @@ +# -*- coding: utf-8 -*- +""" +Created on Sat Jun 29 23:25:55 2013 + +@author: shane +""" + +import glob +import logging +import os +import shutil +import subprocess +from xml.etree import ElementTree + +SETTINGSFILE = "settings.xml" +HANDBRAKECOMMAND = ['HandBrakeCLI', '--verbose', '-i', '"{0}"', '-o', '"{1}"', + '-f', 'mkv', '-e', 'x264', '-x264-preset', 'slower', + '-x264-tune', 'animation', '-q', '20', + '--loose-anamorphic', '--decomb', '--detelecine', + '--denoise="2:1:2:3"', '--deblock'] + +TVRECORDINGSDIR = "/srv/storage2/videos/TVRecordings/" + +LOGFILE = "encoding.log" +ACTIONLOG = "needsAction.log" + +class TVShow: + def __init__(self, name, inputDirectory, outputDirectory): + self.name = name + self.inputDirectory = inputDirectory + self.outputDirectory = outputDirectory + +def LoadSettings(source): + shows = [] + settingsXml = ElementTree.parse(source).getroot() + + for show in settingsXml.findall('show'): + newShow = TVShow(show[0].text, show[1].text, show[2].text) + shows.append(newShow) + return shows + +def FindSeason(path, fileName): + season = "Season {0}".format(fileName[1:3]) + seasonPath = os.path.join(path, season) + if not os.path.exists(seasonPath): + os.makedirs(seasonPath) + + return seasonPath + +def GetRecordingFile(file): + return os.path.join(TVRECORDINGSDIR, os.path.dirname(inputFile).split("/")[-1] + ".mpg") + +def CheckOldOutputFileExists(file, myLogger): + myLogger.debug("Searching for existing file: {0}".format(file[:-3]+"*")) + return glob.glob(file[:-3]+"*") + +def CreateLogger(name, filename, level): + logger = logging.getLogger(name) + handler = logging.FileHandler(filename) + formatter = logging.Formatter('%(asctime)s %(message)s') + handler.setFormatter(formatter) + handler.setLevel(level) + logger.addHandler(handler) + return logger + +#generalLogger.basicConfig(filename=LOGFILE, level=logging.DEBUG, format='%(asctime)s %(message)s') + +#actionLogger = logging.getLogger("action") +#actionLogger.basicConfig(filename=ACTIONLOG, level=logging.INFO, format='%(asctime)s %(message)s') + +logging.basicConfig(level=logging.DEBUG) +generalLogger = CreateLogger("general", LOGFILE, logging.DEBUG) +actionLogger = CreateLogger("action", ACTIONLOG, logging.INFO) + +generalLogger.debug("Loading settings from {0}".format(SETTINGSFILE)) +shows = LoadSettings(SETTINGSFILE) + +for show in shows: + generalLogger.info("Processing {0}".format(show.name)) + fileList = [] + + for r,d,f in os.walk(show.inputDirectory): + for files in f: + if files.endswith(".mpg"): + fileList.append(os.path.join(r,files)) + + for inputFile in fileList: + generalLogger.info("Processing file {0}".format(inputFile)) + + inFile = os.path.basename(inputFile) + outFilename = inFile[:-3]+"mkv" + outPath = FindSeason(show.outputDirectory, outFilename) + outFile = os.path.join(outPath, outFilename) + generalLogger.debug("Output file is {0}".format(outFile)) + + if os.path.isfile(outFile): + message = "File {0} already exists. Not processing any further.".format(outFile) + generalLogger.warning(message) + actionLogger.info(message) + else: + existingFile = CheckOldOutputFileExists(outFile, generalLogger) + generalLogger.debug("Search returned {0}".format(existingFile)) + if len(existingFile) > 0: + message = "There is an existing version of {0} at {1}.".format(outFilename, existingFile[0]) + generalLogger.info(message) + actionLogger.info(message) + + HANDBRAKECOMMAND[3] = inputFile + HANDBRAKECOMMAND[5] = outFile + generalLogger.debug("Handbrake command is: {0}".format(HANDBRAKECOMMAND)) + po = subprocess.Popen(HANDBRAKECOMMAND) + po.wait() + generalLogger.info("Handbrake completed with return code {0}".format(po.returncode)) + + generalLogger.info("Deleting input files from {0}".format(os.path.dirname(inputFile))) + shutil.rmtree(os.path.dirname(inputFile)) + + linkAddress = GetRecordingFile(inputFile) + generalLogger.info("Deleting original file from {0}".format(linkAddress)) + os.remove(linkAddress) + + generalLogger.info("Creating symlink from {0} to {1}".format(linkAddress, outFile)) + os.symlink(outFile, linkAddress) + + generalLogger.info("Processing completed for {0}".format(inputFile)) diff --git a/README.md b/README.md deleted file mode 100644 index dbedcaf..0000000 --- a/README.md +++ /dev/null @@ -1,2 +0,0 @@ -recordingprocessing -=================== diff --git a/sickbeard.py b/sickbeard.py new file mode 100755 index 0000000..31a835d --- /dev/null +++ b/sickbeard.py @@ -0,0 +1,68 @@ +# -*- coding: utf-8 -*- +""" +Created on Tue Jul 2 21:00:35 2013 + +@author: shane +""" +import json +from urllib import urlopen +from fuzzywuzzy import fuzz +from operator import itemgetter + +def FindShowId(showName): + jsonurl = urlopen("http://192.168.0.2:8081/api/3678177136222bf5002be209220ccb20/?cmd=shows") + result = json.loads(jsonurl.read()) + + shows = [] + for show in result['data']: + shows.append((show, fuzz.partial_ratio(showName.lower(), result['data'][show]['show_name'].lower()))) + + shows = sorted(shows, key=itemgetter(1), reverse=True) + + if shows[0][1] > 85: + return shows[0][0] + +def FindEpisode(showId, name=None, description=None): + jsonurl = urlopen("http://192.168.0.2:8081/api/3678177136222bf5002be209220ccb20/?cmd=show.seasons&tvdbid={0}".format(showId)) + result = json.loads(jsonurl.read()) + + for season in result['data']: + for episode in result['data'][season]: + if name is not None and name.lower() == result['data'][season][episode]['name'].lower(): + return (season, episode) + elif description is not None: + result = FindEpisodeByDescription(showId, season, episode, description) + if result is not None: + return result + + return (0, 0) + +def GetEpisodeName(subtitle, showName): + if subtitle[:len(showName)].lower() == showName.lower(): + return subtitle[len(showName + ' and the '):] + else: + return subtitle + +def FindEpisodeByDescription(showId, season, episode, description): + jsonEpisodeUrl = urlopen("http://192.168.0.2:8081/api/3678177136222bf5002be209220ccb20/?cmd=episode&tvdbid={0}&season={1}&episode={2}".format(showId, season, episode)) + episodeResult = json.loads(jsonEpisodeUrl.read()) + + if fuzz.ratio(episodeResult['data']['description'].lower(), description.lower()) > 85: + return (season, episode) + + return None + +showId = FindShowId('Mike the Knight') +#showId = FindShowId("Octonauts") +#print showId + +subtitle = 'Mike the Knight and the Knightly Campout' + +description = "When the Octopod's waterworks are flooded with frightened Humuhumu fish, the Octonauts have to find a way to flush them out!" + +episodeName = GetEpisodeName(subtitle, 'Mike the Knight') + +result = FindEpisode(showId, episodeName) +#result = FindEpisodeByDescription(showId, description) +print result[0] +print result[1] \ No newline at end of file