Skip to content

Instantly share code, notes, and snippets.

@enosh
Last active March 17, 2018 23:53
Show Gist options
  • Select an option

  • Save enosh/d368dc92e98b6cbd13daec3917ed1649 to your computer and use it in GitHub Desktop.

Select an option

Save enosh/d368dc92e98b6cbd13daec3917ed1649 to your computer and use it in GitHub Desktop.
Generate a chapters file for `mp4chaps` from `.mp3` files in the current directory or the one passed as its first argument.
# -*- coding: utf-8 -*-
import sys, re
from datetime import timedelta
from os import listdir, getcwd
from os.path import isfile, join
from mutagen.mp3 import MP3
EXTENSION = ".mp3"
# RE to extract chapter names (name being the first capture group.)
REGEX = r'Chapter \d{1,2} - (.+)(' + EXTENSION + ')'
# REGEX = r'CH\d{2}(.+)(' + EXTENSION + ')'
try:
directory = sys.argv[1]
except IndexError:
directory = getcwd()
result = ""
def get_dir_files(path):
return sorted(filter(lambda x: isfile(join(path, x)), listdir(path)))
def get_dir_files_with_ext(path, ext):
files = get_dir_files(path)
return filter(lambda x: True if ext in x else False, get_dir_files(path))
running_total = timedelta(seconds=0)
for i, file in enumerate(get_dir_files_with_ext(directory, EXTENSION), start=1):
chapter_name = re.sub(REGEX, r'\1', file)
hours = running_total / timedelta(hours=1) # done so to support files longer than 24 hours
msms = str(running_total % timedelta(hours=1))[2:]
file_length = timedelta(seconds=MP3(file).info.length)
result += "%d:%s Chapter %d\n" % (hours, msms, i)
running_total += file_length
result = re.sub(r'^(\d{1}):', r'0\1:', result, flags=re.MULTILINE)
result = re.sub(r'(\.\d{3})\d{3}', r'\1', result, flags=re.MULTILINE)
result = re.sub(r'(\d{2}:\d{2}:\d{2}) ', r'\1.000 ', result, flags=re.MULTILINE)
print(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment