File size: 2,403 Bytes
c996dff | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | import csv
import io
import json
import subprocess
import sys
from ks_g2p.cli import main
SRC = 'کٲشُر زَبان، دٮ۪د تہٕ گۄلاب۔'
IPA = 'kəːʃur zabaːn, dʲad tɨ ɡɔlaːb.'
def run(tmp_path, *args):
out = tmp_path / 'out'
assert main([*map(str, args), '-o', str(out)]) == 0
return out.read_text(encoding='utf-8')
def test_text_option(tmp_path):
assert run(tmp_path, '-t', SRC) == IPA + '\n'
def test_text_file_keeps_lines_and_endings(tmp_path):
src = tmp_path / 'in.txt'
src.write_bytes(f'{SRC}\r\n\nچھُ\n'.encode('utf-8'))
out = tmp_path / 'out'
main([str(src), '-o', str(out)])
assert out.read_bytes().decode('utf-8') == f'{IPA}\r\n\nʧʰu\n'
def test_jsonl_adds_field(tmp_path):
src = tmp_path / 'in.jsonl'
src.write_text(json.dumps({'id': 1, 'text': SRC}, ensure_ascii=False) + '\n', encoding='utf-8')
rec = json.loads(run(tmp_path, src, '-f', 'jsonl'))
assert rec == {'id': 1, 'text': SRC, 'text_ipa': IPA}
def test_csv_and_tsv_add_column(tmp_path):
for fmt, sep in (('csv', ','), ('tsv', '\t')):
src = tmp_path / f'in.{fmt}'
src.write_text(f'id{sep}sentence\n1{sep}{SRC}\n', encoding='utf-8')
rows = list(csv.reader(io.StringIO(run(tmp_path, src, '-f', fmt, '--column', 'sentence')), delimiter=sep))
assert rows == [['id', 'sentence', 'sentence_ipa'], ['1', SRC, IPA]]
def test_lexicon(tmp_path):
src = tmp_path / 'in.txt'
src.write_text('چھُ چھُ کٲشُر\n', encoding='utf-8')
assert run(tmp_path, src, '--lexicon', '--counts') == 'چھُ\tʧʰ u\t2\nکٲشُر\tk əː ʃ u r\t1\n'
def test_exceptions_file(tmp_path):
exc = tmp_path / 'exc.tsv'
exc.write_text('پتن\tpatɨn\n', encoding='utf-8')
assert run(tmp_path, '-t', 'پتن', '--exceptions', exc) == 'patɨn\n'
from ks_g2p.ipa import EXCEPTIONS, _word_cached
EXCEPTIONS.pop('پتن', None)
_word_cached.cache_clear()
def test_workers_give_identical_output(tmp_path):
src = tmp_path / 'in.txt'
src.write_text((SRC + '\n') * 5000, encoding='utf-8')
assert run(tmp_path, src, '-j', '1') == run(tmp_path, src, '-j', '3')
def test_module_entry_point_and_stdin():
r = subprocess.run([sys.executable, '-m', 'ks_g2p'], input=SRC.encode('utf-8'), capture_output=True)
assert r.returncode == 0
assert r.stdout.decode('utf-8').strip() == IPA
|