lexphon 0.1.0__tar.gz

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.
lexphon-0.1.0/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
lexphon-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,109 @@
1
+ Metadata-Version: 2.4
2
+ Name: lexphon
3
+ Version: 0.1.0
4
+ Summary: Lexicon-driven phonemizer and CLI built on G2Lex.
5
+ Author: Holger Nahrstaedt
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Repository, https://github.com/buchwandler/lexphon
8
+ Project-URL: Issues, https://github.com/buchwandler/lexphon/issues
9
+ Project-URL: Data, https://github.com/buchwandler/g2lex-data
10
+ Keywords: g2p,phonemizer,pronunciation,ipa,g2lex,tts
11
+ Requires-Python: >=3.10
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Requires-Dist: g2lex<0.2,>=0.1.8
15
+ Provides-Extra: dev
16
+ Requires-Dist: pytest>=8; extra == "dev"
17
+ Requires-Dist: ruff>=0.16; extra == "dev"
18
+ Requires-Dist: build>=1; extra == "dev"
19
+ Requires-Dist: tomli>=2; python_version < "3.11" and extra == "dev"
20
+ Dynamic: license-file
21
+
22
+ # Lexphon
23
+
24
+ **Lexphon** is a generic, lexicon-driven phonemizer and CLI built on [G2Lex](https://github.com/buchwandler/g2lex). It consumes released pronunciation assets and returns normalized IPA without producing Kokoro phonemes.
25
+
26
+ ```text
27
+ g2lex-data producer -> G2Lex storage -> Lexphon runtime -> application adapter
28
+ ```
29
+
30
+ The ownership boundary is deliberate:
31
+
32
+ - `g2lex-data` obtains, transforms, validates, licenses, and publishes immutable data releases.
33
+ - G2Lex stores and queries typed lexicon data.
34
+ - Lexphon explicitly installs, verifies, selects, and consumes released assets.
35
+ - KokoroG2P or another application converts generic IPA to its model-specific output.
36
+
37
+ Lexphon must never contain source acquisition or G2Lex build recipes for production dictionaries.
38
+
39
+ ## Package layout
40
+
41
+ There is intentionally no `src/` directory. The import package lives at `./lexphon`.
42
+
43
+ ## Install for development
44
+
45
+ ```bash
46
+ python -m pip install -e ".[dev]"
47
+ pytest
48
+ ```
49
+
50
+ ## Data management
51
+
52
+ Catalog access and downloads are explicit. `DataStore.install()` is the network-capable provisioning operation. `Phonemizer`, lookup, token phonemization, rendering, and local store inspection never fetch a catalog or download a lexicon.
53
+
54
+ ```bash
55
+ lexphon data available de-DE
56
+ lexphon data install de-de:gold
57
+ lexphon data list
58
+ lexphon data info de-de:gold
59
+ lexphon data verify de-de:gold
60
+ lexphon data remove de-de:gold
61
+ ```
62
+
63
+ Use `--catalog PATH_OR_URL` and `--data-home PATH` for a local release or alternate store. Installation downloads the manifest first, verifies manifest and asset hashes and sizes, checks catalog and manifest identity, opens the G2Lex asset, and atomically activates a complete version. Installed metadata is sufficient for offline use and a copied store can be opened without the catalog.
64
+
65
+ The production German assets are `de-de:gold`, `de-de:crane`, `de-de:espeak`, and `de-de:olaph`. English CMUdict is available as `en-us:cmudict`. Membership assets can be installed for inventory use but cannot be selected as pronunciation layers.
66
+
67
+ Data release versions and the Lexphon Python package version are independent. Pin the data catalog or release during provisioning, and pin the Python dependency separately.
68
+
69
+ ## CLI
70
+
71
+ ```bash
72
+ lexphon -v de-DE "Die Leute kommen."
73
+ lexphon -v de-DE --lexicon de-de:crane "Die Leute kommen."
74
+ lexphon -v de-DE --lexicon de-de:crane --tag DET "die"
75
+ lexphon -v en-US --lexicon en-us:cmudict --json "read"
76
+ ```
77
+
78
+ JSON output contains the rendered IPA plus structured token fields: original text, pronunciation, source category, output alphabet, source encoding, logical lexicon ID, matched key, ordered IPA variants, selector tag, known status, and punctuation status.
79
+
80
+ Optional standalone fallback is explicit:
81
+
82
+ ```bash
83
+ lexphon -v de-DE --fallback espeak "unbekannteswort"
84
+ ```
85
+
86
+ Fallback is disabled by default. Unknown tokens remain visible to downstream applications.
87
+
88
+ ## Python API
89
+
90
+ ```python
91
+ from lexphon import DataStore, Phonemizer
92
+
93
+ store = DataStore()
94
+ with Phonemizer(
95
+ "de-DE",
96
+ lexicons=["de-de:gold"],
97
+ store=store,
98
+ fallback=None,
99
+ ) as g2p:
100
+ result = g2p.phonemize_tokens("Die Leute")
101
+ for token in result.tokens:
102
+ print(token.text, token.pronunciation, token.source, token.lexicon_id)
103
+ ```
104
+
105
+ `phonemize_tokens()` is the integration API. It preserves token-level provenance, selectors, variants, punctuation, and unknown words. IPA is normalized to Unicode NFC. ARPABET and CMU-style pronunciations are converted deterministically to IPA. Unsupported alphabets and invalid pronunciation tokens raise stable Lexphon exceptions.
106
+
107
+ ## KokoroG2P boundary
108
+
109
+ KokoroG2P should import Lexphon's Python API, use `fallback=None`, convert returned IPA using its model-specific vocabulary, and apply its own fallback, stress, ratings, and diagnostics policy. Lexphon does not import KokoroG2P, perform Kokoro validation, or download dictionaries during phonemization.
@@ -0,0 +1,88 @@
1
+ # Lexphon
2
+
3
+ **Lexphon** is a generic, lexicon-driven phonemizer and CLI built on [G2Lex](https://github.com/buchwandler/g2lex). It consumes released pronunciation assets and returns normalized IPA without producing Kokoro phonemes.
4
+
5
+ ```text
6
+ g2lex-data producer -> G2Lex storage -> Lexphon runtime -> application adapter
7
+ ```
8
+
9
+ The ownership boundary is deliberate:
10
+
11
+ - `g2lex-data` obtains, transforms, validates, licenses, and publishes immutable data releases.
12
+ - G2Lex stores and queries typed lexicon data.
13
+ - Lexphon explicitly installs, verifies, selects, and consumes released assets.
14
+ - KokoroG2P or another application converts generic IPA to its model-specific output.
15
+
16
+ Lexphon must never contain source acquisition or G2Lex build recipes for production dictionaries.
17
+
18
+ ## Package layout
19
+
20
+ There is intentionally no `src/` directory. The import package lives at `./lexphon`.
21
+
22
+ ## Install for development
23
+
24
+ ```bash
25
+ python -m pip install -e ".[dev]"
26
+ pytest
27
+ ```
28
+
29
+ ## Data management
30
+
31
+ Catalog access and downloads are explicit. `DataStore.install()` is the network-capable provisioning operation. `Phonemizer`, lookup, token phonemization, rendering, and local store inspection never fetch a catalog or download a lexicon.
32
+
33
+ ```bash
34
+ lexphon data available de-DE
35
+ lexphon data install de-de:gold
36
+ lexphon data list
37
+ lexphon data info de-de:gold
38
+ lexphon data verify de-de:gold
39
+ lexphon data remove de-de:gold
40
+ ```
41
+
42
+ Use `--catalog PATH_OR_URL` and `--data-home PATH` for a local release or alternate store. Installation downloads the manifest first, verifies manifest and asset hashes and sizes, checks catalog and manifest identity, opens the G2Lex asset, and atomically activates a complete version. Installed metadata is sufficient for offline use and a copied store can be opened without the catalog.
43
+
44
+ The production German assets are `de-de:gold`, `de-de:crane`, `de-de:espeak`, and `de-de:olaph`. English CMUdict is available as `en-us:cmudict`. Membership assets can be installed for inventory use but cannot be selected as pronunciation layers.
45
+
46
+ Data release versions and the Lexphon Python package version are independent. Pin the data catalog or release during provisioning, and pin the Python dependency separately.
47
+
48
+ ## CLI
49
+
50
+ ```bash
51
+ lexphon -v de-DE "Die Leute kommen."
52
+ lexphon -v de-DE --lexicon de-de:crane "Die Leute kommen."
53
+ lexphon -v de-DE --lexicon de-de:crane --tag DET "die"
54
+ lexphon -v en-US --lexicon en-us:cmudict --json "read"
55
+ ```
56
+
57
+ JSON output contains the rendered IPA plus structured token fields: original text, pronunciation, source category, output alphabet, source encoding, logical lexicon ID, matched key, ordered IPA variants, selector tag, known status, and punctuation status.
58
+
59
+ Optional standalone fallback is explicit:
60
+
61
+ ```bash
62
+ lexphon -v de-DE --fallback espeak "unbekannteswort"
63
+ ```
64
+
65
+ Fallback is disabled by default. Unknown tokens remain visible to downstream applications.
66
+
67
+ ## Python API
68
+
69
+ ```python
70
+ from lexphon import DataStore, Phonemizer
71
+
72
+ store = DataStore()
73
+ with Phonemizer(
74
+ "de-DE",
75
+ lexicons=["de-de:gold"],
76
+ store=store,
77
+ fallback=None,
78
+ ) as g2p:
79
+ result = g2p.phonemize_tokens("Die Leute")
80
+ for token in result.tokens:
81
+ print(token.text, token.pronunciation, token.source, token.lexicon_id)
82
+ ```
83
+
84
+ `phonemize_tokens()` is the integration API. It preserves token-level provenance, selectors, variants, punctuation, and unknown words. IPA is normalized to Unicode NFC. ARPABET and CMU-style pronunciations are converted deterministically to IPA. Unsupported alphabets and invalid pronunciation tokens raise stable Lexphon exceptions.
85
+
86
+ ## KokoroG2P boundary
87
+
88
+ KokoroG2P should import Lexphon's Python API, use `fallback=None`, convert returned IPA using its model-specific vocabulary, and apply its own fallback, stress, ratings, and diagnostics policy. Lexphon does not import KokoroG2P, perform Kokoro validation, or download dictionaries during phonemization.
@@ -0,0 +1,32 @@
1
+ """Lexicon-driven phonemization on top of G2Lex."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from ._version import __version__
6
+ from .engine import Phonemizer
7
+ from .errors import (
8
+ CatalogError,
9
+ DataIntegrityError,
10
+ LexiconNotInstalledError,
11
+ LexiconNotUsableError,
12
+ LexphonError,
13
+ UnknownWordError,
14
+ UnsupportedAlphabetError,
15
+ )
16
+ from .models import PhonemizationResult, PronunciationToken
17
+ from .store import DataStore
18
+
19
+ __all__ = [
20
+ "CatalogError",
21
+ "DataIntegrityError",
22
+ "DataStore",
23
+ "LexiconNotInstalledError",
24
+ "LexiconNotUsableError",
25
+ "LexphonError",
26
+ "PhonemizationResult",
27
+ "Phonemizer",
28
+ "PronunciationToken",
29
+ "UnknownWordError",
30
+ "UnsupportedAlphabetError",
31
+ "__version__",
32
+ ]
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
@@ -0,0 +1,72 @@
1
+ """Small dependency-free Git-derived version helper used by setuptools."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import re
7
+ import subprocess
8
+ from email.parser import Parser
9
+ from pathlib import Path
10
+
11
+ _FALLBACK = "0.1.0"
12
+ _TAG = re.compile(
13
+ r"^v?(?P<base>\d+\.\d+\.\d+)(?:-(?P<count>\d+)-g(?P<sha>[0-9a-f]+))?(?P<dirty>-dirty)?$"
14
+ )
15
+
16
+
17
+ def _sdist_version(root: Path) -> str | None:
18
+ try:
19
+ metadata = Parser().parsestr(
20
+ (root / "PKG-INFO").read_text(encoding="utf-8"), headersonly=True
21
+ )
22
+ except (OSError, UnicodeError):
23
+ return None
24
+ if metadata.get("Name") != "lexphon":
25
+ return None
26
+ value = metadata.get("Version")
27
+ return value.strip() if value and value.strip() else None
28
+
29
+
30
+ def get_version() -> str:
31
+ override = os.environ.get("LEXPHON_VERSION")
32
+ if override:
33
+ return override
34
+ root = Path(__file__).resolve().parents[1]
35
+ try:
36
+ text = subprocess.check_output(
37
+ [
38
+ "git",
39
+ "-C",
40
+ str(root),
41
+ "describe",
42
+ "--tags",
43
+ "--long",
44
+ "--dirty",
45
+ "--match",
46
+ "v[0-9]*",
47
+ ],
48
+ stderr=subprocess.DEVNULL,
49
+ text=True,
50
+ timeout=2,
51
+ ).strip()
52
+ except (OSError, subprocess.SubprocessError):
53
+ text = ""
54
+ match = _TAG.match(text)
55
+ if not match:
56
+ return _sdist_version(root) or _FALLBACK
57
+ base = match.group("base")
58
+ count = int(match.group("count") or 0)
59
+ sha = match.group("sha")
60
+ dirty = bool(match.group("dirty"))
61
+ if count == 0 and not dirty:
62
+ return base
63
+ local = []
64
+ if sha:
65
+ local.append(f"g{sha}")
66
+ if dirty:
67
+ local.append("dirty")
68
+ version = f"{base}.post{count}" if count else f"{base}.dev0"
69
+ return version + ("+" + ".".join(local) if local else "")
70
+
71
+
72
+ __version__ = get_version()
@@ -0,0 +1,109 @@
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ import unicodedata
5
+
6
+ from .errors import UnsupportedAlphabetError
7
+
8
+ _ARPA_CONSONANTS = {
9
+ "B": "b",
10
+ "CH": "tʃ",
11
+ "D": "d",
12
+ "DH": "ð",
13
+ "F": "f",
14
+ "G": "ɡ",
15
+ "HH": "h",
16
+ "JH": "dʒ",
17
+ "K": "k",
18
+ "L": "l",
19
+ "M": "m",
20
+ "N": "n",
21
+ "NG": "ŋ",
22
+ "P": "p",
23
+ "R": "ɹ",
24
+ "S": "s",
25
+ "SH": "ʃ",
26
+ "T": "t",
27
+ "TH": "θ",
28
+ "V": "v",
29
+ "W": "w",
30
+ "Y": "j",
31
+ "Z": "z",
32
+ "ZH": "ʒ",
33
+ }
34
+ _ARPA_VOWELS = {
35
+ "AA": "ɑ",
36
+ "AE": "æ",
37
+ "AH": "ʌ",
38
+ "AO": "ɔ",
39
+ "AW": "aʊ",
40
+ "AY": "aɪ",
41
+ "EH": "ɛ",
42
+ "ER": "ɝ",
43
+ "EY": "eɪ",
44
+ "IH": "ɪ",
45
+ "IY": "i",
46
+ "OW": "oʊ",
47
+ "OY": "ɔɪ",
48
+ "UH": "ʊ",
49
+ "UW": "u",
50
+ "AX": "ə",
51
+ "AXR": "ɚ",
52
+ "IX": "ɨ",
53
+ }
54
+ _ARPA_TOKEN = re.compile(r"^(?P<phoneme>[A-Z]+)(?P<stress>[012])?$")
55
+
56
+
57
+ def arpabet_to_ipa(value: str) -> str:
58
+ """Convert CMU-style ARPABET to deterministic broad IPA."""
59
+ if not isinstance(value, str) or not value.strip():
60
+ raise UnsupportedAlphabetError("ARPABET pronunciation must contain phone tokens")
61
+ segments: list[str] = []
62
+ vowel_indices: list[int] = []
63
+ stressed: list[tuple[int, str]] = []
64
+ for raw in value.split():
65
+ match = _ARPA_TOKEN.fullmatch(raw.upper())
66
+ if not match:
67
+ raise UnsupportedAlphabetError(f"invalid ARPABET token: {raw!r}")
68
+ symbol = match.group("phoneme")
69
+ stress = match.group("stress")
70
+ if symbol in _ARPA_VOWELS:
71
+ ipa = _ARPA_VOWELS[symbol]
72
+ if symbol == "AH" and stress == "0":
73
+ ipa = "ə"
74
+ elif symbol == "ER" and stress == "0":
75
+ ipa = "ɚ"
76
+ vowel_ordinal = len(vowel_indices)
77
+ if stress in {"1", "2"}:
78
+ stressed.append((vowel_ordinal, "ˈ" if stress == "1" else "ˌ"))
79
+ vowel_indices.append(len(segments))
80
+ segments.append(ipa)
81
+ elif symbol in _ARPA_CONSONANTS:
82
+ if stress is not None:
83
+ raise UnsupportedAlphabetError(f"stress on ARPABET consonant: {raw!r}")
84
+ segments.append(_ARPA_CONSONANTS[symbol])
85
+ else:
86
+ raise UnsupportedAlphabetError(f"unsupported ARPABET phoneme: {symbol}")
87
+
88
+ insertions: dict[int, list[str]] = {}
89
+ for vowel_ordinal, marker in stressed:
90
+ position = 0 if vowel_ordinal == 0 else vowel_indices[vowel_ordinal - 1] + 1
91
+ insertions.setdefault(position, []).append(marker)
92
+
93
+ output: list[str] = []
94
+ for index, segment in enumerate(segments):
95
+ output.extend(insertions.get(index, ()))
96
+ output.append(segment)
97
+ output.extend(insertions.get(len(segments), ()))
98
+ return unicodedata.normalize("NFC", "".join(output))
99
+
100
+
101
+ def to_ipa(value: str, encoding: str) -> str:
102
+ if not isinstance(value, str) or not value:
103
+ raise UnsupportedAlphabetError("pronunciation must be a non-empty string")
104
+ key = encoding.casefold().replace("-", "")
105
+ if key in {"ipa", "unicodeipa"}:
106
+ return unicodedata.normalize("NFC", value)
107
+ if key in {"arpabet", "cmu", "cmudict"}:
108
+ return arpabet_to_ipa(value)
109
+ raise UnsupportedAlphabetError(f"unsupported pronunciation encoding: {encoding!r}")