yum-slop/TaSTT

Free self-hosted STT for VRChat.

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

yumBegin work on C++ custom chatboxf7d7858

v0.19.2
5.7 KiB149 linesraw
1#!/usr/bin/env python3
2
3import argparse
4import os
5import pickle
6import sys
7
8from math import floor
9from PIL import Image
10from typing import Any, Dict, List, Tuple
11
12# The character range [0x0000, 0xDFFF] is reserved for text.
13# The range [0xE000, infinity) is left over for emotes.
14EMOTES_LETTER_OFFSET = 0xE000
15EMOTES_HEIGHT = 512
16EMOTES_TEX_SZ = 4096
17
18def superimpose_image(base_img: Image, overlay_img: Image, position: Tuple[int, int]) -> Image:
19    base_img.paste(overlay_img, position, overlay_img)
20    return base_img
21
22def i_to_pos(i, sm_wd, sm_ht, big_wd, big_ht) -> Tuple[int, int]:
23    x = i * sm_wd % big_wd
24    row = floor((i * sm_wd) / big_wd)
25    y = row * sm_ht
26    return int(x), int(y)
27
28def get_images_from_directory(directory_path: str) -> List[Tuple[Any, str]]:
29    images = []
30    for filename in os.listdir(directory_path):
31        file_path = os.path.join(directory_path, filename)
32        if os.path.isfile(file_path) and file_path.endswith(".png"):
33            image = Image.open(file_path).convert("RGBA")
34            name = os.path.basename(filename).split('.')[0]
35            images.append((image, name))
36    return images
37
38def split_resized_image(img, wd: int, ht: int) -> List[Any]:
39    aspect_ratio = img.width / img.height
40    width = int(ht * aspect_ratio)
41    img = img.resize((width, ht))
42
43    split_images = []
44    for i in range(0, img.width, wd):
45        split_image = img.crop((i, 0, i + wd, ht))
46        split_images.append(split_image)
47
48    return split_images
49
50def resize_image_with_aspect_ratio(img: Image, aspect_ratio: float) -> Image:
51    original_width, original_height = img.size
52    new_width = int(original_height * aspect_ratio)
53    new_height = original_height
54    return img.resize((new_width, new_height))
55
56def resize_image_to_height(img: Image, height: int) -> Image:
57    aspect_ratio = img.width / img.height
58    new_width = int(height * aspect_ratio)
59    return img.resize((new_width, height))
60
61class EmotesState:
62    def __init__(self):
63        self.bits = {}
64
65    def load(self, pickle_path):
66        try:
67            with open(pickle_path, 'rb') as f:
68                self.bits = pickle.load(f)
69        except FileNotFoundError:
70            print(f"Emotes map does not exist at {pickle_path}",
71                    file=sys.stderr)
72
73    # This is quite slow since we do a search and replace (O(n))
74    # for each keyword O(m) times each variant of said keyword (O(k)).
75    # Thus total complexity is O(m*n*k). All three of these numbers are
76    # typically small: m and k typically < 10, n typically < 200.
77    #
78    # Naively one might split the input into words, but this only works for
79    # English-like languages. Eastern Asian languages like Japanese don't
80    # really divide into words AFAIK so this wouldn't work for them.
81    #
82    # Unless the performance becomes a user-reported problem, stick with this
83    # inefficient but reliable method.
84    def encode_emotes(self, msg: str):
85        for keyword, bits in self.bits.items():
86            bits_str = ""
87            for bit in bits:
88                bits_str += chr(bit)
89            # ALL CAPS
90            tmp = keyword.upper()
91            msg = msg.replace(tmp, bits_str)
92            # lowercase
93            tmp = keyword.lower()
94            msg = msg.replace(tmp, bits_str)
95            # Capitalized
96            tmp = keyword.lower().capitalize()
97            msg = msg.replace(tmp, bits_str)
98            # dashes inserted
99            tmp = '-'.join(keyword.upper())
100            msg = msg.replace(tmp, bits_str)
101            # uppercase, spaces inserted
102            tmp = ' '.join(keyword.upper())
103            msg = msg.replace(tmp, bits_str)
104            # lowercase, spaces inserted
105            tmp = ' '.join(keyword.lower())
106            msg = msg.replace(tmp, bits_str)
107            # uppercase, commas and spaces inserted
108            tmp = ', '.join(keyword.upper())
109            msg = msg.replace(tmp, bits_str)
110        return msg
111
112if __name__ == "__main__":
113    parser = argparse.ArgumentParser()
114    parser.add_argument("dir", type=str, help="directory to get images from")
115    parser.add_argument("board_aspect_ratio", help="aspect ratio of a cell in the board")
116    parser.add_argument("texture_aspect_ratio", help="aspect ratio of a cell in the texture")
117    parser.add_argument("tex_path", type=str, help="path to save the texture to")
118    parser.add_argument("pickle_path", type=str, help="path to save the texture index to")
119    args = parser.parse_args()
120
121    directory_path = args.dir
122    board_aspect_ratio = int(args.board_aspect_ratio)
123    texture_aspect_ratio = int(args.texture_aspect_ratio)
124
125    base_img = Image.new("RGBA", (EMOTES_TEX_SZ, EMOTES_TEX_SZ), (0, 0, 0, 0))
126    images_and_filenames = get_images_from_directory(directory_path)
127    i = 0
128    bits = {}  # Dict[str, List[int]]
129    for img, filename in images_and_filenames:
130        print(f"Adding {filename}")
131        img = resize_image_with_aspect_ratio(img, board_aspect_ratio)
132        img = resize_image_to_height(img, EMOTES_HEIGHT)
133        img_fragments = split_resized_image(img, int(EMOTES_HEIGHT / texture_aspect_ratio), EMOTES_HEIGHT)
134        img_bits = []  # List[int]
135        for img_fragment in img_fragments:
136            i = i + 1
137            img_pos = i_to_pos(i, 
138                    EMOTES_HEIGHT / texture_aspect_ratio, EMOTES_HEIGHT,
139                    EMOTES_TEX_SZ, EMOTES_TEX_SZ)
140            print(f"{img_pos}")
141            superimpose_image(base_img, img_fragment, img_pos)
142            img_bits.append(EMOTES_LETTER_OFFSET + i)
143        emote_name = os.path.basename(filename).split('.')[0]
144        print(f"{emote_name} -> {img_bits}")
145        bits[emote_name] = img_bits
146    base_img.save(args.tex_path)
147    with open(args.pickle_path, 'wb') as f:
148        pickle.dump(bits, f)
149