yum-slop/TaSTT

Free self-hosted STT for VRChat.

git clone https://git.yummers.dev/yum-slop/TaSTT

yumEncapsulate paging & text wrapping logicf48ae0f

v0.19.2
2.0 KiB55 linesraw
1#!/usr/bin/env python3
2
3class TextWrapper:
4    def __init__(self, rows, cols):
5        self.rows = rows
6        self.cols = cols
7
8    # Split `msg` along line boundaries. Long words tend to just go onto new
9    # lines. Words that are too long to fit on any line are hyphenated and
10    # split.
11    # Lines are padded with space (" ") characters so they're all `self.cols`
12    # characters long. Pages are padded with lines full of space characters so
13    # they're all `self.rows` lines long.
14    def wrap(self, msg: str) -> list[list[str]]:
15        pages = []
16        lines = []
17        line = ""
18        for word in msg.split():
19            if len(line) + 1 + len(word) <= self.cols:
20                if len(line):
21                    line += " "
22                line += word
23                continue
24            # Word won't fit onto this line. End the line.
25            if len(line):
26                line += " " * (self.cols - len(line))
27                lines.append(line)
28                line = ""
29            while len(word) > self.cols:
30                prefix = word[0:self.cols-1] + "-"
31                lines.append(prefix)
32                suffix = word[self.cols-1:]
33                word = suffix
34            if len(word):
35                line = word
36        if len(line):
37            line += " " * (self.cols - len(line))
38            lines.append(line)
39        while len(lines):
40            pages.append(lines[0:self.rows])
41            lines = lines[self.rows:]
42        if len(pages):
43            num_extra_lines = (self.rows - (len(pages[-1]) % self.rows)) % self.rows
44            pages[-1] += [" " * self.cols] * num_extra_lines
45        return pages
46
47if __name__ == "__main__":
48    w = TextWrapper(2, 5)
49
50    assert(w.wrap("foo") == [["foo  ", "     "]])
51    assert(w.wrap("foo bar") == [["foo  ", "bar  "]])
52    assert(w.wrap("bagel") == [["bagel", "     "]])
53    assert(w.wrap("bagels") == [["bage-", "ls   "]])
54    assert(w.wrap("hot bagels") == [["hot  ", "bage-"], ["ls   ", "     "]])
55