Skip to content

re_chapters

re_chapters

re_chapters(episodes: tuple[Path], config: Path) -> None

Replaces chapter names in episodes with names from a config file.

Source code in src/encode_utils_cli/re_chapters.py
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
@click.command()
@click.argument(
    "episodes",
    nargs=-1,
    required=True,
    type=click.Path(exists=True, dir_okay=False, path_type=Path),
)
@click.option(
    "-c",
    "--config",
    required=True,
    type=click.Path(exists=True, dir_okay=False, path_type=Path),
    help="Config in YAML format.",
)
def re_chapters(episodes: tuple[Path], config: Path) -> None:
    """Replaces chapter names in episodes with names from a config file."""
    names = safe_load(config.read_text())

    for ep in episodes:
        chapters = ep.read_text()
        chap_count = len(findall(r"(NAME=)", chapters))
        zero_chap = findall(r"(CHAPTER00NAME=)", chapters)
        pad = 0 if zero_chap else 1

        for i in range(chap_count):
            chapters = sub_chapter(
                chapters=chapters,
                num=i + pad,
                name=names[chap_count][i],
            )

        ep.write_text(chapters)

sub_chapter

sub_chapter(chapters: str, num: int, name: str) -> str

Replace chapter name.

Source code in src/encode_utils_cli/re_chapters.py
42
43
44
def sub_chapter(chapters: str, num: int, name: str) -> str:
    """Replace chapter name."""
    return sub(rf"(CHAPTER{num:02d}NAME=)(.*)", rf"\1{name}", chapters)