Last active
May 23, 2019 13:16
-
-
Save beledouxdenis/0f8316228d6832cbba22e2b12436dc03 to your computer and use it in GitHub Desktop.
Sort automatically videos folder into Movies / TV Shows folders with season hierarchy, using symlinks, then update the library on Kodi.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python3 | |
import os | |
import re | |
import requests | |
import subprocess | |
from Levenshtein import distance | |
DOWNLOAD_DIR = '/media/Downloads/' | |
MOVIES_DIR = os.path.expanduser('~/Movies/') | |
SHOWS_DIR = os.path.expanduser('~/TV Shows/') | |
if not os.path.exists(MOVIES_DIR): | |
os.makedirs(MOVIES_DIR) | |
if not os.path.exists(SHOWS_DIR): | |
os.makedirs(SHOWS_DIR) | |
def is_video(file): | |
return file.split('.')[-1] in ['avi', 'mkv', 'mp4', 'srt'] | |
for directory in [MOVIES_DIR, SHOWS_DIR]: | |
subprocess.call('rm -rf "' + directory + '"*', shell=True) | |
shows = [] | |
for root, dirs, files in os.walk(DOWNLOAD_DIR): | |
for filename in files: | |
if is_video(filename): | |
directory = os.path.join(MOVIES_DIR, filename) | |
seasons = [] | |
for regex in [r'(S\d{1,2})', r'((?:Saison|Season)\s*(?:\d{1,2}))', r'(\d{1,2}x\d{1,2})']: | |
match = re.search(regex, filename, re.IGNORECASE) | |
if match: | |
seasons.append(match.groups()[0]) | |
if seasons: | |
show_name = filename | |
for season in seasons: | |
show_name = show_name.split(season)[0] | |
show_name = show_name.replace('.', ' ').strip("- ") | |
year = re.search('(.*)((?:19|20)[0-9][0-9])$', show_name) | |
if year: | |
show_name = year.groups()[0] | |
# Remove [ Torrent9 TV] | |
show_name = re.sub(r'\[.*\]', '', show_name) | |
# Title-ize, but do not use .title() otherwise 'FBI' is changed to 'Fbi' | |
show_name = ' '.join(s[0].upper() + s[1:] for s in show_name.split()) | |
for show in shows: | |
if distance(show.lower(), show_name.lower()) <= 2: | |
show_name = show | |
break | |
else: | |
shows.append(show_name) | |
show_season = int(re.findall(r'\d+', seasons[0])[0]) | |
show_directory = '%s/Season %s/' % (show_name, show_season) | |
directory = os.path.join(SHOWS_DIR, show_directory) | |
if not os.path.isdir(directory): | |
os.makedirs(directory) | |
if is_video(filename): | |
subprocess.call(['ln', '-sf', os.path.join(root, filename), os.path.join(directory, filename)]) | |
else: | |
subprocess.call(['ln', '-sf', os.path.join(root, filename), directory]) | |
params = {'jsonrpc': '2.0', 'method': "VideoLibrary.Scan", 'id': 'raspbian'} | |
requests.post('http://localhost:8080/jsonrpc', json=params) | |
params['method'] = "VideoLibrary.Clean" | |
requests.post('http://localhost:8080/jsonrpc', json=params) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment