Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / keyboard / generate_pinyin.py
generate_pinyin.py198 lines · 9.0 KiBRaw
| 1 | #!/usr/bin/env python3 |
| 2 | """Offline generator: ICU Han-Latin readings -> keyboard/src/main/assets/dict/pinyin_*.txt |
| 3 | |
| 4 | The Chinese layouts need a pinyin-syllable -> characters index, and there is no such |
| 5 | table in the repo. The readings come from ICU's `Han-Latin` transliterator (i.e. from |
| 6 | Unicode's Unihan `kMandarin` data), read here through the system ICU library so the |
| 7 | generated asset is reproducible from Unicode data alone rather than from a scraped |
| 8 | word list. |
| 9 | |
| 10 | Ranking is the hard part: Unihan knows *which* characters read "zhong" but not which |
| 11 | one a person means. Three tiers, in order: |
| 12 | |
| 13 | 1. HAND_FREQ below -- the most common characters, in rough frequency order, written |
| 14 | out by hand. It contains both simplified and traditional forms; each output table |
| 15 | keeps only the ones its own encoding can represent, which is what makes 这 rank |
| 16 | first for simplified and 這 first for traditional from a single list. |
| 17 | 2. Level 1 of the table's own legacy encoding (GB2312 for simplified, Big5 for |
| 18 | traditional) -- the ~5k characters those standards considered common. |
| 19 | 3. Level 2, then the other script's characters, then everything else by codepoint. |
| 20 | |
| 21 | Two files are emitted rather than one shared list, because a traditional-script user |
| 22 | offered 国 before 國 has to skip past a character they will never want. |
| 23 | |
| 24 | Format: `syllable<TAB>characters`, one syllable per line, sorted; characters in rank |
| 25 | order. Parsed by PinyinDictionary.kt. |
| 26 | |
| 27 | Usage: python3 scripts/keyboard/generate_pinyin.py |
| 28 | """ |
| 29 | |
| 30 | import ctypes |
| 31 | import unicodedata |
| 32 | from pathlib import Path |
| 33 | |
| 34 | REPO = Path(__file__).resolve().parents[2] |
| 35 | OUT_DIR = REPO / "keyboard" / "src" / "main" / "assets" / "dict" |
| 36 | |
| 37 | # CJK Unified Ideographs. Ext-A and beyond are rare enough that including them only |
| 38 | # lengthens candidate lists with characters nobody is reaching for. |
| 39 | FIRST, LAST = 0x4E00, 0x9FFF |
| 40 | |
| 41 | # Rough frequency order, simplified and traditional interleaved. Only ordering depends |
| 42 | # on this -- an omission costs a character some rank, it never removes it from the |
| 43 | # candidate list, which comes from Unihan. |
| 44 | HAND_FREQ = ( |
| 45 | "的一是了不我人在有他这這个個中大来來上国國说說们們为為子和你地出道时時年得就那要下以生会會自着" |
| 46 | "着去之过過家学學对對可她里裡後后小么麼心多天而能好都然没沒日于於起还還发發成事只作当當想看文无無" |
| 47 | "开開手十用主行方又如前所本见見经經头頭面公同三已老从從动動两兩长長知民样樣与與定十点點种種间間" |
| 48 | "情感话話回位分爱愛给給名法期它信问問身者被高其此常正真明力全比第水白话世界者九八七六五四百千万萬" |
| 49 | "太少几幾次使身车車走空东東南西北先生活工作学校北京上海中国朝夜早晚昨今明天气氣候雨雪风風云雲山水火" |
| 50 | "土木金石田米茶饭飯菜肉鱼魚鸡雞蛋奶果树樹花草虫蟲鸟鳥马馬牛羊猪豬狗猫貓门門窗床桌椅书書笔筆纸紙" |
| 51 | "电電话話视視脑腦机機车車船飞飛路桥橋店市场場院房屋家庭父母兄弟姐妹儿兒女男朋友同事老师師医醫生病" |
| 52 | "药藥钱錢买買卖賣贵貴便宜快慢新旧舊高低长长短远遠近深浅淺重轻輕难難易忙闲閒累饿餓渴冷热熱疼痛喜怒哀乐樂" |
| 53 | ) |
| 54 | |
| 55 | # Syllables ICU can produce that are not pinyin (it passes some characters through). |
| 56 | VALID_INITIALS = ("b p m f d t n l g k h j q x zh ch sh r z c s y w").split() |
| 57 | |
| 58 | |
| 59 | def icu_transliterator(identifier): |
| 60 | """An ICU transliterator from the system library, as a str -> str function.""" |
| 61 | lib = ctypes.CDLL("/usr/lib/libicucore.dylib") |
| 62 | lib.utrans_openU.restype = ctypes.c_void_p |
| 63 | lib.utrans_openU.argtypes = [ |
| 64 | ctypes.c_void_p, ctypes.c_int32, ctypes.c_int, ctypes.c_void_p, |
| 65 | ctypes.c_int32, ctypes.c_void_p, ctypes.POINTER(ctypes.c_int), |
| 66 | ] |
| 67 | err = ctypes.c_int(0) |
| 68 | ident = identifier.encode("utf-16-le") |
| 69 | handle = lib.utrans_openU( |
| 70 | ctypes.create_string_buffer(ident), len(ident) // 2, 0, None, 0, None, |
| 71 | ctypes.byref(err), |
| 72 | ) |
| 73 | if not handle or err.value > 0: |
| 74 | raise SystemExit(f"could not open the {identifier} transliterator (ICU error {err.value})") |
| 75 | |
| 76 | def translate(text): |
| 77 | data = text.encode("utf-16-le") |
| 78 | capacity = max(1024, len(data) * 8) |
| 79 | buf = ctypes.create_string_buffer(capacity * 2) |
| 80 | ctypes.memmove(buf, data, len(data)) |
| 81 | length = ctypes.c_int32(len(data) // 2) |
| 82 | limit = ctypes.c_int32(len(data) // 2) |
| 83 | status = ctypes.c_int(0) |
| 84 | lib.utrans_transUChars( |
| 85 | ctypes.c_void_p(handle), buf, ctypes.byref(length), capacity, 0, |
| 86 | ctypes.byref(limit), ctypes.byref(status), |
| 87 | ) |
| 88 | if status.value > 0: |
| 89 | raise SystemExit(f"transliteration failed (ICU error {status.value})") |
| 90 | return bytes(buf.raw[: length.value * 2]).decode("utf-16-le") |
| 91 | |
| 92 | return translate |
| 93 | |
| 94 | |
| 95 | def strip_tone(syllable): |
| 96 | """`zhōng` -> `zhong`; the layouts have no tone keys, so the index is toneless.""" |
| 97 | decomposed = unicodedata.normalize("NFD", syllable) |
| 98 | return "".join(c for c in decomposed if not unicodedata.combining(c)).lower() |
| 99 | |
| 100 | |
| 101 | def encodable(char, encoding): |
| 102 | try: |
| 103 | char.encode(encoding) |
| 104 | return True |
| 105 | except UnicodeEncodeError: |
| 106 | return False |
| 107 | |
| 108 | |
| 109 | def level(char, encoding, level1_end): |
| 110 | """0 for the encoding's level-1 (common) block, 1 for the rest of it, 2 for absent.""" |
| 111 | try: |
| 112 | raw = char.encode(encoding) |
| 113 | except UnicodeEncodeError: |
| 114 | return 2 |
| 115 | return 0 if int.from_bytes(raw, "big") <= level1_end else 1 |
| 116 | |
| 117 | |
| 118 | def build_index(translate): |
| 119 | """syllable -> [characters], every CJK ideograph ICU can read.""" |
| 120 | chars = [chr(c) for c in range(FIRST, LAST + 1)] |
| 121 | # One call per 1000 characters: the transliterator is slow to invoke, and its |
| 122 | # output is space-separated readings, one per input character. |
| 123 | index = {} |
| 124 | for start in range(0, len(chars), 1000): |
| 125 | chunk = chars[start : start + 1000] |
| 126 | readings = translate("".join(chunk)).split(" ") |
| 127 | if len(readings) != len(chunk): |
| 128 | raise SystemExit(f"reading count mismatch at {start}: {len(readings)} vs {len(chunk)}") |
| 129 | for char, reading in zip(chunk, readings): |
| 130 | syllable = strip_tone(reading) |
| 131 | if not syllable.isascii() or not syllable.isalpha(): |
| 132 | continue # ICU passed the character through unread |
| 133 | index.setdefault(syllable, []).append(char) |
| 134 | return index |
| 135 | |
| 136 | |
| 137 | def write_table(index, path, encoding, level1_end, other_encoding): |
| 138 | rank_of_hand = {} |
| 139 | for i, char in enumerate(HAND_FREQ): |
| 140 | if char not in rank_of_hand and encodable(char, encoding): |
| 141 | rank_of_hand[char] = i |
| 142 | |
| 143 | def sort_key(char): |
| 144 | hand = rank_of_hand.get(char) |
| 145 | if hand is not None: |
| 146 | return (0, hand, 0) |
| 147 | own = level(char, encoding, level1_end) |
| 148 | if own < 2: |
| 149 | return (1 + own, 0, ord(char)) |
| 150 | # Present in the other script's standard but not this one: still worth |
| 151 | # ranking above the long tail of characters no standard bothered with. |
| 152 | return (3 if encodable(char, other_encoding) else 4, 0, ord(char)) |
| 153 | |
| 154 | lines = [ |
| 155 | "# Pinyin syllable -> characters, for the Chinese layouts.", |
| 156 | "# Generated by scripts/keyboard/generate_pinyin.py from Unicode/ICU Han-Latin", |
| 157 | "# readings. Format: syllable<TAB>characters, most likely candidate first.", |
| 158 | ] |
| 159 | for syllable in sorted(index): |
| 160 | chars = sorted(set(index[syllable]), key=sort_key) |
| 161 | lines.append(f"{syllable}\t{''.join(chars)}") |
| 162 | path.write_text("\n".join(lines) + "\n", encoding="utf-8") |
| 163 | print(f"{path.name}: {len(index)} syllables, {path.stat().st_size // 1024} KiB") |
| 164 | |
| 165 | |
| 166 | def write_bopomofo(index, translate_bopomofo, path): |
| 167 | """bopomofo spelling -> pinyin syllable, so 注音 can share the pinyin index.""" |
| 168 | lines = [ |
| 169 | "# Bopomofo (注音) spelling -> pinyin syllable, for the 注音 layout.", |
| 170 | "# Generated by scripts/keyboard/generate_pinyin.py via ICU Latin-Bopomofo.", |
| 171 | ] |
| 172 | seen = {} |
| 173 | for syllable in sorted(index): |
| 174 | spelling = "".join( |
| 175 | c for c in translate_bopomofo(syllable) if 0x3105 <= ord(c) <= 0x3129 |
| 176 | ) |
| 177 | if spelling and spelling not in seen: |
| 178 | seen[spelling] = syllable |
| 179 | for spelling in sorted(seen): |
| 180 | lines.append(f"{spelling}\t{seen[spelling]}") |
| 181 | path.write_text("\n".join(lines) + "\n", encoding="utf-8") |
| 182 | print(f"{path.name}: {len(seen)} spellings") |
| 183 | |
| 184 | |
| 185 | def main(): |
| 186 | index = build_index(icu_transliterator("Han-Latin")) |
| 187 | dropped = [s for s in index if not any(s.startswith(i) for i in VALID_INITIALS) and s not in ("a", "o", "e", "ai", "ei", "ao", "ou", "an", "en", "ang", "eng", "er")] |
| 188 | for syllable in dropped: |
| 189 | del index[syllable] |
| 190 | OUT_DIR.mkdir(parents=True, exist_ok=True) |
| 191 | # GB2312 level 1 ends at 0xD7F9; Big5 level 1 ends at 0xC67E. |
| 192 | write_table(index, OUT_DIR / "pinyin_sc.txt", "gb2312", 0xD7F9, "big5") |
| 193 | write_table(index, OUT_DIR / "pinyin_tc.txt", "big5", 0xC67E, "gb2312") |
| 194 | write_bopomofo(index, icu_transliterator("Latin-Bopomofo"), OUT_DIR / "bopomofo.txt") |
| 195 | |
| 196 | |
| 197 | if __name__ == "__main__": |
| 198 | main() |