From 4ffc19bbbb2395b8204b852df325fe4b3c07e273 Mon Sep 17 00:00:00 2001 From: Arjun Satarkar Date: Sat, 21 Dec 2024 16:19:13 +0530 Subject: Add type checking, rework parsing, fix bugs --- rebreak_lines.py | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) (limited to 'rebreak_lines.py') diff --git a/rebreak_lines.py b/rebreak_lines.py index 41594a3..54473e2 100755 --- a/rebreak_lines.py +++ b/rebreak_lines.py @@ -13,7 +13,7 @@ import click import parse_srt import math import sys -from typing import List +import typing # May still be exceeded if there are no word boundaries to wrap at MAX_LINE_LENGTH = 42 @@ -33,21 +33,27 @@ def main(in_file_path: str): def rebreak(text: str) -> str: - get_target_line_num = lambda length: math.ceil(length / MAX_LINE_LENGTH) + get_target_line_num: typing.Callable[[int], int] = lambda length: math.ceil( + length / MAX_LINE_LENGTH + ) text = " ".join(text.split("\n")) target_line_num = get_target_line_num(len(text)) - lines: List[str] = [] + lines: list[str] = [] for _ in range(target_line_num): partition_at = round(len(text) / target_line_num) - 1 # Move to a word boundary + steps_backward = 0 for steps_backward, c in enumerate(text[partition_at::-1]): if c.isspace(): break if partition_at - steps_backward != 0: partition_at -= steps_backward else: + # Moving the partition backward would give us an empty line, so + # move forward instead to ensure we always make progress. + steps_forward = 0 for steps_forward, c in enumerate(text[partition_at:]): if c.isspace(): break -- cgit v1.2.3-57-g22cb