Files
ingglish-hyperdope-gematria/node_modules/ingglish/dist/index.js
T

649 lines
20 KiB
JavaScript

// 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
};