import os import sys import subprocess import shutil def load_drop_list(): if not os.path.exists('drop.list'): print 'drop.list not found' return set() else: with open('drop.list') as f: res = {int(x) for x in f.readlines()} print 'Loaded %i entries from drop.list' % len(res) return res def load_csv(filename): scenes = [] with open(filename) as f: lines = f.readlines() for line in lines[2:]: scene, frame, timecode, start_time_s, duration_s = line.split(',') scenes.append((int(scene)+1, timecode)) return scenes def load_enabled_scenes(basename, num_total_scenes): res = set() for i in range(num_total_scenes): if os.path.exists('%s.Scene-%i-IN.jpg' % (basename, i+1)): res.add(i+1) return res def detect(input_file, threshold): call = ['scenedetect', '-i', input_file, '-co', '%s.csv' % input_file, '-d', 'content', '-si', '-t', threshold] raw_input('Press enter to execute %s ...' % call) subprocess.call(call) if raw_input('Change threshold? [y/N]') == 'y': threshold = raw_input('Enter threshold: ') return detect(input_file, threshold) print 'Done. Find the scene screen captures and delete any false positive IN.jpg files, then run the split command when done.' def copy_xmp_file(input_file): xmp_file = '%s.xmp' % input_file if not os.path.exists(xmp_file): return cwd = os.getcwd() for f in os.listdir(cwd): if f.startswith(input_file.replace('.mkv', '')) and f.endswith('.mkv') and f != input_file: shutil.copyfile(xmp_file, '%s.xmp' % f) def split(input_file): scenes = load_csv('%s.csv' % input_file) enabled_scenes = load_enabled_scenes(input_file, len(scenes)) drops = load_drop_list() to_delete = set() cuts = [] for scene, timecode in scenes: if scene in enabled_scenes: cuts.append(timecode) print 'mkvmverge scene %i: scenedetect scene %i (%s)' % (len(cuts)+1, scene, timecode) if scene in drops: to_delete.add('%s-split-%03d.mkv' % (input_file.replace('.mkv', ''), len(cuts)+1)) print 'delete: %s' % to_delete call = ['mkvmerge', '-o', input_file.replace('.mkv', '-split.mkv'), '--split', 'timecodes:%s' % ','.join(cuts), input_file] raw_input('Press enter to execute %s ...' % call) subprocess.call(call) for f in to_delete: if os.path.exists(f): os.remove(f) else: print 'Could not find %s' % f copy_xmp_file(input_file) print 'Done.' if __name__ == '__main__': if len(sys.argv) < 2 or sys.argv[1] not in ('detect', 'split'): print 'Usage: mkv_split.py [detect|split] []' if sys.argv[1] == 'detect': detect(sys.argv[2], sys.argv[3]) elif sys.argv[1] == 'split': split(sys.argv[2])