""" Export the Python package's data tables and reference outputs to the web app (web/). python tools/export_web.py Writes web/src/lib/g2pData.ts consonants, aspirates, vowels, punctuation, exceptions and the Mithi symbol set, generated from ks_g2p so the TypeScript port never carries its own copy of the tables web/tests/vectors.jsonl.gz Python outputs for 30k+ test words and sentences in four option settings; web/tests/g2p.test.ts checks the port against them """ import gzip import json import sys from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / 'src')) from ks_g2p import __version__, phonemize, word_phones # noqa: E402 from ks_g2p._reader import tokenize # noqa: E402 from ks_g2p.ipa import (ASPIRATES, CONSONANTS, EXCEPTIONS, MITHI_SYMBOLS, # noqa: E402 PUNCTUATION, VOWELS) WEB = ROOT / 'web' OPTION_SETS = [ {}, {'implicit_schwa': True}, {'unwritten_a': False}, {'glottal': False}, ] def ts(obj): return json.dumps(obj, ensure_ascii=False, indent=4, sort_keys=True) def write_data(): out = WEB / 'src' / 'lib' / 'g2pData.ts' out.write_text( '// GENERATED by tools/export_web.py from the ks-g2p Python package. Do not edit by hand.\n' f"export const G2P_VERSION = '{__version__}';\n\n" f'export const VOWELS: Record = {ts(VOWELS)};\n\n' f'export const CONSONANTS: Record = {ts(CONSONANTS)};\n\n' f'export const ASPIRATES: Record = {ts(ASPIRATES)};\n\n' f'export const PUNCTUATION: Record = {ts(PUNCTUATION)};\n\n' f'export const EXCEPTIONS: Record = {ts({k: list(v) for k, v in EXCEPTIONS.items()})};\n\n' f'export const MITHI_SYMBOLS: string = {json.dumps("".join(sorted(MITHI_SYMBOLS)), ensure_ascii=False)};\n', encoding='utf-8', newline='\n') print('wrote', out) def write_vectors(): inputs = [] with gzip.open(ROOT / 'tests' / 'data' / 'ks_words.jsonl.gz', 'rt', encoding='utf-8') as f: for line in f: inputs.append(json.loads(line)['input']) inputs = list(dict.fromkeys(inputs)) words = sorted({t for s in inputs for t, w in tokenize(s) if w}) out = WEB / 'tests' / 'vectors.jsonl.gz' n = 0 with gzip.open(out, 'wt', encoding='utf-8', newline='\n') as f: for opts in OPTION_SETS: for s in inputs: f.write(json.dumps({'kind': 'text', 'opts': opts, 'input': s, 'out': phonemize(s, **opts)}, ensure_ascii=False) + '\n') n += 1 for w in words: f.write(json.dumps({'kind': 'word', 'opts': opts, 'input': w, 'out': list(word_phones(w, **opts))}, ensure_ascii=False) + '\n') n += 1 print('wrote', out, n, 'vectors') if __name__ == '__main__': write_data() write_vectors()