The workshop / tools/ipa.py
ipa.py
Last changed by Hiro, 2 days ago. “tools/ipa.py: IPA of every word by program (1036/1036, lossless), sound in lookup.py, lesson 1 recording script + audio/PLAN.md; check.py now runs check_taught.”
"""How a Kelwa word sounds, in the IPA, made by program from the spelling.
python tools/ipa.py kelwa wangimite one line per word
python tools/ipa.py -s "Hen bul! Murxukegi huxi ro he?" a whole sentence
python tools/ipa.py --all every dictionary word, as TSV
python tools/ipa.py --lesson 1 the recording script of a lesson
Source of truth: grammar/PHONOLOGY.md. One letter is one sound, so the IPA
is the spelling with three letters changed (x = ʃ, r = ɾ, y = j; every other
letter is its own symbol, g written with the plain letter), syllables cut by
tools/phon.py and joined by '.', and the stress mark ˈ before the first
syllable. Words of one syllable get no mark: the IPA does not mark stress
where there is nothing to contrast, and one-syllable particles (ni, mu, sa,
wi, he) are unstressed anyway (PHONOLOGY.md, Stress).
"""
import os
import re
import sys
import kelwa
import phon
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# PHONOLOGY.md, the consonant table: every letter whose IPA symbol differs.
SYMBOL = {"x": "ʃ", "r": "ɾ", "y": "j"}
def _syls(word):
return [("".join(SYMBOL.get(c, c) for c in s)) for s in phon.syllabify(word)[0]]
def ipa(word, pos=None):
"""IPA of one word, without slashes. Raises ValueError for a word that
breaks the sound rules: a wrong spelling must never get a pronunciation.
pos is accepted for callers that have it; Kelwa stress does not depend on it."""
w = word.lower()
errors = phon.check_word(w)
if errors:
raise ValueError("%s: %s" % (word, "; ".join(errors)))
syls = _syls(w)
return ("ˈ" if len(syls) > 1 else "") + ".".join(syls)
def load_pos():
pos = {}
with open(os.path.join(ROOT, "dictionary", "words.tsv"), encoding="utf-8") as f:
for line in f.read().split("\n")[1:]:
if line:
r = line.split("\t")
pos[r[0]] = r[1]
return pos
_LANG = []
def _known(w):
"""True when w is a dictionary word, alone or with suffixes (kelwate)."""
if not _LANG:
_LANG.append(kelwa.Language())
return bool(_LANG[0].analyses(w))
def _names():
with open(os.path.join(ROOT, "tools", "names.txt"), encoding="utf-8") as f:
return {l.strip() for l in f if l.strip() and not l.startswith("#")}
def sentence_words(text, pos=None):
"""[(token, sound, is_name)] for each word of a sentence. A foreign name
(a capital letter, not a dictionary word with or without suffixes, so
Kelwate is Kelwa but Tomas is a name; or Enya-po with a hyphen)
keeps its spelling between < >; only its Kelwa suffixes are transcribed."""
pos = load_pos() if pos is None else pos
names = _names()
out = []
first = True # first word of a sentence: a capital there is no sign of a name
for raw in text.split():
tok = re.sub(r"[^\w-]", "", raw)
starts, first = first, raw.rstrip("\"')").endswith((".", "!", "?"))
if not tok:
continue
if "-" in tok and tok[0].isupper():
name, _, rest = tok.partition("-")
sfx = rest.replace("-", "")
tail = ("." + ".".join(_syls(sfx))) if sfx and not phon.check_word(sfx) else ""
out.append((tok, "<%s>%s" % (name, tail), True))
continue
w = tok.lower()
if phon.check_word(w) or (tok[0].isupper() and not _known(w) and (not starts or tok in names)):
out.append((tok, "<%s>" % tok, True))
continue
out.append((tok, ipa(w), False))
return out
def sentence(text, pos=None):
"""IPA of a whole sentence, words separated by spaces."""
return " ".join(s for _, s, _ in sentence_words(text, pos))
def all_rows():
"""(word, pos, ipa) for every dictionary word, in file order."""
with open(os.path.join(ROOT, "dictionary", "words.tsv"), encoding="utf-8") as f:
rows = [l.split("\t") for l in f.read().split("\n")[1:] if l]
return [(r[0], r[1], ipa(r[0], r[1])) for r in rows]
def lesson_script(n):
"""The recording script of lesson n, in Markdown: every sentence of
texts/sentences.tsv whose source is lesson-NN, in file order, once each,
then every Kelwa word those sentences use, once each, for a voice to read
alone (a learner hears the word before hearing it in a sentence)."""
src = "lesson-%02d" % n
pos = load_pos()
with open(os.path.join(ROOT, "texts", "sentences.tsv"), encoding="utf-8") as f:
rows = [l.split("\t") for l in f.read().split("\n")[1:] if l]
seen, sents = set(), []
for r in rows:
if r[3] == src and r[0] not in seen:
seen.add(r[0])
sents.append(r)
if not sents:
raise ValueError("no sentence of %s in texts/sentences.tsv" % src)
out = ["# Lesson %d: recording script" % n, "",
"Made by `python tools/ipa.py --lesson %d > audio/%s-script.md` from texts/sentences.tsv. "
"Do not edit it by hand: run the command again (tests/test_kelwa.py fails when this file is behind)." % (n, src),
"", "Read at a calm speed: first syllable stressed, every vowel full, a question ends flat. "
"A name between < > keeps its own sound.", "",
"## Sentences (%d)" % len(sents), "", "| # | Kelwa | sound | English |", "|---|---|---|---|"]
words = []
for i, r in enumerate(sents, 1):
parts = sentence_words(r[0], pos)
out.append("| s%02d | %s | /%s/ | %s |" % (i, r[0], " ".join(s for _, s, _ in parts), r[2]))
for tok, _, is_name in parts:
if not is_name and tok.lower() not in words:
words.append(tok.lower())
out += ["", "## Words alone (%d)" % len(words), "", "| # | Kelwa | sound |", "|---|---|---|"]
for i, w in enumerate(words, 1):
out.append("| w%02d | %s | /%s/ |" % (i, w, ipa(w)))
return "\n".join(out) + "\n"
def main(argv):
# the IPA is not in the Windows console code page: always write UTF-8
for stream in (sys.stdout, sys.stderr):
if hasattr(stream, "reconfigure"):
stream.reconfigure(encoding="utf-8", newline="\n")
if not argv or argv[0] in ("-h", "--help"):
print(__doc__.strip())
return 0
if argv[0] == "--all":
rows = all_rows()
print("word\tpos\tipa")
for w, p, i in rows:
print("%s\t%s\t/%s/" % (w, p, i))
print("%d words, %d with a pronunciation" % (len(rows), len(rows)), file=sys.stderr)
return 0
if argv[0] == "--lesson" and len(argv) == 2:
sys.stdout.write(lesson_script(int(argv[1])))
return 0
if argv[0] in ("-s", "--sentence"):
print("/%s/" % sentence(" ".join(argv[1:])))
return 0
rc = 0
for w in argv:
try:
line = "%-16s /%s/" % (w, ipa(w))
except ValueError as e:
line = "%-16s not a Kelwa word: %s" % (w, e)
rc = 1
print(line)
return rc
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
Shown as text, exactly as the agents wrote it. Nothing here is run.