Skip to content

Instantly share code, notes, and snippets.

@raindropworks
Forked from onedr0p/simple_convert.py
Last active July 14, 2016 00:18
Show Gist options
  • Save raindropworks/5e9f7812f1745f26af18b4e19dc3f107 to your computer and use it in GitHub Desktop.
Save raindropworks/5e9f7812f1745f26af18b4e19dc3f107 to your computer and use it in GitHub Desktop.
A simple script to convert media files to MP4 for a better Plex experiance
import os
import sys
import time
import platform
import subprocess
import urllib2
import logging
""" Are we windoze or linux """
is_windows = any(platform.win32_ver())
""" Edit the following values to your liking, pay special attention to the media_path, plex_url and plex_token values """
# Paths to ffmpeg, handbrakecli and your log file. If you need help finding your install points in Linux, try 'which ffmpeg' and 'which handbrake'
ffmpeg_cli = 'C:\ffmpeg\bin\ffmpeg.exe' if is_windows else '/usr/bin/ffmpeg'
handbrake_cli = 'C:\Program Files\HandBrake\HandBrakeCLI.exe' if is_windows else '/usr/bin/handbrake'
log_file = os.path.expanduser('~/Desktop/simple_convert.log') if is_windows else os.path.expanduser('~/simple_convert.log')
# Path to your media files (subfolders included)
media_path = '/wash/Movies/Films'
# File types to convert
file_types = ('.avi', '.flv', '.mkv', '.mpeg')
# Plex Server Token - See URL below inorder to obtain your Token
# https://support.plex.tv/hc/en-us/articles/204059436-Finding-your-account-token-X-Plex-Token
plex_url = '{YOUR PLEX IP ADDRESS}:32400'
plex_token = '{YOUR PLEX TOKEN}'
""" Don't change the following unless you know what you are doing!! """
""" Set up the logger """
logging.basicConfig(filename=log_file, level=logging.INFO)
""" Update Plex Server """
def update_plex():
logging.info("Sending request to update Plex")
url = 'http://%s/library/sections/all/refresh?X-Plex-Token=%s' % (plex_url, plex_token)
urllib2.urlopen(url).read()
""" Build a array of files to convert """
def get_media_items():
unconverted = []
for root, dirs, files in os.walk(media_path):
for file in files:
if file.endswith(file_types):
old_file = os.path.join(root, file)
old_file_size = os.path.getsize(old_file)
new_file = os.path.splitext(old_file)[0]+'.mp4'
media_file = {
'old_file': old_file,
'old_file_size': old_file_size,
'new_file': new_file
}
unconverted.append(media_file)
return unconverted
""" Convert files found to mp4 using ffmeg """
def convert_ffmpeg(input_file, output_file):
logging.info("Converting %s to %s using ffmpeg", input_file, output_file)
try:
subprocess.check_call([
ffmpeg_cli,
'-n',
'-fflags', '+genpts',
'-i', input_file,
'-vcodec', 'copy',
'-acodec', 'aac',
'-strict', '-2',
output_file
])
except OSError as e:
if e.errno == os.errno.ENOENT:
logging.warning("Cannot find ffmpeg, please install to use this script")
sys.exit()
""" Convert files found to mp4 using HandBrakeCLI """
def convert_handbrake(input_file, output_file):
logging.info("Converting %s to %s using HandBrakeCLI", input_file, output_file)
try:
subprocess.check_call([
handbrake_cli,
'-i', input_file,
'-o', output_file,
'-f', 'mp4',
'--loose-anamorphic',
'--modulus', '2',
'-e', 'x264',
'-q', '19',
'--cfr',
'-a', '1',
'-E', 'faac',
'-6', 'dp12',
'-R', 'Auto',
'-B', '320',
'-D', '0',
'--gain', '0',
'--audio-copy-mask', 'none',
'--audio-fallback', 'ffac3',
'-x', 'level=4.0:ref=16:bframes=16:b-adapt=2:direct=auto:me=tesa:merange=24:subq=11:rc-lookahead=60:analyse=all:trellis=2:no-fast-pskip=1',
'--verbose=1'
])
except OSError as e:
if e.errno == os.errno.ENOENT:
logging.warning("Cannot find HandBrakeCLI, please install to use this script")
sys.exit()
def remove_media_file(filename):
try:
os.remove(filename)
except OSError as e:
if e.errno != errno.ENOENT:
raise
def main():
media_items = get_media_items()
for item in media_items:
print(item['old_file'])
convert_ffmpeg(item['old_file'], item['new_file'])
new_file_size = os.path.getsize(item['new_file'])
# Remove old file if successful
if (new_file_size >= item['old_file_size']):
logging.info("Converting successful deleting file %s", item['old_file'])
remove_media_file(item['old_file'])
# Remove new file if failure, run handbrake instead
elif (new_file_size < (item['old_file_size'] * .75)):
logging.warning("Converting failure deleting file %s and requesting a conversion using HandBrakeCLI", item['new_file'])
remove_media_file(item['new_file'])
convert_handbrake(item['old_file'], item['new_file'])
# Remove old file if successful
elif (new_file_size < item['old_file_size']):
logging.info("Converting successful deleting file %s", item['old_file'])
remove_media_file(item['old_file'])
update_plex()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment