Baseline: main branch state prior to Top-10 films expansion

This commit is contained in:
Hermes Agent committed 2026-11-02 12:34:51 +00:00
commit 6b15603e56
139 files changed
+329420

No files matched your search

+6
View File
@@ -0,0 +1,6 @@
// src/cmudict.js
var cmudict = JSON.parse(`{"'bout":["B","AW1","T"],"'cause":["K","AH0","Z"],"'course":["K","AO1","R","S"],"'cuse":["K","Y","UW1","Z"],"'em":["AH0","M"],"'frisco":["F","R","IH1","S","K","OW0"],"'gain":["G","EH1","N"],"'kay":["K","EY1"],"'m":["AH0","M"],"'n":["AH0","N"],"'round":["R","AW1","N","D"],"'s":["EH1","S"],"'til":["T","IH1","L"],"'tis":["T","IH1","Z"],"'twas":["T","W","AH1","Z"],"a":["AH0"],"a's":["EY1","Z"],"a.":["EY1"],"a.'s":["EY1","Z"],"a.d.":["EY2","D","IY1"],"a.m.":["EY2","EH1","M"],"a.s":["EY1","Z"],"aaa":["T","R","IH2","P","AH0","L","EY1"],"aaberg":["AA1","B","ER0","G"],"aachen":["AA1","K","AH0","N"],"aachener":["AA1","K","AH0","N","ER0"],"aaker":["AA1","K","ER0"],"aalborg":["AO1","L","B","AO0","R","G","#","place,","danish"],"aalburg":["AE1","L","B","ER0","G","#","place,","dutch"],"aalen":["AE1","L","AH0","N","#","place,","german"],"aaliyah":["AA2","L","IY1","AA2"],"aalseth":["AA1","L","S","EH0","TH"],"aalsmeer":["AA1","L","S","M","IH0","R","#","place,","dutch"],"aalto":["AA1","L","T","OW2","#","name,","finnish"],"aamodt":["AA1","M","AH0","T"],"aancor":["AA1","NG","K","AO2","R"],"aardema":["AA0","R","D","EH1","M","AH0"],"aardvark":["AA1","R","D","V","AA2","R","K"],"aardvarks":["AA1","R","D","V","AA2","R","K","S"],"aargh":["AA1","R","G"],"aarhus":["AA2","HH","UW1","S"],"aaron":["EH1","R","AH0","N"],"aaron's":["EH1","R","AH0","N","Z"],"aarons":["EH1","R","AH0","N","Z"],"aaronson":["EH1","R","AH0","N","S","AH0","N"],"aaronson's":["EH1","R","AH0","N","S","AH0","N","Z"],"aarti":["AA1","R","T","IY2"],"aase":["AA1","S"],"aasen":["AA1","S","AH0","N"],"ab":["AE1","B"],"aba":["EY2","B","IY2","EY1"],"ababa":["AH0","B","AA1","B","AH0"],"abacha":["AE1","B","AH0","K","AH0"],"aback":["AH0","B","AE1","K"],"abaco":["AE1","B","AH0","K","OW2"],"abacus":["AE1","B","AH0","K","AH0","S"],"abad":["AH0","B","AA1","D"],"abadaka":["AH0","B","AE1","D","AH0","K","AH0"],"abadi":["AH0","B","AE1","D","IY0"],"abadie":["AH0","B","AE1","D","IY0"],"abair":["AH0","B","EH1","R"],"abalkin":["AH0","B","AA1","L","K","IH0","N"],"abalone":["AE2","B","AH0","L","OW1","N","IY0"],"abalones":["AE2","B","AH0","L","OW1","N","IY0","Z"],"abalos":["AA0","B","AA1","L","OW0","Z"],"abandon":["AH0","B","AE1","N","D","AH0","N"],"abandoned":["AH0","B","AE1","N","D","AH0","N","D"],"abandoning":["AH0","B","AE1","N","D","AH0","N","IH0","NG"],"abandonment":["AH0","B","AE1","N","D","AH0","N","M","AH0","N","T"],"abandonments":["AH0","B","AE1","N","D","AH0","N","M","AH0","N","T","S"],"abandons":["AH0","B","AE1","N","D","AH0","N","Z"],"abanto":["AH0","B","AE1","N","T","OW0"],"abarca":["AH0","B","AA1","R","K","AH0"],"abare":["AA0","B","AA1","R","IY0"],"abascal":["AE1","B","AH0","S","K","AH0","L"],"abash":["AH0","B","AE1","SH"],"abashed":["AH0","B","AE1","SH","T"],"abasia":["AH0","B","EY1","ZH","Y","AH0"],"abate":["AH0","B","EY1","T"],"abated":["AH0","B","EY1","T","IH0","D"],"abatement":["AH0","B","EY1","T","M","AH0","N","T"],"abatements":["AH0","B","EY1","T","M","AH0","N","T","S"],"abates":["AH0","B","EY1","T","S"],"abating":["AH0","B","EY1","T","IH0","NG"],"abattoir":["AE2","B","AH0","T","W","AA1","R"],"abba":["AE1","B","AH0"],"abbado":["AH0","B","AA1","D","OW0"],"abbas":["AH0","B","AA1","S"],"abbasi":["AA0","B","AA1","S","IY0"],"abbate":["AA1","B","EY0","T"],"abbatiello":["AA0","B","AA0","T","IY0","EH1","L","OW0"],"abbe":["AE1","B","IY0"],"abbenhaus":["AE1","B","AH0","N","HH","AW2","S"],"abbett":["AH0","B","EH1","T"],"abbeville":["AE1","B","V","IH0","L"],"abbey":["AE1","B","IY0"],"abbey's":["AE1","B","IY0","Z"],"abbie":["AE1","B","IY0"],"abbitt":["AE1","B","IH0","T"],"abbot":["AE1","B","AH0","T"],"abbotstown":["AE1","B","AH0","T","S","T","AW1","N"],"abbott":["AE1","B","AH0","T"],"abbott's":["AE1","B","AH0","T","S"],"abbottstown":["AE1","B","AH0","T","S","T","AW1","N"],"abboud":["AH0","B","UW1","D"],"abbreviate":["AH0","B","R","IY1","V","IY0","EY2","T"],"abbreviated":["AH0","B","R","IY1","V","IY0","EY2","T","IH0","D"],"abbreviates":["AH0","B","R","IY1","V","IY0","EY2","T","S"],"abbreviating":["AH0","B","R","IY1","V","IY0","EY2","T","IH0","NG"],"abbreviation":["AH0","B","R","IY2","V","IY0","EY1","SH","AH0","N"],"abbreviations":["AH0","B","R","IY2","V","IY0","EY1","SH","AH0","N","Z"],"abbruzzese":["AA0","B","R","UW0","T","S","EY1","Z","IY0"],"abbs":["AE1","B","Z"],"abby":["AE1","B","IY0"],"abc":["EY1","B","IY2","S","IY2"],"abc's":["EY1","B","IY2","S","IY2","Z"],"abco":["AE1","B","K","OW0"],"abcotek":["AE1","B","K","OW0","T","EH2","K"],"abcs":["EY1","B","IY2","S","IY2","Z"],"abd":["EY2","B","IY2","D","IY1"],"abdalla":["AE2","B","D","AE1","L","AH0"],"abdallah":["AE2","B","D","AE1","L","AH0"],"abdel":["AE1","B","D","EH2","L"],"abdella":["AE2","B","D","EH1","L","AH0"],"abdicate":["AE1","B","D","AH0","K","EY2","T"],"abdicated":["AE1","B","D","AH0","K","EY2","T","IH0","D"],"abdicates":["AE1","B","D","AH0","K","EY2","T","S"],"abdicating":["AE1","B","D","IH0","K","EY2","T","IH0","NG"],"abdication":["AE2","B","D","IH0","K","EY1","SH","AH0","N"],"abdnor":["AE1","B","D" Line truncated
var cmudict_default = cmudict;
export {
cmudict_default as default
};
+707
View File
@@ -0,0 +1,707 @@
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __esm = (fn, res) => function __init() {
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
};
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 __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/data/word-frequencies.js
var word_frequencies_exports = {};
__export(word_frequencies_exports, {
default: () => word_frequencies_default
});
var WORD_FREQUENCIES, word_frequencies_default;
var init_word_frequencies = __esm({
"src/data/word-frequencies.js"() {
"use strict";
WORD_FREQUENCIES = JSON.parse(`{"you":2134713,"I":2038529,"the":1501908,"to":1156570,"s":1057301,"a":1041179,"it":963712,"t":733338,"that":719677,"and":682780,"of":590439,"What":501965,"in":498444,"me":471339,"is":459663,"we":459607,"this":406915,"he":389497,"on":354742,"for":351650,"my":344899,"m":343245,"your":328715,"don":321085,"have":314232,"do":312915,"re":311072,"No":304549,"be":293085,"know":291780,"was":288391,"not":276673,"can":267620,"are":265672,"all":263255,"with":257465,"just":242206,"get":233772,"here":230788,"but":225291,"ll":224097,"there":221754,"so":216452,"they":209250,"right":204428,"like":203947,"out":197131,"go":193445,"she":190377,"up":187170,"about":185206,"if":180610,"him":177710,"got":168631,"Oh":167781,"at":164072,"now":163333,"Come":160190,"one":156684,"How":155867,"Well":152523,"Yeah":152262,"her":144627,"want":140718,"think":137261,"good":133117,"see":130393,"Let":123381,"did":119410,"Why":114687,"who":113370,"as":113068,"his":108364,"will":108306,"going":108288,"from":103992,"when":103739,"back":102467,"Okay":102320,"Yes":101835,"gonna":101804,"d":101335,"time":99890,"look":99311,"take":96443,"an":95071,"man":94133,"Where":93341,"them":90720,"would":90162,"been":88573,"some":88089,"Hey":88079,"tell":87949,"or":86970,"us":86478,"had":85472,"were":84804,"say":83629,"could":83109,"didn":80623,"something":76508,"really":76508,"down":76004,"then":75966,"little":73766,"way":72661,"our":71425,"make":70775,"too":69950,"never":69490,"by":68364,"over":67488,"more":66228,"need":66040,"mean":63443,"very":63304,"off":60155,"Mr":60098,"sorry":59566,"give":59559,"has":57830,"Thank":56877,"love":56864,"said":56531,"am":56438,"people":56252,"please":56149,"sure":56091,"any":56068,"thing":55522,"only":55269,"because":54622,"two":54384,"should":54159,"doing":52492,"much":49636,"sir":49188,"Maybe":47249,"help":46977,"anything":46270,"these":46104,"God":46061,"even":44672,"night":44168,"call":43931,"talk":43605,"nothing":43534,"into":43074,"first":42869,"find":42379,"wait":42343,"put":42251,"great":41864,"thought":41232,"day":40893,"work":40699,"life":40629,"before":40501,"better":40494,"again":40428,"still":40225,"home":39491,"guy":38893,"won":38729,"those":38404,"than":37679,"around":37573,"other":37505,"away":37276,"new":36913,"last":36878,"uh":36579,"ever":36170,"stop":36071,"keep":35846,"told":35679,"must":35661,"things":35337,"big":34824,"after":34812,"long":34433,"does":34002,"always":33418,"their":33413,"everything":33399,"nice":33125,"name":32735,"money":32679,"doesn":32435,"guys":32198,"feel":31989,"believe":31882,"Thanks":31789,"old":31056,"place":30736,"fine":30502,"kind":30125,"isn":29886,"Hello":29857,"lot":29066,"years":29003,"made":28626,"leave":28596,"Hi":28464,"girl":28413,"hear":28323,"father":28279,"through":28026,"every":28007,"bad":27804,"Listen":27784,"remember":27666,"three":27654,"boy":27021,"coming":26878,"wrong":26678,"might":26334,"stay":26298,"house":26214,"may":26080,"baby":25978,"another":25970,"Ok":25928,"Dad":25870,"gotta":25852,"wanna":25796,"wanted":25616,"enough":25568,"talking":25385,"happened":24994,"show":24906,"course":24848,"being":24781,"care":24748,"done":24737,"getting":24719,"mind":24715,"left":24707,"ask":24640,"car":24636,"understand":24605,"mother":24476,"which":24339,"try":24314,"shit":24207,"hell":24012,"Miss":23850,"came":23650,"wouldn":23628,"own":23419,"world":23216,"guess":23153,"next":23090,"kill":23081,"else":22907,"dead":22898,"trying":22849,"someone":22752,"real":22583,"room":22415,"morning":22389,"huh":22350,"hold":22273,"ain":22248,"woman":22166,"yourself":22151,"today":22124,"looking":22066,"wasn":21984,"Mom":21950,"friend":21384,"move":21325,"same":21276,"job":21063,"tonight":21047,"went":20987,"son":20949,"best":20623,"saw":20527,"found":20196,"pretty":20003,"ready":19778,"heard":19775,"whole":19660,"seen":19633,"together":19553,"fuck":19307,"minute":19252,"men":19011,"head":18947,"matter":18900,"haven":18844,"knew":18817,"Excuse":18773,"many":18331,"idea":18311,"without":18087,"play":18081,"family":18067,"meet":17966,"most":17889,"run":17878,"while":17821,"wife":17795,"once":17589,"live":17574,"somebody":17571,"everybody":17555,"used":17551,"use":17536,"myself":17470,"took":17454,"yet":17428,"start":17345,"called":17341,"couldn":17336,"kid":17299,"tomorrow":17134,"happy":16993,"school":16989,"problem":16833,"watch":16831,"bring":16685,"fucking":16603,"actually":16439,"business":16371,"says":16356,"hope":16352,"open":16341,"already":16246,"since":16064,"looks":15886,"sit":15879,"Mrs":15858,"cause":15812,"alone":15735,"hard":15700,"wants":15655,"stuff":15653,"turn":15630,"days":15592,"friends":15578,"until":15426,"few":15393,"kids":15356,"honey":15325,"Dr":15194,"gone":15135,"both":15062,"door":14895,"later":14889,"saying":14874,"such":14852,"killed":14792,"having":14752,"face":14747,"worry":14638,"ago":14592,"five":14558,"second":14513,"brother":14481,"damn":14460,"case":14403,"thinking":14353,"probably":14323,"beautiful":14266," Line truncated
word_frequencies_default = WORD_FREQUENCIES;
}
});
// src/cmudict.js
var cmudict_exports = {};
__export(cmudict_exports, {
default: () => cmudict_default
});
var cmudict, cmudict_default;
var init_cmudict = __esm({
"src/cmudict.js"() {
"use strict";
cmudict = JSON.parse(`{"'bout":["B","AW1","T"],"'cause":["K","AH0","Z"],"'course":["K","AO1","R","S"],"'cuse":["K","Y","UW1","Z"],"'em":["AH0","M"],"'frisco":["F","R","IH1","S","K","OW0"],"'gain":["G","EH1","N"],"'kay":["K","EY1"],"'m":["AH0","M"],"'n":["AH0","N"],"'round":["R","AW1","N","D"],"'s":["EH1","S"],"'til":["T","IH1","L"],"'tis":["T","IH1","Z"],"'twas":["T","W","AH1","Z"],"a":["AH0"],"a's":["EY1","Z"],"a.":["EY1"],"a.'s":["EY1","Z"],"a.d.":["EY2","D","IY1"],"a.m.":["EY2","EH1","M"],"a.s":["EY1","Z"],"aaa":["T","R","IH2","P","AH0","L","EY1"],"aaberg":["AA1","B","ER0","G"],"aachen":["AA1","K","AH0","N"],"aachener":["AA1","K","AH0","N","ER0"],"aaker":["AA1","K","ER0"],"aalborg":["AO1","L","B","AO0","R","G","#","place,","danish"],"aalburg":["AE1","L","B","ER0","G","#","place,","dutch"],"aalen":["AE1","L","AH0","N","#","place,","german"],"aaliyah":["AA2","L","IY1","AA2"],"aalseth":["AA1","L","S","EH0","TH"],"aalsmeer":["AA1","L","S","M","IH0","R","#","place,","dutch"],"aalto":["AA1","L","T","OW2","#","name,","finnish"],"aamodt":["AA1","M","AH0","T"],"aancor":["AA1","NG","K","AO2","R"],"aardema":["AA0","R","D","EH1","M","AH0"],"aardvark":["AA1","R","D","V","AA2","R","K"],"aardvarks":["AA1","R","D","V","AA2","R","K","S"],"aargh":["AA1","R","G"],"aarhus":["AA2","HH","UW1","S"],"aaron":["EH1","R","AH0","N"],"aaron's":["EH1","R","AH0","N","Z"],"aarons":["EH1","R","AH0","N","Z"],"aaronson":["EH1","R","AH0","N","S","AH0","N"],"aaronson's":["EH1","R","AH0","N","S","AH0","N","Z"],"aarti":["AA1","R","T","IY2"],"aase":["AA1","S"],"aasen":["AA1","S","AH0","N"],"ab":["AE1","B"],"aba":["EY2","B","IY2","EY1"],"ababa":["AH0","B","AA1","B","AH0"],"abacha":["AE1","B","AH0","K","AH0"],"aback":["AH0","B","AE1","K"],"abaco":["AE1","B","AH0","K","OW2"],"abacus":["AE1","B","AH0","K","AH0","S"],"abad":["AH0","B","AA1","D"],"abadaka":["AH0","B","AE1","D","AH0","K","AH0"],"abadi":["AH0","B","AE1","D","IY0"],"abadie":["AH0","B","AE1","D","IY0"],"abair":["AH0","B","EH1","R"],"abalkin":["AH0","B","AA1","L","K","IH0","N"],"abalone":["AE2","B","AH0","L","OW1","N","IY0"],"abalones":["AE2","B","AH0","L","OW1","N","IY0","Z"],"abalos":["AA0","B","AA1","L","OW0","Z"],"abandon":["AH0","B","AE1","N","D","AH0","N"],"abandoned":["AH0","B","AE1","N","D","AH0","N","D"],"abandoning":["AH0","B","AE1","N","D","AH0","N","IH0","NG"],"abandonment":["AH0","B","AE1","N","D","AH0","N","M","AH0","N","T"],"abandonments":["AH0","B","AE1","N","D","AH0","N","M","AH0","N","T","S"],"abandons":["AH0","B","AE1","N","D","AH0","N","Z"],"abanto":["AH0","B","AE1","N","T","OW0"],"abarca":["AH0","B","AA1","R","K","AH0"],"abare":["AA0","B","AA1","R","IY0"],"abascal":["AE1","B","AH0","S","K","AH0","L"],"abash":["AH0","B","AE1","SH"],"abashed":["AH0","B","AE1","SH","T"],"abasia":["AH0","B","EY1","ZH","Y","AH0"],"abate":["AH0","B","EY1","T"],"abated":["AH0","B","EY1","T","IH0","D"],"abatement":["AH0","B","EY1","T","M","AH0","N","T"],"abatements":["AH0","B","EY1","T","M","AH0","N","T","S"],"abates":["AH0","B","EY1","T","S"],"abating":["AH0","B","EY1","T","IH0","NG"],"abattoir":["AE2","B","AH0","T","W","AA1","R"],"abba":["AE1","B","AH0"],"abbado":["AH0","B","AA1","D","OW0"],"abbas":["AH0","B","AA1","S"],"abbasi":["AA0","B","AA1","S","IY0"],"abbate":["AA1","B","EY0","T"],"abbatiello":["AA0","B","AA0","T","IY0","EH1","L","OW0"],"abbe":["AE1","B","IY0"],"abbenhaus":["AE1","B","AH0","N","HH","AW2","S"],"abbett":["AH0","B","EH1","T"],"abbeville":["AE1","B","V","IH0","L"],"abbey":["AE1","B","IY0"],"abbey's":["AE1","B","IY0","Z"],"abbie":["AE1","B","IY0"],"abbitt":["AE1","B","IH0","T"],"abbot":["AE1","B","AH0","T"],"abbotstown":["AE1","B","AH0","T","S","T","AW1","N"],"abbott":["AE1","B","AH0","T"],"abbott's":["AE1","B","AH0","T","S"],"abbottstown":["AE1","B","AH0","T","S","T","AW1","N"],"abboud":["AH0","B","UW1","D"],"abbreviate":["AH0","B","R","IY1","V","IY0","EY2","T"],"abbreviated":["AH0","B","R","IY1","V","IY0","EY2","T","IH0","D"],"abbreviates":["AH0","B","R","IY1","V","IY0","EY2","T","S"],"abbreviating":["AH0","B","R","IY1","V","IY0","EY2","T","IH0","NG"],"abbreviation":["AH0","B","R","IY2","V","IY0","EY1","SH","AH0","N"],"abbreviations":["AH0","B","R","IY2","V","IY0","EY1","SH","AH0","N","Z"],"abbruzzese":["AA0","B","R","UW0","T","S","EY1","Z","IY0"],"abbs":["AE1","B","Z"],"abby":["AE1","B","IY0"],"abc":["EY1","B","IY2","S","IY2"],"abc's":["EY1","B","IY2","S","IY2","Z"],"abco":["AE1","B","K","OW0"],"abcotek":["AE1","B","K","OW0","T","EH2","K"],"abcs":["EY1","B","IY2","S","IY2","Z"],"abd":["EY2","B","IY2","D","IY1"],"abdalla":["AE2","B","D","AE1","L","AH0"],"abdallah":["AE2","B","D","AE1","L","AH0"],"abdel":["AE1","B","D","EH2","L"],"abdella":["AE2","B","D","EH1","L","AH0"],"abdicate":["AE1","B","D","AH0","K","EY2","T"],"abdicated":["AE1","B","D","AH0","K","EY2","T","IH0","D"],"abdicates":["AE1","B","D","AH0","K","EY2","T","S"],"abdicating":["AE1","B","D","IH0","K","EY2","T","IH0","NG"],"abdication":["AE2","B","D","IH0","K","EY1","SH","AH0","N"],"abdnor":["AE1","B","D" Line truncated
cmudict_default = cmudict;
}
});
// src/reverse-cmudict.js
var reverse_cmudict_exports = {};
__export(reverse_cmudict_exports, {
default: () => reverse_cmudict_default
});
var reverseCmudict, reverse_cmudict_default;
var init_reverse_cmudict = __esm({
"src/reverse-cmudict.js"() {
"use strict";
reverseCmudict = JSON.parse(`{"B AW T":["bout","'bout"],"K AH Z":["'cause"],"K AO R S":["course","coarse","corse","'course"],"K Y UW Z":["cues","ques","queues","q's","q.s","kuse","kuze","q.'s","'cuse"],"AH M":["um","umm","'m","'em"],"F R IH S K OW":["'frisco"],"G EH N":["'gain"],"K EY":["k","kay","cay","k.","khe","'kay","kaye","quaye"],"AH N":["un","'n"],"R AW N D":["round","'round"],"EH S":["s","es","esse","ess","'s","s."],"T IH L":["till","til","'til"],"T IH Z":["tis","'tis"],"T W AH Z":["twas","'twas"],"AH":["a","uh","uhh"],"EY Z":["a's","a.s","a.'s"],"EY":["ay","ae","a."],"EY D IY":["ady","a.d.","adey","eydie"],"EY EH M":["a.m."],"T R IH P AH L EY":["aaa"],"AA B ER G":["aaberg"],"AA K AH N":["aachen"],"AA K AH N ER":["aachener"],"AA K ER":["aaker","ocker"],"AO L B AO R G # place, danish":["aalborg"],"AE L B ER G # place, dutch":["aalburg"],"AE L AH N # place, german":["aalen"],"AA L IY AA":["aaliyah"],"AA L S EH TH":["aalseth"],"AA L S M IH R # place, dutch":["aalsmeer"],"AA L T OW # name, finnish":["aalto"],"AA M AH T":["aamodt"],"AA NG K AO R":["encore","oncor","aancor"],"AA R D EH M AH":["aardema"],"AA R D V AA R K":["aardvark"],"AA R D V AA R K S":["aardvarks"],"AA R G":["argh","aargh"],"AA HH UW S":["aarhus"],"EH R AH N":["aaron","aran","aron","ehren"],"EH R AH N Z":["arens","aarons","aaron's"],"EH R AH N S AH N":["aronson","aaronson"],"EH R AH N S AH N Z":["aaronson's"],"AA R T IY":["arty","aarti","artie"],"AA S":["os","aase"],"AA S AH N":["aasen","osten"],"AE B":["ab"],"EY B IY EY":["aba"],"AH B AA B AH":["ababa"],"AE B AH K AH":["abacha"],"AH B AE K":["aback"],"AE B AH K OW":["abaco"],"AE B AH K AH S":["abacus"],"AH B AA D":["abad"],"AH B AE D AH K AH":["abadaka"],"AH B AE D IY":["abadi","abadie"],"AH B EH R":["abair"],"AH B AA L K IH N":["abalkin"],"AE B AH L OW N IY":["abalone"],"AE B AH L OW N IY Z":["abalones"],"AA B AA L OW Z":["abalos"],"AH B AE N D AH N":["abandon"],"AH B AE N D AH N D":["abandoned"],"AH B AE N D AH N IH NG":["abandoning"],"AH B AE N D AH N M AH N T":["abandonment"],"AH B AE N D AH N M AH N T S":["abandonments"],"AH B AE N D AH N Z":["abandons"],"AH B AE N T OW":["abanto"],"AH B AA R K AH":["abarca"],"AA B AA R IY":["abare"],"AE B AH S K AH L":["abascal"],"AH B AE SH":["abash"],"AH B AE SH T":["abashed"],"AH B EY ZH Y AH":["abasia"],"AH B EY T":["abate"],"AH B EY T IH D":["abated"],"AH B EY T M AH N T":["abatement"],"AH B EY T M AH N T S":["abatements"],"AH B EY T S":["abates"],"AH B EY T IH NG":["abating"],"AE B AH T W AA R":["abattoir"],"AE B AH":["abba"],"AH B AA D OW":["abbado"],"AH B AA S":["abbas"],"AA B AA S IY":["abbasi"],"AA B EY T":["abbate"],"AA B AA T IY EH L OW":["abbatiello"],"AE B IY":["abby","abbey","abbe","abie","abbie"],"AE B AH N HH AW S":["abbenhaus"],"AH B EH T":["abet","abbett"],"AE B V IH L":["abbeville"],"AE B IY Z":["abbey's"],"AE B IH T":["abbitt"],"AE B AH T":["abbott","abbot"],"AE B AH T S T AW N":["abbotstown","abbottstown"],"AE B AH T S":["abbott's"],"AH B UW D":["abood","abboud"],"AH B R IY V IY EY T":["abbreviate"],"AH B R IY V IY EY T IH D":["abbreviated"],"AH B R IY V IY EY T S":["abbreviates"],"AH B R IY V IY EY T IH NG":["abbreviating"],"AH B R IY V IY EY SH AH N":["abbreviation"],"AH B R IY V IY EY SH AH N Z":["abbreviations"],"AA B R UW T S EY Z IY":["abruzzese","abbruzzese"],"AE B Z":["abbs"],"EY B IY S IY":["abc"],"EY B IY S IY Z":["abcs","abc's"],"AE B K OW":["abco"],"AE B K OW T EH K":["abcotek"],"EY B IY D IY":["abd"],"AE B D AE L AH":["abdalla","abdallah"],"AE B D EH L":["abdel"],"AE B D EH L AH":["abdella"],"AE B D AH K EY T":["abdicate"],"AE B D AH K EY T IH D":["abdicated"],"AE B D AH K EY T S":["abdicates"],"AE B D IH K EY T IH NG":["abdicating"],"AE B D IH K EY SH AH N":["abdication"],"AE B D N ER":["abdnor"],"AE B D OW":["abdo"],"AE B D AA L AH":["abdollah"],"AE B D OW M AH N":["abdomen"],"AE B D AA M AH N AH L":["abdominal"],"AE B D AH K T":["abduct"],"AE B D AH K T IH D":["abducted"],"AE B D AH K T IY":["abductee"],"AE B D AH K T IY Z":["abductees"],"AE B D AH K T IH NG":["abducting"],"AE B D AH K SH AH N":["abduction"],"AE B D AH K SH AH N Z":["abductions"],"AE B D AH K T ER":["abductor"],"AE B D AH K T ER Z":["abductors"],"AE B D AH K T S":["abducts"],"AE B D UW L":["abdul"],"AE B D UW L AH Z IY Z":["abdulaziz"],"AA B D UW L AH":["abdulla"],"AE B D AH L AH":["abdullah"],"EY B":["abe"],"AH B EH D":["abed"],"AH B EH D IY":["abedi"],"AH B IY":["abee"],"EY B AH L":["able","abel","abell"],"AA B EH L AH":["abela"],"AE B IH L ER D":["abelard"],"AH B EH L":["abele"],"AH B EH L Z":["abeles"],"AH B EH L AH":["abella"],"AE B IH L N":["abeln"],"AE B AH L OW":["abelow"],"EY B AH L Z":["abels","ables"],"AE B IH L S AH N":["abelson"],"AE B EH N D":["abend"],"AE B IH N D R AO TH":["abendroth"],"EY B ER":["aber","aybar"],"AE B ER K R AA M B IY":["abercrombie"],"AE B ER D IY N":["aberdeen"],"EY B ER F ER D":["aberford"],"AE B ER G":["aberg"],"AE B ER AH L":["aberle"],"AE B ER M IH N":["abermin"],"AE B ER N AE TH IY":["abernathy"]," Line truncated
reverse_cmudict_default = reverseCmudict;
}
});
// src/index.ts
var index_exports = {};
__export(index_exports, {
CUSTOM_PRONUNCIATIONS: () => CUSTOM_PRONUNCIATIONS,
getCustomPronunciation: () => getCustomPronunciation,
getDictionary: () => getDictionary,
getWordFrequency: () => getWordFrequency,
hasCustomPronunciation: () => hasCustomPronunciation,
isDictionaryLoaded: () => isDictionaryLoaded,
loadDictionary: () => loadDictionary,
loadFrequencies: () => loadFrequencies,
loadReverseDictionary: () => loadReverseDictionary,
lookupPhonemeKey: () => lookupPhonemeKey,
lookupPronunciation: () => lookupPronunciation,
lookupPronunciationLower: () => lookupPronunciationLower,
sortByFrequency: () => sortByFrequency
});
module.exports = __toCommonJS(index_exports);
// src/custom-words.ts
var CUSTOM_PRONUNCIATIONS = {
// ---------------------------------------------------------------------------
// CMU corrections — wrong consonant
// ---------------------------------------------------------------------------
abele: ["AH0", "B", "IY1", "L"],
// /əˈbil/ — CMU has /ɛ/ for /i/
abstention: ["AH0", "B", "S", "T", "EH1", "N", "SH", "AH0", "N"],
// /əbˈstɛnʃən/ — CMU has /tʃ/
abstentions: ["AH0", "B", "S", "T", "EH1", "N", "SH", "AH0", "N", "Z"],
// /əbˈstɛnʃənz/ — CMU has /tʃ/
actuator: ["AE1", "K", "CH", "UW0", "EY2", "T", "ER0"],
// /ˈæktʃuˌeɪtɝ/ — CMU has /tj/
actuators: ["AE1", "K", "CH", "UW0", "EY2", "T", "ER0", "Z"],
// /ˈæktʃuˌeɪtɝz/ — CMU has /tj/
africa: ["AE1", "F", "R", "IH0", "K", "AH0"],
// /ˈæfrɪkə/ — CMU has /ə/ for /ɪ/ and /ɑ/ for /ə/
alienate: ["EY1", "L", "IY0", "AH0", "N", "EY2", "T"],
// /ˈeɪliəˌneɪt/ — CMU has /j/ for /i/
// CMU has /s/ instead of /ʃ/ in -ciate/-ciation suffix
associate: ["AH0", "S", "OW1", "SH", "IY0", "AH0", "T"],
// /əˈsoʊʃiˌət/ — CMU has /s/
associated: ["AH0", "S", "OW1", "SH", "IY0", "EY2", "T", "IH0", "D"],
// /əˈsoʊʃiˌeɪtɪd/ — CMU has /s/
associates: ["AH0", "S", "OW1", "SH", "IY0", "AH0", "T", "S"],
// /əˈsoʊʃiˌəts/ — CMU has /s/
associating: ["AH0", "S", "OW1", "SH", "IY0", "EY2", "T", "IH0", "NG"],
// /əˈsoʊʃiˌeɪtɪŋ/ — CMU has /s/
association: ["AH0", "S", "OW2", "SH", "IY0", "EY1", "SH", "AH0", "N"],
// /əˌsoʊʃiˈeɪʃən/ — CMU has /s/
associations: ["AH0", "S", "OW2", "SH", "IY0", "EY1", "SH", "AH0", "N", "Z"],
// /əˌsoʊʃiˈeɪʃənz/ — CMU has /s/
// Tech terms
async: ["EY1", "S", "IH0", "NG", "K"],
// /ˈeɪsɪŋk/
blog: ["B", "L", "AO1", "G"],
// /blɔɡ/
bocce: ["B", "AA1", "CH", "IY0"],
// /ˈbɑtʃi/ — CMU has /oʊ/ for /ɑ/
// Foreign loanwords
brulee: ["B", "R", "UW0", "L", "EY1"],
// /bruˈleɪ/
buffet: ["B", "AH0", "F", "EY1"],
// /bʌˈfeɪ/ — CMU has verb "to strike", should be noun (food)
// Linguistic terms missing from CMU
camelcase: ["K", "AE1", "M", "AH0", "L", "K", "EY2", "S"],
// /ˈkæməlˌkeɪs/ — G2P gives /eɪ/ for first vowel
ceaselessly: ["S", "IY1", "S", "L", "AH0", "S", "L", "IY0"],
// /ˈsisləsli/ — CMU has /z/
// Irregular English words
chamois: ["SH", "AE1", "M", "IY0"],
// /ˈʃæmi/
chatgpt: ["CH", "AE1", "T", "JH", "IY1", "P", "IY1", "T", "IY1"],
// /tʃæt dʒi pi ti/
cholmondeley: ["CH", "AH1", "M", "L", "IY0"],
// /ˈtʃʌmli/
circumflex: ["S", "ER1", "K", "AH0", "M", "F", "L", "EH2", "K", "S"],
// /ˈsɜrkəmˌflɛks/ — G2P inserts vowel in fl cluster
circumvention: ["S", "ER2", "K", "AH0", "M", "V", "EH1", "N", "SH", "AH0", "N"],
// /ˌsɝkəmˈvɛnʃən/ — CMU has /tʃ/
close: ["K", "L", "OW1", "Z"],
// /kloʊz/ — CMU default is adjective /kloʊs/
conscientiously: ["K", "AA2", "N", "SH", "IY0", "EH1", "N", "SH", "AH0", "S", "L", "IY0"],
// /ˌkɑnʃiˈɛnʃəsli/ — CMU has /tʃ/
contravention: ["K", "AA2", "N", "T", "R", "AH0", "V", "EH1", "N", "SH", "AH0", "N"],
// /ˌkɑntrəˈvɛnʃən/ — CMU has /tʃ/
convulsant: ["K", "AH0", "N", "V", "AH1", "L", "S", "AH0", "N", "T"],
// /kənˈvʌlsənt/ — CMU missing /n/
// Inconsistent vowel in derived form
coughed: ["K", "AA1", "F", "T"],
// /kɑft/ — CMU has /ɔ/ (AO), should match cough's /ɑ/ (AA)
coughs: ["K", "AA1", "F", "S"],
// /kɑfs/ — CMU has /ɔ/ (AO), should match cough's /ɑ/ (AA)
cuckoo: ["K", "UW1", "K", "UW0"],
// /ˈkuku/ — CMU has /ʌ/ for first vowel
// Wrong vowel
dedicate: ["D", "EH1", "D", "IH0", "K", "EY2", "T"],
// /ˈdɛdɪˌkeɪt/ — CMU has /ə/ for /ɪ/
dedicated: ["D", "EH1", "D", "IH0", "K", "EY0", "T", "IH0", "D"],
// /ˈdɛdɪkeɪtɪd/ — CMU has /ə/ for /ɪ/
dedication: ["D", "EH2", "D", "IH0", "K", "EY1", "SH", "AH0", "N"],
// /ˌdɛdɪˈkeɪʃən/ — CMU has /ə/ for /ɪ/
// Wrong consonant in derived form
deliciously: ["D", "IH0", "L", "IH1", "SH", "AH0", "S", "L", "IY0"],
// /dɪˈlɪʃəsli/ — CMU has /ʃ/ for final /s/
derivational: ["D", "EH2", "R", "IH0", "V", "EY1", "SH", "AH0", "N", "AH0", "L"],
// /ˌdɛrɪˈveɪʃənəl/ — G2P gives /aɪ/ for first vowel
// Website/tech terms missing from CMU
digraph: ["D", "AY1", "G", "R", "AE2", "F"],
// /ˈdaɪˌɡræf/ — G2P gives short /ɪ/
digraphs: ["D", "AY1", "G", "R", "AE2", "F", "S"],
// /ˈdaɪˌɡræfs/
// Wrong syllable count
doer: ["D", "UW1", "ER0"],
// /ˈduɝ/ — CMU has 1 syllable (D UW1 R), should be 2 like doers
doppelganger: ["D", "AA1", "P", "AH0", "L", "G", "AE2", "NG", "ER0"],
// /ˈdɑpəlˌɡæŋɝ/
drachm: ["D", "R", "AE1", "M"],
// /dræm/ — silent ch
// Spurious /j/ glide (British /juː/ where AmE uses /uː/)
dudes: ["D", "UW1", "D", "Z"],
// /duːdz/ — CMU has /dju/, should match dude's /du/
duplicates: ["D", "UW1", "P", "L", "AH0", "K", "EY2", "T", "S"],
// /ˈdupləˌkeɪts/ — CMU has /dju/
duplication: ["D", "UW2", "P", "L", "AH0", "K", "EY1", "SH", "AH0", "N"],
// /ˌdupləˈkeɪʃən/ — CMU has /dju/
emoji: ["IH0", "M", "OW1", "JH", "IY0"],
// /ɪˈmoʊdʒi/
engenders: ["EH0", "N", "JH", "EH1", "N", "D", "ER0", "Z"],
// /ɛnˈdʒɛndɝz/ — CMU has /ŋɡ/
excruciatingly: [
"EH2",
"K",
"S",
"K",
"R",
"UW1",
"SH",
"IY0",
"EY2",
"T",
"IH0",
"NG",
"L",
"IY0"
],
// /ɪkˈskruʃiˌeɪtɪŋli/ — CMU has /s/ (excruciating is correct)
expos\u00E9: ["EH2", "K", "S", "P", "OW0", "Z", "EY1"],
// /ˌɛkspoʊˈzeɪ/ — French noun (report), not verb "to expose"
favicon: ["F", "AE1", "V", "IH0", "K", "AA2", "N"],
// /ˈfævɪˌkɑn/ — "favorite icon"
fiancee: ["F", "IY0", "AA0", "N", "S", "EY1"],
// /fiɑnˈseɪ/ — CMU has wrong final syllable
finagle: ["F", "IH0", "N", "EY1", "G", "AH0", "L"],
// /fɪˈneɪɡəl/ — CMU has /ə/ for /eɪ/, wrong stress
flambe: ["F", "L", "AA0", "M", "B", "EY1"],
// /flɑmˈbeɪ/
// ---------------------------------------------------------------------------
// CMU corrections — wrong vowel or glide
// ---------------------------------------------------------------------------
// Missing phoneme
forgings: ["F", "AO1", "R", "JH", "IH0", "NG", "Z"],
// /ˈfɔrdʒɪŋz/ — CMU missing /r/
fraudulently: ["F", "R", "AO1", "JH", "AH0", "L", "AH0", "N", "T", "L", "IY0"],
// /ˈfrɔdʒələntli/ — CMU has /d/
// Days of the week: CMU v1 has /i/ but standard AmE uses /eɪ/
friday: ["F", "R", "AY1", "D", "EY2"],
// /ˈfraɪˌdeɪ/
gestalt: ["G", "AH0", "SH", "T", "AA1", "L", "T"],
// /ɡəˈʃtɑlt/
github: ["G", "IH1", "T", "HH", "AH1", "B"],
// /ˈɡɪtˌhʌb/
grandma: ["G", "R", "AE1", "N", "M", "AA2"],
// /ˈɡrænˌmɑ/ — CMU has spurious /d/
haphazardly: ["HH", "AE0", "P", "HH", "AE1", "Z", "ER0", "D", "L", "IY0"],
// /hæpˈhæzɝdli/ — CMU has /f/
headquartered: ["HH", "EH1", "D", "K", "W", "AO2", "R", "T", "ER0", "D"],
// /ˈhɛdˌkwɔrtɝd/ — CMU missing /w/
hors: ["AO1", "R"],
// /ɔr/ — CMU wrong; French: silent h and s (hors d'oeuvres)
iframe: ["AY1", "F", "R", "EY2", "M"],
// /ˈaɪˌfreɪm/ — G2P gives short /ɪ/ for "i"
immature: ["IH2", "M", "AH0", "CH", "UH1", "R"],
// /ˌɪməˈtʃʊr/ — CMU has /tj/ (British), should match mature's /tʃ/
inattention: ["IH2", "N", "AH0", "T", "EH1", "N", "SH", "AH0", "N"],
// /ˌɪnəˈtɛnʃən/ — CMU has /tʃ/
// N→NG + additional vowel fix (N→NG alone handled by normalizeVelarNasal)
inconclusively: ["IH2", "NG", "K", "AH0", "NG", "K", "L", "UW1", "S", "IH0", "V", "L", "IY0"],
// /ˌɪŋkəŋˈklusɪvli/ — CMU has /nk/
initialisms: ["IH0", "N", "IH1", "SH", "AH0", "L", "IH2", "Z", "AH0", "M", "Z"],
// /ɪˈnɪʃəˌlɪzəmz/
// CMU has /tʃ/ instead of /ʃ/ in -tion/-sion suffix after N
intention: ["IH0", "N", "T", "EH1", "N", "SH", "AH0", "N"],
// /ɪnˈtɛnʃən/ — CMU has /tʃ/
intentions: ["IH0", "N", "T", "EH1", "N", "SH", "AH0", "N", "Z"],
// /ɪnˈtɛnʃənz/ — CMU has /tʃ/
islington: ["IH1", "Z", "L", "IH0", "NG", "T", "AH0", "N"],
// /ˈɪzlɪŋtən/
lead: ["L", "IY1", "D"],
// /liːd/ — CMU default is metal /lɛd/
legalese: ["L", "IY2", "G", "AH0", "L", "IY1", "Z"],
// /ˌliɡəˈliz/ — CMU has /ɛ/, /s/, wrong stress
legit: ["L", "AH0", "JH", "IH1", "T"],
// /ləˈdʒɪt/ — CMU has /ɛ/ and wrong stress
leisure: ["L", "IY1", "ZH", "ER0"],
// /ˈliʒɝ/ — CMU has British /ɛ/, AmE is /i/
leniently: ["L", "IY1", "N", "IY0", "AH0", "N", "T", "L", "IY0"],
// /ˈliniəntli/ — CMU has /j/ for /i/
live: ["L", "IH1", "V"],
// /lɪv/ — CMU default is adjective /laɪv/
localhost: ["L", "OW1", "K", "AH0", "L", "HH", "OW2", "S", "T"],
// /ˈloʊkəlˌhoʊst/
manana: ["M", "AE0", "N", "Y", "AA1", "N", "AH0"],
// /mænˈjɑnə/
mansions: ["M", "AE1", "N", "SH", "AH0", "N", "Z"],
// /ˈmænʃənz/ — CMU has /tʃ/ (singular is correct)
// ---------------------------------------------------------------------------
// CMU corrections — wrong word sense or incomplete entry
// ---------------------------------------------------------------------------
matured: ["M", "AH0", "CH", "UH1", "R", "D"],
// /məˈtʃʊrd/ — CMU has /tj/ (British), should match mature's /tʃ/
monday: ["M", "AH1", "N", "D", "EY2"],
// /ˈmʌnˌdeɪ/
navbar: ["N", "AE1", "V", "B", "AA2", "R"],
// /ˈnævˌbɑr/ — "navigation bar"; G2P gives /ɚ/ for second vowel
negligee: ["N", "EH1", "G", "L", "AH0", "ZH", "EY2"],
// /ˈnɛɡləˌʒeɪ/
// ---------------------------------------------------------------------------
// CMU corrections — variant ordering (v1 wrong for standard AmE)
// ---------------------------------------------------------------------------
nemo: ["N", "IY1", "M", "OW0"],
// /ˈnimoʊ/ — CMU has /ɛ/ for /i/
npm: ["EH1", "N", "P", "IY1", "EH1", "M"],
// /ɛn pi ɛm/
oauth: ["OW1", "AO1", "TH"],
// /oʊɔθ/
obsequies: ["AA1", "B", "S", "IH0", "K", "W", "IY0", "Z"],
// /ˈɑbsɪkwiz/
oppugnant: ["AH0", "P", "AH1", "G", "N", "AH0", "N", "T"],
// /əˈpʌɡnənt/
oppugners: ["AH0", "P", "Y", "UW1", "N", "ER0", "Z"],
// /əˈpjunɝz/ — silent g
orthographic: ["AO2", "R", "TH", "AH0", "G", "R", "AE1", "F", "IH0", "K"],
// /ˌɔrθəˈɡræfɪk/
ow: ["AW1"],
// /aʊ/ — CMU has /oʊ/
padre: ["P", "AA1", "D", "R", "EY0"],
// /ˈpɑdreɪ/ — CMU has /æ/ for /ɑ/
parameterized: ["P", "ER0", "AE1", "M", "IH0", "T", "ER0", "AY2", "Z", "D"],
// /pəˈræmɪtəˌraɪzd/ — G2P gives /eɪ/ for first syllable
patisserie: ["P", "AH0", "T", "IH1", "S", "ER0", "IY0"],
// /pəˈtɪsɝi/
permalink: ["P", "ER1", "M", "AH0", "L", "IH2", "NG", "K"],
// /ˈpɝməˌlɪŋk/ — "permanent link"
phaeton: ["F", "EY1", "IH0", "T", "AH0", "N"],
// /ˈfeɪɪtən/
pinata: ["P", "IH0", "N", "Y", "AA1", "T", "AH0"],
// /pɪnˈjɑtə/
piquet: ["P", "IH0", "K", "EY1"],
// /pɪˈkeɪ/
// ---------------------------------------------------------------------------
// Additions — words not in CMU dictionary
// ---------------------------------------------------------------------------
placeholder: ["P", "L", "EY1", "S", "HH", "OW2", "L", "D", "ER0"],
// /ˈpleɪsˌhoʊldɝ/
podcast: ["P", "AA1", "D", "K", "AE2", "S", "T"],
// /ˈpɑdˌkæst/
potshots: ["P", "AA1", "SH", "AA2", "T", "S"],
// /ˈpɑtˌʃɑts/ — CMU has /tʃ/, should match potshot's /ʃ/
president: ["P", "R", "EH1", "Z", "IH0", "D", "AH0", "N", "T"],
// /ˈprɛzɪdənt/ — CMU has /ə/ for /ɪ/ and /ɛ/ for /ə/
// Voicing errors (/s/↔/z/, /θ/↔/ð/)
presidentially: ["P", "R", "EH2", "Z", "IH0", "D", "EH1", "N", "SH", "AH0", "L", "IY0"],
// /ˌprɛzɪˈdɛnʃəli/ — CMU has /s/
privatize: ["P", "R", "AY1", "V", "AH0", "T", "AY2", "Z"],
// /ˈpraɪvəˌtaɪz/ — CMU has /ɪ/ for /aɪ/, should match private
// Silent letter pronounced
psalm: ["S", "AA1", "M"],
// /sɑm/ — CMU has /l/, but L is silent in psalm
psalms: ["S", "AA1", "M", "Z"],
// /sɑmz/ — CMU has /l/, but L is silent in psalm
puisne: ["P", "Y", "UW1", "N", "IY0"],
// /ˈpjuni/
// Homographs: CMU default is the less common sense
read: ["R", "IY1", "D"],
// /riːd/ — CMU default is past tense /rɛd/
record: ["R", "EH1", "K", "ER0", "D"],
// /ˈrɛkɝd/ — CMU default is verb /rɪˈkɔrd/
rededicate: ["R", "IY2", "D", "EH1", "D", "IH0", "K", "EY2", "T"],
// /ˌriˈdɛdɪˌkeɪt/ — CMU has /ə/ for /ɪ/
rededication: ["R", "IY0", "D", "EH2", "D", "IH0", "K", "EY1", "SH", "AH0", "N"],
// /riˌdɛdɪˈkeɪʃən/ — CMU has /ə/ for /ɪ/
regex: ["R", "EH1", "JH", "EH0", "K", "S"],
// /ˈrɛdʒɛks/ — G2P gives /iː/ for first vowel
reschedulings: ["R", "IY0", "S", "K", "EH1", "JH", "UW0", "L", "IH0", "NG", "Z"],
// /riˈskɛdʒulɪŋz/ — CMU has /ʃ/ (British)
resolutely: ["R", "EH1", "Z", "AH0", "L", "UW2", "T", "L", "IY0"],
// /ˈrɛzəˌlutli/ — CMU has /s/
// Accented homographs: diacritics signal a different word than CMU's default
r\u00E9sum\u00E9: ["R", "EH1", "Z", "AH0", "M", "EY2"],
// /ˈrɛzəˌmeɪ/ — French noun (CV), not verb "to resume"
retroflex: ["R", "EH1", "T", "R", "OW0", "F", "L", "EH2", "K", "S"],
// /ˈrɛtroʊˌflɛks/ — G2P gives /iː/ + epenthetic vowel in fl
revaluations: ["R", "IY0", "V", "AE2", "L", "Y", "UW0", "EY1", "SH", "AH0", "N", "Z"],
// /riˌvæljueɪʃənz/ — CMU has extra /ɪ/
roommate: ["R", "UW1", "M", "M", "EY2", "T"],
// /ˈrumˌmeɪt/ — CMU missing geminate /mm/
roommates: ["R", "UW1", "M", "M", "EY2", "T", "S"],
// /ˈrumˌmeɪts/ — CMU missing geminate /mm/
saturday: ["S", "AE1", "T", "ER0", "D", "EY2"],
// /ˈsætɝˌdeɪ/
soupcon: ["S", "UW0", "P", "S", "AA1", "N"],
// /supˈsɑn/
streatham: ["S", "T", "R", "EH1", "T", "AH0", "M"],
// /ˈstrɛtəm/
syllabification: ["S", "IH0", "L", "AE1", "B", "IH0", "F", "IH0", "K", "EY2", "SH", "AH0", "N"],
// /sɪˌlæbɪfɪˈkeɪʃən/ — G2P drops /b/
temptation: ["T", "EH0", "M", "P", "T", "EY1", "SH", "AH0", "N"],
// /tɛmpˈteɪʃən/ — CMU missing /p/
temptations: ["T", "EH0", "M", "P", "T", "EY1", "SH", "AH0", "N", "Z"],
// /tɛmpˈteɪʃənz/ — CMU missing /p/
tensions: ["T", "EH1", "N", "SH", "AH0", "N", "Z"],
// /ˈtɛnʃənz/ — CMU has /tʃ/ (singular is correct)
terpsichore: ["T", "ER0", "P", "S", "IH1", "K", "ER0", "IY0"],
// /tɝpˈsɪkɝi/
// Missing contracted "is" — "this'" = "this is", needs epenthetic /əz/ since base ends in /s/
"this'": ["DH", "IH1", "S", "AH0", "Z"],
// /ðɪsəz/ — CMU has /ðɪs/ (same as "this", missing "is")
thyme: ["T", "AY1", "M"],
// /taɪm/ — CMU has /θ/, but h is silent
touche: ["T", "UW0", "SH", "EY1"],
// /tuˈʃeɪ/ — CMU missing final syllable
transliteration: ["T", "R", "AE2", "N", "Z", "L", "IH0", "T", "ER0", "EY1", "SH", "AH0", "N"],
// /ˌtrænzlɪtəˈreɪʃən/
tuesday: ["T", "UW1", "Z", "D", "EY2"],
// /ˈtuzˌdeɪ/
tuition: ["T", "UW0", "IH1", "SH", "AH0", "N"],
// /tuˈɪʃən/ — CMU has /tju/
unknowns: ["AH0", "N", "N", "OW1", "N", "Z"],
// /ənˈnoʊnz/ — CMU missing second /n/
use: ["Y", "UW1", "Z"],
// /juːz/ — CMU default is noun /juːs/
valium: ["V", "AE1", "L", "IY0", "AH0", "M"],
// /ˈvæliəm/ — CMU has /eɪ/ for /æ/
velar: ["V", "IY1", "L", "ER0"],
// /ˈviːlɚ/ — G2P gives short /ɛ/ for first vowel
victual: ["V", "IH1", "T", "AH0", "L"],
// /ˈvɪtəl/ — silent c
victuals: ["V", "IH1", "T", "AH0", "L", "Z"],
// /ˈvɪtəlz/ — silent c
vlog: ["V", "L", "AO1", "G"],
// /vlɔɡ/
// Abbreviations
vs: ["V", "ER1", "S", "AH0", "S"],
// /ˈvɝsəs/
webpack: ["W", "EH1", "B", "P", "AE1", "K"],
// /ˈwɛbˌpæk/
wednesday: ["W", "EH1", "N", "Z", "D", "EY2"],
// /ˈwɛnzˌdeɪ/
"well-doer": ["W", "EH1", "L", "D", "UW1", "ER0"],
// /ˈwɛlˌduɝ/ — CMU has 1-syllable doer
wind: ["W", "IH1", "N", "D"],
// /wɪnd/ — CMU default is verb /waɪnd/
withdrawals: ["W", "IH0", "DH", "D", "R", "AO1", "AH0", "L", "Z"],
// /wɪðˈdrɔəlz/ — CMU has /θ/
withdrawing: ["W", "IH0", "DH", "D", "R", "AO1", "IH0", "NG"],
// /wɪðˈdrɔɪŋ/ — CMU has /θ/
withdrawn: ["W", "IH0", "DH", "D", "R", "AO1", "N"]
// /wɪðˈdrɔn/ — CMU has /θ/
};
var CUSTOM_MAP = new Map(Object.entries(CUSTOM_PRONUNCIATIONS));
function getCustomPronunciation(word) {
return CUSTOM_MAP.get(word);
}
function hasCustomPronunciation(word) {
return CUSTOM_MAP.has(word);
}
// src/lazy-loader.ts
function createLazyLoader(loadFn, errorLabel) {
let data = null;
let promise = null;
return {
get() {
if (data === null) {
throw new Error(`${errorLabel} not loaded. Call load() first.`);
}
return data;
},
isLoaded() {
return data !== null;
},
load() {
if (data !== null) {
return Promise.resolve(data);
}
if (promise !== null) {
return promise;
}
promise = loadFn().then((result) => {
data = result;
return data;
}).catch((error) => {
promise = null;
const message = error instanceof Error ? error.message : String(error);
throw new Error(`Failed to load ${errorLabel}: ${message}`);
});
return promise;
},
reset() {
data = null;
promise = null;
}
};
}
// src/load-json.ts
var import_meta = {};
async function loadJson(basename) {
if (typeof process === "undefined" || !process.versions?.node) {
return null;
}
try {
const { readFileSync } = await import("fs");
const { fileURLToPath } = await import("url");
const thisFile = fileURLToPath(import_meta.url);
const dir = thisFile.slice(0, thisFile.lastIndexOf("/"));
return JSON.parse(readFileSync(`${dir}/${basename}.json`, "utf8"));
} catch {
return null;
}
}
// src/frequency.ts
var loader = createLazyLoader(async () => {
const json = await loadJson("data/word-frequencies");
let raw;
if (json === null) {
const mod = await Promise.resolve().then(() => (init_word_frequencies(), word_frequencies_exports));
raw = mod.default;
} else {
raw = json;
}
const map = /* @__PURE__ */ new Map();
for (const [word, count] of Object.entries(raw)) {
map.set(word.toLowerCase(), count);
}
return { map, raw };
}, "word frequencies");
function getWordFrequency(word) {
if (!loader.isLoaded()) {
return void 0;
}
return loader.get().map.get(word.toLowerCase());
}
async function loadFrequencies() {
const data = await loader.load();
return data.raw;
}
var COMMON_CONTRACTIONS = /* @__PURE__ */ new Set([
"ain't",
"aren't",
// n't contractions
"can't",
"could've",
"couldn't",
"didn't",
"doesn't",
"don't",
"hadn't",
"hasn't",
"haven't",
"he'd",
"he'll",
// 's contractions (is/has)
"he's",
"here's",
"how's",
// 'd contractions
"i'd",
// 'll contractions
"i'll",
// 'm contractions
"i'm",
// 've contractions
"i've",
"isn't",
"it'd",
"it'll",
"it's",
"let's",
"might've",
"mightn't",
"must've",
"mustn't",
"needn't",
"shan't",
"she'd",
"she'll",
"she's",
"should've",
"shouldn't",
"that'd",
"that'll",
"that's",
"there'll",
"there's",
"they'd",
"they'll",
"they're",
"they've",
"wasn't",
"we'd",
"we'll",
"we're",
"we've",
"weren't",
"what'll",
"what's",
"where's",
"who'd",
"who'll",
"who's",
"won't",
"would've",
"wouldn't",
"you'd",
"you'll",
// 're contractions
"you're",
"you've"
]);
var CONTRACTION_FREQUENCY_BOOST = 1e7;
var UNKNOWN_CONTRACTION_SCORE = -5e6;
var NUMERIC_WORD_PENALTY = 1e6;
var UNKNOWN_WORD_PENALTY = 1e5;
var NUMERIC_REGEX = /\d/;
function scoreWord(word) {
const lower = word.toLowerCase();
const frequency = loader.isLoaded() ? loader.get().map.get(lower) : void 0;
const isCommonContraction = COMMON_CONTRACTIONS.has(lower);
if (frequency !== void 0) {
return isCommonContraction ? -frequency - CONTRACTION_FREQUENCY_BOOST : -frequency;
}
if (isCommonContraction) {
return UNKNOWN_CONTRACTION_SCORE;
}
if (NUMERIC_REGEX.test(word)) {
return NUMERIC_WORD_PENALTY + word.length;
}
return UNKNOWN_WORD_PENALTY + word.length;
}
function sortByFrequency(words) {
return words.toSorted((a, b) => scoreWord(a) - scoreWord(b));
}
// src/loader.ts
var loader2 = createLazyLoader(async () => {
const json = await loadJson("cmudict");
if (json !== null) {
const dict2 = json;
Object.setPrototypeOf(dict2, null);
return dict2;
}
const mod = await Promise.resolve().then(() => (init_cmudict(), cmudict_exports));
const dict = mod.default;
Object.setPrototypeOf(dict, null);
return dict;
}, "CMU dictionary");
var loadDictionary = loader2.load.bind(loader2);
var getDictionary = loader2.get.bind(loader2);
var isDictionaryLoaded = loader2.isLoaded.bind(loader2);
// src/lookup.ts
function lookupPronunciation(word) {
return lookupPronunciationLower(word.toLowerCase());
}
function lookupPronunciationLower(key) {
const custom = getCustomPronunciation(key);
if (custom) {
return custom;
}
const dict = getDictionary();
if (!(key in dict)) {
return null;
}
return dict[key];
}
// src/reverse.ts
var import_phonemes = require("@ingglish/phonemes");
var loader3 = createLazyLoader(async () => {
const json = await loadJson("reverse-cmudict");
let dict;
if (json === null) {
const mod = await Promise.resolve().then(() => (init_reverse_cmudict(), reverse_cmudict_exports));
dict = mod.default;
} else {
dict = json;
}
await loadFrequencies();
for (const [word, phonemes] of Object.entries(CUSTOM_PRONUNCIATIONS)) {
const key = phonemes.map((p) => (0, import_phonemes.stripStress)(p)).join(" ");
const existing = dict[key];
if (existing === void 0) {
dict[key] = [word];
} else if (!existing.includes(word)) {
existing.push(word);
dict[key] = sortByFrequency(existing);
}
}
return dict;
}, "Reverse dictionary");
var loadReverseDictionary = loader3.load.bind(loader3);
var getReverseDictionary = loader3.get.bind(loader3);
function lookupPhonemeKey(key) {
return getReverseDictionary()[key];
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
CUSTOM_PRONUNCIATIONS,
getCustomPronunciation,
getDictionary,
getWordFrequency,
hasCustomPronunciation,
isDictionaryLoaded,
loadDictionary,
loadFrequencies,
loadReverseDictionary,
lookupPhonemeKey,
lookupPronunciation,
lookupPronunciationLower,
sortByFrequency
});
+98
View File
@@ -0,0 +1,98 @@
/**
* Custom pronunciations that override CMU dictionary entries or add missing words.
*
* Two categories:
* 1. CMU corrections — fix errors in existing CMU entries (verified vs Cambridge/Wiktionary)
* 2. Additions — words not in CMU (tech terms, loanwords, etc.)
*
* Note: ~800 N-before-velar errors (N K → NG K, N G → NG G) are fixed automatically
* by normalizeVelarNasal() in lookup.ts and don't need entries here.
*/
declare const CUSTOM_PRONUNCIATIONS: Record<string, string[]>;
/**
* Gets custom pronunciation for a word.
* @param word The word to look up (should be lowercase for best performance)
*/
declare function getCustomPronunciation(word: string): string[] | undefined;
/**
* Checks if a word has a custom pronunciation.
* @param word The word to look up (should be lowercase for best performance)
*/
declare function hasCustomPronunciation(word: string): boolean;
/**
* Word frequency scoring using SUBTLEX corpus data.
* Used for selecting the most common word among homophones.
*/
/**
* Returns the frequency count for a word (higher = more common).
* Returns undefined if word is not in the corpus or data hasn't loaded yet.
*/
declare function getWordFrequency(word: string): number | undefined;
/**
* Loads word frequency data.
* The data is cached after first load.
*/
declare function loadFrequencies(): Promise<Record<string, number>>;
/**
* Sorts words by frequency (most common first).
*/
declare function sortByFrequency(words: string[]): string[];
type CMUDictionary = Record<string, string[]>;
type ReverseDictionary = Record<string, string[]>;
/**
* CMU Dictionary loading and caching.
*
* Dictionary sourced from: https://github.com/cmusphinx/cmudict
*/
/**
* Loads the CMU Pronouncing Dictionary.
* The dictionary is cached after first load.
*/
declare const loadDictionary: () => Promise<CMUDictionary>;
/**
* Gets the dictionary synchronously.
* Throws if dictionary hasn't been loaded yet.
*/
declare const getDictionary: () => CMUDictionary;
/**
* Checks if the dictionary is loaded.
*/
declare const isDictionaryLoaded: () => boolean;
/**
* Looks up a word in the CMU dictionary, returning the ARPAbet IR.
* Custom pronunciations override dictionary entries.
* @param word The word to look up (case insensitive)
* @returns ARPAbet phoneme array (the pipeline IR), or null if not found
*/
declare function lookupPronunciation(word: string): null | string[];
/**
* Like {@link lookupPronunciation}, but takes a **pre-lowercased** key.
* Skips the `.toLowerCase()` call — use when the caller has already
* confirmed the key is lowercase (e.g., fast-path code).
*/
declare function lookupPronunciationLower(key: string): null | string[];
/**
* Reverse dictionary: phoneme sequence -> English words.
*
* Used for reverse translation (Ingglish/IPA -> English).
* Pre-built at build time with words sorted by frequency.
*/
/**
* Loads the pre-built reverse dictionary.
* The dictionary is cached after first load.
*/
declare const loadReverseDictionary: () => Promise<ReverseDictionary>;
/**
* Looks up words for a phoneme key.
* Results are pre-merged and frequency-sorted at load time.
*/
declare function lookupPhonemeKey(key: string): string[] | undefined;
export { CUSTOM_PRONUNCIATIONS, getCustomPronunciation, getDictionary, getWordFrequency, hasCustomPronunciation, isDictionaryLoaded, loadDictionary, loadFrequencies, loadReverseDictionary, lookupPhonemeKey, lookupPronunciation, lookupPronunciationLower, sortByFrequency };
+98
View File
@@ -0,0 +1,98 @@
/**
* Custom pronunciations that override CMU dictionary entries or add missing words.
*
* Two categories:
* 1. CMU corrections — fix errors in existing CMU entries (verified vs Cambridge/Wiktionary)
* 2. Additions — words not in CMU (tech terms, loanwords, etc.)
*
* Note: ~800 N-before-velar errors (N K → NG K, N G → NG G) are fixed automatically
* by normalizeVelarNasal() in lookup.ts and don't need entries here.
*/
declare const CUSTOM_PRONUNCIATIONS: Record<string, string[]>;
/**
* Gets custom pronunciation for a word.
* @param word The word to look up (should be lowercase for best performance)
*/
declare function getCustomPronunciation(word: string): string[] | undefined;
/**
* Checks if a word has a custom pronunciation.
* @param word The word to look up (should be lowercase for best performance)
*/
declare function hasCustomPronunciation(word: string): boolean;
/**
* Word frequency scoring using SUBTLEX corpus data.
* Used for selecting the most common word among homophones.
*/
/**
* Returns the frequency count for a word (higher = more common).
* Returns undefined if word is not in the corpus or data hasn't loaded yet.
*/
declare function getWordFrequency(word: string): number | undefined;
/**
* Loads word frequency data.
* The data is cached after first load.
*/
declare function loadFrequencies(): Promise<Record<string, number>>;
/**
* Sorts words by frequency (most common first).
*/
declare function sortByFrequency(words: string[]): string[];
type CMUDictionary = Record<string, string[]>;
type ReverseDictionary = Record<string, string[]>;
/**
* CMU Dictionary loading and caching.
*
* Dictionary sourced from: https://github.com/cmusphinx/cmudict
*/
/**
* Loads the CMU Pronouncing Dictionary.
* The dictionary is cached after first load.
*/
declare const loadDictionary: () => Promise<CMUDictionary>;
/**
* Gets the dictionary synchronously.
* Throws if dictionary hasn't been loaded yet.
*/
declare const getDictionary: () => CMUDictionary;
/**
* Checks if the dictionary is loaded.
*/
declare const isDictionaryLoaded: () => boolean;
/**
* Looks up a word in the CMU dictionary, returning the ARPAbet IR.
* Custom pronunciations override dictionary entries.
* @param word The word to look up (case insensitive)
* @returns ARPAbet phoneme array (the pipeline IR), or null if not found
*/
declare function lookupPronunciation(word: string): null | string[];
/**
* Like {@link lookupPronunciation}, but takes a **pre-lowercased** key.
* Skips the `.toLowerCase()` call — use when the caller has already
* confirmed the key is lowercase (e.g., fast-path code).
*/
declare function lookupPronunciationLower(key: string): null | string[];
/**
* Reverse dictionary: phoneme sequence -> English words.
*
* Used for reverse translation (Ingglish/IPA -> English).
* Pre-built at build time with words sorted by frequency.
*/
/**
* Loads the pre-built reverse dictionary.
* The dictionary is cached after first load.
*/
declare const loadReverseDictionary: () => Promise<ReverseDictionary>;
/**
* Looks up words for a phoneme key.
* Results are pre-merged and frequency-sorted at load time.
*/
declare function lookupPhonemeKey(key: string): string[] | undefined;
export { CUSTOM_PRONUNCIATIONS, getCustomPronunciation, getDictionary, getWordFrequency, hasCustomPronunciation, isDictionaryLoaded, loadDictionary, loadFrequencies, loadReverseDictionary, lookupPhonemeKey, lookupPronunciation, lookupPronunciationLower, sortByFrequency };
+612
View File
@@ -0,0 +1,612 @@
// src/custom-words.ts
var CUSTOM_PRONUNCIATIONS = {
// ---------------------------------------------------------------------------
// CMU corrections — wrong consonant
// ---------------------------------------------------------------------------
abele: ["AH0", "B", "IY1", "L"],
// /əˈbil/ — CMU has /ɛ/ for /i/
abstention: ["AH0", "B", "S", "T", "EH1", "N", "SH", "AH0", "N"],
// /əbˈstɛnʃən/ — CMU has /tʃ/
abstentions: ["AH0", "B", "S", "T", "EH1", "N", "SH", "AH0", "N", "Z"],
// /əbˈstɛnʃənz/ — CMU has /tʃ/
actuator: ["AE1", "K", "CH", "UW0", "EY2", "T", "ER0"],
// /ˈæktʃuˌeɪtɝ/ — CMU has /tj/
actuators: ["AE1", "K", "CH", "UW0", "EY2", "T", "ER0", "Z"],
// /ˈæktʃuˌeɪtɝz/ — CMU has /tj/
africa: ["AE1", "F", "R", "IH0", "K", "AH0"],
// /ˈæfrɪkə/ — CMU has /ə/ for /ɪ/ and /ɑ/ for /ə/
alienate: ["EY1", "L", "IY0", "AH0", "N", "EY2", "T"],
// /ˈeɪliəˌneɪt/ — CMU has /j/ for /i/
// CMU has /s/ instead of /ʃ/ in -ciate/-ciation suffix
associate: ["AH0", "S", "OW1", "SH", "IY0", "AH0", "T"],
// /əˈsoʊʃiˌət/ — CMU has /s/
associated: ["AH0", "S", "OW1", "SH", "IY0", "EY2", "T", "IH0", "D"],
// /əˈsoʊʃiˌeɪtɪd/ — CMU has /s/
associates: ["AH0", "S", "OW1", "SH", "IY0", "AH0", "T", "S"],
// /əˈsoʊʃiˌəts/ — CMU has /s/
associating: ["AH0", "S", "OW1", "SH", "IY0", "EY2", "T", "IH0", "NG"],
// /əˈsoʊʃiˌeɪtɪŋ/ — CMU has /s/
association: ["AH0", "S", "OW2", "SH", "IY0", "EY1", "SH", "AH0", "N"],
// /əˌsoʊʃiˈeɪʃən/ — CMU has /s/
associations: ["AH0", "S", "OW2", "SH", "IY0", "EY1", "SH", "AH0", "N", "Z"],
// /əˌsoʊʃiˈeɪʃənz/ — CMU has /s/
// Tech terms
async: ["EY1", "S", "IH0", "NG", "K"],
// /ˈeɪsɪŋk/
blog: ["B", "L", "AO1", "G"],
// /blɔɡ/
bocce: ["B", "AA1", "CH", "IY0"],
// /ˈbɑtʃi/ — CMU has /oʊ/ for /ɑ/
// Foreign loanwords
brulee: ["B", "R", "UW0", "L", "EY1"],
// /bruˈleɪ/
buffet: ["B", "AH0", "F", "EY1"],
// /bʌˈfeɪ/ — CMU has verb "to strike", should be noun (food)
// Linguistic terms missing from CMU
camelcase: ["K", "AE1", "M", "AH0", "L", "K", "EY2", "S"],
// /ˈkæməlˌkeɪs/ — G2P gives /eɪ/ for first vowel
ceaselessly: ["S", "IY1", "S", "L", "AH0", "S", "L", "IY0"],
// /ˈsisləsli/ — CMU has /z/
// Irregular English words
chamois: ["SH", "AE1", "M", "IY0"],
// /ˈʃæmi/
chatgpt: ["CH", "AE1", "T", "JH", "IY1", "P", "IY1", "T", "IY1"],
// /tʃæt dʒi pi ti/
cholmondeley: ["CH", "AH1", "M", "L", "IY0"],
// /ˈtʃʌmli/
circumflex: ["S", "ER1", "K", "AH0", "M", "F", "L", "EH2", "K", "S"],
// /ˈsɜrkəmˌflɛks/ — G2P inserts vowel in fl cluster
circumvention: ["S", "ER2", "K", "AH0", "M", "V", "EH1", "N", "SH", "AH0", "N"],
// /ˌsɝkəmˈvɛnʃən/ — CMU has /tʃ/
close: ["K", "L", "OW1", "Z"],
// /kloʊz/ — CMU default is adjective /kloʊs/
conscientiously: ["K", "AA2", "N", "SH", "IY0", "EH1", "N", "SH", "AH0", "S", "L", "IY0"],
// /ˌkɑnʃiˈɛnʃəsli/ — CMU has /tʃ/
contravention: ["K", "AA2", "N", "T", "R", "AH0", "V", "EH1", "N", "SH", "AH0", "N"],
// /ˌkɑntrəˈvɛnʃən/ — CMU has /tʃ/
convulsant: ["K", "AH0", "N", "V", "AH1", "L", "S", "AH0", "N", "T"],
// /kənˈvʌlsənt/ — CMU missing /n/
// Inconsistent vowel in derived form
coughed: ["K", "AA1", "F", "T"],
// /kɑft/ — CMU has /ɔ/ (AO), should match cough's /ɑ/ (AA)
coughs: ["K", "AA1", "F", "S"],
// /kɑfs/ — CMU has /ɔ/ (AO), should match cough's /ɑ/ (AA)
cuckoo: ["K", "UW1", "K", "UW0"],
// /ˈkuku/ — CMU has /ʌ/ for first vowel
// Wrong vowel
dedicate: ["D", "EH1", "D", "IH0", "K", "EY2", "T"],
// /ˈdɛdɪˌkeɪt/ — CMU has /ə/ for /ɪ/
dedicated: ["D", "EH1", "D", "IH0", "K", "EY0", "T", "IH0", "D"],
// /ˈdɛdɪkeɪtɪd/ — CMU has /ə/ for /ɪ/
dedication: ["D", "EH2", "D", "IH0", "K", "EY1", "SH", "AH0", "N"],
// /ˌdɛdɪˈkeɪʃən/ — CMU has /ə/ for /ɪ/
// Wrong consonant in derived form
deliciously: ["D", "IH0", "L", "IH1", "SH", "AH0", "S", "L", "IY0"],
// /dɪˈlɪʃəsli/ — CMU has /ʃ/ for final /s/
derivational: ["D", "EH2", "R", "IH0", "V", "EY1", "SH", "AH0", "N", "AH0", "L"],
// /ˌdɛrɪˈveɪʃənəl/ — G2P gives /aɪ/ for first vowel
// Website/tech terms missing from CMU
digraph: ["D", "AY1", "G", "R", "AE2", "F"],
// /ˈdaɪˌɡræf/ — G2P gives short /ɪ/
digraphs: ["D", "AY1", "G", "R", "AE2", "F", "S"],
// /ˈdaɪˌɡræfs/
// Wrong syllable count
doer: ["D", "UW1", "ER0"],
// /ˈduɝ/ — CMU has 1 syllable (D UW1 R), should be 2 like doers
doppelganger: ["D", "AA1", "P", "AH0", "L", "G", "AE2", "NG", "ER0"],
// /ˈdɑpəlˌɡæŋɝ/
drachm: ["D", "R", "AE1", "M"],
// /dræm/ — silent ch
// Spurious /j/ glide (British /juː/ where AmE uses /uː/)
dudes: ["D", "UW1", "D", "Z"],
// /duːdz/ — CMU has /dju/, should match dude's /du/
duplicates: ["D", "UW1", "P", "L", "AH0", "K", "EY2", "T", "S"],
// /ˈdupləˌkeɪts/ — CMU has /dju/
duplication: ["D", "UW2", "P", "L", "AH0", "K", "EY1", "SH", "AH0", "N"],
// /ˌdupləˈkeɪʃən/ — CMU has /dju/
emoji: ["IH0", "M", "OW1", "JH", "IY0"],
// /ɪˈmoʊdʒi/
engenders: ["EH0", "N", "JH", "EH1", "N", "D", "ER0", "Z"],
// /ɛnˈdʒɛndɝz/ — CMU has /ŋɡ/
excruciatingly: [
"EH2",
"K",
"S",
"K",
"R",
"UW1",
"SH",
"IY0",
"EY2",
"T",
"IH0",
"NG",
"L",
"IY0"
],
// /ɪkˈskruʃiˌeɪtɪŋli/ — CMU has /s/ (excruciating is correct)
expos\u00E9: ["EH2", "K", "S", "P", "OW0", "Z", "EY1"],
// /ˌɛkspoʊˈzeɪ/ — French noun (report), not verb "to expose"
favicon: ["F", "AE1", "V", "IH0", "K", "AA2", "N"],
// /ˈfævɪˌkɑn/ — "favorite icon"
fiancee: ["F", "IY0", "AA0", "N", "S", "EY1"],
// /fiɑnˈseɪ/ — CMU has wrong final syllable
finagle: ["F", "IH0", "N", "EY1", "G", "AH0", "L"],
// /fɪˈneɪɡəl/ — CMU has /ə/ for /eɪ/, wrong stress
flambe: ["F", "L", "AA0", "M", "B", "EY1"],
// /flɑmˈbeɪ/
// ---------------------------------------------------------------------------
// CMU corrections — wrong vowel or glide
// ---------------------------------------------------------------------------
// Missing phoneme
forgings: ["F", "AO1", "R", "JH", "IH0", "NG", "Z"],
// /ˈfɔrdʒɪŋz/ — CMU missing /r/
fraudulently: ["F", "R", "AO1", "JH", "AH0", "L", "AH0", "N", "T", "L", "IY0"],
// /ˈfrɔdʒələntli/ — CMU has /d/
// Days of the week: CMU v1 has /i/ but standard AmE uses /eɪ/
friday: ["F", "R", "AY1", "D", "EY2"],
// /ˈfraɪˌdeɪ/
gestalt: ["G", "AH0", "SH", "T", "AA1", "L", "T"],
// /ɡəˈʃtɑlt/
github: ["G", "IH1", "T", "HH", "AH1", "B"],
// /ˈɡɪtˌhʌb/
grandma: ["G", "R", "AE1", "N", "M", "AA2"],
// /ˈɡrænˌmɑ/ — CMU has spurious /d/
haphazardly: ["HH", "AE0", "P", "HH", "AE1", "Z", "ER0", "D", "L", "IY0"],
// /hæpˈhæzɝdli/ — CMU has /f/
headquartered: ["HH", "EH1", "D", "K", "W", "AO2", "R", "T", "ER0", "D"],
// /ˈhɛdˌkwɔrtɝd/ — CMU missing /w/
hors: ["AO1", "R"],
// /ɔr/ — CMU wrong; French: silent h and s (hors d'oeuvres)
iframe: ["AY1", "F", "R", "EY2", "M"],
// /ˈaɪˌfreɪm/ — G2P gives short /ɪ/ for "i"
immature: ["IH2", "M", "AH0", "CH", "UH1", "R"],
// /ˌɪməˈtʃʊr/ — CMU has /tj/ (British), should match mature's /tʃ/
inattention: ["IH2", "N", "AH0", "T", "EH1", "N", "SH", "AH0", "N"],
// /ˌɪnəˈtɛnʃən/ — CMU has /tʃ/
// N→NG + additional vowel fix (N→NG alone handled by normalizeVelarNasal)
inconclusively: ["IH2", "NG", "K", "AH0", "NG", "K", "L", "UW1", "S", "IH0", "V", "L", "IY0"],
// /ˌɪŋkəŋˈklusɪvli/ — CMU has /nk/
initialisms: ["IH0", "N", "IH1", "SH", "AH0", "L", "IH2", "Z", "AH0", "M", "Z"],
// /ɪˈnɪʃəˌlɪzəmz/
// CMU has /tʃ/ instead of /ʃ/ in -tion/-sion suffix after N
intention: ["IH0", "N", "T", "EH1", "N", "SH", "AH0", "N"],
// /ɪnˈtɛnʃən/ — CMU has /tʃ/
intentions: ["IH0", "N", "T", "EH1", "N", "SH", "AH0", "N", "Z"],
// /ɪnˈtɛnʃənz/ — CMU has /tʃ/
islington: ["IH1", "Z", "L", "IH0", "NG", "T", "AH0", "N"],
// /ˈɪzlɪŋtən/
lead: ["L", "IY1", "D"],
// /liːd/ — CMU default is metal /lɛd/
legalese: ["L", "IY2", "G", "AH0", "L", "IY1", "Z"],
// /ˌliɡəˈliz/ — CMU has /ɛ/, /s/, wrong stress
legit: ["L", "AH0", "JH", "IH1", "T"],
// /ləˈdʒɪt/ — CMU has /ɛ/ and wrong stress
leisure: ["L", "IY1", "ZH", "ER0"],
// /ˈliʒɝ/ — CMU has British /ɛ/, AmE is /i/
leniently: ["L", "IY1", "N", "IY0", "AH0", "N", "T", "L", "IY0"],
// /ˈliniəntli/ — CMU has /j/ for /i/
live: ["L", "IH1", "V"],
// /lɪv/ — CMU default is adjective /laɪv/
localhost: ["L", "OW1", "K", "AH0", "L", "HH", "OW2", "S", "T"],
// /ˈloʊkəlˌhoʊst/
manana: ["M", "AE0", "N", "Y", "AA1", "N", "AH0"],
// /mænˈjɑnə/
mansions: ["M", "AE1", "N", "SH", "AH0", "N", "Z"],
// /ˈmænʃənz/ — CMU has /tʃ/ (singular is correct)
// ---------------------------------------------------------------------------
// CMU corrections — wrong word sense or incomplete entry
// ---------------------------------------------------------------------------
matured: ["M", "AH0", "CH", "UH1", "R", "D"],
// /məˈtʃʊrd/ — CMU has /tj/ (British), should match mature's /tʃ/
monday: ["M", "AH1", "N", "D", "EY2"],
// /ˈmʌnˌdeɪ/
navbar: ["N", "AE1", "V", "B", "AA2", "R"],
// /ˈnævˌbɑr/ — "navigation bar"; G2P gives /ɚ/ for second vowel
negligee: ["N", "EH1", "G", "L", "AH0", "ZH", "EY2"],
// /ˈnɛɡləˌʒeɪ/
// ---------------------------------------------------------------------------
// CMU corrections — variant ordering (v1 wrong for standard AmE)
// ---------------------------------------------------------------------------
nemo: ["N", "IY1", "M", "OW0"],
// /ˈnimoʊ/ — CMU has /ɛ/ for /i/
npm: ["EH1", "N", "P", "IY1", "EH1", "M"],
// /ɛn pi ɛm/
oauth: ["OW1", "AO1", "TH"],
// /oʊɔθ/
obsequies: ["AA1", "B", "S", "IH0", "K", "W", "IY0", "Z"],
// /ˈɑbsɪkwiz/
oppugnant: ["AH0", "P", "AH1", "G", "N", "AH0", "N", "T"],
// /əˈpʌɡnənt/
oppugners: ["AH0", "P", "Y", "UW1", "N", "ER0", "Z"],
// /əˈpjunɝz/ — silent g
orthographic: ["AO2", "R", "TH", "AH0", "G", "R", "AE1", "F", "IH0", "K"],
// /ˌɔrθəˈɡræfɪk/
ow: ["AW1"],
// /aʊ/ — CMU has /oʊ/
padre: ["P", "AA1", "D", "R", "EY0"],
// /ˈpɑdreɪ/ — CMU has /æ/ for /ɑ/
parameterized: ["P", "ER0", "AE1", "M", "IH0", "T", "ER0", "AY2", "Z", "D"],
// /pəˈræmɪtəˌraɪzd/ — G2P gives /eɪ/ for first syllable
patisserie: ["P", "AH0", "T", "IH1", "S", "ER0", "IY0"],
// /pəˈtɪsɝi/
permalink: ["P", "ER1", "M", "AH0", "L", "IH2", "NG", "K"],
// /ˈpɝməˌlɪŋk/ — "permanent link"
phaeton: ["F", "EY1", "IH0", "T", "AH0", "N"],
// /ˈfeɪɪtən/
pinata: ["P", "IH0", "N", "Y", "AA1", "T", "AH0"],
// /pɪnˈjɑtə/
piquet: ["P", "IH0", "K", "EY1"],
// /pɪˈkeɪ/
// ---------------------------------------------------------------------------
// Additions — words not in CMU dictionary
// ---------------------------------------------------------------------------
placeholder: ["P", "L", "EY1", "S", "HH", "OW2", "L", "D", "ER0"],
// /ˈpleɪsˌhoʊldɝ/
podcast: ["P", "AA1", "D", "K", "AE2", "S", "T"],
// /ˈpɑdˌkæst/
potshots: ["P", "AA1", "SH", "AA2", "T", "S"],
// /ˈpɑtˌʃɑts/ — CMU has /tʃ/, should match potshot's /ʃ/
president: ["P", "R", "EH1", "Z", "IH0", "D", "AH0", "N", "T"],
// /ˈprɛzɪdənt/ — CMU has /ə/ for /ɪ/ and /ɛ/ for /ə/
// Voicing errors (/s/↔/z/, /θ/↔/ð/)
presidentially: ["P", "R", "EH2", "Z", "IH0", "D", "EH1", "N", "SH", "AH0", "L", "IY0"],
// /ˌprɛzɪˈdɛnʃəli/ — CMU has /s/
privatize: ["P", "R", "AY1", "V", "AH0", "T", "AY2", "Z"],
// /ˈpraɪvəˌtaɪz/ — CMU has /ɪ/ for /aɪ/, should match private
// Silent letter pronounced
psalm: ["S", "AA1", "M"],
// /sɑm/ — CMU has /l/, but L is silent in psalm
psalms: ["S", "AA1", "M", "Z"],
// /sɑmz/ — CMU has /l/, but L is silent in psalm
puisne: ["P", "Y", "UW1", "N", "IY0"],
// /ˈpjuni/
// Homographs: CMU default is the less common sense
read: ["R", "IY1", "D"],
// /riːd/ — CMU default is past tense /rɛd/
record: ["R", "EH1", "K", "ER0", "D"],
// /ˈrɛkɝd/ — CMU default is verb /rɪˈkɔrd/
rededicate: ["R", "IY2", "D", "EH1", "D", "IH0", "K", "EY2", "T"],
// /ˌriˈdɛdɪˌkeɪt/ — CMU has /ə/ for /ɪ/
rededication: ["R", "IY0", "D", "EH2", "D", "IH0", "K", "EY1", "SH", "AH0", "N"],
// /riˌdɛdɪˈkeɪʃən/ — CMU has /ə/ for /ɪ/
regex: ["R", "EH1", "JH", "EH0", "K", "S"],
// /ˈrɛdʒɛks/ — G2P gives /iː/ for first vowel
reschedulings: ["R", "IY0", "S", "K", "EH1", "JH", "UW0", "L", "IH0", "NG", "Z"],
// /riˈskɛdʒulɪŋz/ — CMU has /ʃ/ (British)
resolutely: ["R", "EH1", "Z", "AH0", "L", "UW2", "T", "L", "IY0"],
// /ˈrɛzəˌlutli/ — CMU has /s/
// Accented homographs: diacritics signal a different word than CMU's default
r\u00E9sum\u00E9: ["R", "EH1", "Z", "AH0", "M", "EY2"],
// /ˈrɛzəˌmeɪ/ — French noun (CV), not verb "to resume"
retroflex: ["R", "EH1", "T", "R", "OW0", "F", "L", "EH2", "K", "S"],
// /ˈrɛtroʊˌflɛks/ — G2P gives /iː/ + epenthetic vowel in fl
revaluations: ["R", "IY0", "V", "AE2", "L", "Y", "UW0", "EY1", "SH", "AH0", "N", "Z"],
// /riˌvæljueɪʃənz/ — CMU has extra /ɪ/
roommate: ["R", "UW1", "M", "M", "EY2", "T"],
// /ˈrumˌmeɪt/ — CMU missing geminate /mm/
roommates: ["R", "UW1", "M", "M", "EY2", "T", "S"],
// /ˈrumˌmeɪts/ — CMU missing geminate /mm/
saturday: ["S", "AE1", "T", "ER0", "D", "EY2"],
// /ˈsætɝˌdeɪ/
soupcon: ["S", "UW0", "P", "S", "AA1", "N"],
// /supˈsɑn/
streatham: ["S", "T", "R", "EH1", "T", "AH0", "M"],
// /ˈstrɛtəm/
syllabification: ["S", "IH0", "L", "AE1", "B", "IH0", "F", "IH0", "K", "EY2", "SH", "AH0", "N"],
// /sɪˌlæbɪfɪˈkeɪʃən/ — G2P drops /b/
temptation: ["T", "EH0", "M", "P", "T", "EY1", "SH", "AH0", "N"],
// /tɛmpˈteɪʃən/ — CMU missing /p/
temptations: ["T", "EH0", "M", "P", "T", "EY1", "SH", "AH0", "N", "Z"],
// /tɛmpˈteɪʃənz/ — CMU missing /p/
tensions: ["T", "EH1", "N", "SH", "AH0", "N", "Z"],
// /ˈtɛnʃənz/ — CMU has /tʃ/ (singular is correct)
terpsichore: ["T", "ER0", "P", "S", "IH1", "K", "ER0", "IY0"],
// /tɝpˈsɪkɝi/
// Missing contracted "is" — "this'" = "this is", needs epenthetic /əz/ since base ends in /s/
"this'": ["DH", "IH1", "S", "AH0", "Z"],
// /ðɪsəz/ — CMU has /ðɪs/ (same as "this", missing "is")
thyme: ["T", "AY1", "M"],
// /taɪm/ — CMU has /θ/, but h is silent
touche: ["T", "UW0", "SH", "EY1"],
// /tuˈʃeɪ/ — CMU missing final syllable
transliteration: ["T", "R", "AE2", "N", "Z", "L", "IH0", "T", "ER0", "EY1", "SH", "AH0", "N"],
// /ˌtrænzlɪtəˈreɪʃən/
tuesday: ["T", "UW1", "Z", "D", "EY2"],
// /ˈtuzˌdeɪ/
tuition: ["T", "UW0", "IH1", "SH", "AH0", "N"],
// /tuˈɪʃən/ — CMU has /tju/
unknowns: ["AH0", "N", "N", "OW1", "N", "Z"],
// /ənˈnoʊnz/ — CMU missing second /n/
use: ["Y", "UW1", "Z"],
// /juːz/ — CMU default is noun /juːs/
valium: ["V", "AE1", "L", "IY0", "AH0", "M"],
// /ˈvæliəm/ — CMU has /eɪ/ for /æ/
velar: ["V", "IY1", "L", "ER0"],
// /ˈviːlɚ/ — G2P gives short /ɛ/ for first vowel
victual: ["V", "IH1", "T", "AH0", "L"],
// /ˈvɪtəl/ — silent c
victuals: ["V", "IH1", "T", "AH0", "L", "Z"],
// /ˈvɪtəlz/ — silent c
vlog: ["V", "L", "AO1", "G"],
// /vlɔɡ/
// Abbreviations
vs: ["V", "ER1", "S", "AH0", "S"],
// /ˈvɝsəs/
webpack: ["W", "EH1", "B", "P", "AE1", "K"],
// /ˈwɛbˌpæk/
wednesday: ["W", "EH1", "N", "Z", "D", "EY2"],
// /ˈwɛnzˌdeɪ/
"well-doer": ["W", "EH1", "L", "D", "UW1", "ER0"],
// /ˈwɛlˌduɝ/ — CMU has 1-syllable doer
wind: ["W", "IH1", "N", "D"],
// /wɪnd/ — CMU default is verb /waɪnd/
withdrawals: ["W", "IH0", "DH", "D", "R", "AO1", "AH0", "L", "Z"],
// /wɪðˈdrɔəlz/ — CMU has /θ/
withdrawing: ["W", "IH0", "DH", "D", "R", "AO1", "IH0", "NG"],
// /wɪðˈdrɔɪŋ/ — CMU has /θ/
withdrawn: ["W", "IH0", "DH", "D", "R", "AO1", "N"]
// /wɪðˈdrɔn/ — CMU has /θ/
};
var CUSTOM_MAP = new Map(Object.entries(CUSTOM_PRONUNCIATIONS));
function getCustomPronunciation(word) {
return CUSTOM_MAP.get(word);
}
function hasCustomPronunciation(word) {
return CUSTOM_MAP.has(word);
}
// src/lazy-loader.ts
function createLazyLoader(loadFn, errorLabel) {
let data = null;
let promise = null;
return {
get() {
if (data === null) {
throw new Error(`${errorLabel} not loaded. Call load() first.`);
}
return data;
},
isLoaded() {
return data !== null;
},
load() {
if (data !== null) {
return Promise.resolve(data);
}
if (promise !== null) {
return promise;
}
promise = loadFn().then((result) => {
data = result;
return data;
}).catch((error) => {
promise = null;
const message = error instanceof Error ? error.message : String(error);
throw new Error(`Failed to load ${errorLabel}: ${message}`);
});
return promise;
},
reset() {
data = null;
promise = null;
}
};
}
// src/load-json.ts
async function loadJson(basename) {
if (typeof process === "undefined" || !process.versions?.node) {
return null;
}
try {
const { readFileSync } = await import("fs");
const { fileURLToPath } = await import("url");
const thisFile = fileURLToPath(import.meta.url);
const dir = thisFile.slice(0, thisFile.lastIndexOf("/"));
return JSON.parse(readFileSync(`${dir}/${basename}.json`, "utf8"));
} catch {
return null;
}
}
// src/frequency.ts
var loader = createLazyLoader(async () => {
const json = await loadJson("data/word-frequencies");
let raw;
if (json === null) {
const mod = await import("./word-frequencies-CWZLI3FK.js");
raw = mod.default;
} else {
raw = json;
}
const map = /* @__PURE__ */ new Map();
for (const [word, count] of Object.entries(raw)) {
map.set(word.toLowerCase(), count);
}
return { map, raw };
}, "word frequencies");
function getWordFrequency(word) {
if (!loader.isLoaded()) {
return void 0;
}
return loader.get().map.get(word.toLowerCase());
}
async function loadFrequencies() {
const data = await loader.load();
return data.raw;
}
var COMMON_CONTRACTIONS = /* @__PURE__ */ new Set([
"ain't",
"aren't",
// n't contractions
"can't",
"could've",
"couldn't",
"didn't",
"doesn't",
"don't",
"hadn't",
"hasn't",
"haven't",
"he'd",
"he'll",
// 's contractions (is/has)
"he's",
"here's",
"how's",
// 'd contractions
"i'd",
// 'll contractions
"i'll",
// 'm contractions
"i'm",
// 've contractions
"i've",
"isn't",
"it'd",
"it'll",
"it's",
"let's",
"might've",
"mightn't",
"must've",
"mustn't",
"needn't",
"shan't",
"she'd",
"she'll",
"she's",
"should've",
"shouldn't",
"that'd",
"that'll",
"that's",
"there'll",
"there's",
"they'd",
"they'll",
"they're",
"they've",
"wasn't",
"we'd",
"we'll",
"we're",
"we've",
"weren't",
"what'll",
"what's",
"where's",
"who'd",
"who'll",
"who's",
"won't",
"would've",
"wouldn't",
"you'd",
"you'll",
// 're contractions
"you're",
"you've"
]);
var CONTRACTION_FREQUENCY_BOOST = 1e7;
var UNKNOWN_CONTRACTION_SCORE = -5e6;
var NUMERIC_WORD_PENALTY = 1e6;
var UNKNOWN_WORD_PENALTY = 1e5;
var NUMERIC_REGEX = /\d/;
function scoreWord(word) {
const lower = word.toLowerCase();
const frequency = loader.isLoaded() ? loader.get().map.get(lower) : void 0;
const isCommonContraction = COMMON_CONTRACTIONS.has(lower);
if (frequency !== void 0) {
return isCommonContraction ? -frequency - CONTRACTION_FREQUENCY_BOOST : -frequency;
}
if (isCommonContraction) {
return UNKNOWN_CONTRACTION_SCORE;
}
if (NUMERIC_REGEX.test(word)) {
return NUMERIC_WORD_PENALTY + word.length;
}
return UNKNOWN_WORD_PENALTY + word.length;
}
function sortByFrequency(words) {
return words.toSorted((a, b) => scoreWord(a) - scoreWord(b));
}
// src/loader.ts
var loader2 = createLazyLoader(async () => {
const json = await loadJson("cmudict");
if (json !== null) {
const dict2 = json;
Object.setPrototypeOf(dict2, null);
return dict2;
}
const mod = await import("./cmudict-BIVBNNNO.js");
const dict = mod.default;
Object.setPrototypeOf(dict, null);
return dict;
}, "CMU dictionary");
var loadDictionary = loader2.load.bind(loader2);
var getDictionary = loader2.get.bind(loader2);
var isDictionaryLoaded = loader2.isLoaded.bind(loader2);
// src/lookup.ts
function lookupPronunciation(word) {
return lookupPronunciationLower(word.toLowerCase());
}
function lookupPronunciationLower(key) {
const custom = getCustomPronunciation(key);
if (custom) {
return custom;
}
const dict = getDictionary();
if (!(key in dict)) {
return null;
}
return dict[key];
}
// src/reverse.ts
import { stripStress } from "@ingglish/phonemes";
var loader3 = createLazyLoader(async () => {
const json = await loadJson("reverse-cmudict");
let dict;
if (json === null) {
const mod = await import("./reverse-cmudict-JNRLKABR.js");
dict = mod.default;
} else {
dict = json;
}
await loadFrequencies();
for (const [word, phonemes] of Object.entries(CUSTOM_PRONUNCIATIONS)) {
const key = phonemes.map((p) => stripStress(p)).join(" ");
const existing = dict[key];
if (existing === void 0) {
dict[key] = [word];
} else if (!existing.includes(word)) {
existing.push(word);
dict[key] = sortByFrequency(existing);
}
}
return dict;
}, "Reverse dictionary");
var loadReverseDictionary = loader3.load.bind(loader3);
var getReverseDictionary = loader3.get.bind(loader3);
function lookupPhonemeKey(key) {
return getReverseDictionary()[key];
}
export {
CUSTOM_PRONUNCIATIONS,
getCustomPronunciation,
getDictionary,
getWordFrequency,
hasCustomPronunciation,
isDictionaryLoaded,
loadDictionary,
loadFrequencies,
loadReverseDictionary,
lookupPhonemeKey,
lookupPronunciation,
lookupPronunciationLower,
sortByFrequency
};
+6
View File
@@ -0,0 +1,6 @@
// src/reverse-cmudict.js
var reverseCmudict = JSON.parse(`{"B AW T":["bout","'bout"],"K AH Z":["'cause"],"K AO R S":["course","coarse","corse","'course"],"K Y UW Z":["cues","ques","queues","q's","q.s","kuse","kuze","q.'s","'cuse"],"AH M":["um","umm","'m","'em"],"F R IH S K OW":["'frisco"],"G EH N":["'gain"],"K EY":["k","kay","cay","k.","khe","'kay","kaye","quaye"],"AH N":["un","'n"],"R AW N D":["round","'round"],"EH S":["s","es","esse","ess","'s","s."],"T IH L":["till","til","'til"],"T IH Z":["tis","'tis"],"T W AH Z":["twas","'twas"],"AH":["a","uh","uhh"],"EY Z":["a's","a.s","a.'s"],"EY":["ay","ae","a."],"EY D IY":["ady","a.d.","adey","eydie"],"EY EH M":["a.m."],"T R IH P AH L EY":["aaa"],"AA B ER G":["aaberg"],"AA K AH N":["aachen"],"AA K AH N ER":["aachener"],"AA K ER":["aaker","ocker"],"AO L B AO R G # place, danish":["aalborg"],"AE L B ER G # place, dutch":["aalburg"],"AE L AH N # place, german":["aalen"],"AA L IY AA":["aaliyah"],"AA L S EH TH":["aalseth"],"AA L S M IH R # place, dutch":["aalsmeer"],"AA L T OW # name, finnish":["aalto"],"AA M AH T":["aamodt"],"AA NG K AO R":["encore","oncor","aancor"],"AA R D EH M AH":["aardema"],"AA R D V AA R K":["aardvark"],"AA R D V AA R K S":["aardvarks"],"AA R G":["argh","aargh"],"AA HH UW S":["aarhus"],"EH R AH N":["aaron","aran","aron","ehren"],"EH R AH N Z":["arens","aarons","aaron's"],"EH R AH N S AH N":["aronson","aaronson"],"EH R AH N S AH N Z":["aaronson's"],"AA R T IY":["arty","aarti","artie"],"AA S":["os","aase"],"AA S AH N":["aasen","osten"],"AE B":["ab"],"EY B IY EY":["aba"],"AH B AA B AH":["ababa"],"AE B AH K AH":["abacha"],"AH B AE K":["aback"],"AE B AH K OW":["abaco"],"AE B AH K AH S":["abacus"],"AH B AA D":["abad"],"AH B AE D AH K AH":["abadaka"],"AH B AE D IY":["abadi","abadie"],"AH B EH R":["abair"],"AH B AA L K IH N":["abalkin"],"AE B AH L OW N IY":["abalone"],"AE B AH L OW N IY Z":["abalones"],"AA B AA L OW Z":["abalos"],"AH B AE N D AH N":["abandon"],"AH B AE N D AH N D":["abandoned"],"AH B AE N D AH N IH NG":["abandoning"],"AH B AE N D AH N M AH N T":["abandonment"],"AH B AE N D AH N M AH N T S":["abandonments"],"AH B AE N D AH N Z":["abandons"],"AH B AE N T OW":["abanto"],"AH B AA R K AH":["abarca"],"AA B AA R IY":["abare"],"AE B AH S K AH L":["abascal"],"AH B AE SH":["abash"],"AH B AE SH T":["abashed"],"AH B EY ZH Y AH":["abasia"],"AH B EY T":["abate"],"AH B EY T IH D":["abated"],"AH B EY T M AH N T":["abatement"],"AH B EY T M AH N T S":["abatements"],"AH B EY T S":["abates"],"AH B EY T IH NG":["abating"],"AE B AH T W AA R":["abattoir"],"AE B AH":["abba"],"AH B AA D OW":["abbado"],"AH B AA S":["abbas"],"AA B AA S IY":["abbasi"],"AA B EY T":["abbate"],"AA B AA T IY EH L OW":["abbatiello"],"AE B IY":["abby","abbey","abbe","abie","abbie"],"AE B AH N HH AW S":["abbenhaus"],"AH B EH T":["abet","abbett"],"AE B V IH L":["abbeville"],"AE B IY Z":["abbey's"],"AE B IH T":["abbitt"],"AE B AH T":["abbott","abbot"],"AE B AH T S T AW N":["abbotstown","abbottstown"],"AE B AH T S":["abbott's"],"AH B UW D":["abood","abboud"],"AH B R IY V IY EY T":["abbreviate"],"AH B R IY V IY EY T IH D":["abbreviated"],"AH B R IY V IY EY T S":["abbreviates"],"AH B R IY V IY EY T IH NG":["abbreviating"],"AH B R IY V IY EY SH AH N":["abbreviation"],"AH B R IY V IY EY SH AH N Z":["abbreviations"],"AA B R UW T S EY Z IY":["abruzzese","abbruzzese"],"AE B Z":["abbs"],"EY B IY S IY":["abc"],"EY B IY S IY Z":["abcs","abc's"],"AE B K OW":["abco"],"AE B K OW T EH K":["abcotek"],"EY B IY D IY":["abd"],"AE B D AE L AH":["abdalla","abdallah"],"AE B D EH L":["abdel"],"AE B D EH L AH":["abdella"],"AE B D AH K EY T":["abdicate"],"AE B D AH K EY T IH D":["abdicated"],"AE B D AH K EY T S":["abdicates"],"AE B D IH K EY T IH NG":["abdicating"],"AE B D IH K EY SH AH N":["abdication"],"AE B D N ER":["abdnor"],"AE B D OW":["abdo"],"AE B D AA L AH":["abdollah"],"AE B D OW M AH N":["abdomen"],"AE B D AA M AH N AH L":["abdominal"],"AE B D AH K T":["abduct"],"AE B D AH K T IH D":["abducted"],"AE B D AH K T IY":["abductee"],"AE B D AH K T IY Z":["abductees"],"AE B D AH K T IH NG":["abducting"],"AE B D AH K SH AH N":["abduction"],"AE B D AH K SH AH N Z":["abductions"],"AE B D AH K T ER":["abductor"],"AE B D AH K T ER Z":["abductors"],"AE B D AH K T S":["abducts"],"AE B D UW L":["abdul"],"AE B D UW L AH Z IY Z":["abdulaziz"],"AA B D UW L AH":["abdulla"],"AE B D AH L AH":["abdullah"],"EY B":["abe"],"AH B EH D":["abed"],"AH B EH D IY":["abedi"],"AH B IY":["abee"],"EY B AH L":["able","abel","abell"],"AA B EH L AH":["abela"],"AE B IH L ER D":["abelard"],"AH B EH L":["abele"],"AH B EH L Z":["abeles"],"AH B EH L AH":["abella"],"AE B IH L N":["abeln"],"AE B AH L OW":["abelow"],"EY B AH L Z":["abels","ables"],"AE B IH L S AH N":["abelson"],"AE B EH N D":["abend"],"AE B IH N D R AO TH":["abendroth"],"EY B ER":["aber","aybar"],"AE B ER K R AA M B IY":["abercrombie"],"AE B ER D IY N":["aberdeen"],"EY B ER F ER D":["aberford"],"AE B ER G":["aberg"],"AE B ER AH L":["aberle"],"AE B ER M IH N":["abermin"],"AE B ER N AE TH IY":["abernathy"]," Line truncated
var reverse_cmudict_default = reverseCmudict;
export {
reverse_cmudict_default as default
};
+6
View File
@@ -0,0 +1,6 @@
// src/data/word-frequencies.js
var WORD_FREQUENCIES = JSON.parse(`{"you":2134713,"I":2038529,"the":1501908,"to":1156570,"s":1057301,"a":1041179,"it":963712,"t":733338,"that":719677,"and":682780,"of":590439,"What":501965,"in":498444,"me":471339,"is":459663,"we":459607,"this":406915,"he":389497,"on":354742,"for":351650,"my":344899,"m":343245,"your":328715,"don":321085,"have":314232,"do":312915,"re":311072,"No":304549,"be":293085,"know":291780,"was":288391,"not":276673,"can":267620,"are":265672,"all":263255,"with":257465,"just":242206,"get":233772,"here":230788,"but":225291,"ll":224097,"there":221754,"so":216452,"they":209250,"right":204428,"like":203947,"out":197131,"go":193445,"she":190377,"up":187170,"about":185206,"if":180610,"him":177710,"got":168631,"Oh":167781,"at":164072,"now":163333,"Come":160190,"one":156684,"How":155867,"Well":152523,"Yeah":152262,"her":144627,"want":140718,"think":137261,"good":133117,"see":130393,"Let":123381,"did":119410,"Why":114687,"who":113370,"as":113068,"his":108364,"will":108306,"going":108288,"from":103992,"when":103739,"back":102467,"Okay":102320,"Yes":101835,"gonna":101804,"d":101335,"time":99890,"look":99311,"take":96443,"an":95071,"man":94133,"Where":93341,"them":90720,"would":90162,"been":88573,"some":88089,"Hey":88079,"tell":87949,"or":86970,"us":86478,"had":85472,"were":84804,"say":83629,"could":83109,"didn":80623,"something":76508,"really":76508,"down":76004,"then":75966,"little":73766,"way":72661,"our":71425,"make":70775,"too":69950,"never":69490,"by":68364,"over":67488,"more":66228,"need":66040,"mean":63443,"very":63304,"off":60155,"Mr":60098,"sorry":59566,"give":59559,"has":57830,"Thank":56877,"love":56864,"said":56531,"am":56438,"people":56252,"please":56149,"sure":56091,"any":56068,"thing":55522,"only":55269,"because":54622,"two":54384,"should":54159,"doing":52492,"much":49636,"sir":49188,"Maybe":47249,"help":46977,"anything":46270,"these":46104,"God":46061,"even":44672,"night":44168,"call":43931,"talk":43605,"nothing":43534,"into":43074,"first":42869,"find":42379,"wait":42343,"put":42251,"great":41864,"thought":41232,"day":40893,"work":40699,"life":40629,"before":40501,"better":40494,"again":40428,"still":40225,"home":39491,"guy":38893,"won":38729,"those":38404,"than":37679,"around":37573,"other":37505,"away":37276,"new":36913,"last":36878,"uh":36579,"ever":36170,"stop":36071,"keep":35846,"told":35679,"must":35661,"things":35337,"big":34824,"after":34812,"long":34433,"does":34002,"always":33418,"their":33413,"everything":33399,"nice":33125,"name":32735,"money":32679,"doesn":32435,"guys":32198,"feel":31989,"believe":31882,"Thanks":31789,"old":31056,"place":30736,"fine":30502,"kind":30125,"isn":29886,"Hello":29857,"lot":29066,"years":29003,"made":28626,"leave":28596,"Hi":28464,"girl":28413,"hear":28323,"father":28279,"through":28026,"every":28007,"bad":27804,"Listen":27784,"remember":27666,"three":27654,"boy":27021,"coming":26878,"wrong":26678,"might":26334,"stay":26298,"house":26214,"may":26080,"baby":25978,"another":25970,"Ok":25928,"Dad":25870,"gotta":25852,"wanna":25796,"wanted":25616,"enough":25568,"talking":25385,"happened":24994,"show":24906,"course":24848,"being":24781,"care":24748,"done":24737,"getting":24719,"mind":24715,"left":24707,"ask":24640,"car":24636,"understand":24605,"mother":24476,"which":24339,"try":24314,"shit":24207,"hell":24012,"Miss":23850,"came":23650,"wouldn":23628,"own":23419,"world":23216,"guess":23153,"next":23090,"kill":23081,"else":22907,"dead":22898,"trying":22849,"someone":22752,"real":22583,"room":22415,"morning":22389,"huh":22350,"hold":22273,"ain":22248,"woman":22166,"yourself":22151,"today":22124,"looking":22066,"wasn":21984,"Mom":21950,"friend":21384,"move":21325,"same":21276,"job":21063,"tonight":21047,"went":20987,"son":20949,"best":20623,"saw":20527,"found":20196,"pretty":20003,"ready":19778,"heard":19775,"whole":19660,"seen":19633,"together":19553,"fuck":19307,"minute":19252,"men":19011,"head":18947,"matter":18900,"haven":18844,"knew":18817,"Excuse":18773,"many":18331,"idea":18311,"without":18087,"play":18081,"family":18067,"meet":17966,"most":17889,"run":17878,"while":17821,"wife":17795,"once":17589,"live":17574,"somebody":17571,"everybody":17555,"used":17551,"use":17536,"myself":17470,"took":17454,"yet":17428,"start":17345,"called":17341,"couldn":17336,"kid":17299,"tomorrow":17134,"happy":16993,"school":16989,"problem":16833,"watch":16831,"bring":16685,"fucking":16603,"actually":16439,"business":16371,"says":16356,"hope":16352,"open":16341,"already":16246,"since":16064,"looks":15886,"sit":15879,"Mrs":15858,"cause":15812,"alone":15735,"hard":15700,"wants":15655,"stuff":15653,"turn":15630,"days":15592,"friends":15578,"until":15426,"few":15393,"kids":15356,"honey":15325,"Dr":15194,"gone":15135,"both":15062,"door":14895,"later":14889,"saying":14874,"such":14852,"killed":14792,"having":14752,"face":14747,"worry":14638,"ago":14592,"five":14558,"second":14513,"brother":14481,"damn":14460,"case":14403,"thinking":14353,"probably":14323,"beautiful":14266," Line truncated
var word_frequencies_default = WORD_FREQUENCIES;
export {
word_frequencies_default as default
};
+54
View File
@@ -0,0 +1,54 @@
{
"name": "@ingglish/dictionary",
"version": "0.1.1",
"description": "CMU dictionary loading, lookup, and word frequency scoring for Ingglish",
"type": "module",
"main": "./dist/index.js",
"module": "./dist/index.mjs",
"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": {
"prebuild": "npm run update-dictionaries",
"pretest": "npm run update-dictionaries",
"build": "tsup",
"build:fast": "npm run update-dictionaries && tsup src/index.ts --format esm",
"lint": "eslint --cache src",
"test": "vitest run --no-color",
"update-dictionaries": "node scripts/ensure-dictionaries.cjs",
"prepublishOnly": "npm run build"
},
"dependencies": {
"@ingglish/phonemes": "^0.1.0",
"subtlex-word-frequencies": "^2.0.0"
},
"author": "Paul Tarjan",
"license": "MIT",
"repository": {
"type": "git",
"url": "git+https://github.com/ptarjan/ingglish.git",
"directory": "packages/dictionary"
},
"homepage": "https://github.com/ptarjan/ingglish#readme",
"bugs": {
"url": "https://github.com/ptarjan/ingglish/issues"
}
}
+654
View File
@@ -0,0 +1,654 @@
"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, {
KNOWN_INITIALISMS: () => KNOWN_INITIALISMS,
LETTER_PHONEMES: () => LETTER_PHONEMES,
diagnoseUnknown: () => diagnoseUnknown,
isInitialism: () => isInitialism,
matchBritish: () => matchBritish,
parseInitialismWithSuffix: () => parseInitialismWithSuffix,
translateAsAcronym: () => translateAsAcronym,
translateUnknown: () => translateUnknown
});
module.exports = __toCommonJS(index_exports);
var import_dictionary4 = require("@ingglish/dictionary");
var import_g2p = require("@ingglish/g2p");
var import_phonemes5 = require("@ingglish/phonemes");
// src/acronyms.ts
var import_phonemes = require("@ingglish/phonemes");
var INITIALISM_EXPANSIONS = {
ac: ["alternating", "current"],
ad: ["anno", "domini"],
afk: ["away", "from", "keyboard"],
// AI / ML
ai: ["artificial", "intelligence"],
aka: ["also", "known", "as"],
am: ["ante", "meridiem"],
api: ["application", "programming", "interface"],
asap: ["as", "soon", "as", "possible"],
atm: ["automated", "teller", "machine"],
aws: ["amazon", "web", "services"],
b2b: ["business", "to", "business"],
b2c: ["business", "to", "consumer"],
bc: ["before", "christ"],
bdd: ["behavior", "driven", "development"],
brb: ["be", "right", "back"],
btw: ["by", "the", "way"],
byob: ["bring", "your", "own", "bottle"],
cd: ["continuous", "deployment"],
cdn: ["content", "delivery", "network"],
// Business / titles
ceo: ["chief", "executive", "officer"],
cfo: ["chief", "financial", "officer"],
ci: ["continuous", "integration"],
cia: ["central", "intelligence", "agency"],
cio: ["chief", "information", "officer"],
cli: ["command", "line", "interface"],
cmo: ["chief", "marketing", "officer"],
cms: ["content", "management", "system"],
cnn: ["convolutional", "neural", "network"],
coo: ["chief", "operating", "officer"],
cors: ["cross", "origin", "resource", "sharing"],
cpr: ["cardiopulmonary", "resuscitation"],
cpu: ["central", "processing", "unit"],
crm: ["customer", "relationship", "management"],
crud: ["create", "read", "update", "delete"],
cso: ["chief", "security", "officer"],
css: ["cascading", "style", "sheets"],
csv: ["comma", "separated", "values"],
cto: ["chief", "technology", "officer"],
dc: ["direct", "current"],
ddos: ["distributed", "denial", "of", "service"],
dea: ["drug", "enforcement", "administration"],
diy: ["do", "it", "yourself"],
dj: ["disc", "jockey"],
dmv: ["department", "of", "motor", "vehicles"],
// Medical / science
dna: ["deoxyribonucleic", "acid"],
dns: ["domain", "name", "system"],
eod: ["end", "of", "day"],
epa: ["environmental", "protection", "agency"],
er: ["emergency", "room"],
erp: ["enterprise", "resource", "planning"],
eta: ["estimated", "time", "of", "arrival"],
etl: ["extract", "transform", "load"],
eu: ["european", "union"],
faq: ["frequently", "asked", "questions"],
// Government / organizations
fbi: ["federal", "bureau", "of", "investigation"],
fda: ["food", "and", "drug", "administration"],
ftp: ["file", "transfer", "protocol"],
fyi: ["for", "your", "information"],
gan: ["generative", "adversarial", "network"],
gcp: ["google", "cloud", "platform"],
gif: ["graphics", "interchange", "format"],
gps: ["global", "positioning", "system"],
gpt: ["generative", "pre-trained", "transformer"],
gpu: ["graphics", "processing", "unit"],
gui: ["graphical", "user", "interface"],
hdd: ["hard", "disk", "drive"],
hiv: ["human", "immunodeficiency", "virus"],
hr: ["human", "resources"],
html: ["hypertext", "markup", "language"],
http: ["hypertext", "transfer", "protocol"],
https: ["hypertext", "transfer", "protocol", "secure"],
iaas: ["infrastructure", "as", "a", "service"],
icu: ["intensive", "care", "unit"],
// General / common
id: ["identification"],
ide: ["integrated", "development", "environment"],
idk: ["i", "don't", "know"],
imo: ["in", "my", "opinion"],
io: ["input", "output"],
ip: ["internet", "protocol"],
iq: ["intelligence", "quotient"],
irs: ["internal", "revenue", "service"],
isp: ["internet", "service", "provider"],
it: ["information", "technology"],
jpeg: ["joint", "photographic", "experts", "group"],
// Media
jpg: ["joint", "photographic", "experts", "group"],
json: ["javascript", "object", "notation"],
jwt: ["json", "web", "token"],
kpi: ["key", "performance", "indicator"],
// Networking
lan: ["local", "area", "network"],
lcd: ["liquid", "crystal", "display"],
led: ["light", "emitting", "diode"],
llm: ["large", "language", "model"],
mc: ["master", "of", "ceremonies"],
// Security
mfa: ["multi", "factor", "authentication"],
ml: ["machine", "learning"],
mp3: ["moving", "picture", "experts", "group", "audio", "layer"],
mp4: ["moving", "picture", "experts", "group"],
mph: ["miles", "per", "hour"],
mri: ["magnetic", "resonance", "imaging"],
mvp: ["minimum", "viable", "product"],
nasa: ["national", "aeronautics", "space", "administration"],
// Acronyms pronounced as words (pass through unchanged like initialisms)
nato: ["north", "atlantic", "treaty", "organization"],
nda: ["non", "disclosure", "agreement"],
nic: ["network", "interface", "card"],
nlp: ["natural", "language", "processing"],
nosql: ["not", "only", "sql"],
nsa: ["national", "security", "agency"],
nsfw: ["not", "safe", "for", "work"],
nyc: ["new", "york", "city"],
omg: ["oh", "my", "god"],
ooo: ["out", "of", "office"],
// Development
oop: ["object", "oriented", "programming"],
orm: ["object", "relational", "mapping"],
os: ["operating", "system"],
otp: ["one", "time", "password"],
paas: ["platform", "as", "a", "service"],
pc: ["personal", "computer"],
pdf: ["portable", "document", "format"],
php: ["hypertext", "preprocessor"],
pm: ["post", "meridiem"],
png: ["portable", "network", "graphics"],
pov: ["point", "of", "view"],
pr: ["public", "relations"],
pto: ["paid", "time", "off"],
qa: ["quality", "assurance"],
rag: ["retrieval", "augmented", "generation"],
ram: ["random", "access", "memory"],
rfp: ["request", "for", "proposal"],
rip: ["rest", "in", "peace"],
rna: ["ribonucleic", "acid"],
rnn: ["recurrent", "neural", "network"],
roi: ["return", "on", "investment"],
rom: ["read", "only", "memory"],
rpm: ["revolutions", "per", "minute"],
rsvp: ["please", "respond"],
rv: ["recreational", "vehicle"],
// Cloud / services
saas: ["software", "as", "a", "service"],
sdk: ["software", "development", "kit"],
sftp: ["secure", "file", "transfer", "protocol"],
sla: ["service", "level", "agreement"],
// Database
sql: ["structured", "query", "language"],
ssd: ["solid", "state", "drive"],
ssh: ["secure", "shell"],
ssl: ["secure", "sockets", "layer"],
suv: ["sport", "utility", "vehicle"],
svg: ["scalable", "vector", "graphics"],
tba: ["to", "be", "announced"],
tbd: ["to", "be", "determined"],
tcp: ["transmission", "control", "protocol"],
tdd: ["test", "driven", "development"],
tldr: ["too", "long", "didn't", "read"],
tls: ["transport", "layer", "security"],
tv: ["television"],
uat: ["user", "acceptance", "testing"],
udp: ["user", "datagram", "protocol"],
// User interface / experience
ui: ["user", "interface"],
uk: ["united", "kingdom"],
un: ["united", "nations"],
uri: ["uniform", "resource", "identifier"],
// Tech / web
url: ["uniform", "resource", "locator"],
us: ["united", "states"],
usa: ["united", "states", "of", "america"],
// Hardware
usb: ["universal", "serial", "bus"],
uv: ["ultraviolet"],
ux: ["user", "experience"],
vp: ["vice", "president"],
vpn: ["virtual", "private", "network"],
wan: ["wide", "area", "network"],
xml: ["extensible", "markup", "language"],
xss: ["cross", "site", "scripting"]
};
var MAX_INITIALISM_LENGTH = 5;
var LETTER_PHONEMES = {
a: ["EY1"],
b: ["B", "IY1"],
c: ["S", "IY1"],
d: ["D", "IY1"],
e: ["IY1"],
f: ["EH1", "F"],
g: ["JH", "IY1"],
h: ["EY1", "CH"],
i: ["AY1"],
j: ["JH", "EY1"],
k: ["K", "EY1"],
l: ["EH1", "L"],
m: ["EH1", "M"],
n: ["EH1", "N"],
o: ["OW1"],
p: ["P", "IY1"],
q: ["K", "Y", "UW1"],
r: ["AA1", "R"],
s: ["EH1", "S"],
t: ["T", "IY1"],
u: ["Y", "UW1"],
v: ["V", "IY1"],
w: ["D", "AH1", "B", "AH0", "L", "Y", "UW0"],
x: ["EH1", "K", "S"],
y: ["W", "AY1"],
z: ["Z", "IY1"]
};
var KNOWN_INITIALISMS = new Set(Object.keys(INITIALISM_EXPANSIONS));
function isInitialism(word) {
if (word.length > MAX_INITIALISM_LENGTH) {
return false;
}
return KNOWN_INITIALISMS.has(word.toLowerCase());
}
var INITIALISM_SUFFIXES = ["'s", "s"];
function parseInitialismWithSuffix(word) {
for (const suffix of INITIALISM_SUFFIXES) {
if (word.length > suffix.length && word.endsWith(suffix)) {
const base = word.slice(0, -suffix.length);
if (isInitialism(base)) {
return { base, suffix };
}
}
}
return null;
}
function translateAsAcronym(word, format = "ingglish") {
const arpabet = [];
for (const char of word.toLowerCase()) {
const letterArpabet = LETTER_PHONEMES[char];
if (letterArpabet !== void 0) {
arpabet.push(...letterArpabet);
}
}
return (0, import_phonemes.arpabetToFormat)(arpabet, format);
}
// src/british.ts
var import_dictionary = require("@ingglish/dictionary");
var import_phonemes2 = require("@ingglish/phonemes");
var BRITISH_TO_AMERICAN = [
// -isation → -ization (must come before -ise)
{ pattern: /isation$/, replacement: "ization" },
// -ise → -ize (realise→realize, organise→organize)
{ pattern: /ise$/, replacement: "ize" },
// -our → -or (colour→color, favour→favor)
{ pattern: /our$/, replacement: "or" },
// -oured → -ored (coloured→colored, favoured→favored)
{ pattern: /oured$/, replacement: "ored" },
// -ouring → -oring (colouring→coloring)
{ pattern: /ouring$/, replacement: "oring" },
// -ourable → -orable (favourable→favorable)
{ pattern: /ourable$/, replacement: "orable" },
// -re → -er (centre→center, theatre→theater)
// Only after consonants to avoid matching normal -re words
{ pattern: /([a-z])re$/, replacement: "$1er" },
// -lled → -led (travelled→traveled, cancelled→canceled)
{ pattern: /lled$/, replacement: "led" },
// -lling → -ling (travelling→traveling, cancelling→canceling)
{ pattern: /lling$/, replacement: "ling" },
// -ller → -ler (traveller→traveler)
{ pattern: /ller$/, replacement: "ler" },
// -ence → -ense (defence→defense, offence→offense)
{ pattern: /ence$/, replacement: "ense" },
// -ogue → -og (catalogue→catalog, dialogue→dialog)
{ pattern: /ogue$/, replacement: "og" },
// -ae- → -e- (anaesthetic→anesthetic, paediatric→pediatric)
{ pattern: /ae/, replacement: "e" },
// -oe- → -e- (foetus→fetus, oestrogen→estrogen)
{ pattern: /oe/, replacement: "e" },
// -ey → -y (curtsey→curtsy)
{ pattern: /ey$/, replacement: "y" },
// grey → gray
{ pattern: /grey/, replacement: "gray" }
];
function matchBritish(word) {
const lower = word.toLowerCase();
for (const { pattern, replacement } of BRITISH_TO_AMERICAN) {
if (pattern.test(lower)) {
const american = lower.replace(pattern, replacement);
if (american !== lower) {
const phonemes = (0, import_dictionary.lookupPronunciation)(american);
if (phonemes) {
return { american, phonemes };
}
}
}
}
return null;
}
function translateAsBritish(word, format = "ingglish") {
const match = matchBritish(word);
if (match === null) {
return null;
}
return (0, import_phonemes2.arpabetToFormat)(match.phonemes, format);
}
// src/compounds.ts
var import_dictionary2 = require("@ingglish/dictionary");
var import_phonemes3 = require("@ingglish/phonemes");
function capitalize(str) {
if (str.length === 0) {
return str;
}
return str.charAt(0).toUpperCase() + str.slice(1);
}
function isUpperCase(char) {
return char === char.toUpperCase() && char !== char.toLowerCase();
}
var MIN_PART_LENGTH = 3;
var MIN_PART_FREQUENCY = 500;
var MAX_PART_LENGTH = 15;
function dpDecompose(word) {
const n = word.length;
const dp = Array.from({
length: n + 1
});
dp[0] = { parts: [], score: 0 };
for (let i = MIN_PART_LENGTH; i <= n; i++) {
for (let j = Math.max(0, i - MAX_PART_LENGTH); j <= i - MIN_PART_LENGTH; j++) {
if (j === 0 && i === n) {
continue;
}
const prev = dp[j];
if (prev === void 0) {
continue;
}
const chunk = word.slice(j, i);
const phonemes = lookupWord(chunk);
if (!phonemes) {
continue;
}
const freq = (0, import_dictionary2.getWordFrequency)(chunk);
if (freq === void 0 || freq < MIN_PART_FREQUENCY) {
continue;
}
const newScore = prev.score + freq;
const newParts = prev.parts.length + 1;
const current = dp[i];
if (current === void 0 || newParts < current.parts.length || newParts === current.parts.length && newScore > current.score) {
dp[i] = { parts: [...prev.parts, chunk], score: newScore };
}
}
}
const result = dp[n];
if (result === void 0 || result.parts.length < 2) {
return null;
}
return result.parts;
}
function translateAsCompound(word, format = "ingglish") {
const lowerWord = word.toLowerCase();
if (lowerWord.length < 6) {
return null;
}
const parts = dpDecompose(lowerWord);
if (!parts) {
return null;
}
const translations = [];
let pos = 0;
for (const part of parts) {
const phonemes = lookupWord(part);
if (!phonemes) {
return null;
}
let translated = (0, import_phonemes3.arpabetToFormat)(phonemes, format);
if ((0, import_phonemes3.getFormatPreservesCase)(format)) {
const originalPart = word.slice(pos, pos + part.length);
if (originalPart.length > 0 && isUpperCase(originalPart[0])) {
translated = capitalize(translated);
}
}
translations.push(translated);
pos += part.length;
}
return translations.join((0, import_phonemes3.getFormatJoinSeparator)(format));
}
function lookupWord(word) {
return (0, import_dictionary2.lookupPronunciation)(word);
}
// src/stemming.ts
var import_dictionary3 = require("@ingglish/dictionary");
var import_phonemes4 = require("@ingglish/phonemes");
var VOICELESS = /* @__PURE__ */ new Set(["CH", "F", "HH", "K", "P", "S", "SH", "T", "TH"]);
var SIBILANTS = /* @__PURE__ */ new Set(["CH", "JH", "S", "SH", "Z", "ZH"]);
function selectEdPhonemes(lastPhoneme) {
const base = (0, import_phonemes4.stripStress)(lastPhoneme);
if (base === "T" || base === "D") {
return ["IH0", "D"];
}
if (VOICELESS.has(base)) {
return ["T"];
}
return ["D"];
}
function selectSPhonemes(lastPhoneme) {
const base = (0, import_phonemes4.stripStress)(lastPhoneme);
if (SIBILANTS.has(base)) {
return ["IH0", "Z"];
}
if (VOICELESS.has(base)) {
return ["S"];
}
return ["Z"];
}
var INFLECTIONAL_SUFFIXES = /* @__PURE__ */ new Set([
"ed",
"er",
"es",
"est",
"ification",
"ify",
"ifying",
"ing",
"or",
"s"
]);
var SUFFIX_PHONEMES = [
// Long suffixes first (must come before shorter matches: -ification before -tion, -ifying before -ing)
{ phonemes: ["IH0", "F", "IH0", "K", "EY1", "SH", "AH0", "N"], suffix: "ification" },
{ phonemes: ["IH0", "F", "AY1", "IH0", "NG"], suffix: "ifying" },
{ phonemes: ["IH0", "F", "AY1"], suffix: "ify" },
// Verb suffixes
{ phonemes: ["IH0", "NG"], suffix: "ing" },
{ phonemes: null, suffix: "ed" },
// allomorph: T/D/IH0 D (selected dynamically)
{ phonemes: null, suffix: "es" },
// allomorph: same as -s (S/Z/IH0 Z based on stem)
{ phonemes: null, suffix: "s" },
// allomorph: S/Z/IH0 Z (selected dynamically)
// Noun suffixes
{ phonemes: ["SH", "AH0", "N"], suffix: "tion" },
{ phonemes: ["ZH", "AH0", "N"], suffix: "sion" },
{ phonemes: ["N", "AH0", "S"], suffix: "ness" },
{ phonemes: ["M", "AH0", "N", "T"], suffix: "ment" },
{ phonemes: ["IH0", "T", "IY0"], suffix: "ity" },
{ phonemes: ["ER0"], suffix: "er" },
{ phonemes: ["ER0"], suffix: "or" },
{ phonemes: ["IH0", "S", "T"], suffix: "ist" },
{ phonemes: ["IH0", "Z", "AH0", "M"], suffix: "ism" },
// Adjective suffixes
{ phonemes: ["L", "IY0"], suffix: "ly" },
{ phonemes: ["F", "AH0", "L"], suffix: "ful" },
{ phonemes: ["L", "AH0", "S"], suffix: "less" },
{ phonemes: ["AH0", "B", "AH0", "L"], suffix: "able" },
{ phonemes: ["AH0", "B", "AH0", "L"], suffix: "ible" },
{ phonemes: ["AH0", "S"], suffix: "ous" },
{ phonemes: ["IH0", "V"], suffix: "ive" },
{ phonemes: ["AH0", "L"], suffix: "al" },
{ phonemes: ["IH0", "K"], suffix: "ic" },
// Comparative/superlative
{ phonemes: ["AH0", "S", "T"], suffix: "est" },
// Additional suffixes
{ phonemes: ["AH0", "L", "IY0"], suffix: "ally" },
{ phonemes: ["AA1", "L", "AH0", "JH", "IY0"], suffix: "ology" },
{ phonemes: ["AY1", "Z"], suffix: "ize" },
{ phonemes: ["AY1", "Z"], suffix: "ise" }
];
var PREFIX_PHONEMES = [
{ phonemes: ["AH0", "N"], prefix: "un" },
{ phonemes: ["R", "IY0"], prefix: "re" },
{ phonemes: ["P", "R", "IY0"], prefix: "pre" },
{ phonemes: ["D", "IH0", "S"], prefix: "dis" },
{ phonemes: ["M", "IH0", "S"], prefix: "mis" },
{ phonemes: ["OW1", "V", "ER0"], prefix: "over" },
{ phonemes: ["AH1", "N", "D", "ER0"], prefix: "under" },
{ phonemes: ["AW1", "T"], prefix: "out" },
{ phonemes: ["AE1", "N", "T", "IY0"], prefix: "anti" },
{ phonemes: ["S", "UW1", "P", "ER0"], prefix: "super" }
];
function matchStemming(word) {
const lowerWord = word.toLowerCase();
for (const { phonemes: suffixArpabet, suffix } of SUFFIX_PHONEMES) {
if (lowerWord.endsWith(suffix) && lowerWord.length > suffix.length + 2) {
const stem = lowerWord.slice(0, -suffix.length);
for (const variant of getStemVariants(stem, suffix)) {
const baseArpabet = (0, import_dictionary3.lookupPronunciation)(variant);
if (baseArpabet) {
const resolvedSuffix = resolveSuffixPhonemes(suffix, suffixArpabet, baseArpabet);
return {
phonemes: [...baseArpabet, ...resolvedSuffix],
stem: variant,
suffix
};
}
}
}
}
for (const { phonemes: prefixArpabet, prefix } of PREFIX_PHONEMES) {
if (lowerWord.startsWith(prefix) && lowerWord.length > prefix.length + 2) {
const stem = lowerWord.slice(prefix.length);
const baseArpabet = (0, import_dictionary3.lookupPronunciation)(stem);
if (baseArpabet) {
return {
phonemes: [...prefixArpabet, ...baseArpabet],
prefix,
stem
};
}
}
}
return null;
}
function translateWithStemming(word, format = "ingglish") {
const match = matchStemming(word);
if (match === null) {
return null;
}
return (0, import_phonemes4.arpabetToFormat)(match.phonemes, format);
}
function getStemVariants(stem, suffix) {
const variants = [stem];
if (INFLECTIONAL_SUFFIXES.has(suffix)) {
variants.push(
stem + "e",
// hoping -> hope
stem.length > 1 ? stem.slice(0, -1) : stem,
// running -> run (double consonant)
stem.length > 0 ? stem + stem.at(-1) : stem
// big -> bigg (for adding -er)
);
}
if (stem.endsWith("i")) {
variants.push(stem.slice(0, -1) + "y");
}
variants.push(stem + "y");
return variants;
}
function resolveSuffixPhonemes(suffix, suffixArpabet, baseArpabet) {
if (suffixArpabet !== null) {
return suffixArpabet;
}
const lastPhoneme = baseArpabet.at(-1);
if (suffix === "ed") {
return selectEdPhonemes(lastPhoneme);
}
return selectSPhonemes(lastPhoneme);
}
// src/index.ts
function diagnoseUnknown(word) {
if (/(.)\1\1/.test(word) || !/[aeiouy]/i.test(word)) {
return null;
}
const { strategy } = translateUnknownCore(word, "ingglish");
switch (strategy) {
case "british": {
const m = matchBritish(word);
return { americanSpelling: m.american, phonemes: m.phonemes, strategy: "british" };
}
case "compound": {
return { parts: dpDecompose(word.toLowerCase()), strategy: "compound" };
}
case "custom": {
return { phonemes: (0, import_dictionary4.getCustomPronunciation)(word), strategy: "custom" };
}
case "g2p": {
return { strategy: "g2p", trace: (0, import_g2p.wordToArpabetTraced)(word) };
}
case "initialism": {
return { strategy: "initialism" };
}
case "stemming": {
const m = matchStemming(word);
return { prefix: m.prefix, stem: m.stem, strategy: "stemming", suffix: m.suffix };
}
}
}
function translateUnknown(word, format = "ingglish") {
return translateUnknownCore(word, format).translated;
}
function translateUnknownCore(word, format) {
const customPhonemes = (0, import_dictionary4.getCustomPronunciation)(word);
if (customPhonemes !== void 0) {
return { strategy: "custom", translated: (0, import_phonemes5.arpabetToFormat)(customPhonemes, format) };
}
if (isInitialism(word)) {
return { strategy: "initialism", translated: translateAsAcronym(word, format) };
}
const britishResult = translateAsBritish(word, format);
if (britishResult !== null && britishResult.length > 0) {
return { strategy: "british", translated: britishResult };
}
const compoundResult = translateAsCompound(word, format);
if (compoundResult !== null && compoundResult.length > 0) {
return { strategy: "compound", translated: compoundResult };
}
const stemmedResult = translateWithStemming(word, format);
if (stemmedResult !== null && stemmedResult.length > 0) {
return { strategy: "stemming", translated: stemmedResult };
}
return { strategy: "g2p", translated: (0, import_g2p.wordToPhonetic)(word, format) };
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
KNOWN_INITIALISMS,
LETTER_PHONEMES,
diagnoseUnknown,
isInitialism,
matchBritish,
parseInitialismWithSuffix,
translateAsAcronym,
translateUnknown
});
+119
View File
@@ -0,0 +1,119 @@
import { G2PTrace } from '@ingglish/g2p';
import { OutputFormat } from '@ingglish/phonemes';
/**
* Acronym and initialism handling.
*
* Handles words that should be spelled out letter-by-letter
* (e.g., URL -> "you-are-ell") vs acronyms pronounced as words
* (e.g., NASA -> "nasa").
*/
/**
* Phonemes for individual letters (for spelling out acronyms).
* Based on how native English speakers pronounce alphabet letters.
*/
declare const LETTER_PHONEMES: Record<string, string[]>;
/**
* Known initialisms - derived from INITIALISM_EXPANSIONS for consistency.
* These are pronounced as individual letters, NOT as words.
*
* Excludes acronyms pronounced as words like:
* - RAM (ram), ROM (rom), GIF (gif/jif), JPEG (jay-peg)
* - JSON (jason), SQL (sequel), NASA, NATO, SCUBA, LASER
*/
declare const KNOWN_INITIALISMS: Set<string>;
/**
* Checks if a word should be spelled out as individual letters (initialism).
* Only returns true for known initialisms - unknown uppercase words are NOT
* automatically treated as initialisms since they might be acronyms pronounced
* as words (like NASA, GIF, etc).
*/
declare function isInitialism(word: string): boolean;
/**
* Checks if a word is an initialism with a suffix (e.g., "IDs", "TVs", "URLs", "API's").
* Returns the base initialism and suffix if matched, null otherwise.
*/
declare function parseInitialismWithSuffix(word: string): null | {
base: string;
suffix: string;
};
/**
* Translates a word by spelling out each letter.
* Used for acronyms like URL, HTML, API.
*/
declare function translateAsAcronym(word: string, format?: OutputFormat): string;
/**
* British-to-American spelling conversion.
*
* Converts common British English spellings to their American
* equivalents and looks them up in the CMU dictionary.
* Used as a fallback when the British spelling isn't found.
*/
interface BritishMatch {
american: string;
phonemes: string[];
}
/**
* Matches a word against British-to-American spelling rules.
* Returns the American spelling and its phonemes, or null if no match.
*/
declare function matchBritish(word: string): BritishMatch | null;
/**
* Fallback strategies for translating unknown words.
*
* Called when a word isn't in the dictionary. Each strategy ultimately
* produces ARPAbet `string[]` (the pipeline IR), which is then passed
* through `arpabetToFormat()` for final output.
*
* Strategy order:
* 1. Custom pronunciations (tech terms, brand names)
* 2. Initialisms (spell out letters: URL -> you-are-ell)
* 3. British spelling normalization (colour -> color)
* 4. Compound word splitting (github -> git + hub)
* 5. Stemming (find known base word + known suffix)
* 6. Rule-based grapheme-to-phoneme
*/
type WordDiagnosis = {
americanSpelling: string;
phonemes: string[];
strategy: 'british';
} | {
parts: string[];
strategy: 'compound';
} | {
phonemes: string[];
strategy: 'custom';
} | {
prefix?: string;
stem: string;
strategy: 'stemming';
suffix?: string;
} | {
strategy: 'g2p';
trace: G2PTrace;
} | {
strategy: 'initialism';
};
/**
* Diagnoses an unknown word by determining which fallback strategy handles it
* and collecting diagnostic data for display.
*
* Returns null for obvious non-words (3+ repeated chars, no vowels).
*/
declare function diagnoseUnknown(word: string): null | WordDiagnosis;
/**
* Attempts all strategies to translate an unknown word.
*
* @param word The unknown word
* @param format The output format
* @returns The translated word
*/
declare function translateUnknown(word: string, format?: OutputFormat): string;
export { KNOWN_INITIALISMS, LETTER_PHONEMES, type WordDiagnosis, diagnoseUnknown, isInitialism, matchBritish, parseInitialismWithSuffix, translateAsAcronym, translateUnknown };
+119
View File
@@ -0,0 +1,119 @@
import { G2PTrace } from '@ingglish/g2p';
import { OutputFormat } from '@ingglish/phonemes';
/**
* Acronym and initialism handling.
*
* Handles words that should be spelled out letter-by-letter
* (e.g., URL -> "you-are-ell") vs acronyms pronounced as words
* (e.g., NASA -> "nasa").
*/
/**
* Phonemes for individual letters (for spelling out acronyms).
* Based on how native English speakers pronounce alphabet letters.
*/
declare const LETTER_PHONEMES: Record<string, string[]>;
/**
* Known initialisms - derived from INITIALISM_EXPANSIONS for consistency.
* These are pronounced as individual letters, NOT as words.
*
* Excludes acronyms pronounced as words like:
* - RAM (ram), ROM (rom), GIF (gif/jif), JPEG (jay-peg)
* - JSON (jason), SQL (sequel), NASA, NATO, SCUBA, LASER
*/
declare const KNOWN_INITIALISMS: Set<string>;
/**
* Checks if a word should be spelled out as individual letters (initialism).
* Only returns true for known initialisms - unknown uppercase words are NOT
* automatically treated as initialisms since they might be acronyms pronounced
* as words (like NASA, GIF, etc).
*/
declare function isInitialism(word: string): boolean;
/**
* Checks if a word is an initialism with a suffix (e.g., "IDs", "TVs", "URLs", "API's").
* Returns the base initialism and suffix if matched, null otherwise.
*/
declare function parseInitialismWithSuffix(word: string): null | {
base: string;
suffix: string;
};
/**
* Translates a word by spelling out each letter.
* Used for acronyms like URL, HTML, API.
*/
declare function translateAsAcronym(word: string, format?: OutputFormat): string;
/**
* British-to-American spelling conversion.
*
* Converts common British English spellings to their American
* equivalents and looks them up in the CMU dictionary.
* Used as a fallback when the British spelling isn't found.
*/
interface BritishMatch {
american: string;
phonemes: string[];
}
/**
* Matches a word against British-to-American spelling rules.
* Returns the American spelling and its phonemes, or null if no match.
*/
declare function matchBritish(word: string): BritishMatch | null;
/**
* Fallback strategies for translating unknown words.
*
* Called when a word isn't in the dictionary. Each strategy ultimately
* produces ARPAbet `string[]` (the pipeline IR), which is then passed
* through `arpabetToFormat()` for final output.
*
* Strategy order:
* 1. Custom pronunciations (tech terms, brand names)
* 2. Initialisms (spell out letters: URL -> you-are-ell)
* 3. British spelling normalization (colour -> color)
* 4. Compound word splitting (github -> git + hub)
* 5. Stemming (find known base word + known suffix)
* 6. Rule-based grapheme-to-phoneme
*/
type WordDiagnosis = {
americanSpelling: string;
phonemes: string[];
strategy: 'british';
} | {
parts: string[];
strategy: 'compound';
} | {
phonemes: string[];
strategy: 'custom';
} | {
prefix?: string;
stem: string;
strategy: 'stemming';
suffix?: string;
} | {
strategy: 'g2p';
trace: G2PTrace;
} | {
strategy: 'initialism';
};
/**
* Diagnoses an unknown word by determining which fallback strategy handles it
* and collecting diagnostic data for display.
*
* Returns null for obvious non-words (3+ repeated chars, no vowels).
*/
declare function diagnoseUnknown(word: string): null | WordDiagnosis;
/**
* Attempts all strategies to translate an unknown word.
*
* @param word The unknown word
* @param format The output format
* @returns The translated word
*/
declare function translateUnknown(word: string, format?: OutputFormat): string;
export { KNOWN_INITIALISMS, LETTER_PHONEMES, type WordDiagnosis, diagnoseUnknown, isInitialism, matchBritish, parseInitialismWithSuffix, translateAsAcronym, translateUnknown };
+626
View File
@@ -0,0 +1,626 @@
// src/index.ts
import { getCustomPronunciation } from "@ingglish/dictionary";
import { wordToArpabetTraced, wordToPhonetic } from "@ingglish/g2p";
import { arpabetToFormat as arpabetToFormat5 } from "@ingglish/phonemes";
// src/acronyms.ts
import { arpabetToFormat } from "@ingglish/phonemes";
var INITIALISM_EXPANSIONS = {
ac: ["alternating", "current"],
ad: ["anno", "domini"],
afk: ["away", "from", "keyboard"],
// AI / ML
ai: ["artificial", "intelligence"],
aka: ["also", "known", "as"],
am: ["ante", "meridiem"],
api: ["application", "programming", "interface"],
asap: ["as", "soon", "as", "possible"],
atm: ["automated", "teller", "machine"],
aws: ["amazon", "web", "services"],
b2b: ["business", "to", "business"],
b2c: ["business", "to", "consumer"],
bc: ["before", "christ"],
bdd: ["behavior", "driven", "development"],
brb: ["be", "right", "back"],
btw: ["by", "the", "way"],
byob: ["bring", "your", "own", "bottle"],
cd: ["continuous", "deployment"],
cdn: ["content", "delivery", "network"],
// Business / titles
ceo: ["chief", "executive", "officer"],
cfo: ["chief", "financial", "officer"],
ci: ["continuous", "integration"],
cia: ["central", "intelligence", "agency"],
cio: ["chief", "information", "officer"],
cli: ["command", "line", "interface"],
cmo: ["chief", "marketing", "officer"],
cms: ["content", "management", "system"],
cnn: ["convolutional", "neural", "network"],
coo: ["chief", "operating", "officer"],
cors: ["cross", "origin", "resource", "sharing"],
cpr: ["cardiopulmonary", "resuscitation"],
cpu: ["central", "processing", "unit"],
crm: ["customer", "relationship", "management"],
crud: ["create", "read", "update", "delete"],
cso: ["chief", "security", "officer"],
css: ["cascading", "style", "sheets"],
csv: ["comma", "separated", "values"],
cto: ["chief", "technology", "officer"],
dc: ["direct", "current"],
ddos: ["distributed", "denial", "of", "service"],
dea: ["drug", "enforcement", "administration"],
diy: ["do", "it", "yourself"],
dj: ["disc", "jockey"],
dmv: ["department", "of", "motor", "vehicles"],
// Medical / science
dna: ["deoxyribonucleic", "acid"],
dns: ["domain", "name", "system"],
eod: ["end", "of", "day"],
epa: ["environmental", "protection", "agency"],
er: ["emergency", "room"],
erp: ["enterprise", "resource", "planning"],
eta: ["estimated", "time", "of", "arrival"],
etl: ["extract", "transform", "load"],
eu: ["european", "union"],
faq: ["frequently", "asked", "questions"],
// Government / organizations
fbi: ["federal", "bureau", "of", "investigation"],
fda: ["food", "and", "drug", "administration"],
ftp: ["file", "transfer", "protocol"],
fyi: ["for", "your", "information"],
gan: ["generative", "adversarial", "network"],
gcp: ["google", "cloud", "platform"],
gif: ["graphics", "interchange", "format"],
gps: ["global", "positioning", "system"],
gpt: ["generative", "pre-trained", "transformer"],
gpu: ["graphics", "processing", "unit"],
gui: ["graphical", "user", "interface"],
hdd: ["hard", "disk", "drive"],
hiv: ["human", "immunodeficiency", "virus"],
hr: ["human", "resources"],
html: ["hypertext", "markup", "language"],
http: ["hypertext", "transfer", "protocol"],
https: ["hypertext", "transfer", "protocol", "secure"],
iaas: ["infrastructure", "as", "a", "service"],
icu: ["intensive", "care", "unit"],
// General / common
id: ["identification"],
ide: ["integrated", "development", "environment"],
idk: ["i", "don't", "know"],
imo: ["in", "my", "opinion"],
io: ["input", "output"],
ip: ["internet", "protocol"],
iq: ["intelligence", "quotient"],
irs: ["internal", "revenue", "service"],
isp: ["internet", "service", "provider"],
it: ["information", "technology"],
jpeg: ["joint", "photographic", "experts", "group"],
// Media
jpg: ["joint", "photographic", "experts", "group"],
json: ["javascript", "object", "notation"],
jwt: ["json", "web", "token"],
kpi: ["key", "performance", "indicator"],
// Networking
lan: ["local", "area", "network"],
lcd: ["liquid", "crystal", "display"],
led: ["light", "emitting", "diode"],
llm: ["large", "language", "model"],
mc: ["master", "of", "ceremonies"],
// Security
mfa: ["multi", "factor", "authentication"],
ml: ["machine", "learning"],
mp3: ["moving", "picture", "experts", "group", "audio", "layer"],
mp4: ["moving", "picture", "experts", "group"],
mph: ["miles", "per", "hour"],
mri: ["magnetic", "resonance", "imaging"],
mvp: ["minimum", "viable", "product"],
nasa: ["national", "aeronautics", "space", "administration"],
// Acronyms pronounced as words (pass through unchanged like initialisms)
nato: ["north", "atlantic", "treaty", "organization"],
nda: ["non", "disclosure", "agreement"],
nic: ["network", "interface", "card"],
nlp: ["natural", "language", "processing"],
nosql: ["not", "only", "sql"],
nsa: ["national", "security", "agency"],
nsfw: ["not", "safe", "for", "work"],
nyc: ["new", "york", "city"],
omg: ["oh", "my", "god"],
ooo: ["out", "of", "office"],
// Development
oop: ["object", "oriented", "programming"],
orm: ["object", "relational", "mapping"],
os: ["operating", "system"],
otp: ["one", "time", "password"],
paas: ["platform", "as", "a", "service"],
pc: ["personal", "computer"],
pdf: ["portable", "document", "format"],
php: ["hypertext", "preprocessor"],
pm: ["post", "meridiem"],
png: ["portable", "network", "graphics"],
pov: ["point", "of", "view"],
pr: ["public", "relations"],
pto: ["paid", "time", "off"],
qa: ["quality", "assurance"],
rag: ["retrieval", "augmented", "generation"],
ram: ["random", "access", "memory"],
rfp: ["request", "for", "proposal"],
rip: ["rest", "in", "peace"],
rna: ["ribonucleic", "acid"],
rnn: ["recurrent", "neural", "network"],
roi: ["return", "on", "investment"],
rom: ["read", "only", "memory"],
rpm: ["revolutions", "per", "minute"],
rsvp: ["please", "respond"],
rv: ["recreational", "vehicle"],
// Cloud / services
saas: ["software", "as", "a", "service"],
sdk: ["software", "development", "kit"],
sftp: ["secure", "file", "transfer", "protocol"],
sla: ["service", "level", "agreement"],
// Database
sql: ["structured", "query", "language"],
ssd: ["solid", "state", "drive"],
ssh: ["secure", "shell"],
ssl: ["secure", "sockets", "layer"],
suv: ["sport", "utility", "vehicle"],
svg: ["scalable", "vector", "graphics"],
tba: ["to", "be", "announced"],
tbd: ["to", "be", "determined"],
tcp: ["transmission", "control", "protocol"],
tdd: ["test", "driven", "development"],
tldr: ["too", "long", "didn't", "read"],
tls: ["transport", "layer", "security"],
tv: ["television"],
uat: ["user", "acceptance", "testing"],
udp: ["user", "datagram", "protocol"],
// User interface / experience
ui: ["user", "interface"],
uk: ["united", "kingdom"],
un: ["united", "nations"],
uri: ["uniform", "resource", "identifier"],
// Tech / web
url: ["uniform", "resource", "locator"],
us: ["united", "states"],
usa: ["united", "states", "of", "america"],
// Hardware
usb: ["universal", "serial", "bus"],
uv: ["ultraviolet"],
ux: ["user", "experience"],
vp: ["vice", "president"],
vpn: ["virtual", "private", "network"],
wan: ["wide", "area", "network"],
xml: ["extensible", "markup", "language"],
xss: ["cross", "site", "scripting"]
};
var MAX_INITIALISM_LENGTH = 5;
var LETTER_PHONEMES = {
a: ["EY1"],
b: ["B", "IY1"],
c: ["S", "IY1"],
d: ["D", "IY1"],
e: ["IY1"],
f: ["EH1", "F"],
g: ["JH", "IY1"],
h: ["EY1", "CH"],
i: ["AY1"],
j: ["JH", "EY1"],
k: ["K", "EY1"],
l: ["EH1", "L"],
m: ["EH1", "M"],
n: ["EH1", "N"],
o: ["OW1"],
p: ["P", "IY1"],
q: ["K", "Y", "UW1"],
r: ["AA1", "R"],
s: ["EH1", "S"],
t: ["T", "IY1"],
u: ["Y", "UW1"],
v: ["V", "IY1"],
w: ["D", "AH1", "B", "AH0", "L", "Y", "UW0"],
x: ["EH1", "K", "S"],
y: ["W", "AY1"],
z: ["Z", "IY1"]
};
var KNOWN_INITIALISMS = new Set(Object.keys(INITIALISM_EXPANSIONS));
function isInitialism(word) {
if (word.length > MAX_INITIALISM_LENGTH) {
return false;
}
return KNOWN_INITIALISMS.has(word.toLowerCase());
}
var INITIALISM_SUFFIXES = ["'s", "s"];
function parseInitialismWithSuffix(word) {
for (const suffix of INITIALISM_SUFFIXES) {
if (word.length > suffix.length && word.endsWith(suffix)) {
const base = word.slice(0, -suffix.length);
if (isInitialism(base)) {
return { base, suffix };
}
}
}
return null;
}
function translateAsAcronym(word, format = "ingglish") {
const arpabet = [];
for (const char of word.toLowerCase()) {
const letterArpabet = LETTER_PHONEMES[char];
if (letterArpabet !== void 0) {
arpabet.push(...letterArpabet);
}
}
return arpabetToFormat(arpabet, format);
}
// src/british.ts
import { lookupPronunciation } from "@ingglish/dictionary";
import { arpabetToFormat as arpabetToFormat2 } from "@ingglish/phonemes";
var BRITISH_TO_AMERICAN = [
// -isation → -ization (must come before -ise)
{ pattern: /isation$/, replacement: "ization" },
// -ise → -ize (realise→realize, organise→organize)
{ pattern: /ise$/, replacement: "ize" },
// -our → -or (colour→color, favour→favor)
{ pattern: /our$/, replacement: "or" },
// -oured → -ored (coloured→colored, favoured→favored)
{ pattern: /oured$/, replacement: "ored" },
// -ouring → -oring (colouring→coloring)
{ pattern: /ouring$/, replacement: "oring" },
// -ourable → -orable (favourable→favorable)
{ pattern: /ourable$/, replacement: "orable" },
// -re → -er (centre→center, theatre→theater)
// Only after consonants to avoid matching normal -re words
{ pattern: /([a-z])re$/, replacement: "$1er" },
// -lled → -led (travelled→traveled, cancelled→canceled)
{ pattern: /lled$/, replacement: "led" },
// -lling → -ling (travelling→traveling, cancelling→canceling)
{ pattern: /lling$/, replacement: "ling" },
// -ller → -ler (traveller→traveler)
{ pattern: /ller$/, replacement: "ler" },
// -ence → -ense (defence→defense, offence→offense)
{ pattern: /ence$/, replacement: "ense" },
// -ogue → -og (catalogue→catalog, dialogue→dialog)
{ pattern: /ogue$/, replacement: "og" },
// -ae- → -e- (anaesthetic→anesthetic, paediatric→pediatric)
{ pattern: /ae/, replacement: "e" },
// -oe- → -e- (foetus→fetus, oestrogen→estrogen)
{ pattern: /oe/, replacement: "e" },
// -ey → -y (curtsey→curtsy)
{ pattern: /ey$/, replacement: "y" },
// grey → gray
{ pattern: /grey/, replacement: "gray" }
];
function matchBritish(word) {
const lower = word.toLowerCase();
for (const { pattern, replacement } of BRITISH_TO_AMERICAN) {
if (pattern.test(lower)) {
const american = lower.replace(pattern, replacement);
if (american !== lower) {
const phonemes = lookupPronunciation(american);
if (phonemes) {
return { american, phonemes };
}
}
}
}
return null;
}
function translateAsBritish(word, format = "ingglish") {
const match = matchBritish(word);
if (match === null) {
return null;
}
return arpabetToFormat2(match.phonemes, format);
}
// src/compounds.ts
import { lookupPronunciation as lookupPronunciation2, getWordFrequency } from "@ingglish/dictionary";
import {
arpabetToFormat as arpabetToFormat3,
getFormatJoinSeparator,
getFormatPreservesCase
} from "@ingglish/phonemes";
function capitalize(str) {
if (str.length === 0) {
return str;
}
return str.charAt(0).toUpperCase() + str.slice(1);
}
function isUpperCase(char) {
return char === char.toUpperCase() && char !== char.toLowerCase();
}
var MIN_PART_LENGTH = 3;
var MIN_PART_FREQUENCY = 500;
var MAX_PART_LENGTH = 15;
function dpDecompose(word) {
const n = word.length;
const dp = Array.from({
length: n + 1
});
dp[0] = { parts: [], score: 0 };
for (let i = MIN_PART_LENGTH; i <= n; i++) {
for (let j = Math.max(0, i - MAX_PART_LENGTH); j <= i - MIN_PART_LENGTH; j++) {
if (j === 0 && i === n) {
continue;
}
const prev = dp[j];
if (prev === void 0) {
continue;
}
const chunk = word.slice(j, i);
const phonemes = lookupWord(chunk);
if (!phonemes) {
continue;
}
const freq = getWordFrequency(chunk);
if (freq === void 0 || freq < MIN_PART_FREQUENCY) {
continue;
}
const newScore = prev.score + freq;
const newParts = prev.parts.length + 1;
const current = dp[i];
if (current === void 0 || newParts < current.parts.length || newParts === current.parts.length && newScore > current.score) {
dp[i] = { parts: [...prev.parts, chunk], score: newScore };
}
}
}
const result = dp[n];
if (result === void 0 || result.parts.length < 2) {
return null;
}
return result.parts;
}
function translateAsCompound(word, format = "ingglish") {
const lowerWord = word.toLowerCase();
if (lowerWord.length < 6) {
return null;
}
const parts = dpDecompose(lowerWord);
if (!parts) {
return null;
}
const translations = [];
let pos = 0;
for (const part of parts) {
const phonemes = lookupWord(part);
if (!phonemes) {
return null;
}
let translated = arpabetToFormat3(phonemes, format);
if (getFormatPreservesCase(format)) {
const originalPart = word.slice(pos, pos + part.length);
if (originalPart.length > 0 && isUpperCase(originalPart[0])) {
translated = capitalize(translated);
}
}
translations.push(translated);
pos += part.length;
}
return translations.join(getFormatJoinSeparator(format));
}
function lookupWord(word) {
return lookupPronunciation2(word);
}
// src/stemming.ts
import { lookupPronunciation as lookupPronunciation3 } from "@ingglish/dictionary";
import { arpabetToFormat as arpabetToFormat4, stripStress } from "@ingglish/phonemes";
var VOICELESS = /* @__PURE__ */ new Set(["CH", "F", "HH", "K", "P", "S", "SH", "T", "TH"]);
var SIBILANTS = /* @__PURE__ */ new Set(["CH", "JH", "S", "SH", "Z", "ZH"]);
function selectEdPhonemes(lastPhoneme) {
const base = stripStress(lastPhoneme);
if (base === "T" || base === "D") {
return ["IH0", "D"];
}
if (VOICELESS.has(base)) {
return ["T"];
}
return ["D"];
}
function selectSPhonemes(lastPhoneme) {
const base = stripStress(lastPhoneme);
if (SIBILANTS.has(base)) {
return ["IH0", "Z"];
}
if (VOICELESS.has(base)) {
return ["S"];
}
return ["Z"];
}
var INFLECTIONAL_SUFFIXES = /* @__PURE__ */ new Set([
"ed",
"er",
"es",
"est",
"ification",
"ify",
"ifying",
"ing",
"or",
"s"
]);
var SUFFIX_PHONEMES = [
// Long suffixes first (must come before shorter matches: -ification before -tion, -ifying before -ing)
{ phonemes: ["IH0", "F", "IH0", "K", "EY1", "SH", "AH0", "N"], suffix: "ification" },
{ phonemes: ["IH0", "F", "AY1", "IH0", "NG"], suffix: "ifying" },
{ phonemes: ["IH0", "F", "AY1"], suffix: "ify" },
// Verb suffixes
{ phonemes: ["IH0", "NG"], suffix: "ing" },
{ phonemes: null, suffix: "ed" },
// allomorph: T/D/IH0 D (selected dynamically)
{ phonemes: null, suffix: "es" },
// allomorph: same as -s (S/Z/IH0 Z based on stem)
{ phonemes: null, suffix: "s" },
// allomorph: S/Z/IH0 Z (selected dynamically)
// Noun suffixes
{ phonemes: ["SH", "AH0", "N"], suffix: "tion" },
{ phonemes: ["ZH", "AH0", "N"], suffix: "sion" },
{ phonemes: ["N", "AH0", "S"], suffix: "ness" },
{ phonemes: ["M", "AH0", "N", "T"], suffix: "ment" },
{ phonemes: ["IH0", "T", "IY0"], suffix: "ity" },
{ phonemes: ["ER0"], suffix: "er" },
{ phonemes: ["ER0"], suffix: "or" },
{ phonemes: ["IH0", "S", "T"], suffix: "ist" },
{ phonemes: ["IH0", "Z", "AH0", "M"], suffix: "ism" },
// Adjective suffixes
{ phonemes: ["L", "IY0"], suffix: "ly" },
{ phonemes: ["F", "AH0", "L"], suffix: "ful" },
{ phonemes: ["L", "AH0", "S"], suffix: "less" },
{ phonemes: ["AH0", "B", "AH0", "L"], suffix: "able" },
{ phonemes: ["AH0", "B", "AH0", "L"], suffix: "ible" },
{ phonemes: ["AH0", "S"], suffix: "ous" },
{ phonemes: ["IH0", "V"], suffix: "ive" },
{ phonemes: ["AH0", "L"], suffix: "al" },
{ phonemes: ["IH0", "K"], suffix: "ic" },
// Comparative/superlative
{ phonemes: ["AH0", "S", "T"], suffix: "est" },
// Additional suffixes
{ phonemes: ["AH0", "L", "IY0"], suffix: "ally" },
{ phonemes: ["AA1", "L", "AH0", "JH", "IY0"], suffix: "ology" },
{ phonemes: ["AY1", "Z"], suffix: "ize" },
{ phonemes: ["AY1", "Z"], suffix: "ise" }
];
var PREFIX_PHONEMES = [
{ phonemes: ["AH0", "N"], prefix: "un" },
{ phonemes: ["R", "IY0"], prefix: "re" },
{ phonemes: ["P", "R", "IY0"], prefix: "pre" },
{ phonemes: ["D", "IH0", "S"], prefix: "dis" },
{ phonemes: ["M", "IH0", "S"], prefix: "mis" },
{ phonemes: ["OW1", "V", "ER0"], prefix: "over" },
{ phonemes: ["AH1", "N", "D", "ER0"], prefix: "under" },
{ phonemes: ["AW1", "T"], prefix: "out" },
{ phonemes: ["AE1", "N", "T", "IY0"], prefix: "anti" },
{ phonemes: ["S", "UW1", "P", "ER0"], prefix: "super" }
];
function matchStemming(word) {
const lowerWord = word.toLowerCase();
for (const { phonemes: suffixArpabet, suffix } of SUFFIX_PHONEMES) {
if (lowerWord.endsWith(suffix) && lowerWord.length > suffix.length + 2) {
const stem = lowerWord.slice(0, -suffix.length);
for (const variant of getStemVariants(stem, suffix)) {
const baseArpabet = lookupPronunciation3(variant);
if (baseArpabet) {
const resolvedSuffix = resolveSuffixPhonemes(suffix, suffixArpabet, baseArpabet);
return {
phonemes: [...baseArpabet, ...resolvedSuffix],
stem: variant,
suffix
};
}
}
}
}
for (const { phonemes: prefixArpabet, prefix } of PREFIX_PHONEMES) {
if (lowerWord.startsWith(prefix) && lowerWord.length > prefix.length + 2) {
const stem = lowerWord.slice(prefix.length);
const baseArpabet = lookupPronunciation3(stem);
if (baseArpabet) {
return {
phonemes: [...prefixArpabet, ...baseArpabet],
prefix,
stem
};
}
}
}
return null;
}
function translateWithStemming(word, format = "ingglish") {
const match = matchStemming(word);
if (match === null) {
return null;
}
return arpabetToFormat4(match.phonemes, format);
}
function getStemVariants(stem, suffix) {
const variants = [stem];
if (INFLECTIONAL_SUFFIXES.has(suffix)) {
variants.push(
stem + "e",
// hoping -> hope
stem.length > 1 ? stem.slice(0, -1) : stem,
// running -> run (double consonant)
stem.length > 0 ? stem + stem.at(-1) : stem
// big -> bigg (for adding -er)
);
}
if (stem.endsWith("i")) {
variants.push(stem.slice(0, -1) + "y");
}
variants.push(stem + "y");
return variants;
}
function resolveSuffixPhonemes(suffix, suffixArpabet, baseArpabet) {
if (suffixArpabet !== null) {
return suffixArpabet;
}
const lastPhoneme = baseArpabet.at(-1);
if (suffix === "ed") {
return selectEdPhonemes(lastPhoneme);
}
return selectSPhonemes(lastPhoneme);
}
// src/index.ts
function diagnoseUnknown(word) {
if (/(.)\1\1/.test(word) || !/[aeiouy]/i.test(word)) {
return null;
}
const { strategy } = translateUnknownCore(word, "ingglish");
switch (strategy) {
case "british": {
const m = matchBritish(word);
return { americanSpelling: m.american, phonemes: m.phonemes, strategy: "british" };
}
case "compound": {
return { parts: dpDecompose(word.toLowerCase()), strategy: "compound" };
}
case "custom": {
return { phonemes: getCustomPronunciation(word), strategy: "custom" };
}
case "g2p": {
return { strategy: "g2p", trace: wordToArpabetTraced(word) };
}
case "initialism": {
return { strategy: "initialism" };
}
case "stemming": {
const m = matchStemming(word);
return { prefix: m.prefix, stem: m.stem, strategy: "stemming", suffix: m.suffix };
}
}
}
function translateUnknown(word, format = "ingglish") {
return translateUnknownCore(word, format).translated;
}
function translateUnknownCore(word, format) {
const customPhonemes = getCustomPronunciation(word);
if (customPhonemes !== void 0) {
return { strategy: "custom", translated: arpabetToFormat5(customPhonemes, format) };
}
if (isInitialism(word)) {
return { strategy: "initialism", translated: translateAsAcronym(word, format) };
}
const britishResult = translateAsBritish(word, format);
if (britishResult !== null && britishResult.length > 0) {
return { strategy: "british", translated: britishResult };
}
const compoundResult = translateAsCompound(word, format);
if (compoundResult !== null && compoundResult.length > 0) {
return { strategy: "compound", translated: compoundResult };
}
const stemmedResult = translateWithStemming(word, format);
if (stemmedResult !== null && stemmedResult.length > 0) {
return { strategy: "stemming", translated: stemmedResult };
}
return { strategy: "g2p", translated: wordToPhonetic(word, format) };
}
export {
KNOWN_INITIALISMS,
LETTER_PHONEMES,
diagnoseUnknown,
isInitialism,
matchBritish,
parseInitialismWithSuffix,
translateAsAcronym,
translateUnknown
};
+54
View File
@@ -0,0 +1,54 @@
{
"name": "@ingglish/fallback",
"version": "0.1.1",
"description": "Unknown word translation strategies for Ingglish (G2P, stemming, compounds, etc.)",
"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",
"prepublishOnly": "npm run build"
},
"dependencies": {
"@ingglish/phonemes": "^0.1.0",
"@ingglish/ipa": "^0.1.0",
"@ingglish/dictionary": "^0.1.0",
"@ingglish/g2p": "^0.1.0"
},
"author": "Paul Tarjan",
"license": "MIT",
"repository": {
"type": "git",
"url": "git+https://github.com/ptarjan/ingglish.git",
"directory": "packages/fallback"
},
"homepage": "https://github.com/ptarjan/ingglish#readme",
"bugs": {
"url": "https://github.com/ptarjan/ingglish/issues"
}
}
+1392
View File
File diff suppressed because it is too large. Load diff
+81
View File
@@ -0,0 +1,81 @@
import { OutputFormat } from '@ingglish/phonemes';
/**
* NRL/Elovitz letter-to-sound rules for grapheme-to-phoneme conversion.
*
* Based on: Elovitz, H., Johnson, R., McHugh, A., and Shore, J. (1976)
* "Automatic translation of English text to phonetics by means of
* letter-to-sound rules." NRL Report 7948.
*
* ~960 context-sensitive rules that examine left and right letter context
* to determine pronunciation. ~150 are general spelling rules (silent E,
* digraphs, vowel teams, C/G softening, suffixes). The other ~800 are
* narrow context patches and whole-word memorizations for the cases where
* those rules break down.
*
* Each rule has the form:
*
* leftContext[TARGET]rightContext=/PHONEMES/
*
* Special context symbols:
* # = 1+ vowels (AEIOUY)
* . = voiced consonant (BDVGJLMNRWZ)
* % = suffix (ER, E, ES, ED, ING, ELY)
* & = sibilant (S, C, G, Z, X, J, CH, SH)
* @ = non-palate consonant (T, S, R, D, L, Z, N, J, TH, CH, SH)
* ^ = single consonant
* + = front vowel (E, I, Y)
* : = 0+ consonants
* ' '= word boundary (space)
*/
interface G2PTrace {
phonemes: string[];
steps: G2PTraceStep[];
}
interface G2PTraceStep {
letters: string;
phonemes: string[];
rule: string;
}
/**
* Converts a word to ARPAbet using NRL context-sensitive rules.
*
* @param word The word to convert
* @returns Array of ARPAbet phonemes
*/
declare function wordToArpabet(word: string): string[];
/**
* Converts a word to ARPAbet using NRL context-sensitive rules,
* returning both the phonemes and a trace of which rules fired.
*/
declare function wordToArpabetTraced(word: string): G2PTrace;
/**
* Translates an unknown word using NRL letter-to-sound rules.
* This is a fallback when the word isn't in the dictionary.
*
* @param word The unknown word
* @param format The output format
* @returns The best-effort translation
*/
declare function wordToPhonetic(word: string, format?: OutputFormat): string;
/**
* Stress prediction post-processor for G2P rules.
*
* The NRL rules assign stress-1 to ALL non-schwa vowels, meaning multi-syllable
* words get every vowel stressed. This module predicts which syllable gets
* primary stress using Rastle & Coltheart-style affix rules, then reduces
* unstressed vowels to schwa where appropriate.
*/
/**
* Apply stress prediction to a phoneme array produced by NRL rules.
*
* - Finds all vowel positions (phonemes ending in 0/1/2)
* - Predicts which syllable gets primary stress
* - Reduces unstressed reducible vowels to AH0 (schwa)
* - Marks other unstressed vowels with 0
*/
declare function applyStressPrediction(word: string, phonemes: string[]): string[];
export { type G2PTrace, type G2PTraceStep, applyStressPrediction, wordToArpabet, wordToArpabetTraced, wordToPhonetic };
+81
View File
@@ -0,0 +1,81 @@
import { OutputFormat } from '@ingglish/phonemes';
/**
* NRL/Elovitz letter-to-sound rules for grapheme-to-phoneme conversion.
*
* Based on: Elovitz, H., Johnson, R., McHugh, A., and Shore, J. (1976)
* "Automatic translation of English text to phonetics by means of
* letter-to-sound rules." NRL Report 7948.
*
* ~960 context-sensitive rules that examine left and right letter context
* to determine pronunciation. ~150 are general spelling rules (silent E,
* digraphs, vowel teams, C/G softening, suffixes). The other ~800 are
* narrow context patches and whole-word memorizations for the cases where
* those rules break down.
*
* Each rule has the form:
*
* leftContext[TARGET]rightContext=/PHONEMES/
*
* Special context symbols:
* # = 1+ vowels (AEIOUY)
* . = voiced consonant (BDVGJLMNRWZ)
* % = suffix (ER, E, ES, ED, ING, ELY)
* & = sibilant (S, C, G, Z, X, J, CH, SH)
* @ = non-palate consonant (T, S, R, D, L, Z, N, J, TH, CH, SH)
* ^ = single consonant
* + = front vowel (E, I, Y)
* : = 0+ consonants
* ' '= word boundary (space)
*/
interface G2PTrace {
phonemes: string[];
steps: G2PTraceStep[];
}
interface G2PTraceStep {
letters: string;
phonemes: string[];
rule: string;
}
/**
* Converts a word to ARPAbet using NRL context-sensitive rules.
*
* @param word The word to convert
* @returns Array of ARPAbet phonemes
*/
declare function wordToArpabet(word: string): string[];
/**
* Converts a word to ARPAbet using NRL context-sensitive rules,
* returning both the phonemes and a trace of which rules fired.
*/
declare function wordToArpabetTraced(word: string): G2PTrace;
/**
* Translates an unknown word using NRL letter-to-sound rules.
* This is a fallback when the word isn't in the dictionary.
*
* @param word The unknown word
* @param format The output format
* @returns The best-effort translation
*/
declare function wordToPhonetic(word: string, format?: OutputFormat): string;
/**
* Stress prediction post-processor for G2P rules.
*
* The NRL rules assign stress-1 to ALL non-schwa vowels, meaning multi-syllable
* words get every vowel stressed. This module predicts which syllable gets
* primary stress using Rastle & Coltheart-style affix rules, then reduces
* unstressed vowels to schwa where appropriate.
*/
/**
* Apply stress prediction to a phoneme array produced by NRL rules.
*
* - Finds all vowel positions (phonemes ending in 0/1/2)
* - Predicts which syllable gets primary stress
* - Reduces unstressed reducible vowels to AH0 (schwa)
* - Marks other unstressed vowels with 0
*/
declare function applyStressPrediction(word: string, phonemes: string[]): string[];
export { type G2PTrace, type G2PTraceStep, applyStressPrediction, wordToArpabet, wordToArpabetTraced, wordToPhonetic };
+1362
View File
File diff suppressed because it is too large. Load diff
+61
View File
@@ -0,0 +1,61 @@
{
"name": "@ingglish/g2p",
"version": "0.1.1",
"description": "NRL/Elovitz grapheme-to-phoneme rules for English",
"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",
"prepublishOnly": "npm run build"
},
"dependencies": {
"@ingglish/phonemes": "^0.1.0"
},
"devDependencies": {
"@ingglish/ipa": "^0.1.0"
},
"keywords": [
"g2p",
"grapheme-to-phoneme",
"english",
"pronunciation",
"phonemes"
],
"author": "Paul Tarjan",
"license": "MIT",
"repository": {
"type": "git",
"url": "git+https://github.com/ptarjan/ingglish.git",
"directory": "packages/g2p"
},
"homepage": "https://github.com/ptarjan/ingglish#readme",
"bugs": {
"url": "https://github.com/ptarjan/ingglish/issues"
}
}
+3905
View File
File diff suppressed because it is too large. Load diff
+66
View File
@@ -0,0 +1,66 @@
import { OutputFormat, TranslatedToken } from '@ingglish/phonemes';
interface IpaDict {
entries: Record<string, string>;
lang: string;
}
interface Language {
code: string;
label: string;
}
/** Insert spaces between adjacent Khmer words that have no separator. */
declare function segmentKhmerText(text: string): string;
declare const LANGUAGES: Language[];
/**
* Converts an IPA transcription to Ingglish spelling.
* Strips slashes and syllable dots before conversion.
*/
declare function ipaToIngglish(ipa: string): string;
declare function lookupIpa(dict: IpaDict, word: string): string | undefined;
/** Marker for words not found in the dictionary */
declare const NOT_FOUND_MARKER = "\uFFFD";
/**
* Translates foreign text to the specified output format.
* Words not found in the dictionary are returned with a marker prefix.
*
* For caseless scripts (Arabic, Japanese, Chinese, Korean), sentence-initial
* words are automatically capitalized in the output.
*/
declare function translateForeign(text: string, dict: IpaDict, format?: OutputFormat): string;
/**
* Like {@link translateForeign}, but returns token-by-token mappings instead of a string.
* Each token includes the original text, translation, and whether it matched the dictionary.
*/
declare function translateForeignWithMapping(text: string, dict: IpaDict, format?: OutputFormat): TranslatedToken[];
/**
* Converts IPA text to ARPAbet with stress digits stripped.
*/
declare function ipaToArpabetClean(ipa: string): null | string[];
/**
* ARPAbet to IPA conversion.
*
* Converts CMU dictionary phoneme sequences to IPA notation,
* with proper stress marker placement at syllable boundaries.
*/
/**
* Converts a single ARPAbet phoneme to IPA.
* Handles stress markers on vowels.
*
* @param phoneme ARPAbet phoneme (e.g., "AH0", "EY1", "B")
* @returns IPA symbol (e.g., "ə", "ˈeɪ", "b")
*/
declare function arpabetPhonemeToIPA(phoneme: string): string;
/**
* Converts ARPAbet to IPA without surrounding slashes.
* Useful for combining with other text.
*
* @param arpabet Array of ARPAbet symbols
* @returns IPA transcription without surrounding slashes
*/
declare function arpabetToIPARaw(arpabet: string[]): string;
declare function registerIPA(): void;
export { type IpaDict, LANGUAGES, type Language, NOT_FOUND_MARKER, arpabetPhonemeToIPA, arpabetToIPARaw, ipaToArpabetClean, ipaToIngglish, lookupIpa, registerIPA, segmentKhmerText, translateForeign, translateForeignWithMapping };
+66
View File
@@ -0,0 +1,66 @@
import { OutputFormat, TranslatedToken } from '@ingglish/phonemes';
interface IpaDict {
entries: Record<string, string>;
lang: string;
}
interface Language {
code: string;
label: string;
}
/** Insert spaces between adjacent Khmer words that have no separator. */
declare function segmentKhmerText(text: string): string;
declare const LANGUAGES: Language[];
/**
* Converts an IPA transcription to Ingglish spelling.
* Strips slashes and syllable dots before conversion.
*/
declare function ipaToIngglish(ipa: string): string;
declare function lookupIpa(dict: IpaDict, word: string): string | undefined;
/** Marker for words not found in the dictionary */
declare const NOT_FOUND_MARKER = "\uFFFD";
/**
* Translates foreign text to the specified output format.
* Words not found in the dictionary are returned with a marker prefix.
*
* For caseless scripts (Arabic, Japanese, Chinese, Korean), sentence-initial
* words are automatically capitalized in the output.
*/
declare function translateForeign(text: string, dict: IpaDict, format?: OutputFormat): string;
/**
* Like {@link translateForeign}, but returns token-by-token mappings instead of a string.
* Each token includes the original text, translation, and whether it matched the dictionary.
*/
declare function translateForeignWithMapping(text: string, dict: IpaDict, format?: OutputFormat): TranslatedToken[];
/**
* Converts IPA text to ARPAbet with stress digits stripped.
*/
declare function ipaToArpabetClean(ipa: string): null | string[];
/**
* ARPAbet to IPA conversion.
*
* Converts CMU dictionary phoneme sequences to IPA notation,
* with proper stress marker placement at syllable boundaries.
*/
/**
* Converts a single ARPAbet phoneme to IPA.
* Handles stress markers on vowels.
*
* @param phoneme ARPAbet phoneme (e.g., "AH0", "EY1", "B")
* @returns IPA symbol (e.g., "ə", "ˈeɪ", "b")
*/
declare function arpabetPhonemeToIPA(phoneme: string): string;
/**
* Converts ARPAbet to IPA without surrounding slashes.
* Useful for combining with other text.
*
* @param arpabet Array of ARPAbet symbols
* @returns IPA transcription without surrounding slashes
*/
declare function arpabetToIPARaw(arpabet: string[]): string;
declare function registerIPA(): void;
export { type IpaDict, LANGUAGES, type Language, NOT_FOUND_MARKER, arpabetPhonemeToIPA, arpabetToIPARaw, ipaToArpabetClean, ipaToIngglish, lookupIpa, registerIPA, segmentKhmerText, translateForeign, translateForeignWithMapping };
+3881
View File
File diff suppressed because it is too large. Load diff
+51
View File
@@ -0,0 +1,51 @@
{
"name": "@ingglish/ipa",
"version": "0.1.1",
"description": "IPA (International Phonetic Alphabet) conversion for Ingglish",
"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",
"prepublishOnly": "npm run build"
},
"dependencies": {
"@ingglish/normalize": "^0.1.0",
"@ingglish/phonemes": "^0.1.0"
},
"author": "Paul Tarjan",
"license": "MIT",
"repository": {
"type": "git",
"url": "git+https://github.com/ptarjan/ingglish.git",
"directory": "packages/ipa"
},
"homepage": "https://github.com/ptarjan/ingglish#readme",
"bugs": {
"url": "https://github.com/ptarjan/ingglish/issues"
}
}
+258
View File
@@ -0,0 +1,258 @@
"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, {
WORD_SPLIT_REGEX: () => WORD_SPLIT_REGEX,
WORD_TEST_REGEX: () => WORD_TEST_REGEX,
applyCasePattern: () => applyCasePattern,
detectCasePattern: () => detectCasePattern,
extractPreservedPatterns: () => extractPreservedPatterns,
normalizeApostrophes: () => normalizeApostrophes,
splitCamelCase: () => splitCamelCase,
stripDiacritics: () => stripDiacritics,
tokenizeIPA: () => tokenizeIPA,
tokenizeText: () => tokenizeText
});
module.exports = __toCommonJS(index_exports);
// src/case.ts
function applyCasePattern(word, pattern, original) {
if (pattern === "lower") {
const firstChar = word.codePointAt(0);
if (firstChar >= 97 && firstChar <= 122 && word === word.toLowerCase()) {
return word;
}
return word.toLowerCase();
}
switch (pattern) {
case "capitalized": {
return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
}
case "mixed": {
if (original !== void 0 && original.length > 0) {
return applyMixedCase(word, original);
}
return word.toLowerCase();
}
case "upper": {
return word.toUpperCase();
}
default: {
return word.toLowerCase();
}
}
}
function detectCasePattern(word) {
if (word.length === 0) {
return "lower";
}
const firstCode = word.codePointAt(0);
const firstChar = word[0];
const isFirstUpper = firstCode >= 65 && firstCode <= 90 || // A-Z (fast ASCII path)
firstCode > 127 && firstChar !== firstChar.toLowerCase();
if (!isFirstUpper && word === word.toLowerCase()) {
return "lower";
}
if (word.length === 1) {
if (word === "I") {
return "lower";
}
return isFirstUpper ? "capitalized" : "lower";
}
if (word === word.toUpperCase()) {
if (word.length <= 2) {
return "capitalized";
}
return "upper";
}
if (isFirstUpper) {
let restIsLower = true;
for (let i = 1; i < word.length; i++) {
const c = word.codePointAt(i);
if (c >= 65 && c <= 90 || // A-Z
c > 127 && word[i] !== word[i].toLowerCase()) {
restIsLower = false;
break;
}
}
if (restIsLower) {
return "capitalized";
}
}
return "mixed";
}
function splitCamelCase(word) {
if (word.length < 2) {
return null;
}
let hasInternalUpper = false;
for (let i = 1; i < word.length; i++) {
const c = word.codePointAt(i);
if (c >= 65 && c <= 90) {
hasInternalUpper = true;
break;
}
}
if (!hasInternalUpper) {
return null;
}
const parts = [];
let start = 0;
for (let i = 1; i < word.length; i++) {
const prevCode = word.codePointAt(i - 1);
const currCode = word.codePointAt(i);
if (prevCode >= 97 && prevCode <= 122 && currCode >= 65 && currCode <= 90) {
parts.push(word.slice(start, i));
start = i;
}
}
if (parts.length > 0) {
parts.push(word.slice(start));
return parts;
}
return null;
}
function applyMixedCase(translated, original) {
const lowerTranslated = translated.toLowerCase();
let result = "";
let i = 0;
for (const char of lowerTranslated) {
if (i < original.length) {
const origChar = original[i];
result += origChar === origChar.toUpperCase() ? char.toUpperCase() : char;
} else {
result += char;
}
i++;
}
return result;
}
// src/text.ts
var URL_REGEX = /(?:https?|ftp|file):\/\/[^\s<>"')\]]+/gi;
var EMAIL_REGEX = /[\w.%+-]{1,64}@(?:[a-z0-9-]{1,63}\.){1,10}[a-z]{2,63}/gi;
var COMMON_TLDS = "com|org|net|edu|gov|io|co|uk|de|fr|jp|au|ca|ru|ch|it|nl|se|no|es|mil|info|biz|tv|me|app|dev|ai|xyz|rs|site|tech|blog|news|club|lol|new|world|online|space|fun|live|shop|store|gg|fm|im|is|to|cc|ws|ly|gl|be|us|in|eu|asia|pro|cz|pl|fi|dk|pt|ie|nz|za|br|mx|ar|cl|kr|tw|hk|sg|id|th|vn|ph";
var BARE_DOMAIN_REGEX = new RegExp(
String.raw`\b(?:[a-z0-9][-a-z0-9]*\.)+(?:${COMMON_TLDS})\b(?:\/[^\s<>"')\]]*)?`,
"gi"
);
function extractPreservedPatterns(text) {
const preserved = /* @__PURE__ */ new Map();
let counter = 0;
let result = text;
if (text.includes("://")) {
result = result.replaceAll(URL_REGEX, (match) => {
const placeholder = `\0${counter++}\0`;
preserved.set(placeholder, match);
return placeholder;
});
}
if (result.includes("@")) {
result = result.replaceAll(EMAIL_REGEX, (match) => {
const placeholder = `\0${counter++}\0`;
preserved.set(placeholder, match);
return placeholder;
});
}
if (result.includes(".")) {
result = result.replaceAll(BARE_DOMAIN_REGEX, (match) => {
const placeholder = `\0${counter++}\0`;
preserved.set(placeholder, match);
return placeholder;
});
}
return { preserved, text: result };
}
var FANCY_APOSTROPHE = /[\u2018\u2019\u02BC]/g;
var COMBINING_MARKS = /[\u0300-\u036F]/g;
function normalizeApostrophes(text) {
return text.replaceAll(FANCY_APOSTROPHE, "'");
}
function stripDiacritics(text) {
return text.normalize("NFD").replaceAll(COMBINING_MARKS, "");
}
// src/tokenize.ts
var WORD_SPLIT_REGEX = /((?<!\d)[a-zA-Z\u00C0-\u024F']+(?!\d))/;
var WORD_TEST_REGEX = /^[a-zA-Z\u00C0-\u024F']+$/;
var IPA_SYMBOLS_SET = new Set("\u0259\u025D\u025A\u028C\xE6\u0251\u0254\u025B\u026A\u028A\xF0\u03B8\u0283\u0292\u014B\u0279\u0261");
function isIPAChar(char) {
const code = char.codePointAt(0);
if (code >= 65 && code <= 90 || code >= 97 && code <= 122) {
return true;
}
if (code === 8288) {
return true;
}
if (code === 712 || code === 716) {
return true;
}
if (IPA_SYMBOLS_SET.has(char)) {
return true;
}
return false;
}
function tokenizeIPA(text) {
const tokens = [];
let i = 0;
while (i < text.length) {
if (isIPAChar(text[i])) {
let wordEnd = i + 1;
while (wordEnd < text.length && isIPAChar(text[wordEnd])) {
wordEnd++;
}
tokens.push({ isWord: true, text: text.slice(i, wordEnd) });
i = wordEnd;
} else {
let nonWordEnd = i + 1;
while (nonWordEnd < text.length && !isIPAChar(text[nonWordEnd])) {
nonWordEnd++;
}
tokens.push({ isWord: false, text: text.slice(i, nonWordEnd) });
i = nonWordEnd;
}
}
return tokens;
}
function tokenizeText(text) {
const normalized = normalizeApostrophes(text);
const parts = normalized.split(WORD_SPLIT_REGEX);
const tokens = [];
for (const part of parts) {
if (part.length > 0) {
tokens.push({ isWord: WORD_TEST_REGEX.test(part), text: part });
}
}
return tokens;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
WORD_SPLIT_REGEX,
WORD_TEST_REGEX,
applyCasePattern,
detectCasePattern,
extractPreservedPatterns,
normalizeApostrophes,
splitCamelCase,
stripDiacritics,
tokenizeIPA,
tokenizeText
});
+74
View File
@@ -0,0 +1,74 @@
/**
* Utilities for preserving case patterns during translation.
*/
/**
* Case pattern detected in a word.
* - 'lower': all lowercase (hello)
* - 'upper': all uppercase (HELLO)
* - 'capitalized': first letter uppercase (Hello)
* - 'mixed': mixed case like camelCase (GitHub, iPhone)
*/
type CasePattern = 'capitalized' | 'lower' | 'mixed' | 'upper';
/**
* Applies a case pattern to a word, optionally using original word for mixed case.
* Optimized: lowercase case returns word directly if already lowercase.
*/
declare function applyCasePattern(word: string, pattern: CasePattern, original?: string): string;
/**
* Detects the case pattern of a word.
* Optimized for the common case (lowercase) by checking it first.
*/
declare function detectCasePattern(word: string): CasePattern;
/**
* Splits a word at camelCase boundaries.
* e.g., "iCloud" -> ["i", "Cloud"], "MacBook" -> ["Mac", "Book"]
*/
declare function splitCamelCase(word: string): null | string[];
/**
* Extracts URLs and emails from text, replacing them with placeholders.
* Returns the modified text and a map to restore originals.
* Placeholders use non-alphanumeric characters to avoid being split by word regex.
*/
declare function extractPreservedPatterns(text: string): {
preserved: Map<string, string>;
text: string;
};
/**
* Normalizes various apostrophe characters to the standard straight apostrophe.
* Handles: ' (U+2019 right single quotation mark), ' (U+2018 left), ʼ (U+02BC modifier letter)
*/
declare function normalizeApostrophes(text: string): string;
/**
* Strips diacritics/accents from text, preserving base letters.
* Converts résumé→resume, naïve→naive, cliché→cliche, café→cafe.
* Uses Unicode NFD decomposition to separate base letters from combining marks.
*/
declare function stripDiacritics(text: string): string;
/**
* Tokenization utilities for splitting text into word and non-word tokens.
*/
/** Regex to split text into word and non-word tokens (includes accented Latin chars).
* Digit lookaround prevents matching letters in escape sequences like \u2014. */
declare const WORD_SPLIT_REGEX: RegExp;
/** Regex to test if a token is a word (includes accented Latin chars) */
declare const WORD_TEST_REGEX: RegExp;
/**
* Token with text content and word/non-word classification.
*/
interface TextToken {
isWord: boolean;
text: string;
}
/**
* Tokenizes IPA text into words and non-words (punctuation/whitespace).
*/
declare function tokenizeIPA(text: string): TextToken[];
/**
* Tokenizes Ingglish/English text into words and non-words.
* Words are sequences of letters and apostrophes.
*/
declare function tokenizeText(text: string): TextToken[];
export { type CasePattern, WORD_SPLIT_REGEX, WORD_TEST_REGEX, applyCasePattern, detectCasePattern, extractPreservedPatterns, normalizeApostrophes, splitCamelCase, stripDiacritics, tokenizeIPA, tokenizeText };
+74
View File
@@ -0,0 +1,74 @@
/**
* Utilities for preserving case patterns during translation.
*/
/**
* Case pattern detected in a word.
* - 'lower': all lowercase (hello)
* - 'upper': all uppercase (HELLO)
* - 'capitalized': first letter uppercase (Hello)
* - 'mixed': mixed case like camelCase (GitHub, iPhone)
*/
type CasePattern = 'capitalized' | 'lower' | 'mixed' | 'upper';
/**
* Applies a case pattern to a word, optionally using original word for mixed case.
* Optimized: lowercase case returns word directly if already lowercase.
*/
declare function applyCasePattern(word: string, pattern: CasePattern, original?: string): string;
/**
* Detects the case pattern of a word.
* Optimized for the common case (lowercase) by checking it first.
*/
declare function detectCasePattern(word: string): CasePattern;
/**
* Splits a word at camelCase boundaries.
* e.g., "iCloud" -> ["i", "Cloud"], "MacBook" -> ["Mac", "Book"]
*/
declare function splitCamelCase(word: string): null | string[];
/**
* Extracts URLs and emails from text, replacing them with placeholders.
* Returns the modified text and a map to restore originals.
* Placeholders use non-alphanumeric characters to avoid being split by word regex.
*/
declare function extractPreservedPatterns(text: string): {
preserved: Map<string, string>;
text: string;
};
/**
* Normalizes various apostrophe characters to the standard straight apostrophe.
* Handles: ' (U+2019 right single quotation mark), ' (U+2018 left), ʼ (U+02BC modifier letter)
*/
declare function normalizeApostrophes(text: string): string;
/**
* Strips diacritics/accents from text, preserving base letters.
* Converts résumé→resume, naïve→naive, cliché→cliche, café→cafe.
* Uses Unicode NFD decomposition to separate base letters from combining marks.
*/
declare function stripDiacritics(text: string): string;
/**
* Tokenization utilities for splitting text into word and non-word tokens.
*/
/** Regex to split text into word and non-word tokens (includes accented Latin chars).
* Digit lookaround prevents matching letters in escape sequences like \u2014. */
declare const WORD_SPLIT_REGEX: RegExp;
/** Regex to test if a token is a word (includes accented Latin chars) */
declare const WORD_TEST_REGEX: RegExp;
/**
* Token with text content and word/non-word classification.
*/
interface TextToken {
isWord: boolean;
text: string;
}
/**
* Tokenizes IPA text into words and non-words (punctuation/whitespace).
*/
declare function tokenizeIPA(text: string): TextToken[];
/**
* Tokenizes Ingglish/English text into words and non-words.
* Words are sequences of letters and apostrophes.
*/
declare function tokenizeText(text: string): TextToken[];
export { type CasePattern, WORD_SPLIT_REGEX, WORD_TEST_REGEX, applyCasePattern, detectCasePattern, extractPreservedPatterns, normalizeApostrophes, splitCamelCase, stripDiacritics, tokenizeIPA, tokenizeText };
+222
View File
@@ -0,0 +1,222 @@
// src/case.ts
function applyCasePattern(word, pattern, original) {
if (pattern === "lower") {
const firstChar = word.codePointAt(0);
if (firstChar >= 97 && firstChar <= 122 && word === word.toLowerCase()) {
return word;
}
return word.toLowerCase();
}
switch (pattern) {
case "capitalized": {
return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
}
case "mixed": {
if (original !== void 0 && original.length > 0) {
return applyMixedCase(word, original);
}
return word.toLowerCase();
}
case "upper": {
return word.toUpperCase();
}
default: {
return word.toLowerCase();
}
}
}
function detectCasePattern(word) {
if (word.length === 0) {
return "lower";
}
const firstCode = word.codePointAt(0);
const firstChar = word[0];
const isFirstUpper = firstCode >= 65 && firstCode <= 90 || // A-Z (fast ASCII path)
firstCode > 127 && firstChar !== firstChar.toLowerCase();
if (!isFirstUpper && word === word.toLowerCase()) {
return "lower";
}
if (word.length === 1) {
if (word === "I") {
return "lower";
}
return isFirstUpper ? "capitalized" : "lower";
}
if (word === word.toUpperCase()) {
if (word.length <= 2) {
return "capitalized";
}
return "upper";
}
if (isFirstUpper) {
let restIsLower = true;
for (let i = 1; i < word.length; i++) {
const c = word.codePointAt(i);
if (c >= 65 && c <= 90 || // A-Z
c > 127 && word[i] !== word[i].toLowerCase()) {
restIsLower = false;
break;
}
}
if (restIsLower) {
return "capitalized";
}
}
return "mixed";
}
function splitCamelCase(word) {
if (word.length < 2) {
return null;
}
let hasInternalUpper = false;
for (let i = 1; i < word.length; i++) {
const c = word.codePointAt(i);
if (c >= 65 && c <= 90) {
hasInternalUpper = true;
break;
}
}
if (!hasInternalUpper) {
return null;
}
const parts = [];
let start = 0;
for (let i = 1; i < word.length; i++) {
const prevCode = word.codePointAt(i - 1);
const currCode = word.codePointAt(i);
if (prevCode >= 97 && prevCode <= 122 && currCode >= 65 && currCode <= 90) {
parts.push(word.slice(start, i));
start = i;
}
}
if (parts.length > 0) {
parts.push(word.slice(start));
return parts;
}
return null;
}
function applyMixedCase(translated, original) {
const lowerTranslated = translated.toLowerCase();
let result = "";
let i = 0;
for (const char of lowerTranslated) {
if (i < original.length) {
const origChar = original[i];
result += origChar === origChar.toUpperCase() ? char.toUpperCase() : char;
} else {
result += char;
}
i++;
}
return result;
}
// src/text.ts
var URL_REGEX = /(?:https?|ftp|file):\/\/[^\s<>"')\]]+/gi;
var EMAIL_REGEX = /[\w.%+-]{1,64}@(?:[a-z0-9-]{1,63}\.){1,10}[a-z]{2,63}/gi;
var COMMON_TLDS = "com|org|net|edu|gov|io|co|uk|de|fr|jp|au|ca|ru|ch|it|nl|se|no|es|mil|info|biz|tv|me|app|dev|ai|xyz|rs|site|tech|blog|news|club|lol|new|world|online|space|fun|live|shop|store|gg|fm|im|is|to|cc|ws|ly|gl|be|us|in|eu|asia|pro|cz|pl|fi|dk|pt|ie|nz|za|br|mx|ar|cl|kr|tw|hk|sg|id|th|vn|ph";
var BARE_DOMAIN_REGEX = new RegExp(
String.raw`\b(?:[a-z0-9][-a-z0-9]*\.)+(?:${COMMON_TLDS})\b(?:\/[^\s<>"')\]]*)?`,
"gi"
);
function extractPreservedPatterns(text) {
const preserved = /* @__PURE__ */ new Map();
let counter = 0;
let result = text;
if (text.includes("://")) {
result = result.replaceAll(URL_REGEX, (match) => {
const placeholder = `\0${counter++}\0`;
preserved.set(placeholder, match);
return placeholder;
});
}
if (result.includes("@")) {
result = result.replaceAll(EMAIL_REGEX, (match) => {
const placeholder = `\0${counter++}\0`;
preserved.set(placeholder, match);
return placeholder;
});
}
if (result.includes(".")) {
result = result.replaceAll(BARE_DOMAIN_REGEX, (match) => {
const placeholder = `\0${counter++}\0`;
preserved.set(placeholder, match);
return placeholder;
});
}
return { preserved, text: result };
}
var FANCY_APOSTROPHE = /[\u2018\u2019\u02BC]/g;
var COMBINING_MARKS = /[\u0300-\u036F]/g;
function normalizeApostrophes(text) {
return text.replaceAll(FANCY_APOSTROPHE, "'");
}
function stripDiacritics(text) {
return text.normalize("NFD").replaceAll(COMBINING_MARKS, "");
}
// src/tokenize.ts
var WORD_SPLIT_REGEX = /((?<!\d)[a-zA-Z\u00C0-\u024F']+(?!\d))/;
var WORD_TEST_REGEX = /^[a-zA-Z\u00C0-\u024F']+$/;
var IPA_SYMBOLS_SET = new Set("\u0259\u025D\u025A\u028C\xE6\u0251\u0254\u025B\u026A\u028A\xF0\u03B8\u0283\u0292\u014B\u0279\u0261");
function isIPAChar(char) {
const code = char.codePointAt(0);
if (code >= 65 && code <= 90 || code >= 97 && code <= 122) {
return true;
}
if (code === 8288) {
return true;
}
if (code === 712 || code === 716) {
return true;
}
if (IPA_SYMBOLS_SET.has(char)) {
return true;
}
return false;
}
function tokenizeIPA(text) {
const tokens = [];
let i = 0;
while (i < text.length) {
if (isIPAChar(text[i])) {
let wordEnd = i + 1;
while (wordEnd < text.length && isIPAChar(text[wordEnd])) {
wordEnd++;
}
tokens.push({ isWord: true, text: text.slice(i, wordEnd) });
i = wordEnd;
} else {
let nonWordEnd = i + 1;
while (nonWordEnd < text.length && !isIPAChar(text[nonWordEnd])) {
nonWordEnd++;
}
tokens.push({ isWord: false, text: text.slice(i, nonWordEnd) });
i = nonWordEnd;
}
}
return tokens;
}
function tokenizeText(text) {
const normalized = normalizeApostrophes(text);
const parts = normalized.split(WORD_SPLIT_REGEX);
const tokens = [];
for (const part of parts) {
if (part.length > 0) {
tokens.push({ isWord: WORD_TEST_REGEX.test(part), text: part });
}
}
return tokens;
}
export {
WORD_SPLIT_REGEX,
WORD_TEST_REGEX,
applyCasePattern,
detectCasePattern,
extractPreservedPatterns,
normalizeApostrophes,
splitCamelCase,
stripDiacritics,
tokenizeIPA,
tokenizeText
};
+47
View File
@@ -0,0 +1,47 @@
{
"name": "@ingglish/normalize",
"version": "0.1.1",
"description": "Text normalization, case handling, and URL/email preservation for Ingglish",
"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",
"prepublishOnly": "npm run build"
},
"author": "Paul Tarjan",
"license": "MIT",
"repository": {
"type": "git",
"url": "git+https://github.com/ptarjan/ingglish.git",
"directory": "packages/normalize"
},
"homepage": "https://github.com/ptarjan/ingglish#readme",
"bugs": {
"url": "https://github.com/ptarjan/ingglish/issues"
}
}
+698
View File
@@ -0,0 +1,698 @@
"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, {
ARPABET_CONSONANTS: () => ARPABET_CONSONANTS,
ARPABET_TO_INGGLISH_MAP: () => ARPABET_TO_INGGLISH_MAP,
ARPABET_VOWELS: () => ARPABET_VOWELS,
R_COLORED_FORWARD: () => R_COLORED_FORWARD,
STRESS_MARKER_REGEX: () => STRESS_MARKER_REGEX,
arpabetPhonemeToIngglish: () => arpabetPhonemeToIngglish,
arpabetToFormat: () => arpabetToFormat,
arpabetToIngglish: () => arpabetToIngglish,
createCustomConverter: () => createCustomConverter,
expandArpabetAlternatives: () => expandArpabetAlternatives,
findOnsetStart: () => findOnsetStart,
getFormatHandler: () => getFormatHandler,
getFormatIsLatinScript: () => getFormatIsLatinScript,
getFormatJoinSeparator: () => getFormatJoinSeparator,
getFormatLabel: () => getFormatLabel,
getFormatNativeLabel: () => getFormatNativeLabel,
getFormatPreservesCase: () => getFormatPreservesCase,
getStress: () => getStress,
ingglishToArpabet: () => ingglishToArpabet,
isVowel: () => isVowel,
registerFormat: () => registerFormat,
registerPronunciation: () => registerPronunciation,
stripStress: () => stripStress
});
module.exports = __toCommonJS(index_exports);
// src/arpabet.ts
var ARPABET_VOWELS = [
"AA",
// father, hot
"AE",
// cat, bat
"AH",
// but, cup (stressed) / schwa (unstressed)
"AO",
// thought, law
"AW",
// cow, how
"AY",
// my, time
"EH",
// bed, red
"ER",
// bird, her
"EY",
// say, day
"IH",
// bit, sit
"IY",
// bee, see
"OW",
// go, show
"OY",
// boy, toy
"UH",
// book, put
"UW"
// too, blue
];
var ARPABET_CONSONANTS = [
// Stops
"B",
"D",
"G",
"K",
"P",
"T",
// Fricatives
"DH",
// the, this
"F",
"HH",
// hat
"S",
"SH",
// ship
"TH",
// think
"V",
"Z",
"ZH",
// measure
// Affricates
"CH",
// chat
"JH",
// just
// Nasals
"M",
"N",
"NG",
// sing
// Liquids
"L",
"R",
// Glides
"W",
"Y"
];
var VOWELS_SET = new Set(ARPABET_VOWELS);
var CONSONANTS_SET = new Set(ARPABET_CONSONANTS);
var STRESS_MARKER_REGEX = /[012]$/;
function getStress(phoneme) {
const lastChar = phoneme.codePointAt(phoneme.length - 1);
if (lastChar >= 48 && lastChar <= 50) {
return lastChar - 48;
}
return null;
}
function isVowel(phoneme) {
const base = stripStress(phoneme);
return VOWELS_SET.has(base);
}
function stripStress(phoneme) {
const lastChar = phoneme.codePointAt(phoneme.length - 1);
if (lastChar >= 48 && lastChar <= 50) {
return phoneme.slice(0, -1);
}
return phoneme;
}
// src/phonotactics.ts
var VALID_ONSETS = /* @__PURE__ */ new Set([
// Single consonants (all are valid onsets except NG)
"B",
// Two-consonant clusters: consonant + liquid (L, R)
"B L",
"B R",
// Two-consonant clusters: consonant + glide (W, Y)
"B Y",
"CH",
"D",
"DH",
"D R",
"D W",
"D Y",
"F",
"F L",
"F R",
"F Y",
"G",
"G L",
"G R",
"G W",
"G Y",
"HH",
"HH W",
"HH Y",
"JH",
"K",
"K L",
"K R",
"K W",
"K Y",
"L",
"L Y",
"M",
"M Y",
"N",
"N Y",
"P",
"P L",
"P R",
"P Y",
"R",
"S",
"SH",
"SH R",
// Two-consonant clusters: s + consonant
"S K",
// Three-consonant clusters: s + stop + liquid/glide
"S K R",
"S K W",
"S K Y",
"S L",
"S M",
"S N",
"S P",
"S P L",
"S P R",
"S P Y",
"S T",
"S T R",
"S T Y",
"S W",
"S Y",
"T",
"TH",
"TH R",
"TH W",
"T R",
"T W",
"T Y",
"V",
"V Y",
"W",
"Y",
"Z",
"ZH"
]);
function findOnsetStart(consonants) {
if (consonants.length === 0) {
return 0;
}
for (let start = 0; start < consonants.length; start++) {
const candidate = consonants.slice(start);
if (isValidOnset(candidate)) {
return start;
}
}
return consonants.length - 1;
}
function isValidOnset(consonants) {
if (consonants.length === 0) {
return true;
}
const key = consonants.join(" ");
return VALID_ONSETS.has(key);
}
// src/format-registry.ts
var registry = /* @__PURE__ */ new Map();
var isLatinScriptCache = /* @__PURE__ */ new Map();
var preservesCaseCache = /* @__PURE__ */ new Map();
function getFormatHandler(name) {
return registry.get(name);
}
function getFormatIsLatinScript(name) {
return isLatinScriptCache.get(name) ?? true;
}
function getFormatJoinSeparator(name) {
return registry.get(name)?.joinSeparator ?? "";
}
function getFormatLabel(name) {
return registry.get(name)?.label ?? name;
}
function getFormatNativeLabel(name) {
const handler = registry.get(name);
return handler?.nativeLabel ?? handler?.label ?? name;
}
function getFormatPreservesCase(name) {
return preservesCaseCache.get(name) ?? true;
}
function registerFormat(name, handler) {
const existing = registry.get(name);
const merged = { ...existing, ...handler };
registry.set(name, merged);
isLatinScriptCache.set(name, merged.isLatinScript ?? true);
preservesCaseCache.set(name, merged.preservesCase ?? merged.isLatinScript ?? true);
}
// src/ingglish-maps.ts
var INGGLISH_VOWEL_MAP = {
// Monophthongs
AA: "o",
// father, hot, rock (but AA+R → 'ar' in star, car)
AE: "a",
// cat, bat, had (but AE+R → 'arr' in arrow, barrow)
AH: "uh",
// but, cup, son (stressed /ʌ/; unstressed /ə/ AH0 → 'a' in conversion)
AO: "aw",
// thought, caught, law (but AO+R → 'or' in store, more)
// Diphthongs
AW: "ou",
// cow, how, out
AY: "ai",
// my, eye, time
EH: "e",
// bed, red, said (but EH+R → 'air' in air, care, there)
ER: "er",
// bird, her, nurse
EY: "ay",
// say, day, make
IH: "i",
// bit, sit, gym
IY: "ee",
// bee, see, machine
OW: "oh",
// go, show, coat
OY: "oi",
// boy, toy, coin
UH: "u",
// book, put, could
UW: "oo"
// too, blue, food
};
var INGGLISH_CONSONANT_MAP = {
// Stops (plosives)
B: "b",
// bat, cab
// Affricates
CH: "ch",
// chat, batch
D: "d",
// dog, bed
// Fricatives
DH: "dh",
// the, this (voiced) - distinguishes from TH
F: "f",
// fat, laugh
G: "g",
// go, big
// Aspirate
HH: "h",
// hat, ahead
JH: "j",
// just, edge
K: "k",
// cat, back
// Liquids
L: "l",
// let, well
// Nasals
M: "m",
// man, come
N: "n",
// no, pen
NG: "ng",
// sing, thing
P: "p",
// pat, cup
R: "r",
// run, car
S: "s",
// sat, miss
SH: "sh",
// she, push
T: "t",
// top, cat
TH: "th",
// think, bath (voiceless)
V: "v",
// van, love
// Semivowels (glides)
W: "w",
// wet, away
Y: "y",
// yes, you
Z: "z",
// zoo, is
ZH: "zh"
// measure, beige
};
var ARPABET_TO_INGGLISH_MAP = {
...INGGLISH_VOWEL_MAP,
...INGGLISH_CONSONANT_MAP
};
var INGGLISH_TO_ARPABET_MAP = Object.fromEntries(
Object.entries(ARPABET_TO_INGGLISH_MAP).map(([arpabet, ingglish]) => [ingglish, arpabet])
);
var R_COLORED_VOWELS = [
{ arpabet: "AA", prefix: "a" },
// star, car, far → 'ar'
{ arpabet: "AO", prefix: "o" },
// store, more, for → 'or'
{ arpabet: "EH", prefix: "ai" },
// air, care, there → 'air'
{ arpabet: "AE", prefix: "ar" },
// arrow, barrow, carrot → 'arr'
{ arpabet: "IH", prefix: "ee" },
// beer, beard, fear → 'eer'
{ arpabet: "UH", prefix: "u" },
// tour, cure, pure → 'ur' (CURE vowel, experimentable)
{ arpabet: "AH", prefix: "uh" }
// curry, burroughs → 'uhr' (AH=uh, prevents AH0+R collision with 'ar')
];
var R_COLORED_FORWARD = new Map(
R_COLORED_VOWELS.map(({ arpabet, prefix }) => [arpabet, prefix])
);
var R_COLORED_REVERSE_3CHAR = Object.fromEntries(
R_COLORED_VOWELS.filter(({ prefix }) => prefix.length === 2).map(({ arpabet, prefix }) => [
prefix + "r",
[arpabet, "R"]
])
);
var R_COLORED_REVERSE_2CHAR = Object.fromEntries(
R_COLORED_VOWELS.filter(({ prefix }) => prefix.length === 1).map(({ arpabet, prefix }) => [
prefix + "r",
[arpabet, "R"]
])
);
// src/to-ingglish.ts
function arpabetPhonemeToIngglish(phoneme) {
if (phoneme === "AH0") {
return "a";
}
const base = stripStress(phoneme);
return ARPABET_TO_INGGLISH_MAP[base] ?? phoneme.toLowerCase();
}
function convertArpabet(arpabet, phonemeMap, rColoredMap, stressOverrides) {
let result = "";
const len = arpabet.length;
for (let i = 0; i < len; i++) {
const phoneme = arpabet[i];
const base = stripStress(phoneme);
if (i + 1 < len && arpabet[i + 1] === "R") {
const rPrefix = rColoredMap.get(base);
if (rPrefix !== void 0) {
result += rPrefix;
continue;
}
}
const stressOverride = stressOverrides.get(phoneme);
if (stressOverride !== void 0) {
result += stressOverride;
continue;
}
result += phonemeMap[base] ?? phoneme.toLowerCase();
}
return result;
}
var INGGLISH_FULL_MAP = {};
for (const [base, spelling] of Object.entries(ARPABET_TO_INGGLISH_MAP)) {
INGGLISH_FULL_MAP[base] = spelling;
INGGLISH_FULL_MAP[base + "0"] = spelling;
INGGLISH_FULL_MAP[base + "1"] = spelling;
INGGLISH_FULL_MAP[base + "2"] = spelling;
}
INGGLISH_FULL_MAP.AH0 = "a";
function arpabetToIngglish(arpabet) {
let result = "";
const len = arpabet.length;
for (let i = 0; i < len; i++) {
const phoneme = arpabet[i];
if (i + 1 < len && arpabet[i + 1] === "R") {
const base = stripStress(phoneme);
const rPrefix = R_COLORED_FORWARD.get(base);
if (rPrefix !== void 0) {
result += rPrefix;
continue;
}
}
result += INGGLISH_FULL_MAP[phoneme] ?? phoneme.toLowerCase();
}
return result;
}
registerFormat("ingglish", {
forward: arpabetToIngglish,
isLatinScript: true,
label: "Ingglish",
preservesCase: true
});
var EMPTY_R_COLORED = /* @__PURE__ */ new Map();
var INGGLISH_STRESS_OVERRIDES = /* @__PURE__ */ new Map([["AH0", "a"]]);
function arpabetToFormat(arpabet, format = "ingglish", options) {
if (format === "ingglish") {
if (options?.disableRColoring === true) {
return convertArpabet(
arpabet,
ARPABET_TO_INGGLISH_MAP,
EMPTY_R_COLORED,
INGGLISH_STRESS_OVERRIDES
);
}
return arpabetToIngglish(arpabet);
}
const handler = getFormatHandler(format);
if (handler?.forward) {
return handler.forward(arpabet, options);
}
return arpabetToIngglish(arpabet);
}
// src/to-pronunciation.ts
var GUIDE_MAP = {};
for (const [base, spelling] of Object.entries(ARPABET_TO_INGGLISH_MAP)) {
GUIDE_MAP[base] = spelling;
GUIDE_MAP[base + "0"] = spelling;
GUIDE_MAP[base + "1"] = spelling;
GUIDE_MAP[base + "2"] = spelling;
}
GUIDE_MAP.AH0 = "a";
function arpabetToPronunciation(arpabet) {
const syllables = syllabify(arpabet);
return syllables.map(({ phonemes, stress }) => {
const spelling = syllableToSpelling(phonemes);
return stress >= 1 ? spelling.toUpperCase() : spelling;
}).join("-");
}
function registerPronunciation() {
registerFormat("pronunciation", {
forward: arpabetToPronunciation,
isLatinScript: true,
label: "Guide",
preservesCase: false
});
}
function syllabify(arpabet) {
const vowelIndices = [];
for (const [i, phoneme] of arpabet.entries()) {
if (isVowel(phoneme)) {
vowelIndices.push(i);
}
}
if (vowelIndices.length === 0) {
return [{ phonemes: arpabet, stress: 0 }];
}
const syllables = [];
let start = 0;
for (let vi = 0; vi < vowelIndices.length; vi++) {
const vowelIdx = vowelIndices[vi];
const stress = getStress(arpabet[vowelIdx]) ?? 0;
if (vi < vowelIndices.length - 1) {
const nextVowelIdx = vowelIndices[vi + 1];
const consonantStart = vowelIdx + 1;
const consonants = [];
for (let j = consonantStart; j < nextVowelIdx; j++) {
consonants.push(stripStress(arpabet[j]));
}
if (consonants.length === 0) {
syllables.push({ phonemes: arpabet.slice(start, consonantStart), stress });
start = consonantStart;
} else {
const onsetIdx = findOnsetStart(consonants);
const boundary = consonantStart + onsetIdx;
syllables.push({ phonemes: arpabet.slice(start, boundary), stress });
start = boundary;
}
} else {
syllables.push({ phonemes: arpabet.slice(start), stress });
}
}
return syllables;
}
function syllableToSpelling(phonemes) {
let result = "";
for (let i = 0; i < phonemes.length; i++) {
const phoneme = phonemes[i];
if (i + 1 < phonemes.length && phonemes[i + 1] === "R") {
const base = stripStress(phoneme);
const rPrefix = R_COLORED_FORWARD.get(base);
if (rPrefix !== void 0) {
result += rPrefix;
continue;
}
}
result += GUIDE_MAP[phoneme] ?? phoneme.toLowerCase();
}
return result;
}
// src/from-ingglish.ts
var ARPABET_ALTERNATIVES = {
AE: [["AH"]],
// "a" could be AE (cat) or AH (schwa: about, the)
ER: [["EH", "R"]],
SH: [["S", "HH"]]
// "sh" could be SH (ship) or S+HH (exhume)
};
var ARPABET_ALTERNATIVES_ENTRIES = Object.entries(ARPABET_ALTERNATIVES);
function expandArpabetAlternatives(arpabet) {
const results = [arpabet];
for (let i = 0; i < arpabet.length; i++) {
const alternatives = ARPABET_ALTERNATIVES[arpabet[i]];
if (alternatives !== void 0) {
for (const alt of alternatives) {
const expanded = [...arpabet.slice(0, i), ...alt, ...arpabet.slice(i + 1)];
results.push(expanded);
}
}
}
for (const [phoneme, alts] of ARPABET_ALTERNATIVES_ENTRIES) {
for (const alt of alts) {
if (alt.length === 1) {
let count = 0;
for (const p of arpabet) {
if (p === phoneme) {
count++;
}
}
if (count >= 2) {
results.push(arpabet.map((p) => p === phoneme ? alt[0] : p));
}
}
}
}
return results;
}
var TWO_CHAR_SPELLINGS = new Set(
Object.keys(INGGLISH_TO_ARPABET_MAP).filter((s) => s.length === 2)
);
var ONE_CHAR_SPELLINGS = new Set(
Object.keys(INGGLISH_TO_ARPABET_MAP).filter((s) => s.length === 1)
);
function ingglishToArpabet(ingglish) {
const result = [];
const str = ingglish.toLowerCase();
const len = str.length;
let pos = 0;
while (pos < len) {
if (pos + 3 <= len) {
const threeChar = str.slice(pos, pos + 3);
if (threeChar in R_COLORED_REVERSE_3CHAR) {
result.push(...R_COLORED_REVERSE_3CHAR[threeChar]);
pos += 3;
continue;
}
}
if (pos + 2 <= len) {
const twoChar = str.slice(pos, pos + 2);
if (twoChar in R_COLORED_REVERSE_2CHAR) {
result.push(...R_COLORED_REVERSE_2CHAR[twoChar]);
pos += 2;
continue;
}
if (TWO_CHAR_SPELLINGS.has(twoChar)) {
result.push(INGGLISH_TO_ARPABET_MAP[twoChar]);
pos += 2;
continue;
}
}
const oneChar = str[pos];
if (ONE_CHAR_SPELLINGS.has(oneChar)) {
result.push(INGGLISH_TO_ARPABET_MAP[oneChar]);
pos += 1;
continue;
}
pos += 1;
}
return result.length > 0 ? result : null;
}
// src/custom-format.ts
function createCustomConverter(config) {
const mergedMap = { ...ARPABET_TO_INGGLISH_MAP, ...config.phonemeMap };
const mergedRColored = new Map(R_COLORED_FORWARD);
for (const [vowel] of R_COLORED_FORWARD) {
if (vowel in config.phonemeMap && !(vowel in config.rColoredPrefixes)) {
mergedRColored.set(vowel, config.phonemeMap[vowel]);
}
}
for (const [key, value] of Object.entries(config.rColoredPrefixes)) {
mergedRColored.set(key, value);
}
const stressOverrides = /* @__PURE__ */ new Map([["AH0", "a"]]);
for (const [key, value] of Object.entries(config.phonemeMap)) {
const lastChar = key.codePointAt(key.length - 1);
if (lastChar >= 48 && lastChar <= 50) {
stressOverrides.set(key, value);
}
}
const emptyRColored = /* @__PURE__ */ new Map();
return (arpabet, options) => convertArpabet(
arpabet,
mergedMap,
options?.disableRColoring === true ? emptyRColored : mergedRColored,
stressOverrides
);
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
ARPABET_CONSONANTS,
ARPABET_TO_INGGLISH_MAP,
ARPABET_VOWELS,
R_COLORED_FORWARD,
STRESS_MARKER_REGEX,
arpabetPhonemeToIngglish,
arpabetToFormat,
arpabetToIngglish,
createCustomConverter,
expandArpabetAlternatives,
findOnsetStart,
getFormatHandler,
getFormatIsLatinScript,
getFormatJoinSeparator,
getFormatLabel,
getFormatNativeLabel,
getFormatPreservesCase,
getStress,
ingglishToArpabet,
isVowel,
registerFormat,
registerPronunciation,
stripStress
});
+254
View File
@@ -0,0 +1,254 @@
/**
* ARPAbet phoneme utilities and constants.
*
* ARPAbet is the phonetic notation system used by the CMU Pronouncing Dictionary.
* Each English phoneme is represented by a 1-3 letter code, with vowels having
* optional stress markers (0=unstressed, 1=primary, 2=secondary).
*/
/**
* All ARPAbet vowel phonemes (without stress markers).
*/
declare const ARPABET_VOWELS: readonly ["AA", "AE", "AH", "AO", "AW", "AY", "EH", "ER", "EY", "IH", "IY", "OW", "OY", "UH", "UW"];
/**
* All ARPAbet consonant phonemes.
*/
declare const ARPABET_CONSONANTS: readonly ["B", "D", "G", "K", "P", "T", "DH", "F", "HH", "S", "SH", "TH", "V", "Z", "ZH", "CH", "JH", "M", "N", "NG", "L", "R", "W", "Y"];
/** Regex pattern to match ARPAbet stress markers (0, 1, 2) at end of phoneme */
declare const STRESS_MARKER_REGEX: RegExp;
/**
* Extracts the stress level from a phoneme.
* Returns null for consonants or vowels without explicit stress.
* Uses charCode check instead of regex (consistent with stripStress).
*
* @example
* getStress('AH0') // 0
* getStress('EY1') // 1
* getStress('AO2') // 2
* getStress('B') // null
*/
declare function getStress(phoneme: string): 0 | 1 | 2 | null;
/**
* Checks if an ARPAbet phoneme is a vowel.
* Vowels can have stress markers (0, 1, 2).
*
* @example
* isVowel('AH0') // true
* isVowel('EY1') // true
* isVowel('B') // false
*/
declare function isVowel(phoneme: string): boolean;
/**
* Strips stress markers (0, 1, 2) from a phoneme.
* Uses charCode check instead of regex (benchmarked 2x faster).
*
* @example
* stripStress('AH0') // 'AH'
* stripStress('EY1') // 'EY'
* stripStress('B') // 'B'
*/
declare function stripStress(phoneme: string): string;
/**
* Finds the starting index of the maximal valid onset from a consonant cluster.
*
* Uses the Maximal Onset Principle: assign as many consonants as possible
* to the onset, as long as they form a legal onset cluster. The remaining
* consonants become the coda of the previous syllable.
*
* @param consonants Array of consonant phonemes between two vowels
* @returns Index within the consonant array where the valid onset begins
*
* @example
* // "extra" has consonants [K, S, T, R] between vowels
* // [S, T, R] is valid onset, so onset starts at index 1
* findOnsetStart(['K', 'S', 'T', 'R']) // 1
*
* // "instruct" has [N, S, T, R]
* // [S, T, R] is valid, so onset starts at index 1
* findOnsetStart(['N', 'S', 'T', 'R']) // 1
*/
declare function findOnsetStart(consonants: string[]): number;
interface FormatHandler {
forward?: ForwardConverter;
isLatinScript?: boolean;
/** Compound word join separator. Default '' */
joinSeparator?: string;
/** Display name ('Ingglish', 'IPA', etc.) */
label?: string;
/** Display name in the format's own script (e.g. '𐑖𐑱𐑝𐑾𐑯' for Shavian) */
nativeLabel?: string;
/** Whether case is preserved (caps, sentence start). Defaults to isLatinScript. */
preservesCase?: boolean;
reverseText?: ReverseTextConverter;
reverseTextWithMapping?: ReverseTextWithMappingConverter;
}
type ForwardConverter = (arpabet: string[], options?: ForwardConverterOptions) => string;
interface ForwardConverterOptions {
/** Disable English R-coloring rules (vowel+R fusion). Use for foreign text. */
disableRColoring?: boolean;
}
/** Token returned by reverse-with-mapping translation */
interface ReverseToken {
isWord: boolean;
matched?: boolean;
original: string;
translated: string;
}
type ReverseTextConverter = (text: string) => string;
type ReverseTextWithMappingConverter = (text: string) => ReverseToken[];
declare function getFormatHandler(name: string): FormatHandler | undefined;
/**
* Returns whether a format uses Latin script characters.
* Defaults to true for unknown formats (safe for case handling).
*/
declare function getFormatIsLatinScript(name: string): boolean;
/**
* Returns the join separator for compound word parts.
* Defaults to '' (no separator).
*/
declare function getFormatJoinSeparator(name: string): string;
/**
* Returns the display label for a format (e.g. 'Ingglish', 'IPA').
* Falls back to the raw format name.
*/
declare function getFormatLabel(name: string): string;
/**
* Returns the native-script label for a format (e.g. '𐑖𐑱𐑝𐑾𐑯' for Shavian).
* Falls back to the standard label, then the raw format name.
*/
declare function getFormatNativeLabel(name: string): string;
/**
* Returns whether a format preserves case (capitalization, sentence start).
* Falls back to isLatinScript, then true for unknown formats.
*/
declare function getFormatPreservesCase(name: string): boolean;
declare function registerFormat(name: string, handler: FormatHandler): void;
/**
* Output format for phoneme conversion.
*/
type OutputFormat = 'ingglish' | 'ipa' | (string & {});
/**
* ARPAbet to Ingglish conversion.
*
* Converts CMU dictionary phoneme sequences to Ingglish spelling.
* Ingglish is a phonetic spelling system that uses only standard
* English letters with no ambiguity.
*/
/**
* Converts a single ARPAbet phoneme to Ingglish spelling.
*
* @param phoneme ARPAbet phoneme (e.g., "AH0", "EY1", "B")
* @returns Ingglish spelling (e.g., "a", "ay", "b")
*/
declare function arpabetPhonemeToIngglish(phoneme: string): string;
/**
* Converts an array of ARPAbet phonemes to Ingglish spelling.
* Uses direct loop + string concat (benchmarked 60% faster than map+join).
*
* R-colored vowels: AA+R → 'ar', AO+R → 'or', IH+R → 'eer' (more intuitive than 'or'/'awr'/'ir')
*
* @param arpabet Array of ARPAbet symbols (e.g., ["HH", "AH0", "L", "OW1"])
* @returns Ingglish spelling (e.g., "haloh")
*/
declare function arpabetToIngglish(arpabet: string[]): string;
interface FormatOptions {
/** Disable English R-coloring rules (vowel+R fusion). Use for foreign text. */
disableRColoring?: boolean;
}
/**
* Universal pipeline exit point: converts the ARPAbet IR to any output format.
*
* Every translation path (dictionary, fallback, G2P) produces an ARPAbet
* `string[]` and calls this function to get the final user-facing string.
*
* @param arpabet Array of ARPAbet symbols (the IR)
* @param format Output format (e.g. 'ingglish', 'ipa', 'shavian')
* @param options Conversion options (e.g. disable R-coloring for foreign text)
* @returns Formatted string
*/
declare function arpabetToFormat(arpabet: string[], format?: OutputFormat, options?: FormatOptions): string;
declare function registerPronunciation(): void;
/**
* Ingglish to ARPAbet conversion.
*
* Used to parse Ingglish spellings back to ARPAbet phonemes
* for reverse translation (Ingglish -> English).
*/
/**
* Generates alternative ARPAbet sequences for ambiguous spellings.
*
* For length-changing alternatives (ER→EH+R, SH→S+HH), generates
* single-position substitutions. For same-length alternatives (AE→AH),
* also generates an "all-replaced" variant to handle words with multiple
* ambiguous vowels (e.g., "difakalt" → D IH F AH K AH L T).
*/
declare function expandArpabetAlternatives(arpabet: string[]): string[][];
/**
* Converts an Ingglish spelling to ARPAbet phonemes.
* Uses index-based parsing to avoid intermediate string allocations.
*
* @param ingglish - Ingglish string (e.g., "haloh" for "hello")
* @returns Array of ARPAbet phonemes (e.g., ["HH", "AH", "L", "OW"]), or null if empty
*/
declare function ingglishToArpabet(ingglish: string): null | string[];
/**
* Combined ARPAbet to Ingglish map.
*/
declare const ARPABET_TO_INGGLISH_MAP: Record<string, string>;
/**
* Forward lookup: ARPAbet vowel → Ingglish prefix (before 'r').
* Used by arpabetToIngglish() to handle VOWEL+R sequences.
*/
declare const R_COLORED_FORWARD: Map<string, string>;
/**
* Custom format converter builder.
*
* Creates ARPAbet-to-spelling converters using user-defined phoneme mappings.
* Mirrors arpabetToIngglish() logic but uses merged custom mappings.
*/
/**
* Configuration for a custom phoneme-to-spelling mapping.
* Only diffs from the default Ingglish mapping need to be specified.
*/
interface CustomMappingConfig {
/** Overrides of ARPABET_TO_INGGLISH_MAP. Includes AH0 as a separate key. */
phonemeMap: Record<string, string>;
/** Overrides of R_COLORED_FORWARD prefixes (keyed by base vowel, e.g. 'AA'). */
rColoredPrefixes: Record<string, string>;
}
/**
* Creates a forward converter function from a custom mapping config.
*
* The converter checks phonemes in this order:
* 1. Exact phoneme with stress digit (e.g., AH0, EY0) in phonemeMap
* 2. Stress-stripped base (e.g., AH, EY) in phonemeMap
* 3. Default ARPABET_TO_INGGLISH_MAP
* 4. Lowercase phoneme as fallback
*/
declare function createCustomConverter(config: CustomMappingConfig): (arpabet: string[], options?: ForwardConverterOptions) => string;
/**
* A single token from a translated text, preserving the mapping between
* original and translated forms. Used by both forward and reverse translation.
*/
interface TranslatedToken {
/** Whether this token is a word (true) or punctuation/whitespace (false). */
isWord: boolean;
/** Whether the word was found in the dictionary (false = heuristic fallback). */
matched: boolean;
/** The original text of this token (English for forward, Ingglish for reverse). */
original: string;
/** The translated text (Ingglish for forward, English for reverse). */
translated: string;
}
export { ARPABET_CONSONANTS, ARPABET_TO_INGGLISH_MAP, ARPABET_VOWELS, type CustomMappingConfig, type OutputFormat, R_COLORED_FORWARD, type ReverseToken, STRESS_MARKER_REGEX, type TranslatedToken, arpabetPhonemeToIngglish, arpabetToFormat, arpabetToIngglish, createCustomConverter, expandArpabetAlternatives, findOnsetStart, getFormatHandler, getFormatIsLatinScript, getFormatJoinSeparator, getFormatLabel, getFormatNativeLabel, getFormatPreservesCase, getStress, ingglishToArpabet, isVowel, registerFormat, registerPronunciation, stripStress };
+254
View File
@@ -0,0 +1,254 @@
/**
* ARPAbet phoneme utilities and constants.
*
* ARPAbet is the phonetic notation system used by the CMU Pronouncing Dictionary.
* Each English phoneme is represented by a 1-3 letter code, with vowels having
* optional stress markers (0=unstressed, 1=primary, 2=secondary).
*/
/**
* All ARPAbet vowel phonemes (without stress markers).
*/
declare const ARPABET_VOWELS: readonly ["AA", "AE", "AH", "AO", "AW", "AY", "EH", "ER", "EY", "IH", "IY", "OW", "OY", "UH", "UW"];
/**
* All ARPAbet consonant phonemes.
*/
declare const ARPABET_CONSONANTS: readonly ["B", "D", "G", "K", "P", "T", "DH", "F", "HH", "S", "SH", "TH", "V", "Z", "ZH", "CH", "JH", "M", "N", "NG", "L", "R", "W", "Y"];
/** Regex pattern to match ARPAbet stress markers (0, 1, 2) at end of phoneme */
declare const STRESS_MARKER_REGEX: RegExp;
/**
* Extracts the stress level from a phoneme.
* Returns null for consonants or vowels without explicit stress.
* Uses charCode check instead of regex (consistent with stripStress).
*
* @example
* getStress('AH0') // 0
* getStress('EY1') // 1
* getStress('AO2') // 2
* getStress('B') // null
*/
declare function getStress(phoneme: string): 0 | 1 | 2 | null;
/**
* Checks if an ARPAbet phoneme is a vowel.
* Vowels can have stress markers (0, 1, 2).
*
* @example
* isVowel('AH0') // true
* isVowel('EY1') // true
* isVowel('B') // false
*/
declare function isVowel(phoneme: string): boolean;
/**
* Strips stress markers (0, 1, 2) from a phoneme.
* Uses charCode check instead of regex (benchmarked 2x faster).
*
* @example
* stripStress('AH0') // 'AH'
* stripStress('EY1') // 'EY'
* stripStress('B') // 'B'
*/
declare function stripStress(phoneme: string): string;
/**
* Finds the starting index of the maximal valid onset from a consonant cluster.
*
* Uses the Maximal Onset Principle: assign as many consonants as possible
* to the onset, as long as they form a legal onset cluster. The remaining
* consonants become the coda of the previous syllable.
*
* @param consonants Array of consonant phonemes between two vowels
* @returns Index within the consonant array where the valid onset begins
*
* @example
* // "extra" has consonants [K, S, T, R] between vowels
* // [S, T, R] is valid onset, so onset starts at index 1
* findOnsetStart(['K', 'S', 'T', 'R']) // 1
*
* // "instruct" has [N, S, T, R]
* // [S, T, R] is valid, so onset starts at index 1
* findOnsetStart(['N', 'S', 'T', 'R']) // 1
*/
declare function findOnsetStart(consonants: string[]): number;
interface FormatHandler {
forward?: ForwardConverter;
isLatinScript?: boolean;
/** Compound word join separator. Default '' */
joinSeparator?: string;
/** Display name ('Ingglish', 'IPA', etc.) */
label?: string;
/** Display name in the format's own script (e.g. '𐑖𐑱𐑝𐑾𐑯' for Shavian) */
nativeLabel?: string;
/** Whether case is preserved (caps, sentence start). Defaults to isLatinScript. */
preservesCase?: boolean;
reverseText?: ReverseTextConverter;
reverseTextWithMapping?: ReverseTextWithMappingConverter;
}
type ForwardConverter = (arpabet: string[], options?: ForwardConverterOptions) => string;
interface ForwardConverterOptions {
/** Disable English R-coloring rules (vowel+R fusion). Use for foreign text. */
disableRColoring?: boolean;
}
/** Token returned by reverse-with-mapping translation */
interface ReverseToken {
isWord: boolean;
matched?: boolean;
original: string;
translated: string;
}
type ReverseTextConverter = (text: string) => string;
type ReverseTextWithMappingConverter = (text: string) => ReverseToken[];
declare function getFormatHandler(name: string): FormatHandler | undefined;
/**
* Returns whether a format uses Latin script characters.
* Defaults to true for unknown formats (safe for case handling).
*/
declare function getFormatIsLatinScript(name: string): boolean;
/**
* Returns the join separator for compound word parts.
* Defaults to '' (no separator).
*/
declare function getFormatJoinSeparator(name: string): string;
/**
* Returns the display label for a format (e.g. 'Ingglish', 'IPA').
* Falls back to the raw format name.
*/
declare function getFormatLabel(name: string): string;
/**
* Returns the native-script label for a format (e.g. '𐑖𐑱𐑝𐑾𐑯' for Shavian).
* Falls back to the standard label, then the raw format name.
*/
declare function getFormatNativeLabel(name: string): string;
/**
* Returns whether a format preserves case (capitalization, sentence start).
* Falls back to isLatinScript, then true for unknown formats.
*/
declare function getFormatPreservesCase(name: string): boolean;
declare function registerFormat(name: string, handler: FormatHandler): void;
/**
* Output format for phoneme conversion.
*/
type OutputFormat = 'ingglish' | 'ipa' | (string & {});
/**
* ARPAbet to Ingglish conversion.
*
* Converts CMU dictionary phoneme sequences to Ingglish spelling.
* Ingglish is a phonetic spelling system that uses only standard
* English letters with no ambiguity.
*/
/**
* Converts a single ARPAbet phoneme to Ingglish spelling.
*
* @param phoneme ARPAbet phoneme (e.g., "AH0", "EY1", "B")
* @returns Ingglish spelling (e.g., "a", "ay", "b")
*/
declare function arpabetPhonemeToIngglish(phoneme: string): string;
/**
* Converts an array of ARPAbet phonemes to Ingglish spelling.
* Uses direct loop + string concat (benchmarked 60% faster than map+join).
*
* R-colored vowels: AA+R → 'ar', AO+R → 'or', IH+R → 'eer' (more intuitive than 'or'/'awr'/'ir')
*
* @param arpabet Array of ARPAbet symbols (e.g., ["HH", "AH0", "L", "OW1"])
* @returns Ingglish spelling (e.g., "haloh")
*/
declare function arpabetToIngglish(arpabet: string[]): string;
interface FormatOptions {
/** Disable English R-coloring rules (vowel+R fusion). Use for foreign text. */
disableRColoring?: boolean;
}
/**
* Universal pipeline exit point: converts the ARPAbet IR to any output format.
*
* Every translation path (dictionary, fallback, G2P) produces an ARPAbet
* `string[]` and calls this function to get the final user-facing string.
*
* @param arpabet Array of ARPAbet symbols (the IR)
* @param format Output format (e.g. 'ingglish', 'ipa', 'shavian')
* @param options Conversion options (e.g. disable R-coloring for foreign text)
* @returns Formatted string
*/
declare function arpabetToFormat(arpabet: string[], format?: OutputFormat, options?: FormatOptions): string;
declare function registerPronunciation(): void;
/**
* Ingglish to ARPAbet conversion.
*
* Used to parse Ingglish spellings back to ARPAbet phonemes
* for reverse translation (Ingglish -> English).
*/
/**
* Generates alternative ARPAbet sequences for ambiguous spellings.
*
* For length-changing alternatives (ER→EH+R, SH→S+HH), generates
* single-position substitutions. For same-length alternatives (AE→AH),
* also generates an "all-replaced" variant to handle words with multiple
* ambiguous vowels (e.g., "difakalt" → D IH F AH K AH L T).
*/
declare function expandArpabetAlternatives(arpabet: string[]): string[][];
/**
* Converts an Ingglish spelling to ARPAbet phonemes.
* Uses index-based parsing to avoid intermediate string allocations.
*
* @param ingglish - Ingglish string (e.g., "haloh" for "hello")
* @returns Array of ARPAbet phonemes (e.g., ["HH", "AH", "L", "OW"]), or null if empty
*/
declare function ingglishToArpabet(ingglish: string): null | string[];
/**
* Combined ARPAbet to Ingglish map.
*/
declare const ARPABET_TO_INGGLISH_MAP: Record<string, string>;
/**
* Forward lookup: ARPAbet vowel → Ingglish prefix (before 'r').
* Used by arpabetToIngglish() to handle VOWEL+R sequences.
*/
declare const R_COLORED_FORWARD: Map<string, string>;
/**
* Custom format converter builder.
*
* Creates ARPAbet-to-spelling converters using user-defined phoneme mappings.
* Mirrors arpabetToIngglish() logic but uses merged custom mappings.
*/
/**
* Configuration for a custom phoneme-to-spelling mapping.
* Only diffs from the default Ingglish mapping need to be specified.
*/
interface CustomMappingConfig {
/** Overrides of ARPABET_TO_INGGLISH_MAP. Includes AH0 as a separate key. */
phonemeMap: Record<string, string>;
/** Overrides of R_COLORED_FORWARD prefixes (keyed by base vowel, e.g. 'AA'). */
rColoredPrefixes: Record<string, string>;
}
/**
* Creates a forward converter function from a custom mapping config.
*
* The converter checks phonemes in this order:
* 1. Exact phoneme with stress digit (e.g., AH0, EY0) in phonemeMap
* 2. Stress-stripped base (e.g., AH, EY) in phonemeMap
* 3. Default ARPABET_TO_INGGLISH_MAP
* 4. Lowercase phoneme as fallback
*/
declare function createCustomConverter(config: CustomMappingConfig): (arpabet: string[], options?: ForwardConverterOptions) => string;
/**
* A single token from a translated text, preserving the mapping between
* original and translated forms. Used by both forward and reverse translation.
*/
interface TranslatedToken {
/** Whether this token is a word (true) or punctuation/whitespace (false). */
isWord: boolean;
/** Whether the word was found in the dictionary (false = heuristic fallback). */
matched: boolean;
/** The original text of this token (English for forward, Ingglish for reverse). */
original: string;
/** The translated text (Ingglish for forward, English for reverse). */
translated: string;
}
export { ARPABET_CONSONANTS, ARPABET_TO_INGGLISH_MAP, ARPABET_VOWELS, type CustomMappingConfig, type OutputFormat, R_COLORED_FORWARD, type ReverseToken, STRESS_MARKER_REGEX, type TranslatedToken, arpabetPhonemeToIngglish, arpabetToFormat, arpabetToIngglish, createCustomConverter, expandArpabetAlternatives, findOnsetStart, getFormatHandler, getFormatIsLatinScript, getFormatJoinSeparator, getFormatLabel, getFormatNativeLabel, getFormatPreservesCase, getStress, ingglishToArpabet, isVowel, registerFormat, registerPronunciation, stripStress };
+649
View File
@@ -0,0 +1,649 @@
// src/arpabet.ts
var ARPABET_VOWELS = [
"AA",
// father, hot
"AE",
// cat, bat
"AH",
// but, cup (stressed) / schwa (unstressed)
"AO",
// thought, law
"AW",
// cow, how
"AY",
// my, time
"EH",
// bed, red
"ER",
// bird, her
"EY",
// say, day
"IH",
// bit, sit
"IY",
// bee, see
"OW",
// go, show
"OY",
// boy, toy
"UH",
// book, put
"UW"
// too, blue
];
var ARPABET_CONSONANTS = [
// Stops
"B",
"D",
"G",
"K",
"P",
"T",
// Fricatives
"DH",
// the, this
"F",
"HH",
// hat
"S",
"SH",
// ship
"TH",
// think
"V",
"Z",
"ZH",
// measure
// Affricates
"CH",
// chat
"JH",
// just
// Nasals
"M",
"N",
"NG",
// sing
// Liquids
"L",
"R",
// Glides
"W",
"Y"
];
var VOWELS_SET = new Set(ARPABET_VOWELS);
var CONSONANTS_SET = new Set(ARPABET_CONSONANTS);
var STRESS_MARKER_REGEX = /[012]$/;
function getStress(phoneme) {
const lastChar = phoneme.codePointAt(phoneme.length - 1);
if (lastChar >= 48 && lastChar <= 50) {
return lastChar - 48;
}
return null;
}
function isVowel(phoneme) {
const base = stripStress(phoneme);
return VOWELS_SET.has(base);
}
function stripStress(phoneme) {
const lastChar = phoneme.codePointAt(phoneme.length - 1);
if (lastChar >= 48 && lastChar <= 50) {
return phoneme.slice(0, -1);
}
return phoneme;
}
// src/phonotactics.ts
var VALID_ONSETS = /* @__PURE__ */ new Set([
// Single consonants (all are valid onsets except NG)
"B",
// Two-consonant clusters: consonant + liquid (L, R)
"B L",
"B R",
// Two-consonant clusters: consonant + glide (W, Y)
"B Y",
"CH",
"D",
"DH",
"D R",
"D W",
"D Y",
"F",
"F L",
"F R",
"F Y",
"G",
"G L",
"G R",
"G W",
"G Y",
"HH",
"HH W",
"HH Y",
"JH",
"K",
"K L",
"K R",
"K W",
"K Y",
"L",
"L Y",
"M",
"M Y",
"N",
"N Y",
"P",
"P L",
"P R",
"P Y",
"R",
"S",
"SH",
"SH R",
// Two-consonant clusters: s + consonant
"S K",
// Three-consonant clusters: s + stop + liquid/glide
"S K R",
"S K W",
"S K Y",
"S L",
"S M",
"S N",
"S P",
"S P L",
"S P R",
"S P Y",
"S T",
"S T R",
"S T Y",
"S W",
"S Y",
"T",
"TH",
"TH R",
"TH W",
"T R",
"T W",
"T Y",
"V",
"V Y",
"W",
"Y",
"Z",
"ZH"
]);
function findOnsetStart(consonants) {
if (consonants.length === 0) {
return 0;
}
for (let start = 0; start < consonants.length; start++) {
const candidate = consonants.slice(start);
if (isValidOnset(candidate)) {
return start;
}
}
return consonants.length - 1;
}
function isValidOnset(consonants) {
if (consonants.length === 0) {
return true;
}
const key = consonants.join(" ");
return VALID_ONSETS.has(key);
}
// src/format-registry.ts
var registry = /* @__PURE__ */ new Map();
var isLatinScriptCache = /* @__PURE__ */ new Map();
var preservesCaseCache = /* @__PURE__ */ new Map();
function getFormatHandler(name) {
return registry.get(name);
}
function getFormatIsLatinScript(name) {
return isLatinScriptCache.get(name) ?? true;
}
function getFormatJoinSeparator(name) {
return registry.get(name)?.joinSeparator ?? "";
}
function getFormatLabel(name) {
return registry.get(name)?.label ?? name;
}
function getFormatNativeLabel(name) {
const handler = registry.get(name);
return handler?.nativeLabel ?? handler?.label ?? name;
}
function getFormatPreservesCase(name) {
return preservesCaseCache.get(name) ?? true;
}
function registerFormat(name, handler) {
const existing = registry.get(name);
const merged = { ...existing, ...handler };
registry.set(name, merged);
isLatinScriptCache.set(name, merged.isLatinScript ?? true);
preservesCaseCache.set(name, merged.preservesCase ?? merged.isLatinScript ?? true);
}
// src/ingglish-maps.ts
var INGGLISH_VOWEL_MAP = {
// Monophthongs
AA: "o",
// father, hot, rock (but AA+R → 'ar' in star, car)
AE: "a",
// cat, bat, had (but AE+R → 'arr' in arrow, barrow)
AH: "uh",
// but, cup, son (stressed /ʌ/; unstressed /ə/ AH0 → 'a' in conversion)
AO: "aw",
// thought, caught, law (but AO+R → 'or' in store, more)
// Diphthongs
AW: "ou",
// cow, how, out
AY: "ai",
// my, eye, time
EH: "e",
// bed, red, said (but EH+R → 'air' in air, care, there)
ER: "er",
// bird, her, nurse
EY: "ay",
// say, day, make
IH: "i",
// bit, sit, gym
IY: "ee",
// bee, see, machine
OW: "oh",
// go, show, coat
OY: "oi",
// boy, toy, coin
UH: "u",
// book, put, could
UW: "oo"
// too, blue, food
};
var INGGLISH_CONSONANT_MAP = {
// Stops (plosives)
B: "b",
// bat, cab
// Affricates
CH: "ch",
// chat, batch
D: "d",
// dog, bed
// Fricatives
DH: "dh",
// the, this (voiced) - distinguishes from TH
F: "f",
// fat, laugh
G: "g",
// go, big
// Aspirate
HH: "h",
// hat, ahead
JH: "j",
// just, edge
K: "k",
// cat, back
// Liquids
L: "l",
// let, well
// Nasals
M: "m",
// man, come
N: "n",
// no, pen
NG: "ng",
// sing, thing
P: "p",
// pat, cup
R: "r",
// run, car
S: "s",
// sat, miss
SH: "sh",
// she, push
T: "t",
// top, cat
TH: "th",
// think, bath (voiceless)
V: "v",
// van, love
// Semivowels (glides)
W: "w",
// wet, away
Y: "y",
// yes, you
Z: "z",
// zoo, is
ZH: "zh"
// measure, beige
};
var ARPABET_TO_INGGLISH_MAP = {
...INGGLISH_VOWEL_MAP,
...INGGLISH_CONSONANT_MAP
};
var INGGLISH_TO_ARPABET_MAP = Object.fromEntries(
Object.entries(ARPABET_TO_INGGLISH_MAP).map(([arpabet, ingglish]) => [ingglish, arpabet])
);
var R_COLORED_VOWELS = [
{ arpabet: "AA", prefix: "a" },
// star, car, far → 'ar'
{ arpabet: "AO", prefix: "o" },
// store, more, for → 'or'
{ arpabet: "EH", prefix: "ai" },
// air, care, there → 'air'
{ arpabet: "AE", prefix: "ar" },
// arrow, barrow, carrot → 'arr'
{ arpabet: "IH", prefix: "ee" },
// beer, beard, fear → 'eer'
{ arpabet: "UH", prefix: "u" },
// tour, cure, pure → 'ur' (CURE vowel, experimentable)
{ arpabet: "AH", prefix: "uh" }
// curry, burroughs → 'uhr' (AH=uh, prevents AH0+R collision with 'ar')
];
var R_COLORED_FORWARD = new Map(
R_COLORED_VOWELS.map(({ arpabet, prefix }) => [arpabet, prefix])
);
var R_COLORED_REVERSE_3CHAR = Object.fromEntries(
R_COLORED_VOWELS.filter(({ prefix }) => prefix.length === 2).map(({ arpabet, prefix }) => [
prefix + "r",
[arpabet, "R"]
])
);
var R_COLORED_REVERSE_2CHAR = Object.fromEntries(
R_COLORED_VOWELS.filter(({ prefix }) => prefix.length === 1).map(({ arpabet, prefix }) => [
prefix + "r",
[arpabet, "R"]
])
);
// src/to-ingglish.ts
function arpabetPhonemeToIngglish(phoneme) {
if (phoneme === "AH0") {
return "a";
}
const base = stripStress(phoneme);
return ARPABET_TO_INGGLISH_MAP[base] ?? phoneme.toLowerCase();
}
function convertArpabet(arpabet, phonemeMap, rColoredMap, stressOverrides) {
let result = "";
const len = arpabet.length;
for (let i = 0; i < len; i++) {
const phoneme = arpabet[i];
const base = stripStress(phoneme);
if (i + 1 < len && arpabet[i + 1] === "R") {
const rPrefix = rColoredMap.get(base);
if (rPrefix !== void 0) {
result += rPrefix;
continue;
}
}
const stressOverride = stressOverrides.get(phoneme);
if (stressOverride !== void 0) {
result += stressOverride;
continue;
}
result += phonemeMap[base] ?? phoneme.toLowerCase();
}
return result;
}
var INGGLISH_FULL_MAP = {};
for (const [base, spelling] of Object.entries(ARPABET_TO_INGGLISH_MAP)) {
INGGLISH_FULL_MAP[base] = spelling;
INGGLISH_FULL_MAP[base + "0"] = spelling;
INGGLISH_FULL_MAP[base + "1"] = spelling;
INGGLISH_FULL_MAP[base + "2"] = spelling;
}
INGGLISH_FULL_MAP.AH0 = "a";
function arpabetToIngglish(arpabet) {
let result = "";
const len = arpabet.length;
for (let i = 0; i < len; i++) {
const phoneme = arpabet[i];
if (i + 1 < len && arpabet[i + 1] === "R") {
const base = stripStress(phoneme);
const rPrefix = R_COLORED_FORWARD.get(base);
if (rPrefix !== void 0) {
result += rPrefix;
continue;
}
}
result += INGGLISH_FULL_MAP[phoneme] ?? phoneme.toLowerCase();
}
return result;
}
registerFormat("ingglish", {
forward: arpabetToIngglish,
isLatinScript: true,
label: "Ingglish",
preservesCase: true
});
var EMPTY_R_COLORED = /* @__PURE__ */ new Map();
var INGGLISH_STRESS_OVERRIDES = /* @__PURE__ */ new Map([["AH0", "a"]]);
function arpabetToFormat(arpabet, format = "ingglish", options) {
if (format === "ingglish") {
if (options?.disableRColoring === true) {
return convertArpabet(
arpabet,
ARPABET_TO_INGGLISH_MAP,
EMPTY_R_COLORED,
INGGLISH_STRESS_OVERRIDES
);
}
return arpabetToIngglish(arpabet);
}
const handler = getFormatHandler(format);
if (handler?.forward) {
return handler.forward(arpabet, options);
}
return arpabetToIngglish(arpabet);
}
// src/to-pronunciation.ts
var GUIDE_MAP = {};
for (const [base, spelling] of Object.entries(ARPABET_TO_INGGLISH_MAP)) {
GUIDE_MAP[base] = spelling;
GUIDE_MAP[base + "0"] = spelling;
GUIDE_MAP[base + "1"] = spelling;
GUIDE_MAP[base + "2"] = spelling;
}
GUIDE_MAP.AH0 = "a";
function arpabetToPronunciation(arpabet) {
const syllables = syllabify(arpabet);
return syllables.map(({ phonemes, stress }) => {
const spelling = syllableToSpelling(phonemes);
return stress >= 1 ? spelling.toUpperCase() : spelling;
}).join("-");
}
function registerPronunciation() {
registerFormat("pronunciation", {
forward: arpabetToPronunciation,
isLatinScript: true,
label: "Guide",
preservesCase: false
});
}
function syllabify(arpabet) {
const vowelIndices = [];
for (const [i, phoneme] of arpabet.entries()) {
if (isVowel(phoneme)) {
vowelIndices.push(i);
}
}
if (vowelIndices.length === 0) {
return [{ phonemes: arpabet, stress: 0 }];
}
const syllables = [];
let start = 0;
for (let vi = 0; vi < vowelIndices.length; vi++) {
const vowelIdx = vowelIndices[vi];
const stress = getStress(arpabet[vowelIdx]) ?? 0;
if (vi < vowelIndices.length - 1) {
const nextVowelIdx = vowelIndices[vi + 1];
const consonantStart = vowelIdx + 1;
const consonants = [];
for (let j = consonantStart; j < nextVowelIdx; j++) {
consonants.push(stripStress(arpabet[j]));
}
if (consonants.length === 0) {
syllables.push({ phonemes: arpabet.slice(start, consonantStart), stress });
start = consonantStart;
} else {
const onsetIdx = findOnsetStart(consonants);
const boundary = consonantStart + onsetIdx;
syllables.push({ phonemes: arpabet.slice(start, boundary), stress });
start = boundary;
}
} else {
syllables.push({ phonemes: arpabet.slice(start), stress });
}
}
return syllables;
}
function syllableToSpelling(phonemes) {
let result = "";
for (let i = 0; i < phonemes.length; i++) {
const phoneme = phonemes[i];
if (i + 1 < phonemes.length && phonemes[i + 1] === "R") {
const base = stripStress(phoneme);
const rPrefix = R_COLORED_FORWARD.get(base);
if (rPrefix !== void 0) {
result += rPrefix;
continue;
}
}
result += GUIDE_MAP[phoneme] ?? phoneme.toLowerCase();
}
return result;
}
// src/from-ingglish.ts
var ARPABET_ALTERNATIVES = {
AE: [["AH"]],
// "a" could be AE (cat) or AH (schwa: about, the)
ER: [["EH", "R"]],
SH: [["S", "HH"]]
// "sh" could be SH (ship) or S+HH (exhume)
};
var ARPABET_ALTERNATIVES_ENTRIES = Object.entries(ARPABET_ALTERNATIVES);
function expandArpabetAlternatives(arpabet) {
const results = [arpabet];
for (let i = 0; i < arpabet.length; i++) {
const alternatives = ARPABET_ALTERNATIVES[arpabet[i]];
if (alternatives !== void 0) {
for (const alt of alternatives) {
const expanded = [...arpabet.slice(0, i), ...alt, ...arpabet.slice(i + 1)];
results.push(expanded);
}
}
}
for (const [phoneme, alts] of ARPABET_ALTERNATIVES_ENTRIES) {
for (const alt of alts) {
if (alt.length === 1) {
let count = 0;
for (const p of arpabet) {
if (p === phoneme) {
count++;
}
}
if (count >= 2) {
results.push(arpabet.map((p) => p === phoneme ? alt[0] : p));
}
}
}
}
return results;
}
var TWO_CHAR_SPELLINGS = new Set(
Object.keys(INGGLISH_TO_ARPABET_MAP).filter((s) => s.length === 2)
);
var ONE_CHAR_SPELLINGS = new Set(
Object.keys(INGGLISH_TO_ARPABET_MAP).filter((s) => s.length === 1)
);
function ingglishToArpabet(ingglish) {
const result = [];
const str = ingglish.toLowerCase();
const len = str.length;
let pos = 0;
while (pos < len) {
if (pos + 3 <= len) {
const threeChar = str.slice(pos, pos + 3);
if (threeChar in R_COLORED_REVERSE_3CHAR) {
result.push(...R_COLORED_REVERSE_3CHAR[threeChar]);
pos += 3;
continue;
}
}
if (pos + 2 <= len) {
const twoChar = str.slice(pos, pos + 2);
if (twoChar in R_COLORED_REVERSE_2CHAR) {
result.push(...R_COLORED_REVERSE_2CHAR[twoChar]);
pos += 2;
continue;
}
if (TWO_CHAR_SPELLINGS.has(twoChar)) {
result.push(INGGLISH_TO_ARPABET_MAP[twoChar]);
pos += 2;
continue;
}
}
const oneChar = str[pos];
if (ONE_CHAR_SPELLINGS.has(oneChar)) {
result.push(INGGLISH_TO_ARPABET_MAP[oneChar]);
pos += 1;
continue;
}
pos += 1;
}
return result.length > 0 ? result : null;
}
// src/custom-format.ts
function createCustomConverter(config) {
const mergedMap = { ...ARPABET_TO_INGGLISH_MAP, ...config.phonemeMap };
const mergedRColored = new Map(R_COLORED_FORWARD);
for (const [vowel] of R_COLORED_FORWARD) {
if (vowel in config.phonemeMap && !(vowel in config.rColoredPrefixes)) {
mergedRColored.set(vowel, config.phonemeMap[vowel]);
}
}
for (const [key, value] of Object.entries(config.rColoredPrefixes)) {
mergedRColored.set(key, value);
}
const stressOverrides = /* @__PURE__ */ new Map([["AH0", "a"]]);
for (const [key, value] of Object.entries(config.phonemeMap)) {
const lastChar = key.codePointAt(key.length - 1);
if (lastChar >= 48 && lastChar <= 50) {
stressOverrides.set(key, value);
}
}
const emptyRColored = /* @__PURE__ */ new Map();
return (arpabet, options) => convertArpabet(
arpabet,
mergedMap,
options?.disableRColoring === true ? emptyRColored : mergedRColored,
stressOverrides
);
}
export {
ARPABET_CONSONANTS,
ARPABET_TO_INGGLISH_MAP,
ARPABET_VOWELS,
R_COLORED_FORWARD,
STRESS_MARKER_REGEX,
arpabetPhonemeToIngglish,
arpabetToFormat,
arpabetToIngglish,
createCustomConverter,
expandArpabetAlternatives,
findOnsetStart,
getFormatHandler,
getFormatIsLatinScript,
getFormatJoinSeparator,
getFormatLabel,
getFormatNativeLabel,
getFormatPreservesCase,
getStress,
ingglishToArpabet,
isVowel,
registerFormat,
registerPronunciation,
stripStress
};
+48
View File
@@ -0,0 +1,48 @@
{
"name": "@ingglish/phonemes",
"version": "0.1.1",
"description": "Phoneme definitions and ARPAbet/IPA/Ingglish conversion maps",
"type": "module",
"main": "./dist/index.js",
"module": "./dist/index.mjs",
"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",
"prepublishOnly": "npm run build"
},
"author": "Paul Tarjan",
"license": "MIT",
"repository": {
"type": "git",
"url": "git+https://github.com/ptarjan/ingglish.git",
"directory": "packages/phonemes"
},
"homepage": "https://github.com/ptarjan/ingglish#readme",
"bugs": {
"url": "https://github.com/ptarjan/ingglish/issues"
}
}