CI / Trivy (dependências, segredos e configuração) (push) Successful in 1m2s
CI / Testes e imagem Docker (linux/arm64) (push) Successful in 4m24s
Release / Plano (reaproveitar a imagem?) (push) Successful in 5s
Release / ci (push) Skipped
Release / Publica a imagem (linux/arm64) (push) Successful in 18s
Release / Cria a release no Gitea (push) Successful in 4s
Interface reescrita (design próprio, tema claro/escuro, a11y WCAG 2.2 AA), seções do site e artigo IDEIA @ CSBC 2025. Tradutor portado para JS com paridade 100% contra o Python; sem Tailwind nem axios. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
157 lines
9.8 KiB
JavaScript
157 lines
9.8 KiB
JavaScript
#!/usr/bin/env node
|
||
// Paridade do tradutor JS (public/modules/translator.js) contra o Python (src/translation).
|
||
// Uso: node scripts/paridade-tradutor.mjs (PYTHON=/caminho/python3 se precisar de um venv com pypinyin)
|
||
// Sai com código 1 se QUALQUER saída divergir.
|
||
import { spawnSync } from "node:child_process";
|
||
import { mkdtempSync, writeFileSync, readFileSync, rmSync } from "node:fs";
|
||
import { tmpdir } from "node:os";
|
||
import { join, dirname } from "node:path";
|
||
import { fileURLToPath } from "node:url";
|
||
import { encodeText, decodeText } from "../public/modules/translator.js";
|
||
|
||
const here = dirname(fileURLToPath(import.meta.url));
|
||
const ALPHABETS = ["Brazilian", "North American", "Chinese", "Klingon"];
|
||
const PYTHON = process.env.PYTHON || "python3";
|
||
|
||
// PRNG determinístico (mulberry32) para a parte aleatória ser reproduzível.
|
||
let seed = 20261115;
|
||
const rnd = () => {
|
||
seed |= 0; seed = (seed + 0x6d2b79f5) | 0;
|
||
let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
|
||
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
|
||
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
||
};
|
||
const pick = (arr) => arr[Math.floor(rnd() * arr.length)];
|
||
|
||
const curated = [
|
||
"", " ", "\n", "a", "A", "Olá, mundo!", "AÇÃO", "Ação e Coração", "João Pedro", "Maria José 123", "Rua das Flores, 45 - Centro",
|
||
"PÃO DE AÇÚCAR", "Pão de açúcar", "É proibido.", "à, â, ê, ô, ã, õ, ç", "ÁÉÍÓÚ áéíóú", "Texto (com parênteses) e [colchetes]",
|
||
"(abc)def", "abc(def)ghi", "x)y(z", "50% de desconto", "R$ 1.234,56", "1a 2b 3c", "a1 b2", "123abc", "abc123", "A1B2", "1,5 + 2 = 3,5",
|
||
"a/b", "a*b&c$d", "<tag>", "!?.,;:", "Hello, World!", "The quick brown fox jumps over the lazy dog.", "HELLO WORLD", "Hello \"quoted\" it's",
|
||
"email@example.com #hashtag", "C:\\path\\file_name", "a\tb", "linha1\nlinha2\n\nlinha4", " espaços múltiplos ", "fim com espaço ", "\n\nabc\n\n",
|
||
"Ünïcödé ñ ß", "İstanbul", "Σίσυφος ΣΟΦΟΣ", "emoji 😀 teste", "一二三 abc", "②³ x", "½ y", "ⅷ", "Ⅷ",
|
||
"你好", "你好,世界!", "我爱你", "中国", "中国人民共和国", "银行行长", "重庆市长江大桥", "我的书", "他的、她的;它的:好。", "什么?真的!", "你好 世界", "你好\n世界",
|
||
"今天天气很好", "北京欢迎你", "谢谢", "对不起", "再见", "学习汉语很有意思", "女儿绿色", "吗了的得地", "不要紧", "一个一样", "朋友们", "电脑", "手机", "水果", "我们都是中国人。",
|
||
"ni3 hao3", "zhong1guo2", "nǐ hǎo", "lǜ nǚ lüè", "Beijing", "pinyin ü v", "xiang jiang qiang", "zhi chi shi ri zi ci si", "de5 de",
|
||
"你好abc", "abc你好", "hello 世界 123", "A你B", ",。、", "...", "…", "123", "1 2 3",
|
||
"⠓⠑⠇⠇⠕", "⠠⠓⠑⠇⠇⠕", "⠼⠁⠃⠉", "⠨⠨⠁⠃⠉", "⠣⠄⠁⠃⠉⠄⠜", "⠷⠄⠁⠄⠾", "⠸⠴", "⠠⠂", "⠨⠁⠃", "⠼⠁⠂⠁", "⠐", "⠀⠀", "⠁⠀⠃\n⠉",
|
||
];
|
||
const sample = {
|
||
pt: "o a de que e do da em um para com não uma os no se na por mais as dos como mas foi ao ele das tem à seu sua ou ser quando muito há nos já está eu também só pelo pela até isso ela entre era depois sem mesmo aos ter seus quem nas me esse eles estão você tinha foram essa num nem suas meu às minha têm numa pelos elas havia seja qual será nós tenho lhe deles essas esses pelas este fosse dele ação coração informação João Maria José São Paulo Ângela Álvaro Érica Ônibus açúcar pão mãe avó irmã".split(" "),
|
||
en: "the be to of and a in that have I it for not on with he as you do at this but his by from they we say her she or an will my one all would there their what so up out if about who get which go me when make can like time no just him know take people into year your good some could them see other than then now look only come its over think also back after use two how our work first well way even new want because any these give day most us".split(" "),
|
||
zh: "我你他她它们的是不了在有人这中大为上个国到说时要就出会可也你对生能而子那得于着下自之年过发后作里用道行所然家种事成方多经么当起与好看学进种将还分此心前面又定见只主没公从".split(""),
|
||
zhw: "你好 谢谢 中国 北京 上海 银行 行走 重庆 重要 长大 长度 音乐 快乐 还有 还是 都是 首都 觉得 睡觉 地方 土地 得到 的确 目的 好的 了解 为了 因为 为什么 不是 没有 朋友 学校 老师 学生 工作 生活 电话 电影 吃饭 喝水 看书 写字 说话 听歌 走路 开车 坐车 飞机 火车 汽车 自行车 我们 你们 他们 大家 孩子 爸爸 妈妈 哥哥 姐姐 弟弟 妹妹 爷爷 奶奶".split(" "),
|
||
punct: [",", "。", "!", "?", "、", ";", ":", ",", ".", "!", "?", ";", ":", "-", "…", "(", ")", "[", "]", "\"", "'", "%", "$", "&", "*", "/", "\\", "#", "@", "_", "+", "=", "<", ">"],
|
||
nums: ["0", "1", "2", "3", "45", "678", "9", "100", "2026", "3,14", "1.000"],
|
||
};
|
||
const seps = [" ", " ", " ", "\n", ""];
|
||
function randomText(kind) {
|
||
const n = 1 + Math.floor(rnd() * 25);
|
||
const words = [];
|
||
for (let i = 0; i < n; i++) {
|
||
const r = rnd();
|
||
let w;
|
||
if (kind === "pt") w = r < 0.7 ? pick(sample.pt) : r < 0.8 ? pick(sample.nums) : pick(sample.punct);
|
||
else if (kind === "en") w = r < 0.75 ? pick(sample.en) : r < 0.85 ? pick(sample.nums) : pick(sample.punct);
|
||
else w = r < 0.35 ? pick(sample.zhw) : r < 0.6 ? pick(sample.zh) + pick(sample.zh) : r < 0.75 ? pick(sample.punct) : r < 0.85 ? pick(sample.en) : pick(sample.nums);
|
||
const c = rnd();
|
||
if (c < 0.15) w = w.toUpperCase(); else if (c < 0.3) w = w[0].toUpperCase() + w.slice(1);
|
||
words.push(w);
|
||
words.push(pick(seps));
|
||
}
|
||
return words.join("");
|
||
}
|
||
|
||
const cases = [];
|
||
const add = (op, alphabet, input) => cases.push({ op, alphabet, input });
|
||
|
||
// 1. Curados: encode e decode em todos os alfabetos (+ alfabeto inválido).
|
||
for (const text of curated) for (const a of ALPHABETS) { add("encode", a, text); add("decode", a, text); }
|
||
// 2. Aleatórios: pt, en, zh em todos os alfabetos.
|
||
for (let i = 0; i < 400; i++) {
|
||
const kind = ["pt", "en", "zh"][i % 3];
|
||
const a = ALPHABETS[Math.floor(rnd() * 3)];
|
||
add("encode", a, randomText(kind));
|
||
}
|
||
// 3. Textos longos (limite do servidor: 5000).
|
||
for (const a of ALPHABETS.slice(0, 3)) {
|
||
let t = "";
|
||
while (t.length < 4900) t += randomText(a === "Chinese" ? "zh" : "pt") + "\n";
|
||
add("encode", a, t.slice(0, 5000));
|
||
add("encode", a, "a".repeat(5000));
|
||
}
|
||
add("encode", "Chinese", "你好".repeat(2500));
|
||
// 4. Cada caractere Han (20992) em Chinese: valida o dicionário inteiro.
|
||
for (let cp = 0x4e00; cp < 0xa000; cp++) add("encode", "Chinese", String.fromCodePoint(cp));
|
||
// 5. Todo o BMP individualmente, Brazilian e North American (isalpha/isnumeric/isupper/lower/espaços).
|
||
// Pontos ainda não atribuídos no Unicode do Python (Cn) ficam de fora: o Node costuma ter um Unicode
|
||
// mais novo, e a diferença seria só de versão da tabela, não de lógica.
|
||
const unassigned = new Set(JSON.parse(spawnSync(PYTHON, ["-c",
|
||
"import unicodedata,json;print(json.dumps([c for c in range(65536) if unicodedata.category(chr(c))=='Cn']))"], { encoding: "utf8" }).stdout || "[]"));
|
||
for (let cp = 0; cp < 0x10000; cp++) {
|
||
if ((cp >= 0xd800 && cp < 0xe000) || unassigned.has(cp)) continue;
|
||
const ch = String.fromCodePoint(cp);
|
||
add("encode", "Brazilian", ch); add("encode", "Brazilian", "a" + ch + "b"); add("encode", "North American", ch);
|
||
add("encode", "Chinese", ch + "a"); add("encode", "Chinese", "ni" + ch + "3");
|
||
}
|
||
// 6. Pares aleatórios de braille para decode.
|
||
const braille = (n) => Array.from({ length: n }, () => String.fromCodePoint(0x2800 + Math.floor(rnd() * 64))).join("");
|
||
for (let i = 0; i < 400; i++) {
|
||
const a = ALPHABETS[i % 3];
|
||
let s = "";
|
||
const n = 1 + Math.floor(rnd() * 12);
|
||
for (let j = 0; j < n; j++) s += braille(1 + Math.floor(rnd() * 6)) + pick(["⠀", "⠀", " ", "\n", ""]);
|
||
add("decode", a, s);
|
||
}
|
||
|
||
// 7. Decode da saída de encode (round trip): gerado depois de rodar o Python (ver abaixo).
|
||
const dir = mkdtempSync(join(tmpdir(), "paridade-"));
|
||
function runPython(list) {
|
||
const inF = join(dir, "in.json"); const outF = join(dir, "out.json");
|
||
writeFileSync(inF, JSON.stringify(list));
|
||
const r = spawnSync(PYTHON, [join(here, "paridade-tradutor.py"), inF, outF], { encoding: "utf8", maxBuffer: 1 << 28 });
|
||
if (r.status !== 0) { console.error(r.stderr || r.stdout); process.exit(2); }
|
||
return JSON.parse(readFileSync(outF, "utf8"));
|
||
}
|
||
async function runJs(list) {
|
||
const out = [];
|
||
for (const c of list) {
|
||
try {
|
||
out.push(c.op === "encode" ? await encodeText(c.input, c.alphabet) : decodeText(c.input, c.alphabet));
|
||
} catch (e) { out.push({ error: true }); }
|
||
}
|
||
return out;
|
||
}
|
||
|
||
try {
|
||
const pyEnc = runPython(cases);
|
||
// Round trip: decodifica o braille produzido pelo Python (curados + aleatórios, não o varrimento BMP/Han).
|
||
const roundStart = cases.length;
|
||
cases.forEach((c, i) => {
|
||
if (c.op === "encode" && i < 5000 && typeof pyEnc[i] === "string" && pyEnc[i] && ALPHABETS.slice(0, 3).includes(c.alphabet)) {
|
||
add("decode", c.alphabet, pyEnc[i]);
|
||
}
|
||
});
|
||
const py = runPython(cases);
|
||
const js = await runJs(cases);
|
||
|
||
let diffs = 0;
|
||
const groups = {};
|
||
cases.forEach((c, i) => {
|
||
const g = i < roundStart ? c.op : "roundtrip-decode";
|
||
groups[g] ??= { total: 0, diff: 0 };
|
||
groups[g].total++;
|
||
if (JSON.stringify(py[i]) !== JSON.stringify(js[i])) {
|
||
groups[g].diff++;
|
||
if (++diffs <= 15) console.error("DIFF", JSON.stringify({ op: c.op, alphabet: c.alphabet, input: c.input.slice(0, 80), py: py[i], js: js[i] }));
|
||
}
|
||
});
|
||
console.log(`Casos: ${cases.length} | divergentes: ${diffs}`);
|
||
console.log(JSON.stringify(groups));
|
||
const encoded = py.filter((v, i) => cases[i].op === "encode" && typeof v === "string" && v).length;
|
||
console.log(`Encodes com saída não vazia: ${encoded}`);
|
||
process.exitCode = diffs ? 1 : 0;
|
||
} finally {
|
||
rmSync(dir, { recursive: true, force: true });
|
||
}
|