#!/usr/bin/env python3 # pip install tvnamer fuzzywuzzy import os, sys import logging import tvdb_api # use tvnamer import re import html # Need python-levenshtein for faster sequence matching from fuzzywuzzy import fuzz outdir="renamed" ext="mkv" TVNAMER_THETVDB_APIKEY='fb51f9b848ffac9750bada89ecba0225' # https://github.com/dbr/tvnamer/blob/24a9642f261611499a026f95b4fa5496de553e45/tvnamer/main.py#L55 debuglevel=logging.INFO debuglevel=logging.DEBUG logging.basicConfig(level=debuglevel) inparen=re.compile('.*\(([^\)]\+)\)') if len(sys.argv) < 2: logging.error("usage %s SERIES SEASON [EXTENSION [OUTDIR]]" % sys.argv[0]) exit(1) series = sys.argv[1] season = int(sys.argv[2]) if len(sys.argv)>3: ext = sys.argv[3] if len(sys.argv)>4: outdir = sys.argv[4] t=tvdb_api.Tvdb(apikey=TVNAMER_THETVDB_APIKEY) s=t[series][season] logging.info("got %s season %s with %d episodes" % (s.show, season, len(s))) try: os.mkdir(outdir) logging.debug("created output folder %s" % outdir) except OSError: pass count=0 eps = {e['episodeName']: e for e in s.values()} for f in os.listdir("."): title = f.split("- ")[-1].rstrip(".%s" % ext) if f != outdir and f.split(".")[-1] == ext: em = {fuzz.ratio(title, t): t for t in eps.keys()} logging.debug("found %s", em) maxt = em[max(em.keys())] maxe = eps[maxt] clean_title = maxe['episodeName'] logging.debug("found %s", clean_title) episodeNumber = maxe['dvdEpisodeNumber'] if not episodeNumber: episodeNumber = maxe['airedEpisodeNumber'] d = "%s/%s - S%02dE%02d - %s.%s" % (outdir, maxe.season.show['seriesName'], season, episodeNumber, clean_title, ext ) logging.info("%s -> S%02dE%02d " % ( f, season, episodeNumber, )) count += 1 try: os.link(f, d) except OSError as e: logging.warning("%s: %s" % (d, e.strerror)) if count != len(s): logging.warning("processed %d files but expected %d" % (count, len(s)))