-
Notifications
You must be signed in to change notification settings - Fork 0
/
generate.py
executable file
·317 lines (282 loc) · 9.83 KB
/
generate.py
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
#!/usr/bin/env python
"""First-pass Korean stimulus generation.
This simply generates potential stimuli and codes their basic properties.
Subsequent steps will remove actual lexical items and balance the stimuli
according to our assumptions about grammaticality.
"""
import csv
import dataclasses
import functools
import itertools
import logging
from typing import Iterator, List, Optional, Set, Tuple
import jamo
import korean_romanizer
# Onsets.
# /c/ <ㅈ>: more precisely /t͡ɕ/.
# /"cʰ/ <ㅊ>: more precisely /t͡ɕʰ/.
PLAIN_STOP_ONSETS = ["p", "t", "c", "k"]
ASPIRATED_STOP_ONSETS = ["pʰ", "tʰ", "cʰ", "kʰ"]
STOP_ONSETS = PLAIN_STOP_ONSETS + ASPIRATED_STOP_ONSETS
NASAL_ONSETS = ["m", "n"]
SIMPLE_ONSETS = STOP_ONSETS + ["s"] + NASAL_ONSETS
# /e/ proposes transcription problems.
FRONT_VOWELS = ["i", "a"]
BACK_VOWELS = ["o", "u"]
VOWELS = FRONT_VOWELS + BACK_VOWELS
NASAL_CODAS = ["m", "n", "ŋ"]
STOP_CODAS = ["p̚", "t̚", "k̚"]
CODAS = NASAL_CODAS + STOP_CODAS
MONOSYLLABLES = "monosyllables.tsv"
DISYLLABLES = "disyllables.tsv"
LEXICON = "kor_hang_narrow.tsv"
HANGUL_ONSET = {
"p": "ㅂ",
"t": "ㄷ",
"c": "ㅈ",
"k": "ㄱ",
"pʰ": "ㅍ",
"tʰ": "ㅌ",
"cʰ": "ㅊ",
"kʰ": "ㅋ",
"s": "ᄉ", # Has an allophone [ʃ] before /i/.
"m": "ᄆ",
"n": "ᄂ",
}
HANGUL_NUCLEUS = {
"a": "ㅏ",
"o": "ㅗ",
"u": "ㅜ",
"i": "ㅣ",
"wa": "ㅘ",
"wi": "ㅟ", # More precisely /ɰi/.
}
HANGUL_CODA = {"p̚": "ᆸ", "t̚": "ᆮ", "k̚": "ᆨ", "m": "ᆷ", "n": "ᆫ", "ŋ": "ᆼ"}
class Error(Exception):
pass
def _romanize(hangul: str) -> str:
return korean_romanizer.Romanizer(hangul).romanize()
@dataclasses.dataclass
class Monosyllable:
onset: str
nucleus: str
coda: Optional[str] = None
shape: Optional[str] = None
def jamo_tuple(self) -> Tuple[str, str, str]:
if self.shape in ["CV", "CVC", "CwV", "CwVC"]:
spelled_onset = HANGUL_ONSET[self.onset]
elif self.shape.startswith("NCV"):
spelled_onset = (
HANGUL_ONSET[self.onset[0]] + HANGUL_ONSET[self.onset[1:]]
)
elif self.shape.startswith("CNV"):
spelled_onset = (
HANGUL_ONSET[self.onset[:-1]] + HANGUL_ONSET[self.onset[-1]]
)
else:
raise Error(f"Unknown shape: {self.shape}")
spelled_nucleus = HANGUL_NUCLEUS[self.nucleus]
spelled_coda = HANGUL_CODA[self.coda] if self.coda else ""
return spelled_onset, spelled_nucleus, spelled_coda
@property
def jamo(self) -> str:
return "".join(self.jamo_tuple())
@functools.cached_property
def hangul(self) -> str:
spelled_onset, spelled_nucleus, spelled_coda = self.jamo_tuple()
try:
return jamo.jamo_to_hangul(
spelled_onset, spelled_nucleus, spelled_coda
)
except TypeError:
return ""
# TODO: maybe should be a mixin so I don't have to repeat.
@functools.cached_property
def romanization(self) -> str:
return _romanize(self.hangul)
@property
def line(self) -> List[str]:
return [
self.onset,
self.nucleus,
self.coda,
self.shape,
self.jamo,
self.hangul,
self.romanization,
]
@dataclasses.dataclass
class Disyllable:
syl1: Monosyllable
syl2: Monosyllable
shape: str
@property
def jamo(self) -> str:
return self.syl1.jamo + self.syl2.jamo
@functools.cached_property
def hangul(self) -> str:
hangul1 = self.syl1.hangul
hangul2 = self.syl2.hangul
if not hangul1 or not hangul2:
return ""
return hangul1 + hangul2
@functools.cached_property
def romanization(self) -> str:
return _romanize(self.hangul)
@property
def line(self) -> List[str]:
return [
self.syl1.onset,
self.syl1.nucleus,
self.syl2.onset,
self.syl2.nucleus,
self.syl2.coda,
self.shape,
self.jamo,
self.hangul,
self.romanization,
]
def _monosyllables() -> Iterator[Monosyllable]:
# The checks on coda inoculate us against things like /mpip̚/.
# Plain.
for onset in SIMPLE_ONSETS:
for vowel in VOWELS:
for coda in CODAS:
if coda.startswith(onset[0]):
continue
yield Monosyllable(onset, vowel, coda, "CVC")
# Cw. I am treating this as part of the nucleus because that's how it's
# spelled.
for onset in STOP_ONSETS:
for vowel in FRONT_VOWELS:
for coda in CODAS:
if coda.startswith(onset[0]):
continue
yield Monosyllable(onset, "w" + vowel, coda, "CwVC")
# Prenasal.
for stop in STOP_ONSETS:
for nasal in NASAL_ONSETS:
onset = nasal + stop
for vowel in VOWELS:
for coda in STOP_CODAS:
if coda.startswith(stop[0]):
continue
yield Monosyllable(onset, vowel, coda, "NCVC")
# Postnasal.
for stop in STOP_ONSETS:
for nasal in NASAL_ONSETS:
onset = stop + nasal
for vowel in VOWELS:
for coda in STOP_CODAS:
if coda.startswith(stop[0]):
continue
yield Monosyllable(onset, vowel, coda, "CNVC")
def _disyllables() -> Iterator[Disyllable]:
# The checks on coda inoculate us against things like /mpip̚/.
# We avoid similar onsets or vowels in back-to-back syllables too.
# Plain.
for onset1, onset2 in itertools.permutations(SIMPLE_ONSETS, 2):
if onset1.startswith(onset2) or onset2.startswith(onset1):
continue
for vowel1, vowel2 in itertools.permutations(VOWELS, 2):
syl1 = Monosyllable(onset1, vowel1, shape="CV")
for coda in CODAS:
if coda.startswith(onset2[0]):
continue
syl2 = Monosyllable(onset2, vowel2, coda, shape="CVC")
yield Disyllable(syl1, syl2, "CVCVC")
# Cw. I am treating this as part of the nucleus because that's how it's
# spelled.
for onset1, onset2 in itertools.permutations(SIMPLE_ONSETS, 2):
if onset1.startswith(onset2) or onset2.startswith(onset1):
continue
for vowel1, vowel2 in itertools.product(FRONT_VOWELS, VOWELS):
syl1 = Monosyllable(onset1, "w" + vowel1, shape="CwV")
for coda in CODAS:
if coda.startswith(onset2[0]):
continue
syl2 = Monosyllable(onset2, vowel2, coda, shape="CVC")
yield Disyllable(syl1, syl2, "CwVCVC")
# Prenasal.
for stop in STOP_ONSETS:
for nasal in NASAL_ONSETS:
onset1 = nasal + stop
for vowel1, vowel2 in itertools.permutations(VOWELS, 2):
syl1 = Monosyllable(onset1, vowel1, shape="NCV")
for onset2 in SIMPLE_ONSETS:
if onset2.startswith(stop):
continue
for coda in CODAS:
if coda.startswith(onset2[0]):
continue
syl2 = Monosyllable(onset2, vowel2, coda, shape="CVC")
yield Disyllable(syl1, syl2, "NCVCVC")
# Postnasal.
for stop in STOP_ONSETS:
for nasal in NASAL_ONSETS:
onset1 = stop + nasal
for vowel1, vowel2 in itertools.permutations(VOWELS, 2):
syl1 = Monosyllable(onset1, vowel1, shape="CNV")
for onset2 in SIMPLE_ONSETS:
if onset2.startswith(stop):
continue
for coda in CODAS:
if coda.startswith(onset2[0]):
continue
syl2 = Monosyllable(onset2, vowel2, coda, shape="CVC")
yield Disyllable(syl1, syl2, "CNVCVC")
def main():
with open(MONOSYLLABLES, "w") as sink:
tsv_writer = csv.writer(sink, delimiter="\t")
tsv_writer.writerow(
[
"onset",
"nucleus",
"coda",
"shape",
"jamo",
"hangul",
"romanization",
]
)
for entry in _monosyllables():
tsv_writer.writerow(entry.line)
# This probably could be cleverer and focus just on disyllables.
lexicon: Set[str] = set()
with open(LEXICON, "r") as source:
tsv_reader = csv.reader(source, delimiter="\t")
for word, _ in tsv_reader:
try:
lexicon.add(_romanize(word))
except (KeyError, AttributeError): # Raised by the romanizer.
pass
logging.info(f"{len(lexicon):,} lexicon entries")
with open(DISYLLABLES, "w") as sink:
tsv_writer = csv.writer(sink, delimiter="\t")
tsv_writer.writerow(
[
"onset1",
"nucleus1",
"onset2",
"nucleus2",
"coda",
"shape",
"jamo",
"hangul",
"romanization",
]
)
filtered = 0
for entry in _disyllables():
# Filters based on the lexicon.
if entry.romanization and entry.romanization in lexicon:
logging.info(
f"{entry.hangul} ({entry.romanization}) is lexical"
)
filtered += 1
continue
tsv_writer.writerow(entry.line)
logging.info(f"{filtered:,} disyllables filtered")
if __name__ == "__main__":
logging.basicConfig(format="%(levelname)s: %(message)s", level="INFO")
main()