import os
from pathlib import Path
import unicodedata
OPENCC_TS = Path(os.environ.get("OPENCC_TS", "/tmp/opencc/data/dictionary/TSCharacters.txt"))
PG_STOP_DIR = Path(
os.environ.get("PG_STOP_DIR", "/home/winix/rs/db/pg/src/backend/snowball/stopwords")
)
OUT_RS = Path(__file__).resolve().parent.parent / "src" / "table_gen.rs"
LIGATURE_CP = {0x00DF, 0x00E6, 0x00FE, 0x0133, 0x0153, 0x01C6, 0x01C9, 0x01CC, 0x01F3}
SPECIAL_FOLD = {
0x00F8: "o", 0x0111: "d", 0x00F0: "d", 0x0142: "l", 0x0131: "i", 0x1E9A: "a", 0x03D2: "υ", 0x03D3: "υ", 0x03D4: "υ", }
EN_COLLISION = {
"ad", "also", "bin", "biz", "ci", "com", "come", "dig", "dir", "door", "dos", "em", "hat",
"hay", "io", "li", "met", "min", "nas", "non", "num", "op", "par", "per", "sea", "seas",
"sedan", "soy", "sue", "till", "ton", "van", "var", "vars", "want", "war",
}
def parse_opencc_ts():
if not OPENCC_TS.exists():
raise FileNotFoundError(f"Missing OpenCC dictionary: {OPENCC_TS}")
pairs = []
seen = set()
for raw_line in OPENCC_TS.read_text(encoding="utf-8").splitlines():
line = raw_line.strip()
if not line or line.startswith("#") or "\t" not in line:
continue
trad, vals = line.split("\t", 1)
if len(trad) != 1:
continue
cand = vals.split()[0]
if len(cand) != 1 or trad == cand or trad in seen:
continue
seen.add(trad)
pairs.append((ord(trad), trad, cand))
pairs.sort(key=lambda x: x[0])
return [(t, s) for _, t, s in pairs]
def build_fold_map():
entries = {}
ranges = (
(range(0x00C0, 0x0250), True),
(range(0x1E00, 0x1F00), False),
(range(0x0370, 0x0400), False),
(range(0x1F00, 0x2000), False),
)
for rng, require_ascii in ranges:
for cp in rng:
if cp in LIGATURE_CP:
continue
if cp in SPECIAL_FOLD:
entries[cp] = SPECIAL_FOLD[cp]
continue
ch = chr(cp)
if unicodedata.category(ch) != "Ll" or cp != ord(ch.lower()):
continue
nfkd = unicodedata.normalize("NFKD", ch)
stripped = "".join(c for c in nfkd if unicodedata.category(c) != "Mn")
if len(stripped) == 1 and ord(stripped) in SPECIAL_FOLD:
stripped = SPECIAL_FOLD[ord(stripped)]
if (
len(stripped) == 1
and stripped != ch
and stripped.isalpha()
and (not require_ascii or stripped.isascii())
):
entries[cp] = stripped
return sorted((chr(cp), val) for cp, val in entries.items())
def extract_snowball_stop_cues():
stop_files = {
"En": PG_STOP_DIR / "english.stop",
"De": PG_STOP_DIR / "german.stop",
"Fr": PG_STOP_DIR / "french.stop",
"Es": PG_STOP_DIR / "spanish.stop",
"Pt": PG_STOP_DIR / "portuguese.stop",
"It": PG_STOP_DIR / "italian.stop",
"Nl": PG_STOP_DIR / "dutch.stop",
"Sv": PG_STOP_DIR / "swedish.stop",
"Tr": PG_STOP_DIR / "turkish.stop",
}
word_langs = {}
for lang, p in stop_files.items():
if not p.exists():
raise FileNotFoundError(f"Missing Snowball stopword file: {p}")
for line in p.read_text(encoding="utf-8", errors="ignore").splitlines():
w = line.split("|", 1)[0].strip().lower()
if w and len(w) >= 2 and all(c.isalpha() for c in w):
word_langs.setdefault(w, set()).add(lang)
for w, extra in (
("les", ("Fr",)),
("si", ("Es", "Fr")),
("ja", ("De", "Sv")),
("worden", ("De",)),
):
word_langs.setdefault(w, set()).update(extra)
cues = []
for w, langs in word_langs.items():
if len(langs) == 1 and w not in EN_COLLISION:
cues.append((w, next(iter(langs))))
cues.sort(key=lambda x: x[0])
return cues
def rs_char(ch: str) -> str:
return f"'\\u{{{ord(ch):04X}}}'"
def main():
OUT_RS.parent.mkdir(parents=True, exist_ok=True)
tc_sc = parse_opencc_ts()
fold_map = build_fold_map()
cues = extract_snowball_stop_cues()
lines = [
"// @generated by script/gen_table.py from OpenCC TSCharacters.txt, Unicode NFKD, and PG Snowball stopwords.",
"",
"use crate::lang::LangHint;",
"",
"/// Traditional-to-Simplified Chinese character pairs sorted by source code point.",
"pub(crate) const TC_TO_SC: &[(char, char)] = &[",
]
for t, s in tc_sc:
lines.append(f" ({rs_char(t)}, {rs_char(s)}),")
lines.append("];")
lines.append("")
lines.append("/// Canonical single-char diacritic/special Latin/Greek fold pairs sorted by source char.")
lines.append("pub(crate) const FOLD_CHAR: &[(char, char)] = &[")
for src, dst in fold_map:
lines.append(f" ({rs_char(src)}, {rs_char(dst)}),")
lines.append("];")
lines.append("")
lines.append("/// Exclusive top Snowball function-word cues for Latin language auto-detection.")
lines.append("pub(crate) const LATIN_CUE: &[(&str, LangHint)] = &[")
for w, lang in cues:
esc = w.replace("\\", "\\\\").replace('"', '\\"')
lines.append(f' ("{esc}", LangHint::{lang}),')
lines.append("];")
lines.append("")
OUT_RS.write_text("\n".join(lines), encoding="utf-8")
print(f"Generated {OUT_RS}: TC_TO_SC={len(tc_sc)}, FOLD_CHAR={len(fold_map)}, LATIN_CUE={len(cues)}")
if __name__ == "__main__":
main()