khmer-dictionary / scripts /build_hf_dataset.py
phonsobon's picture
Add g2p config (word->pronunciation, train/val/test); fix pronunciation typos
2afb0c6 verified
Raw History Blame Contribute Delete
6.8 kB
"""Build a clean Hugging Face dataset from the raw NCKL Khmer Dictionary 2022 CSV.
Usage: python scripts/build_hf_dataset.py [raw_csv] [out_dir]
"""
import re
import sys
from pathlib import Path
import pandas as pd
ROOT = Path(__file__).resolve().parent.parent
RAW = Path(sys.argv[1]) if len(sys.argv) > 1 else ROOT / "datasets/nckl_khmer_dictionary_2022/khmer_dictionary_2022.csv"
OUT = Path(sys.argv[2]) if len(sys.argv) > 2 else ROOT / "hf/khmer-dictionary"
KHMER_DIGITS = str.maketrans("០១២៣៤៥៦៧៨៩", "0123456789")
SUPERSCRIPT = str.maketrans("0123456789", "⁰¹²³⁴⁵⁶⁷⁸⁹")
POS_EN = {
"ន.": "noun",
"កិ.": "verb",
"គុ.": "adjective",
"គុ.កិ.": "adverb",
"សព្វ.": "pronoun",
"ប.": "preposition",
"ឈ.": "conjunction",
"ឧ.": "interjection",
"ធ.": "particle",
}
def homograph_markup(s: str) -> str:
"""`កេងកង{¥¥}១{££}` -> `កេងកង¹` (superscript homograph number)."""
return re.sub(
r"\{¥¥\}(.*?)\{££\}",
lambda m: m.group(1).translate(KHMER_DIGITS).translate(SUPERSCRIPT),
s,
)
def split_pronunciation(s: str) -> tuple[str, str]:
"""`[ស្ដន់] (ជើង ត អានជា ដ)` -> (`ស្ដន់`, `ជើង ត អានជា ដ`);
`[កន់-តា] ឬ [កន់-តា-រៈ]` -> (`កន់-តា ឬ កន់-តា-រៈ`, ``)."""
note = ""
# Source typos: stray accents, `:` typed for `ៈ`, doubled `[[`.
s = s.replace("´", "").replace(":", "ៈ").replace("[[", "[")
if m := re.fullmatch(r"(.*\])\s*\(([^()]*)\)", s):
s, note = m.group(1), m.group(2).strip()
alts = re.findall(r"\[([^\]]*)\]", s)
if alts and re.fullmatch(r"[\sឬ,]*", re.sub(r"\[[^\]]*\]", "", s)):
return " ឬ ".join(a.strip() for a in alts), note
return s, note
def build_g2p(entries: pd.DataFrame) -> pd.DataFrame:
"""Word -> pronunciation pairs for G2P training, split 90/5/5 by word.
Skips entries with no pronunciation (proverbs/idioms), bound forms such as
`កម្ពុជ—`, and phrases containing spaces or other non-Khmer characters.
Alternative readings (`a ឬ b`) become separate rows.
"""
g = entries[["word", "pronunciation", "entry_id"]].copy()
g["word"] = g["word"].str.rstrip("!?")
g["pronunciation"] = g["pronunciation"].str.split(" ឬ ")
g = g.explode("pronunciation")
khmer_only = r"[ក-៿‌‍]+"
g = g[
g["word"].str.fullmatch(khmer_only)
& g["pronunciation"].str.fullmatch(r"[ក-៿‌‍\-]+")
& ~g["pronunciation"].str.contains(r"^-|-$|--")
]
g = (g.groupby(["word", "pronunciation"], sort=False, as_index=False)
.agg(entry_ids=("entry_id", list)))
g["syllables"] = g["pronunciation"].str.count("-") + 1
# Split by word so all readings of a word stay in the same split.
words = pd.Series(g["word"].unique()).sample(frac=1, random_state=42)
n = len(words)
split = {w: "train" for w in words.iloc[: int(n * 0.9)]}
split |= {w: "validation" for w in words.iloc[int(n * 0.9): int(n * 0.95)]}
split |= {w: "test" for w in words.iloc[int(n * 0.95):]}
g["split"] = g["word"].map(split)
return g
def pos_list(s: str) -> list[str]:
return [p for p in re.split(r"[,\s]+", s) if p]
def main() -> None:
d = pd.read_csv(RAW, dtype=str, keep_default_na=False, encoding="utf-8-sig")
for c in ("definition", "examples", "notes", "etymology", "pronunciation"):
d[c] = d[c].map(homograph_markup)
# Row 1 has a stray "1" in the sub-word column.
d.loc[d["level"] == "1", "sense"] = ""
# Continuation rows (2nd, 3rd ... sense) leave word fields blank and point at
# the entry's first row through `ref`; copy the entry-level fields down.
first = d[d["word"] != ""].set_index("id")
for c in ("word", "homograph", "sense", "pronunciation", "etymology", "level"):
d[c] = d["ref"].map(first[c])
d["pos"] = d["pos"].mask(d["pos"] == "", d["ref"].map(first["pos"]))
pron = d["pronunciation"].map(split_pronunciation)
is_sub = d["level"] == "2"
senses = pd.DataFrame(
{
"entry_id": d["ref"].astype(int),
"sense_id": d["id"].astype(int),
"word": d["sense"].where(is_sub, d["word"]),
"headword": d["word"],
"homograph": pd.to_numeric(d["homograph"]).astype("Int64"),
"is_subentry": is_sub,
"pronunciation": pron.str[0],
"pronunciation_note": pron.str[1],
"etymology": d["etymology"],
"sense_no": d.groupby("ref").cumcount() + 1,
"sense_label": d["poly"],
"part_of_speech": d["pos"],
"part_of_speech_en": d["pos"].map(
lambda s: ", ".join(POS_EN.get(p, p) for p in pos_list(s))
),
"definition": d["definition"].str.replace(r"\s*:$", "", regex=True),
"examples": d["examples"],
"notes": d["notes"],
}
)
sense_cols = ["sense_no", "sense_label", "part_of_speech", "part_of_speech_en",
"definition", "examples", "notes"]
entry_cols = ["entry_id", "word", "headword", "homograph", "is_subentry",
"pronunciation", "pronunciation_note", "etymology"]
entries = (
senses.groupby("entry_id", sort=False)
.apply(lambda g: pd.Series({
**g.iloc[0][entry_cols[1:]].to_dict(),
"senses": g[sense_cols].to_dict("records"),
}), include_groups=False)
.reset_index()
)
entries["homograph"] = entries["homograph"].astype("Int64")
entries["is_subentry"] = entries["is_subentry"].astype(bool)
(OUT / "data").mkdir(parents=True, exist_ok=True)
entries.to_parquet(OUT / "data/entries.parquet", index=False)
senses.to_parquet(OUT / "data/senses.parquet", index=False)
senses.to_csv(OUT / "data/senses.csv", index=False, encoding="utf-8-sig")
words = sorted(set(senses["word"]) - {""})
(OUT / "data/words.txt").write_text("\n".join(words) + "\n", encoding="utf-8")
g2p = build_g2p(entries)
(OUT / "data/g2p").mkdir(exist_ok=True)
for name, part in g2p.groupby("split"):
part.drop(columns="split").to_parquet(OUT / f"data/g2p/{name}.parquet", index=False)
print(f"entries={len(entries)} senses={len(senses)} words={len(words)} "
f"headwords={senses['headword'].nunique()} subentries={entries['is_subentry'].sum()} "
f"no_pron_entries={(entries['pronunciation'] == '').sum()}")
print(f"g2p pairs={len(g2p)} words={g2p['word'].nunique()} "
+ " ".join(f"{k}={v}" for k, v in g2p["split"].value_counts().items()))
if __name__ == "__main__":
main()