Skip to content

Instantly share code, notes, and snippets.

@jessielw
Created January 3, 2023 19:02
Show Gist options
  • Save jessielw/88b049951479eb4abd6822d6f2167a6f to your computer and use it in GitHub Desktop.
Save jessielw/88b049951479eb4abd6822d6f2167a6f to your computer and use it in GitHub Desktop.
Script to convert 'tagged' or incorrectly numbered chapters to correctly numbered chapters
from pathlib import Path
from typing import Union
from pymediainfo import MediaInfo
def generate_chapters(mode: str, mode_input: Union[Path, str] = None):
"""
Generate proper chapters with existing timestamps
:param mode: Accepts selection via strings 'chapter_data' or 'parse_file'.
:param mode_input: 'chapter_data' = pymediainfo dictionary of menu data, 'parse_file' = mediafile input
:return: Correctly numbered chapters based off of the input timestamps
"""
# check which mode
if mode == "chapter_data":
mi_parse = mode_input
elif mode == "parse_file":
if not Path(mode_input).is_file():
raise FileNotFoundError("You must pass a media file with mode 'parse_file'")
mi_parse = MediaInfo.parse(Path(mode_input)).menu_tracks[0].to_data()
else:
raise ValueError("'mode' must be equal to 'chapter_data' or 'parse_file'")
# parse file with mediainfo
chapter_starting_index = list(mi_parse.keys()).index("chapters_pos_end") + 1
chapter_timestamps = list(mi_parse.keys())[chapter_starting_index:]
# create chapters
new_chapter_file = ""
for ch_num, ct in enumerate(chapter_timestamps, start=1):
# format timestamps
chap_timestamps_list = ct.replace("_", ":").split(":")
chap_timestamps = "{}:{}:{}".format(
chap_timestamps_list[0],
chap_timestamps_list[1],
chap_timestamps_list[2][:2] + "." + chap_timestamps_list[2][2:],
)
# format chapter numbers
chapter_number = str(ch_num).zfill(2)
# create chapter lines
chapter_line1 = "CHAPTER{}={}".format(chapter_number, chap_timestamps)
chapter_line2 = "CHAPTER{}NAME=Chapter {}".format(
chapter_number, chapter_number
)
# update chapter file
new_chapter_file = (
new_chapter_file + chapter_line1 + "\n" + chapter_line2 + "\n"
)
return new_chapter_file.rstrip()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment