-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpaliscript.py
More file actions
927 lines (781 loc) · 37.7 KB
/
paliscript.py
File metadata and controls
927 lines (781 loc) · 37.7 KB
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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
"""Lightweight Pali script transliteration — Thai, Sinhala, and IAST.
Zero dependencies. Single file. Converts between Thai Pali script,
Sinhala script, and IAST (International Alphabet of Sanskrit
Transliteration), using IAST as pivot for cross-script conversion.
Original transliteration tables and algorithm by Bhante Buddhañāṇo
(Буддханяно) Thera, implemented as LibreOffice StarBasic macros
(ASIAbib/ASIAmod.xba). Rewritten in Python with his permission and
distributed as open-source software.
This is for **Pali scripts** — not modern Thai or Sinhala.
Usage as library:
from paliscript import to_iast, to_thai, sinhala_to_iast, iast_to_sinhala
to_iast("กุสลา ธมฺมา") # "kusalā dḣammā"
sinhala_to_iast("කුසලා ධම්මා") # "kusalā dḣammā"
iast_to_sinhala("kusalā dḣammā") # "කුසලා ධම්මා"
Usage as CLI:
paliscript --to-iast "กุสลา ธมฺมา"
paliscript --to-iast --script sinhala "කුසලා ධම්මා"
paliscript --from-iast --script sinhala "kusalā dḣammā"
paliscript --to-thai "kusalā dhammā" --aspiration digraph
"""
from __future__ import annotations
import argparse
import enum
import sys
import unicodedata
from dataclasses import dataclass
from typing import List, Optional, Tuple
# ---------------------------------------------------------------------------
# Aspiration style enum
# ---------------------------------------------------------------------------
class AspirationStyle(enum.Enum):
"""How aspirated consonants are represented in IAST.
DOTTED_H: kḣ, gḣ, cḣ, jḣ, ṭḣ, ḍḣ, tḣ, dḣ, pḣ, bḣ (Ḣ = U+1E23)
Unambiguous — each aspirate is a single IAST token.
DIGRAPH: kh, gh, ch, jh, ṭh, ḍh, th, dh, ph, bh (plain ASCII h)
Traditional but ambiguous — requires longest-match parsing.
"""
DOTTED_H = "dotted_h"
DIGRAPH = "digraph"
# ---------------------------------------------------------------------------
# Mapping tables (decoded from ASIAmod.xba)
# ---------------------------------------------------------------------------
# Vowels: (Thai char, IAST string, description)
# Index 0 = Yamakkan (silent marker), 1..7 = right vowels, 8..9 = left vowels
VOWELS: List[Tuple[str, str, str]] = [
("\u0E4E", "\u00AA", "yamakkan → feminine ordinal (silent marker)"), # ๎ → ª
("\u0E30", "a", "sara a (short)"), # ะ → a
("\u0E31", "\u1EA1", "mai han akat → ạ"), # ั → ạ
("\u0E32", "\u0101", "sara aa (long) → ā"), # า → ā
("\u0E34", "i", "sara i (short)"), # ิ → i
("\u0E35", "\u012B", "sara ii (long) → ī"), # ี → ī
("\u0E38", "u", "sara u (short)"), # ุ → u
("\u0E39", "\u016B", "sara uu (long) → ū"), # ู → ū
("\u0E40", "e", "sara e (left vowel)"), # เ → e
("\u0E42", "o", "sara o (left vowel)"), # โ → o
]
# Consonants: (Thai char, IAST dotted-H form, IAST digraph form, description)
# Index 0 = O'Ang (อ) which maps to empty string (vowel carrier)
CONSONANTS: List[Tuple[str, str, str, str]] = [
("\u0E2D", "", "", "o'ang (vowel carrier)"), # อ
("\u0E01", "k", "k", "ko kai"), # ก
("\u0E02", "k\u1E23","kh", "kho khai (aspirated k)"), # ข
("\u0E04", "g", "g", "kho khwai"), # ค
("\u0E06", "g\u1E23","gh", "kho ra-khang (aspirated g)"), # ฆ
("\u0E07", "\u1E43", "\u1E43", "ngo ngu (ṃ / niggahita)"), # ง
("\u0E08", "c", "c", "cho chan"), # จ
("\u0E09", "c\u1E23","ch", "cho ching (aspirated c)"), # ฉ
("\u0E0A", "j", "j", "cho chang"), # ช
("\u0E0C", "j\u1E23","jh", "cho choe (aspirated j)"), # ฌ
("\u0E0D", "\u00F1", "\u00F1", "yo ying (ñ)"), # ญ
("\u0E0F", "\u1E6D", "\u1E6D", "to pa-tak (ṭ retroflex)"), # ฏ
("\u0E10", "\u1E6D\u1E23", "\u1E6Dh", "tho than (ṭḣ retroflex asp)"), # ฐ
("\u0E11", "\u1E0D", "\u1E0D", "tho montho (ḍ retroflex)"), # ฑ
("\u0E12", "\u1E0D\u1E23", "\u1E0Dh", "tho phu-thao (ḍḣ retroflex asp)"), # ฒ
("\u0E13", "\u1E47", "\u1E47", "no nen (ṇ retroflex)"), # ณ
("\u0E15", "t", "t", "to tao"), # ต
("\u0E16", "t\u1E23","th", "tho thung (aspirated t)"), # ถ
("\u0E17", "d", "d", "tho thahan"), # ท
("\u0E18", "d\u1E23","dh", "tho thong (aspirated d)"), # ธ
("\u0E19", "n", "n", "no nu"), # น
("\u0E1B", "p", "p", "po pla"), # ป
("\u0E1C", "p\u1E23","ph", "pho phueng (aspirated p)"), # ผ
("\u0E1E", "b", "b", "pho phan"), # พ
("\u0E20", "b\u1E23","bh", "pho sam-phao (aspirated b)"), # ภ
("\u0E21", "m", "m", "mo ma"), # ม
("\u0E22", "y", "y", "yo yak"), # ย
("\u0E23", "r", "r", "ro ruea"), # ร
("\u0E25", "l", "l", "lo ling"), # ล
("\u0E27", "v", "v", "wo waen"), # ว
("\u0E2A", "s", "s", "so suea"), # ส
("\u0E2B", "h", "h", "ho hip"), # ห
("\u0E2C", "\u1E37", "\u1E37", "lo chula (ḷ)"), # ฬ
]
# Special marks: (Thai char, IAST char, description)
SPECIAL_MARKS: List[Tuple[str, str, str]] = [
("\u0E48", "\u02CD", "mai ek → low macron (ˍ)"),
("\u0E49", "\u2193", "mai tho → downwards arrow (↓)"),
("\u0E4A", "\u02C9", "mai tri → high macron (ˉ)"),
("\u0E4B", "\u2191", "mai chattawa → upwards arrow (↑)"),
("\u0E4C", "\u2260", "thanthakhat → not-equal sign (≠)"),
("\u0E2F", "\u00A7", "paiyannoi → section sign (§)"),
]
# Thai Pali uses phinthu (U+0E3A) as virama to suppress inherent vowel
# in consonant clusters (e.g. ธมฺมา = dḣammā, the ฺ under ม kills its vowel)
PHINTHU = "\u0E3A" # ฺ (Thai character phinthu / pinthu)
# Digits: Thai digit → ASCII digit
DIGITS: List[Tuple[str, str]] = [
(chr(0x0E50 + i), str(i)) for i in range(10)
]
# ---------------------------------------------------------------------------
# Sinhala mapping tables (decoded from ASIAmod.xba SINHIAST/IASTSINH)
# ---------------------------------------------------------------------------
# Standalone vowels: (Sinhala char, IAST string, description)
# Used word-initially and between consecutive vowels
SINHALA_VOWELS_STANDALONE: List[Tuple[str, str, str]] = [
("\u0D85", "a", "ayanna (short a)"),
("\u0D86", "\u0101", "aayanna (long ā)"),
("\u0D87", "\u00E6", "aeyanna (æ)"),
("\u0D88", "\u01E3", "aeeyanna (ǣ)"),
("\u0D89", "i", "iyanna (short i)"),
("\u0D8A", "\u012B", "iiyanna (long ī)"),
("\u0D8B", "u", "uyanna (short u)"),
("\u0D8C", "\u016B", "uuyanna (long ū)"),
("\u0D8D", "\u1E5B", "iruyanna (vocalic ṛ)"),
("\u0D8E", "\u1E5D", "iruuyanna (vocalic ṝ)"),
("\u0D8F", "\u013C", "iluyanna (vocalic ļ)"),
("\u0D90", "\u1E39", "iluuyanna (vocalic ḹ)"),
("\u0D91", "e", "eyanna (short e)"),
("\u0D92", "\u0113", "eeyanna (long ē)"),
("\u0D93", "a\u012D", "aiyanna (ai diphthong)"),
("\u0D94", "o", "oyanna (short o)"),
("\u0D95", "\u014D", "ooyanna (long ō)"),
("\u0D96", "a\u016D", "auyanna (au diphthong)"),
]
# Dependent vowel signs: (Sinhala sign, IAST string, description)
# Used after consonants; index 0 is empty (inherent "a" has no sign)
SINHALA_VOWELS_DEPENDENT: List[Tuple[str, str, str]] = [
("", "a", "(inherent a — no sign)"),
("\u0DCF", "\u0101", "aela-pilla (long ā)"),
("\u0DD0", "\u00E6", "ketti aeda-pilla (æ)"),
("\u0DD1", "\u01E3", "diga aeda-pilla (ǣ)"),
("\u0DD2", "i", "ketti is-pilla (short i)"),
("\u0DD3", "\u012B", "diga is-pilla (long ī)"),
("\u0DD4", "u", "ketti paa-pilla (short u)"),
("\u0DD6", "\u016B", "diga paa-pilla (long ū)"),
("\u0DD8", "\u1E5B", "gaetta-pilla (vocalic ṛ)"),
("\u0DF2", "\u1E5D", "diga gaetta-pilla (vocalic ṝ)"),
("\u0DDF", "\u013C", "gayanukitta (vocalic ļ)"),
("\u0DF3", "\u1E39", "diga gayanukitta (vocalic ḹ)"),
("\u0DD9", "e", "kombuva (short e)"),
("\u0DDA", "\u0113", "diga kombuva (long ē)"),
("\u0DDB", "a\u012D", "kombu deka (ai diphthong)"),
("\u0DDC", "o", "kombuva haa aela-pilla (short o)"),
("\u0DDD", "\u014D", "kombuva haa diga aela-pilla (long ō)"),
("\u0DDE", "a\u016D", "kombuva haa gayanukitta (au diphthong)"),
]
# Consonants: (Sinhala char, IAST dotted-H form, IAST digraph form, description)
SINHALA_CONSONANTS: List[Tuple[str, str, str, str]] = [
("\u0D9A", "k", "k", "kayanna"),
("\u0D9B", "k\u1E23", "kh", "mahaapraana kayanna"),
("\u0D9C", "g", "g", "gayanna"),
("\u0D9D", "g\u1E23", "gh", "mahaapraana gayanna"),
("\u0D9E", "\u1E45", "\u1E45", "kantaja naasikyaya (ṅ)"),
("\u0D9F", "\u0148g", "\u0148g", "sanyaka gayanna (ňg ligature)"),
("\u0DA0", "c", "c", "cayanna"),
("\u0DA1", "c\u1E23", "ch", "mahaapraana cayanna"),
("\u0DA2", "j", "j", "jayanna"),
("\u0DA3", "j\u1E23", "jh", "mahaapraana jayanna"),
("\u0DA4", "\u00F1", "\u00F1", "taaluja naasikyaya (ñ)"),
("\u0DA5", "\u0121\u00F1", "\u0121\u00F1", "taaluja sanyooga naaksikyaya (ġñ)"),
("\u0DA6", "\u0148j", "\u0148j", "sanyaka jayanna (ňj ligature)"),
("\u0DA7", "\u1E6D", "\u1E6D", "alpapraana ttayanna (ṭ)"),
("\u0DA8", "\u1E6D\u1E23", "\u1E6Dh", "mahaapraana ttayanna (ṭḣ)"),
("\u0DA9", "\u1E0D", "\u1E0D", "alpapraana ddayanna (ḍ)"),
("\u0DAA", "\u1E0D\u1E23", "\u1E0Dh", "mahaapraana ddayanna (ḍḣ)"),
("\u0DAB", "\u1E47", "\u1E47", "muurdhaja nayanna (ṇ)"),
("\u0DAC", "\u0148\u1E0D", "\u0148\u1E0D", "sanyaka ddayanna (ňḍ ligature)"),
("\u0DAD", "t", "t", "tayanna"),
("\u0DAE", "t\u1E23", "th", "mahaapraana tayanna"),
("\u0DAF", "d", "d", "dayanna"),
("\u0DB0", "d\u1E23", "dh", "mahaapraana dayanna"),
("\u0DB1", "n", "n", "dantaja nayanna"),
("\u0DB3", "\u0148d", "\u0148d", "sanyaka dayanna (ňd ligature)"),
("\u0DB4", "p", "p", "payanna"),
("\u0DB5", "p\u1E23", "ph", "mahaapraana payanna"),
("\u0DB6", "b", "b", "bayanna"),
("\u0DB7", "b\u1E23", "bh", "mahaapraana bayanna"),
("\u0DB8", "m", "m", "mayanna"),
("\u0DB9", "\u1E3Fb", "\u1E3Fb", "amba bayanna (ḿb ligature)"),
("\u0DBA", "y", "y", "yayanna"),
("\u0DBB", "r", "r", "rayanna"),
("\u0DBD", "l", "l", "dantaja layanna"),
("\u0DC0", "v", "v", "vayanna"),
("\u0DC1", "\u015B", "\u015B", "taaluja sayanna (ś)"),
("\u0DC2", "\u1E63", "\u1E63", "muurdhaja sayanna (ṣ)"),
("\u0DC3", "s", "s", "dantaja sayanna"),
("\u0DC4", "h", "h", "hayanna"),
("\u0DC5", "\u1E37", "\u1E37", "muurdhaja layanna (ḷ)"),
("\u0DC6", "f", "f", "fayanna"),
]
# Sinhala special marks
SINHALA_VIRAMA = "\u0DCA" # Hal kirīma (kills inherent vowel)
SINHALA_ANUSVARA = "\u0D82" # → ṃ (U+1E43)
SINHALA_VISARGA = "\u0D83" # → ḥ (U+1E25)
SINHALA_ZWJ = "\u200D" # Zero-width joiner (used in ligatures)
# ---------------------------------------------------------------------------
# Derived lookup structures (built at import time)
# ---------------------------------------------------------------------------
# Thai → IAST lookups
_THAI_CONSONANT_TO_IAST: dict[str, str] = {} # dotted-H form
for _t, _d, _s, _desc in CONSONANTS:
_THAI_CONSONANT_TO_IAST[_t] = _d
_THAI_VOWEL_TO_IAST: dict[str, str] = {}
for _t, _r, _desc in VOWELS:
_THAI_VOWEL_TO_IAST[_t] = _r
_THAI_SPECIAL_TO_IAST: dict[str, str] = {}
for _t, _r, _desc in SPECIAL_MARKS:
_THAI_SPECIAL_TO_IAST[_t] = _r
_THAI_DIGIT_TO_ASCII: dict[str, str] = {}
for _t, _a in DIGITS:
_THAI_DIGIT_TO_ASCII[_t] = _a
# Set of left-vowel Thai characters (precede their consonant in script)
_LEFT_VOWELS_THAI = {"\u0E40", "\u0E42"} # เ, โ
# Set of all Thai consonant characters
_THAI_CONSONANTS = {t for t, _, _, _ in CONSONANTS}
# O'Ang character
_OANG = "\u0E2D" # อ
# Set of all right-vowel Thai characters (excluding left vowels)
_RIGHT_VOWELS_THAI = {t for t, _, _ in VOWELS if t not in _LEFT_VOWELS_THAI}
# IAST → Thai lookups (dotted-H form, sorted longest-first for matching)
_IAST_CONSONANT_TO_THAI: dict[str, str] = {} # dotted-H IAST → Thai
for _t, _d, _s, _desc in CONSONANTS:
if _d: # skip O'Ang (empty IAST)
_IAST_CONSONANT_TO_THAI[_d] = _t
_IAST_VOWEL_TO_THAI_RIGHT: dict[str, str] = {} # IAST vowel → Thai right form
_IAST_VOWEL_TO_THAI_FULL: dict[str, str] = {} # IAST vowel → Thai standalone (=right for Pali)
for _t, _r, _desc in VOWELS:
_IAST_VOWEL_TO_THAI_RIGHT[_r] = _t
_IAST_VOWEL_TO_THAI_FULL[_r] = _t
_IAST_SPECIAL_TO_THAI: dict[str, str] = {}
for _t, _r, _desc in SPECIAL_MARKS:
_IAST_SPECIAL_TO_THAI[_r] = _t
_ASCII_DIGIT_TO_THAI: dict[str, str] = {}
for _t, _a in DIGITS:
_ASCII_DIGIT_TO_THAI[_a] = _t
# Digraph → dotted-H normalization map (only for aspirates)
_DIGRAPH_TO_DOTTED: dict[str, str] = {}
for _t, _d, _s, _desc in CONSONANTS:
if _d != _s and _d and _s: # aspirated: digraph differs from dotted
_DIGRAPH_TO_DOTTED[_s] = _d
# All IAST tokens for longest-match, sorted longest first
_ALL_IAST_TOKENS: list[str] = sorted(
set(
list(_IAST_CONSONANT_TO_THAI.keys())
+ list(_IAST_VOWEL_TO_THAI_RIGHT.keys())
+ list(_IAST_SPECIAL_TO_THAI.keys())
+ list(_ASCII_DIGIT_TO_THAI.keys())
),
key=lambda x: (-len(x), x),
)
# All digraph IAST tokens for longest-match normalization, sorted longest first
_ALL_DIGRAPH_TOKENS: list[str] = sorted(
_DIGRAPH_TO_DOTTED.keys(),
key=lambda x: (-len(x), x),
)
# Sinhala → IAST lookups
_SINH_CONSONANT_TO_IAST: dict[str, str] = {}
for _s, _d, _dg, _desc in SINHALA_CONSONANTS:
_SINH_CONSONANT_TO_IAST[_s] = _d
_SINH_VOWEL_STANDALONE_TO_IAST: dict[str, str] = {}
for _s, _r, _desc in SINHALA_VOWELS_STANDALONE:
_SINH_VOWEL_STANDALONE_TO_IAST[_s] = _r
_SINH_VOWEL_DEPENDENT_TO_IAST: dict[str, str] = {}
for _s, _r, _desc in SINHALA_VOWELS_DEPENDENT:
if _s: # skip empty (inherent a)
_SINH_VOWEL_DEPENDENT_TO_IAST[_s] = _r
# IAST → Sinhala lookups
_IAST_TO_SINH_CONSONANT: dict[str, str] = {}
for _s, _d, _dg, _desc in SINHALA_CONSONANTS:
_IAST_TO_SINH_CONSONANT[_d] = _s
_IAST_TO_SINH_VOWEL_STANDALONE: dict[str, str] = {}
for _s, _r, _desc in SINHALA_VOWELS_STANDALONE:
_IAST_TO_SINH_VOWEL_STANDALONE[_r] = _s
_IAST_TO_SINH_VOWEL_DEPENDENT: dict[str, str] = {}
for _s, _r, _desc in SINHALA_VOWELS_DEPENDENT:
_IAST_TO_SINH_VOWEL_DEPENDENT[_r] = _s # includes "" for "a"
# Sinhala digraph → dotted-H normalization (same aspirates as Thai plus extras)
_SINH_DIGRAPH_TO_DOTTED: dict[str, str] = {}
for _s, _d, _dg, _desc in SINHALA_CONSONANTS:
if _d != _dg and _d and _dg:
_SINH_DIGRAPH_TO_DOTTED[_dg] = _d
# Sets of Sinhala characters
_SINH_CONSONANTS = {s for s, _, _, _ in SINHALA_CONSONANTS}
_SINH_VOWELS_STANDALONE = {s for s, _, _ in SINHALA_VOWELS_STANDALONE}
_SINH_VOWELS_DEPENDENT = {s for s, _, _ in SINHALA_VOWELS_DEPENDENT if s}
# All Sinhala IAST consonant tokens (dotted-H), sorted longest first
_ALL_SINH_IAST_CONSONANT_TOKENS: list[str] = sorted(
_IAST_TO_SINH_CONSONANT.keys(),
key=lambda x: (-len(x), x),
)
# All Sinhala IAST vowel tokens, sorted longest first
_ALL_SINH_IAST_VOWEL_TOKENS: list[str] = sorted(
_IAST_TO_SINH_VOWEL_STANDALONE.keys(),
key=lambda x: (-len(x), x),
)
# All Sinhala digraph tokens for normalization, sorted longest first
_ALL_SINH_DIGRAPH_TOKENS: list[str] = sorted(
_SINH_DIGRAPH_TO_DOTTED.keys(),
key=lambda x: (-len(x), x),
)
# ---------------------------------------------------------------------------
# Token types and dataclass
# ---------------------------------------------------------------------------
class _TokenType(enum.Enum):
CONSONANT = "C"
VOWEL = "V"
SPECIAL = "S"
DIGIT = "D"
PASSTHROUGH = "P"
@dataclass
class _Token:
type: _TokenType
iast: str # IAST form
thai: str # Thai form
is_left_vowel: bool = False # True for เ/โ vowels
had_inherent_a: bool = False # True if consonant's following "a" was absorbed
# ---------------------------------------------------------------------------
# Internal helpers
# ---------------------------------------------------------------------------
def _normalize_nfc(text: str) -> str:
"""Apply Unicode NFC normalization."""
return unicodedata.normalize("NFC", text)
def _normalize_digraphs(text: str) -> str:
"""Convert digraph aspiration (kh, gh, ...) to dotted-H (kḣ, gḣ, ...).
Uses longest-match to avoid false positives. Only converts known
aspirate digraphs; standalone 'h' is left alone.
"""
result: list[str] = []
i = 0
while i < len(text):
matched = False
for token in _ALL_DIGRAPH_TOKENS:
if text[i:i + len(token)] == token:
result.append(_DIGRAPH_TO_DOTTED[token])
i += len(token)
matched = True
break
if not matched:
result.append(text[i])
i += 1
return "".join(result)
def _classify_iast(token_str: str) -> Optional[_TokenType]:
"""Classify an IAST string as consonant, vowel, special, or digit."""
if token_str in _IAST_CONSONANT_TO_THAI:
return _TokenType.CONSONANT
if token_str in _IAST_VOWEL_TO_THAI_RIGHT:
return _TokenType.VOWEL
if token_str in _IAST_SPECIAL_TO_THAI:
return _TokenType.SPECIAL
if token_str in _ASCII_DIGIT_TO_THAI:
return _TokenType.DIGIT
return None
def _tokenize_iast(text: str) -> list[_Token]:
"""Tokenize IAST text into a stream of typed tokens using longest match."""
tokens: list[_Token] = []
i = 0
while i < len(text):
matched = False
for candidate in _ALL_IAST_TOKENS:
if text[i:i + len(candidate)] == candidate:
ttype = _classify_iast(candidate)
if ttype == _TokenType.CONSONANT:
thai = _IAST_CONSONANT_TO_THAI[candidate]
elif ttype == _TokenType.VOWEL:
thai = _IAST_VOWEL_TO_THAI_RIGHT[candidate]
elif ttype == _TokenType.SPECIAL:
thai = _IAST_SPECIAL_TO_THAI[candidate]
elif ttype == _TokenType.DIGIT:
thai = _ASCII_DIGIT_TO_THAI[candidate]
else:
continue
is_lv = (ttype == _TokenType.VOWEL and thai in _LEFT_VOWELS_THAI)
tokens.append(_Token(type=ttype, iast=candidate, thai=thai,
is_left_vowel=is_lv))
i += len(candidate)
matched = True
break
if not matched:
tokens.append(_Token(type=_TokenType.PASSTHROUGH, iast=text[i],
thai=text[i]))
i += 1
return tokens
def _is_word_boundary_before(tokens: list[_Token], idx: int) -> bool:
"""Check if position idx is at a word boundary (start of text or after whitespace/passthrough)."""
if idx == 0:
return True
prev = tokens[idx - 1]
if prev.type == _TokenType.PASSTHROUGH and prev.iast.strip() == "":
return True
return False
def _insert_oang(tokens: list[_Token]) -> list[_Token]:
"""Insert O'Ang (อ) before word-initial vowels and between consecutive vowels."""
result: list[_Token] = []
oang_token = _Token(type=_TokenType.CONSONANT, iast="", thai=_OANG)
for i, tok in enumerate(tokens):
if tok.type == _TokenType.VOWEL:
# Word-initial vowel: insert O'Ang
if _is_word_boundary_before(tokens, i):
result.append(oang_token)
# Consecutive vowels: insert O'Ang between them
elif i > 0 and tokens[i - 1].type == _TokenType.VOWEL:
result.append(oang_token)
result.append(tok)
return result
def _reorder_left_vowels(tokens: list[_Token]) -> list[_Token]:
"""Reorder left vowels: [consonant, e/o] → [เ/โ, consonant].
In Thai, left vowels (เ, โ) are written before the consonant cluster.
In IAST they come after. This pass swaps them.
"""
result: list[_Token] = []
i = 0
while i < len(tokens):
# Look for pattern: consonant(s) followed by a left-vowel
if (tokens[i].type == _TokenType.CONSONANT
and i + 1 < len(tokens)
and tokens[i + 1].type == _TokenType.VOWEL
and tokens[i + 1].is_left_vowel):
# Collect the consonant cluster (consonants possibly separated by phinthu)
cluster_start = i
j = i
while j < len(tokens) and tokens[j].type == _TokenType.CONSONANT:
j += 1
# Check if next after cluster is the left vowel
if j < len(tokens) and tokens[j].type == _TokenType.VOWEL and tokens[j].is_left_vowel:
# Emit: left-vowel, then the consonant cluster
result.append(tokens[j])
for k in range(cluster_start, j):
result.append(tokens[k])
i = j + 1
continue
result.append(tokens[i])
i += 1
return result
# ---------------------------------------------------------------------------
# Public API: Thai → IAST
# ---------------------------------------------------------------------------
def to_iast(
text: str,
aspiration: AspirationStyle = AspirationStyle.DOTTED_H,
) -> str:
"""Convert Thai Pali text to IAST.
Thai Pali uses an inherent vowel system: a consonant without an explicit
vowel sign or phinthu (virama) carries an inherent short "a". This "a"
is written explicitly in IAST output.
Args:
text: Thai Pali text.
aspiration: How to represent aspirated consonants in the output.
DOTTED_H (default): kḣ, gḣ, ...
DIGRAPH: kh, gh, ...
Returns:
IAST transliteration string.
"""
text = _normalize_nfc(text)
result: list[str] = []
i = 0
n = len(text)
while i < n:
ch = text[i]
# Left vowel (เ, โ): look ahead for consonant cluster, then reorder
if ch in _LEFT_VOWELS_THAI:
vowel_iast = _THAI_VOWEL_TO_IAST[ch]
j = i + 1
consonant_parts: list[str] = []
while j < n and text[j] in _THAI_CONSONANTS:
consonant_parts.append(_THAI_CONSONANT_TO_IAST[text[j]])
j += 1
# Phinthu continues the cluster
if j < n and text[j] == PHINTHU:
j += 1
continue
break
if consonant_parts:
result.extend(consonant_parts)
result.append(vowel_iast)
i = j
else:
result.append(vowel_iast)
i += 1
continue
# Consonant
if ch in _THAI_CONSONANTS:
ciast = _THAI_CONSONANT_TO_IAST[ch]
j = i + 1
# Right vowel follows → consonant + that vowel
if j < n and text[j] in _RIGHT_VOWELS_THAI:
result.append(ciast)
result.append(_THAI_VOWEL_TO_IAST[text[j]])
i = j + 1
# Phinthu follows → suppress inherent vowel (cluster)
elif j < n and text[j] == PHINTHU:
result.append(ciast)
i = j + 1
# Anything else: bare consonant → inherent "a"
# (left-vowel, another consonant, special mark, whitespace, end)
# O'Ang maps to empty string and does NOT get inherent "a"
else:
result.append(ciast)
if ciast: # not O'Ang
result.append("a")
i = j
continue
# Right vowel without preceding consonant (unusual in well-formed text)
if ch in _RIGHT_VOWELS_THAI:
result.append(_THAI_VOWEL_TO_IAST[ch])
i += 1
continue
# Phinthu appearing unexpectedly — skip
if ch == PHINTHU:
i += 1
continue
# Special marks
if ch in _THAI_SPECIAL_TO_IAST:
result.append(_THAI_SPECIAL_TO_IAST[ch])
i += 1
continue
# Digits
if ch in _THAI_DIGIT_TO_ASCII:
result.append(_THAI_DIGIT_TO_ASCII[ch])
i += 1
continue
# Passthrough (spaces, punctuation, etc.)
result.append(ch)
i += 1
output = "".join(result)
# Post-processing: convert dotted-H to digraph if requested
if aspiration == AspirationStyle.DIGRAPH:
output = output.replace("\u1E23", "h") # Ḣ → h
return output
# ---------------------------------------------------------------------------
# Public API: IAST → Thai
# ---------------------------------------------------------------------------
def to_thai(
text: str,
aspiration: AspirationStyle = AspirationStyle.DOTTED_H,
) -> str:
"""Convert IAST text to Thai Pali.
Handles the inherent vowel system: IAST "a" after a consonant produces
a bare Thai consonant (no vowel sign). Other vowels produce the
appropriate Thai vowel sign. Consecutive consonants without vowels
between them get phinthu (virama).
Args:
text: IAST transliteration of Pali text.
aspiration: Which aspiration style the input uses.
DOTTED_H (default): input has kḣ, gḣ, ...
DIGRAPH: input has kh, gh, ... (will be normalized)
Returns:
Thai Pali text.
"""
text = _normalize_nfc(text)
# Step 1: Normalize digraphs to dotted-H if needed
if aspiration == AspirationStyle.DIGRAPH:
text = _normalize_digraphs(text)
# Step 2: Tokenize
tokens = _tokenize_iast(text)
# Step 3: Absorb inherent "a" — when a consonant is followed by IAST
# "a", the "a" is the inherent vowel and produces no vowel sign in
# Thai (bare consonant). Mark the consonant and drop the "a" token.
absorbed: set[int] = set()
for idx in range(len(tokens) - 1):
if (tokens[idx].type == _TokenType.CONSONANT
and tokens[idx + 1].type == _TokenType.VOWEL
and tokens[idx + 1].iast == "a"):
tokens[idx].had_inherent_a = True
absorbed.add(idx + 1)
intermediate: list[_Token] = [
tok for idx, tok in enumerate(tokens) if idx not in absorbed
]
# Step 4: Insert O'Ang before word-initial vowels and between consecutive vowels
intermediate = _insert_oang(intermediate)
# Step 5: Insert phinthu between consecutive consonants.
# Must happen BEFORE left-vowel reordering so that the original
# vowel positions are still between consonants they belong to.
# Skip phinthu after consonants whose inherent "a" was absorbed —
# those are bare consonants, not part of a cluster.
phinthu_tok = _Token(type=_TokenType.SPECIAL, iast="", thai=PHINTHU)
with_phinthu: list[_Token] = []
for idx, tok in enumerate(intermediate):
with_phinthu.append(tok)
if (tok.type == _TokenType.CONSONANT
and tok.thai != ""
and not tok.had_inherent_a
and idx + 1 < len(intermediate)
and intermediate[idx + 1].type == _TokenType.CONSONANT
and intermediate[idx + 1].thai != ""):
with_phinthu.append(phinthu_tok)
# Step 6: Reorder left vowels (now phinthu tokens are in place,
# so reordering won't create false consonant adjacencies)
with_phinthu = _reorder_left_vowels(with_phinthu)
return "".join(tok.thai for tok in with_phinthu)
# ---------------------------------------------------------------------------
# Public API: Sinhala → IAST
# ---------------------------------------------------------------------------
def sinhala_to_iast(
text: str,
aspiration: AspirationStyle = AspirationStyle.DOTTED_H,
) -> str:
"""Convert Sinhala Pali text to IAST.
Follows the SINHIAST algorithm from the original macro:
1. Remove ZWJ characters (decompose visual ligatures)
2. Replace standalone vowels → IAST
3. Replace consonants → IAST + inherent "a"
4. Replace "a" + dependent vowel → IAST vowel (removes extra "a")
5. Remove "a" before virama (virama kills inherent vowel)
6. Anusvara → ṃ, Visarga → ḥ
Args:
text: Sinhala Pali text.
aspiration: How to represent aspirated consonants in the output.
Returns:
IAST transliteration string.
"""
text = _normalize_nfc(text)
# Step 1: Remove ZWJ (decomposes ligatures)
text = text.replace(SINHALA_ZWJ, "")
# Step 2: Replace standalone vowels → IAST
for sinh, iast, _desc in SINHALA_VOWELS_STANDALONE:
text = text.replace(sinh, iast)
# Step 3: Replace consonants → IAST + inherent "a"
for sinh, iast_d, _iast_s, _desc in SINHALA_CONSONANTS:
text = text.replace(sinh, iast_d + "a")
# Step 4: Replace "a" + dependent vowel → IAST vowel
for sinh, iast, _desc in SINHALA_VOWELS_DEPENDENT:
if sinh: # skip empty (inherent a)
text = text.replace("a" + sinh, iast)
# Step 5: Remove "a" before virama
text = text.replace("a" + SINHALA_VIRAMA, "")
# Step 6: Anusvara and Visarga
text = text.replace(SINHALA_ANUSVARA, "\u1E43") # → ṃ
text = text.replace(SINHALA_VISARGA, "\u1E25") # → ḥ
# Post-processing: convert dotted-H to digraph if requested
if aspiration == AspirationStyle.DIGRAPH:
text = text.replace("\u1E23", "h")
return text
# ---------------------------------------------------------------------------
# Public API: IAST → Sinhala
# ---------------------------------------------------------------------------
def _normalize_sinh_digraphs(text: str) -> str:
"""Convert digraph aspiration to dotted-H for Sinhala consonant set."""
result: list[str] = []
i = 0
while i < len(text):
matched = False
for token in _ALL_SINH_DIGRAPH_TOKENS:
if text[i:i + len(token)] == token:
result.append(_SINH_DIGRAPH_TO_DOTTED[token])
i += len(token)
matched = True
break
if not matched:
result.append(text[i])
i += 1
return "".join(result)
def iast_to_sinhala(
text: str,
aspiration: AspirationStyle = AspirationStyle.DOTTED_H,
) -> str:
"""Convert IAST text to Sinhala script.
Follows the IASTSINH algorithm from the original macro:
1. Normalize digraphs if needed
2. Collapse composite vowels (aĭ→single, aŭ→single)
3. Word-initial vowels → standalone Sinhala vowels
4. Consonants → Sinhala + virama
5. Virama + vowel → dependent vowel sign
6. ṃ → Anusvara, ḥ → Visarga
7. Remaining vowels → standalone Sinhala vowels
Args:
text: IAST transliteration of Pali text.
aspiration: Which aspiration style the input uses.
Returns:
Sinhala text.
"""
text = _normalize_nfc(text)
# Step 1: Normalize digraphs to dotted-H if needed
if aspiration == AspirationStyle.DIGRAPH:
text = _normalize_sinh_digraphs(text)
# Step 2: Collapse composite vowels aĭ and aŭ into single chars
# (matches macro's VIASTa(14)=Chr(&H12d), VIASTa(17)=Chr(&H16d))
text = text.replace("a\u012D", "\u012D") # aĭ → ĭ (temporary single char)
text = text.replace("a\u016D", "\u016D") # aŭ → ŭ (temporary single char)
# Step 3: Word-initial vowels → standalone Sinhala vowels
# The macro uses \< (word boundary). We match start-of-string and after
# whitespace/punctuation.
for sinh, iast, _desc in SINHALA_VOWELS_STANDALONE:
# Replace at start of string
if text.startswith(iast):
text = sinh + text[len(iast):]
# Replace after word boundaries (whitespace, punctuation)
i = 1
while i < len(text):
if i >= len(iast) and text[i:i + len(iast)] == iast:
# Check if previous char is a word boundary
prev = text[i - 1]
if prev in (" ", "\t", "\n", "\r", ".", ",", ";", ":", "!", "?",
"(", ")", "[", "]", "{", "}", '"', "'", "\u2014",
"\u2013", "/"):
text = text[:i] + sinh + text[i + len(iast):]
i += len(sinh)
continue
i += 1
# Step 4: Consonants → Sinhala + virama (longest-match order)
for iast_token in _ALL_SINH_IAST_CONSONANT_TOKENS:
sinh = _IAST_TO_SINH_CONSONANT[iast_token]
text = text.replace(iast_token, sinh + SINHALA_VIRAMA)
# Step 5: Virama + IAST vowel → dependent vowel sign
for sinh_dep, iast, _desc in SINHALA_VOWELS_DEPENDENT:
if sinh_dep: # non-empty dependent sign
text = text.replace(SINHALA_VIRAMA + iast, sinh_dep)
else:
# Inherent "a": virama + "a" → remove virama (bare consonant)
text = text.replace(SINHALA_VIRAMA + "a", "")
# Step 6: Anusvara and Visarga
text = text.replace("\u1E43", SINHALA_ANUSVARA) # ṃ → Anusvara
text = text.replace("\u1E25", SINHALA_VISARGA) # ḥ → Visarga
# Step 7: Remaining IAST vowels → standalone Sinhala vowels
# (handles vowel-vowel sequences that weren't at word boundaries)
for sinh, iast, _desc in SINHALA_VOWELS_STANDALONE:
text = text.replace(iast, sinh)
return text
# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------
def main(argv: Optional[list[str]] = None) -> None:
"""Command-line interface."""
parser = argparse.ArgumentParser(
description="paliscript — Pali script transliteration (Thai, Sinhala, IAST)",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=(
"Examples:\n"
' %(prog)s --to-iast "กุสลา ธมฺมา"\n'
' %(prog)s --to-iast --script sinhala "කුසලා ධම්මා"\n'
' %(prog)s --to-thai "kusalā dḣammā"\n'
' %(prog)s --from-iast --script sinhala "kusalā dḣammā"\n'
' %(prog)s --to-thai --aspiration digraph "kusalā dhammā"\n'
" cat pali.txt | %(prog)s --to-iast\n"
),
)
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument("--to-iast", action="store_true",
help="Convert source script → IAST")
group.add_argument("--to-thai", action="store_true",
help="Convert IAST → Thai Pali")
group.add_argument("--from-iast", action="store_true",
help="Convert IAST → target script (use --script)")
parser.add_argument("--script", choices=["thai", "sinhala"],
default="thai",
help="Source/target script (default: thai)")
parser.add_argument("--aspiration", choices=["dotted_h", "digraph"],
default="dotted_h",
help="Aspiration style (default: dotted_h)")
parser.add_argument("text", nargs="?", default=None,
help="Text to convert (reads stdin if omitted)")
args = parser.parse_args(argv)
asp = (AspirationStyle.DIGRAPH if args.aspiration == "digraph"
else AspirationStyle.DOTTED_H)
if args.text is not None:
text = args.text
else:
text = sys.stdin.read()
if args.to_iast:
if args.script == "sinhala":
print(sinhala_to_iast(text, aspiration=asp), end="")
else:
print(to_iast(text, aspiration=asp), end="")
elif args.from_iast:
if args.script == "sinhala":
print(iast_to_sinhala(text, aspiration=asp), end="")
else:
print(to_thai(text, aspiration=asp), end="")
else: # --to-thai
print(to_thai(text, aspiration=asp), end="")
if __name__ == "__main__":
main()