IMDB MKV file renamer: Quick and dirty Python script using IMDbPY and Enzyme.

By isendev.

 Posted on 2014/06/26 23:10.

 Tagged as: programming, python.

This is a quick and dirty Python script to rename video files using IMDb movie info and Matroska meta stream information. It uses my own conventions, but it may be an useful point to start your own script.

The resulting filenames are something like this:

Ocean's Eleven.(2001).x264[1080p].AC3[EN].AC3[ES].SUBS[ES][EN].mkv

To use this script, you must install IMDBpy (to retrieve IMDb movie info) and Enzyme (Matroska meta data parser) Python libraries.

Using pip Python package manager:

sudo pip install IMDbPY

sudo pip install enzyme

<imdbrenamer.py>

#!/usr/bin/python
# IMDB MKV file renamer.
# By: Antonio Perdices.
# Site: https://www.isendev.com
# 26/06/2014

import imdb
import enzyme
import os

# By default access the web.
ia = imdb.IMDb()

# Root directory.
rootdir = '/usbhdd/Unsorted/'

# Get files from directory.
files = os.listdir(rootdir)

# Loop through them.
for file in files:
   
    # Split filename and extension.
    fileName, fileExtension = os.path.splitext(file)
   
    # Process file confirmation.
    inputtext = ''
    while inputtext != 'n' and inputtext != 'y':
        inputtext = raw_input('\nProcessing file ['  + fileName + fileExtension + ']... Continue [y/n]? ')
        # print 'Input text is [' + inputtext + ']'

    # File processing.
    if inputtext == 'y':

        # Set IMBD search string. "Enter" defaults search string to filename.
        f = fileName.split('.')
        searchstring = f[0]
        inputtext = raw_input('IMDB Search String ['  + searchstring + ']: ')
        if len(inputtext) > 0:
            searchstring = inputtext

        # Search.
        print 'Searching IMDB with [' + searchstring + ']...'
        s_result = ia.search_movie(searchstring)

        # Print results.
        index = 1
        print '(0) - ORIGINAL - ' + fileName
        for item in s_result:
            try:
                print '({}) - Year {} - '.format(index, item['year']) + item['title']
            except KeyError:
                print '({}) - '.format(index) + item['title']
            index = index + 1

        # Title selection.
        index = -1
        while index < 0 or index > len(s_result):
            inputtext = raw_input('Select an Title entry [0]: ')
            if len(inputtext) > 0:
                try:
                    index = int(inputtext)
                except ValueError:
                    index = -1
                    # print 'Invalid entry!'
            else:
                index = 0

        # Confirm selected title.
        if index == 0:
            title = f[0]
        else:
            title = s_result[index-1]['title']
            title = title.replace('/', '').replace('\\', '').replace('?', '').replace('*', '')
            title = title.replace('|', '').replace('>', '').replace('<', '').replace(':', '')
        inputtext = raw_input('Title to use ['  + title + ']: ')
        if len(inputtext) > 0:
            title = inputtext
       
        # Confirm selected year.
        year = '2014'
        if index > 0:
            year = s_result[index-1]['year']
        inputtext = raw_input('Year to use [{}]: '.format(year))
        if len(inputtext) > 0:
            year = inputtext

        # Get MKV Info
        streamtags = ''
        try:
            with open(rootdir + file, 'rb') as m:

                print 'Extracting MKV Metadata...'

                mkv = enzyme.MKV(m)

                mkvinfo = ''
               
                # Get video stream info.
                vinfo=''
                if mkv.video_tracks[0].height <= 480:
                    vinfo = '.[DVD]'
                if mkv.video_tracks[0].height > 480:
                    vinfo = '.x264[720p]'
                if mkv.video_tracks[0].height > 720:
                    vinfo = '.x264[1080p]'           

                mkvinfo = 'Video: [' +  mkv.video_tracks[0].codec_id + '][' + '{}'.format(mkv.video_tracks[0].width) + '][' +  '{}'.format(mkv.video_tracks[0].height) + ']'

                # Get audio stream info.
                ainfo = ''
                for atrack in mkv.audio_tracks:
                    ainfo = ainfo + '.' + atrack.codec_id.replace('A_','')               
                    if atrack.language == 'spa' or atrack.language == 'es':
                        ainfo = ainfo + '[ES]'
                    elif atrack.language == 'eng' or atrack.language == 'en':
                        ainfo = ainfo + '[EN]'
                    else:
                        ainfo = ainfo + '[EN]'
                    mkvinfo = mkvinfo + '\nAudio: [' + atrack.codec_id + '][' + (atrack.language if atrack.language else 'None') + ']'


                # Get subtitle stream info.
                sinfo = ''
                for strack in mkv.subtitle_tracks:
                    if sinfo == '':
                        sinfo = '.SUBS'
                    if strack.forced == True:
                        sinfo = sinfo + '[FOR]'
                    elif strack.language == 'spa' or strack.language == 'es':
                        sinfo = sinfo + '[ES]'
                    elif strack.language == 'eng' or strack.language == 'en':
                        sinfo = sinfo + '[EN]'
                    else:
                        sinfo = sinfo + '[EN]'
                    mkvinfo = mkvinfo + '\nSubtitle: [' + strack.codec_id + '][' + (strack.language if strack.language else 'None') + ']'

                # Print stream info.
                print mkvinfo

                # Generate my own stream tags.
                streamtags = vinfo + ainfo + sinfo

                inputtext = raw_input('Use this stream tags ['  + streamtags + ']: ')
                if len(inputtext) > 0:
                    streamtags = '.' + inputtext
       
        except (IOError, enzyme.exceptions.MalformedMKVError):
            print 'No metadata found.'
                   
        # Rename.
        newFileName = title + '.({})'.format(year) + streamtags + fileExtension
        while inputtext != 'n' and inputtext != 'y':
            inputtext = raw_input('Renaming file to ['  + newFileName + ']... Continue [y/n]? ')
        if inputtext == 'y':
            os.rename(rootdir + file, rootdir + newFileName)


Tags
Archives