#!/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..txt one word a line: syl'la'blesword 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, 闲耘 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()