@try-works/extension-laya 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +38 -2
- package/lib/index.d.ts +18 -0
- package/lib/index.js +172 -0
- package/lib/index.js.map +1 -0
- package/lib/pure.d.ts +35 -0
- package/lib/pure.js +71 -0
- package/lib/pure.js.map +1 -0
- package/models.lock.json +63 -0
- package/package.json +39 -4
- package/schema/decision-choose.input.json +22 -0
- package/schema/decision-choose.output.json +20 -0
- package/schema/decision-score.input.json +18 -0
- package/schema/decision-score.output.json +18 -0
- package/schema/decision-test.input.json +10 -0
- package/schema/decision-test.output.json +18 -0
- package/tool-mode.extension.json +87 -0
- package/vendor/LICENSE.laya-ts +176 -0
- package/vendor/laya-ts/agent.d.ts +216 -0
- package/vendor/laya-ts/agent.js +631 -0
- package/vendor/laya-ts/common.d.ts +167 -0
- package/vendor/laya-ts/common.js +478 -0
- package/vendor/laya-ts/dx.d.ts +17 -0
- package/vendor/laya-ts/dx.js +46 -0
- package/vendor/laya-ts/email.d.ts +2 -0
- package/vendor/laya-ts/email.js +184 -0
- package/vendor/laya-ts/hooks.d.ts +134 -0
- package/vendor/laya-ts/hooks.js +379 -0
- package/vendor/laya-ts/index.d.ts +22 -0
- package/vendor/laya-ts/index.js +13 -0
- package/vendor/laya-ts/lang.d.ts +24 -0
- package/vendor/laya-ts/lang.js +590 -0
- package/vendor/laya-ts/presets.d.ts +5 -0
- package/vendor/laya-ts/presets.js +175 -0
- package/vendor/laya-ts/providers.d.ts +67 -0
- package/vendor/laya-ts/providers.js +668 -0
- package/vendor/laya-ts/router.d.ts +186 -0
- package/vendor/laya-ts/router.js +757 -0
- package/vendor/laya-ts/shortlist.d.ts +65 -0
- package/vendor/laya-ts/shortlist.js +407 -0
- package/vendor/laya-ts/structured.d.ts +89 -0
- package/vendor/laya-ts/structured.js +256 -0
- package/vendor/laya-ts/tokenizer.d.ts +66 -0
- package/vendor/laya-ts/tokenizer.js +482 -0
|
@@ -0,0 +1,590 @@
|
|
|
1
|
+
const SCRIPT_RANGES = [
|
|
2
|
+
["greek", [[0x0370, 0x03ff], [0x1f00, 0x1fff]]],
|
|
3
|
+
["cyrillic", [[0x0400, 0x052f], [0x2de0, 0x2dff], [0xa640, 0xa69f]]],
|
|
4
|
+
["armenian", [[0x0530, 0x058f]]],
|
|
5
|
+
["hebrew", [[0x0590, 0x05ff]]],
|
|
6
|
+
["arabic", [[0x0600, 0x06ff], [0x0750, 0x077f], [0x08a0, 0x08ff], [0xfb50, 0xfdff], [0xfe70, 0xfeff]]],
|
|
7
|
+
["devanagari", [[0x0900, 0x097f], [0xa8e0, 0xa8ff]]],
|
|
8
|
+
["bengali", [[0x0980, 0x09ff]]],
|
|
9
|
+
["gurmukhi", [[0x0a00, 0x0a7f]]],
|
|
10
|
+
["gujarati", [[0x0a80, 0x0aff]]],
|
|
11
|
+
["oriya", [[0x0b00, 0x0b7f]]],
|
|
12
|
+
["tamil", [[0x0b80, 0x0bff]]],
|
|
13
|
+
["telugu", [[0x0c00, 0x0c7f]]],
|
|
14
|
+
["kannada", [[0x0c80, 0x0cff]]],
|
|
15
|
+
["malayalam", [[0x0d00, 0x0d7f]]],
|
|
16
|
+
["sinhala", [[0x0d80, 0x0dff]]],
|
|
17
|
+
["thai", [[0x0e00, 0x0e7f]]],
|
|
18
|
+
["lao", [[0x0e80, 0x0eff]]],
|
|
19
|
+
["tibetan", [[0x0f00, 0x0fff]]],
|
|
20
|
+
["myanmar", [[0x1000, 0x109f]]],
|
|
21
|
+
["georgian", [[0x10a0, 0x10ff]]],
|
|
22
|
+
["ethiopic", [[0x1200, 0x137f]]],
|
|
23
|
+
["khmer", [[0x1780, 0x17ff]]],
|
|
24
|
+
["hangul", [[0x1100, 0x11ff], [0x3130, 0x318f], [0xac00, 0xd7af]]],
|
|
25
|
+
["kana", [[0x3040, 0x309f], [0x30a0, 0x30ff], [0x31f0, 0x31ff]]],
|
|
26
|
+
["han", [[0x3400, 0x4dbf], [0x4e00, 0x9fff], [0xf900, 0xfaff]]],
|
|
27
|
+
];
|
|
28
|
+
const STOP = {
|
|
29
|
+
en: new Set(["the", "and", "is", "are", "was", "were", "to", "of", "in", "for", "with", "that",
|
|
30
|
+
"this", "it", "you", "have", "has", "not", "but", "on", "at", "be", "as", "from",
|
|
31
|
+
"will", "can", "would", "there", "their", "what", "which", "please", "we", "i"]),
|
|
32
|
+
fr: new Set(["le", "la", "les", "des", "une", "est", "pour", "dans", "que", "qui", "avec", "sur",
|
|
33
|
+
"pas", "plus", "nous", "vous", "être", "cette", "mais", "sont", "ont", "aux", "ce",
|
|
34
|
+
"et", "du", "au", "ou", "je", "tu", "il", "elle", "ils", "elles", "mon", "ton",
|
|
35
|
+
"ma", "ta", "sa", "mes", "tes", "ses", "ces", "deux", "trois", "très", "bien",
|
|
36
|
+
"tout", "tous", "toute", "fait", "veux", "veut", "peux", "peut", "dois", "doit",
|
|
37
|
+
"merci", "bonjour", "jour", "jours", "mois", "fois", "quand", "comment", "pourquoi",
|
|
38
|
+
"alors", "donc"]),
|
|
39
|
+
de: new Set(["der", "die", "das", "und", "ist", "ein", "eine", "den", "dem", "nicht", "mit", "für",
|
|
40
|
+
"auf", "von", "zu", "sich", "auch", "werden", "wurde", "haben", "sind", "oder", "aber",
|
|
41
|
+
"ich", "wir", "mir", "mich", "dir", "dich", "uns", "mein", "meine", "meinen",
|
|
42
|
+
"meinem", "meiner", "diese", "dieser", "diesen", "dieses", "einen", "einem", "einer",
|
|
43
|
+
"wie", "wo", "wann", "welche", "im", "zum", "zur", "aus", "bei", "nach", "noch", "bitte",
|
|
44
|
+
"heute", "jetzt", "kann", "kannst", "habe", "gibt", "wird",
|
|
45
|
+
// shared with English on purpose: counted for English alone, they outvoted short German
|
|
46
|
+
"in", "was"]),
|
|
47
|
+
es: new Set(["el", "los", "las", "que", "por", "con", "para", "una", "es", "se", "del", "como",
|
|
48
|
+
"pero", "son", "está", "este", "esta", "todo", "más", "muy", "hay", "sus",
|
|
49
|
+
"la", "un", "y", "al", "lo", "le", "les", "su", "mi", "tu", "nos",
|
|
50
|
+
"ni", "dos", "tres", "fue", "fueron", "ser", "tiene", "tienen", "tengo", "puede",
|
|
51
|
+
"pueden", "quiero", "necesito", "hemos", "han", "sobre", "entre", "cuando", "donde",
|
|
52
|
+
"porque", "aunque", "también", "ya", "eso", "esto", "esa", "ese", "nada", "algo",
|
|
53
|
+
"aquí", "hoy", "gracias"]),
|
|
54
|
+
pt: new Set(["os", "as", "que", "em", "um", "uma", "para", "com", "não", "é", "se", "do", "da",
|
|
55
|
+
"dos", "das", "mas", "são", "está", "este", "esta", "muito", "pelo", "pela",
|
|
56
|
+
"o", "e", "na", "nas", "nos", "ao", "aos", "por", "foi", "era", "ser", "sou",
|
|
57
|
+
"tem", "tenho", "pode", "podem", "quero", "preciso", "eu", "meu", "minha", "seu",
|
|
58
|
+
"sua", "isso", "isto", "aqui", "ali", "como", "quando", "onde", "porque", "mais",
|
|
59
|
+
"já", "ainda", "agora", "hoje", "ontem", "dois", "três", "tudo", "nada", "obrigado",
|
|
60
|
+
"olá",
|
|
61
|
+
"você", "vocês", "voce", "voces", "vc", "vcs", "nao", "sao", "ja", "até", "tá", "pra",
|
|
62
|
+
"gostaria", "obrigada", "também", "tambem", "estou", "estamos", "meus", "minhas",
|
|
63
|
+
"nosso", "nossa", "consigo", "cadê", "boa", "tarde", "noite",
|
|
64
|
+
"depois", "antes", "então", "entao", "ninguém", "ninguem", "alguém", "alguem", "nenhum",
|
|
65
|
+
"nenhuma", "estava", "ficou", "fiz", "deu"]),
|
|
66
|
+
it: new Set(["il", "lo", "gli", "che", "di", "per", "con", "non", "è", "si", "del", "della", "sono",
|
|
67
|
+
"questo", "questa", "anche", "come", "più", "sono", "nella", "alla",
|
|
68
|
+
"la", "le", "un", "uno", "una", "e", "ed", "o", "da", "su", "tra", "fra", "mi",
|
|
69
|
+
"ci", "ne", "ho", "hai", "ha", "abbiamo", "avete", "hanno", "era", "stato", "stata",
|
|
70
|
+
"devo", "deve", "devono", "voglio", "vorrei", "mio", "mia", "tuo", "sua", "quando",
|
|
71
|
+
"dove", "perche", "molto", "poco", "sempre", "mai", "già", "ancora", "adesso", "oggi",
|
|
72
|
+
"ieri", "grazie", "ciao", "scusa",
|
|
73
|
+
"nel", "nell", "negli", "sul", "sulla", "sulle", "dal", "dalla", "dallo", "dagli", "dei",
|
|
74
|
+
"delle", "dello", "degli", "agli", "alle", "col"]),
|
|
75
|
+
nl: new Set(["het", "een", "van", "is", "op", "te", "dat", "niet", "met", "voor", "zijn", "aan",
|
|
76
|
+
"door", "maar", "ook", "worden", "deze", "naar", "wordt"]),
|
|
77
|
+
// Keep Swedish routing in parity with Python. Distinctive words help ASCII-normalised ticket text;
|
|
78
|
+
// shared Nordic words are tracked separately so Danish and Norwegian are not named Swedish.
|
|
79
|
+
sv: new Set(["jag", "är", "och", "inte", "att", "från", "till", "behöver", "får", "skulle", "ska",
|
|
80
|
+
"vill", "måste", "också", "dessa", "detta", "säger", "upp", "utan", "mitt", "min", "om",
|
|
81
|
+
"kommer", "här", "två", "vi", "nästa", "gör", "göra", "hjälp", "hjälpa", "mig",
|
|
82
|
+
"återbetalning", "återbetala", "faktura", "gång", "gånger", "hittar", "inställningen",
|
|
83
|
+
"inställningarna", "lösenord", "när", "öppnar", "spårningen", "aterbetalning", "aterbetala",
|
|
84
|
+
"behover", "fel", "ganger", "hjalp", "hjalpa", "installningen", "installningarna", "kraschar",
|
|
85
|
+
"kvittot", "losenord", "nar", "oppnar", "paket", "skicka", "sparningen", "tva", "uppdaterats",
|
|
86
|
+
"blivit", "debiterade", "appen"]),
|
|
87
|
+
ro: new Set(["și", "să", "este", "sunt", "care", "pentru", "din", "dar", "după", "până", "fără",
|
|
88
|
+
"ale", "lui", "în", "fost", "acum", "vreau", "trebuie", "foarte", "acest", "această",
|
|
89
|
+
"acesta", "aceasta", "mi", "ți", "vă", "nu"]),
|
|
90
|
+
// Romanized Bangla ("Banglish"): how Bangla is typed in chats, tickets and email when no Bengali
|
|
91
|
+
// keyboard is at hand. It has no diacritics, so without a list it read as undecided-but-English
|
|
92
|
+
// and went to the English checkpoint, which scores 0.08 on Bangla at 0.94 confidence.
|
|
93
|
+
bn: new Set(["ami", "amar", "amake", "amra", "amader", "apni", "apnar", "apnake", "apnara",
|
|
94
|
+
"tumi", "tomar", "tomake", "tomra", "tader", "ota", "eita", "oita",
|
|
95
|
+
"ekta", "ei", "oi", "ki", "keno", "kivabe", "kibhabe", "kothay", "kokhon", "kobe",
|
|
96
|
+
"koto", "kintu", "jodi", "tahole", "ar", "theke", "jonno", "sathe", "shathe", "diye",
|
|
97
|
+
"niye", "moddhe", "kore", "korte", "korchi", "korsi", "korbo", "korechi", "koreche",
|
|
98
|
+
"korun", "koren", "korlam", "hobe", "hoyeche", "hoise", "hocche", "hoyni",
|
|
99
|
+
"chai", "chaina", "lagbe", "parchi", "parbo", "parchina", "peyechi", "paini",
|
|
100
|
+
"dite", "dilam", "diyechi", "nai", "khub", "onek", "ekhon", "akhon", "ekhono",
|
|
101
|
+
"abar", "ekbar", "duibar", "ajke", "kalke", "taka", "bhalo", "valo", "kharap",
|
|
102
|
+
"shomossa", "somossa", "dhonnobad", "bhai", "shob", "keu", "kichu", "bolte", "bolun",
|
|
103
|
+
"parben", "asbe", "jabe", "pabo", "ferot", "dorkar", "hoye", "geche", "gese"]),
|
|
104
|
+
az: new Set(["və", "ve", "bir", "bu", "üçün", "ucun", "ilə", "ile", "olan", "olub", "olmasa",
|
|
105
|
+
"var", "yox", "yoxdur", "mən", "sən", "biz", "siz", "onlar", "daha", "çox", "cox",
|
|
106
|
+
"hər", "nə", "kimi", "görə", "sonra", "əgər", "eger", "deyil", "lakin", "amma",
|
|
107
|
+
"ancaq", "artıq", "artiq", "də", "isə", "həm", "yalnız", "yalniz"]),
|
|
108
|
+
};
|
|
109
|
+
const NON_EN_DIACRITICS = new Set(("àâäãáåçéèêëíìîïñóòôöõøúùûüýÿßæœ" + // Western European
|
|
110
|
+
"ăâîșțşţ" + // Romanian
|
|
111
|
+
"ąćęłńśźż" + // Polish
|
|
112
|
+
"čďěňřšťůž" + // Czech / Slovak
|
|
113
|
+
"őű" + // Hungarian
|
|
114
|
+
"ğı" + // Turkish (text is lowercased before matching)
|
|
115
|
+
"āēģīķļņūž" + // Baltic
|
|
116
|
+
"đ" + // Serbo-Croatian / Vietnamese
|
|
117
|
+
"ə").split(""));
|
|
118
|
+
export const NON_EN_DIACRITIC_RATE = 0.02;
|
|
119
|
+
const ENGLISH_RESCUE_DIACRITIC_RATE = 0.06;
|
|
120
|
+
// One accented loanword (`café`, `José`) clears the rate above on its own; two English-only function words
|
|
121
|
+
// and at most one accented word keep the text English, as in laya/lang.py.
|
|
122
|
+
function englishRescuedByWords(wordSet, diacRate) {
|
|
123
|
+
if (diacRate >= ENGLISH_RESCUE_DIACRITIC_RATE)
|
|
124
|
+
return false;
|
|
125
|
+
let englishOnly = 0;
|
|
126
|
+
let accented = 0;
|
|
127
|
+
for (const w of wordSet) {
|
|
128
|
+
if (EN_ONLY_WORDS.has(w))
|
|
129
|
+
englishOnly += 1;
|
|
130
|
+
if ([...w].some((ch) => NON_EN_DIACRITICS.has(ch)))
|
|
131
|
+
accented += 1;
|
|
132
|
+
}
|
|
133
|
+
return englishOnly >= 2 && accented <= 1;
|
|
134
|
+
}
|
|
135
|
+
const SHARED_WORDS = (() => {
|
|
136
|
+
const counts = new Map();
|
|
137
|
+
for (const words of Object.values(STOP)) {
|
|
138
|
+
for (const w of words)
|
|
139
|
+
counts.set(w, (counts.get(w) ?? 0) + 1);
|
|
140
|
+
}
|
|
141
|
+
const out = new Set();
|
|
142
|
+
for (const [w, n] of counts)
|
|
143
|
+
if (n > 1)
|
|
144
|
+
out.add(w);
|
|
145
|
+
return out;
|
|
146
|
+
})();
|
|
147
|
+
// Danish and Norwegian share many common words with Swedish; they can add score but cannot name sv alone.
|
|
148
|
+
const NORDIC_OVERLAP_WORDS = new Set(["hej", "ja", "nej", "jo", "tack", "mig", "min", "om", "kommer", "får", "skulle", "vi"]);
|
|
149
|
+
for (const word of NORDIC_OVERLAP_WORDS)
|
|
150
|
+
SHARED_WORDS.add(word);
|
|
151
|
+
const EN_ONLY_WORDS = new Set([...STOP["en"]].filter((w) => !SHARED_WORDS.has(w)));
|
|
152
|
+
// Foreign function words that are also ordinary English words (`im` is also `I'm` without the
|
|
153
|
+
// apostrophe). Each counts once however often it repeats, so "do more, do less" cannot clear the
|
|
154
|
+
// `best >= 2` bar on one word. Every other word keeps counting occurrences: `der` twice is still
|
|
155
|
+
// German, and Dutch `van` is deliberately left out. See _EN_COLLISION_WORDS in laya/lang.py.
|
|
156
|
+
const EN_COLLISION_WORDS = new Set(["come", "son", "do", "care", "todo", "im", "per", "plus"].filter((w) => Object.entries(STOP).some(([lg, sw]) => lg !== "en" && sw.has(w))));
|
|
157
|
+
// Short support fragments need a narrower vocabulary than the general four-word language guess.
|
|
158
|
+
// Generic words such as "fel" and "hjälp" are deliberately omitted from this subset.
|
|
159
|
+
const SHORT_SWEDISH_WORDS = new Set([
|
|
160
|
+
"åtkomst", "atkomst", "lösenord", "losenord", "fakturan", "betalningen", "inloggningen",
|
|
161
|
+
"glömt", "glomt", "behöver", "behover", "återbetalning", "aterbetalning", "kvitto", "kvittot",
|
|
162
|
+
"spårningen", "sparningen", "inställningen", "installningen", "felmeddelande", "abonnemanget",
|
|
163
|
+
]);
|
|
164
|
+
// JS `\w` is ASCII-only, so Python's `[^\W\d_]` needs the Unicode classes spelled out (Nl/No are in Python's `\w`).
|
|
165
|
+
const WORD_RE = /[\p{L}\p{Nl}\p{No}]+/gu;
|
|
166
|
+
// Lookbehind for the same reason as the Python side (see laya/lang.py): without it the
|
|
167
|
+
// greedy prefix is retried at every offset inside a run of word characters, which is
|
|
168
|
+
// quadratic in the run's length -- 50 000 characters of one token took 1540 ms here.
|
|
169
|
+
// It removes no match, because a leftmost match can only begin at a run start.
|
|
170
|
+
const IDENTIFIER_RE = /(?<![\p{L}\p{N}_-])[\p{L}\p{N}_-]*(?:[.@][\p{L}\p{N}_-]+)+/gu;
|
|
171
|
+
const IS_ALPHA_RE = /\p{L}/u;
|
|
172
|
+
// Python uses two different boundaries on purpose: detect_script/script_profile count the IPA
|
|
173
|
+
// Extensions block (0x0250-0x02AF) as Latin, while _script_of (used for non-Latin word runs)
|
|
174
|
+
// stops at 0x0250 so a pronunciation like [vlɐˈdʲimʲɪr] is neither Latin nor a script run.
|
|
175
|
+
function isLatinCp(cp) {
|
|
176
|
+
return cp < 0x02b0 || (0x1e00 <= cp && cp <= 0x1eff) || (0xff21 <= cp && cp <= 0xff3a) || (0xff41 <= cp && cp <= 0xff5a);
|
|
177
|
+
}
|
|
178
|
+
function scriptOf(ch) {
|
|
179
|
+
const cp = ch.codePointAt(0);
|
|
180
|
+
if (cp < 0x0250 || (0x1e00 <= cp && cp <= 0x1eff) || (0xff21 <= cp && cp <= 0xff3a) || (0xff41 <= cp && cp <= 0xff5a)) {
|
|
181
|
+
return null;
|
|
182
|
+
}
|
|
183
|
+
for (const [name, ranges] of SCRIPT_RANGES) {
|
|
184
|
+
if (ranges.some(([lo, hi]) => lo <= cp && cp <= hi))
|
|
185
|
+
return name;
|
|
186
|
+
}
|
|
187
|
+
return null;
|
|
188
|
+
}
|
|
189
|
+
/** String leaves of a state. Keys are ignored: they are usually English field names. */
|
|
190
|
+
function iterText(state, depth = 0) {
|
|
191
|
+
if (depth > 6 || state == null)
|
|
192
|
+
return [];
|
|
193
|
+
if (typeof state === "string")
|
|
194
|
+
return [state];
|
|
195
|
+
if (state instanceof Uint8Array) {
|
|
196
|
+
try {
|
|
197
|
+
return [new TextDecoder("utf-8", { fatal: true }).decode(state)];
|
|
198
|
+
}
|
|
199
|
+
catch {
|
|
200
|
+
return [];
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
if (Array.isArray(state)) {
|
|
204
|
+
const out = [];
|
|
205
|
+
for (const v of state)
|
|
206
|
+
out.push(...iterText(v, depth + 1));
|
|
207
|
+
return out;
|
|
208
|
+
}
|
|
209
|
+
if (typeof state === "object") {
|
|
210
|
+
const out = [];
|
|
211
|
+
for (const v of Object.values(state))
|
|
212
|
+
out.push(...iterText(v, depth + 1));
|
|
213
|
+
return out;
|
|
214
|
+
}
|
|
215
|
+
return [];
|
|
216
|
+
}
|
|
217
|
+
export function stateText(state, maxChars = 4000) {
|
|
218
|
+
return iterText(state).join(" ").slice(0, maxChars);
|
|
219
|
+
}
|
|
220
|
+
export function detectScript(text) {
|
|
221
|
+
const counts = new Map();
|
|
222
|
+
let latin = 0;
|
|
223
|
+
for (const ch of text) {
|
|
224
|
+
if (!IS_ALPHA_RE.test(ch))
|
|
225
|
+
continue;
|
|
226
|
+
const cp = ch.codePointAt(0);
|
|
227
|
+
if (isLatinCp(cp)) {
|
|
228
|
+
latin += 1;
|
|
229
|
+
continue;
|
|
230
|
+
}
|
|
231
|
+
let found = null;
|
|
232
|
+
for (const [name, ranges] of SCRIPT_RANGES) {
|
|
233
|
+
if (ranges.some(([lo, hi]) => lo <= cp && cp <= hi)) {
|
|
234
|
+
found = name;
|
|
235
|
+
break;
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
counts.set(found ?? "other", (counts.get(found ?? "other") ?? 0) + 1);
|
|
239
|
+
}
|
|
240
|
+
counts.set("latin", latin);
|
|
241
|
+
let total = 0;
|
|
242
|
+
for (const v of counts.values())
|
|
243
|
+
total += v;
|
|
244
|
+
if (total === 0)
|
|
245
|
+
return "unknown";
|
|
246
|
+
let best = "latin";
|
|
247
|
+
let bestN = -1;
|
|
248
|
+
for (const [k, v] of counts) {
|
|
249
|
+
if (v > bestN) {
|
|
250
|
+
bestN = v;
|
|
251
|
+
best = k;
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
return best;
|
|
255
|
+
}
|
|
256
|
+
export function scriptProfile(text) {
|
|
257
|
+
const counts = new Map([["latin", 0]]);
|
|
258
|
+
for (const ch of text) {
|
|
259
|
+
if (!IS_ALPHA_RE.test(ch))
|
|
260
|
+
continue;
|
|
261
|
+
const cp = ch.codePointAt(0);
|
|
262
|
+
if (isLatinCp(cp)) {
|
|
263
|
+
counts.set("latin", (counts.get("latin") ?? 0) + 1);
|
|
264
|
+
continue;
|
|
265
|
+
}
|
|
266
|
+
let found = null;
|
|
267
|
+
for (const [name, ranges] of SCRIPT_RANGES) {
|
|
268
|
+
if (ranges.some(([lo, hi]) => lo <= cp && cp <= hi)) {
|
|
269
|
+
found = name;
|
|
270
|
+
break;
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
const key = found ?? "other";
|
|
274
|
+
counts.set(key, (counts.get(key) ?? 0) + 1);
|
|
275
|
+
}
|
|
276
|
+
let total = 0;
|
|
277
|
+
for (const v of counts.values())
|
|
278
|
+
total += v;
|
|
279
|
+
if (!total)
|
|
280
|
+
return {};
|
|
281
|
+
const out = {};
|
|
282
|
+
for (const [k, v] of counts) {
|
|
283
|
+
if (v)
|
|
284
|
+
out[k] = v / total;
|
|
285
|
+
}
|
|
286
|
+
return out;
|
|
287
|
+
}
|
|
288
|
+
// Non-Latin text is not for the English checkpoint even when Latin letters are the plurality: a
|
|
289
|
+
// brand name or order code outvotes the CJK request around it letter for letter, though one CJK
|
|
290
|
+
// character carries far more than a letter. A short message needs a large share to count; a long
|
|
291
|
+
// payload (ticket fields, English agent turns) dilutes the share, so there a sentence's worth of
|
|
292
|
+
// letters counts too.
|
|
293
|
+
const NON_LATIN_FRACTION = 0.2;
|
|
294
|
+
const NON_LATIN_MIN_FRACTION = 0.1;
|
|
295
|
+
const NON_LATIN_MIN_LETTERS = 10;
|
|
296
|
+
/** Non-Latin runs that read as words rather than as annotation inside English prose. */
|
|
297
|
+
function nonLatinWords(text) {
|
|
298
|
+
// English prose carries three kinds of non-Latin letters that are not a request written in
|
|
299
|
+
// another script, and each is excluded here: a symbol ("Set α to 0.05", one letter), a proper
|
|
300
|
+
// name (capitalised), and a pronunciation ([vlɐˈdʲimʲɪr], which no script range claims). A
|
|
301
|
+
// combining mark belongs to the letter before it and never splits a word.
|
|
302
|
+
const runs = [];
|
|
303
|
+
let cur = "";
|
|
304
|
+
let script = null;
|
|
305
|
+
for (const ch of text) {
|
|
306
|
+
if (/^\p{M}$/u.test(ch))
|
|
307
|
+
continue;
|
|
308
|
+
const s = scriptOf(ch);
|
|
309
|
+
if (s !== null && s === script) {
|
|
310
|
+
cur += ch;
|
|
311
|
+
continue;
|
|
312
|
+
}
|
|
313
|
+
if (cur)
|
|
314
|
+
runs.push(cur);
|
|
315
|
+
if (s !== null) {
|
|
316
|
+
cur = ch;
|
|
317
|
+
script = s;
|
|
318
|
+
}
|
|
319
|
+
else {
|
|
320
|
+
cur = "";
|
|
321
|
+
script = null;
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
if (cur)
|
|
325
|
+
runs.push(cur);
|
|
326
|
+
return runs.filter((w) => [...w].length >= 2 && !/^[\p{Lu}\p{Lt}]/u.test(w));
|
|
327
|
+
}
|
|
328
|
+
export function latinProfile(text) {
|
|
329
|
+
const stripped = text.replace(IDENTIFIER_RE, " ");
|
|
330
|
+
const rawWords = stripped.match(WORD_RE) ?? [];
|
|
331
|
+
const words = rawWords.map((w) => w.toLowerCase());
|
|
332
|
+
const lowered = text.toLowerCase();
|
|
333
|
+
let diac = 0;
|
|
334
|
+
for (const ch of lowered) {
|
|
335
|
+
if (NON_EN_DIACRITICS.has(ch))
|
|
336
|
+
diac += 1;
|
|
337
|
+
}
|
|
338
|
+
const diacRate = diac / Math.max(1, lowered.length);
|
|
339
|
+
const nonEnglish = diacRate >= NON_EN_DIACRITIC_RATE;
|
|
340
|
+
const nordicOverlap = words.some((w) => NORDIC_OVERLAP_WORDS.has(w)) &&
|
|
341
|
+
!words.some((w) => EN_ONLY_WORDS.has(w));
|
|
342
|
+
if (words.length > 1 && words.length < 4 && words.some((w) => SHORT_SWEDISH_WORDS.has(w))) {
|
|
343
|
+
return { language: "sv", englishHits: 0, diacriticRate: diacRate, looksNonEnglish: nonEnglish };
|
|
344
|
+
}
|
|
345
|
+
if (words.length < 4) {
|
|
346
|
+
return { language: null, englishHits: 0, diacriticRate: diacRate, looksNonEnglish: nonEnglish || nordicOverlap };
|
|
347
|
+
}
|
|
348
|
+
// A collision word counts once however often it repeats; every other word counts its hits.
|
|
349
|
+
const counts = new Map();
|
|
350
|
+
for (const w of words)
|
|
351
|
+
counts.set(w, (counts.get(w) ?? 0) + 1);
|
|
352
|
+
const scores = {};
|
|
353
|
+
for (const [lg, sw] of Object.entries(STOP)) {
|
|
354
|
+
let s = 0;
|
|
355
|
+
for (const [w, n] of counts)
|
|
356
|
+
if (sw.has(w))
|
|
357
|
+
s += EN_COLLISION_WORDS.has(w) ? 1 : n;
|
|
358
|
+
scores[lg] = s;
|
|
359
|
+
}
|
|
360
|
+
const en = scores["en"] ?? 0;
|
|
361
|
+
const wordSet = new Set(words);
|
|
362
|
+
let bestLg = null;
|
|
363
|
+
let best = 0;
|
|
364
|
+
for (const [lg, s] of Object.entries(scores)) {
|
|
365
|
+
if (lg === "en")
|
|
366
|
+
continue;
|
|
367
|
+
const hasEvidence = [...wordSet].some((w) => STOP[lg].has(w) && !SHARED_WORDS.has(w));
|
|
368
|
+
if (!hasEvidence)
|
|
369
|
+
continue;
|
|
370
|
+
if (s > best) {
|
|
371
|
+
best = s;
|
|
372
|
+
bestLg = lg;
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
let lang = null;
|
|
376
|
+
if (bestLg && best >= Math.max(2, en + 2)) {
|
|
377
|
+
lang = bestLg;
|
|
378
|
+
}
|
|
379
|
+
else if (bestLg === "sv" && words.includes("inte") && words.includes("kan") &&
|
|
380
|
+
["kan", "jag", "vi"].includes(words[0]) && en <= 1) {
|
|
381
|
+
// Short login requests like "kan inte logga in" contain one English-shaped token (`in`).
|
|
382
|
+
lang = bestLg;
|
|
383
|
+
}
|
|
384
|
+
else if (bestLg && nonEnglish && best >= Math.max(2, en)) {
|
|
385
|
+
lang = bestLg;
|
|
386
|
+
}
|
|
387
|
+
else if (en && (!nonEnglish || englishRescuedByWords(wordSet, diacRate))) {
|
|
388
|
+
lang = "en";
|
|
389
|
+
}
|
|
390
|
+
return { language: lang, englishHits: en, diacriticRate: diacRate, looksNonEnglish: nonEnglish || (lang === null && nordicOverlap) };
|
|
391
|
+
}
|
|
392
|
+
export function guessLatinLanguage(text) {
|
|
393
|
+
return latinProfile(text).language;
|
|
394
|
+
}
|
|
395
|
+
// Code is not prose in any language, but split into words it reads as one: `os.path` is Portuguese
|
|
396
|
+
// (`os`), `round(el, 2)` Spanish (`el`), `non_english` Italian (`non`). A line pasted from a program
|
|
397
|
+
// into an English request must not count as a foreign segment, so a line carrying code syntax --
|
|
398
|
+
// `=`, `;`, braces, brackets or a call `name(` -- is skipped, and dotted or underscored identifiers
|
|
399
|
+
// are dropped from the rest. Prose keeps "Deu erro (500)": the parenthesis follows a space.
|
|
400
|
+
const CODE_LINE_RE = /[=;{}[\]]|\w\(/;
|
|
401
|
+
// Slash and backslash compounds are names, not sentences: `Nav/Com` and `OS/2` read as Portuguese
|
|
402
|
+
// (`com`, `os`), `C:\DOS\mode` as Portuguese (`dos`), `ESA/UN` as Spanish (`un`). A whitespace token
|
|
403
|
+
// holding a letter or digit, a joiner (`.`, `_`, `/`, `\`) and another letter or digit is an
|
|
404
|
+
// identifier or a compound and is dropped whole.
|
|
405
|
+
const JOINED_RE = /[^\W_][._/\\][^\W_]/;
|
|
406
|
+
// An all-caps token inside mixed-case text is an acronym or a code: `MON`, `LA`, `EST`, `COM`, `DES`
|
|
407
|
+
// are hockey teams, states, time zones and radio bands, not French or Portuguese. A segment written
|
|
408
|
+
// entirely in capitals keeps its words -- a customer shouting in Portuguese is still Portuguese.
|
|
409
|
+
const LETTER_RUN_RE = /[\p{L}]{2,}/gu;
|
|
410
|
+
/** Language code for one non-code line, or null when it does not name a foreign language.
|
|
411
|
+
*
|
|
412
|
+
* Same evidence bar as `nonEnglishSegment`: four words, a language `latinProfile` will name,
|
|
413
|
+
* and two *different* words of that language. Acronyms and slash compounds are not words.
|
|
414
|
+
*/
|
|
415
|
+
function namedProseLanguage(segment) {
|
|
416
|
+
if (!segment.trim() || CODE_LINE_RE.test(segment))
|
|
417
|
+
return null;
|
|
418
|
+
const prose = segment.split(/\s+/).filter((tok) => !JOINED_RE.test(tok)).join(" ");
|
|
419
|
+
// In mixed-case text, replace all-caps runs with spaces (they are acronyms).
|
|
420
|
+
let cleaned = prose;
|
|
421
|
+
if ([...prose].some((ch) => /\p{Ll}/u.test(ch))) {
|
|
422
|
+
cleaned = prose.replace(LETTER_RUN_RE, (m) => (m === m.toUpperCase() ? " " : m));
|
|
423
|
+
}
|
|
424
|
+
const tokens = cleaned.match(WORD_RE) ?? [];
|
|
425
|
+
if (tokens.length < 4)
|
|
426
|
+
return null;
|
|
427
|
+
const lang = latinProfile(cleaned).language;
|
|
428
|
+
if (lang === null || lang === "en")
|
|
429
|
+
return null;
|
|
430
|
+
const stopSet = STOP[lang];
|
|
431
|
+
if (!stopSet)
|
|
432
|
+
return null;
|
|
433
|
+
const distinctHits = new Set(tokens.map((w) => w.toLowerCase()).filter((w) => stopSet.has(w)));
|
|
434
|
+
if (distinctHits.size < 2)
|
|
435
|
+
return null;
|
|
436
|
+
return lang;
|
|
437
|
+
}
|
|
438
|
+
/** First line or field that, read on its own, is named a non-English language, else null.
|
|
439
|
+
*
|
|
440
|
+
* Returns [language, segment]. A segment needs the evidence a whole state needs -- at least four
|
|
441
|
+
* words, and a language named by `latinProfile` -- and, because one line carries far less text
|
|
442
|
+
* than a state, two things more: the words that name the language must be two *different* ones
|
|
443
|
+
* (`COM ... COM` in an English radio listing is one word seen twice), and acronyms and slash
|
|
444
|
+
* compounds are not words. This adds no new way to call English text foreign; it only stops a
|
|
445
|
+
* longer English part from outvoting a foreign one. Reads at most `maxChars` characters in all.
|
|
446
|
+
*/
|
|
447
|
+
function nonEnglishSegment(state, maxChars = 4000) {
|
|
448
|
+
let seen = 0;
|
|
449
|
+
for (const leaf of iterText(state)) {
|
|
450
|
+
for (const seg of leaf.split("\n")) {
|
|
451
|
+
if (seen >= maxChars)
|
|
452
|
+
return null;
|
|
453
|
+
const capped = seg.slice(0, maxChars - seen);
|
|
454
|
+
seen += capped.length;
|
|
455
|
+
const lang = namedProseLanguage(capped);
|
|
456
|
+
if (lang)
|
|
457
|
+
return [lang, capped.trim()];
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
return null;
|
|
461
|
+
}
|
|
462
|
+
function round4(x) {
|
|
463
|
+
return Math.round(x * 10000) / 10000;
|
|
464
|
+
}
|
|
465
|
+
function analyseText(text) {
|
|
466
|
+
const prof = scriptProfile(text);
|
|
467
|
+
let script = detectScript(text);
|
|
468
|
+
const nonLatin = prof && Object.keys(prof).length ? round4(1.0 - (prof["latin"] ?? 0.0)) : 0.0;
|
|
469
|
+
let nAlpha = 0;
|
|
470
|
+
for (const ch of text)
|
|
471
|
+
if (IS_ALPHA_RE.test(ch))
|
|
472
|
+
nAlpha += 1;
|
|
473
|
+
const nNonLatin = Math.round(nonLatin * nAlpha);
|
|
474
|
+
if (script === "latin" && nonLatinWords(text).length > 0 &&
|
|
475
|
+
(nonLatin >= NON_LATIN_FRACTION ||
|
|
476
|
+
(nonLatin >= NON_LATIN_MIN_FRACTION && nNonLatin >= NON_LATIN_MIN_LETTERS))) {
|
|
477
|
+
// The plurality said Latin, but the non-Latin share is a real message, not a stray name or
|
|
478
|
+
// symbol: re-classify to the dominant non-Latin script, as Python's analyse does.
|
|
479
|
+
let bestScript = script;
|
|
480
|
+
let bestShare = -1;
|
|
481
|
+
for (const [s, share] of Object.entries(prof)) {
|
|
482
|
+
if (s !== "latin" && share > bestShare) {
|
|
483
|
+
bestShare = share;
|
|
484
|
+
bestScript = s;
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
script = bestScript;
|
|
488
|
+
}
|
|
489
|
+
if (script === "unknown") {
|
|
490
|
+
return {
|
|
491
|
+
script: "unknown", scriptProfile: prof, language: null,
|
|
492
|
+
isEnglish: true, languageUndecided: true, diacriticRate: 0.0,
|
|
493
|
+
nonLatinFraction: 0.0, mixedSegment: null,
|
|
494
|
+
};
|
|
495
|
+
}
|
|
496
|
+
if (script !== "latin") {
|
|
497
|
+
return {
|
|
498
|
+
script, scriptProfile: prof, language: null,
|
|
499
|
+
isEnglish: false, languageUndecided: true, diacriticRate: 0.0,
|
|
500
|
+
nonLatinFraction: nonLatin, mixedSegment: null,
|
|
501
|
+
};
|
|
502
|
+
}
|
|
503
|
+
const profLat = latinProfile(text);
|
|
504
|
+
const lang = profLat.language;
|
|
505
|
+
const undecided = lang === null;
|
|
506
|
+
const english = lang === "en" || (undecided && !profLat.looksNonEnglish);
|
|
507
|
+
return {
|
|
508
|
+
script: "latin", scriptProfile: prof, language: lang,
|
|
509
|
+
isEnglish: english, languageUndecided: undecided,
|
|
510
|
+
diacriticRate: round4(profLat.diacriticRate),
|
|
511
|
+
nonLatinFraction: nonLatin, mixedSegment: null,
|
|
512
|
+
};
|
|
513
|
+
}
|
|
514
|
+
function alphaCount(text) {
|
|
515
|
+
let n = 0;
|
|
516
|
+
for (const ch of text)
|
|
517
|
+
if (IS_ALPHA_RE.test(ch))
|
|
518
|
+
n += 1;
|
|
519
|
+
return n;
|
|
520
|
+
}
|
|
521
|
+
/** A string value that is itself not safe for the English checkpoint, else null. */
|
|
522
|
+
function leafNonEnglish(leaf) {
|
|
523
|
+
const sample = leaf.slice(0, 4000);
|
|
524
|
+
if (!sample.trim())
|
|
525
|
+
return null;
|
|
526
|
+
const det = analyseText(sample);
|
|
527
|
+
if (det.isEnglish)
|
|
528
|
+
return null;
|
|
529
|
+
if (det.language !== null && det.language !== "en")
|
|
530
|
+
return det;
|
|
531
|
+
const nAlpha = alphaCount(sample);
|
|
532
|
+
if (det.script !== "latin" && det.script !== "unknown") {
|
|
533
|
+
if (nonLatinWords(sample).length > 0 && nAlpha >= NON_LATIN_MIN_LETTERS)
|
|
534
|
+
return det;
|
|
535
|
+
return null;
|
|
536
|
+
}
|
|
537
|
+
const words = sample.match(WORD_RE) ?? [];
|
|
538
|
+
if (det.languageUndecided && det.diacriticRate >= NON_EN_DIACRITIC_RATE && words.length >= 4) {
|
|
539
|
+
return det;
|
|
540
|
+
}
|
|
541
|
+
return null;
|
|
542
|
+
}
|
|
543
|
+
export function analyse(state) {
|
|
544
|
+
// One non-English string value is enough. Joining every value let a long English
|
|
545
|
+
// note fill the window, or outvote a short German message, and that message was
|
|
546
|
+
// then sent to the English checkpoint.
|
|
547
|
+
const result = analyseText(stateText(state));
|
|
548
|
+
if (result.script === "latin" && result.isEnglish) {
|
|
549
|
+
// A Portuguese ticket with an English stack trace, error payload or form template reads as
|
|
550
|
+
// English as a whole, because the English part is longer -- yet the part a question is about
|
|
551
|
+
// is the customer's, and the English checkpoint cannot read it. So a state that would go to
|
|
552
|
+
// English is checked line by line and field by field.
|
|
553
|
+
const leaves = iterText(state);
|
|
554
|
+
// a single line has no other part to be outvoted by, and was just read whole
|
|
555
|
+
if (leaves.length > 1 || leaves.some((leaf) => leaf.includes("\n"))) {
|
|
556
|
+
const found = nonEnglishSegment(state);
|
|
557
|
+
if (found) {
|
|
558
|
+
const [lang, mixed] = found;
|
|
559
|
+
return {
|
|
560
|
+
...result,
|
|
561
|
+
language: lang,
|
|
562
|
+
isEnglish: false,
|
|
563
|
+
languageUndecided: false,
|
|
564
|
+
mixedSegment: mixed,
|
|
565
|
+
};
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
// A plain string was just read whole. A structured state can still hide a message past the
|
|
570
|
+
// segment cap, or in a script `latinProfile` does not name.
|
|
571
|
+
if (typeof state === "string" || state == null || state instanceof Uint8Array || !result.isEnglish) {
|
|
572
|
+
return result;
|
|
573
|
+
}
|
|
574
|
+
let best = null;
|
|
575
|
+
let bestN = -1;
|
|
576
|
+
for (const leaf of iterText(state)) {
|
|
577
|
+
const det = leafNonEnglish(leaf);
|
|
578
|
+
if (!det)
|
|
579
|
+
continue;
|
|
580
|
+
const n = alphaCount(leaf.slice(0, 4000));
|
|
581
|
+
if (n > bestN) {
|
|
582
|
+
bestN = n;
|
|
583
|
+
best = det;
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
return best ?? result;
|
|
587
|
+
}
|
|
588
|
+
export function isEnglish(state) {
|
|
589
|
+
return analyse(state).isEnglish;
|
|
590
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export declare function triageQuestions(): Record<string, unknown>;
|
|
2
|
+
export declare function emailQuestions(categories?: Record<string, string>): Record<string, unknown>;
|
|
3
|
+
export declare function guardQuestions(): Record<string, unknown>;
|
|
4
|
+
export declare function moderationQuestions(): Record<string, unknown>;
|
|
5
|
+
export declare function routerQuestions(): Record<string, unknown>;
|