mandarin-ipa 0.0.0-stage → 0.1.0

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 KasumiKitsune & T·Grid Contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,190 @@
1
- # Temporary Holding Version
1
+ # mandarin-ipa
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Phonologically accurate Mandarin Chinese (Putonghua) **Hanzi & Pinyin → IPA** transcription engine for JavaScript and TypeScript. Extracted from [T·Grid](https://github.com/kasumikitsune/tgrid), designed for corpus linguistics, Praat/MFA speech annotation, TTS frontends, and language learning tools.
4
+
5
+ 面向语音学标注、语料库语言学、语音合成前端与教学工具的普通话**汉字/拼音 → 国际音标(IPA)**开源引擎(抽离自 [T·Grid](https://github.com/kasumikitsune/tgrid)),支持汉学派、宽式、严式三套音标体系、韵律连读变调、北京话儿化音系合并及轻声弱化/清塞音浊化。
6
+
7
+ ---
8
+
9
+ ## Highlights / 核心特性
10
+
11
+ - **Dual Entrypoints / 双入口按需架构**
12
+ - `mandarin-ipa`: Full Hanzi / Pinyin / digits / silence-tag mixed-text transcription; lazily loads optional `pinyin-pro` via dynamic `import('pinyin-pro')` only when Hanzi or verbalized digits are encountered.
13
+ - `mandarin-ipa/pinyin`: **Zero external dependencies** (`~10.0 KB` minified + gzipped), providing syllable parsing/formatting, multi-syllable Pinyin sandhi (`convertPinyinSequence`), erhua rhotacization, and IPA conversion.
14
+ - **Three Phonetic Transcription Schools / 三套音标学派与细粒度开关**
15
+ - `'sinological'` (赵元任/罗常培汉学派传统: `ɿ / ʅ`, `ʈʂ / ʐ`, `ɤ`, `ɡ`)
16
+ - `'broad'` (宽式音位标音: `ɹ̩ / ɻ̩`, `tʂ / ɻ`, `po`, ASCII `g`)
17
+ - `'strict'` (严式语音标音: tie-bars `ʈ͡ʂ / t͡ɕ / t͡s`, fricative syllabic `z̩ / ʐ̩`, `ɑŋ / ʊŋ`, tone-conditioned mid-vowel compression `t͡ɕiu˥˥` vs `t͡ɕioʊ˨˩˦`)
18
+ - Every phonetic detail (`apicalVowel`, `rInitial`, `retroflex`, `tieBar`, `narrowVowels`, `scriptG`, `zeroInitial`) can be individually overridden.
19
+ - **Prosodic & Morphological Sandhi / 连读变调与词法轻声**
20
+ - Consecutive T3 sandhi respecting word boundaries (`展览馆` 2+1 `zhán lán guǎn` vs `纸老虎` / `水很冷` 1+2 `zhǐ láo hǔ` / `shuǐ hén lěng`, 4+ syllable prosodic feet `小展览馆` `xiǎo zhán lán guǎn`), plus optional half-third `˨˩` (`21`).
21
+ - Morphological `一` (`yi`) & `不` (`bu`) sandhi: distinguishes ordinals/counting (`第一 dì yī`, `一二三 yī èr sān`), reduplication (`看一看 kàn yi kàn`, `好不好 hǎo bu hǎo`), V-不-C potential complements (`看不见 kàn bu jiàn`), and Subject+不+Verb (`他不来 tā bù lái`, `我不去 wǒ bú qù`).
22
+ - Particle neutralization (`我的 wǒ de`, `走了 zǒu le`, `去过 qù guo`) while preserving lexical full-tone compounds (`获得 huò dé`, `酒吧 jiǔ bā`).
23
+ - **Word-Aware Beijing Erhua / 词法感知的儿化音系**
24
+ - Merges genuine erhua suffixes (`花儿 huār → xua˞˥˥`, `一点儿 yì diǎnr → i˥˩ tia˞˨˩˦`, `字儿 zìr → tsə˞˥˩`, `鹅儿 é'r → ɤ˞˧˥`, nasalized `-ŋr → ã˞ / ə̃˞ / ũ˞`) while keeping non-erhua words intact (`儿童 ér tóng`, `儿子 ér zi`, `女儿 nǚ ér`, `婴儿 yīng ér`).
25
+ - **Neutral-Tone Vowel Reduction & Obstruent Voicing / 轻声央化与清塞音弱化浊化**
26
+ - Optional `neutralTone.reduceVowel` (`ɤ → ə`, `a / ya / wa → ɐ / jɐ / wɐ`, enabled by default).
27
+ - Optional `neutralTone.voicingInNeutral` (default `false`): voices unaspirated stops and affricates `b, d, g, j, z, zh` in neutral-tone syllables (`tone === 0`) to `[b, d, ɡ/g, dʑ/d͡ʑ, dz/d͡z, ɖʐ/ɖ͡ʐ/dʐ/d͡ʐ]`, while keeping aspirated `p, t, k, q, c, ch` voiceless aspirated.
28
+
29
+ ---
30
+
31
+ ## Installation / 安装
32
+
33
+ ```bash
34
+ # Full Hanzi + Pinyin support (installs optional peer dependency pinyin-pro)
35
+ # 完整汉字 + 拼音混排转写(安装可选依赖 pinyin-pro)
36
+ npm install mandarin-ipa pinyin-pro
37
+
38
+ # Zero-dependency Pinyin-only usage
39
+ # 仅使用 ./pinyin 纯拼音零依赖模式(无需安装 pinyin-pro)
40
+ npm install mandarin-ipa
41
+ ```
42
+
43
+ ---
44
+
45
+ ## Quick Start / 快速上手
46
+
47
+ ### 1. Hanzi & Mixed Text (`mandarin-ipa`)
48
+
49
+ ```ts
50
+ import {
51
+ mandarinToIpa,
52
+ mandarinToPinyin,
53
+ convertMandarinText,
54
+ extractPolyphones
55
+ } from 'mandarin-ipa';
56
+
57
+ // Default Sinological IPA with Chao contour tone letters
58
+ await mandarinToIpa('我说妈这个词。');
59
+ // => "wo˨˩˦ ʂuo˥˥ ma˥˥ ʈʂɤ˥˩ kə tsʰɿ˧˥"
60
+
61
+ // Switch preset & enable half-third tone + neutral-tone unaspirated voicing
62
+ await mandarinToIpa('爸爸看着我的桌子。', {
63
+ ipaPreset: 'strict',
64
+ sandhi: { halfThirdTone: true },
65
+ neutralTone: { voicingInNeutral: true }
66
+ });
67
+ // => "pa˥˩ bɐ kʰan˥˩ ɖ͡ʐə wo˨˩ də ʈ͡ʂuɔ˥˥ d͡zz̩"
68
+
69
+ // Rich structured output with syllable units, character offsets & polyphone candidates
70
+ const res = await convertMandarinText('银行2026年 <pau> 花儿开了', {
71
+ customDict: { 重庆: 'chóng qìng' }
72
+ });
73
+ // res.pinyinText => "yín háng èr líng èr liù nián <pau> huār kāi le"
74
+ // res.ipaText => "in˧˥ xaŋ˧˥ ɚ˥˩ liŋ˧˥ ɚ˥˩ liou˥˩ niɛn˧˥ <pau> xua˞˥˥ kʰai˥˥ lə"
75
+
76
+ // Inspect polyphonic characters and candidate readings in context
77
+ const polyphones = await extractPolyphones('音乐让人快乐');
78
+ // polyphones[0] => { char: '乐', charIndex: 1, selectedPinyin: 'yuè', candidates: ['yuè', 'lè', ...] }
79
+ ```
80
+
81
+ ### 2. Zero-Dependency Pinyin Subpath (`mandarin-ipa/pinyin`)
82
+
83
+ ```ts
84
+ import {
85
+ pinyinToIpa,
86
+ convertPinyinSequence,
87
+ pinyinSyllableToIpa,
88
+ parsePinyinSyllable,
89
+ formatPinyinSyllable,
90
+ buildIpaOptionsFromConfig
91
+ } from 'mandarin-ipa/pinyin';
92
+
93
+ // Multi-syllable Pinyin phrase -> T3 sandhi -> Pinyin & IPA (zero external dependencies)
94
+ const seq = convertPinyinSequence("ni3 hao3, xi1'an1!", {
95
+ punctuationMode: 'attach-prev'
96
+ });
97
+ // seq.pinyinText => "ní hǎo, xī ān!"
98
+ // seq.ipaText => "ni˧˥ xau˨˩˦, ɕi˥˥ an˥˥!"
99
+
100
+ // Prosodic word spacing resolves 1+2 vs 2+1 3rd-tone sandhi in Pinyin
101
+ convertPinyinSequence('zhǐ lǎohǔ').pinyinText; // => "zhǐ láo hǔ" (1+2)
102
+ convertPinyinSequence('zhǎnlǎn guǎn').pinyinText; // => "zhán lán guǎn" (2+1)
103
+
104
+ // Single-syllable conversion with granular overrides
105
+ const opts = buildIpaOptionsFromConfig({
106
+ ipaPreset: 'broad',
107
+ neutralTone: { voicingInNeutral: true }
108
+ });
109
+ pinyinSyllableToIpa('zhe0', opts); // => "dʐə"
110
+ pinyinSyllableToIpa('ge0', opts); // => "gə"
111
+ ```
112
+
113
+ ---
114
+
115
+ ## Configuration Reference / 配置项说明
116
+
117
+ All high-level functions (`mandarinToIpa`, `mandarinToPinyin`, `convertMandarinText`, `convertPinyinSequence`, `pinyinToIpa`, `buildIpaOptionsFromConfig`, `createDefaultMandarinConfig`) accept **deep-partial overrides** (`MandarinConvertOptions` / `MandarinIpaConfigOverrides`) and automatically merge with defaults:
118
+
119
+ | Option | Type | Default | Description / 说明 |
120
+ | --- | --- | --- | --- |
121
+ | `ipaPreset` | `'sinological' \| 'broad' \| 'strict'` | `'sinological'` | Phonetic transcription preset / 音标学派预设 |
122
+ | `ipaToneStyle` | `'chao-contour' \| 'chao-single' \| 'superscript' \| 'digits' \| 'none'` | `'chao-contour'` | Tone notation (`˥˥`, `˥`, `⁵⁵`, `55`, or none) |
123
+ | `pinyinFormat` | `'tone-marks' \| 'tone-numbers' \| 'tone-numbers-v' \| 'toneless'` | `'tone-marks'` | Formatted Pinyin style (`lǜ`, `lü4`, `lv4`, `lü`) |
124
+ | `erhua` | `'auto' \| 'off'` | `'auto'` | Word-aware Beijing erhua merging in Hanzi mode |
125
+ | `zeroInitial` | `'bare' \| 'glottal'` | `'bare'` | Prepend `ʔ` on zero-initial `a/o/e/ê` finals (`ʔan˥˥`) |
126
+ | `punctuationMode` | `'ignore' \| 'attach-prev' \| 'keep'` | `'ignore'` | Punctuation handling in output tokens |
127
+ | `digitMode` | `'verbalize' \| 'keep'` | `'verbalize'` | Verbalize Arabic digits to Chinese numerals in Hanzi mode |
128
+ | `latinInIpa` | `'keep' \| 'skip'` | `'keep'` | Keep or omit non-Pinyin Latin tokens (e.g. `F0`, `VOT`) in IPA |
129
+ | `sandhi.thirdTone` | `boolean` | `true` | Prosodic T3 + T3 → T2 + T3 sandhi |
130
+ | `sandhi.halfThirdTone` | `boolean` | `false` | Output half-third `˨˩` / `²¹` / `21` before non-T3 syllables |
131
+ | `sandhi.yiSandhi` | `boolean` | `true` | Morphological `一` sandhi (Hanzi mode) |
132
+ | `sandhi.buSandhi` | `boolean` | `true` | Morphological `不` sandhi (Hanzi mode) |
133
+ | `neutralTone.mark` | `'none' \| 'dot' \| 'zero'` | `'none'` | Neutral tone suffix (`꜋/꜊/꜉/꜌`, `·`, `0` / `⁰`) |
134
+ | `neutralTone.reduceVowel` | `boolean` | `true` | Centralize neutral `e → ə` and `a/ya/wa → ɐ/jɐ/wɐ` |
135
+ | `neutralTone.voicingInNeutral` | `boolean` | `false` | Voice unaspirated `b/d/g/j/z/zh` in neutral tone (`tone === 0`) |
136
+ | `ipaGranular` | `Partial<IpaGranularConfig>` | *(per preset)* | Override `apicalVowel`, `rInitial`, `retroflex`, `tieBar`, `narrowVowels`, `scriptG` |
137
+ | `customDict` | `Record<string, string>` | `{}` | Longest-match word Pinyin overrides (supports 2-char erhua like `{ 花儿: 'huār' }`) |
138
+ | `polyphoneOverrides` | `Map \| Record` | `undefined` | Per-occurrence character reading override (`"charIndex"` or `"intervalIndex:charIndex"`) |
139
+
140
+ ---
141
+
142
+ ## Ecosystem Comparison & Honest Linguistic Boundaries / 生态对比与语言学边界说明
143
+
144
+ ### Comparison with Existing JS/TS Packages / 与现有库对比
145
+
146
+ | Capability / 维度 | `mandarin-ipa` (`.`) | `mandarin-ipa/pinyin` | `pinyin-to-ipa` | `pinyin-pro` |
147
+ | --- | --- | --- | --- | --- |
148
+ | Direct Hanzi → IPA | Yes (via lazy `pinyin-pro`) | No (Pinyin input) | No (single Pinyin syllable/word) | Hanzi → Pinyin only (no IPA) |
149
+ | Runtime Dependencies | `pinyin-pro` (optional peer) | **0 dependencies** | External dict/tables | Self-contained (~319 KB CJS/ESM dict) |
150
+ | IPA Transcription Schools | `sinological` / `broad` / `strict` + 6 granular toggles | `sinological` / `broad` / `strict` + 6 granular toggles | Single fixed scheme | N/A |
151
+ | Prosodic 3+ T3 Sandhi (2+1 vs 1+2) | Word- & lexicon-aware | Word-spacing-aware | No | Basic pair T3 option |
152
+ | Morphological `一` / `不` / Particle Sandhi | Context-aware (`第一`, `看不见`, `酒吧`, `获得`) | Surface Pinyin tones only (see below) | No | Basic `一` / `不` sandhi |
153
+ | Beijing Erhua Rhotacization | Word-aware (`花儿` vs `女儿/儿童`) + full rhotic table | Orthographic `-r` / `'r` + full rhotic table | Limited / non-rhotacized | No IPA rhotics |
154
+ | Neutral-Tone Obstruent Voicing | Configurable (`voicingInNeutral`) | Configurable (`voicingInNeutral`) | No | N/A |
155
+
156
+ ### Honest Linguistic Boundaries / 客观局限与边界说明
157
+
158
+ 1. **Pure Pinyin Mode (`mandarin-ipa/pinyin`, `convertPinyinSequence`) Without Hanzi Glyphs / 纯拼音模式缺少汉字字形时的同音词法边界**
159
+ - In Mandarin phonology, **Third Tone Sandhi** (`T3 + T3 → T2 + T3`) and **Half-Third Tone** (`T3 → 21` before non-T3) apply across the board phonologically, so `convertPinyinSequence` executes them automatically (and uses Pinyin word spacing/apostrophes to distinguish `zhǐ lǎohǔ` `[1+2]` from `zhǎnlǎn guǎn` `[2+1]`).
160
+ - By contrast, **`一` (`yi1`) sandhi, `不` (`bu4`) sandhi, and modal/structural particle neutralization are morpho-lexical rules bound to specific Hanzi morphemes**, NOT general phonological rules over the syllables `yi1` or `bu4`:
161
+ - **`yi1` homophony (`第一` vs `一天` vs `医生`)**: Without Hanzi glyphs, `yi1` in `yī shēng` (`医生`) or `yī yuàn` (`医院`) is indistinguishable from `一` in `yī tiān` (`一天 → yì tiān`), and `di4 yi1 ming2` cannot distinguish ordinal `第一名` (`dì yī míng`, retains citation T1) from `递一名` (`dì yì míng`, changes to T4).
162
+ - **`bu4` homophony (`看不见` vs `看部件` vs `部队`)**: Without Hanzi glyphs, `bu4` in `bù duì` (`部队`) is indistinguishable from `不对` (`bú duì`), and `kan4 bu4 jian4` cannot distinguish the V-不-C potential complement `看不见` (`kàn bu jiàn`, neutralizes `bu` to tone 0) from verb + noun `看部件` (`kàn bù jiàn`, retains citation T4).
163
+ - **Space-separated 3-T3 ambiguity**: Space-separated `zhi3 lao3 hu3` lacks Hanzi lexical heads (`纸` + `老虎`), so it defaults to `2+1` (`zhí láo hǔ`) unless written with Pinyin word grouping (`zhǐ lǎohǔ → zhǐ láo hǔ`).
164
+ - Therefore, `convertPinyinSequence` **intentionally avoids mutating `yi1` / `bu4` or guessing neutral particles** in pure Pinyin input so ordinary words like `医生 (yī shēng)` and `部队 (bù duì)` are never corrupted. When morpho-lexical sandhi is required, either pass Hanzi text to `convertMandarinText` / `mandarinToIpa`, or write surface sandhi/neutral tones directly in Pinyin (`kàn bu jiàn`, `yí gè`).
165
+
166
+ 2. **Syntactic vs. Lexical Disambiguation in Hanzi Mode / 汉字模式的句法歧义边界**
167
+ - `mandarin-ipa` combines `pinyin-pro` word segmentation with curated prosodic/morphological lexicons rather than running a heavy neural constituency parser. Rare classical readings, personal names, or syntactically ambiguous strings (e.g., `行` or `长` in unusual proper nouns) can be deterministically pinned via `customDict` or per-character `polyphoneOverrides`.
168
+
169
+ ---
170
+
171
+ ## Bundle Size / 打包体积数据
172
+
173
+ Measured directly on the compiled ESM output in `dist/` using `terser --module --compress --mangle` and `gzip -9` (excluding optional peer dependency `pinyin-pro`, which is dynamically imported on demand only in Hanzi mode):
174
+
175
+ | Entrypoint / Module | Raw Size (`dist/`) | `terser` Minified | `terser` + `gzip -9` | External Dependencies |
176
+ | --- | ---: | ---: | ---: | --- |
177
+ | **`mandarin-ipa/pinyin`** *(complete reachable graph: 4 ESM modules)* | **61,072 B (59.64 KB)** | **28,699 B (28.03 KB)** | **10,209 B (9.97 KB)** | **0 (Zero-dep)** |
178
+ | **`mandarin-ipa`** *(complete reachable graph: 6 ESM modules)* | **97,338 B (95.06 KB)** | **41,649 B (40.67 KB)** | **14,145 B (13.81 KB)** | Optional lazy `pinyin-pro` |
179
+ | `dist/types.js` | 3,712 B (3.62 KB) | 2,333 B (2.28 KB) | 724 B (0.71 KB) | — |
180
+ | `dist/ipaRules.js` | 18,752 B (18.31 KB) | 10,105 B (9.87 KB) | 3,700 B (3.61 KB) | — |
181
+ | `dist/sandhi.js` | 19,251 B (18.80 KB) | 8,163 B (7.97 KB) | 3,558 B (3.47 KB) | — |
182
+ | `dist/pinyin.js` *(subpath entry module)* | 19,357 B (18.90 KB) | 8,098 B (7.91 KB) | 2,774 B (2.71 KB) | — |
183
+ | `dist/converter.js` *(Hanzi & mixed-text engine)* | 36,084 B (35.24 KB) | 12,782 B (12.48 KB) | 4,943 B (4.83 KB) | Dynamic `import('pinyin-pro')` |
184
+ | `dist/index.js` *(main re-export entry)* | 182 B (0.18 KB) | 168 B (0.16 KB) | 144 B (0.14 KB) | — |
185
+
186
+ ---
187
+
188
+ ## License / 开源协议
189
+
190
+ [MIT](./LICENSE) © 2026 KasumiKitsune & T·Grid Contributors
@@ -0,0 +1,50 @@
1
+ import { isWholeSilenceTag } from './pinyin.js';
2
+ import { type ConvertTextOptions, type ConvertTextResult, type MandarinConvertOptions, type MandarinIpaConfig, type PolyphoneCandidate } from './types.js';
3
+ export { isWholeSilenceTag };
4
+ export interface PinyinProAllItem {
5
+ origin: string;
6
+ pinyin: string;
7
+ polyphonic: string[];
8
+ result: string;
9
+ }
10
+ export interface PinyinProModule {
11
+ pinyin(text: string, options: {
12
+ type: 'all';
13
+ toneType?: 'symbol' | 'num' | 'none';
14
+ toneSandhi?: boolean;
15
+ }): PinyinProAllItem[];
16
+ segment(text: string, options: {
17
+ format?: number;
18
+ toneType?: 'symbol' | 'num' | 'none';
19
+ toneSandhi?: boolean;
20
+ }): Array<Array<{
21
+ origin: string;
22
+ result: string;
23
+ }>>;
24
+ OutputFormat: {
25
+ readonly AllArray: number;
26
+ };
27
+ }
28
+ export declare function loadPinyinPro(): Promise<PinyinProModule>;
29
+ export interface CustomDictDiagnostic {
30
+ line: number;
31
+ text: string;
32
+ message: string;
33
+ }
34
+ export declare function parseCustomDictWithDiagnostics(raw: string): {
35
+ dict: Record<string, string>;
36
+ errors: CustomDictDiagnostic[];
37
+ };
38
+ export declare function convertMandarinText(sourceText: string, configOrOptions?: MandarinConvertOptions | MandarinIpaConfig, extraOptions?: ConvertTextOptions): Promise<ConvertTextResult>;
39
+ /**
40
+ * Extract context-disambiguated polyphone candidates from Mandarin Hanzi text.
41
+ */
42
+ export declare function extractPolyphones(sourceText: string, configOrOptions?: MandarinConvertOptions | MandarinIpaConfig, extraOptions?: ConvertTextOptions): Promise<PolyphoneCandidate[]>;
43
+ /**
44
+ * High-level convenience helper returning the converted IPA string for Hanzi / mixed text.
45
+ */
46
+ export declare function mandarinToIpa(sourceText: string, overrides?: MandarinConvertOptions): Promise<string>;
47
+ /**
48
+ * High-level convenience helper returning the sandhi-resolved Pinyin string for Hanzi / mixed text.
49
+ */
50
+ export declare function mandarinToPinyin(sourceText: string, overrides?: MandarinConvertOptions): Promise<string>;