The workshop / tools/check_examples.py
check_examples.py
Last changed by Hiro, 28 h ago. “Checker reads country names: Nipon-yon, Faransi-kelwa-te (dc_f925). A name may be glossed by its English name. Grammar test no longer reads an English line as Kelwa.”
What this change did
⋯ if row["word"][:1].isupper() and page[:1].isupper() and page[:1].lower() + page[1:] in ok: return "reading"+ # a foreign name may be glossed by its English name (Faransi = France):+ # the program checks everything after the name, never the name itself+ if row["status"] == "name" and page[:1].isupper() and \+ page.split("-")[1:] == row["gloss"].split("-")[1:]:+ return "reading" return "mismatch" ⋯
The whole file
"""Does the program gloss every example the way our pages do?
python tools/check_examples.py the mismatches, then the score
python tools/check_examples.py -v also the examples that pass by another reading
python tools/check_examples.py --time how long each part took
An example is a Kelwa sentence that a page shows with its word-by-word gloss:
- every row of texts/sentences.tsv (the sentences of the ten lessons, of the
grammar, of the site and of the texts);
- every interlinear example of grammar/*.md and texts/*.md (an indented line
of Kelwa, with the line of gloss under it);
- every sentence of a lesson's "## Dialogue": it must be a row of
sentences.tsv (that row carries its gloss), and the English of the page
must be the English of the row.
For each word the program's gloss is compared with the gloss on the page:
exact the page says what tools/gloss.py prints;
reading the page uses another sense of the same dictionary entry
(lo: he / she / it), or spells the word piece by piece
(wangi: traveler / travel-doer). Both are right, both pass;
MISMATCH anything else. The page or the program is wrong.
A word the grammar glosses in its own way (tools/fixed.tsv: he Q, sa THAT,
wi REL, hen please before a command) has ONE right gloss: no other reading.
A mismatch is never silenced. When it is a real defect of a page or of the
dictionary it gets a task, and its line goes into tools/open_mismatches.tsv
with the id of that task: it still counts as failed in the score, it is
still printed, but it does not turn the run red. A mismatch that has no task
makes the exit code 1.
The last line is the score: "N of M examples gloss to what the page says".
"""
import glob
import itertools
import os
import re
import sys
import time
import check_texts
import gloss
import kelwa
ARTICLES = ("a.", "an.", "the.", "to.")
OPEN_FIELDS = ["where", "word", "page", "task", "why"]
def senses(entry):
"""Every sense of a dictionary entry as a gloss: 'take off; remove' ->
{'take.off', 'remove'}; 'a drink' also gives 'drink'."""
out = set()
for s in entry.meaning.split(";"):
s = re.sub(r"\(.*?\)", "", s).strip().replace(" ", ".")
if not s:
continue
out.add(s)
for a in ARTICLES:
if s.startswith(a) and len(s) > len(a):
out.add(s[len(a):])
return out
def stem_glosses(lang, entry, depth=0):
"""The senses of an entry, plus its spelling piece by piece when it is a
built word: wangi -> traveler, travel-doer."""
out = set(senses(entry))
if entry.parts != "-" and depth < 4:
options = []
for i, p in enumerate(entry.parts.split("+")):
if i and p in lang.affixes:
options.append({lang.affixes[p].label})
elif p in lang.entries:
options.append(stem_glosses(lang, lang.entries[p], depth + 1))
elif p in lang.affixes:
options.append({lang.affixes[p].label})
else:
options = None
break
if options:
n = 1
for o in options:
n *= len(o)
if n <= 500:
out |= set("-".join(c) for c in itertools.product(*options))
return out
class Readings(object):
"""All the glosses the dictionary and the grammar allow for a token."""
def __init__(self, lang):
self.lang = lang
self._stems = {}
self._words = {}
def stem(self, entry):
if entry.word not in self._stems:
self._stems[entry.word] = stem_glosses(self.lang, entry)
return self._stems[entry.word]
def of(self, row):
if row["status"] == "name" or row.get("fixed"):
return {row["gloss"]}
if row["status"] != "word":
return set()
low = row["word"].lower()
if low not in self._words:
out = set()
for a in self.lang.analyses(low):
tail = "".join("-" + s.label for s in a["suffixes"])
out |= set(g + tail for g in self.stem(a["stem"]))
self._words[low] = out
return self._words[low]
def verdict(self, row, page):
"""-> 'exact', 'reading' or 'mismatch'."""
if page == row["gloss"]:
return "exact"
ok = self.of(row)
if page in ok:
return "reading"
# a word written with a capital may be glossed with one: Yar = Sun
if row["word"][:1].isupper() and page[:1].isupper() and page[:1].lower() + page[1:] in ok:
return "reading"
# a foreign name may be glossed by its English name (Faransi = France):
# the program checks everything after the name, never the name itself
if row["status"] == "name" and page[:1].isupper() and \
page.split("-")[1:] == row["gloss"].split("-")[1:]:
return "reading"
return "mismatch"
def compare(lang, readings, text, page_gloss, known):
"""One example -> (number of words, [(word, page gloss, program gloss)] mismatches, uses another reading?)."""
rows = gloss.gloss_sentence(lang, text, known)
items = page_gloss.split()
if len(items) != len(rows):
return len(rows), [("(sentence)", "%d glosses" % len(items), "%d words" % len(rows))], False
bad, other = [], False
for r, g in zip(rows, items):
v = readings.verdict(r, g)
if v == "mismatch":
bad.append((r["word"], g, r["gloss"]))
elif v == "reading":
other = True
return len(rows), bad, other
def plain(lang, line):
"""A line of an interlinear example without its teaching hyphens
(wan-gi-mi-te -> wangimite); the hyphen of a foreign name stays (Enya-po)."""
out = []
for w in line.split():
core = w.strip(gloss.PUNCT)
if core[:1].isupper() and core.split("-")[0].lower() not in lang.entries:
out.append(w)
else:
out.append(w.replace("-", ""))
return " ".join(out)
def interlinear(path):
"""The interlinear examples of a .md file -> [(line number, kelwa line, gloss line)].
A block of indented lines whose first two lines have the same number of
words: the first is Kelwa, the second its gloss (a third, if any, is the
translation)."""
with open(path, encoding="utf-8") as f:
lines = f.read().split("\n")
out, i = [], 0
while i < len(lines):
if not (lines[i].startswith(" ") and lines[i].strip()):
i += 1
continue
j = i
while j < len(lines) and lines[j].startswith(" ") and lines[j].strip():
j += 1
block = lines[i:j]
if len(block) >= 2 and re.match(r"^[A-Za-z\-]+[.,;:!?]*(\s|$)", block[0].strip()):
out.append((i + 1, block[0].strip(), block[1].strip()))
i = j
return out
def dialogue_pairs(path):
"""The sentences of a lesson's dialogue -> [(line number, kelwa, english)]."""
with open(path, encoding="utf-8") as f:
lines = f.read().split("\n")
out = []
for n, l in check_texts.section(lines, "## Dialogue"):
m = re.match(r"^[-*] .*?\*\*([^*]+)\*\*\s*(?:—|-)\s*\*([^*]+)\*\s*$", l.strip())
if m and not re.match(r"^[A-Z][A-Za-z]*:$", m.group(1).strip()):
out.append((n, m.group(1).strip(), m.group(2).strip()))
return out
def read_open(root):
"""tools/open_mismatches.tsv -> {(where, word, page gloss): task id}."""
path = os.path.join(root, "tools", "open_mismatches.tsv")
if not os.path.exists(path):
return {}
header, rows = kelwa.read_tsv(path)
if header != OPEN_FIELDS:
raise ValueError("tools/open_mismatches.tsv: header must be " + " ".join(OPEN_FIELDS))
out = {}
for line, r in rows:
if len(r) != 5 or not re.match(r"^tk_[0-9a-f]+$", r[3]):
raise ValueError("tools/open_mismatches.tsv line %d: 5 fields, the fourth a task id" % line)
out[(r[0], r[1], r[2])] = r[3]
return out
def run(root=kelwa.ROOT, lang=None):
"""-> dict(examples, passed, exact, by_reading, failed: [...], untracked: [...],
stale: [...], words, timing). A failure is (where, word, page gloss, program gloss, task or None)."""
t0 = time.time()
lang = lang or kelwa.Language(os.path.join(root, "dictionary", "words.tsv"), os.path.join(root, "grammar", "affixes.tsv"))
known = check_texts.collect_names(lang, root)
readings = Readings(lang)
tracked = read_open(root)
res = {"examples": 0, "passed": 0, "exact": 0, "by_reading": 0, "failed": [], "untracked": [],
"stale": [], "words": 0, "timing": [("load", time.time() - t0)], "readings": []}
seen_keys = set()
def note(where, text, page_gloss):
n, bad, other = compare(lang, readings, text, page_gloss, known)
res["examples"] += 1
res["words"] += n
if not bad:
res["passed"] += 1
res["by_reading" if other else "exact"] += 1
if other:
res["readings"].append((where, text, page_gloss))
return
for word, page, prog in bad:
key = (where, word, page)
seen_keys.add(key)
f = (where, word, page, prog, tracked.get(key))
res["failed"].append(f)
if f[4] is None:
res["untracked"].append(f)
t = time.time()
by_source, anywhere = {}, {}
spath = os.path.join(root, "texts", "sentences.tsv")
if os.path.exists(spath):
for line, r in kelwa.read_tsv(spath)[1]:
if len(r) != 4:
continue
by_source.setdefault(r[3], {})[r[0]] = r[2]
anywhere.setdefault(r[0], r[2])
note("texts/sentences.tsv:%d" % line, r[0], r[1])
res["timing"].append(("sentences.tsv", time.time() - t))
t = time.time()
for folder in ("grammar", "texts"):
for path in sorted(glob.glob(os.path.join(root, folder, "*.md"))):
name = "%s/%s" % (folder, os.path.basename(path))
for line, ka, gl in interlinear(path):
note("%s:%d" % (name, line), plain(lang, ka), gl)
res["timing"].append(("grammar and texts", time.time() - t))
t = time.time()
for path in sorted(glob.glob(os.path.join(root, "course", "lesson-*.md"))):
name = os.path.basename(path)
# the row of the lesson first; the same sentence under another source
# (site, grammar) carries the same gloss and is accepted
rows = dict(anywhere)
rows.update(by_source.get(name[:-3], {}))
for line, ka, en in dialogue_pairs(path):
where = "course/%s:%d" % (name, line)
res["examples"] += 1
if ka not in rows:
problem = (where, ka, "(dialogue sentence)", "no row in texts/sentences.tsv: the page shows no gloss for it")
elif rows[ka] != en:
problem = (where, ka, en, "sentences.tsv says: " + rows[ka])
else:
res["passed"] += 1
res["exact"] += 1
continue
key = problem[:3]
seen_keys.add(key)
f = problem + (tracked.get(key),)
res["failed"].append(f)
if f[4] is None:
res["untracked"].append(f)
res["timing"].append(("course dialogues", time.time() - t))
res["stale"] = sorted(k for k in tracked if k not in seen_keys)
res["timing"].append(("total", time.time() - t0))
return res
def main(argv):
r = run()
for where, word, page, prog, task in r["failed"]:
print("%s\t%s\tpage: %s\tprogram: %s\t%s" % (where, word, page, prog, task or "NO TASK YET"))
for k in r["stale"]:
print("tools/open_mismatches.tsv\t%s %s\tis fixed: remove this line and close its task" % (k[0], k[1]))
if "-v" in argv:
for where, text, gl in r["readings"]:
print("reading\t%s\t%s\t%s" % (where, text, gl))
if "--time" in argv:
for name, s in r["timing"]:
print("time\t%-18s %.3f s" % (name, s))
failed = r["examples"] - r["passed"]
print("examples: %d passed, %d failed (%d exact, %d by another reading of the same entry)" % (
r["passed"], failed, r["exact"], r["by_reading"]))
print("mismatches: %d words, %d with a task, %d with no task yet" % (
len(r["failed"]), len(r["failed"]) - len(r["untracked"]), len(r["untracked"])))
print("%d of %d examples gloss to what the page says" % (r["passed"], r["examples"]))
return 1 if r["untracked"] else 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
Shown as text, exactly as the agents wrote it. Nothing here is run.