pycotovia 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.
pycotovia/__init__.py ADDED
@@ -0,0 +1,6 @@
1
+ """pycotovia — pure-Python Cotovia G2P phonemizer for Galician and Spanish."""
2
+
3
+ from .phonemize import phonemize, Phonemizer
4
+ from .phonemes import COTOVIA2IPA, cotovia_to_ipa
5
+
6
+ __version__ = "0.1.0"
pycotovia/__main__.py ADDED
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env python3
2
+ """Allow `python -m pycotovia`."""
3
+
4
+ from pycotovia.cli import main
5
+
6
+ main()
pycotovia/charset.py ADDED
@@ -0,0 +1,166 @@
1
+ """Latin-1 character classification — direct port of letras.hpp/cpp, ansi.hpp."""
2
+
3
+ # Latin-1 character constants
4
+ a_acentuada = 0xE1 # á
5
+ e_acentuada = 0xE9 # é
6
+ i_acentuada = 0xED # í
7
+ o_acentuada = 0xF3 # ó
8
+ u_acentuada = 0xFA # ú
9
+ u_con_dierese = 0xFC # ü
10
+ i_con_dierese = 0xEF # ï
11
+ e_con_dierese = 0xEB # ë
12
+ enne_minuscula = 0xF1 # ñ
13
+ cedilla_minuscula = 0xE7 # ç
14
+
15
+ VOCAL_MINUSCULA_RARA = {
16
+ 0xE0, 0xE1, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6,
17
+ 0xE8, 0xE9, 0xEA, 0xEB,
18
+ 0xEC, 0xED, 0xEE, 0xEF,
19
+ 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF8,
20
+ 0xF9, 0xFA, 0xFB, 0xFC,
21
+ 0xFD, 0xFE, 0xFF,
22
+ }
23
+
24
+ VOCAL_MAIUSCULA_RARA = {
25
+ 0xC0, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6,
26
+ 0xC8, 0xC9, 0xCA, 0xCB,
27
+ 0xCC, 0xCD, 0xCE, 0xCF,
28
+ 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD8,
29
+ 0xD9, 0xDA, 0xDB, 0xDC,
30
+ 0xDD, 0xDE,
31
+ }
32
+
33
+ _to_minuscula = list(range(256))
34
+ for i in range(65, 91):
35
+ _to_minuscula[i] = i + 32
36
+ EXTENDED_LOWER = {
37
+ 0xC0: 0xE0, 0xC1: 0xE1, 0xC2: 0xE2, 0xC3: 0xE3,
38
+ 0xC4: 0xE4, 0xC5: 0xE5, 0xC6: 0xE6,
39
+ 0xC7: 0xE7, 0xC8: 0xE8, 0xC9: 0xE9, 0xCA: 0xEA,
40
+ 0xCB: 0xEB, 0xCC: 0xEC, 0xCD: 0xED, 0xCE: 0xEE,
41
+ 0xCF: 0xEF, 0xD1: 0xF1, 0xD2: 0xF2, 0xD3: 0xF3,
42
+ 0xD4: 0xF4, 0xD5: 0xF5, 0xD6: 0xF6, 0xD8: 0xF8,
43
+ 0xD9: 0xF9, 0xDA: 0xFA, 0xDB: 0xFB, 0xDC: 0xFC,
44
+ 0xDD: 0xFD, 0xDE: 0xFE, 0xDF: 0xDF,
45
+ }
46
+ for k, v in EXTENDED_LOWER.items():
47
+ _to_minuscula[k] = v
48
+
49
+
50
+ def to_minuscula(b: int) -> int:
51
+ return _to_minuscula[b & 0xFF]
52
+
53
+
54
+ def to_minusculas(s: str) -> str:
55
+ return "".join(chr(to_minuscula(ord(c))) for c in s)
56
+
57
+
58
+ def vocal_minuscula_acentuada(c: str) -> bool:
59
+ return ord(c) in (a_acentuada, e_acentuada, i_acentuada, o_acentuada, u_acentuada)
60
+
61
+
62
+ def vocal_maiuscula_acentuada(c: str) -> bool:
63
+ b = ord(c)
64
+ return b in (0xC1, 0xC9, 0xCD, 0xD3, 0xDA)
65
+
66
+
67
+ def vocal_acentuada(c: str) -> bool:
68
+ return vocal_minuscula_acentuada(c) or vocal_maiuscula_acentuada(c)
69
+
70
+
71
+ _VOCAL_SET = {
72
+ 0x41, 0x45, 0x49, 0x4F, 0x55,
73
+ 0x61, 0x65, 0x69, 0x6F, 0x75,
74
+ a_acentuada, e_acentuada, i_acentuada, o_acentuada, u_acentuada,
75
+ 0xC1, 0xC9, 0xCD, 0xD3, 0xDA,
76
+ 0xDC, 0xFC, 0xCF, 0xEF, 0xCB, 0xEB,
77
+ }
78
+ _VOCAL_SET.update(VOCAL_MINUSCULA_RARA)
79
+ _VOCAL_SET.update(VOCAL_MAIUSCULA_RARA)
80
+
81
+
82
+ def vocal(c: str) -> bool:
83
+ return ord(c) in _VOCAL_SET
84
+
85
+
86
+ def letra(c: str) -> bool:
87
+ b = ord(c)
88
+ return (65 <= b <= 90) or (97 <= b <= 122) or b in _VOCAL_SET or b in (
89
+ 0xF1, 0xD1, 0xE7, 0xC7
90
+ )
91
+
92
+
93
+ def consonante(c: str) -> bool:
94
+ return letra(c) and not vocal(c)
95
+
96
+
97
+ def vocal_feble(c: str) -> bool:
98
+ b = ord(c)
99
+ return b in (0x49, 0x55, 0x69, 0x75, 0xDC, 0xFC)
100
+
101
+
102
+ def vocal_aberta(c: str) -> bool:
103
+ b = ord(c)
104
+ return b in (0x41, 0x61, 0x45, 0x65, 0x4F, 0x6F,
105
+ 0xC1, 0xE1, 0xC9, 0xE9, 0xD3, 0xF3)
106
+
107
+
108
+ def es_diptongo(v1: str, v2: str) -> bool:
109
+ if vocal_feble(v1):
110
+ return True
111
+ if vocal_aberta(v1) and vocal_feble(v2):
112
+ return True
113
+ return False
114
+
115
+
116
+ def es_triptongo(v1: str, v2: str, v3: str) -> bool:
117
+ if vocal_feble(v1) and vocal_aberta(v2) and vocal_feble(v3):
118
+ return True
119
+ if ord(v2) in (0x69, 0x49) and vocal_aberta(v3):
120
+ return True
121
+ return False
122
+
123
+
124
+ GRUPOS_INDIVISIBLES = {
125
+ "bl", "br", "pl", "pr", "cl", "cr", "gl", "gr",
126
+ "dr", "tl", "tr", "fl", "fr",
127
+ "ps", "pn", "ch", "ck", "rr", "ll",
128
+ "kr", "kl", "vl", "gh",
129
+ }
130
+
131
+
132
+ ACENTO_A_BASE = {
133
+ 0xE1: 'a', 0xC1: 'A',
134
+ 0xE0: 'a', 0xC0: 'A',
135
+ 0xE2: 'a', 0xC2: 'A',
136
+ 0xE3: 'a', 0xC3: 'A',
137
+ 0xE4: 'a', 0xC4: 'A',
138
+ 0xE5: 'a', 0xC5: 'A',
139
+ 0xE6: 'a', 0xC6: 'A',
140
+ 0xE9: 'e', 0xC9: 'E',
141
+ 0xE8: 'e', 0xC8: 'E',
142
+ 0xEA: 'e', 0xCA: 'E',
143
+ 0xEB: 'e', 0xCB: 'E',
144
+ 0xED: 'i', 0xCD: 'I',
145
+ 0xEC: 'i', 0xCC: 'I',
146
+ 0xEE: 'i', 0xCE: 'I',
147
+ 0xEF: 'i', 0xCF: 'I',
148
+ 0xF3: 'o', 0xD3: 'O',
149
+ 0xF2: 'o', 0xD2: 'O',
150
+ 0xF4: 'o', 0xD4: 'O',
151
+ 0xF5: 'o', 0xD5: 'O',
152
+ 0xF6: 'o', 0xD6: 'O',
153
+ 0xF8: 'o', 0xD8: 'O',
154
+ 0xFA: 'u', 0xDA: 'U',
155
+ 0xF9: 'u', 0xD9: 'U',
156
+ 0xFB: 'u', 0xDB: 'U',
157
+ 0xFC: 'u', 0xDC: 'U',
158
+ 0xFD: 'y', 0xDD: 'Y',
159
+ 0xFF: 'y',
160
+ 0xF1: 'n', 0xD1: 'N',
161
+ 0xE7: 'c', 0xC7: 'C',
162
+ }
163
+
164
+
165
+ def base_vowel(c: str) -> str:
166
+ return ACENTO_A_BASE.get(ord(c), c)
pycotovia/cli.py ADDED
@@ -0,0 +1,30 @@
1
+ """Command-line interface for pycotovia."""
2
+
3
+ import sys
4
+ from .phonemize import Phonemizer
5
+
6
+
7
+ def main():
8
+ lang = "gl"
9
+ args = sys.argv[1:]
10
+ while args and args[0].startswith('-'):
11
+ flag = args.pop(0)
12
+ if flag == '-l' and args:
13
+ lang = args.pop(0)
14
+ elif flag == '--help':
15
+ print("Usage: python -m pycotovia [-l gl|es] < input.txt", file=sys.stderr)
16
+ sys.exit(0)
17
+
18
+ p = Phonemizer(lang)
19
+ try:
20
+ for line in sys.stdin:
21
+ line = line.rstrip('\n').rstrip('\r')
22
+ result = p.phonemize(line)
23
+ sys.stdout.write(result + '\n')
24
+ sys.stdout.flush()
25
+ except (BrokenPipeError, IOError):
26
+ pass
27
+
28
+
29
+ if __name__ == "__main__":
30
+ main()
pycotovia/engine.py ADDED
@@ -0,0 +1,27 @@
1
+ """Rule-matching engine — port of transcripcion.cpp."""
2
+
3
+
4
+ def apply_rules(text: str, rules: dict[int, list], use_sv: bool = False) -> str:
5
+ result = []
6
+ pos = 0
7
+ length = len(text)
8
+
9
+ while pos < length:
10
+ b = ord(text[pos])
11
+ rule_list = rules.get(b)
12
+ matched = False
13
+
14
+ if rule_list:
15
+ for antecedent, consume, consequent in rule_list:
16
+ ant_len = len(antecedent)
17
+ if pos + ant_len <= length and text[pos:pos + ant_len] == antecedent:
18
+ result.append(consequent)
19
+ pos += consume
20
+ matched = True
21
+ break
22
+
23
+ if not matched:
24
+ result.append(text[pos])
25
+ pos += 1
26
+
27
+ return "".join(result)
@@ -0,0 +1,79 @@
1
+ """Exception word lists — ported from trat_fon.cpp."""
2
+
3
+ X_PASA_A_KS = [
4
+ "amplex", "anafilax", "anaptix", "anex", "anorex", "anor\xe9x",
5
+ "antitoxi", "apirex", "apodix", "aprox", "asex", "asfix",
6
+ "atarax", "atax", "autotax", "auxi", "auxo", "axes", "axia",
7
+ "axila", "axio", "axoi", "axom", "baux", "biconvex", "bisex",
8
+ "boxe", "caquex", "carbox", "catalex", "coax", "coex",
9
+ "complexi\xf3", "conex", "convex", "coxal", "crucifixi",
10
+ "desconex", "desintoxi", "desoxi", "dexio", "dislex", "dox",
11
+ "eflux", "epistax", "ex",
12
+ "filoxer", "flex", "fluxi", "fluxom",
13
+ "galaxi", "heterodox", "heterosex", "hexa", "hexo",
14
+ "hidroxi", "homosex", "index", "inflex", "intermax",
15
+ "intox", "irreflex", "ixi", "ixo",
16
+ "laxan", "laxat", "laxi", "laxa", "laxo", "lexem", "l\xe9xic",
17
+ "luxa", "marxis", "maxil", "m\xe1xim", "mitilotox", "mix",
18
+ "monoxi", "morfoxintax", "nex",
19
+ "ortodox", "ox",
20
+ "paralax", "paratax", "parox", "pirex", "profilax",
21
+ "proxene", "proxi", "pr\xf3simo",
22
+ "radiotax", "reex", "reflexi", "retroflex",
23
+ "sax", "sexis", "sexo", "sext", "sexua", "sexy", "sintax",
24
+ "six", "submax", "taxat", "taxi", "taxo", "tirox",
25
+ "toxem", "toxi", "toxop", "unisex", "ux", "vexil", "\xe9xito",
26
+ ]
27
+
28
+ PRONUNCIANSE_CON_XE = [
29
+ "complexo", "exacu", "execu", "exem", "exerc",
30
+ "exerd", "exip", "ex\xe9rc", "oxal\xe1", "oxiv",
31
+ "saxit", "saxon", "ux\xe1",
32
+ "xerogl", "xeron", "xeros",
33
+ ]
34
+
35
+ W_PRONUNCIASE_GU = [
36
+ "darwi", "hawa", "sandwi", "taiwa",
37
+ "walk", "wash", "whisk", "winch", "wind",
38
+ ]
39
+
40
+ W_PRONUNCIASE_U = [
41
+ "twist", "newto",
42
+ ]
43
+
44
+
45
+ def _prefix_match(word: str, wordlist: list[str]) -> bool:
46
+ wl = word.lower()
47
+ for entry in wordlist:
48
+ if wl.startswith(entry):
49
+ return True
50
+ return False
51
+
52
+
53
+ def trata_excepcions_xe(word: str, lang: str = "gl") -> str | None:
54
+ word_lower = word.lower()
55
+
56
+ if lang == "gl":
57
+ if _prefix_match(word, PRONUNCIANSE_CON_XE):
58
+ return None
59
+ if _prefix_match(word, X_PASA_A_KS):
60
+ idx = word_lower.index('x')
61
+ return word[:idx] + "ks" + word[idx + 1:]
62
+ return None
63
+ else:
64
+ if _prefix_match(word, PRONUNCIANSE_CON_XE):
65
+ return None
66
+ if 'x' in word_lower:
67
+ idx = word_lower.index('x')
68
+ return word[:idx] + "ks" + word[idx + 1:]
69
+ return None
70
+
71
+
72
+ def trata_excepcions_w(word: str) -> str | None:
73
+ if _prefix_match(word, W_PRONUNCIASE_U):
74
+ idx = word.lower().index('w')
75
+ return word[:idx] + "u" + word[idx + 1:]
76
+ if _prefix_match(word, W_PRONUNCIASE_GU):
77
+ idx = word.lower().index('w')
78
+ return word[:idx] + "gu" + word[idx + 1:]
79
+ return None
pycotovia/phonemes.py ADDED
@@ -0,0 +1,81 @@
1
+ """Phoneme inventory — port of fonemas.cpp."""
2
+
3
+ PHONEME_NAMES = [
4
+ "#", "B", "D", "E", "G", "J", "N", "O", "S", "T",
5
+ "Z", "a", "b", "d", "e", "f", "g", "i", "k", "l",
6
+ "m", "n", "o", "p", "r", "s", "t", "u", "x", "tS",
7
+ "rr", "j", "w", "L", "c", "ts", "s`", "gj", "jj", "ts`",
8
+ ]
9
+
10
+ DOUBLE_PHONEME = {'tS': 29, 'rr': 30}
11
+
12
+ VOWEL_PHONEMES = {'a', 'e', 'E', 'i', 'o', 'O', 'u'}
13
+ SILENCE_VOICELESS_PLOSIVE = {'#', 't', 'k', 'p'}
14
+ SEGMENT_BOUNDARY = {'#', 't', 'k', 'p', 'f', 's', 'S', 'T', 'h'}
15
+ VOICELESS = {'#', 'p', 't', 'k', 'f', 's', 'S', 'T', 'x'}
16
+
17
+
18
+ def is_vowel(p: str) -> bool:
19
+ return p[0:1] in VOWEL_PHONEMES
20
+
21
+
22
+ def is_voiceless(p: str) -> bool:
23
+ return p[0:1] in VOICELESS
24
+
25
+
26
+ COTOVIA2IPA = {
27
+ "#": "pau",
28
+ "B": "β",
29
+ "D": "ð",
30
+ "E": "ɛ",
31
+ "G": "ɣ",
32
+ "J": "ɲ",
33
+ "N": "ŋ",
34
+ "O": "ɔ",
35
+ "S": "ʃ",
36
+ "T": "θ",
37
+ "Z": "ʎ",
38
+ "a": "a",
39
+ "b": "b",
40
+ "d": "d",
41
+ "e": "e",
42
+ "f": "f",
43
+ "g": "ɡ",
44
+ "i": "i",
45
+ "k": "k",
46
+ "l": "l",
47
+ "m": "m",
48
+ "n": "n",
49
+ "o": "o",
50
+ "p": "p",
51
+ "r": "ɾ",
52
+ "s": "s",
53
+ "t": "t",
54
+ "u": "u",
55
+ "x": "x",
56
+ "tS": "tʃ",
57
+ "rr": "r",
58
+ "j": "j",
59
+ "w": "w",
60
+ "L": "ʎ",
61
+ "jj": "ʎ",
62
+ "X": "x",
63
+ }
64
+
65
+
66
+ def cotovia_to_ipa(phoneme_str: str) -> str:
67
+ result = []
68
+ i = 0
69
+ s = phoneme_str.strip()
70
+ while i < len(s):
71
+ if s[i] == ' ':
72
+ result.append(' ')
73
+ i += 1
74
+ continue
75
+ if i + 1 < len(s) and s[i:i + 2] in DOUBLE_PHONEME:
76
+ result.append(COTOVIA2IPA.get(s[i:i + 2], s[i:i + 2]))
77
+ i += 2
78
+ else:
79
+ result.append(COTOVIA2IPA.get(s[i], s[i]))
80
+ i += 1
81
+ return "".join(result)
pycotovia/phonemize.py ADDED
@@ -0,0 +1,155 @@
1
+ """Pipeline orchestrator — input text → phoneme string.
2
+
3
+ Matches the Cotovia binary pipeline exactly:
4
+ 1. Input text is normalized and split into words
5
+ 2. Each word: exception preprocessing → syllabification → stress → timbre
6
+ 3. Words are joined into a single phrase: "## word1 word2 ##"
7
+ 4. All G2P rewrite rules are applied to the full phrase
8
+ 5. Final output strips pause markers, stress marks, and syllable separators
9
+ matching the binary's -t0 mode (phonemes only)
10
+ """
11
+
12
+ from .charset import letra, to_minusculas
13
+ from .exceptions import trata_excepcions_xe, trata_excepcions_w
14
+ from .syllabify import syllabify
15
+ from .stress import assign_stress
16
+ from .timbre import assign_timbre
17
+ from .engine import apply_rules
18
+ from .rules_data import GALEGO_RULES_SV, CASTELLANO_RULES_SV
19
+
20
+
21
+ def _strip_t0(s: str, tra: int = 1) -> str:
22
+ """Strip #...# and %...% blocks, ^ and - (matching binary sacar_transcripcion).
23
+
24
+ Args:
25
+ s: Raw rule-engine output
26
+ tra: Output level (1=phonemes only, 2=+stress, 3=+sep, 4=raw)
27
+ """
28
+ result = []
29
+ i = 0
30
+ n = len(s)
31
+ while i < n:
32
+ ch = s[i]
33
+ if ch == '#':
34
+ i += 1
35
+ while i < n and s[i] != '#':
36
+ i += 1
37
+ i += 1
38
+ # Consume the character after ## (usually a space) —
39
+ # matches C's if(*aux2)aux2++ after the switch
40
+ if i < n:
41
+ i += 1
42
+ elif ch == '%':
43
+ i += 1
44
+ while i < n and s[i] != '%':
45
+ i += 1
46
+ i += 1
47
+ if i < n:
48
+ i += 1
49
+ elif ch == '^':
50
+ if tra > 1:
51
+ result.append(ch)
52
+ i += 1
53
+ elif ch == '-':
54
+ if tra > 2:
55
+ result.append(ch)
56
+ i += 1
57
+ else:
58
+ result.append(ch)
59
+ i += 1
60
+ return "".join(result)
61
+
62
+
63
+ class Phonemizer:
64
+ """G2P phonemizer for Galician and Spanish."""
65
+
66
+ def __init__(self, lang: str = "gl"):
67
+ if lang not in ("gl", "es"):
68
+ raise ValueError(f"Unsupported language: {lang!r}. Use 'gl' or 'es'.")
69
+ self.lang = lang
70
+ self.rules = GALEGO_RULES_SV if lang == "gl" else CASTELLANO_RULES_SV
71
+
72
+ def phonemize(self, text: str, tra: int = 1) -> str:
73
+ """Convert plain text to a phoneme string.
74
+
75
+ Args:
76
+ text: Input text (Latin-1 or Unicode)
77
+ tra: Output level (1=phonemes, 2=+stress, 3=+syllables, 4=raw)
78
+
79
+ Returns:
80
+ Phoneme string (Cotovia notation)
81
+ """
82
+ # Step 1: Collect words
83
+ words = self._tokenize(text)
84
+
85
+ # Step 2: Process each word through pre-rules pipeline
86
+ processed_words = []
87
+ for word in words:
88
+ processed_words.append(self._preprocess_word(word))
89
+
90
+ # Step 3: Join into phrase with silence wrappers (matching binary)
91
+ phrase = "## " + " ".join(processed_words) + " ##"
92
+
93
+ # Step 4: Apply G2P rewrite rules to the full phrase
94
+ phoneme_phrase = apply_rules(phrase, self.rules)
95
+
96
+ # Step 5: Strip per tra level
97
+ if tra >= 4:
98
+ return phoneme_phrase
99
+ result = _strip_t0(phoneme_phrase, tra=tra)
100
+
101
+ return result
102
+
103
+ def _tokenize(self, text: str) -> list[str]:
104
+ """Split text into words (whitespace-separated)."""
105
+ words = []
106
+ current = []
107
+ for ch in text.strip():
108
+ if letra(ch):
109
+ current.append(ch)
110
+ else:
111
+ if current:
112
+ words.append("".join(current))
113
+ current = []
114
+ if current:
115
+ words.append("".join(current))
116
+ return words
117
+
118
+ def _preprocess_word(self, word: str) -> str:
119
+ """Apply pre-rule processing to a single word.
120
+
121
+ Pipeline: lowercase → exceptions → syllabify → stress → timbre
122
+ """
123
+ w = word
124
+
125
+ # Lowercase — matches pasar_a_minusculas() in the C binary
126
+ w = to_minusculas(w)
127
+
128
+ # Exception preprocessing
129
+ xe_result = trata_excepcions_xe(w, self.lang)
130
+ if xe_result is not None:
131
+ w = xe_result
132
+ w_result = trata_excepcions_w(w)
133
+ if w_result is not None:
134
+ w = w_result
135
+
136
+ # Syllabify
137
+ s = syllabify(w)
138
+
139
+ # Assign stress
140
+ s = assign_stress(s, self.lang)
141
+
142
+ # NOTE: Timbre assignment (assign_timbre) is NOT applied here.
143
+ # The binary only uses it for voice-building (-lin mode), not for -t
144
+ # transcription. The pal_sil_e_acentuada fed to transcribe() does NOT
145
+ # carry open/closed e/o marks. See transcribe() line 741:
146
+ # //atono_ou_tonico_aberto_ou_pechado_e_w_x(frase_sil_e_acentuada,item);
147
+ # That call is COMMENTED OUT in the transcribe path.
148
+
149
+ return s
150
+
151
+
152
+ def phonemize(text: str, lang: str = "gl", tra: int = 1) -> str:
153
+ """Convenience function — phonemize text in one call."""
154
+ p = Phonemizer(lang)
155
+ return p.phonemize(text, tra=tra)