Skip to content

Instantly share code, notes, and snippets.

@joshfriend
Last active August 29, 2015 14:00
Show Gist options
  • Save joshfriend/11388397 to your computer and use it in GitHub Desktop.
Save joshfriend/11388397 to your computer and use it in GitHub Desktop.
TV show auto-filer
#!/usr/bin/env python
import os
import re
from path import path
import shutil
import argparse
# Regexp to match show name, season, episode, file ext
SHOW_RE1 = r'(\S+)(\d{4})?.[Ss](\d+)[Ee](\d+).*.(\w{3})'
SHOW_RE2 = r'([a-zA-Z\.]+).(\d{4})?.(\d+)x(\d+).*.(\w{3})'
EXTENSIONS = ['*.mkv', '*.avi', '*.mp4']
def fix_show_name(n):
n = n.replace('S H I E L D', 'S.H.I.E.L.D.')
n = n.replace('US', '')
n = n.replace('UK', '')
n = n.strip()
return n
def format_name(*args):
fmt = '{0} - S{1:02d}E{2:02d}.{3}'
return fmt.format(*args)
def find_episodes(d):
d = path(d)
eps = {}
show_re1 = re.compile(SHOW_RE1)
show_re2 = re.compile(SHOW_RE2)
for ext in EXTENSIONS:
for f in d.walkfiles(pattern=ext):
f = path(f)
# ignore junk
if f.name.startswith('.'):
continue
elif 'sample' in f.name.lower():
continue
elif '.AppleDouble' in f.abspath():
continue
try:
show, yr, season, ep, ext = show_re1.findall(f.name)[0]
except:
try:
show, yr, season, ep, ext = show_re2.findall(f.name)[0]
except:
continue
# Fix weirdness
season = int(season)
ep = int(ep)
show = ' '.join([w.capitalize() for w in show.split('.')])
show = fix_show_name(show)
# Save info by file path
eps[f] = (show, season, ep, ext)
return eps
def file_episodes(eps):
for p, info in eps.iteritems():
show, season, ep, ext = info
src = path(p)
dst = path('tv/{0}/Season {1}/{2}'.format(show, season, format_name(*info)))
dstfolder = dst.dirname()
print('Moving "{0}" -> "{1}"'.format(src, dst))
dstfolder.makedirs_p()
src.move(dst)
if __name__ == '__main__':
try:
d = sys.argv[1]
except:
d = 'seeding/tv'
os.chdir(path(__file__).dirname())
eps = find_episodes(d)
file_episodes(eps)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment