Script for manual process for utorrent-postprocess/AMC Script

Running FileBot from the console, Groovy scripting, shell scripts, etc
Post Reply
abedecain
Posts: 2
Joined: 10 Jul 2019, 12:34

Script for manual process for utorrent-postprocess/AMC Script

Post by abedecain »

So I have just wrote some simple python scripts to manually run the utorrent-postprocess/AMC Script. This probs already exsists/is stupid, but I thought id share it just incase. I use qtorrent so its slightly different.

Heres the code for the sorting, specify a folder and it will go through each folder and each file on the 'fileformats' variable, run 'sort.py -h' for more info

Code: Select all

import os
import sys
import argparse
from datetime import datetime


set_type = ''
fileformats = ['.mp4', '.m4a', '.m4v', '.f4v', '.f4a', '.mkv', '.mk4', '.m4b', '.m4r', '.f4b', '.mov', '.3gp', '.3gp2', '.3g2', '.3gpp', '.3gpp2', '.ogg', '.oga', '.ogv', '.ogx', '.wmv', '.wma', '.asf', '.webm', '.flv']
set_dir = ''
set_log_fldr = 'Logs'

prog = r'C:\path\to\utorrent-postprocess.py'

log = None

def main():
    args = args_interp()
    arg_fn = args.root
    arg_test = args.test
    script_path = os.path.dirname(os.path.realpath(__file__))
    
    if args.root:
        dir = args.root
    elif set_dir: 
        dir = set_dir;
    else:
        dir = script_path;
    
    if args.type:
        type = args.type
    elif set_type: 
        type = set_type;
    else:
        type = 'TV';
    
    init_log(script_path,type)
    
    for filename in os.listdir(dir):
        error_msg = ''
        file_path = dir + '\\' + filename
        if os.path.isfile(file_path):
            if any(substring in filename for substring in fileformats):
                cmd = prog + ' "' + type + '" "5" "' + filename + '" "single" "" "' + file_path + '" "move"'
                print('File: ' + filename)
                print('cmd: ' + cmd)
                write_log('cmd: ' + cmd)
                if not (arg_test):
                    os.system(cmd)
            else:
                error_msg = 'err type: ' + filename
                print(error_msg)
                write_log(error_msg)
        elif os.path.isdir(file_path):
            cmd = prog + ' "' + type + '" "5" "' + filename + '"   "multi" "" "' + file_path + '" "move"'
            print('Folder: ' + filename)
            print('cmd: ' + cmd)
            write_log('cmd: ' + cmd)
            if not (arg_test):
                os.system(cmd)
        else: 
            error_msg = 'err excptn: ' + file_path
            print(error_msg)
            write_log(error_msg)
    close_log(log)
            
def args_interp():
    parser = argparse.ArgumentParser(description='Process files for python script by directory')
    parser.add_argument('-r -root -dir', dest='root', metavar='DIR', type=str, default='', help='Set root directory for itteration')
    parser.add_argument('-t -type', dest='type', metavar='TYPE', type=str, default='', help='Set type of file')
    parser.add_argument('--t --test', dest='test', action='store_true', help='Run test without calling program')

    return parser.parse_args()

def init_log(dir,type):
    now = datetime.now()
    log_fn = type + ' ' + now.strftime('%y-%m-%d') + '.log'
    log_fldr = dir + '\\' + set_log_fldr
    if not os.path.isdir(log_fldr):
        os.mkdir(log_fldr)
    log_path = log_fldr + '\\' + log_fn;
    global log
    log = open(log_path, 'a+')

def write_log(txt):
    log.write(txt + '\n')
    
def close_log(log):
    log.close();
main()

Here is my modified utorrent-postprocess script, it varies somewhat from the original, extra argument for process type, dynamic label processing (so it can accept sublabels like 'TV/RSS/Test' and custom folders for TV and Movies, as for movies, I'm british and call them films, with TV, I like to have the year with the name, and the name on the file itself.

Code: Select all

# Run Program: 
# "C:\path\to\utorrent-postprocess.py"  "%L" "" "%N" "multi" "" "%F" "duplicate"
#
# Test with Console:
# python "C:\path\to\utorrent-postprocess.py" "Movie" "" "Avatar" "multi" "" "X:\Files\Avatar" "duplicate"

from datetime import datetime
import sys
import subprocess


# configuration
output = 'D:/Media'
sudo_movie = ['movie','film']
sudo_tv = ['show','tv','series']
sudo_anime = ['anime']
sudo_music = ['music']

# custom formats (use / instead of \ as directory separator)
#movieFormat  = '''{plex}'''
#seriesFormat = '''{plex}'''
movieFormat = '''Films/{n} ({y})/{n} ({y}){' CD'+pi}{'.'+lang}'''
seriesFormat = '''TV/{ny}/{episode.special ? 'Special' : 'Season '+s.pad(2)}/{ny} - {episode.special ? 'S00E'+special.pad(2) : s00e00} - {t.replaceAll(/[`´‘’ʻ]/, /'/).replaceAll(/[!?.]+$/).replacePart(', Part $1')}{'.'+lang}'''
animeFormat  = '''{plex}'''
musicFormat  = '''{plex}'''



# required args
labelin, state, title, kind, file, directory, cmd = sys.argv[1:8]
label=labelin
if any(substr.lower() in labelin.lower() for substr in sudo_movie):
    label="movie"
if any(substr.lower() in labelin.lower() for substr in sudo_tv):
    label="tv"
if any(substr.lower() in labelin.lower() for substr in sudo_anime):
    label="anime"  
if any(substr.lower() in labelin.lower() for substr in sudo_music):
    label="music"
ignore="([^\s]+(\.(?i)(bat))$)"

command = [
	'filebot', '-script', 'fn:amc',
	'--output', output,
	'--action', cmd,
	'--conflict', 'auto',
	'-non-strict',
	'--log-file', output + '/AMC/' + label + '-' + datetime.today().strftime('%Y-%m-%d') + '.log',
	'--def',
		'unsorted=y',
		'music=y',
		'artwork=y',
        'subtitles=en',
        'clean=y',
        'extras=y',
        'minFileSize=0',
        'minLengthMS=0',
        'pushbullet=o.sdfsdfsfefsdfsefsdfsdfsdf',
		'plex=localhost:sdfsdfsfefsdfsefsdfsdfsdf',
		'movieFormat='  + movieFormat,
		'seriesFormat=' + seriesFormat,
		'animeFormat='  + animeFormat,
		'musicFormat='  + musicFormat,
		'ut_label=' + label,
		'ut_state=' + state,
		'ut_title=' + title,
		'ut_kind='  + kind,
		'ut_file='  + file,
		'ut_dir='   + directory,
        'ignore='   + ignore
]


# execute command only for certain conditions (disabled by default)
'''
if state not in ['5', '11']:
	print('Illegal state: %s' % state)
	sys.exit(0)
'''


# execute command (and hide cmd window)
subprocess.run(command, creationflags=0x08000000)
Any feedback or questions are welcome, let me know if this is useful and ill post updates when I do them
abedecain
Posts: 2
Joined: 10 Jul 2019, 12:34

Re: Script for manual process for utorrent-postprocess/AMC Script

Post by abedecain »

Updated version:

Code: Select all

# Run Program: 
# "C:\path\to\utorrent-postprocess.pyw" "%L" "%S" "%N" "%K" "%F" "%D"
#
# Test with Console:
# python "C:\path\to\utorrent-postprocess.pyw" "Movie" "5" "Avatar" "multi" "" "X:\Files\Avatar"

from datetime import datetime
import sys
import subprocess
import os

# configuration
output		  = 'E:/Media'

output_movie	= 'H:/Media/Films'
output_movie_3D = 'H:/Media/Films 3D'
output_tv	   = 'E:/Media/TV'
output_anime	= 'E:/Media/Anime'
output_music	= 'H:/Media/Music'
sudo_movie	  = ['movie','film','movies','films', 'films']
sudo_tv		  = ['show','tv','series','television']
sudo_anime	  = ['anime']
sudo_music	  = ['music']


# custom formats (use / instead of \ as directory separator)
movieFormat = '''{n} ({y})/{n} ({y}){' CD'+pi}{'.'+lang}'''
seriesFormat = '''{ny}/{episode.special ? 'Special' : 'Season '+s.pad(2)}/{ny} - {episode.special ? 'S00E'+special.pad(2) : s00e00} - {t.replaceAll(/[`´‘’ʻ]/, /'/).replaceAll(/[!?.]+$/).replacePart(', Part $1')}{'.'+lang}'''
animeFormat  = '''{ny}/{episode.special ? 'Special' : 'Season '+s.pad(2)}/{ny} - {episode.special ? 'S00E'+special.pad(2) : s00e00 } - {'#' + absolute.pad(4)} - {t.replaceAll(/[`´‘’ʻ]/, /'/).replaceAll(/[!?.]+$/).replacePart(', Part $1')}{'.'+lang}'''
musicFormat  = '''{any{albumArtist}{n}{'Various'}}/{any{album+' ('+y+')/'}{album}{'Unknown'}}/{pi.pad(2)+' - '}{t.replaceAll(/[`´‘’ʻ]/, /'/).replaceAll(/[!?.]+$/).replacePart(', Part $1')}'''

# required args
labelin, state, title, kind, file, directory, cmd = sys.argv[1:8]
label=labelin
labelAMC=labelin
output2		 = output + "/" + labelin.lower()
if any(sub_str.lower() in labelin.lower() for sub_str in sudo_movie):
	label="Movie"
	labelAMC="movie"
	output2 = output_movie
	if ("3d" in labelin.lower()):
		output2 = output_movie_3D
if any(sub_str.lower() in labelin.lower() for sub_str in sudo_tv):
	label="TV"
	labelAMC="tv"
	output2 = output_tv
if any(sub_str.lower() in labelin.lower() for sub_str in sudo_anime):
	label="Anime" 
	labelAMC="tv"
	seriesFormat=animeFormat
	output2 = output_anime
if any(sub_str.lower() in labelin.lower() for sub_str in sudo_music):
	label="Music"
	labelAMC="music"
	output2 = output_music
ignore="([^\s]+(\.(?i)(bat))$)"

if not os.path.exists(output2):
	os.makedirs(output2)

if not os.path.exists(output):
	os.makedirs(output)
logdiramc = output + '/AMC'
if not os.path.exists(logdiramc):
	os.makedirs(logdiramc)
logdirlabel = logdiramc + '/' + label
if not os.path.exists(logdirlabel):
	os.makedirs(logdirlabel)
logdir = logdirlabel + '/' + datetime.today().strftime('%Y/%m %b') + '/' 
if not os.path.exists(logdir):
	os.makedirs(logdir)
logname = label + '-' + datetime.today().strftime('%Y-%m-%d') + '.log'
listname = label + '-list.log'

logpath = logdir + logname
listpath = logdir + listname

log = open(listpath, 'a+')
log.write(directory  + " - " + label + '\n')
log.close();

command = [
	'filebot', '-script', 'fn:amc',
	'--output', output2,
	'--action', cmd,
	'--conflict', 'auto',
	'-non-strict',
	'--mapper','AnimeList.AniDB',
	'--log-file', logpath,
	'--def',
		#'animeDB=TheTVDB',
		'unsorted=y',
		'music=y',
		'artwork=y',
		'subtitles=en',
		'clean=y',
		'extras=y',
		'storeReport=' + logdir,
		'minFileSize=0',
		'minLengthMS=0',
		'movieFormat='  + movieFormat,
		'seriesFormat=' + seriesFormat,
		'animeFormat='  + animeFormat,
		'musicFormat='  + musicFormat,
		'ut_label=' + labelAMC,
		'ut_state=' + state,
		'ut_title=' + title,
		'ut_kind='  + kind,
		'ut_file='  + file,
		'ut_dir='   + directory,
		'ignore='   + ignore,
	
]


# execute command only for certain conditions (disabled by default)
'''
if state not in ['5', '11']:
	print('Illegal state: %s' % state)
	sys.exit(0)
'''


# execute command (and hide cmd window)
#subprocess.run(command, creationflags=0x08000000)
subprocess.run(command)
Post Reply