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

657 lines
22 KiB
JavaScript

"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
});