open-standards/aac/aac-rs/tools/lang/build_pinyin.py
Transaction Science 3a4c8f25eb fix(aac-core, aac-web): the keyboard review — letter names by ear, standard layouts, keys that keep their size
The alphabet by ear
- Says each letter by its name (keyboard/letter_names.json), never the bare
  key a voice reads as a word, and the app's own words in the language. The
  names are data with a review: drafted, checked by an independent
  back-reading and a register check, disputes decided and checked again
  (rounds 2-3), then a voice check with espeak-ng
  (tools/keyboard/check_letter_names.py). 43 of 45 languages agreed; Amharic
  (ኸ) and Tagalog (z, v, e) are not, and there it says it is not ready yet.
  The readers were AI models, not native speakers, and the table says so.
- Its own speech path (tts::say_cue): the device voice of the language, no
  text_for_speech, and never over or cancelling the person's words; after
  Speak the next cue waits until the message has been said. It does not
  start without a voice that speaks the language, and says why.
- Offers a letter's marks, a kana's forms and an Ethiopic consonant's orders
  after it; reads a lone suggestion as the word; Stop is in the last group;
  a key reaches it from every keyboard. Each choice records whether a tap
  relayed it; "only my own switch or look" is a setting; a message spelled
  with relayed choices is learned only when the person keeps it (Item::Learn)
  with their own yes. A panel open takes the switch first.

Keyboards
- National layouts from published standards, both layers, read from
  xkeyboard-config (tools/keyboard/build_layouts.py): InScript (IS 13194) for
  the nine Indic languages, Kedmanee (TIS 820-2538) for Thai, CRULP phonetic
  for Urdu; Shift's layer is a page at the same positions.
- Defaults follow the access method (kbd::suggested): most used letters first
  for a switch, colour groups (or alphabetical, large keys) for gaze; a key
  size setting. A Board key leaves text mode. Amharic syllable pages have
  Back. Malayalam signs shown bare (WebKit drew two circles).
- Pinyin: each candidate covers its own letters, ranked by the likeliest
  split (不 + 舒服, not 部署 + 副); ▸▸ pages through them; capitals read as
  the letters; no conversion during a device IME's composition; a failed
  download is said once and retried with back-off; the note says exactly what
  it does.

Access and fit
- With the on-screen keys, the box never takes a switch's Space or Enter, and
  a chosen suggestion no longer moves the focus into it.
- A look must leave a key before it can choose again.
- Keys never shrink below 24 x 32 px: on a phone on its side the box goes
  beside the keys, and the keyboard scrolls with the scan's highlight kept in
  view; the colour frame's text keeps its end in view; the notes fold to a
  line; the colour marks sit on badges with 4.5:1 ink; toggles show in dark
  and high-contrast; dir=auto on the box and what by-ear shows.
- Phrases page: Add to bar and Recent. Unreadable keyboard settings are not
  overwritten at start. First letters keeps where it reads from when text
  mode comes back.

Credits: Settings -> Keyboard lists every word list's source and licence; the
pinyin licence file carries pypinyin's, pinyin-data's, phrase-pinyin-data's
and the Unicode notices in full (the generator pins pypinyin 0.55.0); the
compose table names the Unicode data it comes from. SPEC §12 and
spec/keyboard.md updated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-05 02:18:26 -04:00

210 lines
10 KiB
Python

#!/usr/bin/env python3
"""Build the pinyin index for typing Chinese on the on-screen keyboard.
Reads the Chinese pack's words, most written first (from
`cargo test -p aac-core --lib dump_chinese_words -- --ignored --nocapture`),
gives each its toneless pinyin (pypinyin; v for ü, as pinyin keyboards type
it), and writes the words in that order — then, after them all, the other
readings of words of one character (是 as "ti" is listed, but never above a
word whose usual reading "ti" is) — to:
data/pinyin/zh.<sha256-12>.txt one word a line: syl'la'bles<TAB>word
data/pinyin/index.json file, sha256, bytes, where it came from
data/pinyin/LICENSE.md its licence (the pack's, CC BY-SA 4.0)
usage: cargo test ... | python3 tools/lang/build_pinyin.py
Needs pypinyin 0.55.0 exactly (MIT), so the index is the same wherever it is
built: pip install pypinyin==0.55.0
"""
import hashlib
import json
import re
import sys
from pathlib import Path
import pypinyin
from pypinyin import Style, lazy_pinyin, pinyin
OUT = Path(__file__).resolve().parents[2] / "data" / "pinyin"
PYPINYIN = "0.55.0"
# The notices of what the index is made with, shipped with it in full.
PYPINYIN_LICENSE = """The MIT License (MIT)
Copyright (c) 2016 mozillazg, 闲耘 <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE."""
PINYIN_DATA_LICENSE = """The MIT License (MIT)
Copyright (c) 2016 mozillazg
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE."""
PHRASE_PINYIN_DATA_LICENSE = """MIT License
Copyright (c) 2017 mozillazg
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE."""
UNICODE_LICENSE = """UNICODE LICENSE V3
COPYRIGHT AND PERMISSION NOTICE
Copyright © 1991-2026 Unicode, Inc.
NOTICE TO USER: Carefully read the following legal agreement. BY
DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING DATA FILES, AND/OR
SOFTWARE, YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE
TERMS AND CONDITIONS OF THIS AGREEMENT. IF YOU DO NOT AGREE, DO NOT
DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE THE DATA FILES OR SOFTWARE.
Permission is hereby granted, free of charge, to any person obtaining a
copy of data files and any associated documentation (the "Data Files") or
software and any associated documentation (the "Software") to deal in the
Data Files or Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, and/or sell
copies of the Data Files or Software, and to permit persons to whom the
Data Files or Software are furnished to do so, provided that either (a)
this copyright and permission notice appear with all copies of the Data
Files or Software, or (b) this copyright and permission notice appear in
associated Documentation.
THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF
THIRD PARTY RIGHTS.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE
BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES,
OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THE DATA
FILES OR SOFTWARE.
Except as contained in this notice, the name of a copyright holder shall
not be used in advertising or otherwise to promote the sale, use or other
dealings in these Data Files or Software without prior written
authorization of the copyright holder."""
HAN = re.compile(r"^[㐀-䶿一-鿿豈-﫿]+$")
def readings(word: str) -> list[str]:
if len(word) == 1:
found = pinyin(word, style=Style.NORMAL, heteronym=True, v_to_u=False)[0]
else:
found = ["'".join(lazy_pinyin(word, style=Style.NORMAL, v_to_u=False))]
return [r for r in dict.fromkeys(found) if re.fullmatch(r"[a-z']+", r)]
def main() -> None:
if pypinyin.__version__ != PYPINYIN:
sys.exit(f"needs pypinyin {PYPINYIN} (found {pypinyin.__version__}): pip install pypinyin=={PYPINYIN}")
pack = None
lines = []
others = []
for raw in sys.stdin:
raw = raw.rstrip("\n")
if raw.startswith("#pack\t"):
pack = raw.split("\t", 1)[1]
continue
word = raw.strip()
if not word or not HAN.match(word):
continue
found = readings(word)
lines.extend(f"{r}\t{word}" for r in found[:1])
others.extend(f"{r}\t{word}" for r in found[1:])
lines.extend(others)
if pack is None or not lines:
sys.exit("no word list on stdin (see the usage)")
body = ("\n".join(lines) + "\n").encode("utf-8")
digest = hashlib.sha256(body).hexdigest()
OUT.mkdir(parents=True, exist_ok=True)
for old in OUT.glob("zh.*.txt"):
old.unlink()
name = f"zh.{digest[:12]}.txt"
(OUT / name).write_bytes(body)
index = {
"format": "aac-pinyin-index",
"builder": "aac/aac-rs/tools/lang/build_pinyin.py",
"file": name,
"sha256": digest,
"bytes": len(body),
"entries": len(lines),
"words_from": f"data/lang/{pack}",
"readings_from": f"pypinyin {pypinyin.__version__} (MIT)",
"licence": "CC-BY-SA-4.0",
}
(OUT / "index.json").write_text(json.dumps(index, indent=1, ensure_ascii=False) + "\n", encoding="utf-8")
(OUT / "LICENSE.md").write_text(
"# Pinyin index — licence\n\n"
"Generated by `aac/aac-rs/tools/lang/build_pinyin.py`; do not edit by hand.\n\n"
f"`{name}` lists the words of the Chinese language pack (`data/lang/{pack}`, CC BY-SA 4.0: see "
"`data/lang/LICENSE.md` for its sources and attribution) with their toneless pinyin, read by "
f"pypinyin {pypinyin.__version__} (https://github.com/mozillazg/python-pinyin), whose readings come "
"from the pinyin-data project (https://github.com/mozillazg/pinyin-data, itself drawn from the "
"Unicode Han Database) and the phrase-pinyin-data project "
"(https://github.com/mozillazg/phrase-pinyin-data). As an adaptation of the pack it is shared under "
"the same licence, **Creative Commons Attribution-ShareAlike 4.0 International** "
"(https://creativecommons.org/licenses/by-sa/4.0/).\n\n"
"The readings are what those tools give for each word on its own: a word read otherwise in a "
"sentence is listed under its usual reading. They are offered as typing suggestions only, with no "
"warranty of correctness.\n\n"
"The notices of the software and data the readings come from follow in full.\n\n"
"## pypinyin\n\n```\n" + PYPINYIN_LICENSE + "\n```\n\n"
"## pinyin-data\n\n```\n" + PINYIN_DATA_LICENSE + "\n```\n\n"
"## phrase-pinyin-data\n\n```\n" + PHRASE_PINYIN_DATA_LICENSE + "\n```\n\n"
"## Unicode Han Database (Unihan)\n\n"
"pinyin-data's readings are drawn from the Unicode Han Database (https://www.unicode.org/charts/unihan.html), "
"distributed under the Unicode License:\n\n```\n" + UNICODE_LICENSE + "\n```\n",
encoding="utf-8",
)
print(f"{name}: {len(lines)} readings, {len(body)} bytes", file=sys.stderr)
if __name__ == "__main__":
main()