Skip to content

Commit

Permalink
conforms to output of pep8
Browse files Browse the repository at this point in the history
  • Loading branch information
sagargp committed Apr 23, 2012
1 parent ddf2db7 commit f4ee906
Show file tree
Hide file tree
Showing 5 changed files with 133 additions and 123 deletions.
72 changes: 36 additions & 36 deletions EpGuidesParser.py
@@ -1,39 +1,39 @@
import sgmllib


class EpGuidesParser(sgmllib.SGMLParser):

def __init__(self, verbose=0):
sgmllib.SGMLParser.__init__(self, verbose)
self.hyperlinks = []
self.epcsv = ''
self.inside_pre = 0

def parse(self, s):
self.feed(s)
self.close()

def handle_data(self, data):
if self.inside_pre:
self.epcsv = self.epcsv + data

def start_pre(self, attributes):
self.inside_pre = 1

def end_pre(self):
self.inside_pre = 0

def start_a(self, attributes):
for name, value in attributes:
if name == 'href':
self.hyperlinks.append(value)

def get_hyperlinks(self):
return self.hyperlinks

def get_eps_csv(self):
return self.epcsv.splitlines()

def reset_data(self):
self.inside_pre = 0
self.epcsv = ''
self.hyperlinks = []
def __init__(self, verbose=0):
sgmllib.SGMLParser.__init__(self, verbose)
self.hyperlinks = []
self.epcsv = ''
self.inside_pre = 0

def parse(self, s):
self.feed(s)
self.close()

def handle_data(self, data):
if self.inside_pre:
self.epcsv = self.epcsv + data

def start_pre(self, attributes):
self.inside_pre = 1

def end_pre(self):
self.inside_pre = 0

def start_a(self, attributes):
for name, value in attributes:
if name == 'href':
self.hyperlinks.append(value)

def get_hyperlinks(self):
return self.hyperlinks

def get_eps_csv(self):
return self.epcsv.splitlines()

def reset_data(self):
self.inside_pre = 0
self.epcsv = ''
self.hyperlinks = []
26 changes: 16 additions & 10 deletions EpGuidesSearch.py
@@ -1,6 +1,10 @@
import sgmllib, urllib, json, re, time, socket
import urllib
import json
import time
import socket
from EpGuidesParser import EpGuidesParser


class EpGuidesSearch:
def __init__(self, title, debugfile='debug.log', debug=False, verbose=False):
self.title = title
Expand All @@ -21,16 +25,17 @@ def debug(self, str):

if self.doDebug:
self.debughandle.write(out)

if self.verbose:
print out,

def getEpisodes(self):
if self.cache.has_key(self.title):
if self.title in self.cache:
self.debug('Returning cached data...')
return self.cache[self.title]

query = {"q": "allintitle: site:epguides.com %s" % self.title, "userip": socket.gethostbyname(socket.gethostname())}
query = {"q": "allintitle: site:epguides.com %s" % self.title,
"userip": socket.gethostbyname(socket.gethostname())}
search_url = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s" % urllib.urlencode(query)

self.debug('Searching for show at %s' % search_url)
Expand All @@ -40,7 +45,7 @@ def getEpisodes(self):
results = json.loads(json_results)
page.close()

if results['responseStatus'] == 200 and results['responseData']['cursor'].has_key('estimatedResultCount'):
if results['responseStatus'] == 200 and 'estimatedResultCount' in results['responseData']['cursor']:
self.epguides_url = results['responseData']['results'][0]['url']
else:
self.debug('Show not found! Dumping search results object:')
Expand All @@ -62,9 +67,10 @@ def getEpisodes(self):
break

if csv_link == '':
self.debug('Error! Can\'t find CSV listing for %s at %s! Bailing out...' % (self.title, self.epguides_url))
self.debug('Error! Can\'t find CSV listing for %s at %s! Bailing out...' % (self.title,
self.epguides_url))
return None

self.debug('Downloading show data...')
page = urllib.urlopen(csv_link)
parser.reset_data()
Expand All @@ -86,7 +92,7 @@ def getEpisodes(self):

for key in range(0, len(headers)):
rowdict[headers[key]] = row[key]

eps.append(rowdict)

self.debug('Done')
Expand All @@ -95,10 +101,10 @@ def getEpisodes(self):

def search(self, season, ep):
results = []

if self.getEpisodes():
for episode in self.cache[self.title]:
if episode['season'] == season and episode['episode'] == ep:
results.append(episode)

return results
41 changes: 0 additions & 41 deletions README

This file was deleted.

107 changes: 76 additions & 31 deletions automover.py
@@ -1,20 +1,51 @@


if __name__ == '__main__':
from editDistance import editDistance
from EpGuidesSearch import EpGuidesSearch
import re, os, sys, argparse, ConfigParser

argparser = argparse.ArgumentParser(description='Automatically rename and move TV shows')
argparser.add_argument('searchpath', nargs=1, help='The file or directory to process')
argparser.add_argument('--conf', nargs=1, help='Path to the config file', default='/home/sagar/Projects/Github/tvrenamer/automover.conf')
argparser.add_argument('--confirm', action='store_true', help='Ask before doing anything')
argparser.add_argument('--debug', nargs=1, help='Write output to a debug files')
argparser.add_argument('--forcetitle', nargs=1, help='Force a TV show match')
argparser.add_argument('--inplace', action='store_true', help='Rename files in place')
argparser.add_argument('--read', action='store_true', help='Take filenames from STDIN')
argparser.add_argument('--script', nargs='?', help='Write a bash script')
argparser.add_argument('--verbose', action='store_true', help='Verbose output')
import re
import os
import sys
import argparse
import ConfigParser

argparser = argparse.ArgumentParser(
description='Automatically rename and move TV shows')

argparser.add_argument('searchpath',
nargs=1,
help='The file or directory to process')

argparser.add_argument('--conf',
nargs=1,
help='Path to the config file',
default='/etc/automover.conf')

argparser.add_argument('--confirm',
action='store_true', help='Ask before doing anything')

argparser.add_argument('--debug',
nargs=1,
help='Write output to a debug files')

argparser.add_argument('--forcetitle',
nargs=1,
help='Force a TV show match')

argparser.add_argument('--inplace',
action='store_true',
help='Rename files in place')

argparser.add_argument('--read',
action='store_true',
help='Take filenames from STDIN')

argparser.add_argument('--script',
nargs='?',
help='Write a bash script')

argparser.add_argument('--verbose',
action='store_true',
help='Verbose output')

args = argparser.parse_args(sys.argv[1:])

config = ConfigParser.RawConfigParser()
Expand All @@ -29,7 +60,7 @@

dest = config.get('main', 'destination')
path = args.searchpath[0]

dictionary = []
for file in os.listdir(dest):
dictionary.append(file)
Expand All @@ -38,15 +69,19 @@
titlecache = dict()
destpathcache = dict()

pattern_regs = [re.compile(config.get('patterns', x), flags=re.IGNORECASE) for x in patterns]
pattern_regs = [re.compile(config.get('patterns', x), flags=re.IGNORECASE)
for x in patterns]

exc = re.compile(config.get('patterns', 'exclude'), flags=re.IGNORECASE)

def getYesNo(str):
while True:
yn = raw_input(str)

if (yn == 'y'): return True
elif (yn == 'n'): return False

if (yn == 'y'):
return True
elif (yn == 'n'):
return False

print "Please answer 'y' or 'n'"

Expand All @@ -57,7 +92,7 @@ def getEpisodeTitle(dictionary, name):
match = editDistance(name, file)
if match < mindist or mindist is None:
mindist = match
bestMatch = file
bestMatch = file
return bestMatch

def doRename(root, file):
Expand All @@ -70,7 +105,8 @@ def doRename(root, file):
p = None
for pattern in pattern_regs:
p = pattern.search(file)
if p != None: break
if p != None:
break

if p == None:
return
Expand All @@ -88,26 +124,35 @@ def doRename(root, file):
episode = groups[2].lstrip('0')

# use a cache to avoid repeating searches
if titlecache.has_key(title):
if title in titlecache:
bestMatch = titlecache[title]
else:
bestMatch = getEpisodeTitle(dictionary, title)
titlecache[title] = bestMatch
if showcache.has_key(bestMatch):

if bestMatch in showcache:
show = showcache[bestMatch]
else:
show = EpGuidesSearch(bestMatch, debugfile=debugfile, debug=(args.debug is not None), verbose=args.verbose)
show = EpGuidesSearch(bestMatch,
debugfile=debugfile,
debug=(args.debug is not None),
verbose=args.verbose)
showcache[bestMatch] = show

# search epguides.com for the specific episode
result = show.search(season, episode)

if len(result) == 0:
print 'No results for %s Season %s episode %s' % (bestMatch, season, episode)
print 'No results for %s Season %s episode %s' % (bestMatch,
season,
episode)
return

newname = "%s S%02dE%02d %s.%s" % (bestMatch, int(season), int(episode), result[0]['title'].lstrip('"').rstrip('"'), groups[-1])
newname = "%s S%02dE%02d %s.%s" % (bestMatch,
int(season),
int(episode),
result[0]['title'].strip('"'),
groups[-1])

destpath = "%s/%s/Season %s" % (dest, bestMatch, season)
destination = "%s/%s" % (destpath, newname)
Expand All @@ -124,8 +169,8 @@ def doRename(root, file):
if args.script:
s = open(args.script, 'a')
cmd = '# %s' % newname
if not destpathcache.has_key(destpath):

if destpath not in destpathcache:
destpathcache[destpath] = False

if not os.path.isdir(destpath) and not destpathcache[destpath]:
Expand All @@ -137,7 +182,7 @@ def doRename(root, file):
else:
if not os.path.isdir(destpath):
os.mkdir(destpath)
os.rename(fullpath, destination)
os.rename(fullpath, destination)

if args.read:
for file in sys.stdin.read().splitlines():
Expand Down
10 changes: 5 additions & 5 deletions editDistance.py
@@ -1,5 +1,5 @@
def editDistance(s1, s2):
from numpy import zeros
from numpy import zeros

m = zeros([len(s1), len(s2)], int)
m[0, 0] = 0
Expand All @@ -12,12 +12,12 @@ def editDistance(s1, s2):

for i in range(1, len(s1)):
for j in range(1, len(s2)):
if s1[i-1] == s2[j-1]:
m[i, j] = m[i-1, j-1]
if s1[i - 1] == s2[j - 1]:
m[i, j] = m[i - 1, j - 1]
else:
m[i, j] = 1 + min(m[i, j-1], m[i-1, j], m[i-1, j-1])
m[i, j] = 1 + min(m[i, j - 1], m[i - 1, j], m[i - 1, j - 1])

return m[len(s1)-1, len(s2)-1]
return m[len(s1) - 1, len(s2) - 1]


if __name__ == '__main__':
Expand Down

0 comments on commit f4ee906

Please sign in to comment.