Skip to content

Instantly share code, notes, and snippets.

@nosmokingbandit
Created June 6, 2018 03:34
Show Gist options
  • Save nosmokingbandit/aac5860f859431970a910b679dba9b13 to your computer and use it in GitHub Desktop.
Save nosmokingbandit/aac5860f859431970a910b679dba9b13 to your computer and use it in GitHub Desktop.
Simple tv episode sorting script
'''
Requires packages PTN, tvdb_api
Pass path to download dir/file as arg $1
'''
import PTN
from tvdb_api import tvdb_api
import sys
import os
import shutil
import re
'''
CONFIG:
'''
target_dir = r'/media/TV'
name_format = '{title} [{season}x{episode}] {episodeName}'
delete_after_move = True
'''
/CONFIG
'''
def err(e):
print(e)
with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'err.txt'), 'a+') as f:
f.write(str(e))
f.write('/n')
if not os.path.exists(target_dir):
os.makedirs(target_dir)
elif os.path.isfile(target_dir):
err('Target dir is file, cannot continue.')
sys.exit(1)
tvdb = tvdb_api.Tvdb()
episode_data = {'year': '',
'season': '',
'title': '',
'episode': '',
'episodeName': ''
}
download_dir = sys.argv[1]
def clean_path(s):
return re.sub('[\\/:"*?<>|]+', '_', s)
def episode_file(path):
if os.path.isfile(path):
return path
else:
biggestfile = None
s = 0
try:
for root, dirs, filenames in os.walk(path):
for file in filenames:
f = os.path.join(root, file)
size = os.path.getsize(f)
if size > s:
biggestfile = f
s = size
except Exception as e:
err(e)
raise e
return biggestfile
file = episode_file(download_dir)
if file is None:
err('Unable to determine video file.')
sys.exit(1)
episode_data.update(PTN.parse(os.path.basename(file)))
episode_data.setdefault('year', '')
t = '{} {}'.format(episode_data['title'], episode_data['year'])
try:
ep = tvdb[t][episode_data['season']][episode_data['episode']]
for i in ep:
episode_data[i] = ep[i]
except Exception as e:
pass
for k, v in episode_data.items():
if type(v) == str:
episode_data[k] = v.title()
renamed_file = clean_path(name_format.format(**episode_data) + os.path.splitext(file)[1]).replace(' ', ' ')
try:
shutil.move(file, os.path.join(target_dir, renamed_file))
except Exception as e:
err(e)
raise e
if delete_after_move and os.path.isdir(download_dir):
shutil.rmtree(download_dir)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment