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.
@@ -0,0 +1,896 @@
1
+ import { buildIpaOptionsFromConfig, formatPinyinSyllable, parsePinyinSyllable, pinyinSyllableToIpa } from './ipaRules.js';
2
+ import { applyPunctuationModeToUnits, isWholeSilenceTag, parseExplicitChaoTone } from './pinyin.js';
3
+ import { applyMandarinSandhi } from './sandhi.js';
4
+ import { createDefaultMandarinConfig } from './types.js';
5
+ export { isWholeSilenceTag };
6
+ let cachedPinyinPro = null;
7
+ let loadingPromise = null;
8
+ async function loadInternalPinyinPro() {
9
+ if (cachedPinyinPro)
10
+ return cachedPinyinPro;
11
+ if (!loadingPromise) {
12
+ loadingPromise = import('pinyin-pro')
13
+ .then((mod) => {
14
+ cachedPinyinPro = mod;
15
+ return mod;
16
+ })
17
+ .catch((err) => {
18
+ loadingPromise = null;
19
+ throw new Error('mandarin-ipa: Optional peer dependency "pinyin-pro" is not installed. ' +
20
+ 'Install it via `npm install pinyin-pro` to convert Hanzi text, or import ' +
21
+ '`mandarin-ipa/pinyin` for zero-dependency Pinyin-to-IPA conversion.', { cause: err });
22
+ });
23
+ }
24
+ return loadingPromise;
25
+ }
26
+ export async function loadPinyinPro() {
27
+ return (await loadInternalPinyinPro());
28
+ }
29
+ // ---------------------------------------------------------------------------
30
+ // Character / Pattern Constants
31
+ // ---------------------------------------------------------------------------
32
+ const HANZI_RE = /\p{Script=Han}/u;
33
+ const PUNCT_RE = /^\p{P}$/u;
34
+ const CHAO_TONE_RE = /[˥˦˧˨˩]/;
35
+ const INLINE_SILENCE_TAG_RE = /^(?:<(?:sil|sp|pau|unk|nsn)>|\[(?:sil|sp|pau|sigh|breath|noise|cough|laugh|pause)\])/i;
36
+ // Words starting with 儿 where 儿 is a full syllable (never erhua suffix)
37
+ const NON_ERHUA_PREFIX_WORDS = new Set([
38
+ '儿童', '儿子', '儿女', '儿歌', '儿科', '儿媳', '儿戏', '儿孙',
39
+ '儿时', '儿化', '儿郎', '儿茶', '儿马', '儿辈', '儿皇帝'
40
+ ]);
41
+ // Compounds ending in 儿 where 儿 is literary/full syllable ér (never erhua suffix)
42
+ const NON_ERHUA_SUFFIX_WORDS = new Set([
43
+ '女儿', '婴儿', '幼儿', '少儿', '孤儿', '健儿', '宠儿', '胎儿',
44
+ '男儿', '小儿', '育儿', '患儿', '产儿', '乳儿', '弃儿', '娇儿',
45
+ '骄儿', '爱儿', '痴儿', '呆儿', '傻儿', '孩儿', '徒儿', '侄儿',
46
+ '孙儿', '吾儿', '我儿', '托儿', '早产儿', '新生儿', '混血儿',
47
+ '幸运儿', '弄潮儿', '宁馨儿'
48
+ ]);
49
+ const DIGIT_CHARS = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
50
+ // ---------------------------------------------------------------------------
51
+ // Digit -> Mandarin Verbalization Helpers
52
+ // ---------------------------------------------------------------------------
53
+ function integerToChinese(numStr) {
54
+ const cleaned = numStr.replace(/^0+/, '');
55
+ if (!cleaned)
56
+ return '零';
57
+ const n = Number(cleaned);
58
+ if (!Number.isSafeInteger(n) || n > 99999999) {
59
+ return Array.from(numStr)
60
+ .map((d) => DIGIT_CHARS[Number(d)] ?? d)
61
+ .join('');
62
+ }
63
+ if (n < 10)
64
+ return DIGIT_CHARS[n];
65
+ if (n < 20)
66
+ return n === 10 ? '十' : '十' + DIGIT_CHARS[n % 10];
67
+ if (n < 100) {
68
+ const tens = Math.floor(n / 10);
69
+ const ones = n % 10;
70
+ return DIGIT_CHARS[tens] + '十' + (ones > 0 ? DIGIT_CHARS[ones] : '');
71
+ }
72
+ const units = ['', '十', '百', '千'];
73
+ const convertUnder10000 = (val, leadingZero) => {
74
+ if (val === 0)
75
+ return '';
76
+ const digits = String(val).padStart(4, '0').split('').map(Number);
77
+ let res = '';
78
+ let needZero = leadingZero;
79
+ let started = false;
80
+ for (let i = 0; i < 4; i++) {
81
+ const d = digits[i];
82
+ const u = units[3 - i];
83
+ if (d === 0) {
84
+ if (started)
85
+ needZero = true;
86
+ }
87
+ else {
88
+ if (needZero) {
89
+ res += '零';
90
+ needZero = false;
91
+ }
92
+ if (d === 1 && u === '十' && !started && !leadingZero) {
93
+ res += '十';
94
+ }
95
+ else {
96
+ res += DIGIT_CHARS[d] + u;
97
+ }
98
+ started = true;
99
+ }
100
+ }
101
+ return res;
102
+ };
103
+ const wan = Math.floor(n / 10000);
104
+ const rem = n % 10000;
105
+ if (wan > 0) {
106
+ const high = convertUnder10000(wan, false) + '万';
107
+ if (rem === 0)
108
+ return high;
109
+ const low = convertUnder10000(rem, rem < 1000);
110
+ return high + low;
111
+ }
112
+ return convertUnder10000(rem, false);
113
+ }
114
+ function verbalizeNumberToken(numStr, prevChar, nextChar) {
115
+ // Decimal (e.g. 3.14 -> 三点一四)
116
+ if (numStr.includes('.')) {
117
+ const [intPart, fracPart] = numStr.split('.');
118
+ const intZh = integerToChinese(intPart || '0');
119
+ const fracZh = Array.from(fracPart || '')
120
+ .map((d) => DIGIT_CHARS[Number(d)] ?? '')
121
+ .join('');
122
+ return { text: intZh + '点' + fracZh, lockDigitTones: true };
123
+ }
124
+ // Year (e.g. 2026年 -> 二零二六年, 1998年 -> 一九九八年)
125
+ if (numStr.length === 4 && nextChar === '年') {
126
+ return {
127
+ text: Array.from(numStr)
128
+ .map((d) => DIGIT_CHARS[Number(d)] ?? '')
129
+ .join(''),
130
+ lockDigitTones: true
131
+ };
132
+ }
133
+ // Phone / code with leading zeros (e.g. 007, 014) -> digit-by-digit
134
+ if (numStr.length > 1 && numStr.startsWith('0')) {
135
+ return {
136
+ text: Array.from(numStr)
137
+ .map((d) => DIGIT_CHARS[Number(d)] ?? '')
138
+ .join(''),
139
+ lockDigitTones: true
140
+ };
141
+ }
142
+ // Ordinal after 第 always uses 二, never 两
143
+ if (prevChar === '第') {
144
+ return { text: integerToChinese(numStr), lockDigitTones: false };
145
+ }
146
+ return { text: integerToChinese(numStr), lockDigitTones: false };
147
+ }
148
+ // ---------------------------------------------------------------------------
149
+ // Explicit Numeric Tone Suffix Parsing on Inline Latin Pinyin (ma35, lv4, ni214)
150
+ // ---------------------------------------------------------------------------
151
+ function parseExplicitNumericTone(str) {
152
+ switch (str) {
153
+ case '1':
154
+ case '55':
155
+ return { tone: 1, isHalfThird: false };
156
+ case '2':
157
+ case '35':
158
+ return { tone: 2, isHalfThird: false };
159
+ case '3':
160
+ case '214':
161
+ return { tone: 3, isHalfThird: false };
162
+ case '21':
163
+ return { tone: 3, isHalfThird: true };
164
+ case '4':
165
+ case '51':
166
+ return { tone: 4, isHalfThird: false };
167
+ case '0':
168
+ case '5':
169
+ return { tone: 0, isHalfThird: false };
170
+ default:
171
+ return null;
172
+ }
173
+ }
174
+ function tryParseLatinPinyinWithTone(word) {
175
+ // Only parse numeric tone suffix on pure lowercase Latin Pinyin syllables (e.g. ma3, lv4, ni214),
176
+ // never on uppercase technical acronyms like F0/VOT or after ordinary Hanzi.
177
+ const m = /^([a-züê']+)([0-9]+)$/.exec(word);
178
+ if (!m)
179
+ return null;
180
+ const [, body, digits] = m;
181
+ const toneParsed = parseExplicitNumericTone(digits);
182
+ if (!toneParsed)
183
+ return null;
184
+ const sylParsed = parsePinyinSyllable(body);
185
+ if (!sylParsed.isValid)
186
+ return null;
187
+ return {
188
+ bare: sylParsed.bare,
189
+ tone: toneParsed.tone,
190
+ isErhua: sylParsed.isErhua,
191
+ isHalfThird: toneParsed.isHalfThird
192
+ };
193
+ }
194
+ function tokenizeMixedText(text, digitMode) {
195
+ const chars = Array.from(text);
196
+ const chunks = [];
197
+ const pushHanzi = (item) => {
198
+ const last = chunks[chunks.length - 1];
199
+ if (last && last.kind === 'hanzi-run') {
200
+ last.items.push(item);
201
+ }
202
+ else {
203
+ chunks.push({ kind: 'hanzi-run', items: [item] });
204
+ }
205
+ };
206
+ let i = 0;
207
+ while (i < chars.length) {
208
+ const ch = chars[i];
209
+ // Whitespace ends current Hanzi run; newlines and multi-space/tab separators emit prosodic domain breaks
210
+ if (/^\s+$/.test(ch)) {
211
+ const wsStart = i;
212
+ while (i < chars.length && /^\s+$/.test(chars[i]))
213
+ i++;
214
+ const ws = chars.slice(wsStart, i).join('');
215
+ if (ws.includes('\n') || ws.includes('\r') || ws.includes('\t') || ws.length >= 2) {
216
+ chunks.push({ kind: 'break', text: ws, start: wsStart, end: i });
217
+ }
218
+ continue;
219
+ }
220
+ // Inline silence / paralinguistic tags (<sil>, <pau>, [sigh], etc.)
221
+ if (ch === '<' || ch === '[') {
222
+ const rest = chars.slice(i).join('');
223
+ const tagMatch = rest.match(INLINE_SILENCE_TAG_RE);
224
+ if (tagMatch) {
225
+ const tagLen = Array.from(tagMatch[0]).length;
226
+ chunks.push({ kind: 'silence', text: tagMatch[0], start: i, end: i + tagLen });
227
+ i += tagLen;
228
+ continue;
229
+ }
230
+ }
231
+ // Hanzi character (with optional explicit Chao tone letters like 妈˥˥; digits after Hanzi are NEVER swallowed as tones)
232
+ if (HANZI_RE.test(ch)) {
233
+ const charIndex = i;
234
+ let rawText = ch;
235
+ let explicitTone;
236
+ let explicitHalfThird = false;
237
+ i++;
238
+ // Check immediate Chao tone suffix (e.g. 妈˥˥)
239
+ if (i < chars.length && CHAO_TONE_RE.test(chars[i])) {
240
+ let j = i;
241
+ while (j < chars.length && CHAO_TONE_RE.test(chars[j]))
242
+ j++;
243
+ const toneStr = chars.slice(i, j).join('');
244
+ const parsed = parseExplicitChaoTone(toneStr);
245
+ if (parsed) {
246
+ explicitTone = parsed.tone;
247
+ explicitHalfThird = parsed.isHalfThird;
248
+ rawText += toneStr;
249
+ i = j;
250
+ }
251
+ }
252
+ const item = {
253
+ char: ch,
254
+ charIndex,
255
+ sourceCharStart: charIndex,
256
+ sourceCharEnd: i,
257
+ rawText,
258
+ explicitTone,
259
+ explicitHalfThird
260
+ };
261
+ const prevWasWhitespace = charIndex > 0 && /^\s+$/.test(chars[charIndex - 1]);
262
+ if (prevWasWhitespace) {
263
+ chunks.push({ kind: 'hanzi-run', items: [item] });
264
+ }
265
+ else {
266
+ pushHanzi(item);
267
+ }
268
+ continue;
269
+ }
270
+ // Digits (strictly follow digitMode: 'verbalize' -> Chinese numerals, 'keep' -> raw digits)
271
+ if (/[0-9]/.test(ch)) {
272
+ const start = i;
273
+ let j = i;
274
+ while (j < chars.length &&
275
+ (/[0-9]/.test(chars[j]) ||
276
+ (chars[j] === '.' && j + 1 < chars.length && /[0-9]/.test(chars[j + 1])))) {
277
+ j++;
278
+ }
279
+ const numStr = chars.slice(i, j).join('');
280
+ const prevChar = start > 0 ? chars[start - 1] : '';
281
+ const nextChar = j < chars.length ? chars[j] : '';
282
+ i = j;
283
+ if (digitMode === 'verbalize') {
284
+ const { text: zh, lockDigitTones } = verbalizeNumberToken(numStr, prevChar, nextChar);
285
+ const prevWasWhitespace = start > 0 && /^\s+$/.test(chars[start - 1]);
286
+ const zhChars = Array.from(zh);
287
+ zhChars.forEach((zc, idx) => {
288
+ const item = {
289
+ char: zc,
290
+ charIndex: -1,
291
+ sourceCharStart: start,
292
+ sourceCharEnd: j,
293
+ rawText: zc,
294
+ fromDigit: true,
295
+ lockDigitTone: lockDigitTones
296
+ };
297
+ if (idx === 0 && prevWasWhitespace) {
298
+ chunks.push({ kind: 'hanzi-run', items: [item] });
299
+ }
300
+ else {
301
+ pushHanzi(item);
302
+ }
303
+ });
304
+ }
305
+ else {
306
+ chunks.push({ kind: 'digit', text: numStr, start, end: j });
307
+ }
308
+ continue;
309
+ }
310
+ // Latin word / code (e.g. F0, VOT, Hz, TextGrid) or numeric-tone Pinyin syllable (e.g. ma3, lv4, ni214)
311
+ if (/[A-Za-züê]/.test(ch)) {
312
+ const start = i;
313
+ let j = i;
314
+ while (j < chars.length && /[A-Za-züê0-9_'-]/.test(chars[j])) {
315
+ j++;
316
+ }
317
+ while (j > i + 1 && /['-]/.test(chars[j - 1])) {
318
+ j--;
319
+ }
320
+ const word = chars.slice(i, j).join('');
321
+ const pinyinTone = tryParseLatinPinyinWithTone(word);
322
+ if (pinyinTone) {
323
+ chunks.push({
324
+ kind: 'pinyin-latin',
325
+ text: word,
326
+ bare: pinyinTone.bare,
327
+ tone: pinyinTone.tone,
328
+ isErhua: pinyinTone.isErhua,
329
+ isHalfThird: pinyinTone.isHalfThird,
330
+ start,
331
+ end: j
332
+ });
333
+ }
334
+ else {
335
+ chunks.push({ kind: 'latin', text: word, start, end: j });
336
+ }
337
+ i = j;
338
+ continue;
339
+ }
340
+ // Punctuation
341
+ if (PUNCT_RE.test(ch)) {
342
+ chunks.push({ kind: 'punctuation', text: ch, start: i, end: i + 1 });
343
+ i++;
344
+ continue;
345
+ }
346
+ // Other symbol
347
+ chunks.push({ kind: 'other', text: ch, start: i, end: i + 1 });
348
+ i++;
349
+ }
350
+ return chunks;
351
+ }
352
+ // ---------------------------------------------------------------------------
353
+ // Erhua Word-Aware Detection
354
+ // ---------------------------------------------------------------------------
355
+ function shouldMergeErhuaAt(chars, wordIds, posInWords, wordLengths, idx) {
356
+ if (idx <= 0 || chars[idx] !== '儿')
357
+ return false;
358
+ if (chars[idx - 1] === '儿')
359
+ return false;
360
+ // 儿 starting a multi-char lexical word (儿童, 儿子, 儿歌, 儿科...)
361
+ if (posInWords[idx] === 0 && wordLengths[idx] >= 2)
362
+ return false;
363
+ if (idx + 1 < chars.length && NON_ERHUA_PREFIX_WORDS.has(chars[idx] + chars[idx + 1])) {
364
+ return false;
365
+ }
366
+ // Known literary non-erhua compounds ending in 儿 (女儿, 婴儿, 早产儿, 新生儿...)
367
+ const prev2 = chars[idx - 1] + '儿';
368
+ if (NON_ERHUA_SUFFIX_WORDS.has(prev2))
369
+ return false;
370
+ if (idx >= 2) {
371
+ const prev3 = chars[idx - 2] + chars[idx - 1] + '儿';
372
+ if (NON_ERHUA_SUFFIX_WORDS.has(prev3))
373
+ return false;
374
+ }
375
+ // If 儿 shares a wordId with the FOLLOWING character (e.g. 儿+童), never merge backward
376
+ if (idx + 1 < chars.length && wordIds[idx] === wordIds[idx + 1])
377
+ return false;
378
+ return true;
379
+ }
380
+ function isTrailingErhuaDictEntry(keyChars, syls) {
381
+ return (keyChars.length >= 2 &&
382
+ keyChars[keyChars.length - 1] === '儿' &&
383
+ syls.length === keyChars.length - 1 &&
384
+ parsePinyinSyllable(syls[syls.length - 1]).isErhua);
385
+ }
386
+ export function parseCustomDictWithDiagnostics(raw) {
387
+ const dict = {};
388
+ const errors = [];
389
+ const lines = raw.split(/\r?\n/);
390
+ for (let i = 0; i < lines.length; i++) {
391
+ const trimmed = lines[i].trim();
392
+ if (!trimmed || trimmed.startsWith('#'))
393
+ continue;
394
+ const eqIdx = trimmed.indexOf('=');
395
+ if (eqIdx <= 0) {
396
+ errors.push({
397
+ line: i + 1,
398
+ text: trimmed,
399
+ message: `第 ${i + 1} 行缺少「=」或词条为空,格式应为「词语=pīn yīn」`
400
+ });
401
+ continue;
402
+ }
403
+ const key = trimmed.slice(0, eqIdx).trim();
404
+ const val = trimmed.slice(eqIdx + 1).trim();
405
+ if (!key || !val) {
406
+ errors.push({
407
+ line: i + 1,
408
+ text: trimmed,
409
+ message: `第 ${i + 1} 行词条或拼音为空,格式应为「词语=pīn yīn」`
410
+ });
411
+ continue;
412
+ }
413
+ const keyChars = Array.from(key);
414
+ const syls = val.split(/\s+/).filter(Boolean);
415
+ const matchesLen = syls.length === keyChars.length || isTrailingErhuaDictEntry(keyChars, syls);
416
+ if (!matchesLen) {
417
+ errors.push({
418
+ line: i + 1,
419
+ text: trimmed,
420
+ message: `第 ${i + 1} 行「${key}」音节数(${syls.length})与字数(${keyChars.length})不匹配,请用空格分隔每个音节`
421
+ });
422
+ continue;
423
+ }
424
+ const badSyl = syls.find((s) => !parsePinyinSyllable(s).isValid);
425
+ if (badSyl) {
426
+ errors.push({
427
+ line: i + 1,
428
+ text: trimmed,
429
+ message: `第 ${i + 1} 行「${key}」包含无法识别的拼音「${badSyl}」`
430
+ });
431
+ continue;
432
+ }
433
+ dict[key] = val;
434
+ }
435
+ return { dict, errors };
436
+ }
437
+ const compiledCustomDictCache = new WeakMap();
438
+ function compileCustomDict(customDict) {
439
+ if (!customDict)
440
+ return [];
441
+ const rawEntries = Object.entries(customDict);
442
+ if (rawEntries.length === 0)
443
+ return [];
444
+ const sig = rawEntries.map(([k, v]) => `${k}\0${v}`).join('\n');
445
+ const cached = compiledCustomDictCache.get(customDict);
446
+ if (cached && cached.sig === sig) {
447
+ return cached.entries;
448
+ }
449
+ const entries = [];
450
+ for (const [key, value] of rawEntries) {
451
+ const k = key.trim();
452
+ const v = value.trim();
453
+ if (!k || !v)
454
+ continue;
455
+ const keyChars = Array.from(k);
456
+ const syls = v.split(/\s+/).filter(Boolean);
457
+ const trailingErhuaMerged = isTrailingErhuaDictEntry(keyChars, syls);
458
+ if (syls.length === keyChars.length || trailingErhuaMerged) {
459
+ entries.push({ key: k, chars: keyChars, syllables: syls, trailingErhuaMerged });
460
+ }
461
+ }
462
+ entries.sort((a, b) => b.chars.length - a.chars.length);
463
+ compiledCustomDictCache.set(customDict, { sig, entries });
464
+ return entries;
465
+ }
466
+ // ---------------------------------------------------------------------------
467
+ // Polyphone Override Lookup
468
+ // ---------------------------------------------------------------------------
469
+ function getPolyphoneOverride(overrides, intervalIndex, charIndex) {
470
+ if (!overrides || charIndex < 0)
471
+ return undefined;
472
+ const scopedKey = `${intervalIndex}:${charIndex}`;
473
+ const plainKey = String(charIndex);
474
+ if (overrides instanceof Map) {
475
+ return (overrides.get(scopedKey) ??
476
+ (intervalIndex === 0 ? overrides.get(plainKey) ?? overrides.get(charIndex) : undefined));
477
+ }
478
+ const rec = overrides;
479
+ return rec[scopedKey] ?? (intervalIndex === 0 ? rec[plainKey] : undefined);
480
+ }
481
+ export async function convertMandarinText(sourceText, configOrOptions, extraOptions) {
482
+ const trimmed = sourceText.trim();
483
+ if (!trimmed) {
484
+ return {
485
+ sourceText,
486
+ pinyinText: '',
487
+ ipaText: '',
488
+ syllables: [],
489
+ polyphones: []
490
+ };
491
+ }
492
+ // Whole-utterance silence/paralinguistic tag passthrough
493
+ if (isWholeSilenceTag(trimmed)) {
494
+ return {
495
+ sourceText,
496
+ pinyinText: trimmed,
497
+ ipaText: trimmed,
498
+ syllables: [
499
+ {
500
+ kind: 'silence',
501
+ sourceText: trimmed,
502
+ pinyin: trimmed,
503
+ ipa: trimmed,
504
+ durationWeight: 1.0,
505
+ acousticClass: 'other'
506
+ }
507
+ ],
508
+ polyphones: []
509
+ };
510
+ }
511
+ const config = createDefaultMandarinConfig(configOrOptions);
512
+ // Preserve caller's customDict object reference when provided so WeakMap cache hits
513
+ const customDictRef = configOrOptions?.customDict ?? config.customDict;
514
+ const inlineOpts = configOrOptions;
515
+ const intervalIndex = extraOptions?.intervalIndex ?? inlineOpts?.intervalIndex ?? 0;
516
+ const timeSec = extraOptions?.timeSec ?? inlineOpts?.timeSec;
517
+ const polyphoneOverrides = extraOptions?.polyphoneOverrides ?? inlineOpts?.polyphoneOverrides;
518
+ const chunks = tokenizeMixedText(sourceText, config.digitMode);
519
+ const needsPinyinPro = chunks.some((c) => c.kind === 'hanzi-run');
520
+ const mod = needsPinyinPro ? await loadInternalPinyinPro() : null;
521
+ const customEntries = needsPinyinPro ? compileCustomDict(customDictRef) : [];
522
+ const intermediate = [];
523
+ const polyphones = [];
524
+ const sourceChars = Array.from(sourceText);
525
+ let nextWordId = 1;
526
+ for (const chunk of chunks) {
527
+ if (chunk.kind === 'pinyin-latin') {
528
+ intermediate.push({
529
+ kind: 'hanzi',
530
+ sourceText: chunk.text,
531
+ char: '',
532
+ charIndex: -1,
533
+ sourceCharStart: chunk.start,
534
+ sourceCharEnd: chunk.end,
535
+ bare: chunk.bare,
536
+ tone: chunk.tone,
537
+ isErhua: chunk.isErhua,
538
+ lockedTone: true,
539
+ explicitHalfThird: chunk.isHalfThird,
540
+ rawText: chunk.text
541
+ });
542
+ continue;
543
+ }
544
+ if (chunk.kind !== 'hanzi-run') {
545
+ intermediate.push({
546
+ kind: chunk.kind,
547
+ sourceText: chunk.text,
548
+ char: chunk.text,
549
+ charIndex: -1,
550
+ sourceCharStart: chunk.start,
551
+ sourceCharEnd: chunk.end,
552
+ bare: '',
553
+ tone: 0,
554
+ isErhua: false,
555
+ lockedTone: true,
556
+ explicitHalfThird: false,
557
+ rawText: chunk.text
558
+ });
559
+ continue;
560
+ }
561
+ const pinyinMod = mod;
562
+ const items = chunk.items;
563
+ const runChars = items.map((it) => it.char);
564
+ const runStr = runChars.join('');
565
+ // 1. Word segmentation + base word-level disambiguation (sandhi off; handled by sandhi.ts)
566
+ const segResult = pinyinMod.segment(runStr, {
567
+ format: pinyinMod.OutputFormat.AllArray,
568
+ toneType: 'num',
569
+ toneSandhi: false
570
+ });
571
+ const allResult = pinyinMod.pinyin(runStr, {
572
+ type: 'all',
573
+ toneType: 'num',
574
+ toneSandhi: false
575
+ });
576
+ const segPinyins = [];
577
+ const wordIds = [];
578
+ const posInWords = [];
579
+ const wordLengths = [];
580
+ for (const segWord of segResult) {
581
+ const wid = nextWordId++;
582
+ const wLen = segWord.length;
583
+ for (let p = 0; p < wLen; p++) {
584
+ segPinyins.push(segWord[p].result);
585
+ wordIds.push(wid);
586
+ posInWords.push(p);
587
+ wordLengths.push(wLen);
588
+ }
589
+ }
590
+ // Fallback alignment guard in case segment output length ever differs
591
+ while (segPinyins.length < items.length) {
592
+ const idx = segPinyins.length;
593
+ segPinyins.push(allResult[idx]?.pinyin ?? items[idx].char);
594
+ wordIds.push(nextWordId++);
595
+ posInWords.push(0);
596
+ wordLengths.push(1);
597
+ }
598
+ // 2. Apply customDict longest-match overrides
599
+ const customLocked = new Array(items.length).fill(false);
600
+ const customAbsorbed = new Array(items.length).fill(false);
601
+ if (customEntries.length > 0) {
602
+ let pos = 0;
603
+ while (pos < items.length) {
604
+ let matched = false;
605
+ for (const entry of customEntries) {
606
+ const len = entry.chars.length;
607
+ if (pos + len > items.length)
608
+ continue;
609
+ let ok = true;
610
+ for (let k = 0; k < len; k++) {
611
+ if (runChars[pos + k] !== entry.chars[k]) {
612
+ ok = false;
613
+ break;
614
+ }
615
+ }
616
+ if (ok) {
617
+ const wid = nextWordId++;
618
+ if (entry.trailingErhuaMerged) {
619
+ const sylLen = entry.syllables.length;
620
+ for (let k = 0; k < sylLen; k++) {
621
+ segPinyins[pos + k] = entry.syllables[k];
622
+ wordIds[pos + k] = wid;
623
+ posInWords[pos + k] = k;
624
+ wordLengths[pos + k] = sylLen;
625
+ customLocked[pos + k] = true;
626
+ }
627
+ customLocked[pos + len - 1] = true;
628
+ customAbsorbed[pos + len - 1] = true;
629
+ }
630
+ else {
631
+ for (let k = 0; k < len; k++) {
632
+ segPinyins[pos + k] = entry.syllables[k];
633
+ wordIds[pos + k] = wid;
634
+ posInWords[pos + k] = k;
635
+ wordLengths[pos + k] = len;
636
+ customLocked[pos + k] = true;
637
+ }
638
+ }
639
+ pos += len;
640
+ matched = true;
641
+ break;
642
+ }
643
+ }
644
+ if (!matched)
645
+ pos++;
646
+ }
647
+ }
648
+ // 3. Build per-character syllable records + collect polyphone candidates
649
+ const runTokens = [];
650
+ for (let k = 0; k < items.length; k++) {
651
+ const item = items[k];
652
+ if (customAbsorbed[k] && runTokens.length > 0) {
653
+ const prevTok = runTokens[runTokens.length - 1];
654
+ prevTok.sourceText += item.rawText;
655
+ prevTok.rawText += item.rawText;
656
+ prevTok.sourceCharEnd = item.sourceCharEnd;
657
+ continue;
658
+ }
659
+ let chosenRaw = segPinyins[k] ?? allResult[k]?.pinyin ?? '';
660
+ let lockedTone = customLocked[k] || Boolean(item.lockDigitTone);
661
+ let explicitHalfThird = false;
662
+ // Apply per-occurrence polyphone override if present
663
+ const userOverride = getPolyphoneOverride(polyphoneOverrides, intervalIndex, item.charIndex);
664
+ if (userOverride) {
665
+ chosenRaw = userOverride;
666
+ lockedTone = true;
667
+ }
668
+ const parsed = parsePinyinSyllable(chosenRaw);
669
+ let tone = parsed.tone;
670
+ const bare = parsed.bare;
671
+ // Explicit inline tone suffix (e.g. 妈˥˥) overrides tone & locks against sandhi
672
+ if (item.explicitTone !== undefined) {
673
+ tone = item.explicitTone;
674
+ explicitHalfThird = Boolean(item.explicitHalfThird);
675
+ lockedTone = true;
676
+ }
677
+ // Collect deduplicated polyphone candidates (skip synthetic verbalized digits and customDict-locked hits)
678
+ if (!item.fromDigit && !customLocked[k] && item.charIndex >= 0) {
679
+ const rawPoly = allResult[k]?.polyphonic ?? [];
680
+ const uniqueKeySet = new Set();
681
+ const formattedCandidates = [];
682
+ const addCandidate = (candRaw) => {
683
+ const cp = parsePinyinSyllable(candRaw);
684
+ if (!cp.isValid)
685
+ return;
686
+ const dedupeKey = `${cp.bare}:${cp.tone}`;
687
+ if (uniqueKeySet.has(dedupeKey))
688
+ return;
689
+ uniqueKeySet.add(dedupeKey);
690
+ formattedCandidates.push(formatPinyinSyllable(cp, config.pinyinFormat, config.neutralTone.mark));
691
+ };
692
+ const selectedFormatted = formatPinyinSyllable({ bare, tone, isErhua: parsed.isErhua }, config.pinyinFormat, config.neutralTone.mark);
693
+ if (parsed.isValid) {
694
+ uniqueKeySet.add(`${bare}:${tone}`);
695
+ formattedCandidates.push(selectedFormatted);
696
+ }
697
+ for (const p of rawPoly) {
698
+ addCandidate(p);
699
+ }
700
+ if (formattedCandidates.length > 1) {
701
+ const ctxStart = Math.max(0, item.charIndex - 3);
702
+ const ctxEnd = Math.min(sourceChars.length, item.charIndex + 4);
703
+ polyphones.push({
704
+ intervalIndex,
705
+ charIndex: item.charIndex,
706
+ char: item.char,
707
+ context: sourceChars.slice(ctxStart, ctxEnd).join(''),
708
+ selectedPinyin: selectedFormatted,
709
+ candidates: formattedCandidates,
710
+ timeSec
711
+ });
712
+ }
713
+ }
714
+ runTokens.push({
715
+ kind: 'hanzi',
716
+ sourceText: item.rawText,
717
+ char: item.char,
718
+ charIndex: item.charIndex,
719
+ sourceCharStart: item.sourceCharStart,
720
+ sourceCharEnd: item.sourceCharEnd,
721
+ bare,
722
+ tone,
723
+ isErhua: parsed.isErhua,
724
+ lockedTone,
725
+ explicitHalfThird,
726
+ wordId: wordIds[k],
727
+ posInWord: posInWords[k],
728
+ wordLength: wordLengths[k],
729
+ rawText: item.rawText
730
+ });
731
+ }
732
+ // 4. Word-aware erhua merging (花儿 -> huār / xua˞˥˥, while preserving 儿童/儿子/女儿/婴儿)
733
+ if (config.erhua === 'auto') {
734
+ const merged = [];
735
+ for (let k = 0; k < runTokens.length; k++) {
736
+ const cur = runTokens[k];
737
+ if (cur.char === '儿' &&
738
+ cur.bare === 'er' &&
739
+ !cur.lockedTone &&
740
+ merged.length > 0 &&
741
+ shouldMergeErhuaAt(runChars, wordIds, posInWords, wordLengths, k)) {
742
+ const prev = merged[merged.length - 1];
743
+ prev.isErhua = true;
744
+ prev.sourceText += cur.sourceText;
745
+ prev.sourceCharEnd = cur.sourceCharEnd;
746
+ }
747
+ else {
748
+ merged.push(cur);
749
+ }
750
+ }
751
+ intermediate.push(...merged);
752
+ }
753
+ else {
754
+ intermediate.push(...runTokens);
755
+ }
756
+ }
757
+ // 5. Apply Mandarin tone sandhi across all tokens (non-Hanzi tokens act as domain breaks)
758
+ const sandhiInputs = intermediate.map((tok) => ({
759
+ char: tok.char,
760
+ bare: tok.bare,
761
+ tone: tok.tone,
762
+ isHanzi: tok.kind === 'hanzi' && tok.char.length > 0,
763
+ isDomainBreak: tok.kind !== 'hanzi',
764
+ wordId: tok.wordId,
765
+ posInWord: tok.posInWord,
766
+ wordLength: tok.wordLength,
767
+ lockedTone: tok.lockedTone,
768
+ explicitHalfThird: tok.explicitHalfThird
769
+ }));
770
+ const sandhiOutputs = applyMandarinSandhi(sandhiInputs, config.sandhi);
771
+ // 6. Format Pinyin & IPA for every token
772
+ const baseIpaOptions = buildIpaOptionsFromConfig(config);
773
+ const rawUnits = [];
774
+ let prevHanziTone;
775
+ for (let i = 0; i < intermediate.length; i++) {
776
+ const tok = intermediate[i];
777
+ const so = sandhiOutputs[i];
778
+ if (tok.kind === 'break') {
779
+ prevHanziTone = undefined;
780
+ continue;
781
+ }
782
+ if (tok.kind === 'hanzi') {
783
+ const parsedForFormat = {
784
+ bare: tok.bare,
785
+ tone: so.tone,
786
+ isErhua: tok.isErhua
787
+ };
788
+ const pinyinOut = tok.bare
789
+ ? formatPinyinSyllable(parsedForFormat, config.pinyinFormat, config.neutralTone.mark)
790
+ : tok.sourceText;
791
+ // Construct structured ParsedPinyinSyllable directly so zero-initial 'e' + erhua
792
+ // never collides with independent syllable 'er' (e.g. 鹅儿 -> ɤ˞˧˥, not ɑɻ˧˥)
793
+ const baseParsed = parsePinyinSyllable(tok.bare);
794
+ const parsedFull = {
795
+ ...baseParsed,
796
+ raw: tok.bare +
797
+ (tok.isErhua ? (tok.bare === 'e' ? "'r" : 'r') : '') +
798
+ String(so.tone),
799
+ tone: so.tone,
800
+ isErhua: tok.isErhua
801
+ };
802
+ const ipaOut = parsedFull.isValid
803
+ ? pinyinSyllableToIpa(parsedFull, {
804
+ ...baseIpaOptions,
805
+ isHalfThird: so.isHalfThird,
806
+ prevTone: prevHanziTone
807
+ })
808
+ : tok.sourceText;
809
+ prevHanziTone = so.tone;
810
+ rawUnits.push({
811
+ kind: 'hanzi',
812
+ sourceText: tok.sourceText,
813
+ pinyin: pinyinOut,
814
+ ipa: ipaOut,
815
+ tone: so.tone,
816
+ isHalfThird: so.isHalfThird,
817
+ isErhua: tok.isErhua,
818
+ durationWeight: so.tone === 0 ? 0.72 : tok.isErhua ? 1.15 : 1.0,
819
+ acousticClass: 'syllable',
820
+ sourceCharStart: tok.sourceCharStart,
821
+ sourceCharEnd: tok.sourceCharEnd
822
+ });
823
+ }
824
+ else if (tok.kind === 'latin') {
825
+ prevHanziTone = undefined;
826
+ rawUnits.push({
827
+ kind: 'latin',
828
+ sourceText: tok.sourceText,
829
+ pinyin: tok.sourceText,
830
+ ipa: config.latinInIpa === 'keep' ? tok.sourceText : '',
831
+ durationWeight: Math.max(0.8, Math.min(2.2, tok.sourceText.length * 0.45)),
832
+ acousticClass: 'syllable',
833
+ sourceCharStart: tok.sourceCharStart,
834
+ sourceCharEnd: tok.sourceCharEnd
835
+ });
836
+ }
837
+ else if (tok.kind === 'digit' || tok.kind === 'silence' || tok.kind === 'other') {
838
+ prevHanziTone = undefined;
839
+ rawUnits.push({
840
+ kind: tok.kind,
841
+ sourceText: tok.sourceText,
842
+ pinyin: tok.sourceText,
843
+ ipa: tok.sourceText,
844
+ durationWeight: 0.9,
845
+ acousticClass: 'other',
846
+ sourceCharStart: tok.sourceCharStart,
847
+ sourceCharEnd: tok.sourceCharEnd
848
+ });
849
+ }
850
+ else if (tok.kind === 'punctuation') {
851
+ prevHanziTone = undefined;
852
+ rawUnits.push({
853
+ kind: 'punctuation',
854
+ sourceText: tok.sourceText,
855
+ pinyin: tok.sourceText,
856
+ ipa: tok.sourceText,
857
+ durationWeight: 0.35,
858
+ acousticClass: 'other',
859
+ sourceCharStart: tok.sourceCharStart,
860
+ sourceCharEnd: tok.sourceCharEnd
861
+ });
862
+ }
863
+ }
864
+ // 7. Apply punctuationMode ('ignore' | 'attach-prev' | 'keep')
865
+ const finalUnits = applyPunctuationModeToUnits(rawUnits, config.punctuationMode);
866
+ const pinyinParts = finalUnits.map((u) => u.pinyin).filter((s) => s.length > 0);
867
+ const ipaParts = finalUnits.map((u) => u.ipa).filter((s) => s.length > 0);
868
+ return {
869
+ sourceText,
870
+ pinyinText: pinyinParts.join(' '),
871
+ ipaText: ipaParts.join(' '),
872
+ syllables: finalUnits,
873
+ polyphones
874
+ };
875
+ }
876
+ /**
877
+ * Extract context-disambiguated polyphone candidates from Mandarin Hanzi text.
878
+ */
879
+ export async function extractPolyphones(sourceText, configOrOptions, extraOptions) {
880
+ const result = await convertMandarinText(sourceText, configOrOptions, extraOptions);
881
+ return result.polyphones;
882
+ }
883
+ /**
884
+ * High-level convenience helper returning the converted IPA string for Hanzi / mixed text.
885
+ */
886
+ export async function mandarinToIpa(sourceText, overrides) {
887
+ const result = await convertMandarinText(sourceText, overrides);
888
+ return result.ipaText;
889
+ }
890
+ /**
891
+ * High-level convenience helper returning the sandhi-resolved Pinyin string for Hanzi / mixed text.
892
+ */
893
+ export async function mandarinToPinyin(sourceText, overrides) {
894
+ const result = await convertMandarinText(sourceText, overrides);
895
+ return result.pinyinText;
896
+ }