Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save JySzE/af47980b23dec457a5d0ded74d5e9180 to your computer and use it in GitHub Desktop.
Save JySzE/af47980b23dec457a5d0ded74d5e9180 to your computer and use it in GitHub Desktop.

How to Offset Chapter Timecodes Using Python

This script processes XML files in a specified directory, adjusting the chapter start times based on a user-defined offset. It reads the XML files, identifies <ChapterTimeStart> tags, and updates their time values accordingly.

Here’s a step-by-step guide on how to use the script:

Prerequisites

  1. Python 3.x: The script is written in Python and requires Python 3.x to run.
  2. XML Files: The script is designed to work with XML files that contain chapter timecodes in the <ChapterTimeStart> tags.
  3. Text Editor: You can edit the script with any text editor, like VSCode or Sublime.

Script Overview

The script performs the following actions:

  1. Reads XML Files: It processes each XML file in the specified directory.
  2. Finds <ChapterTimeStart> Tags: It looks for the timecodes inside <ChapterTimeStart> tags.
  3. Adjusts Timecode: The script adjusts the timecode by adding or subtracting the user-specified offset.
  4. Saves the Updated XML Files: It saves the modified XML files into a new output directory within the original directory.

How to Use the Script

Step 1: Set Up Your Files

Place all your XML files (which contain the chapter timecodes) in a directory on your computer.

Let’s assume this directory is /DIR/HERE/.

Step 2: Save and Modify the Script

Copy and save the provided script as XML_ChapterOffsetScript.py Open the script file, XML_ChapterOffsetScript.py, and modify the following lines to suit your needs:

  • Directory Path: In the line where the directory is defined (directory = r'/DIR/HERE/'), replace /DIR/HERE/ with the actual path to your directory containing the XML files.

  • Offset: Set the desired time offset in seconds by modifying the offset variable. Use a positive value to add time, or a negative value to subtract time from the timecodes. For example:

    • offset = -1 will subtract 1 second from each timecode.
    • offset = 60 will add 1 minute to each timecode.

Step 3: Run the Script

  1. Open a terminal or command prompt.
  2. Navigate to the folder where the script is located.
  3. Run the script with Python:
    python XML_ChapterOffsetScript.py
    

Step 4: Review the Output

After running the script, a new directory called output will be created inside your original directory. This folder will contain the updated XML files with the adjusted chapter start times.

Script Details

Here is the complete script:

import os
from datetime import timedelta
import re

def parse_timecode(timecode):
    h, m, s = timecode.split(':')
    s, ns = s.split('.')
    return timedelta(hours=int(h), minutes=int(m), seconds=int(s), microseconds=int(ns[:6]))

def format_timecode(td):
    total_seconds = td.total_seconds()
    h = int(total_seconds // 3600)
    m = int((total_seconds % 3600) // 60)
    s = int(total_seconds % 60)
    ns = int(td.microseconds * 1000)
    return f"{h:02}:{m:02}:{s:02}.{ns:09}"

def process_directory(directory, offset):
    output_directory = os.path.join(directory, 'output')
    os.makedirs(output_directory, exist_ok=True)

    for filename in os.listdir(directory):
        if filename.endswith(".xml"):
            file_path = os.path.join(directory, filename)
            output_path = os.path.join(output_directory, filename)
            
            with open(file_path, 'r', encoding='utf-8') as file:
                lines = file.readlines()

            with open(output_path, 'w', encoding='utf-8') as file:
                for line in lines:
                    if "<ChapterTimeStart>" in line:
                        timecode_match = re.search(r'(\d{2}:\d{2}:\d{2}\.\d{9})', line)
                        if timecode_match:
                            timecode = timecode_match.group(1)
                            if timecode != "00:00:00.000000000":
                                new_timecode = parse_timecode(timecode) + timedelta(seconds=offset)
                                if new_timecode.total_seconds() < 0:
                                    new_timecode = timedelta(seconds=0)
                                new_timecode_str = format_timecode(new_timecode)
                                line = line.replace(timecode, new_timecode_str)
                    file.write(line)

# Set the directory containing the XML files
directory = r'/DIR/HERE/'

# Set the offset in seconds (use a negative value to reduce time)
offset = -1

process_directory(directory, offset)

Example

Before running the script:

An XML file may contain a timecode like:

<ChapterTimeStart>00:10:00.789733334</ChapterTimeStart>

After running the script with an offset of -1 second:

The timecode will be adjusted to:

<ChapterTimeStart>00:09:59.789733000</ChapterTimeStart>

Conclusion

This script is a simple and efficient way to adjust chapter start times in multiple XML files by a specified offset. It saves you time by automating the process for all XML files in a given directory. Just adjust the directory path and offset, run the script, and review the output in the output folder!

Enjoy!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment