turkic-ocr-code / src /pagesynth /scripts /build_label_vocab.py
treoa's picture
Release 1
24aaa76
Raw History Blame Contribute Delete
2.17 kB
"""Build the label vocabulary files of one or all languages (ZEN4 job; reads the full corpus).
python build_label_vocab.py --text-dir DIR [--lang kk] [--display]
Writes DIR/<lang>/label_words.json (from sentences.tsv) or label_words_display.json (from sentences_display.tsv).
Rules: see pagesynth/vocab.py. Thresholds: lower-case count at least 20 (display: 30, the threshold of the name screen), capitalised mid-sentence
count at most 2 % (display: 1 %) of the lower-case count.
"""
import argparse
import json
import os
import sys
import time
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
from pagesynth import text as T # noqa: E402
from pagesynth import vocab as V # noqa: E402
ap = argparse.ArgumentParser()
ap.add_argument("--text-dir", required=True)
ap.add_argument("--lang", default=None)
ap.add_argument("--display", action="store_true")
a = ap.parse_args()
langs = [a.lang] if a.lang else T.LANG_ORDER
src_name = "sentences_display.tsv" if a.display else "sentences.tsv"
out_name = "label_words_display.json" if a.display else "label_words.json"
min_low, max_cap = (30, 0.01) if a.display else (20, 0.02)
for lang in langs:
t0 = time.time()
path = os.path.join(a.text_dir, lang, src_name)
sents = []
with open(path, encoding="utf-8") as f:
for line in f:
_src, _, txt = line.rstrip("\n").partition("\t")
if txt:
sents.append(txt)
low, cap = V.count_words(sents, lang, min_low, max_cap)
chosen, stats = V.select_words(low, cap, lang, min_low, max_cap)
words = [w for w, _ in chosen]
with open(os.path.join(a.text_dir, lang, out_name), "w", encoding="utf-8") as f:
json.dump(dict(lang=lang, source=src_name, sentences=len(sents), min_lower_count=min_low, max_capitalised_ratio=max_cap, words=words, counts=[c for _, c in chosen], words_with_letter=stats),
f, ensure_ascii=False)
print(lang, src_name, "sentences", len(sents), "distinct lower-case tokens", len(low), "words kept", len(words), "with special letters", json.dumps(stats, ensure_ascii=False), "seconds %.0f" % (time.time() - t0), flush=True)