mkv_split.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import os
  2. import sys
  3. import subprocess
  4. import shutil
  5. def load_csv(filename):
  6. scenes = []
  7. with open(filename) as f:
  8. lines = f.readlines()
  9. for line in lines[2:]:
  10. scene, frame, timecode, start_time_s, duration_s = line.split(',')
  11. scenes.append((int(scene)+1, timecode))
  12. return scenes
  13. def load_enabled_scenes(basename, num_total_scenes):
  14. res = set()
  15. for i in range(num_total_scenes):
  16. if os.path.exists('%s.Scene-%i-IN.jpg' % (basename, i+1)):
  17. res.add(i+1)
  18. return res
  19. def detect(input_file, threshold):
  20. call = ['scenedetect', '-i', input_file, '-co', '%s.csv' % input_file, '-d', 'content', '-si', '-t', threshold]
  21. raw_input('Press enter to execute %s ...' % call)
  22. subprocess.call(call)
  23. if raw_input('Change threshold? [y/N]') == 'y':
  24. threshold = raw_input('Enter threshold: ')
  25. return detect(input_file, threshold)
  26. print 'Done. Find the scene screen captures and delete any false positive IN.jpg files, then run the split command when done.'
  27. def copy_xmp_file(input_file):
  28. xmp_file = '%s.xmp' % input_file
  29. if not os.path.exists(xmp_file):
  30. return
  31. cwd = os.getcwd()
  32. for f in os.listdir(cwd):
  33. if f.startswith(input_file.replace('.mkv', '')) and f.endswith('.mkv') and f != input_file:
  34. shutil.copyfile(xmp_file, '%s.xmp' % f)
  35. def split(input_file):
  36. scenes = load_csv('%s.csv' % input_file)
  37. enabled_scenes = load_enabled_scenes(input_file, len(scenes))
  38. cuts = []
  39. for scene, timecode in scenes:
  40. if scene in enabled_scenes:
  41. cuts.append(timecode)
  42. print 'mkvmverge scene %i: scenedetect scene %i (%s)' % (len(cuts)+1, scene, timecode)
  43. call = ['mkvmerge', '-o', input_file.replace('.mkv', '-split.mkv'), '--split', 'timecodes:%s' % ','.join(cuts), input_file]
  44. raw_input('Press enter to execute %s ...' % call)
  45. subprocess.call(call)
  46. copy_xmp_file(input_file)
  47. print 'Done.'
  48. if __name__ == '__main__':
  49. if len(sys.argv) < 2 or sys.argv[1] not in ('detect', 'split'):
  50. print 'Usage: mkv_split.py [detect|split] <input file> [<detection threshold>]'
  51. if sys.argv[1] == 'detect':
  52. detect(sys.argv[2], sys.argv[3])
  53. elif sys.argv[1] == 'split':
  54. split(sys.argv[2])