Baseline: main branch state prior to Top-10 films expansion
This commit is contained in:
commit
6b15603e56
139 files changed
+329420
No files matched your search
+656
@@ -0,0 +1,656 @@
|
||||
"use strict";
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
|
||||
// src/index.ts
|
||||
var index_exports = {};
|
||||
__export(index_exports, {
|
||||
LANGUAGES: () => import_ipa4.LANGUAGES,
|
||||
reverseTranslate: () => reverseTranslate,
|
||||
reverseTranslateSync: () => reverseTranslateSync,
|
||||
reverseTranslateSyncWithMapping: () => reverseTranslateSyncWithMapping,
|
||||
setForeignDictLoader: () => setForeignDictLoader,
|
||||
translate: () => translate,
|
||||
translateSync: () => translateSync,
|
||||
translateSyncWithMapping: () => translateSyncWithMapping
|
||||
});
|
||||
module.exports = __toCommonJS(index_exports);
|
||||
var import_dictionary4 = require("@ingglish/dictionary");
|
||||
var import_ipa3 = require("@ingglish/ipa");
|
||||
|
||||
// src/foreign-dict.ts
|
||||
var foreignDictLoader;
|
||||
var foreignDictCache = /* @__PURE__ */ new Map();
|
||||
function getForeignDict(lang) {
|
||||
return foreignDictCache.get(lang);
|
||||
}
|
||||
function isForeignLang(lang) {
|
||||
return lang !== void 0 && lang !== "" && lang !== "en";
|
||||
}
|
||||
async function loadForeignDict(lang) {
|
||||
const cached = foreignDictCache.get(lang);
|
||||
if (cached) {
|
||||
return cached;
|
||||
}
|
||||
if (!foreignDictLoader) {
|
||||
throw new Error(
|
||||
`No foreign dictionary loader registered. Call setForeignDictLoader() before translating foreign languages.`
|
||||
);
|
||||
}
|
||||
const dict = await foreignDictLoader(lang);
|
||||
foreignDictCache.set(lang, dict);
|
||||
return dict;
|
||||
}
|
||||
function setForeignDictLoader(loader) {
|
||||
foreignDictLoader = loader;
|
||||
}
|
||||
|
||||
// src/translate/forward.ts
|
||||
var import_dictionary2 = require("@ingglish/dictionary");
|
||||
var import_fallback = require("@ingglish/fallback");
|
||||
var import_ipa = require("@ingglish/ipa");
|
||||
var import_normalize3 = require("@ingglish/normalize");
|
||||
var import_phonemes3 = require("@ingglish/phonemes");
|
||||
|
||||
// src/translate/contractions.ts
|
||||
var import_dictionary = require("@ingglish/dictionary");
|
||||
var import_normalize = require("@ingglish/normalize");
|
||||
var import_phonemes = require("@ingglish/phonemes");
|
||||
function translateContraction(token, format, translateWord2) {
|
||||
const phonemes = (0, import_dictionary.lookupPronunciation)(token);
|
||||
if (phonemes) {
|
||||
const translated = (0, import_phonemes.arpabetToFormat)(phonemes, format);
|
||||
if ((0, import_phonemes.getFormatPreservesCase)(format)) {
|
||||
if (token.toLowerCase().startsWith("i'")) {
|
||||
return translated.toLowerCase();
|
||||
}
|
||||
const casePattern = (0, import_normalize.detectCasePattern)(token);
|
||||
return (0, import_normalize.applyCasePattern)(translated, casePattern, token);
|
||||
}
|
||||
return translated;
|
||||
}
|
||||
const parts = token.split("'");
|
||||
return parts.map((p, i) => {
|
||||
if (!p) {
|
||||
return "";
|
||||
}
|
||||
if (i > 0 && p.toLowerCase() === "t") {
|
||||
return "t";
|
||||
}
|
||||
return translateWord2(p, format);
|
||||
}).join("'");
|
||||
}
|
||||
|
||||
// src/translate/pipeline.ts
|
||||
var import_normalize2 = require("@ingglish/normalize");
|
||||
var import_phonemes2 = require("@ingglish/phonemes");
|
||||
|
||||
// src/translate/preserved.ts
|
||||
function expandPlaceholder(token, preserved) {
|
||||
const matches = [];
|
||||
for (const [placeholder, original] of preserved) {
|
||||
const idx = token.indexOf(placeholder);
|
||||
if (idx !== -1) {
|
||||
matches.push({ index: idx, original, placeholder });
|
||||
}
|
||||
}
|
||||
if (matches.length === 0) {
|
||||
return null;
|
||||
}
|
||||
matches.sort((a, b) => a.index - b.index);
|
||||
const result = [];
|
||||
let pos = 0;
|
||||
for (const { index, original, placeholder } of matches) {
|
||||
if (index > pos) {
|
||||
const before = token.slice(pos, index);
|
||||
result.push({ isWord: false, matched: true, original: before, translated: before });
|
||||
}
|
||||
result.push({ isWord: false, matched: true, original, translated: original });
|
||||
pos = index + placeholder.length;
|
||||
}
|
||||
if (pos < token.length) {
|
||||
const after = token.slice(pos);
|
||||
result.push({ isWord: false, matched: true, original: after, translated: after });
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// src/translate/pipeline.ts
|
||||
var SENTENCE_END = /[.?!]/;
|
||||
var HAS_LETTER = /[a-z]/i;
|
||||
function extractTokens(text) {
|
||||
const normalized = (0, import_normalize2.normalizeApostrophes)(text);
|
||||
const { preserved, text: textWithPlaceholders } = (0, import_normalize2.extractPreservedPatterns)(normalized);
|
||||
const rawTokens = textWithPlaceholders.split(import_normalize2.WORD_SPLIT_REGEX);
|
||||
return { preserved, rawTokens };
|
||||
}
|
||||
function mapTokens(rawTokens, preserved, translateWord2) {
|
||||
const result = [];
|
||||
const hasPreserved = preserved.size > 0;
|
||||
for (const [i, token] of rawTokens.entries()) {
|
||||
if (token.length === 0) {
|
||||
continue;
|
||||
}
|
||||
if (hasPreserved) {
|
||||
const expanded = expandPlaceholder(token, preserved);
|
||||
if (expanded) {
|
||||
result.push(...expanded);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (i % 2 === 1) {
|
||||
const { matched, translated } = translateWord2(token);
|
||||
result.push({ isWord: true, matched, original: token, translated });
|
||||
} else {
|
||||
result.push({ isWord: false, matched: true, original: token, translated: token });
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
var expandPlaceholderText = (token, preserved) => {
|
||||
let found = false;
|
||||
let result = token;
|
||||
for (const [placeholder, original] of preserved) {
|
||||
const idx = result.indexOf(placeholder);
|
||||
if (idx !== -1) {
|
||||
result = result.slice(0, idx) + original + result.slice(idx + placeholder.length);
|
||||
found = true;
|
||||
}
|
||||
}
|
||||
return found ? result : null;
|
||||
};
|
||||
function renderText(rawTokens, preserved, translateWord2, format) {
|
||||
const preservesCase = (0, import_phonemes2.getFormatPreservesCase)(format);
|
||||
const hasPreserved = preserved.size > 0;
|
||||
let result = "";
|
||||
let wordCount = 0;
|
||||
let sentenceStart = true;
|
||||
let firstWordStart = -1;
|
||||
for (const [i, token] of rawTokens.entries()) {
|
||||
if (token.length === 0) {
|
||||
continue;
|
||||
}
|
||||
if (hasPreserved) {
|
||||
const expanded = expandPlaceholderText(token, preserved);
|
||||
if (expanded !== null) {
|
||||
result += expanded;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (i % 2 === 1) {
|
||||
const translated = translateWord2(token);
|
||||
wordCount++;
|
||||
if (preservesCase && sentenceStart && translated.length > 0) {
|
||||
if (wordCount === 1) {
|
||||
firstWordStart = result.length;
|
||||
result += translated;
|
||||
} else {
|
||||
result += translated.charAt(0).toUpperCase() + translated.slice(1);
|
||||
}
|
||||
} else {
|
||||
result += translated;
|
||||
}
|
||||
sentenceStart = false;
|
||||
} else {
|
||||
if (preservesCase && SENTENCE_END.test(token) && !HAS_LETTER.test(token)) {
|
||||
sentenceStart = true;
|
||||
}
|
||||
result += token;
|
||||
}
|
||||
}
|
||||
if (preservesCase && wordCount > 1 && firstWordStart !== -1) {
|
||||
const firstChar = result.charAt(firstWordStart);
|
||||
const upper = firstChar.toUpperCase();
|
||||
if (upper !== firstChar) {
|
||||
result = result.slice(0, firstWordStart) + upper + result.slice(firstWordStart + 1);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// src/translate/forward.ts
|
||||
var ALL_UPPER = /^[A-Z]+$/;
|
||||
var TRIPLE_CHAR = /(.)\1\1/;
|
||||
var HAS_VOWEL = /[aeiouy]/i;
|
||||
var TITLE_CASE = /^[A-Z][a-z]*$/;
|
||||
function translateSync(text, options = {}) {
|
||||
const { format = "ingglish", lang } = options;
|
||||
if (isForeignLang(lang)) {
|
||||
const dict = getForeignDict(lang);
|
||||
if (!dict) {
|
||||
throw new Error(
|
||||
`Foreign dictionary for "${lang}" not loaded. Call translate(text, { lang: "${lang}" }) or loadForeignDict("${lang}") first.`
|
||||
);
|
||||
}
|
||||
return (0, import_ipa.translateForeign)(text, dict, format);
|
||||
}
|
||||
const { preserved, rawTokens } = extractTokens(text);
|
||||
return renderText(rawTokens, preserved, (w) => translateWordString(w, format), format);
|
||||
}
|
||||
function translateSyncWithMapping(text, options = {}) {
|
||||
const { format = "ingglish", lang } = options;
|
||||
if (isForeignLang(lang)) {
|
||||
const dict = getForeignDict(lang);
|
||||
if (!dict) {
|
||||
throw new Error(
|
||||
`Foreign dictionary for "${lang}" not loaded. Call translate(text, { lang: "${lang}" }) or loadForeignDict("${lang}") first.`
|
||||
);
|
||||
}
|
||||
return (0, import_ipa.translateForeignWithMapping)(text, dict, format);
|
||||
}
|
||||
const { preserved, rawTokens } = extractTokens(text);
|
||||
return mapTokens(rawTokens, preserved, (w) => translateWordInternal(w, format));
|
||||
}
|
||||
function translateWord(word, options = {}) {
|
||||
const { format = "ingglish", lang } = options;
|
||||
if (isForeignLang(lang)) {
|
||||
const dict = getForeignDict(lang);
|
||||
if (!dict) {
|
||||
throw new Error(
|
||||
`Foreign dictionary for "${lang}" not loaded. Call translate(text, { lang: "${lang}" }) or loadForeignDict("${lang}") first.`
|
||||
);
|
||||
}
|
||||
const ipa = (0, import_ipa.lookupIpa)(dict, word);
|
||||
return ipa ?? word;
|
||||
}
|
||||
return translateWordInternal(word, format).translated;
|
||||
}
|
||||
function isAllLowerAscii(word) {
|
||||
for (let i = 0; i < word.length; i++) {
|
||||
const c = word.codePointAt(i);
|
||||
if (c < 97 || c > 122) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
function isInitialismLower(key) {
|
||||
if (import_fallback.KNOWN_INITIALISMS.has(key)) {
|
||||
return true;
|
||||
}
|
||||
return key.length > 1 && key.endsWith("s") && import_fallback.KNOWN_INITIALISMS.has(key.slice(0, -1));
|
||||
}
|
||||
function isTitleCaseAscii(word) {
|
||||
if (word.length < 2) {
|
||||
return false;
|
||||
}
|
||||
const first = word.codePointAt(0);
|
||||
if (first < 65 || first > 90) {
|
||||
return false;
|
||||
}
|
||||
for (let i = 1; i < word.length; i++) {
|
||||
const c = word.codePointAt(i);
|
||||
if (c < 97 || c > 122) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
function translateWithFallback(word, format, casePattern) {
|
||||
if (TRIPLE_CHAR.test(word) || !HAS_VOWEL.test(word)) {
|
||||
return { matched: false, translated: word };
|
||||
}
|
||||
const stripped = (0, import_normalize3.stripDiacritics)(word);
|
||||
const fallbackResult = (0, import_fallback.translateUnknown)(stripped, format);
|
||||
if (!fallbackResult || fallbackResult.length === 0) {
|
||||
return { matched: false, translated: word };
|
||||
}
|
||||
if ((0, import_phonemes3.getFormatPreservesCase)(format)) {
|
||||
const hasInternalMixedCase = fallbackResult !== fallbackResult.toLowerCase() && fallbackResult !== fallbackResult.toUpperCase() && !TITLE_CASE.test(fallbackResult);
|
||||
if (hasInternalMixedCase) {
|
||||
return { matched: false, translated: fallbackResult };
|
||||
}
|
||||
return { matched: false, translated: (0, import_normalize3.applyCasePattern)(fallbackResult, casePattern, word) };
|
||||
}
|
||||
return { matched: false, translated: fallbackResult };
|
||||
}
|
||||
function translateWordInternal(word, format) {
|
||||
if (!word || !HAS_LETTER.test(word)) {
|
||||
return { matched: true, translated: word };
|
||||
}
|
||||
const fast = tryFastPath(word, format) ?? tryTitleCaseFastPath(word, format);
|
||||
if (fast !== null) {
|
||||
return { matched: true, translated: fast };
|
||||
}
|
||||
const isLatinScript = (0, import_phonemes3.getFormatIsLatinScript)(format);
|
||||
const initialismSuffix = tryInitialismWithSuffix(word, format, isLatinScript);
|
||||
if (initialismSuffix) {
|
||||
return initialismSuffix;
|
||||
}
|
||||
if (word.includes("'")) {
|
||||
return {
|
||||
matched: true,
|
||||
translated: translateContraction(word, format, (w, f) => translateWord(w, { format: f }))
|
||||
};
|
||||
}
|
||||
const initialism = tryInitialism(word, format, isLatinScript);
|
||||
if (initialism) {
|
||||
return initialism;
|
||||
}
|
||||
if (isLatinScript && word.length >= 2 && ALL_UPPER.test(word)) {
|
||||
return { matched: true, translated: word };
|
||||
}
|
||||
const camel = tryCamelCase(word, format);
|
||||
if (camel) {
|
||||
return camel;
|
||||
}
|
||||
const casePattern = (0, import_normalize3.detectCasePattern)(word);
|
||||
const dictResult = tryDictionaryLookup(word, format, casePattern);
|
||||
if (dictResult) {
|
||||
return dictResult;
|
||||
}
|
||||
return translateWithFallback(word, format, casePattern);
|
||||
}
|
||||
function translateWordString(word, format) {
|
||||
if (!word || !HAS_LETTER.test(word)) {
|
||||
return word;
|
||||
}
|
||||
return tryFastPath(word, format) ?? tryTitleCaseFastPath(word, format) ?? translateWordInternal(word, format).translated;
|
||||
}
|
||||
function tryCamelCase(word, format) {
|
||||
const parts = (0, import_normalize3.splitCamelCase)(word);
|
||||
if (parts === null || parts.length <= 1) {
|
||||
return null;
|
||||
}
|
||||
let allMatched = true;
|
||||
const translatedParts = parts.map((part) => {
|
||||
if (part.length >= 2 && ALL_UPPER.test(part)) {
|
||||
return part;
|
||||
}
|
||||
const partCase = (0, import_normalize3.detectCasePattern)(part);
|
||||
const phonemes = (0, import_dictionary2.lookupPronunciation)(part);
|
||||
let translated;
|
||||
if (phonemes) {
|
||||
translated = (0, import_phonemes3.arpabetToFormat)(phonemes, format);
|
||||
} else {
|
||||
allMatched = false;
|
||||
translated = (0, import_fallback.translateUnknown)(part, format);
|
||||
}
|
||||
return (0, import_phonemes3.getFormatPreservesCase)(format) ? (0, import_normalize3.applyCasePattern)(translated, partCase, part) : translated;
|
||||
});
|
||||
return { matched: allMatched, translated: translatedParts.join("") };
|
||||
}
|
||||
function tryDictionaryLookup(word, format, casePattern) {
|
||||
const wordLower = word.toLowerCase();
|
||||
const phonemes = (0, import_dictionary2.lookupPronunciationLower)(wordLower);
|
||||
if (phonemes) {
|
||||
let result = (0, import_phonemes3.arpabetToFormat)(phonemes, format);
|
||||
if ((0, import_phonemes3.getFormatPreservesCase)(format)) {
|
||||
result = (0, import_normalize3.applyCasePattern)(result, casePattern, word);
|
||||
}
|
||||
return { matched: true, translated: result };
|
||||
}
|
||||
const stripped = (0, import_normalize3.stripDiacritics)(word);
|
||||
if (stripped !== word) {
|
||||
const strippedLower = stripped.toLowerCase();
|
||||
const strippedPhonemes = (0, import_dictionary2.lookupPronunciationLower)(strippedLower);
|
||||
if (strippedPhonemes) {
|
||||
let result = (0, import_phonemes3.arpabetToFormat)(strippedPhonemes, format);
|
||||
if ((0, import_phonemes3.getFormatPreservesCase)(format)) {
|
||||
result = (0, import_normalize3.applyCasePattern)(result, casePattern, word);
|
||||
}
|
||||
return { matched: true, translated: result };
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
function tryFastPath(word, format) {
|
||||
if (!isAllLowerAscii(word)) {
|
||||
return null;
|
||||
}
|
||||
if (isInitialismLower(word)) {
|
||||
return null;
|
||||
}
|
||||
const phonemes = (0, import_dictionary2.lookupPronunciationLower)(word);
|
||||
return phonemes ? (0, import_phonemes3.arpabetToFormat)(phonemes, format) : null;
|
||||
}
|
||||
function tryInitialism(word, format, isLatinScript) {
|
||||
if (!(0, import_fallback.isInitialism)(word)) {
|
||||
return null;
|
||||
}
|
||||
if (isLatinScript) {
|
||||
return { matched: true, translated: word };
|
||||
}
|
||||
if (word === word.toUpperCase()) {
|
||||
return { matched: true, translated: (0, import_fallback.translateAsAcronym)(word, format) };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
function tryInitialismWithSuffix(word, format, isLatinScript) {
|
||||
const parsed = (0, import_fallback.parseInitialismWithSuffix)(word);
|
||||
if (parsed === null) {
|
||||
return null;
|
||||
}
|
||||
if (isLatinScript || parsed.base === parsed.base.toUpperCase()) {
|
||||
const baseTranslated = translateWord(parsed.base, { format });
|
||||
return { matched: true, translated: baseTranslated + parsed.suffix };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
function tryTitleCaseFastPath(word, format) {
|
||||
if (!isTitleCaseAscii(word)) {
|
||||
return null;
|
||||
}
|
||||
const lower = word.toLowerCase();
|
||||
if (isInitialismLower(lower)) {
|
||||
return null;
|
||||
}
|
||||
const phonemes = (0, import_dictionary2.lookupPronunciationLower)(lower);
|
||||
if (!phonemes) {
|
||||
return null;
|
||||
}
|
||||
let translated = (0, import_phonemes3.arpabetToFormat)(phonemes, format);
|
||||
if ((0, import_phonemes3.getFormatPreservesCase)(format) && translated.length > 0) {
|
||||
translated = translated.charAt(0).toUpperCase() + translated.slice(1);
|
||||
}
|
||||
return translated;
|
||||
}
|
||||
|
||||
// src/translate/reverse.ts
|
||||
var import_dictionary3 = require("@ingglish/dictionary");
|
||||
var import_ipa2 = require("@ingglish/ipa");
|
||||
var import_normalize4 = require("@ingglish/normalize");
|
||||
var import_phonemes4 = require("@ingglish/phonemes");
|
||||
var ALT_FREQUENCY_THRESHOLD = 5;
|
||||
function reverseTranslateIPAWord(ipaWord) {
|
||||
if (!ipaWord || ipaWord.trim().length === 0) {
|
||||
return ipaWord ? [ipaWord] : [];
|
||||
}
|
||||
const arpabet = (0, import_ipa2.ipaToArpabetClean)(ipaWord);
|
||||
if (!arpabet) {
|
||||
return [ipaWord];
|
||||
}
|
||||
const matches = lookupByArpabet(arpabet);
|
||||
if (matches.length === 0) {
|
||||
return [ipaWord];
|
||||
}
|
||||
return matches;
|
||||
}
|
||||
function reverseTranslateWord(ingglishWord) {
|
||||
if (!ingglishWord || !HAS_LETTER.test(ingglishWord)) {
|
||||
return ingglishWord ? [ingglishWord] : [];
|
||||
}
|
||||
const casePattern = (0, import_normalize4.detectCasePattern)(ingglishWord);
|
||||
const arpabet = (0, import_phonemes4.ingglishToArpabet)(ingglishWord);
|
||||
if (!arpabet) {
|
||||
return [];
|
||||
}
|
||||
const matches = lookupByArpabet(arpabet);
|
||||
if (matches.length === 0) {
|
||||
return [];
|
||||
}
|
||||
return matches.map((word) => (0, import_normalize4.applyCasePattern)(word, casePattern));
|
||||
}
|
||||
function lookupByArpabet(arpabet) {
|
||||
const [primary, ...alternatives] = (0, import_phonemes4.expandArpabetAlternatives)(arpabet);
|
||||
if (!primary) {
|
||||
return [];
|
||||
}
|
||||
const primaryKey = primary.join(" ");
|
||||
const primaryMatches = (0, import_dictionary3.lookupPhonemeKey)(primaryKey);
|
||||
if (!primaryMatches || primaryMatches.length === 0) {
|
||||
const allMatches = [];
|
||||
const seen = /* @__PURE__ */ new Set();
|
||||
for (const variant of alternatives) {
|
||||
const key = variant.join(" ");
|
||||
const matches = (0, import_dictionary3.lookupPhonemeKey)(key);
|
||||
if (matches) {
|
||||
for (const match of matches) {
|
||||
if (!seen.has(match)) {
|
||||
seen.add(match);
|
||||
allMatches.push(match);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return allMatches.length > 1 ? (0, import_dictionary3.sortByFrequency)(allMatches) : allMatches;
|
||||
}
|
||||
const primaryBestFreq = (0, import_dictionary3.getWordFrequency)(primaryMatches[0] ?? "") ?? 0;
|
||||
for (const variant of alternatives) {
|
||||
const key = variant.join(" ");
|
||||
const matches = (0, import_dictionary3.lookupPhonemeKey)(key);
|
||||
if (matches && matches.length > 0) {
|
||||
const altBestFreq = (0, import_dictionary3.getWordFrequency)(matches[0] ?? "") ?? 0;
|
||||
if (altBestFreq > primaryBestFreq * ALT_FREQUENCY_THRESHOLD) {
|
||||
const allMatches = [...primaryMatches];
|
||||
const seen = new Set(primaryMatches);
|
||||
for (const match of matches) {
|
||||
if (!seen.has(match)) {
|
||||
seen.add(match);
|
||||
allMatches.push(match);
|
||||
}
|
||||
}
|
||||
return (0, import_dictionary3.sortByFrequency)(allMatches);
|
||||
}
|
||||
}
|
||||
}
|
||||
return primaryMatches;
|
||||
}
|
||||
(0, import_phonemes4.registerFormat)("ingglish", {
|
||||
reverseText: reverseTranslateIngglishText,
|
||||
reverseTextWithMapping: reverseTranslateIngglishTextWithMapping
|
||||
});
|
||||
(0, import_phonemes4.registerFormat)("ipa", {
|
||||
reverseText: reverseTranslateIPATextInternal,
|
||||
reverseTextWithMapping: reverseTranslateIPATextWithMapping
|
||||
});
|
||||
function reverseTranslateSync(text, options = {}) {
|
||||
const { format = "ingglish" } = options;
|
||||
const handler = (0, import_phonemes4.getFormatHandler)(format);
|
||||
if (handler?.reverseText) {
|
||||
return handler.reverseText(text);
|
||||
}
|
||||
return reverseTranslateIngglishText(text);
|
||||
}
|
||||
function reverseTranslateSyncWithMapping(text, options = {}) {
|
||||
const { format = "ingglish" } = options;
|
||||
const handler = (0, import_phonemes4.getFormatHandler)(format);
|
||||
if (handler?.reverseTextWithMapping) {
|
||||
return handler.reverseTextWithMapping(text);
|
||||
}
|
||||
return reverseTranslateIngglishTextWithMapping(text);
|
||||
}
|
||||
function reverseTranslateIngglishText(text) {
|
||||
return reverseTranslateIngglishTextWithMapping(text).map((t) => t.translated).join("");
|
||||
}
|
||||
function reverseTranslateIngglishTextWithMapping(text) {
|
||||
const { preserved, rawTokens } = extractTokens(text);
|
||||
return mapTokens(rawTokens, preserved, reverseTranslateWordAsResult);
|
||||
}
|
||||
function reverseTranslateIPATextInternal(text) {
|
||||
const cleanText = text.replaceAll(/^[/[\]]+|[/[\]]+$/g, "");
|
||||
const tokens = (0, import_normalize4.tokenizeIPA)(cleanText);
|
||||
return tokens.map((token) => {
|
||||
if (token.isWord) {
|
||||
const matches = reverseTranslateIPAWord(token.text);
|
||||
return matches[0] ?? token.text;
|
||||
}
|
||||
return token.text;
|
||||
}).join("");
|
||||
}
|
||||
function reverseTranslateIPATextWithMapping(text) {
|
||||
const cleanText = text.replaceAll(/^[/[\]]+|[/[\]]+$/g, "");
|
||||
const tokens = (0, import_normalize4.tokenizeIPA)(cleanText);
|
||||
return tokens.map((token) => {
|
||||
if (token.isWord) {
|
||||
const matches = reverseTranslateIPAWord(token.text);
|
||||
const translated = matches[0] ?? token.text;
|
||||
return {
|
||||
isWord: true,
|
||||
matched: translated !== token.text,
|
||||
original: token.text,
|
||||
translated
|
||||
};
|
||||
}
|
||||
return { isWord: false, matched: true, original: token.text, translated: token.text };
|
||||
});
|
||||
}
|
||||
function reverseTranslateWordAsResult(word) {
|
||||
if (!HAS_LETTER.test(word)) {
|
||||
return { matched: true, translated: word };
|
||||
}
|
||||
if (word.includes("'")) {
|
||||
const parts = word.split("'");
|
||||
let allMatched = true;
|
||||
const translatedParts = parts.map((p) => {
|
||||
if (!p) {
|
||||
return "";
|
||||
}
|
||||
const matches2 = reverseTranslateWord(p);
|
||||
if (matches2[0]) {
|
||||
return matches2[0];
|
||||
}
|
||||
allMatched = false;
|
||||
return p;
|
||||
});
|
||||
return { matched: allMatched, translated: translatedParts.join("'") };
|
||||
}
|
||||
const matches = reverseTranslateWord(word);
|
||||
if (matches[0]) {
|
||||
return { matched: true, translated: matches[0] };
|
||||
}
|
||||
return { matched: false, translated: word };
|
||||
}
|
||||
|
||||
// src/index.ts
|
||||
var import_ipa4 = require("@ingglish/ipa");
|
||||
async function reverseTranslate(text, options = {}) {
|
||||
const { format = "ingglish" } = options;
|
||||
await Promise.all([(0, import_dictionary4.loadReverseDictionary)(), (0, import_dictionary4.loadFrequencies)()]);
|
||||
return reverseTranslateSync(text, { format });
|
||||
}
|
||||
async function translate(text, options = {}) {
|
||||
const { format = "ingglish", lang } = options;
|
||||
if (isForeignLang(lang)) {
|
||||
const dict = await loadForeignDict(lang);
|
||||
return (0, import_ipa3.translateForeign)(text, dict, format);
|
||||
}
|
||||
await Promise.all([(0, import_dictionary4.loadDictionary)(), (0, import_dictionary4.loadFrequencies)()]);
|
||||
return translateSync(text, { format });
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
LANGUAGES,
|
||||
reverseTranslate,
|
||||
reverseTranslateSync,
|
||||
reverseTranslateSyncWithMapping,
|
||||
setForeignDictLoader,
|
||||
translate,
|
||||
translateSync,
|
||||
translateSyncWithMapping
|
||||
});
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
import { IpaDict } from '@ingglish/ipa';
|
||||
export { LANGUAGES, Language } from '@ingglish/ipa';
|
||||
import { OutputFormat, TranslatedToken } from '@ingglish/phonemes';
|
||||
export { OutputFormat, TranslatedToken } from '@ingglish/phonemes';
|
||||
|
||||
/**
|
||||
* Foreign dictionary loader and cache.
|
||||
*
|
||||
* Separated from index.ts to avoid circular dependencies with translate/forward.ts.
|
||||
*/
|
||||
|
||||
type ForeignDictLoader = (lang: string) => Promise<IpaDict>;
|
||||
interface TranslateOptions {
|
||||
/** Output format. @default 'ingglish' */
|
||||
format?: OutputFormat;
|
||||
/** Language code (omit or 'en' for English). */
|
||||
lang?: string;
|
||||
}
|
||||
/**
|
||||
* Register a function that loads IPA dictionaries for foreign languages.
|
||||
* Called once at application startup (e.g. in the website's entry point).
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* setForeignDictLoader(async (lang) => {
|
||||
* const resp = await fetch(`/ipa-dicts/${lang}.json`);
|
||||
* const entries = await resp.json();
|
||||
* return { entries, lang };
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
declare function setForeignDictLoader(loader: ForeignDictLoader): void;
|
||||
|
||||
/**
|
||||
* Forward translation: English -> Ingglish/IPA.
|
||||
*
|
||||
* Pipeline: English word → routing (dictionary, initialism, contraction,
|
||||
* camelCase, fallback) → ARPAbet `string[]` (the IR) → `arpabetToFormat()` → output.
|
||||
*
|
||||
* Every code path converges on an ARPAbet phoneme array before converting to
|
||||
* the requested output format. See `translateWordInternal()` for routing.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Synchronous version of {@link translate}. Dictionary must already be loaded.
|
||||
*
|
||||
* For foreign languages, the dictionary must have been loaded by a prior
|
||||
* `await translate(text, { lang })` or `await loadForeignDict(lang)` call.
|
||||
*/
|
||||
declare function translateSync(text: string, options?: TranslateOptions): string;
|
||||
/**
|
||||
* Like {@link translate}, but returns token-by-token mappings instead of a string.
|
||||
* Each token includes the original text, translation, and whether it matched
|
||||
* the dictionary. Dictionary must already be loaded.
|
||||
*
|
||||
* For foreign languages, the dictionary must have been loaded by a prior
|
||||
* `await translate(text, { lang })` or `await loadForeignDict(lang)` call.
|
||||
*/
|
||||
declare function translateSyncWithMapping(text: string, options?: TranslateOptions): TranslatedToken[];
|
||||
|
||||
/**
|
||||
* Reverse translation: Ingglish/IPA -> English.
|
||||
*
|
||||
* Uses ARPAbet matching to find English words that would produce
|
||||
* the given spelling. Handles homophones by preferring more common
|
||||
* words based on frequency data.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Synchronous version of {@link reverseTranslate}. Dictionary must already be loaded.
|
||||
*/
|
||||
declare function reverseTranslateSync(text: string, options?: TranslateOptions): string;
|
||||
/**
|
||||
* Like {@link reverseTranslate}, but returns token-by-token mappings instead of a string.
|
||||
* Each token includes the original text, translation, and whether it matched
|
||||
* the dictionary. Dictionary must already be loaded.
|
||||
*/
|
||||
declare function reverseTranslateSyncWithMapping(text: string, options?: TranslateOptions): TranslatedToken[];
|
||||
|
||||
/**
|
||||
* ingglish - Phonetic English Translation Library
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { translate } from 'ingglish';
|
||||
*
|
||||
* await translate('Hello, world!'); // 'Haloh, werld!'
|
||||
* await translate('Bonjour', { lang: 'fr' }); // French → Ingglish
|
||||
* ```
|
||||
*/
|
||||
|
||||
/**
|
||||
* Translates Ingglish/IPA text back to English.
|
||||
* Auto-loads the dictionary on first call.
|
||||
* For homophones, uses the most common word.
|
||||
*
|
||||
* @param text - Text in Ingglish or IPA format
|
||||
* @param options - Translation options (format)
|
||||
* @returns English text
|
||||
*/
|
||||
declare function reverseTranslate(text: string, options?: TranslateOptions): Promise<string>;
|
||||
/**
|
||||
* Translates text to the specified format.
|
||||
* Auto-loads dictionaries on first call.
|
||||
*
|
||||
* For English (default): loads the CMU pronunciation dictionary.
|
||||
* For foreign languages: loads the IPA dictionary via the registered loader.
|
||||
*
|
||||
* @param text - The text to translate
|
||||
* @param options - Translation options (format, lang)
|
||||
* @returns The translated text
|
||||
*/
|
||||
declare function translate(text: string, options?: TranslateOptions): Promise<string>;
|
||||
|
||||
export { type TranslateOptions, reverseTranslate, reverseTranslateSync, reverseTranslateSyncWithMapping, setForeignDictLoader, translate, translateSync, translateSyncWithMapping };
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
import { IpaDict } from '@ingglish/ipa';
|
||||
export { LANGUAGES, Language } from '@ingglish/ipa';
|
||||
import { OutputFormat, TranslatedToken } from '@ingglish/phonemes';
|
||||
export { OutputFormat, TranslatedToken } from '@ingglish/phonemes';
|
||||
|
||||
/**
|
||||
* Foreign dictionary loader and cache.
|
||||
*
|
||||
* Separated from index.ts to avoid circular dependencies with translate/forward.ts.
|
||||
*/
|
||||
|
||||
type ForeignDictLoader = (lang: string) => Promise<IpaDict>;
|
||||
interface TranslateOptions {
|
||||
/** Output format. @default 'ingglish' */
|
||||
format?: OutputFormat;
|
||||
/** Language code (omit or 'en' for English). */
|
||||
lang?: string;
|
||||
}
|
||||
/**
|
||||
* Register a function that loads IPA dictionaries for foreign languages.
|
||||
* Called once at application startup (e.g. in the website's entry point).
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* setForeignDictLoader(async (lang) => {
|
||||
* const resp = await fetch(`/ipa-dicts/${lang}.json`);
|
||||
* const entries = await resp.json();
|
||||
* return { entries, lang };
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
declare function setForeignDictLoader(loader: ForeignDictLoader): void;
|
||||
|
||||
/**
|
||||
* Forward translation: English -> Ingglish/IPA.
|
||||
*
|
||||
* Pipeline: English word → routing (dictionary, initialism, contraction,
|
||||
* camelCase, fallback) → ARPAbet `string[]` (the IR) → `arpabetToFormat()` → output.
|
||||
*
|
||||
* Every code path converges on an ARPAbet phoneme array before converting to
|
||||
* the requested output format. See `translateWordInternal()` for routing.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Synchronous version of {@link translate}. Dictionary must already be loaded.
|
||||
*
|
||||
* For foreign languages, the dictionary must have been loaded by a prior
|
||||
* `await translate(text, { lang })` or `await loadForeignDict(lang)` call.
|
||||
*/
|
||||
declare function translateSync(text: string, options?: TranslateOptions): string;
|
||||
/**
|
||||
* Like {@link translate}, but returns token-by-token mappings instead of a string.
|
||||
* Each token includes the original text, translation, and whether it matched
|
||||
* the dictionary. Dictionary must already be loaded.
|
||||
*
|
||||
* For foreign languages, the dictionary must have been loaded by a prior
|
||||
* `await translate(text, { lang })` or `await loadForeignDict(lang)` call.
|
||||
*/
|
||||
declare function translateSyncWithMapping(text: string, options?: TranslateOptions): TranslatedToken[];
|
||||
|
||||
/**
|
||||
* Reverse translation: Ingglish/IPA -> English.
|
||||
*
|
||||
* Uses ARPAbet matching to find English words that would produce
|
||||
* the given spelling. Handles homophones by preferring more common
|
||||
* words based on frequency data.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Synchronous version of {@link reverseTranslate}. Dictionary must already be loaded.
|
||||
*/
|
||||
declare function reverseTranslateSync(text: string, options?: TranslateOptions): string;
|
||||
/**
|
||||
* Like {@link reverseTranslate}, but returns token-by-token mappings instead of a string.
|
||||
* Each token includes the original text, translation, and whether it matched
|
||||
* the dictionary. Dictionary must already be loaded.
|
||||
*/
|
||||
declare function reverseTranslateSyncWithMapping(text: string, options?: TranslateOptions): TranslatedToken[];
|
||||
|
||||
/**
|
||||
* ingglish - Phonetic English Translation Library
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { translate } from 'ingglish';
|
||||
*
|
||||
* await translate('Hello, world!'); // 'Haloh, werld!'
|
||||
* await translate('Bonjour', { lang: 'fr' }); // French → Ingglish
|
||||
* ```
|
||||
*/
|
||||
|
||||
/**
|
||||
* Translates Ingglish/IPA text back to English.
|
||||
* Auto-loads the dictionary on first call.
|
||||
* For homophones, uses the most common word.
|
||||
*
|
||||
* @param text - Text in Ingglish or IPA format
|
||||
* @param options - Translation options (format)
|
||||
* @returns English text
|
||||
*/
|
||||
declare function reverseTranslate(text: string, options?: TranslateOptions): Promise<string>;
|
||||
/**
|
||||
* Translates text to the specified format.
|
||||
* Auto-loads dictionaries on first call.
|
||||
*
|
||||
* For English (default): loads the CMU pronunciation dictionary.
|
||||
* For foreign languages: loads the IPA dictionary via the registered loader.
|
||||
*
|
||||
* @param text - The text to translate
|
||||
* @param options - Translation options (format, lang)
|
||||
* @returns The translated text
|
||||
*/
|
||||
declare function translate(text: string, options?: TranslateOptions): Promise<string>;
|
||||
|
||||
export { type TranslateOptions, reverseTranslate, reverseTranslateSync, reverseTranslateSyncWithMapping, setForeignDictLoader, translate, translateSync, translateSyncWithMapping };
|
||||
+648
@@ -0,0 +1,648 @@
|
||||
// src/index.ts
|
||||
import { loadDictionary, loadReverseDictionary, loadFrequencies } from "@ingglish/dictionary";
|
||||
import { translateForeign as translateForeign2 } from "@ingglish/ipa";
|
||||
|
||||
// src/foreign-dict.ts
|
||||
var foreignDictLoader;
|
||||
var foreignDictCache = /* @__PURE__ */ new Map();
|
||||
function getForeignDict(lang) {
|
||||
return foreignDictCache.get(lang);
|
||||
}
|
||||
function isForeignLang(lang) {
|
||||
return lang !== void 0 && lang !== "" && lang !== "en";
|
||||
}
|
||||
async function loadForeignDict(lang) {
|
||||
const cached = foreignDictCache.get(lang);
|
||||
if (cached) {
|
||||
return cached;
|
||||
}
|
||||
if (!foreignDictLoader) {
|
||||
throw new Error(
|
||||
`No foreign dictionary loader registered. Call setForeignDictLoader() before translating foreign languages.`
|
||||
);
|
||||
}
|
||||
const dict = await foreignDictLoader(lang);
|
||||
foreignDictCache.set(lang, dict);
|
||||
return dict;
|
||||
}
|
||||
function setForeignDictLoader(loader) {
|
||||
foreignDictLoader = loader;
|
||||
}
|
||||
|
||||
// src/translate/forward.ts
|
||||
import { lookupPronunciation as lookupPronunciation2, lookupPronunciationLower } from "@ingglish/dictionary";
|
||||
import {
|
||||
translateUnknown,
|
||||
isInitialism,
|
||||
KNOWN_INITIALISMS,
|
||||
parseInitialismWithSuffix,
|
||||
translateAsAcronym
|
||||
} from "@ingglish/fallback";
|
||||
import { lookupIpa, translateForeign, translateForeignWithMapping } from "@ingglish/ipa";
|
||||
import {
|
||||
applyCasePattern as applyCasePattern2,
|
||||
detectCasePattern as detectCasePattern2,
|
||||
splitCamelCase,
|
||||
stripDiacritics
|
||||
} from "@ingglish/normalize";
|
||||
import {
|
||||
arpabetToFormat as arpabetToFormat2,
|
||||
getFormatIsLatinScript,
|
||||
getFormatPreservesCase as getFormatPreservesCase3
|
||||
} from "@ingglish/phonemes";
|
||||
|
||||
// src/translate/contractions.ts
|
||||
import { lookupPronunciation } from "@ingglish/dictionary";
|
||||
import { detectCasePattern, applyCasePattern } from "@ingglish/normalize";
|
||||
import { arpabetToFormat, getFormatPreservesCase } from "@ingglish/phonemes";
|
||||
function translateContraction(token, format, translateWord2) {
|
||||
const phonemes = lookupPronunciation(token);
|
||||
if (phonemes) {
|
||||
const translated = arpabetToFormat(phonemes, format);
|
||||
if (getFormatPreservesCase(format)) {
|
||||
if (token.toLowerCase().startsWith("i'")) {
|
||||
return translated.toLowerCase();
|
||||
}
|
||||
const casePattern = detectCasePattern(token);
|
||||
return applyCasePattern(translated, casePattern, token);
|
||||
}
|
||||
return translated;
|
||||
}
|
||||
const parts = token.split("'");
|
||||
return parts.map((p, i) => {
|
||||
if (!p) {
|
||||
return "";
|
||||
}
|
||||
if (i > 0 && p.toLowerCase() === "t") {
|
||||
return "t";
|
||||
}
|
||||
return translateWord2(p, format);
|
||||
}).join("'");
|
||||
}
|
||||
|
||||
// src/translate/pipeline.ts
|
||||
import {
|
||||
extractPreservedPatterns,
|
||||
normalizeApostrophes,
|
||||
WORD_SPLIT_REGEX
|
||||
} from "@ingglish/normalize";
|
||||
import { getFormatPreservesCase as getFormatPreservesCase2 } from "@ingglish/phonemes";
|
||||
|
||||
// src/translate/preserved.ts
|
||||
function expandPlaceholder(token, preserved) {
|
||||
const matches = [];
|
||||
for (const [placeholder, original] of preserved) {
|
||||
const idx = token.indexOf(placeholder);
|
||||
if (idx !== -1) {
|
||||
matches.push({ index: idx, original, placeholder });
|
||||
}
|
||||
}
|
||||
if (matches.length === 0) {
|
||||
return null;
|
||||
}
|
||||
matches.sort((a, b) => a.index - b.index);
|
||||
const result = [];
|
||||
let pos = 0;
|
||||
for (const { index, original, placeholder } of matches) {
|
||||
if (index > pos) {
|
||||
const before = token.slice(pos, index);
|
||||
result.push({ isWord: false, matched: true, original: before, translated: before });
|
||||
}
|
||||
result.push({ isWord: false, matched: true, original, translated: original });
|
||||
pos = index + placeholder.length;
|
||||
}
|
||||
if (pos < token.length) {
|
||||
const after = token.slice(pos);
|
||||
result.push({ isWord: false, matched: true, original: after, translated: after });
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// src/translate/pipeline.ts
|
||||
var SENTENCE_END = /[.?!]/;
|
||||
var HAS_LETTER = /[a-z]/i;
|
||||
function extractTokens(text) {
|
||||
const normalized = normalizeApostrophes(text);
|
||||
const { preserved, text: textWithPlaceholders } = extractPreservedPatterns(normalized);
|
||||
const rawTokens = textWithPlaceholders.split(WORD_SPLIT_REGEX);
|
||||
return { preserved, rawTokens };
|
||||
}
|
||||
function mapTokens(rawTokens, preserved, translateWord2) {
|
||||
const result = [];
|
||||
const hasPreserved = preserved.size > 0;
|
||||
for (const [i, token] of rawTokens.entries()) {
|
||||
if (token.length === 0) {
|
||||
continue;
|
||||
}
|
||||
if (hasPreserved) {
|
||||
const expanded = expandPlaceholder(token, preserved);
|
||||
if (expanded) {
|
||||
result.push(...expanded);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (i % 2 === 1) {
|
||||
const { matched, translated } = translateWord2(token);
|
||||
result.push({ isWord: true, matched, original: token, translated });
|
||||
} else {
|
||||
result.push({ isWord: false, matched: true, original: token, translated: token });
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
var expandPlaceholderText = (token, preserved) => {
|
||||
let found = false;
|
||||
let result = token;
|
||||
for (const [placeholder, original] of preserved) {
|
||||
const idx = result.indexOf(placeholder);
|
||||
if (idx !== -1) {
|
||||
result = result.slice(0, idx) + original + result.slice(idx + placeholder.length);
|
||||
found = true;
|
||||
}
|
||||
}
|
||||
return found ? result : null;
|
||||
};
|
||||
function renderText(rawTokens, preserved, translateWord2, format) {
|
||||
const preservesCase = getFormatPreservesCase2(format);
|
||||
const hasPreserved = preserved.size > 0;
|
||||
let result = "";
|
||||
let wordCount = 0;
|
||||
let sentenceStart = true;
|
||||
let firstWordStart = -1;
|
||||
for (const [i, token] of rawTokens.entries()) {
|
||||
if (token.length === 0) {
|
||||
continue;
|
||||
}
|
||||
if (hasPreserved) {
|
||||
const expanded = expandPlaceholderText(token, preserved);
|
||||
if (expanded !== null) {
|
||||
result += expanded;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (i % 2 === 1) {
|
||||
const translated = translateWord2(token);
|
||||
wordCount++;
|
||||
if (preservesCase && sentenceStart && translated.length > 0) {
|
||||
if (wordCount === 1) {
|
||||
firstWordStart = result.length;
|
||||
result += translated;
|
||||
} else {
|
||||
result += translated.charAt(0).toUpperCase() + translated.slice(1);
|
||||
}
|
||||
} else {
|
||||
result += translated;
|
||||
}
|
||||
sentenceStart = false;
|
||||
} else {
|
||||
if (preservesCase && SENTENCE_END.test(token) && !HAS_LETTER.test(token)) {
|
||||
sentenceStart = true;
|
||||
}
|
||||
result += token;
|
||||
}
|
||||
}
|
||||
if (preservesCase && wordCount > 1 && firstWordStart !== -1) {
|
||||
const firstChar = result.charAt(firstWordStart);
|
||||
const upper = firstChar.toUpperCase();
|
||||
if (upper !== firstChar) {
|
||||
result = result.slice(0, firstWordStart) + upper + result.slice(firstWordStart + 1);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// src/translate/forward.ts
|
||||
var ALL_UPPER = /^[A-Z]+$/;
|
||||
var TRIPLE_CHAR = /(.)\1\1/;
|
||||
var HAS_VOWEL = /[aeiouy]/i;
|
||||
var TITLE_CASE = /^[A-Z][a-z]*$/;
|
||||
function translateSync(text, options = {}) {
|
||||
const { format = "ingglish", lang } = options;
|
||||
if (isForeignLang(lang)) {
|
||||
const dict = getForeignDict(lang);
|
||||
if (!dict) {
|
||||
throw new Error(
|
||||
`Foreign dictionary for "${lang}" not loaded. Call translate(text, { lang: "${lang}" }) or loadForeignDict("${lang}") first.`
|
||||
);
|
||||
}
|
||||
return translateForeign(text, dict, format);
|
||||
}
|
||||
const { preserved, rawTokens } = extractTokens(text);
|
||||
return renderText(rawTokens, preserved, (w) => translateWordString(w, format), format);
|
||||
}
|
||||
function translateSyncWithMapping(text, options = {}) {
|
||||
const { format = "ingglish", lang } = options;
|
||||
if (isForeignLang(lang)) {
|
||||
const dict = getForeignDict(lang);
|
||||
if (!dict) {
|
||||
throw new Error(
|
||||
`Foreign dictionary for "${lang}" not loaded. Call translate(text, { lang: "${lang}" }) or loadForeignDict("${lang}") first.`
|
||||
);
|
||||
}
|
||||
return translateForeignWithMapping(text, dict, format);
|
||||
}
|
||||
const { preserved, rawTokens } = extractTokens(text);
|
||||
return mapTokens(rawTokens, preserved, (w) => translateWordInternal(w, format));
|
||||
}
|
||||
function translateWord(word, options = {}) {
|
||||
const { format = "ingglish", lang } = options;
|
||||
if (isForeignLang(lang)) {
|
||||
const dict = getForeignDict(lang);
|
||||
if (!dict) {
|
||||
throw new Error(
|
||||
`Foreign dictionary for "${lang}" not loaded. Call translate(text, { lang: "${lang}" }) or loadForeignDict("${lang}") first.`
|
||||
);
|
||||
}
|
||||
const ipa = lookupIpa(dict, word);
|
||||
return ipa ?? word;
|
||||
}
|
||||
return translateWordInternal(word, format).translated;
|
||||
}
|
||||
function isAllLowerAscii(word) {
|
||||
for (let i = 0; i < word.length; i++) {
|
||||
const c = word.codePointAt(i);
|
||||
if (c < 97 || c > 122) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
function isInitialismLower(key) {
|
||||
if (KNOWN_INITIALISMS.has(key)) {
|
||||
return true;
|
||||
}
|
||||
return key.length > 1 && key.endsWith("s") && KNOWN_INITIALISMS.has(key.slice(0, -1));
|
||||
}
|
||||
function isTitleCaseAscii(word) {
|
||||
if (word.length < 2) {
|
||||
return false;
|
||||
}
|
||||
const first = word.codePointAt(0);
|
||||
if (first < 65 || first > 90) {
|
||||
return false;
|
||||
}
|
||||
for (let i = 1; i < word.length; i++) {
|
||||
const c = word.codePointAt(i);
|
||||
if (c < 97 || c > 122) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
function translateWithFallback(word, format, casePattern) {
|
||||
if (TRIPLE_CHAR.test(word) || !HAS_VOWEL.test(word)) {
|
||||
return { matched: false, translated: word };
|
||||
}
|
||||
const stripped = stripDiacritics(word);
|
||||
const fallbackResult = translateUnknown(stripped, format);
|
||||
if (!fallbackResult || fallbackResult.length === 0) {
|
||||
return { matched: false, translated: word };
|
||||
}
|
||||
if (getFormatPreservesCase3(format)) {
|
||||
const hasInternalMixedCase = fallbackResult !== fallbackResult.toLowerCase() && fallbackResult !== fallbackResult.toUpperCase() && !TITLE_CASE.test(fallbackResult);
|
||||
if (hasInternalMixedCase) {
|
||||
return { matched: false, translated: fallbackResult };
|
||||
}
|
||||
return { matched: false, translated: applyCasePattern2(fallbackResult, casePattern, word) };
|
||||
}
|
||||
return { matched: false, translated: fallbackResult };
|
||||
}
|
||||
function translateWordInternal(word, format) {
|
||||
if (!word || !HAS_LETTER.test(word)) {
|
||||
return { matched: true, translated: word };
|
||||
}
|
||||
const fast = tryFastPath(word, format) ?? tryTitleCaseFastPath(word, format);
|
||||
if (fast !== null) {
|
||||
return { matched: true, translated: fast };
|
||||
}
|
||||
const isLatinScript = getFormatIsLatinScript(format);
|
||||
const initialismSuffix = tryInitialismWithSuffix(word, format, isLatinScript);
|
||||
if (initialismSuffix) {
|
||||
return initialismSuffix;
|
||||
}
|
||||
if (word.includes("'")) {
|
||||
return {
|
||||
matched: true,
|
||||
translated: translateContraction(word, format, (w, f) => translateWord(w, { format: f }))
|
||||
};
|
||||
}
|
||||
const initialism = tryInitialism(word, format, isLatinScript);
|
||||
if (initialism) {
|
||||
return initialism;
|
||||
}
|
||||
if (isLatinScript && word.length >= 2 && ALL_UPPER.test(word)) {
|
||||
return { matched: true, translated: word };
|
||||
}
|
||||
const camel = tryCamelCase(word, format);
|
||||
if (camel) {
|
||||
return camel;
|
||||
}
|
||||
const casePattern = detectCasePattern2(word);
|
||||
const dictResult = tryDictionaryLookup(word, format, casePattern);
|
||||
if (dictResult) {
|
||||
return dictResult;
|
||||
}
|
||||
return translateWithFallback(word, format, casePattern);
|
||||
}
|
||||
function translateWordString(word, format) {
|
||||
if (!word || !HAS_LETTER.test(word)) {
|
||||
return word;
|
||||
}
|
||||
return tryFastPath(word, format) ?? tryTitleCaseFastPath(word, format) ?? translateWordInternal(word, format).translated;
|
||||
}
|
||||
function tryCamelCase(word, format) {
|
||||
const parts = splitCamelCase(word);
|
||||
if (parts === null || parts.length <= 1) {
|
||||
return null;
|
||||
}
|
||||
let allMatched = true;
|
||||
const translatedParts = parts.map((part) => {
|
||||
if (part.length >= 2 && ALL_UPPER.test(part)) {
|
||||
return part;
|
||||
}
|
||||
const partCase = detectCasePattern2(part);
|
||||
const phonemes = lookupPronunciation2(part);
|
||||
let translated;
|
||||
if (phonemes) {
|
||||
translated = arpabetToFormat2(phonemes, format);
|
||||
} else {
|
||||
allMatched = false;
|
||||
translated = translateUnknown(part, format);
|
||||
}
|
||||
return getFormatPreservesCase3(format) ? applyCasePattern2(translated, partCase, part) : translated;
|
||||
});
|
||||
return { matched: allMatched, translated: translatedParts.join("") };
|
||||
}
|
||||
function tryDictionaryLookup(word, format, casePattern) {
|
||||
const wordLower = word.toLowerCase();
|
||||
const phonemes = lookupPronunciationLower(wordLower);
|
||||
if (phonemes) {
|
||||
let result = arpabetToFormat2(phonemes, format);
|
||||
if (getFormatPreservesCase3(format)) {
|
||||
result = applyCasePattern2(result, casePattern, word);
|
||||
}
|
||||
return { matched: true, translated: result };
|
||||
}
|
||||
const stripped = stripDiacritics(word);
|
||||
if (stripped !== word) {
|
||||
const strippedLower = stripped.toLowerCase();
|
||||
const strippedPhonemes = lookupPronunciationLower(strippedLower);
|
||||
if (strippedPhonemes) {
|
||||
let result = arpabetToFormat2(strippedPhonemes, format);
|
||||
if (getFormatPreservesCase3(format)) {
|
||||
result = applyCasePattern2(result, casePattern, word);
|
||||
}
|
||||
return { matched: true, translated: result };
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
function tryFastPath(word, format) {
|
||||
if (!isAllLowerAscii(word)) {
|
||||
return null;
|
||||
}
|
||||
if (isInitialismLower(word)) {
|
||||
return null;
|
||||
}
|
||||
const phonemes = lookupPronunciationLower(word);
|
||||
return phonemes ? arpabetToFormat2(phonemes, format) : null;
|
||||
}
|
||||
function tryInitialism(word, format, isLatinScript) {
|
||||
if (!isInitialism(word)) {
|
||||
return null;
|
||||
}
|
||||
if (isLatinScript) {
|
||||
return { matched: true, translated: word };
|
||||
}
|
||||
if (word === word.toUpperCase()) {
|
||||
return { matched: true, translated: translateAsAcronym(word, format) };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
function tryInitialismWithSuffix(word, format, isLatinScript) {
|
||||
const parsed = parseInitialismWithSuffix(word);
|
||||
if (parsed === null) {
|
||||
return null;
|
||||
}
|
||||
if (isLatinScript || parsed.base === parsed.base.toUpperCase()) {
|
||||
const baseTranslated = translateWord(parsed.base, { format });
|
||||
return { matched: true, translated: baseTranslated + parsed.suffix };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
function tryTitleCaseFastPath(word, format) {
|
||||
if (!isTitleCaseAscii(word)) {
|
||||
return null;
|
||||
}
|
||||
const lower = word.toLowerCase();
|
||||
if (isInitialismLower(lower)) {
|
||||
return null;
|
||||
}
|
||||
const phonemes = lookupPronunciationLower(lower);
|
||||
if (!phonemes) {
|
||||
return null;
|
||||
}
|
||||
let translated = arpabetToFormat2(phonemes, format);
|
||||
if (getFormatPreservesCase3(format) && translated.length > 0) {
|
||||
translated = translated.charAt(0).toUpperCase() + translated.slice(1);
|
||||
}
|
||||
return translated;
|
||||
}
|
||||
|
||||
// src/translate/reverse.ts
|
||||
import { lookupPhonemeKey, sortByFrequency, getWordFrequency } from "@ingglish/dictionary";
|
||||
import { ipaToArpabetClean } from "@ingglish/ipa";
|
||||
import { applyCasePattern as applyCasePattern3, detectCasePattern as detectCasePattern3, tokenizeIPA } from "@ingglish/normalize";
|
||||
import {
|
||||
expandArpabetAlternatives,
|
||||
getFormatHandler,
|
||||
ingglishToArpabet,
|
||||
registerFormat
|
||||
} from "@ingglish/phonemes";
|
||||
var ALT_FREQUENCY_THRESHOLD = 5;
|
||||
function reverseTranslateIPAWord(ipaWord) {
|
||||
if (!ipaWord || ipaWord.trim().length === 0) {
|
||||
return ipaWord ? [ipaWord] : [];
|
||||
}
|
||||
const arpabet = ipaToArpabetClean(ipaWord);
|
||||
if (!arpabet) {
|
||||
return [ipaWord];
|
||||
}
|
||||
const matches = lookupByArpabet(arpabet);
|
||||
if (matches.length === 0) {
|
||||
return [ipaWord];
|
||||
}
|
||||
return matches;
|
||||
}
|
||||
function reverseTranslateWord(ingglishWord) {
|
||||
if (!ingglishWord || !HAS_LETTER.test(ingglishWord)) {
|
||||
return ingglishWord ? [ingglishWord] : [];
|
||||
}
|
||||
const casePattern = detectCasePattern3(ingglishWord);
|
||||
const arpabet = ingglishToArpabet(ingglishWord);
|
||||
if (!arpabet) {
|
||||
return [];
|
||||
}
|
||||
const matches = lookupByArpabet(arpabet);
|
||||
if (matches.length === 0) {
|
||||
return [];
|
||||
}
|
||||
return matches.map((word) => applyCasePattern3(word, casePattern));
|
||||
}
|
||||
function lookupByArpabet(arpabet) {
|
||||
const [primary, ...alternatives] = expandArpabetAlternatives(arpabet);
|
||||
if (!primary) {
|
||||
return [];
|
||||
}
|
||||
const primaryKey = primary.join(" ");
|
||||
const primaryMatches = lookupPhonemeKey(primaryKey);
|
||||
if (!primaryMatches || primaryMatches.length === 0) {
|
||||
const allMatches = [];
|
||||
const seen = /* @__PURE__ */ new Set();
|
||||
for (const variant of alternatives) {
|
||||
const key = variant.join(" ");
|
||||
const matches = lookupPhonemeKey(key);
|
||||
if (matches) {
|
||||
for (const match of matches) {
|
||||
if (!seen.has(match)) {
|
||||
seen.add(match);
|
||||
allMatches.push(match);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return allMatches.length > 1 ? sortByFrequency(allMatches) : allMatches;
|
||||
}
|
||||
const primaryBestFreq = getWordFrequency(primaryMatches[0] ?? "") ?? 0;
|
||||
for (const variant of alternatives) {
|
||||
const key = variant.join(" ");
|
||||
const matches = lookupPhonemeKey(key);
|
||||
if (matches && matches.length > 0) {
|
||||
const altBestFreq = getWordFrequency(matches[0] ?? "") ?? 0;
|
||||
if (altBestFreq > primaryBestFreq * ALT_FREQUENCY_THRESHOLD) {
|
||||
const allMatches = [...primaryMatches];
|
||||
const seen = new Set(primaryMatches);
|
||||
for (const match of matches) {
|
||||
if (!seen.has(match)) {
|
||||
seen.add(match);
|
||||
allMatches.push(match);
|
||||
}
|
||||
}
|
||||
return sortByFrequency(allMatches);
|
||||
}
|
||||
}
|
||||
}
|
||||
return primaryMatches;
|
||||
}
|
||||
registerFormat("ingglish", {
|
||||
reverseText: reverseTranslateIngglishText,
|
||||
reverseTextWithMapping: reverseTranslateIngglishTextWithMapping
|
||||
});
|
||||
registerFormat("ipa", {
|
||||
reverseText: reverseTranslateIPATextInternal,
|
||||
reverseTextWithMapping: reverseTranslateIPATextWithMapping
|
||||
});
|
||||
function reverseTranslateSync(text, options = {}) {
|
||||
const { format = "ingglish" } = options;
|
||||
const handler = getFormatHandler(format);
|
||||
if (handler?.reverseText) {
|
||||
return handler.reverseText(text);
|
||||
}
|
||||
return reverseTranslateIngglishText(text);
|
||||
}
|
||||
function reverseTranslateSyncWithMapping(text, options = {}) {
|
||||
const { format = "ingglish" } = options;
|
||||
const handler = getFormatHandler(format);
|
||||
if (handler?.reverseTextWithMapping) {
|
||||
return handler.reverseTextWithMapping(text);
|
||||
}
|
||||
return reverseTranslateIngglishTextWithMapping(text);
|
||||
}
|
||||
function reverseTranslateIngglishText(text) {
|
||||
return reverseTranslateIngglishTextWithMapping(text).map((t) => t.translated).join("");
|
||||
}
|
||||
function reverseTranslateIngglishTextWithMapping(text) {
|
||||
const { preserved, rawTokens } = extractTokens(text);
|
||||
return mapTokens(rawTokens, preserved, reverseTranslateWordAsResult);
|
||||
}
|
||||
function reverseTranslateIPATextInternal(text) {
|
||||
const cleanText = text.replaceAll(/^[/[\]]+|[/[\]]+$/g, "");
|
||||
const tokens = tokenizeIPA(cleanText);
|
||||
return tokens.map((token) => {
|
||||
if (token.isWord) {
|
||||
const matches = reverseTranslateIPAWord(token.text);
|
||||
return matches[0] ?? token.text;
|
||||
}
|
||||
return token.text;
|
||||
}).join("");
|
||||
}
|
||||
function reverseTranslateIPATextWithMapping(text) {
|
||||
const cleanText = text.replaceAll(/^[/[\]]+|[/[\]]+$/g, "");
|
||||
const tokens = tokenizeIPA(cleanText);
|
||||
return tokens.map((token) => {
|
||||
if (token.isWord) {
|
||||
const matches = reverseTranslateIPAWord(token.text);
|
||||
const translated = matches[0] ?? token.text;
|
||||
return {
|
||||
isWord: true,
|
||||
matched: translated !== token.text,
|
||||
original: token.text,
|
||||
translated
|
||||
};
|
||||
}
|
||||
return { isWord: false, matched: true, original: token.text, translated: token.text };
|
||||
});
|
||||
}
|
||||
function reverseTranslateWordAsResult(word) {
|
||||
if (!HAS_LETTER.test(word)) {
|
||||
return { matched: true, translated: word };
|
||||
}
|
||||
if (word.includes("'")) {
|
||||
const parts = word.split("'");
|
||||
let allMatched = true;
|
||||
const translatedParts = parts.map((p) => {
|
||||
if (!p) {
|
||||
return "";
|
||||
}
|
||||
const matches2 = reverseTranslateWord(p);
|
||||
if (matches2[0]) {
|
||||
return matches2[0];
|
||||
}
|
||||
allMatched = false;
|
||||
return p;
|
||||
});
|
||||
return { matched: allMatched, translated: translatedParts.join("'") };
|
||||
}
|
||||
const matches = reverseTranslateWord(word);
|
||||
if (matches[0]) {
|
||||
return { matched: true, translated: matches[0] };
|
||||
}
|
||||
return { matched: false, translated: word };
|
||||
}
|
||||
|
||||
// src/index.ts
|
||||
import { LANGUAGES } from "@ingglish/ipa";
|
||||
async function reverseTranslate(text, options = {}) {
|
||||
const { format = "ingglish" } = options;
|
||||
await Promise.all([loadReverseDictionary(), loadFrequencies()]);
|
||||
return reverseTranslateSync(text, { format });
|
||||
}
|
||||
async function translate(text, options = {}) {
|
||||
const { format = "ingglish", lang } = options;
|
||||
if (isForeignLang(lang)) {
|
||||
const dict = await loadForeignDict(lang);
|
||||
return translateForeign2(text, dict, format);
|
||||
}
|
||||
await Promise.all([loadDictionary(), loadFrequencies()]);
|
||||
return translateSync(text, { format });
|
||||
}
|
||||
export {
|
||||
LANGUAGES,
|
||||
reverseTranslate,
|
||||
reverseTranslateSync,
|
||||
reverseTranslateSyncWithMapping,
|
||||
setForeignDictLoader,
|
||||
translate,
|
||||
translateSync,
|
||||
translateSyncWithMapping
|
||||
};
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
{
|
||||
"name": "ingglish",
|
||||
"version": "0.1.1",
|
||||
"description": "Core phonetic English translation library",
|
||||
"type": "module",
|
||||
"main": "dist/index.js",
|
||||
"module": "dist/index.js",
|
||||
"types": "dist/index.d.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"source": "./src/index.ts",
|
||||
"import": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"default": "./dist/index.js"
|
||||
},
|
||||
"require": {
|
||||
"types": "./dist/index.d.cts",
|
||||
"default": "./dist/index.cjs"
|
||||
}
|
||||
}
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"sideEffects": false,
|
||||
"engines": {
|
||||
"node": ">=16"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsup",
|
||||
"build:fast": "tsup src/index.ts --format esm",
|
||||
"lint": "eslint --cache src",
|
||||
"test": "vitest run --no-color",
|
||||
"bench": "vitest bench --no-color",
|
||||
"test:watch": "vitest",
|
||||
"translate": "npx vite-node scripts/cli/translate.ts",
|
||||
"debug:roundtrip": "npx vite-node scripts/cli/debug-roundtrip.ts",
|
||||
"analyze-collisions": "npx vite-node scripts/cli/collision-analysis.ts",
|
||||
"prepublishOnly": "npm run build"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ingglish/normalize": "^0.1.0",
|
||||
"@ingglish/phonemes": "^0.1.0",
|
||||
"@ingglish/ipa": "^0.1.0",
|
||||
"@ingglish/dictionary": "^0.1.0",
|
||||
"@ingglish/fallback": "^0.1.0",
|
||||
"@ingglish/g2p": "^0.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^25.3.0",
|
||||
"jsdom": "^28.1.0",
|
||||
"vite": "^7.3.1"
|
||||
},
|
||||
"keywords": [
|
||||
"phonetic",
|
||||
"english",
|
||||
"pronunciation",
|
||||
"spelling",
|
||||
"ipa",
|
||||
"cmu",
|
||||
"dictionary"
|
||||
],
|
||||
"author": "Paul Tarjan",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/ptarjan/ingglish.git",
|
||||
"directory": "packages/core"
|
||||
},
|
||||
"homepage": "https://github.com/ptarjan/ingglish#readme",
|
||||
"bugs": {
|
||||
"url": "https://github.com/ptarjan/ingglish/issues"
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user