PyHakka 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pyhakka/phon/parser.py ADDED
@@ -0,0 +1,748 @@
1
+ """Parsers converting Hakka transcriptions in multiple schemes into canonical `Syllable` IR."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ import unicodedata
7
+
8
+ from pyhakka.dialects import DEFAULT_DIALECT, DialectInfo, get_dialect
9
+ from pyhakka.phon.schemes import (
10
+ CHAO_TO_DIGITS,
11
+ DEFAULT_HPS_DIACRITICS,
12
+ FROM_SUPERSCRIPT_DIGITS,
13
+ TONE_6_TO_8,
14
+ get_phon_profile,
15
+ normalize_scheme,
16
+ )
17
+ from pyhakka.phon.syllable import (
18
+ CHECKED_CODAS,
19
+ HPS_EXT_ONSETS,
20
+ SYLLABIC_CONSONANTS,
21
+ Syllable,
22
+ )
23
+
24
+ READING_MARKS = frozenset("-=+*@?")
25
+
26
+ # Trailing tone extractor (digits or Chao tone letters)
27
+ _TRAILING_TONE_RE = re.compile(r"([0-9]+|[˩˨˧˦˥]+)$")
28
+ _HPS_DIACRITIC_RE = re.compile(r"([ˊˇˋ+^])$")
29
+
30
+ # Ordered IPA onset table: (ipa_prefix, hps_ext_onset)
31
+ _IPA_ONSETS: tuple[tuple[str, str], ...] = (
32
+ ("tʃʰ", "ch"),
33
+ ("tʂʰ", "ch"),
34
+ ("ʧʰ", "ch"),
35
+ ("tɕʰ", "q"),
36
+ ("tsʰ", "c"),
37
+ ("dʑ", "jj"),
38
+ ("dz", "zz"),
39
+ ("tʃ", "zh"),
40
+ ("tʂ", "zh"),
41
+ ("ʧ", "zh"),
42
+ ("tɕ", "j"),
43
+ ("ts", "z"),
44
+ ("pʰ", "p"),
45
+ ("tʰ", "t"),
46
+ ("kʰ", "k"),
47
+ ("ȶʰ", "q"),
48
+ ("cʰ", "q"),
49
+ ("p'", "p"),
50
+ ("t'", "t"),
51
+ ("k'", "k"),
52
+ ("ts'", "c"),
53
+ ("tʃ'", "ch"),
54
+ ("tʂ'", "ch"),
55
+ ("tɕ'", "q"),
56
+ ("b", "bb"),
57
+ ("p", "b"),
58
+ ("d", "dd"),
59
+ ("t", "d"),
60
+ ("ɡ", "gg"),
61
+ ("g", "gg"),
62
+ ("k", "g"),
63
+ ("m", "m"),
64
+ ("n", "n"),
65
+ ("ŋ", "ng"),
66
+ ("ȵ", "nj"),
67
+ ("ɲ", "nj"),
68
+ ("ɳ", "nj"),
69
+ ("f", "f"),
70
+ ("ɸ", "f"),
71
+ ("v", "v"),
72
+ ("ʋ", "v"),
73
+ ("w", "v"),
74
+ ("l", "l"),
75
+ ("ɬ", "sl"),
76
+ ("θ", "th"),
77
+ ("s", "s"),
78
+ ("z", "zz"),
79
+ ("ʃ", "sh"),
80
+ ("ʂ", "sh"),
81
+ ("ʒ", "rh"),
82
+ ("ʐ", "rh"),
83
+ ("ɕ", "x"),
84
+ ("ç", "x"),
85
+ ("ʑ", "jj"),
86
+ ("ȶ", "j"),
87
+ ("c", "j"),
88
+ ("ɟ", "jj"),
89
+ ("ʝ", "r"),
90
+ ("ɣ", "gh"),
91
+ ("h", "h"),
92
+ ("x", "h"),
93
+ ("ɦ", "hh"),
94
+ ("r", "r"),
95
+ ("ɹ", "r"),
96
+ )
97
+
98
+ _IPA_CODA_MAP: tuple[tuple[str, str], ...] = (
99
+ ("ŋ", "ng"),
100
+ ("m", "m"),
101
+ ("n", "n"),
102
+ ("p", "b"),
103
+ ("t", "d"),
104
+ ("k", "g"),
105
+ ("ʔ", "h"),
106
+ ("ˀ", "h"),
107
+ )
108
+
109
+ _IPA_VOWEL_ATOMS = frozenset("aeioɔɛæəɤʌɜɘɚɑɐᴀᴇɪɒʊɯuyʉøœɵɿʅɨʮʯ")
110
+
111
+ # Valid standalone nuclei in HPS-Ext
112
+ _VALID_NUCLEI = frozenset({"a", "e", "ee", "ae", "i", "ii", "o", "oo", "u", "y", "oe", "er"})
113
+ # Valid medials
114
+ _VALID_MEDIALS = ("i", "u", "y")
115
+
116
+
117
+ def _split_vowel_cluster(vpart: str, has_consonant_coda: bool) -> tuple[str, str, str]:
118
+ """Split a HPS-Ext vowel cluster into `(medial, nucleus, vowel_coda)`.
119
+
120
+ Raises `ValueError` if `vpart` cannot be decomposed cleanly.
121
+ """
122
+ if not vpart:
123
+ raise ValueError("Empty vowel cluster in syllable")
124
+
125
+ if vpart in _VALID_NUCLEI:
126
+ return "", vpart, ""
127
+
128
+ # 1. If there is no consonant coda, check pure diphthong (no medial):
129
+ # e.g., ai, au, ei, eu, oi, ou, eeu, aeu, iiu, ooi, eri, oei
130
+ if not has_consonant_coda:
131
+ for nuc in ("ee", "ae", "oo", "ii", "er", "oe", "a", "e", "o"):
132
+ if vpart.startswith(nuc):
133
+ rem = vpart[len(nuc) :]
134
+ if rem in ("i", "u"):
135
+ return "", nuc, rem
136
+
137
+ # 2. Check medial + (nucleus + optional vowel coda)
138
+ for med in _VALID_MEDIALS:
139
+ if vpart.startswith(med) and len(vpart) > len(med):
140
+ rest = vpart[len(med) :]
141
+ if rest in _VALID_NUCLEI:
142
+ return med, rest, ""
143
+ if not has_consonant_coda:
144
+ for nuc in ("ee", "ae", "oo", "ii", "er", "oe", "a", "e", "o", "i", "u", "y"):
145
+ if rest.startswith(nuc):
146
+ rem = rest[len(nuc) :]
147
+ if rem in ("i", "u"):
148
+ return med, nuc, rem
149
+
150
+ # 3. Fallback for rare MCPDict triphthongs / vowel glides (e.g. `iui`, `uee`, `uoe`, `uoo`)
151
+ if not has_consonant_coda and len(vpart) >= 2 and vpart[-1] in ("i", "u"):
152
+ return "", vpart[:-1], vpart[-1]
153
+ return "", vpart, ""
154
+
155
+
156
+ def _parse_hps_ext_base(base: str) -> tuple[str, str, str, str, bool]:
157
+ """Parse tone-stripped HPS-Ext syllable string into `(onset, medial, nucleus, coda, nasalized)`."""
158
+ if not base:
159
+ raise ValueError("Empty syllable base")
160
+
161
+ # Handle standalone syllabic consonants (m, n, ng, v) with optional glottal coda `-h`
162
+ if base in SYLLABIC_CONSONANTS:
163
+ return "", "", base, "", False
164
+ if base.endswith("h") and base[:-1] in SYLLABIC_CONSONANTS:
165
+ return "", "", base[:-1], "h", False
166
+
167
+ work = base
168
+ onset = ""
169
+ # Strip onset greedily (including optional glottal onset `'`), ensuring rime remains valid
170
+ for cand in HPS_EXT_ONSETS:
171
+ if work.startswith(cand) and len(work) > len(cand):
172
+ rem = work[len(cand) :]
173
+ if rem == "h":
174
+ continue
175
+ onset = cand
176
+ work = rem
177
+ break
178
+
179
+ # Strip glottal stop coda `-h` before `-nn` so nasalized glottal syllables (`-nnh`) parse cleanly
180
+ coda = ""
181
+ if len(work) > 1 and work.endswith("h"):
182
+ coda = "h"
183
+ work = work[:-1]
184
+
185
+ # Check nasalization suffix `-nn`
186
+ nasalized = False
187
+ if len(work) > 2 and work.endswith("nn"):
188
+ nasalized = True
189
+ work = work[:-2]
190
+
191
+ # Check if rime is a syllabic consonant after an onset (e.g. `hng`, `hvh`, `hmh`)
192
+ if work in SYLLABIC_CONSONANTS:
193
+ return onset, "", work, coda, nasalized
194
+
195
+ # Strip remaining consonant codas if vowels remain before it
196
+ if not coda:
197
+ for cand_coda in ("ng", "m", "n", "b", "d", "g"):
198
+ if work.endswith(cand_coda) and len(work) > len(cand_coda):
199
+ coda = cand_coda
200
+ work = work[: -len(cand_coda)]
201
+ break
202
+
203
+ medial, nucleus, vowel_coda = _split_vowel_cluster(work, has_consonant_coda=bool(coda))
204
+ final_coda = coda or vowel_coda
205
+ return onset, medial, nucleus, final_coda, nasalized
206
+
207
+
208
+ def _resolve_tone_pair(
209
+ raw_tone: str,
210
+ is_checked: bool,
211
+ dialect_info: DialectInfo | None,
212
+ force_tone_value: bool = False,
213
+ allow_dialect_tone_value: bool = False,
214
+ ) -> tuple[str, str]:
215
+ """Resolve `(tone_class, tone_value)` from a numeric tone string."""
216
+ if not raw_tone:
217
+ return "", ""
218
+
219
+ is_val = force_tone_value or len(raw_tone) >= 2
220
+ if not is_val and allow_dialect_tone_value and dialect_info is not None and dialect_info.use_tone_value:
221
+ is_val = True
222
+
223
+ if is_val:
224
+ tone_val = raw_tone
225
+ tone_cls = ""
226
+ if dialect_info is not None:
227
+ # Disambiguate single-digit checked tone values (e.g. '1' or '5') vs open tones
228
+ matches = [
229
+ cls for cls, spec in dialect_info.tones.items() if spec.value == tone_val
230
+ ]
231
+ if len(matches) == 1:
232
+ tone_cls = matches[0]
233
+ elif len(matches) > 1:
234
+ checked_matches = [c for c in matches if c in ("7", "8")]
235
+ open_matches = [c for c in matches if c not in ("7", "8")]
236
+ if is_checked and checked_matches:
237
+ tone_cls = checked_matches[0]
238
+ elif not is_checked and open_matches:
239
+ tone_cls = open_matches[0]
240
+ else:
241
+ tone_cls = matches[0]
242
+ return tone_cls, tone_val
243
+
244
+ # Tone class 0-8
245
+ tone_cls = raw_tone
246
+ tone_val = dialect_info.tone_value_for(tone_cls) if dialect_info is not None else ""
247
+ return tone_cls, tone_val
248
+
249
+
250
+ def _parse_hps_ext(
251
+ token: str,
252
+ dialect_info: DialectInfo | None,
253
+ ) -> Syllable:
254
+ raw = token.strip()
255
+ if not raw:
256
+ raise ValueError("Empty syllable token")
257
+
258
+ work = raw
259
+ mark = ""
260
+ while work and work[-1] in READING_MARKS:
261
+ mark = work[-1] + mark
262
+ work = work[:-1]
263
+
264
+ work = work.translate(FROM_SUPERSCRIPT_DIGITS)
265
+ tone_str = ""
266
+ force_val = False
267
+ m = _TRAILING_TONE_RE.search(work)
268
+ if m:
269
+ tone_str = m.group(1)
270
+ if any(c in "˩˨˧˦˥" for c in tone_str):
271
+ tone_str = tone_str.translate(CHAO_TO_DIGITS)
272
+ force_val = True
273
+ work = work[: m.start()]
274
+
275
+ base = work.lower()
276
+ onset, medial, nucleus, coda, nasalized = _parse_hps_ext_base(base)
277
+ tone, tone_val = _resolve_tone_pair(
278
+ tone_str,
279
+ coda in CHECKED_CODAS,
280
+ dialect_info,
281
+ force_tone_value=force_val,
282
+ allow_dialect_tone_value=False,
283
+ )
284
+ return Syllable(
285
+ onset=onset,
286
+ medial=medial,
287
+ nucleus=nucleus,
288
+ coda=coda,
289
+ nasalized=nasalized,
290
+ tone=tone,
291
+ tone_value=tone_val,
292
+ reading_mark=mark,
293
+ raw=raw,
294
+ )
295
+
296
+
297
+ def _parse_hps_diacritic(token: str, dialect_info: DialectInfo | None) -> Syllable:
298
+ raw = token.strip()
299
+ if not raw:
300
+ raise ValueError("Empty syllable token")
301
+ work = raw
302
+ diac = ""
303
+ m = _HPS_DIACRITIC_RE.search(work)
304
+ if m:
305
+ diac = m.group(1)
306
+ work = work[: m.start()]
307
+
308
+ base = work.lower()
309
+ onset, medial, nucleus, coda, nasalized = _parse_hps_ext_base(base)
310
+ is_checked = coda in CHECKED_CODAS
311
+
312
+ slug = dialect_info.slug if dialect_info is not None else "meixian"
313
+ profile = get_phon_profile(slug)
314
+ dmap = profile.hps_diacritics or DEFAULT_HPS_DIACRITICS
315
+
316
+ # Match diacritic back to tone class, respecting checked vs open syllable
317
+ candidates = [cls for cls, mark in dmap.items() if mark == diac]
318
+ tone = ""
319
+ if candidates:
320
+ checked_c = [c for c in candidates if c in ("7", "8")]
321
+ open_c = [c for c in candidates if c not in ("7", "8")]
322
+ if is_checked and checked_c:
323
+ tone = checked_c[0]
324
+ elif not is_checked and open_c:
325
+ tone = open_c[0]
326
+ else:
327
+ tone = candidates[0]
328
+
329
+ tone_val = dialect_info.tone_value_for(tone) if (dialect_info and tone) else ""
330
+ return Syllable(
331
+ onset=onset,
332
+ medial=medial,
333
+ nucleus=nucleus,
334
+ coda=coda,
335
+ nasalized=nasalized,
336
+ tone=tone,
337
+ tone_value=tone_val,
338
+ raw=raw,
339
+ )
340
+
341
+
342
+ def _parse_gd(token: str, dialect_info: DialectInfo | None) -> Syllable:
343
+ """Parse Guangdong Hakka Pinyin (廣東省《客家話拼音方案》, 1-6 tones)."""
344
+ raw = token.strip()
345
+ if not raw:
346
+ raise ValueError("Empty syllable token")
347
+
348
+ work = raw.translate(FROM_SUPERSCRIPT_DIGITS)
349
+ tone6 = ""
350
+ m = _TRAILING_TONE_RE.search(work)
351
+ if m:
352
+ tone6 = m.group(1)
353
+ work = work[: m.start()]
354
+
355
+ base = work.lower()
356
+ if base in ("m", "n", "ng"):
357
+ tone = TONE_6_TO_8.get(tone6, tone6)
358
+ tv = dialect_info.tone_value_for(tone) if dialect_info else ""
359
+ return Syllable("", "", base, "", False, tone, tv, raw=raw)
360
+
361
+ # Normalize Guangdong `ê` -> `e` while distinguishing `e` after z/c/s before m/n/b/d ([ə] -> ii)
362
+ has_circumflex = "ê" in base
363
+ clean = base.replace("ê", "e")
364
+
365
+ # Strip Guangdong onset
366
+ gd_onsets = ("ng", "b", "p", "m", "f", "v", "d", "t", "n", "l", "g", "k", "h", "j", "q", "x", "z", "c", "s", "y")
367
+ onset = ""
368
+ rest = clean
369
+ for cand in gd_onsets:
370
+ if clean.startswith(cand) and len(clean) > len(cand):
371
+ onset = cand
372
+ rest = clean[len(cand) :]
373
+ break
374
+
375
+ # Map Guangdong onsets/finals to HPS-Ext (Meixian standard):
376
+ # 1. `y-` -> zero onset + `i-` (yi -> i, yiu -> iu, yan -> ian, yung -> iung)
377
+ if onset == "y":
378
+ onset = ""
379
+ if not rest.startswith("i"):
380
+ rest = "i" + rest
381
+ # 2. `j/q/x` (palatalized before i) -> `z/c/s`
382
+ elif onset in ("j", "q", "x"):
383
+ onset = {"j": "z", "q": "c", "x": "s"}[onset]
384
+ # 3. `z/c/s` + `i` (apical vowel [ɿ]) -> `ii`
385
+ elif onset in ("z", "c", "s"):
386
+ if rest == "i":
387
+ rest = "ii"
388
+ elif not has_circumflex and rest in ("em", "en", "eb", "ed"):
389
+ rest = "ii" + rest[1:]
390
+
391
+ # Map Guangdong -p/-t/-k if user supplies them alongside standard -b/-d/-g
392
+ if rest.endswith(("p", "t", "k")) and len(rest) > 1:
393
+ rest = rest[:-1] + {"p": "b", "t": "d", "k": "g"}[rest[-1]]
394
+
395
+ full_onset, medial, nucleus, coda, nasalized = _parse_hps_ext_base(onset + rest)
396
+ tone = TONE_6_TO_8.get(tone6, tone6)
397
+ tv = dialect_info.tone_value_for(tone) if dialect_info else ""
398
+ return Syllable(
399
+ onset=full_onset,
400
+ medial=medial,
401
+ nucleus=nucleus,
402
+ coda=coda,
403
+ nasalized=nasalized,
404
+ tone=tone,
405
+ tone_value=tv,
406
+ raw=raw,
407
+ )
408
+
409
+
410
+ def _parse_hkilang(token: str, dialect_info: DialectInfo | None) -> Syllable:
411
+ """Parse HKILANG romanization (1-6 tones, -p/-t/-k codas, `y-` for zero-onset `i-`)."""
412
+ raw = token.strip().rstrip(".")
413
+ if not raw:
414
+ raise ValueError("Empty syllable token")
415
+
416
+ work = raw.translate(FROM_SUPERSCRIPT_DIGITS)
417
+ tone6 = ""
418
+ m = _TRAILING_TONE_RE.search(work)
419
+ if m:
420
+ tone6 = m.group(1)
421
+ work = work[: m.start()]
422
+
423
+ base = work.lower()
424
+ if base.endswith(("p", "t", "k")) and len(base) > 1:
425
+ base = base[:-1] + {"p": "b", "t": "d", "k": "g"}[base[-1]]
426
+
427
+ # HKILANG marks all palatal zero-onsets with `y-` (`yit/yiu/ya/yung`) and uses bare `iu` for 歐
428
+ if base == "iu":
429
+ base = "'iu"
430
+ elif base.startswith("y") and len(base) > 1:
431
+ rem = base[1:]
432
+ base = rem if rem.startswith("i") else ("i" + rem)
433
+
434
+ onset, medial, nucleus, coda, nasalized = _parse_hps_ext_base(base)
435
+ tone = TONE_6_TO_8.get(tone6, tone6)
436
+ tv = dialect_info.tone_value_for(tone) if dialect_info else ""
437
+ return Syllable(
438
+ onset=onset,
439
+ medial=medial,
440
+ nucleus=nucleus,
441
+ coda=coda,
442
+ nasalized=nasalized,
443
+ tone=tone,
444
+ tone_value=tv,
445
+ raw=raw,
446
+ )
447
+
448
+
449
+ def _map_ipa_vowels(vseq: str, onset: str, coda: str, dialect_slug: str) -> str:
450
+ """Convert a cleaned IPA vowel sequence into a HPS-Ext vowel cluster."""
451
+ profile = get_phon_profile(dialect_slug)
452
+
453
+ # Changting diphthong `əɯ` -> `eu` (`iəɯ` -> `iu` or `ieu`)
454
+ if "əɯ" in vseq:
455
+ vseq = vseq.replace("iəɯ", "iu").replace("əɯ", "eu")
456
+ if "ɐɯ" in vseq:
457
+ vseq = vseq.replace("ɐɯ", "eu")
458
+ if "ɑɔ" in vseq:
459
+ vseq = vseq.replace("ɑɔ", "au")
460
+
461
+ # Dabu Baihou `oŋ/ok` -> `ung/ug` vs `ɔŋ/ɔk` -> `ong/og`
462
+ if profile.ung_as_ong and coda in ("ng", "g"):
463
+ if vseq == "o":
464
+ return "u"
465
+ if vseq == "io":
466
+ return "iu"
467
+ if vseq == "ɔ":
468
+ return "o"
469
+ if vseq == "iɔ":
470
+ return "io"
471
+ if vseq == "uɔ":
472
+ return "uo"
473
+
474
+ # Meixian / Sixian `[ə]` after z/c/s before m/n/b/d -> `ii`
475
+ if profile.ii_closed_as_schwa and vseq == "ə" and onset in ("z", "c", "s") and coda in ("m", "n", "b", "d"):
476
+ return "ii"
477
+
478
+ out: list[str] = []
479
+ for ch in vseq:
480
+ if ch in ("ɿ", "ʅ", "ɨ", "ʮ", "ʯ"):
481
+ out.append("ii")
482
+ elif ch == "æ":
483
+ out.append("ee" if profile.ee_ipa == "æ" else "ae")
484
+ elif ch == "ɛ":
485
+ out.append("ee" if profile.ee_ipa == "ɛ" else "e")
486
+ elif ch == "ɔ":
487
+ out.append("oo" if profile.o_oo_contrast else "o")
488
+ elif ch in ("ə", "ɤ", "ʌ", "ɜ", "ɘ", "ɚ"):
489
+ out.append("er")
490
+ elif ch in ("ɑ", "ɐ", "ᴀ", "a"):
491
+ out.append("a")
492
+ elif ch in ("ɪ", "i"):
493
+ out.append("i")
494
+ elif ch in ("ᴇ", "e"):
495
+ out.append("e")
496
+ elif ch in ("ɒ", "o"):
497
+ out.append("o")
498
+ elif ch in ("ʊ", "ɯ", "u"):
499
+ out.append("u")
500
+ elif ch in ("y", "ʉ"):
501
+ out.append("y")
502
+ elif ch in ("ø", "œ", "ɵ"):
503
+ out.append("oe")
504
+ return "".join(out)
505
+
506
+
507
+ def _parse_ipa(
508
+ token: str,
509
+ dialect_info: DialectInfo | None,
510
+ *,
511
+ force_tone_value: bool = False,
512
+ ) -> Syllable:
513
+ """Parse IPA (including MCPDict narrow IPA & diacritics) into canonical `Syllable`."""
514
+ raw = token.strip()
515
+ if not raw:
516
+ raise ValueError("Empty IPA token")
517
+
518
+ # Strip surrounding brackets if provided (e.g. `[ŋin¹¹]`)
519
+ work = raw.strip("[]/ ")
520
+ work = work.replace("`", "")
521
+
522
+ # Strip trailing reading marks (- = + * @ ?)
523
+ mark = ""
524
+ while work and work[-1] in READING_MARKS:
525
+ mark = work[-1] + mark
526
+ work = work[:-1]
527
+
528
+ # Superscript digits in IPA convention (e.g. ŋin¹¹, it¹) signify 5-level tone values
529
+ had_superscript = any(c in "⁰¹²³⁴⁵⁶⁷⁸⁹" for c in work)
530
+ work = work.translate(FROM_SUPERSCRIPT_DIGITS)
531
+ tone_str = ""
532
+ force_val = force_tone_value or had_superscript
533
+ m = _TRAILING_TONE_RE.search(work)
534
+ if m:
535
+ tone_str = m.group(1)
536
+ if any(c in "˩˨˧˦˥" for c in tone_str):
537
+ tone_str = tone_str.translate(CHAO_TO_DIGITS)
538
+ force_val = True
539
+ work = work[: m.start()]
540
+
541
+ # Decompose precomposed nasalized vowels (e.g. ã -> a + \u0303), keeping `ç` intact
542
+ work = unicodedata.normalize("NFD", work).replace("c\u0327", "ç")
543
+
544
+ # Detect vowel nasalization (\u0303 or superscript ⁿ)
545
+ nasalized = "\u0303" in work or "ⁿ" in work
546
+ work = work.replace("\u0303", "").replace("ⁿ", "")
547
+
548
+ # Normalize aspiration apostrophe variants & remove non-phonemic modifiers
549
+ work = work.replace("‘", "'").replace("ʻ", "'").replace("’", "'")
550
+ work = work.replace("\u0361", "") # tie bar
551
+ work = work.replace("\u032F", "") # non-syllabic arch
552
+ work = work.replace("\u031C", "") # less rounded
553
+ work = work.replace("\u030A", "") # voiceless ring
554
+ work = work.replace("\u0307", "") # overdot
555
+ work = work.replace("\u0304", "") # macron
556
+ work = work.replace("ː", "").replace("ˑ", "").replace("̚", "")
557
+ # Superscript micro-glides like ᵘ, ᶠ, ᵗ
558
+ work = work.replace("ᵘ", "u").replace("ᶠ", "").replace("ᵗ", "")
559
+
560
+ # Detect syllabic marker (\u0329 / \u030D)
561
+ has_syllabic_mark = "\u0329" in work or "\u030D" in work
562
+ work = work.replace("\u0329", "").replace("\u030D", "")
563
+
564
+ if not work:
565
+ raise ValueError(f"IPA token {raw!r} has no segmental content")
566
+
567
+ # Initial glottal stop `ʔ`: strip non-phonemic glottal attack on syllabic nasals (`ʔŋ̍3` -> `ng3`),
568
+ # preserve explicit glottal onset `'` before vowels (`ʔiu1` -> `'iu1`) for lossless roundtrip.
569
+ explicit_glottal = False
570
+ if work.startswith("ʔ") and len(work) > 1:
571
+ after_glottal = work[1:]
572
+ if after_glottal in ("m", "n", "ŋ", "ȵ", "ɲ", "v", "ʋ"):
573
+ work = after_glottal
574
+ else:
575
+ explicit_glottal = True
576
+ work = after_glottal
577
+
578
+ # Standalone syllabic consonant (optionally with glottal/stop coda, e.g. `m̩`, `ŋ̍ʔ7`, `ȵ̍3`, `l̩2`)
579
+ _SC_MAP = {"m": "m", "n": "n", "ŋ": "ng", "ȵ": "nj", "ɲ": "nj", "v": "v", "ʋ": "v", "l": "l"}
580
+ if work in _SC_MAP and (work != "l" or has_syllabic_mark):
581
+ nuc = _SC_MAP[work]
582
+ tone, tone_val = _resolve_tone_pair(
583
+ tone_str, False, dialect_info, force_tone_value=force_val, allow_dialect_tone_value=True
584
+ )
585
+ return Syllable(
586
+ onset="",
587
+ medial="",
588
+ nucleus=nuc,
589
+ coda="",
590
+ nasalized=nasalized,
591
+ tone=tone,
592
+ tone_value=tone_val,
593
+ reading_mark=mark,
594
+ raw=raw,
595
+ )
596
+
597
+ slug = dialect_info.slug if dialect_info is not None else "meixian"
598
+
599
+ # IPA palatal glide `j` before vowels/syllabic nasals -> standard zero-onset `i-`
600
+ core = work
601
+ if not explicit_glottal and core.startswith("j") and len(core) > 1:
602
+ after_j = core[1:]
603
+ if any(ch in _IPA_VOWEL_ATOMS for ch in after_j) or after_j in ("m", "n", "ŋ"):
604
+ core = after_j if after_j.startswith("i") else ("i" + after_j)
605
+
606
+ # Strip IPA consonant coda BEFORE onset check when remaining could be syllabic consonant
607
+ coda = ""
608
+ if core.endswith("ɡʔ") and len(core) > 2:
609
+ coda = "h"
610
+ core = core[:-2]
611
+ else:
612
+ for ipa_c, hps_c in _IPA_CODA_MAP:
613
+ if core.endswith(ipa_c) and len(core) > len(ipa_c):
614
+ rem_c = core[: -len(ipa_c)]
615
+ if any(ch in _IPA_VOWEL_ATOMS for ch in rem_c) or rem_c in _SC_MAP or (
616
+ len(rem_c) >= 2 and rem_c[-1] in ("m", "n", "ŋ", "v", "ʋ")
617
+ ):
618
+ coda = hps_c
619
+ core = rem_c
620
+ break
621
+
622
+ # Standalone syllabic consonant with coda (e.g. `ŋʔ7`, `nʔ8`, `ʋʔ8`)
623
+ if core in _SC_MAP and (core != "l" or has_syllabic_mark):
624
+ nuc = _SC_MAP[core]
625
+ tone, tone_val = _resolve_tone_pair(
626
+ tone_str,
627
+ coda in CHECKED_CODAS,
628
+ dialect_info,
629
+ force_tone_value=force_val,
630
+ allow_dialect_tone_value=True,
631
+ )
632
+ return Syllable(
633
+ onset="",
634
+ medial="",
635
+ nucleus=nuc,
636
+ coda=coda,
637
+ nasalized=nasalized,
638
+ tone=tone,
639
+ tone_value=tone_val,
640
+ reading_mark=mark,
641
+ raw=raw,
642
+ )
643
+
644
+ # Parse IPA onset ONLY if remaining string contains a vowel or syllabic consonant (`m/n/ŋ/v/ʋ`)
645
+ onset = "'" if explicit_glottal else ""
646
+ rest = core
647
+ if not explicit_glottal:
648
+ for ipa_pre, hps_on in _IPA_ONSETS:
649
+ if core.startswith(ipa_pre) and len(core) > len(ipa_pre):
650
+ rem = core[len(ipa_pre) :]
651
+ if any(ch in _IPA_VOWEL_ATOMS for ch in rem) or rem in ("m", "n", "ŋ", "v", "ʋ"):
652
+ onset = hps_on
653
+ rest = rem
654
+ break
655
+
656
+ # If dialect folds palatal nasal `ȵ/ɲ` into `ng` (all 10 core dialects do)
657
+ if onset == "nj" and slug in (
658
+ "meixian",
659
+ "changting",
660
+ "xingning",
661
+ "wuhua",
662
+ "dabu-baihou",
663
+ "huiyang-danshui",
664
+ "huiyang-1987",
665
+ "huidong-daling",
666
+ "shenzhen-baoan",
667
+ "hongkong-newterritories",
668
+ ):
669
+ onset = "ng"
670
+
671
+ # Syllabic consonant after an onset (e.g. `lʋ̩2`, `hʋʔ8`, `hmʔ7`)
672
+ if rest in ("m", "n", "ŋ", "v", "ʋ"):
673
+ nuc = _SC_MAP[rest]
674
+ tone, tone_val = _resolve_tone_pair(
675
+ tone_str,
676
+ coda in CHECKED_CODAS,
677
+ dialect_info,
678
+ force_tone_value=force_val,
679
+ allow_dialect_tone_value=True,
680
+ )
681
+ return Syllable(
682
+ onset=onset,
683
+ medial="",
684
+ nucleus=nuc,
685
+ coda=coda,
686
+ nasalized=nasalized,
687
+ tone=tone,
688
+ tone_value=tone_val,
689
+ reading_mark=mark,
690
+ raw=raw,
691
+ )
692
+
693
+ vcluster = _map_ipa_vowels(rest, onset=onset, coda=coda, dialect_slug=slug)
694
+ if not vcluster:
695
+ raise ValueError(f"Could not parse vowel nucleus from IPA {raw!r}")
696
+
697
+ medial, nucleus, vowel_coda = _split_vowel_cluster(vcluster, has_consonant_coda=bool(coda))
698
+ final_coda = coda or vowel_coda
699
+ tone, tone_val = _resolve_tone_pair(
700
+ tone_str,
701
+ final_coda in CHECKED_CODAS,
702
+ dialect_info,
703
+ force_tone_value=force_val,
704
+ allow_dialect_tone_value=True,
705
+ )
706
+ return Syllable(
707
+ onset=onset,
708
+ medial=medial,
709
+ nucleus=nucleus,
710
+ coda=final_coda,
711
+ nasalized=nasalized,
712
+ tone=tone,
713
+ tone_value=tone_val,
714
+ reading_mark=mark,
715
+ raw=raw,
716
+ )
717
+
718
+
719
+ def parse_syllable(
720
+ text: str,
721
+ scheme: str = "hps_ext",
722
+ dialect: str = DEFAULT_DIALECT,
723
+ ) -> Syllable:
724
+ """Parse a single Hakka syllable from `scheme` into a canonical `Syllable`."""
725
+ canon_scheme = normalize_scheme(scheme)
726
+ dialect_info = get_dialect(dialect) if dialect else None
727
+
728
+ if canon_scheme == "hps_ext":
729
+ return _parse_hps_ext(text, dialect_info)
730
+ if canon_scheme == "hps_diacritic":
731
+ return _parse_hps_diacritic(text, dialect_info)
732
+ if canon_scheme in ("ipa", "ipa_value", "ipa_chao"):
733
+ return _parse_ipa(text, dialect_info, force_tone_value=(canon_scheme != "ipa"))
734
+ if canon_scheme == "gd":
735
+ return _parse_gd(text, dialect_info)
736
+ if canon_scheme == "hkilang":
737
+ return _parse_hkilang(text, dialect_info)
738
+ raise ValueError(f"Unsupported scheme for parsing: {scheme!r}")
739
+
740
+
741
+ def parse_syllables(
742
+ text: str,
743
+ scheme: str = "hps_ext",
744
+ dialect: str = DEFAULT_DIALECT,
745
+ ) -> list[Syllable]:
746
+ """Parse a whitespace-separated sequence of syllables into `list[Syllable]`."""
747
+ tokens = [tok for tok in re.split(r"[\s\-]+", text.strip()) if tok]
748
+ return [parse_syllable(tok, scheme=scheme, dialect=dialect) for tok in tokens]