Skip to content

armgit / laya

Public Imported from GitHub
0

Non-autoregressive System 1 decision engine. Typed choice, score and yes/no decisions over any text in a single forward pass, in 100+ languages, with a router that picks the right checkpoint per request.

fix(laya-ts): stop reading all-caps lines as French or Portuguese

thread3d5a611d598c1a
diff --git a/laya-ts/src/lang.ts b/laya-ts/src/lang.ts
index 13e89913..31554cf5 100644
--- a/laya-ts/src/lang.ts
+++ b/laya-ts/src/lang.ts
@@ -287,6 +287,13 @@ export function scriptProfile(text: string): Record<string, number> {
// character carries far more than a letter. A short message needs a large share to count; a long
// payload (ticket fields, English agent turns) dilutes the share, so there a sentence's worth of
// letters counts too.
+// All-caps handling. A customer shouting in Portuguese is still Portuguese; an acronym block is not
+// French. A token of this many LETTERS is a word rather than an acronym, and on an all-caps line it
+// has to be a function word of the named language (or the line has to carry non-English
+// diacritics) before the line counts as prose in that language.
+const SHOUTED_MIN_WORD = 5;
+const SHOUTED_MIN_STOPWORD = 4;
+
const NON_LATIN_FRACTION = 0.2;
const NON_LATIN_MIN_FRACTION = 0.1;
const NON_LATIN_MIN_LETTERS = 10;
@@ -411,6 +418,32 @@ const JOINED_RE = /[^\W_][._/\\][^\W_]/;
// entirely in capitals keeps its words -- a customer shouting in Portuguese is still Portuguese.
const LETTER_RUN_RE = /[\p{L}]{2,}/gu;
+/** True for a CASED segment written entirely in capitals.
+ *
+ * The uppercase half is not redundant: a caseless script has no lowercase either, so testing only
+ * "has a lowercase letter" would call every Devanagari or CJK line shouted and hold it to a bar it
+ * cannot clear. Both caps bars stay off text that is partly caseless (`analyseText`), because a bar
+ * that works by discarding Latin evidence has nothing to say about the half it cannot read.
+ */
+function shouted(text: string): boolean {
+ let upper = false;
+ for (const ch of text) {
+ if (/\p{Ll}/u.test(ch)) return false;
+ if (/\p{Lu}|\p{Lt}/u.test(ch)) upper = true;
+ }
+ return upper;
+}
+
+/** Whether an all-caps line's evidence for `lang` is more than acronym-shaped tokens. */
+function shoutedEvidence(tokens: string[], lang: string, diacriticRate: number): boolean {
+ if (!tokens.some((t) => t.length >= SHOUTED_MIN_WORD)) return false;
+ if (diacriticRate >= NON_EN_DIACRITIC_RATE) return true;
+ const stopSet = STOP[lang];
+ if (!stopSet) return false;
+ const matched = new Set(tokens.map((t) => t.toLowerCase()).filter((t) => stopSet.has(t)));
+ return [...matched].some((w) => w.length >= SHOUTED_MIN_STOPWORD);
+}
+
/** Language code for one non-code line, or null when it does not name a foreign language.
*
* Same evidence bar as `nonEnglishSegment`: four words, a language `latinProfile` will name,
@@ -418,16 +451,20 @@ const LETTER_RUN_RE = /[\p{L}]{2,}/gu;
*/
function namedProseLanguage(segment: string): string | null {
if (!segment.trim() || CODE_LINE_RE.test(segment)) return null;
- const prose = segment.split(/\s+/).filter((tok) => !JOINED_RE.test(tok)).join(" ");
- // In mixed-case text, replace all-caps runs with spaces (they are acronyms).
- let cleaned = prose;
- if ([...prose].some((ch) => /\p{Ll}/u.test(ch))) {
- cleaned = prose.replace(LETTER_RUN_RE, (m) => (m === m.toUpperCase() ? " " : m));
+ let prose = segment.split(/\s+/).filter((tok) => !JOINED_RE.test(tok)).join(" ");
+ // A shouted segment keeps its acronym-shaped tokens -- shouting is not a foreign language, so it
+ // must also clear `shoutedEvidence` below. Mixed-case text blanks all-caps runs (they are
+ // acronyms) before the words are counted, which is Python's `_named_prose_language` split.
+ const isShouted = shouted(prose);
+ if (!isShouted) {
+ prose = prose.replace(LETTER_RUN_RE, (m) => (m === m.toUpperCase() ? " " : m));
}
- const tokens = cleaned.match(WORD_RE) ?? [];
+ const tokens = prose.match(WORD_RE) ?? [];
if (tokens.length < 4) return null;
- const lang = latinProfile(cleaned).language;
+ const prof = latinProfile(prose);
+ const lang = prof.language;
if (lang === null || lang === "en") return null;
+ if (isShouted && !shoutedEvidence(tokens, lang, prof.diacriticRate)) return null;
const stopSet = STOP[lang];
if (!stopSet) return null;
const distinctHits = new Set(tokens.map((w) => w.toLowerCase()).filter((w) => stopSet.has(w)));
@@ -458,6 +495,12 @@ function nonEnglishSegment(state: unknown, maxChars = 4000): [string, string] |
return null;
}
+/** Whether the non-Latin share of a Latin-plurality text is a real message, not a stray name. */
+function nonLatinCarries(nonLatin: number, nNonLatin: number): boolean {
+ return nonLatin >= NON_LATIN_FRACTION ||
+ (nonLatin >= NON_LATIN_MIN_FRACTION && nNonLatin >= NON_LATIN_MIN_LETTERS);
+}
+
function round4(x: number): number {
return Math.round(x * 10000) / 10000;
}
@@ -469,9 +512,7 @@ function analyseText(text: string): AnalyseResult {
let nAlpha = 0;
for (const ch of text) if (IS_ALPHA_RE.test(ch)) nAlpha += 1;
const nNonLatin = Math.round(nonLatin * nAlpha);
- if (script === "latin" && nonLatinWords(text).length > 0 &&
- (nonLatin >= NON_LATIN_FRACTION ||
- (nonLatin >= NON_LATIN_MIN_FRACTION && nNonLatin >= NON_LATIN_MIN_LETTERS))) {
+ if (script === "latin" && nonLatinWords(text).length > 0 && nonLatinCarries(nonLatin, nNonLatin)) {
// The plurality said Latin, but the non-Latin share is a real message, not a stray name or
// symbol: re-classify to the dominant non-Latin script, as Python's analyse does.
let bestScript = script;
@@ -499,7 +540,34 @@ function analyseText(text: string): AnalyseResult {
};
}
const profLat = latinProfile(text);
- const lang = profLat.language;
+ let lang = profLat.language;
+ // The acronym bar belongs here too, not only in the segment scan. That scan runs once a state
+ // already reads English overall, so a state that is *nothing but* an acronym line -- or one
+ // diluted by fewer English lines than it takes to tip this verdict -- never reached it and was
+ // named foreign outright: `MON DES EST LA` read French on its own. Vetoing here leaves the text
+ // undecided, so `looksNonEnglish` still decides it, and a shouted line with non-English
+ // diacritics is kept.
+ //
+ // Neither bar applies when the state is carried by a caseless script: both answer the verdict by
+ // taking evidence away from the Latin letters, and what is left is judged on Latin diacritics,
+ // which cannot see the caseless half -- so `ПРИВЕТ MON DES EST LA` would otherwise be sent to the
+ // English checkpoint on the strength of disbelieving the Latin part.
+ if (lang !== null && lang !== "en" && !nonLatinCarries(nonLatin, nNonLatin)) {
+ if (shouted(text)) {
+ if (!shoutedEvidence(text.match(WORD_RE) ?? [], lang, profLat.diacriticRate)) lang = null;
+ } else {
+ // Mixed-case text: re-take the verdict without the all-caps runs that voted in it. Only
+ // ACRONYM-SHAPED runs are blanked -- a run of SHOUTED_MIN_WORD letters is a word, and a word
+ // is not blanked out of its own sentence (blanking every run deleted emphasis capitals, so
+ // `sag mir das HEUTIGE DATUM` lost its verdict). Diacritic evidence stays measured on the
+ // original text, so a shouted foreign word cannot be blanked out of the safety net.
+ const caps = (text.match(LETTER_RUN_RE) ?? []).filter((m) => m === m.toUpperCase());
+ if (caps.length > 0 && !caps.some((c) => c.length >= SHOUTED_MIN_WORD)) {
+ const blanked = text.replace(LETTER_RUN_RE, (m) => (m === m.toUpperCase() ? " " : m));
+ if (blanked !== text) lang = latinProfile(blanked).language;
+ }
+ }
+ }
const undecided = lang === null;
const english = lang === "en" || (undecided && !profLat.looksNonEnglish);
return {
diff --git a/laya-ts/tests/lang.test.ts b/laya-ts/tests/lang.test.ts
index fd567e0f..843253b4 100644
--- a/laya-ts/tests/lang.test.ts
+++ b/laya-ts/tests/lang.test.ts
@@ -1,6 +1,7 @@
// laya-ts/tests/lang.test.ts
import { describe, expect, it } from "vitest";
import { analyse, detectScript, guessLatinLanguage, isEnglish } from "../src/lang.js";
+import { Router } from "../src/router.js";
describe("lang", () => {
it("detects devanagari as non-latin", () => {
expect(detectScript("मुझसे दो बार शुल्क लिया गया")).toBe("devanagari");
@@ -257,3 +258,51 @@ describe("lang", () => {
expect(analyse(text).isEnglish).toBe(false);
});
});
+
+// All-caps handling, ported from `laya/lang.py:605-660, 750-800` (#1315's follow-up). An acronym
+// block is not a foreign language, so it must not vote in the whole-state verdict nor name a
+// foreign segment on its own line; a customer shouting in Portuguese is still Portuguese.
+//
+// The states and expectations below are the Python reference's own, recorded in
+// `laya-rust/tests/golden/routing/lang_probe.json` (generated by `laya/lang.py`). Before the port
+// nine of those recorded cases diverged; they are these.
+describe("lang/all-caps routing", () => {
+ const recorded: [string, string, unknown, string | null, boolean][] = [
+ // label, comment, state, expected language, expected isEnglish
+ ["shouted acronyms", "an acronym line alone is not French", "MON DES EST LA", null, true],
+ ["acronyms under one English line", "", "Please look at this\nMON DES EST LA", "en", true],
+ ["acronyms under two English lines", "", "Please look at this\nand send me the details.\nMON DES EST LA", "en", true],
+ ["shouted address", "US cities, not Spanish", "STORES LOS ANGELES LAS VEGAS EL PASO CLOSED", null, true],
+ ["shouted German, umlaut", "diacritics are evidence, so it stays non-English", "WIE SPÄT IST ES IN KÖLN", null, false],
+ ["shouted German, ASCII", "no diacritics and no long stopword: the documented loss", "WIE SPAET IST ES IN KOELN", null, true],
+ ["emphasis capitals in Portuguese", "a word-length run is not an acronym and is not blanked", "quero cancelar o pedido MON DES EST LA por favor", "pt", false],
+ ["acronym segment beside prose", "", "Please review the error and send me the details.\nMON DES EST LA", "en", true],
+ ];
+ it.each(recorded)("%s: %s", (label, _comment, state, language, isEnglish) => {
+ const got = analyse(state);
+ expect(got.language, label).toBe(language);
+ expect(got.isEnglish, label).toBe(isEnglish);
+ });
+
+ it("routes ordinary English support text carrying an acronym line to the English checkpoint", () => {
+ // The reported shape: real mail with a technical block in capitals. Python routes it english;
+ // this side named the block Portuguese and took the multilingual checkpoint.
+ const state = "Hello,\nNAV COM OS 2 DESKTOP SUPPORT\nI cannot connect to the VPN";
+ expect(analyse(state).isEnglish).toBe(true);
+ expect(new Router().route(state, {}).model).toBe("english");
+ });
+
+ it("keeps a shouted foreign line foreign when it carries diacritics", () => {
+ // `shoutedEvidence`'s other branch: non-English diacritics count in place of a long stopword,
+ // so the veto must not swallow a customer writing in capitals in their own language.
+ const state = "WIE SPÄT IST ES IN KÖLN";
+ expect(analyse(state).isEnglish).toBe(false);
+ expect(new Router().route(state, {}).model).toBe("multilingual");
+ });
+
+ it("does not blank a word-length run out of its own sentence", () => {
+ // Blanking every all-caps run deleted emphasis capitals and lost verdicts (`sag mir das
+ // HEUTIGE DATUM` routed english). Only runs short enough to be acronyms are blanked.
+ expect(analyse("quero cancelar o pedido MON DES EST LA por favor").language).toBe("pt");
+ });
+});