Compare commits
1
Commits
v1.3.3
...
07aaf8e1a7
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
07aaf8e1a7 |
No files matched your search
@@ -13,6 +13,30 @@ Everything notable in InBraille is recorded here. The format follows
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [1.4.0] - 2026-11-15
|
||||
|
||||
### Added
|
||||
|
||||
- New website around the converter: hero with a tactile Braille plate, "How it works", 3D printing
|
||||
specs and tips, privacy, the peer-reviewed paper (IDEIA @ CSBC 2025, DOI
|
||||
10.5753/ideia.2025.9057) with copyable BibTeX and ABNT citations, credits and FAQ.
|
||||
- Light/dark theme (follows the system, toggle persisted), mobile navigation menu, keyboard
|
||||
shortcuts (Ctrl/Cmd+Enter converts; arrow keys move between tabs; Esc closes menus), toasts and
|
||||
screen-reader announcements for conversion and STL generation.
|
||||
- Text↔Braille translation now runs in the browser (`public/modules/translator.js`, a port of
|
||||
`src/translation` and `src/domain`, Chinese pinyin data loaded on demand). A parity script
|
||||
(`scripts/paridade-tradutor.mjs`) checks it against the Python translator: 337,176 cases, 0
|
||||
differences.
|
||||
|
||||
### Changed
|
||||
|
||||
- Interface rewritten from scratch: Tailwind CDN and axios removed, own design system
|
||||
(Atkinson Hyperlegible, embossed-dot motif), WCAG 2.2 AA focus, contrast, targets, reduced
|
||||
motion and forced colors. All rewritten copy in Portuguese, English and Chinese, plus new
|
||||
title, description, Open Graph and JSON-LD (including the `ScholarlyArticle`).
|
||||
- Nothing the user types leaves the browser: conversion, STL generation and preview are local.
|
||||
The `/api/*` routes stay available for existing integrations.
|
||||
|
||||
## [1.3.3] - 2026-11-02
|
||||
|
||||
### Changed
|
||||
|
||||
@@ -33,6 +33,8 @@ In addition to being an accessible and easy-to-use technology, this project has
|
||||
|
||||
## Backend Architecture (`src/`)
|
||||
|
||||
> Since 1.4.0 the web interface translates and generates STL entirely in the browser (`public/modules/`); the Python API below remains for integrations.
|
||||
|
||||
The Python backend is organized into domain-driven subdirectories under `src/`, utilizing **FastAPI** for web routing and **VTK (Visualization Toolkit)** for 3D modeling:
|
||||
|
||||
### 1. Domain Model (`src/domain/`)
|
||||
|
||||
+455
-436
File diff suppressed because it is too large.
Load diff
+211
-3
@@ -1,7 +1,9 @@
|
||||
import { state } from './modules/state.js';
|
||||
import { setLanguage } from './modules/i18n.js';
|
||||
import { initConverterDOM, switchConversionMode, updateCharCount, copyOutput, saveOutput, convert, clearInput } from './modules/converter.js';
|
||||
import { initStlDOM, updateParameters, applyPointsOnlyState, updateInputs, generateSTL, downloadSTL, toggleAdvancedOptions, triggerRealtimePreview } from './modules/stl.js';
|
||||
import { initConverterDOM, switchConversionMode, updateCharCount, updateActionStates, copyOutput, saveOutput, convert, clearInput } from './modules/converter.js';
|
||||
import { announce } from './modules/ui.js';
|
||||
import { getTranslation } from './modules/i18n.js';
|
||||
import { initStlDOM, updateParameters, applyPointsOnlyState, updateInputs, generateSTL, downloadSTL, toggleAdvancedOptions, triggerRealtimePreview, openAdvancedOptionsOnDesktop } from './modules/stl.js';
|
||||
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
// Gather all DOM elements
|
||||
@@ -47,6 +49,8 @@ document.addEventListener('DOMContentLoaded', function() {
|
||||
if (elements.input_points_only) elements.input_points_only.checked = state.points_only;
|
||||
if (elements.output_plate_width) elements.output_plate_width.innerHTML = state.plate_width.toFixed(1);
|
||||
applyPointsOnlyState();
|
||||
openAdvancedOptionsOnDesktop();
|
||||
updateActionStates();
|
||||
|
||||
// Event listeners registration
|
||||
if (elements.text_to_braille_tab) {
|
||||
@@ -73,6 +77,7 @@ document.addEventListener('DOMContentLoaded', function() {
|
||||
}
|
||||
if (elements.output_textbox) {
|
||||
elements.output_textbox.addEventListener("input", () => {
|
||||
updateActionStates();
|
||||
triggerRealtimePreview(60);
|
||||
});
|
||||
}
|
||||
@@ -116,6 +121,7 @@ document.addEventListener('DOMContentLoaded', function() {
|
||||
elements.input_symbols_per_line.addEventListener("input", updateParameters);
|
||||
elements.input_symbols_per_line.addEventListener("change", () => {
|
||||
if (elements.output_textbox) elements.output_textbox.value = "";
|
||||
updateActionStates();
|
||||
});
|
||||
}
|
||||
if (elements.select_text_alignment) {
|
||||
@@ -138,6 +144,7 @@ document.addEventListener('DOMContentLoaded', function() {
|
||||
elements.input_symbols_per_line.addEventListener("blur", () => {
|
||||
updateInputs();
|
||||
if (elements.output_textbox) elements.output_textbox.value = "";
|
||||
updateActionStates();
|
||||
});
|
||||
}
|
||||
if (elements.select_text_alignment) elements.select_text_alignment.addEventListener("blur", updateInputs);
|
||||
@@ -158,6 +165,7 @@ document.addEventListener('DOMContentLoaded', function() {
|
||||
const selectedLang = e.currentTarget.getAttribute("data-lang");
|
||||
|
||||
changeLanguage(selectedLang, () => {
|
||||
syncThemeUI();
|
||||
let newPath = "/";
|
||||
if (selectedLang === "en") newPath = "/en";
|
||||
else if (selectedLang === "zh") newPath = "/zh";
|
||||
@@ -178,6 +186,206 @@ document.addEventListener('DOMContentLoaded', function() {
|
||||
radio.addEventListener("change", () => switchConversionMode());
|
||||
});
|
||||
|
||||
|
||||
// ---------- Roving-tabindex tablists (APG) ----------
|
||||
function setupTablist(tabs, onActivate) {
|
||||
tabs = tabs.filter(Boolean);
|
||||
if (tabs.length < 2) return;
|
||||
tabs.forEach((tab, i) => {
|
||||
tab.addEventListener("keydown", (e) => {
|
||||
let next = null;
|
||||
if (e.key === "ArrowRight" || e.key === "ArrowDown") next = (i + 1) % tabs.length;
|
||||
else if (e.key === "ArrowLeft" || e.key === "ArrowUp") next = (i - 1 + tabs.length) % tabs.length;
|
||||
else if (e.key === "Home") next = 0;
|
||||
else if (e.key === "End") next = tabs.length - 1;
|
||||
if (next === null) return;
|
||||
e.preventDefault();
|
||||
tabs[next].focus();
|
||||
onActivate(tabs[next]);
|
||||
});
|
||||
});
|
||||
}
|
||||
setupTablist([elements.text_to_braille_tab, elements.braille_to_text_tab], (tab) => tab.click());
|
||||
|
||||
// Citation tabs (BibTeX / ABNT)
|
||||
const citeTabs = [document.getElementById("cite_tab_bibtex"), document.getElementById("cite_tab_abnt")];
|
||||
function selectCiteTab(tab) {
|
||||
citeTabs.forEach(t => {
|
||||
if (!t) return;
|
||||
const on = t === tab;
|
||||
t.setAttribute("aria-selected", String(on));
|
||||
t.setAttribute("tabindex", on ? "0" : "-1");
|
||||
t.classList.toggle("tab-active", on);
|
||||
const panel = document.getElementById(t.getAttribute("aria-controls"));
|
||||
if (panel) panel.classList.toggle("hidden", !on);
|
||||
});
|
||||
}
|
||||
citeTabs.forEach(t => t && t.addEventListener("click", () => selectCiteTab(t)));
|
||||
setupTablist(citeTabs, selectCiteTab);
|
||||
|
||||
// ---------- Keyboard shortcuts ----------
|
||||
if (elements.input_textbox) {
|
||||
elements.input_textbox.addEventListener("keydown", (e) => {
|
||||
if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) {
|
||||
e.preventDefault();
|
||||
convert();
|
||||
}
|
||||
});
|
||||
}
|
||||
const langDropdown = document.getElementById("lang_dropdown");
|
||||
document.addEventListener("keydown", (e) => {
|
||||
if (e.key !== "Escape") return;
|
||||
if (langDropdown && langDropdown.hasAttribute("open")) {
|
||||
langDropdown.removeAttribute("open");
|
||||
const summary = langDropdown.querySelector("summary");
|
||||
if (summary) summary.focus();
|
||||
}
|
||||
closeNav(true);
|
||||
});
|
||||
document.addEventListener("click", (e) => {
|
||||
if (langDropdown && langDropdown.hasAttribute("open") && !langDropdown.contains(e.target)) {
|
||||
langDropdown.removeAttribute("open");
|
||||
}
|
||||
});
|
||||
|
||||
// ---------- Theme ----------
|
||||
const themeToggle = document.getElementById("theme_toggle");
|
||||
const prefersDark = window.matchMedia ? window.matchMedia("(prefers-color-scheme: dark)") : null;
|
||||
function isDarkEffective() {
|
||||
const t = document.documentElement.dataset.theme;
|
||||
if (t === "dark") return true;
|
||||
if (t === "light") return false;
|
||||
return !!(prefersDark && prefersDark.matches);
|
||||
}
|
||||
function syncThemeUI() {
|
||||
const dark = isDarkEffective();
|
||||
if (typeof window.setPreviewTheme === "function") window.setPreviewTheme(dark);
|
||||
if (!themeToggle) return;
|
||||
themeToggle.setAttribute("aria-pressed", String(dark));
|
||||
const icon = themeToggle.querySelector("i");
|
||||
if (icon) icon.className = dark ? "fas fa-sun" : "fas fa-moon";
|
||||
const label = getTranslation(dark ? "theme_light" : "theme_dark");
|
||||
if (label) themeToggle.setAttribute("title", label);
|
||||
}
|
||||
if (themeToggle) {
|
||||
themeToggle.addEventListener("click", () => {
|
||||
const next = isDarkEffective() ? "light" : "dark";
|
||||
document.documentElement.dataset.theme = next;
|
||||
try { localStorage.setItem("inbraille-theme", next); } catch (e) { /* ignore */ }
|
||||
syncThemeUI();
|
||||
});
|
||||
}
|
||||
if (prefersDark && prefersDark.addEventListener) prefersDark.addEventListener("change", syncThemeUI);
|
||||
syncThemeUI();
|
||||
// preview.js is a module and may load after this one
|
||||
window.addEventListener("load", syncThemeUI);
|
||||
|
||||
// ---------- Mobile nav ----------
|
||||
const navToggle = document.getElementById("nav_toggle");
|
||||
const siteNav = document.getElementById("site_nav");
|
||||
const siteHeader = document.querySelector(".site-header") || document.querySelector("header");
|
||||
function closeNav(returnFocus) {
|
||||
if (!navToggle || navToggle.getAttribute("aria-expanded") !== "true") return;
|
||||
navToggle.setAttribute("aria-expanded", "false");
|
||||
if (siteHeader) siteHeader.classList.remove("nav-open");
|
||||
if (returnFocus) navToggle.focus();
|
||||
}
|
||||
if (navToggle) {
|
||||
navToggle.addEventListener("click", () => {
|
||||
const open = navToggle.getAttribute("aria-expanded") !== "true";
|
||||
navToggle.setAttribute("aria-expanded", String(open));
|
||||
if (siteHeader) siteHeader.classList.toggle("nav-open", open);
|
||||
});
|
||||
}
|
||||
if (siteNav) {
|
||||
siteNav.querySelectorAll("a").forEach(a => a.addEventListener("click", () => closeNav(false)));
|
||||
}
|
||||
|
||||
// ---------- Citation copy ----------
|
||||
function setupCopy(buttonId, blockId) {
|
||||
const btn = document.getElementById(buttonId);
|
||||
const block = document.getElementById(blockId);
|
||||
if (!btn || !block) return;
|
||||
btn.addEventListener("click", async () => {
|
||||
const text = block.textContent.trim();
|
||||
let ok = false;
|
||||
try {
|
||||
if (navigator.clipboard) { await navigator.clipboard.writeText(text); ok = true; }
|
||||
} catch (e) { /* fall through */ }
|
||||
if (!ok) {
|
||||
try {
|
||||
const ta = document.createElement("textarea");
|
||||
ta.value = text;
|
||||
ta.setAttribute("readonly", "");
|
||||
ta.style.position = "fixed";
|
||||
ta.style.opacity = "0";
|
||||
document.body.appendChild(ta);
|
||||
ta.select();
|
||||
ok = document.execCommand("copy");
|
||||
document.body.removeChild(ta);
|
||||
} catch (e) { ok = false; }
|
||||
}
|
||||
if (!ok) return;
|
||||
const label = btn.querySelector("[data-i18n]") || btn;
|
||||
const original = label.textContent;
|
||||
const copied = getTranslation("paper_copied") || "Copied";
|
||||
label.textContent = copied;
|
||||
announce(copied);
|
||||
setTimeout(() => { label.textContent = getTranslation(label.getAttribute("data-i18n")) || original; }, 2000);
|
||||
});
|
||||
}
|
||||
setupCopy("copy_bibtex", "bibtex_block");
|
||||
setupCopy("copy_abnt", "abnt_block");
|
||||
|
||||
// ---------- Reveal on scroll + active nav link ----------
|
||||
const reduceMotion = window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
|
||||
const revealEls = document.querySelectorAll(".reveal");
|
||||
if (revealEls.length) {
|
||||
if (reduceMotion || !("IntersectionObserver" in window)) {
|
||||
revealEls.forEach(el => el.classList.add("is-visible"));
|
||||
} else {
|
||||
const showAll = () => revealEls.forEach(el => el.classList.add("is-visible"));
|
||||
const io = new IntersectionObserver((entries) => {
|
||||
entries.forEach(entry => {
|
||||
if (entry.isIntersecting) {
|
||||
entry.target.classList.add("is-visible");
|
||||
io.unobserve(entry.target);
|
||||
}
|
||||
});
|
||||
}, { rootMargin: "0px 0px 15% 0px", threshold: 0 });
|
||||
revealEls.forEach(el => io.observe(el));
|
||||
// Rede de segurança: nunca deixar conteúdo escondido
|
||||
setTimeout(showAll, 1500);
|
||||
window.addEventListener("beforeprint", showAll);
|
||||
window.addEventListener("hashchange", showAll);
|
||||
}
|
||||
}
|
||||
if (siteNav && "IntersectionObserver" in window) {
|
||||
const links = Array.from(siteNav.querySelectorAll('a[href^="#"]'));
|
||||
const map = new Map();
|
||||
links.forEach(a => {
|
||||
const sec = document.getElementById(a.getAttribute("href").slice(1));
|
||||
if (sec) map.set(sec, a);
|
||||
});
|
||||
const navIo = new IntersectionObserver((entries) => {
|
||||
entries.forEach(entry => {
|
||||
if (!entry.isIntersecting) return;
|
||||
links.forEach(a => a.removeAttribute("aria-current"));
|
||||
const a = map.get(entry.target);
|
||||
if (a) a.setAttribute("aria-current", "true");
|
||||
});
|
||||
}, { rootMargin: "-35% 0px -60% 0px" });
|
||||
map.forEach((_, sec) => navIo.observe(sec));
|
||||
}
|
||||
|
||||
// Skip link / CTA to the converter: move focus to it
|
||||
document.querySelectorAll('a[href="#conversor"]').forEach(a => {
|
||||
a.addEventListener("click", () => {
|
||||
const target = document.getElementById("conversor");
|
||||
if (target) setTimeout(() => target.focus({ preventScroll: true }), 0);
|
||||
});
|
||||
});
|
||||
|
||||
// Determine and set initial language and default alphabet
|
||||
const path = window.location.pathname;
|
||||
let initialLang = "pt-BR";
|
||||
@@ -193,5 +401,5 @@ document.addEventListener('DOMContentLoaded', function() {
|
||||
const radio = document.getElementById("brazilian");
|
||||
if (radio) radio.checked = true;
|
||||
}
|
||||
changeLanguage(initialLang);
|
||||
changeLanguage(initialLang, syncThemeUI);
|
||||
});
|
||||
+162
-82
@@ -1,84 +1,164 @@
|
||||
export default {
|
||||
page_title: "InBraille - Text to Braille Converter & 3D STL Generator",
|
||||
meta_description: "Free Brazilian assistive technology tool to convert text to Braille and export 3D STL models for tactile 3D printing and accessibility.",
|
||||
hero_title: "Transform text into Braille easily",
|
||||
hero_description: "InBraille is a Brazilian tool that converts text to Braille and exports in ASCII and STL format for 3D printing, promoting accessibility and inclusion.",
|
||||
try_now: "Try it now",
|
||||
converter_title: "Converter",
|
||||
tab_text_to_braille: "Text → Braille",
|
||||
tab_braille_to_text: "Braille → Text",
|
||||
alphabet_label: "Braille Alphabet",
|
||||
alphabet_brazilian: "Brazilian",
|
||||
alphabet_north_american: "North American",
|
||||
alphabet_chinese: "Chinese (Mandarin)",
|
||||
warning_brazilian: "In the Brazilian alphabet, this conversion has problems with some characters. For example, the character \"&\" has the same braille symbol as the character \"ç\".",
|
||||
clear_button: "Clear",
|
||||
copy_button: "Copy",
|
||||
save_button: "Save",
|
||||
convert_button: "Convert",
|
||||
export_3d_title: "Export to 3D Printing",
|
||||
stl_alert_text: "Attention: The export to STL uses only the content in Braille. The original text, or converted text, is not used to generate the 3D model. Make sure to convert your text to Braille before exporting.",
|
||||
compass_alert_title: "Orientation indicator:",
|
||||
compass_alert_text: "so you don't assemble the piece upside down, the model includes a reference mark. With a plate, there is a larger dot in the bottom-left corner. In \"dots only\" mode, there is a small bar at the bottom. Keep this mark at the bottom/left when reading or gluing.",
|
||||
stl_button: "Generate & Preview STL",
|
||||
stl_preview_title: "3D Preview",
|
||||
download_stl_button: "Download STL",
|
||||
preview_instructions: "Drag to rotate, scroll to zoom.",
|
||||
advanced_options_title: "Advanced Options",
|
||||
points_only_title: "Dots Only (no plate)",
|
||||
points_only_desc: "Generates only the dot caps (0.65 mm), without the base plate, plus a small orientation bar at the bottom. Ideal for gluing the dots onto existing STLs. When enabled, the plate options are disabled.",
|
||||
separate_plates_title: "Separate Plates",
|
||||
separate_plates_desc: "Each line on a separate plate",
|
||||
rounded_edges_title: "Rounded Edges",
|
||||
rounded_edges_desc: "Rounded corners on the plates",
|
||||
text_alignment_title: "Text Alignment",
|
||||
align_center: "Center",
|
||||
align_left: "Left",
|
||||
align_right: "Right",
|
||||
symbols_per_line_title: "Symbols per Line",
|
||||
symbols_per_line_desc_prefix: "Value between 8 and 50 (plate width: ",
|
||||
symbols_per_line_desc_suffix: " mm)",
|
||||
plate_thickness_title: "Plate Thickness (mm)",
|
||||
plate_thickness_desc: "Value between 2 and 100",
|
||||
point_resolution_title: "Point Resolution",
|
||||
point_resolution_desc: "Value between 15 and 50",
|
||||
about_title: "About InBraille",
|
||||
about_p1: "InBraille is an innovative Brazilian tool that converts texts to Braille and exports them in both ASCII format and STL plates for 3D printing.",
|
||||
about_p2: "With this solution, it is possible to expand accessibility and inclusion, allowing anyone to create tactile materials for people with visual impairments.",
|
||||
about_p3: "In addition to being an accessible and easy-to-use technology, this project has a significant social impact, enabling the production of texts, labels, informational plates, and educational materials in Braille in an accessible and personalized way.",
|
||||
about_p4: "Whether for educational, professional, or everyday purposes, this tool aims to make information truly universal. The goal is to democratize access to Braille through maker culture and 3D printing, providing autonomy and independence for those in need.",
|
||||
neurodiversity_title: "Neurodiversity in Technology",
|
||||
neurodiversity_p1: "This tool was developed by Lucas Guerra, a autistic student and developer who transformed his unique perspective into inclusive technological solutions. Autism brought a different approach to the creation of this project, with intense focus on details and patterns that resulted in a more accessible and intuitive tool.",
|
||||
neurodiversity_p2: "This solution is the result of the 3D Technology and Inclusive Laboratory of the Computer Department at the Federal Rural University of Pernambuco (UFRPE), which promotes inclusion and accessibility through technology. The laboratory is a research and development space that seeks to create innovative solutions for people with disabilities, using 3D printing and other assistive technologies.",
|
||||
learn_more_title: "Learn More",
|
||||
learn_more_p1: "Learn more about this tool on the page of Ciência Embarcada",
|
||||
footer_text: "Tool for converting text to Braille",
|
||||
developed_by: "Developed by",
|
||||
|
||||
// Converter specifics
|
||||
input_label_text_to_braille: "Type your text",
|
||||
input_placeholder_text_to_braille: "Type the text you want to convert to Braille...",
|
||||
output_label_text_to_braille: "Result in Braille",
|
||||
output_placeholder_text_to_braille: "The result in Braille will appear here...",
|
||||
input_label_braille_to_text: "Type in Braille",
|
||||
input_placeholder_braille_to_text: "Type the text in Braille you want to convert...",
|
||||
output_label_braille_to_text: "Result in Text",
|
||||
output_placeholder_braille_to_text: "The result in text will appear here...",
|
||||
|
||||
// Alert and helper text translations
|
||||
console_copy_success: "Text copied to clipboard",
|
||||
console_copy_error: "Error copying text: ",
|
||||
copy_button_feedback: "Copied!",
|
||||
confirm_line_exceeds: "One of the lines exceeds the symbol limit per line.\nDo you want the program to try to adjust it automatically?",
|
||||
alert_word_exceeds_prefix: "One of the words exceeds the symbol limit per line.\nIn the advanced options, adjust the number of symbols per line to at least",
|
||||
alert_auto_adjust_success: "The program was able to automatically adjust the line.\n",
|
||||
alert_manual_correct_prefix: "Manually correct or adjust the number of symbols per line to at least",
|
||||
alert_general_error: "Try Again",
|
||||
toast_enter_braille: "Enter the Braille you want to print.",
|
||||
toast_enter_text: "Enter some text to generate the plate.",
|
||||
toast_converting: "Automatically converting to Braille...",
|
||||
generating_loader: "Generating...",
|
||||
stl_button_default: "Generate & Preview STL",
|
||||
alert_stl_error: "Error generating STL file. Please try again.",
|
||||
chinese_input_tip: "You can enter pinyin with tone numbers (like ni3 hao3) or Chinese characters (like 你好). The system will automatically recognize and convert. Use spaces to separate words."
|
||||
"page_title": "InBraille: text to Braille and 3D-printable tactile plates",
|
||||
"meta_description": "Convert text to Braille (Brazilian, North American or Chinese) and generate STL files of tactile plates for 3D printing. Free, open source and entirely in your browser.",
|
||||
"hero_title": "Write it. Touch it. Read it.",
|
||||
"hero_description": "InBraille is a Brazilian tool that converts text to Braille and exports in ASCII and STL format for 3D printing, promoting accessibility and inclusion.",
|
||||
"try_now": "Try it now",
|
||||
"converter_title": "Converter",
|
||||
"tab_text_to_braille": "Text → Braille",
|
||||
"tab_braille_to_text": "Braille → Text",
|
||||
"alphabet_label": "Braille Alphabet",
|
||||
"alphabet_brazilian": "Brazilian",
|
||||
"alphabet_north_american": "North American",
|
||||
"alphabet_chinese": "Chinese (Mandarin)",
|
||||
"warning_brazilian": "In the Brazilian alphabet, this conversion has problems with some characters. For example, the character \"&\" has the same braille symbol as the character \"ç\".",
|
||||
"clear_button": "Clear",
|
||||
"copy_button": "Copy",
|
||||
"save_button": "Save",
|
||||
"convert_button": "Convert",
|
||||
"export_3d_title": "Export to 3D Printing",
|
||||
"stl_alert_text": "STL export uses only the Braille content. The original text is not used to build the 3D model, so convert your text to Braille before exporting.",
|
||||
"compass_alert_title": "Orientation indicator:",
|
||||
"compass_alert_text": "so you don't assemble the piece upside down, the model includes a reference mark. With a plate, there is a larger dot in the bottom-left corner. In \"dots only\" mode, there is a small bar at the bottom. Keep this mark at the bottom/left when reading or gluing.",
|
||||
"stl_button": "Generate & Preview STL",
|
||||
"stl_preview_title": "3D Preview",
|
||||
"download_stl_button": "Download STL",
|
||||
"preview_instructions": "Drag to rotate, scroll to zoom.",
|
||||
"advanced_options_title": "Advanced Options",
|
||||
"points_only_title": "Dots Only (no plate)",
|
||||
"points_only_desc": "Generates only the dot caps (0.65 mm), without the base plate, plus a small orientation bar at the bottom. Ideal for gluing the dots onto existing STLs. When enabled, the plate options are disabled.",
|
||||
"separate_plates_title": "Separate Plates",
|
||||
"separate_plates_desc": "Each line on a separate plate",
|
||||
"rounded_edges_title": "Rounded Edges",
|
||||
"rounded_edges_desc": "Rounded corners on the plates",
|
||||
"text_alignment_title": "Text Alignment",
|
||||
"align_center": "Center",
|
||||
"align_left": "Left",
|
||||
"align_right": "Right",
|
||||
"symbols_per_line_title": "Symbols per Line",
|
||||
"symbols_per_line_desc_prefix": "Value between 8 and 50 (plate width: ",
|
||||
"symbols_per_line_desc_suffix": " mm)",
|
||||
"plate_thickness_title": "Plate Thickness (mm)",
|
||||
"plate_thickness_desc": "Value between 2 and 100",
|
||||
"point_resolution_title": "Point Resolution",
|
||||
"point_resolution_desc": "Value between 15 and 50",
|
||||
"about_title": "Who makes InBraille",
|
||||
"about_p1": "InBraille was born at the 3D and Inclusive Technology Lab of UFRPE's Computing Department, in Pernambuco, Brazil, so schools, families and transcribers can produce Braille material without expensive equipment.",
|
||||
"about_p2": "With this solution, it is possible to expand accessibility and inclusion, allowing anyone to create tactile materials for people with visual impairments.",
|
||||
"about_p3": "In addition to being an accessible and easy-to-use technology, this project has a significant social impact, enabling the production of texts, labels, informational plates, and educational materials in Braille in an accessible and personalized way.",
|
||||
"about_p4": "Whether for educational, professional, or everyday purposes, this tool aims to make information truly universal. The goal is to democratize access to Braille through maker culture and 3D printing, providing autonomy and independence for those in need.",
|
||||
"neurodiversity_title": "Neurodiversity in Technology",
|
||||
"neurodiversity_p1": "This tool was developed by Lucas Guerra, an autistic student and developer who transformed his unique perspective into inclusive technological solutions. Autism brought a different approach to the creation of this project, with intense focus on details and patterns that resulted in a more accessible and intuitive tool.",
|
||||
"neurodiversity_p2": "This solution is the result of the 3D Technology and Inclusive Laboratory of the Computer Department at the Federal Rural University of Pernambuco (UFRPE), which promotes inclusion and accessibility through technology. The laboratory is a research and development space that seeks to create innovative solutions for people with disabilities, using 3D printing and other assistive technologies.",
|
||||
"learn_more_title": "Learn More",
|
||||
"learn_more_p1": "Learn more about this tool on the page of Ciência Embarcada",
|
||||
"footer_text": "Tool for converting text to Braille",
|
||||
"developed_by": "Developed by",
|
||||
"input_label_text_to_braille": "Type your text",
|
||||
"input_placeholder_text_to_braille": "Type the text you want to convert to Braille...",
|
||||
"output_label_text_to_braille": "Result in Braille",
|
||||
"output_placeholder_text_to_braille": "The result in Braille will appear here...",
|
||||
"input_label_braille_to_text": "Type in Braille",
|
||||
"input_placeholder_braille_to_text": "Type the text in Braille you want to convert...",
|
||||
"output_label_braille_to_text": "Result in Text",
|
||||
"output_placeholder_braille_to_text": "The result in text will appear here...",
|
||||
"console_copy_success": "Text copied to clipboard",
|
||||
"console_copy_error": "Error copying text: ",
|
||||
"copy_button_feedback": "Copied!",
|
||||
"confirm_line_exceeds": "One of the lines exceeds the symbol limit per line.\nDo you want the program to try to adjust it automatically?",
|
||||
"alert_word_exceeds_prefix": "One of the words exceeds the symbol limit per line.\nIn the advanced options, adjust the number of symbols per line to at least",
|
||||
"alert_auto_adjust_success": "The program was able to automatically adjust the line.\n",
|
||||
"alert_manual_correct_prefix": "Manually correct or adjust the number of symbols per line to at least",
|
||||
"alert_general_error": "Try Again",
|
||||
"toast_enter_braille": "Enter the Braille you want to print.",
|
||||
"toast_enter_text": "Enter some text to generate the plate.",
|
||||
"toast_converting": "Automatically converting to Braille...",
|
||||
"generating_loader": "Generating...",
|
||||
"stl_button_default": "Generate & Preview STL",
|
||||
"alert_stl_error": "Error generating STL file. Please try again.",
|
||||
"chinese_input_tip": "You can enter pinyin with tone numbers (like ni3 hao3) or Chinese characters (like 你好). The system will automatically recognize and convert. Use spaces to separate words.",
|
||||
"skip_to_converter": "Skip to converter",
|
||||
"theme_toggle_label": "Toggle light/dark theme",
|
||||
"language_label": "Language",
|
||||
"mode_label": "Conversion direction",
|
||||
"kbd_hint": "Shortcut: Ctrl+Enter converts.",
|
||||
"before_print_title": "Before printing",
|
||||
"stl_alert_title": "Note:",
|
||||
"stl_empty_hint": "Convert some text, then press Generate STL to see the plate in 3D here.",
|
||||
"preview_canvas_label": "3D preview of the Braille plate",
|
||||
"opens_new_tab": "(opens in a new tab)",
|
||||
"char_count_one": "{n} character",
|
||||
"char_count_other": "{n} characters",
|
||||
"status_converted": "Braille ready: {n} cells.",
|
||||
"status_text_converted": "Text converted.",
|
||||
"status_stl_ready": "3D model ready. Download STL is available.",
|
||||
"toast_nothing_to_copy": "Nothing to copy yet. Convert some text first.",
|
||||
"toast_nothing_to_save": "Nothing to save yet. Convert some text first.",
|
||||
"toast_generate_first": "Generate the STL before downloading.",
|
||||
"toast_saved": "File saved.",
|
||||
"toast_close": "Dismiss notification",
|
||||
"field_range_error": "Use a value between {min} and {max}.",
|
||||
"theme_dark": "Dark theme",
|
||||
"theme_light": "Light theme",
|
||||
"og_title": "InBraille: write in Braille, print it in 3D",
|
||||
"hero_eyebrow": "Free assistive technology",
|
||||
"hero_lede": "InBraille turns any text into Braille and into a tactile plate ready for your 3D printer, in seconds and without leaving your browser.",
|
||||
"cta_convert": "Convert now",
|
||||
"cta_how": "How it works",
|
||||
"hero_fact_free": "Free and open source",
|
||||
"hero_fact_local": "Runs in your browser",
|
||||
"hero_fact_langs": "Portuguese, English and Chinese",
|
||||
"nav_converter": "Converter",
|
||||
"nav_how": "How it works",
|
||||
"nav_print": "3D printing",
|
||||
"nav_privacy": "Privacy",
|
||||
"nav_paper": "Paper",
|
||||
"nav_about": "About",
|
||||
"nav_menu": "Menu",
|
||||
"how_title": "From text to plate in three steps",
|
||||
"step1_title": "Write",
|
||||
"step1_text": "Type or paste your text and pick a Braille alphabet.",
|
||||
"step2_title": "Check the Braille",
|
||||
"step2_text": "Review the result, then copy or save it for other materials.",
|
||||
"step3_title": "Print the plate",
|
||||
"step3_text": "Generate the STL, rotate the 3D model and download it for your printer.",
|
||||
"print_title": "Made to be read by touch",
|
||||
"print_text": "Plates follow standard Braille dimensions so tactile reading feels right. An orientation mark shows which side goes up.",
|
||||
"spec_dot_height": "Dot height",
|
||||
"spec_cell_spacing": "Cell spacing",
|
||||
"spec_plate_width": "Default plate width",
|
||||
"spec_orientation": "Orientation mark",
|
||||
"spec_orientation_value": "Reference dot in the corner",
|
||||
"print_tips_title": "Printing tips",
|
||||
"print_tip1": "Print with the dots facing up.",
|
||||
"print_tip2": "Use 0.1–0.12 mm layers for crisp dots.",
|
||||
"print_tip3": "PLA or PETG work well.",
|
||||
"privacy_title": "Your text never leaves your device",
|
||||
"privacy_text": "Everything happens in your browser: the Braille conversion, the STL generation and the 3D preview. No text is sent to any server or stored.",
|
||||
"paper_eyebrow": "Published at CSBC 2025",
|
||||
"paper_section_title": "Peer-reviewed research",
|
||||
"paper_authors_label": "Authors",
|
||||
"paper_venue_label": "Venue",
|
||||
"paper_place_label": "Location",
|
||||
"paper_pages_label": "Pages",
|
||||
"paper_publisher_label": "Publisher",
|
||||
"paper_date_label": "Published",
|
||||
"paper_venue": "1st Workshop on Innovation, Development, Education and Inclusion with Maker Actions (IDEIA), at CSBC 2025",
|
||||
"paper_summary": "InBraille converts text to Braille and generates inclusive 3D plates following Brazilian and US standards. Validated prototypes showed accurate dimensions and good tactile readability.",
|
||||
"paper_read": "Read the paper",
|
||||
"paper_pdf": "Download PDF",
|
||||
"paper_copy": "Copy citation",
|
||||
"paper_copied": "Citation copied",
|
||||
"paper_bibtex_label": "BibTeX citation",
|
||||
"paper_abnt_label": "ABNT citation (Brazilian standard)",
|
||||
"paper_lang_note": "Paper written in Portuguese.",
|
||||
"credits_title": "Credits",
|
||||
"credits_text": "Created by Lucas Guerra, with Marcos Cardoso and Marcos Castro, at the 3D and Inclusive Technology Lab (DC/UFRPE). Maintained by Ciência Embarcada.",
|
||||
"source_code": "Source code",
|
||||
"maintained_by": "Maintained by Ciência Embarcada",
|
||||
"footer_tagline": "Braille for everyone, from text to 3D print.",
|
||||
"footer_site": "Site",
|
||||
"footer_project": "Project",
|
||||
"footer_rights": "© 2026 InBraille. Open source.",
|
||||
"faq_title": "Frequently asked questions"
|
||||
};
|
||||
+162
-82
@@ -1,84 +1,164 @@
|
||||
export default {
|
||||
page_title: "InBraille - Conversor de Texto para Braille e Impressão 3D STL",
|
||||
meta_description: "Ferramenta brasileira pública e gratuita de tecnologia assistiva para converter texto em Braille e gerar arquivos STL para impressão 3D de placas táteis inclusivas.",
|
||||
hero_title: "Transforme texto em Braille facilmente",
|
||||
hero_description: "O InBraille é uma ferramenta brasileira que converte textos para Braille e os exporta em formato ASCII e STL para impressão 3D, promovendo acessibilidade e inclusão.",
|
||||
try_now: "Experimente agora",
|
||||
converter_title: "Conversor",
|
||||
tab_text_to_braille: "Texto → Braille",
|
||||
tab_braille_to_text: "Braille → Texto",
|
||||
alphabet_label: "Alfabeto Braille",
|
||||
alphabet_brazilian: "Brasileiro",
|
||||
alphabet_north_american: "Norte Americano",
|
||||
alphabet_chinese: "Chinês (Mandarim)",
|
||||
warning_brazilian: "No alfabeto brasileiro, essa conversão tem problemas com alguns caracteres. Por exemplo, o caractere \"&\" tem o mesmo símbolo braille que o caractere \"ç\".",
|
||||
clear_button: "Limpar",
|
||||
copy_button: "Copiar",
|
||||
save_button: "Salvar",
|
||||
convert_button: "Converter",
|
||||
export_3d_title: "Exportar para Impressão 3D",
|
||||
stl_alert_text: "Atenção: A exportação para STL utiliza apenas o conteúdo em Braille. O texto original, ou convertido, não é usado para gerar o modelo 3D. Certifique-se de converter seu texto para Braille antes de exportar.",
|
||||
compass_alert_title: "Indicador de orientação:",
|
||||
compass_alert_text: "para você não montar a peça de cabeça para baixo, o modelo inclui uma marca de referência. Com placa, há um ponto maior no canto inferior esquerdo. No modo \"apenas os pontos\", há uma barrinha na parte de baixo. Mantenha essa marca embaixo/à esquerda ao ler ou colar.",
|
||||
stl_button: "Gerar e Visualizar STL",
|
||||
stl_preview_title: "Pré-visualização 3D",
|
||||
download_stl_button: "Baixar STL",
|
||||
preview_instructions: "Arraste para girar, role para dar zoom.",
|
||||
advanced_options_title: "Opções Avançadas",
|
||||
points_only_title: "Apenas os Pontos (sem placa)",
|
||||
points_only_desc: "Gera somente as calotas dos pontos (0,65 mm), sem a placa de base, mais uma barrinha de orientação embaixo. Ideal para colar os pontos em STLs já prontos. Ao ativar, as opções de placa são desativadas.",
|
||||
separate_plates_title: "Placas Separadas",
|
||||
separate_plates_desc: "Cada linha em uma placa separada",
|
||||
rounded_edges_title: "Bordas Arredondadas",
|
||||
rounded_edges_desc: "Cantos arredondados nas placas",
|
||||
text_alignment_title: "Alinhamento do Texto",
|
||||
align_center: "Centro",
|
||||
align_left: "Esquerda",
|
||||
align_right: "Direita",
|
||||
symbols_per_line_title: "Símbolos por Linha",
|
||||
symbols_per_line_desc_prefix: "Valor entre 8 e 50 (largura da placa: ",
|
||||
symbols_per_line_desc_suffix: " mm)",
|
||||
plate_thickness_title: "Espessura da Placa (mm)",
|
||||
plate_thickness_desc: "Valor entre 2 e 100",
|
||||
point_resolution_title: "Resolução dos Pontos",
|
||||
point_resolution_desc: "Valor entre 15 e 50",
|
||||
about_title: "Sobre o InBraille",
|
||||
about_p1: "O InBraille é uma ferramenta inovadora, brasileira e pernambucana, que converte textos para Braille e os exporta tanto em formato ASCII quanto em placas STL para impressão 3D.",
|
||||
about_p2: "Com essa solução, é possível ampliar a acessibilidade e a inclusão, permitindo que qualquer pessoa possa criar materiais táteis para pessoas com deficiência visual.",
|
||||
about_p3: "Além de ser uma tecnologia acessível e de fácil uso, esse projeto tem um impacto social significativo, possibilitando a produção de textos, etiquetas, placas informativas e materiais educacionais em Braille de forma acessível e personalizada.",
|
||||
about_p4: "Seja para fins educacionais, profissionais ou do dia a dia, essa ferramenta visa tornar a informação verdadeiramente universal. O objetivo é democratizar o acesso ao Braille por meio da cultura maker e da impressão 3D, proporcionando autonomia e independência para quem precisa.",
|
||||
neurodiversity_title: "Neurodiversidade na Tecnologia",
|
||||
neurodiversity_p1: "Esta ferramenta foi desenvolvida por Lucas Guerra, um estudante e desenvolvedor autista que transformou sua perspectiva única em soluções tecnológicas inclusivas. O autismo trouxe uma abordagem diferente para a criação deste projeto, com foco intenso em detalhes e padrões que resultaram em uma ferramenta mais acessível e intuitiva.",
|
||||
neurodiversity_p2: "Essa solução é fruto do Laboratório de Tecnologia 3D e Inclusiva do Departamento de Computação da Universidade Federal Rural de Pernambuco (UFRPE), que promove a inclusão e acessibilidade por meio da tecnologia. O laboratório é um espaço de pesquisa e desenvolvimento que busca criar soluções inovadoras para pessoas com deficiência, utilizando impressão 3D e outras tecnologias assistivas.",
|
||||
learn_more_title: "Saiba mais",
|
||||
learn_more_p1: "Veja mais sobre essa ferramenta na página dela no Ciência Embarcada",
|
||||
footer_text: "Ferramenta de conversão para Braille",
|
||||
developed_by: "Desenvolvido por",
|
||||
|
||||
// Converter specifics
|
||||
input_label_text_to_braille: "Digite seu texto",
|
||||
input_placeholder_text_to_braille: "Digite o texto que deseja converter para Braille...",
|
||||
output_label_text_to_braille: "Resultado em Braille",
|
||||
output_placeholder_text_to_braille: "O resultado em Braille aparecerá aqui...",
|
||||
input_label_braille_to_text: "Digite em Braille",
|
||||
input_placeholder_braille_to_text: "Digite o texto em Braille que deseja converter...",
|
||||
output_label_braille_to_text: "Resultado em Texto",
|
||||
output_placeholder_braille_to_text: "O resultado em texto aparecerá aqui...",
|
||||
|
||||
// Alert and helper text translations
|
||||
console_copy_success: "Texto copiado para a área de transferência",
|
||||
console_copy_error: "Erro ao copiar o texto: ",
|
||||
copy_button_feedback: "Copiado!",
|
||||
confirm_line_exceeds: "Uma das linhas ultrapassa o limite de símbolos por linha.\nVocê quer que o programa tente ajustar automaticamente?",
|
||||
alert_word_exceeds_prefix: "Uma das palavras ultrapassa o limite de símbolos por linha.\nNas opções avançadas, ajuste a quantidade de símbolos por linha para no mínimo",
|
||||
alert_auto_adjust_success: "O programa conseguiu ajustar automaticamente a linha.\n",
|
||||
alert_manual_correct_prefix: "Corrija manualmente ou, ajuste a quantidade de símbolos por linha para no mínimo",
|
||||
alert_general_error: "Tente Novamente",
|
||||
toast_enter_braille: "Digite o Braille que deseja imprimir.",
|
||||
toast_enter_text: "Digite um texto para gerar a placa.",
|
||||
toast_converting: "Convertendo automaticamente para Braille...",
|
||||
generating_loader: "Gerando...",
|
||||
stl_button_default: "Gerar e Visualizar STL",
|
||||
alert_stl_error: "Erro ao gerar o arquivo STL. Tente novamente.",
|
||||
chinese_input_tip: "Você pode digitar pinyin com números de tom (como ni3 hao3) ou caracteres chineses (como 你好). O sistema irá reconhecer e converter automaticamente. Use espaço para separar as palavras."
|
||||
"page_title": "InBraille: texto para Braille e placas táteis em 3D",
|
||||
"meta_description": "Converta texto em Braille (brasileiro, norte-americano ou chinês) e gere arquivos STL de placas táteis para impressão 3D. Gratuito, de código aberto e 100% no navegador.",
|
||||
"hero_title": "Escreva. Toque. Leia.",
|
||||
"hero_description": "O InBraille é uma ferramenta brasileira que converte textos para Braille e os exporta em formato ASCII e STL para impressão 3D, promovendo acessibilidade e inclusão.",
|
||||
"try_now": "Experimente agora",
|
||||
"converter_title": "Conversor",
|
||||
"tab_text_to_braille": "Texto → Braille",
|
||||
"tab_braille_to_text": "Braille → Texto",
|
||||
"alphabet_label": "Alfabeto Braille",
|
||||
"alphabet_brazilian": "Brasileiro",
|
||||
"alphabet_north_american": "Norte Americano",
|
||||
"alphabet_chinese": "Chinês (Mandarim)",
|
||||
"warning_brazilian": "No alfabeto brasileiro, essa conversão tem problemas com alguns caracteres. Por exemplo, o caractere \"&\" tem o mesmo símbolo braille que o caractere \"ç\".",
|
||||
"clear_button": "Limpar",
|
||||
"copy_button": "Copiar",
|
||||
"save_button": "Salvar",
|
||||
"convert_button": "Converter",
|
||||
"export_3d_title": "Exportar para Impressão 3D",
|
||||
"stl_alert_text": "A exportação para STL usa apenas o conteúdo em Braille. O texto original não é usado para gerar o modelo 3D, então converta seu texto para Braille antes de exportar.",
|
||||
"compass_alert_title": "Indicador de orientação:",
|
||||
"compass_alert_text": "para você não montar a peça de cabeça para baixo, o modelo inclui uma marca de referência. Com placa, há um ponto maior no canto inferior esquerdo. No modo \"apenas os pontos\", há uma barrinha na parte de baixo. Mantenha essa marca embaixo/à esquerda ao ler ou colar.",
|
||||
"stl_button": "Gerar e Visualizar STL",
|
||||
"stl_preview_title": "Pré-visualização 3D",
|
||||
"download_stl_button": "Baixar STL",
|
||||
"preview_instructions": "Arraste para girar, role para dar zoom.",
|
||||
"advanced_options_title": "Opções Avançadas",
|
||||
"points_only_title": "Apenas os Pontos (sem placa)",
|
||||
"points_only_desc": "Gera somente as calotas dos pontos (0,65 mm), sem a placa de base, mais uma barrinha de orientação embaixo. Ideal para colar os pontos em STLs já prontos. Ao ativar, as opções de placa são desativadas.",
|
||||
"separate_plates_title": "Placas Separadas",
|
||||
"separate_plates_desc": "Cada linha em uma placa separada",
|
||||
"rounded_edges_title": "Bordas Arredondadas",
|
||||
"rounded_edges_desc": "Cantos arredondados nas placas",
|
||||
"text_alignment_title": "Alinhamento do Texto",
|
||||
"align_center": "Centro",
|
||||
"align_left": "Esquerda",
|
||||
"align_right": "Direita",
|
||||
"symbols_per_line_title": "Símbolos por Linha",
|
||||
"symbols_per_line_desc_prefix": "Valor entre 8 e 50 (largura da placa: ",
|
||||
"symbols_per_line_desc_suffix": " mm)",
|
||||
"plate_thickness_title": "Espessura da Placa (mm)",
|
||||
"plate_thickness_desc": "Valor entre 2 e 100",
|
||||
"point_resolution_title": "Resolução dos Pontos",
|
||||
"point_resolution_desc": "Valor entre 15 e 50",
|
||||
"about_title": "Quem faz o InBraille",
|
||||
"about_p1": "O InBraille nasceu no Laboratório de Tecnologia 3D e Inclusiva do Departamento de Computação da UFRPE, em Pernambuco, para que escolas, famílias e transcritores produzam material em Braille sem equipamento caro.",
|
||||
"about_p2": "Com essa solução, é possível ampliar a acessibilidade e a inclusão, permitindo que qualquer pessoa possa criar materiais táteis para pessoas com deficiência visual.",
|
||||
"about_p3": "Além de ser uma tecnologia acessível e de fácil uso, esse projeto tem um impacto social significativo, possibilitando a produção de textos, etiquetas, placas informativas e materiais educacionais em Braille de forma acessível e personalizada.",
|
||||
"about_p4": "Seja para fins educacionais, profissionais ou do dia a dia, essa ferramenta visa tornar a informação verdadeiramente universal. O objetivo é democratizar o acesso ao Braille por meio da cultura maker e da impressão 3D, proporcionando autonomia e independência para quem precisa.",
|
||||
"neurodiversity_title": "Neurodiversidade na Tecnologia",
|
||||
"neurodiversity_p1": "Esta ferramenta foi desenvolvida por Lucas Guerra, um estudante e desenvolvedor autista que transformou sua perspectiva única em soluções tecnológicas inclusivas. O autismo trouxe uma abordagem diferente para a criação deste projeto, com foco intenso em detalhes e padrões que resultaram em uma ferramenta mais acessível e intuitiva.",
|
||||
"neurodiversity_p2": "Essa solução é fruto do Laboratório de Tecnologia 3D e Inclusiva do Departamento de Computação da Universidade Federal Rural de Pernambuco (UFRPE), que promove a inclusão e acessibilidade por meio da tecnologia. O laboratório é um espaço de pesquisa e desenvolvimento que busca criar soluções inovadoras para pessoas com deficiência, utilizando impressão 3D e outras tecnologias assistivas.",
|
||||
"learn_more_title": "Saiba mais",
|
||||
"learn_more_p1": "Veja mais sobre essa ferramenta na página dela no Ciência Embarcada",
|
||||
"footer_text": "Ferramenta de conversão para Braille",
|
||||
"developed_by": "Desenvolvido por",
|
||||
"input_label_text_to_braille": "Digite seu texto",
|
||||
"input_placeholder_text_to_braille": "Digite o texto que deseja converter para Braille...",
|
||||
"output_label_text_to_braille": "Resultado em Braille",
|
||||
"output_placeholder_text_to_braille": "O resultado em Braille aparecerá aqui...",
|
||||
"input_label_braille_to_text": "Digite em Braille",
|
||||
"input_placeholder_braille_to_text": "Digite o texto em Braille que deseja converter...",
|
||||
"output_label_braille_to_text": "Resultado em Texto",
|
||||
"output_placeholder_braille_to_text": "O resultado em texto aparecerá aqui...",
|
||||
"console_copy_success": "Texto copiado para a área de transferência",
|
||||
"console_copy_error": "Erro ao copiar o texto: ",
|
||||
"copy_button_feedback": "Copiado!",
|
||||
"confirm_line_exceeds": "Uma das linhas ultrapassa o limite de símbolos por linha.\nVocê quer que o programa tente ajustar automaticamente?",
|
||||
"alert_word_exceeds_prefix": "Uma das palavras ultrapassa o limite de símbolos por linha.\nNas opções avançadas, ajuste a quantidade de símbolos por linha para no mínimo",
|
||||
"alert_auto_adjust_success": "O programa conseguiu ajustar automaticamente a linha.\n",
|
||||
"alert_manual_correct_prefix": "Corrija manualmente ou, ajuste a quantidade de símbolos por linha para no mínimo",
|
||||
"alert_general_error": "Tente Novamente",
|
||||
"toast_enter_braille": "Digite o Braille que deseja imprimir.",
|
||||
"toast_enter_text": "Digite um texto para gerar a placa.",
|
||||
"toast_converting": "Convertendo automaticamente para Braille...",
|
||||
"generating_loader": "Gerando...",
|
||||
"stl_button_default": "Gerar e Visualizar STL",
|
||||
"alert_stl_error": "Erro ao gerar o arquivo STL. Tente novamente.",
|
||||
"chinese_input_tip": "Você pode digitar pinyin com números de tom (como ni3 hao3) ou caracteres chineses (como 你好). O sistema irá reconhecer e converter automaticamente. Use espaço para separar as palavras.",
|
||||
"skip_to_converter": "Pular para o conversor",
|
||||
"theme_toggle_label": "Alternar tema claro/escuro",
|
||||
"language_label": "Idioma",
|
||||
"mode_label": "Direção da conversão",
|
||||
"kbd_hint": "Atalho: Ctrl+Enter converte.",
|
||||
"before_print_title": "Antes de imprimir",
|
||||
"stl_alert_title": "Atenção:",
|
||||
"stl_empty_hint": "Converta um texto e toque em Gerar STL para ver a placa em 3D aqui.",
|
||||
"preview_canvas_label": "Pré-visualização 3D da placa Braille",
|
||||
"opens_new_tab": "(abre em nova aba)",
|
||||
"char_count_one": "{n} caractere",
|
||||
"char_count_other": "{n} caracteres",
|
||||
"status_converted": "Braille gerado: {n} celas.",
|
||||
"status_text_converted": "Texto convertido.",
|
||||
"status_stl_ready": "Modelo 3D pronto. Baixar STL disponível.",
|
||||
"toast_nothing_to_copy": "Nada para copiar ainda. Converta um texto primeiro.",
|
||||
"toast_nothing_to_save": "Nada para salvar ainda. Converta um texto primeiro.",
|
||||
"toast_generate_first": "Gere o STL antes de baixar.",
|
||||
"toast_saved": "Arquivo salvo.",
|
||||
"toast_close": "Fechar aviso",
|
||||
"field_range_error": "Use um valor entre {min} e {max}.",
|
||||
"theme_dark": "Tema escuro",
|
||||
"theme_light": "Tema claro",
|
||||
"og_title": "InBraille: escreva em Braille e imprima em 3D",
|
||||
"hero_eyebrow": "Tecnologia assistiva gratuita",
|
||||
"hero_lede": "O InBraille transforma qualquer texto em Braille e em uma placa tátil pronta para a impressora 3D, em segundos e sem sair do navegador.",
|
||||
"cta_convert": "Converter agora",
|
||||
"cta_how": "Como funciona",
|
||||
"hero_fact_free": "Gratuito e aberto",
|
||||
"hero_fact_local": "Roda no seu navegador",
|
||||
"hero_fact_langs": "Português, inglês e chinês",
|
||||
"nav_converter": "Conversor",
|
||||
"nav_how": "Como funciona",
|
||||
"nav_print": "Impressão 3D",
|
||||
"nav_privacy": "Privacidade",
|
||||
"nav_paper": "Artigo",
|
||||
"nav_about": "Sobre",
|
||||
"nav_menu": "Menu",
|
||||
"how_title": "Do texto à placa em três passos",
|
||||
"step1_title": "Escreva",
|
||||
"step1_text": "Digite ou cole o texto e escolha o alfabeto Braille.",
|
||||
"step2_title": "Confira o Braille",
|
||||
"step2_text": "Veja o resultado, copie ou salve para usar em outros materiais.",
|
||||
"step3_title": "Imprima a placa",
|
||||
"step3_text": "Gere o STL, gire o modelo em 3D e baixe para a sua impressora.",
|
||||
"print_title": "Feito para ser lido com os dedos",
|
||||
"print_text": "As placas seguem as medidas usuais do Braille para que a leitura tátil seja confortável. Uma marca de orientação mostra qual lado fica para cima.",
|
||||
"spec_dot_height": "Altura do ponto",
|
||||
"spec_cell_spacing": "Distância entre celas",
|
||||
"spec_plate_width": "Largura padrão da placa",
|
||||
"spec_orientation": "Marca de orientação",
|
||||
"spec_orientation_value": "Ponto de referência no canto",
|
||||
"print_tips_title": "Dicas de impressão",
|
||||
"print_tip1": "Imprima com a face dos pontos para cima.",
|
||||
"print_tip2": "Use camadas de 0,1 a 0,12 mm para pontos bem definidos.",
|
||||
"print_tip3": "PLA ou PETG funcionam bem.",
|
||||
"privacy_title": "Seu texto não sai do seu computador",
|
||||
"privacy_text": "Tudo acontece no seu navegador: a conversão para Braille, a geração do STL e a pré-visualização em 3D. Nenhum texto é enviado a servidores nem armazenado.",
|
||||
"paper_eyebrow": "Publicado no CSBC 2025",
|
||||
"paper_section_title": "Pesquisa revisada por pares",
|
||||
"paper_authors_label": "Autores",
|
||||
"paper_venue_label": "Evento",
|
||||
"paper_place_label": "Local",
|
||||
"paper_pages_label": "Páginas",
|
||||
"paper_publisher_label": "Editora",
|
||||
"paper_date_label": "Publicado em",
|
||||
"paper_venue": "I Workshop de Inovação, Desenvolvimento, Educação e Inclusão com Ações Maker (IDEIA), no CSBC 2025",
|
||||
"paper_summary": "O InBraille converte textos para Braille e gera placas 3D inclusivas, seguindo os padrões brasileiro e estadunidense. Protótipos validados demonstraram precisão nas medidas e legibilidade tátil.",
|
||||
"paper_read": "Ler o artigo",
|
||||
"paper_pdf": "Baixar PDF",
|
||||
"paper_copy": "Copiar citação",
|
||||
"paper_copied": "Citação copiada",
|
||||
"paper_bibtex_label": "Citação em BibTeX",
|
||||
"paper_abnt_label": "Citação em ABNT",
|
||||
"paper_lang_note": "",
|
||||
"credits_title": "Créditos",
|
||||
"credits_text": "Criado por Lucas Guerra, com Marcos Cardoso e Marcos Castro, no Laboratório de Tecnologia 3D e Inclusiva (DC/UFRPE). Mantido por Ciência Embarcada.",
|
||||
"source_code": "Código-fonte",
|
||||
"maintained_by": "Mantido por Ciência Embarcada",
|
||||
"footer_tagline": "Braille para todos, do texto à impressão 3D.",
|
||||
"footer_site": "Site",
|
||||
"footer_project": "Projeto",
|
||||
"footer_rights": "© 2026 InBraille. Código aberto.",
|
||||
"faq_title": "Perguntas frequentes"
|
||||
};
|
||||
+162
-82
@@ -1,84 +1,164 @@
|
||||
export default {
|
||||
page_title: "InBraille - 文本盲文转换器与3D STL模型生成器",
|
||||
meta_description: "免费公开的无障碍辅助技术工具:将文本(支持中文拼音、汉字等)转换为盲文,并导出用于3D打印的STL触觉模型文件。",
|
||||
hero_title: "轻松将中文转换为盲文",
|
||||
hero_description: "InBraille 可将中文(拼音或汉字)转换为盲文,并导出为 ASCII 和 STL 格式用于 3D 打印,促进无障碍与包容。中文盲文基于普通话拼音(声母 + 韵母 + 声调)。",
|
||||
try_now: "立即体验",
|
||||
converter_title: "转换器",
|
||||
tab_text_to_braille: "中文 → 盲文",
|
||||
tab_braille_to_text: "盲文 → 拼音",
|
||||
alphabet_label: "盲文标准",
|
||||
alphabet_brazilian: "巴西",
|
||||
alphabet_north_american: "北美",
|
||||
alphabet_chinese: "中文(普通话)",
|
||||
warning_brazilian: "在巴西盲文字母表中,此转换在某些字符上存在问题。例如,字符“&”与字符“ç”具有相同的盲文符号。",
|
||||
chinese_input_tip: "您可以输入带声调数字的拼音(如 ni3 hao3)或中文汉字(如 你好)。系统会自动识别并转换。词与词之间请用空格分隔。",
|
||||
clear_button: "清除",
|
||||
copy_button: "复制",
|
||||
save_button: "保存",
|
||||
convert_button: "转换",
|
||||
export_3d_title: "导出为 3D 打印",
|
||||
stl_alert_text: "注意:导出 STL 仅使用盲文内容。原始文字或转换后的文字不用于生成 3D 模型。导出前请先将文字转换为盲文。",
|
||||
compass_alert_title: "方向标记:",
|
||||
compass_alert_text: "为避免上下颠倒,模型包含参考标记。带底板时,左下角有一个较大的点;在\"仅点\"模式下,底部有一条小横杠。阅读或粘贴时请让该标记保持在下方/左侧。",
|
||||
stl_button: "生成并预览 STL",
|
||||
stl_preview_title: "3D 预览",
|
||||
download_stl_button: "下载 STL",
|
||||
preview_instructions: "拖动旋转,滚动缩放。",
|
||||
advanced_options_title: "高级选项",
|
||||
points_only_title: "仅点(无底板)",
|
||||
points_only_desc: "仅生成点的凸帽(0.65 毫米),不含底板,并在底部附加一条方向横杠。适合将点粘贴到已有的 STL 上。启用后,底板相关选项将被禁用。",
|
||||
separate_plates_title: "分离底板",
|
||||
separate_plates_desc: "每行一个独立底板",
|
||||
rounded_edges_title: "圆角",
|
||||
rounded_edges_desc: "底板圆角",
|
||||
text_alignment_title: "文字对齐",
|
||||
align_center: "居中",
|
||||
align_left: "左对齐",
|
||||
align_right: "右对齐",
|
||||
symbols_per_line_title: "每行符号数",
|
||||
symbols_per_line_desc_prefix: "8 到 50 之间(底板宽度:",
|
||||
symbols_per_line_desc_suffix: " 毫米)",
|
||||
plate_thickness_title: "底板厚度(毫米)",
|
||||
plate_thickness_desc: "2 到 100 之间",
|
||||
point_resolution_title: "点分辨率",
|
||||
point_resolution_desc: "15 到 50 之间",
|
||||
about_title: "关于 InBraille",
|
||||
about_p1: "InBraille 是一个来自巴西的创新工具,可将文字转换为盲文,并导出为 ASCII 格式和用于 3D 打印的 STL 底板。",
|
||||
about_p2: "借助该方案,可以扩展无障碍与包容,让任何人都能为视障人士制作触觉材料。",
|
||||
about_p3: "中文盲文基于普通话拼音的语音表示:每个音节由声母、韵母和声调组成。本工具依照官方中文盲文规则进行转写。",
|
||||
about_p4: "无论用于教育、专业还是日常场景,本工具都致力于让信息真正普及。目标是通过创客文化和 3D 打印普及盲文,为有需要的人提供自主与独立。",
|
||||
neurodiversity_title: "技术中的神经多样性",
|
||||
neurodiversity_p1: "本工具由 Lucas Guerra 开发。他是一名自闭症学生和开发者,将自己独特的视角转化为包容性的技术方案。自闭症为该项目带来了不同的思路,对细节和模式的高度专注造就了更易用、更直观的工具。",
|
||||
neurodiversity_p2: "该方案源自伯南布哥联邦农村大学(UFRPE)计算机系的 3D 与包容技术实验室,致力于通过技术促进包容与无障碍,利用 3D 打印及其他辅助技术为残障人士创造创新方案。",
|
||||
learn_more_title: "了解更多",
|
||||
learn_more_p1: "在 Ciência Embarcada 页面了解更多关于本工具的信息。",
|
||||
footer_text: "文字转盲文工具",
|
||||
developed_by: "开发者",
|
||||
|
||||
// Converter specifics
|
||||
input_label_text_to_braille: "输入文字",
|
||||
input_placeholder_text_to_braille: "输入拼音(如 ni3 hao3)或汉字(如 你好)...",
|
||||
output_label_text_to_braille: "盲文结果",
|
||||
output_placeholder_text_to_braille: "盲文结果将显示在此处...",
|
||||
input_label_braille_to_text: "输入盲文",
|
||||
input_placeholder_braille_to_text: "输入要转换的盲文...",
|
||||
output_label_braille_to_text: "拼音结果",
|
||||
output_placeholder_braille_to_text: "拼音结果将显示在此处...",
|
||||
|
||||
// Alert and helper text translations
|
||||
console_copy_success: "文本已复制到剪贴板",
|
||||
console_copy_error: "复制文本出错:",
|
||||
copy_button_feedback: "已复制!",
|
||||
confirm_line_exceeds: "其中一行超过了每行符号数限制。\n您想让程序尝试自动调整吗?",
|
||||
alert_word_exceeds_prefix: "其中一个单词/字数超过了每行符号数限制。\n请在高级选项中,将每行符号数调整为至少",
|
||||
alert_auto_adjust_success: "程序已成功自动调整该行。\n",
|
||||
alert_manual_correct_prefix: "请手动更正,或在高级选项中将每行符号数调整为至少",
|
||||
alert_general_error: "请重试",
|
||||
toast_enter_braille: "请输入要打印的盲文。",
|
||||
toast_enter_text: "请输入文字以生成底板。",
|
||||
toast_converting: "正在自动转换为盲文...",
|
||||
generating_loader: "生成中...",
|
||||
stl_button_default: "生成并预览 STL",
|
||||
alert_stl_error: "生成 STL 文件出错,请重试。"
|
||||
"page_title": "InBraille:文本转盲文,生成可 3D 打印的触觉板",
|
||||
"meta_description": "将文本转换为盲文(巴西、北美或中文盲文),并生成可 3D 打印的触觉板 STL 文件。免费、开源,完全在浏览器中运行。",
|
||||
"hero_title": "书写,触摸,阅读。",
|
||||
"hero_description": "InBraille 可将中文(拼音或汉字)转换为盲文,并导出为 ASCII 和 STL 格式用于 3D 打印,促进无障碍与包容。中文盲文基于普通话拼音(声母 + 韵母 + 声调)。",
|
||||
"try_now": "立即体验",
|
||||
"converter_title": "转换器",
|
||||
"tab_text_to_braille": "中文 → 盲文",
|
||||
"tab_braille_to_text": "盲文 → 拼音",
|
||||
"alphabet_label": "盲文标准",
|
||||
"alphabet_brazilian": "巴西",
|
||||
"alphabet_north_american": "北美",
|
||||
"alphabet_chinese": "中文(普通话)",
|
||||
"warning_brazilian": "在巴西盲文字母表中,此转换在某些字符上存在问题。例如,字符“&”与字符“ç”具有相同的盲文符号。",
|
||||
"chinese_input_tip": "您可以输入带声调数字的拼音(如 ni3 hao3)或中文汉字(如 你好)。系统会自动识别并转换。词与词之间请用空格分隔。",
|
||||
"clear_button": "清除",
|
||||
"copy_button": "复制",
|
||||
"save_button": "保存",
|
||||
"convert_button": "转换",
|
||||
"export_3d_title": "导出为 3D 打印",
|
||||
"stl_alert_text": "导出 STL 仅使用盲文内容,原始文字不会用于生成 3D 模型,请先将文字转换为盲文再导出。",
|
||||
"compass_alert_title": "方向标记:",
|
||||
"compass_alert_text": "为避免上下颠倒,模型包含参考标记。带底板时,左下角有一个较大的点;在\"仅点\"模式下,底部有一条小横杠。阅读或粘贴时请让该标记保持在下方/左侧。",
|
||||
"stl_button": "生成并预览 STL",
|
||||
"stl_preview_title": "3D 预览",
|
||||
"download_stl_button": "下载 STL",
|
||||
"preview_instructions": "拖动旋转,滚动缩放。",
|
||||
"advanced_options_title": "高级选项",
|
||||
"points_only_title": "仅点(无底板)",
|
||||
"points_only_desc": "仅生成点的凸帽(0.65 毫米),不含底板,并在底部附加一条方向横杠。适合将点粘贴到已有的 STL 上。启用后,底板相关选项将被禁用。",
|
||||
"separate_plates_title": "分离底板",
|
||||
"separate_plates_desc": "每行一个独立底板",
|
||||
"rounded_edges_title": "圆角",
|
||||
"rounded_edges_desc": "底板圆角",
|
||||
"text_alignment_title": "文字对齐",
|
||||
"align_center": "居中",
|
||||
"align_left": "左对齐",
|
||||
"align_right": "右对齐",
|
||||
"symbols_per_line_title": "每行符号数",
|
||||
"symbols_per_line_desc_prefix": "8 到 50 之间(底板宽度:",
|
||||
"symbols_per_line_desc_suffix": " 毫米)",
|
||||
"plate_thickness_title": "底板厚度(毫米)",
|
||||
"plate_thickness_desc": "2 到 100 之间",
|
||||
"point_resolution_title": "点分辨率",
|
||||
"point_resolution_desc": "15 到 50 之间",
|
||||
"about_title": "InBraille 的团队",
|
||||
"about_p1": "InBraille 诞生于巴西伯南布哥州 UFRPE 计算机系的 3D 与包容性技术实验室,让学校、家庭和盲文转写员无需昂贵设备即可制作盲文材料。",
|
||||
"about_p2": "借助该方案,可以扩展无障碍与包容,让任何人都能为视障人士制作触觉材料。",
|
||||
"about_p3": "中文盲文基于普通话拼音的语音表示:每个音节由声母、韵母和声调组成。本工具依照官方中文盲文规则进行转写。",
|
||||
"about_p4": "无论用于教育、专业还是日常场景,本工具都致力于让信息真正普及。目标是通过创客文化和 3D 打印普及盲文,为有需要的人提供自主与独立。",
|
||||
"neurodiversity_title": "技术中的神经多样性",
|
||||
"neurodiversity_p1": "本工具由 Lucas Guerra 开发。他是一名自闭症学生和开发者,将自己独特的视角转化为包容性的技术方案。自闭症为该项目带来了不同的思路,对细节和模式的高度专注造就了更易用、更直观的工具。",
|
||||
"neurodiversity_p2": "该方案源自伯南布哥联邦农村大学(UFRPE)计算机系的 3D 与包容技术实验室,致力于通过技术促进包容与无障碍,利用 3D 打印及其他辅助技术为残障人士创造创新方案。",
|
||||
"learn_more_title": "了解更多",
|
||||
"learn_more_p1": "在 Ciência Embarcada 页面了解更多关于本工具的信息。",
|
||||
"footer_text": "文字转盲文工具",
|
||||
"developed_by": "开发者",
|
||||
"input_label_text_to_braille": "输入文字",
|
||||
"input_placeholder_text_to_braille": "输入拼音(如 ni3 hao3)或汉字(如 你好)...",
|
||||
"output_label_text_to_braille": "盲文结果",
|
||||
"output_placeholder_text_to_braille": "盲文结果将显示在此处...",
|
||||
"input_label_braille_to_text": "输入盲文",
|
||||
"input_placeholder_braille_to_text": "输入要转换的盲文...",
|
||||
"output_label_braille_to_text": "拼音结果",
|
||||
"output_placeholder_braille_to_text": "拼音结果将显示在此处...",
|
||||
"console_copy_success": "文本已复制到剪贴板",
|
||||
"console_copy_error": "复制文本出错:",
|
||||
"copy_button_feedback": "已复制!",
|
||||
"confirm_line_exceeds": "其中一行超过了每行符号数限制。\n您想让程序尝试自动调整吗?",
|
||||
"alert_word_exceeds_prefix": "其中一个单词/字数超过了每行符号数限制。\n请在高级选项中,将每行符号数调整为至少",
|
||||
"alert_auto_adjust_success": "程序已成功自动调整该行。\n",
|
||||
"alert_manual_correct_prefix": "请手动更正,或在高级选项中将每行符号数调整为至少",
|
||||
"alert_general_error": "请重试",
|
||||
"toast_enter_braille": "请输入要打印的盲文。",
|
||||
"toast_enter_text": "请输入文字以生成底板。",
|
||||
"toast_converting": "正在自动转换为盲文...",
|
||||
"generating_loader": "生成中...",
|
||||
"stl_button_default": "生成并预览 STL",
|
||||
"alert_stl_error": "生成 STL 文件出错,请重试。",
|
||||
"skip_to_converter": "跳到转换器",
|
||||
"theme_toggle_label": "切换浅色/深色主题",
|
||||
"language_label": "语言",
|
||||
"mode_label": "转换方向",
|
||||
"kbd_hint": "快捷键:Ctrl+Enter 转换。",
|
||||
"before_print_title": "打印前须知",
|
||||
"stl_alert_title": "注意:",
|
||||
"stl_empty_hint": "先转换文本,再点击“生成 STL”,即可在此查看 3D 板。",
|
||||
"preview_canvas_label": "盲文板 3D 预览",
|
||||
"opens_new_tab": "(在新标签页打开)",
|
||||
"char_count_one": "{n} 个字符",
|
||||
"char_count_other": "{n} 个字符",
|
||||
"status_converted": "盲文已生成:{n} 个方。",
|
||||
"status_text_converted": "文本已转换。",
|
||||
"status_stl_ready": "3D 模型已就绪,可下载 STL。",
|
||||
"toast_nothing_to_copy": "暂无可复制内容,请先转换文本。",
|
||||
"toast_nothing_to_save": "暂无可保存内容,请先转换文本。",
|
||||
"toast_generate_first": "请先生成 STL 再下载。",
|
||||
"toast_saved": "文件已保存。",
|
||||
"toast_close": "关闭提示",
|
||||
"field_range_error": "请输入 {min} 到 {max} 之间的数值。",
|
||||
"theme_dark": "深色主题",
|
||||
"theme_light": "浅色主题",
|
||||
"og_title": "InBraille:书写盲文,3D 打印",
|
||||
"hero_eyebrow": "免费辅助技术",
|
||||
"hero_lede": "InBraille 能在几秒内把任何文本转换成盲文,并生成可直接用 3D 打印机打印的触觉板,全程无需离开浏览器。",
|
||||
"cta_convert": "立即转换",
|
||||
"cta_how": "工作原理",
|
||||
"hero_fact_free": "免费开源",
|
||||
"hero_fact_local": "在浏览器中运行",
|
||||
"hero_fact_langs": "支持葡萄牙语、英语和中文",
|
||||
"nav_converter": "转换器",
|
||||
"nav_how": "工作原理",
|
||||
"nav_print": "3D 打印",
|
||||
"nav_privacy": "隐私",
|
||||
"nav_paper": "论文",
|
||||
"nav_about": "关于",
|
||||
"nav_menu": "菜单",
|
||||
"how_title": "三步从文本到触觉板",
|
||||
"step1_title": "书写",
|
||||
"step1_text": "输入或粘贴文本,并选择盲文体系。",
|
||||
"step2_title": "检查盲文",
|
||||
"step2_text": "查看结果,可复制或保存用于其他材料。",
|
||||
"step3_title": "打印触觉板",
|
||||
"step3_text": "生成 STL,旋转查看 3D 模型,然后下载到打印机。",
|
||||
"print_title": "为触读而设计",
|
||||
"print_text": "触觉板遵循常用盲文尺寸,便于舒适触读;方向标记指示哪一面朝上。",
|
||||
"spec_dot_height": "点高",
|
||||
"spec_cell_spacing": "方距",
|
||||
"spec_plate_width": "默认板宽",
|
||||
"spec_orientation": "方向标记",
|
||||
"spec_orientation_value": "角部参考点",
|
||||
"print_tips_title": "打印建议",
|
||||
"print_tip1": "打印时点面朝上。",
|
||||
"print_tip2": "层高 0.1–0.12 毫米,点更清晰。",
|
||||
"print_tip3": "PLA 或 PETG 效果都很好。",
|
||||
"privacy_title": "您的文本不会离开您的设备",
|
||||
"privacy_text": "一切都在您的浏览器中完成:盲文转换、STL 生成和 3D 预览。任何文本都不会发送到服务器,也不会被存储。",
|
||||
"paper_eyebrow": "发表于 CSBC 2025",
|
||||
"paper_section_title": "同行评审研究",
|
||||
"paper_authors_label": "作者",
|
||||
"paper_venue_label": "会议",
|
||||
"paper_place_label": "地点",
|
||||
"paper_pages_label": "页码",
|
||||
"paper_publisher_label": "出版方",
|
||||
"paper_date_label": "发表日期",
|
||||
"paper_venue": "第一届创客行动创新、发展、教育与包容研讨会(IDEIA),CSBC 2025",
|
||||
"paper_summary": "InBraille 将文本转换为盲文,并按照巴西和美国标准生成包容性 3D 板。经过验证的原型在尺寸精度和触觉可读性方面表现良好。",
|
||||
"paper_read": "阅读论文",
|
||||
"paper_pdf": "下载 PDF",
|
||||
"paper_copy": "复制引用",
|
||||
"paper_copied": "已复制引用",
|
||||
"paper_bibtex_label": "BibTeX 引用",
|
||||
"paper_abnt_label": "ABNT 引用格式(巴西标准)",
|
||||
"paper_lang_note": "论文以葡萄牙语撰写。",
|
||||
"credits_title": "致谢",
|
||||
"credits_text": "由 Lucas Guerra 与 Marcos Cardoso、Marcos Castro 在 UFRPE 计算机系 3D 与包容性技术实验室共同创建,由 Ciência Embarcada 维护。",
|
||||
"source_code": "源代码",
|
||||
"maintained_by": "由 Ciência Embarcada 维护",
|
||||
"footer_tagline": "人人可用的盲文,从文本到 3D 打印。",
|
||||
"footer_site": "网站",
|
||||
"footer_project": "项目",
|
||||
"footer_rights": "© 2026 InBraille。开源项目。",
|
||||
"faq_title": "常见问题"
|
||||
};
|
||||
@@ -0,0 +1,83 @@
|
||||
// Tabelas de Braille (porte fiel de src/domain/alphabets.py, braille_codes.py e chinese_braille.py).
|
||||
// Somente dados e funcoes puras de tabela; a logica fica em translator.js.
|
||||
|
||||
// NOTA: as tabelas sao copias literais dos dados originais (inclusive o ":'" fundido da lista
|
||||
// norte-americana) para que a saida seja byte a byte identica a do servidor Python.
|
||||
export const BRAZILIAN = {
|
||||
normal: ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "á", "é", "í", "ó", "ú", "à", "â", "ê", "ô", "ã", "õ", "ç", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "!", "?", ".", ",", ";", ":", "(", ")", "[", "]", "-", "+", "/", "*", "&", "$", "%", "=", "<", ">"],
|
||||
braille: ["⠁", "⠃", "⠉", "⠙", "⠑", "⠋", "⠛", "⠓", "⠊", "⠚", "⠅", "⠇", "⠍", "⠝", "⠕", "⠏", "⠟", "⠗", "⠎", "⠞", "⠥", "⠧", "⠺", "⠭", "⠽", "⠵", "⠷", "⠿", "⠌", "⠬", "⠾", "⠫", "⠡", "⠣", "⠹", "⠜", "⠪", "⠯", "⠚", "⠁", "⠃", "⠉", "⠙", "⠑", "⠋", "⠛", "⠓", "⠊", "⠖", "⠢", "⠄", "⠂", "⠆", "⠒", "⠣⠄", "⠄⠜", "⠷⠄", "⠄⠾", "⠤", "⠖", "⠠⠂", "⠔", "⠯", "⠰", "⠸⠴", "⠶", "⠪", "⠕"],
|
||||
};
|
||||
|
||||
export const NORTH_AMERICAN = {
|
||||
normal: ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "!", "?", "&", "$", "#", "@", "%", "(", ")", "[", "]", "_", "+", "-", "*", "/", "\\", "=", "<", ">", ".", ",", ";", ":'", "\""],
|
||||
braille: ["⠁", "⠃", "⠉", "⠙", "⠑", "⠋", "⠛", "⠓", "⠊", "⠚", "⠅", "⠇", "⠍", "⠝", "⠕", "⠏", "⠟", "⠗", "⠎", "⠞", "⠥", "⠧", "⠺", "⠭", "⠽", "⠵", "⠴", "⠂", "⠆", "⠒", "⠲", "⠢", "⠖", "⠶", "⠦", "⠔", "⠮", "⠹", "⠯", "⠫", "⠼", "⠈", "⠩", "⠷", "⠾", "⠪", "⠻", "⠸", "⠬", "⠤", "⠡", "⠌", "⠳", "⠿", "⠣", "⠜", "⠨", "⠠", "⠰", "⠱", "⠄", "⠐"],
|
||||
};
|
||||
|
||||
// Codigo de 6 pontos (dot1..dot6) de cada celula Braille.
|
||||
export const BRAILLE_CODES = new Map([["⠁", "100000"], ["⠃", "110000"], ["⠉", "100100"], ["⠙", "100110"], ["⠑", "100010"], ["⠋", "110100"], ["⠛", "110110"], ["⠓", "110010"], ["⠊", "010100"], ["⠚", "010110"], ["⠅", "101000"], ["⠇", "111000"], ["⠍", "101100"], ["⠝", "101110"], ["⠕", "101010"], ["⠏", "111100"], ["⠟", "111110"], ["⠗", "111010"], ["⠎", "011100"], ["⠞", "011110"], ["⠥", "101001"], ["⠧", "111001"], ["⠺", "010111"], ["⠭", "101101"], ["⠽", "101111"], ["⠵", "101011"], ["⠴", "001011"], ["⠂", "010000"], ["⠆", "011000"], ["⠒", "010010"], ["⠲", "010011"], ["⠢", "010001"], ["⠖", "011010"], ["⠶", "011011"], ["⠦", "011001"], ["⠔", "001010"], ["⠮", "011101"], ["⠹", "100111"], ["⠯", "111101"], ["⠫", "110101"], ["⠼", "001111"], ["⠈", "000100"], ["⠩", "100101"], ["⠷", "111011"], ["⠾", "011111"], ["⠪", "010101"], ["⠻", "110111"], ["⠸", "000111"], ["⠬", "001101"], ["⠤", "001001"], ["⠡", "100001"], ["⠌", "001100"], ["⠿", "111111"], ["⠣", "110001"], ["⠜", "001110"], ["⠨", "000101"], ["⠠", "000001"], ["⠰", "000011"], ["⠱", "100011"], ["⠄", "001000"], ["⠐", "000010"], ["⣄", "011001"]]);
|
||||
|
||||
export function codeFor(character) {
|
||||
const mapped = BRAILLE_CODES.get(character);
|
||||
if (mapped !== undefined) return mapped;
|
||||
const value = character.codePointAt(0) - 0x2800;
|
||||
let out = "";
|
||||
for (let bit = 0; bit < 6; bit++) out += (value >> bit) & 1 ? "1" : "0";
|
||||
return out;
|
||||
}
|
||||
|
||||
// ---- Braille chines (mandarim) ----
|
||||
// Fonte: Australian Braille Authority, "Chinese (Mandarin) and UEB" (maio de 2024).
|
||||
// Uma silaba = inicial + final + tom. Padroes de pontos 1-6 viram celulas Unicode via cell().
|
||||
// Maps preservam a ordem de insercao (importante para "mantem a primeira grafia").
|
||||
|
||||
export function cell(dots) {
|
||||
let value = 0;
|
||||
for (const dot of dots) value |= 1 << (parseInt(dot, 10) - 1);
|
||||
return String.fromCodePoint(0x2800 + value);
|
||||
}
|
||||
|
||||
export const BLANK = cell("");
|
||||
|
||||
const INITIAL_DOTS = new Map([["b", "12"], ["p", "1234"], ["m", "134"], ["f", "124"], ["d", "145"], ["t", "2345"], ["n", "1345"], ["l", "123"], ["g", "1245"], ["j", "1245"], ["k", "13"], ["q", "13"], ["h", "125"], ["x", "125"], ["zh", "34"], ["ch", "12345"], ["sh", "156"], ["r", "245"], ["z", "1356"], ["c", "14"], ["s", "234"]]);
|
||||
const FINAL_DOTS = new Map([["a", "35"], ["o", "26"], ["e", "26"], ["i", "24"], ["yi", "24"], ["u", "136"], ["wu", "136"], ["ü", "346"], ["yu", "346"], ["v", "346"], ["er", "1235"], ["ai", "246"], ["ao", "235"], ["ei", "2346"], ["ou", "12356"], ["ia", "1246"], ["ya", "1246"], ["iao", "345"], ["yao", "345"], ["ie", "15"], ["ye", "15"], ["iu", "1256"], ["you", "1256"], ["ua", "123456"], ["wa", "123456"], ["uai", "13456"], ["wai", "13456"], ["ui", "2456"], ["wei", "2456"], ["uo", "135"], ["wo", "135"], ["üe", "23456"], ["yue", "23456"], ["ve", "23456"], ["an", "1236"], ["ang", "236"], ["en", "356"], ["eng", "3456"], ["ian", "146"], ["yan", "146"], ["iang", "1346"], ["yang", "1346"], ["in", "126"], ["yin", "126"], ["ing", "16"], ["ying", "16"], ["uan", "12456"], ["wan", "12456"], ["uang", "2356"], ["wang", "2356"], ["un", "25"], ["wen", "25"], ["ong", "256"], ["weng", "256"], ["üan", "12346"], ["yuan", "12346"], ["van", "12346"], ["ün", "456"], ["yun", "456"], ["vn", "456"], ["iong", "1456"], ["yong", "1456"]]);
|
||||
const TONE_DOTS = new Map([["1", "1"], ["2", "2"], ["3", "3"], ["4", "23"]]);
|
||||
const PUNCTUATION_DOTS = new Map([[",", ["5"]], [",", ["5"]], ["、", ["4"]], [";", ["56"]], [";", ["56"]], [":", ["36"]], [":", ["36"]], [".", ["5", "23"]], ["。", ["5", "23"]], ["?", ["5", "3"]], ["?", ["5", "3"]], ["!", ["56", "2"]], ["!", ["56", "2"]], ["-", ["36"]], ["…", ["5", "5", "5"]]]);
|
||||
|
||||
export const BUZZING_INITIALS = ["zh", "ch", "sh", "r", "z", "c", "s"];
|
||||
export const YU_INITIALS = ["j", "q", "x"];
|
||||
export const ACCENTS = new Map([["ā", ["a", "1"]], ["á", ["a", "2"]], ["ǎ", ["a", "3"]], ["à", ["a", "4"]], ["ō", ["o", "1"]], ["ó", ["o", "2"]], ["ǒ", ["o", "3"]], ["ò", ["o", "4"]], ["ē", ["e", "1"]], ["é", ["e", "2"]], ["ě", ["e", "3"]], ["è", ["e", "4"]], ["ī", ["i", "1"]], ["í", ["i", "2"]], ["ǐ", ["i", "3"]], ["ì", ["i", "4"]], ["ū", ["u", "1"]], ["ú", ["u", "2"]], ["ǔ", ["u", "3"]], ["ù", ["u", "4"]], ["ǖ", ["ü", "1"]], ["ǘ", ["ü", "2"]], ["ǚ", ["ü", "3"]], ["ǜ", ["ü", "4"]], ["ü", ["ü", ""]]]);
|
||||
|
||||
function mapValues(map, fn) {
|
||||
const out = new Map();
|
||||
for (const [k, v] of map) out.set(k, fn(v));
|
||||
return out;
|
||||
}
|
||||
|
||||
export const INITIAL_CELLS = mapValues(INITIAL_DOTS, cell);
|
||||
export const FINAL_CELLS = mapValues(FINAL_DOTS, cell);
|
||||
export const TONE_CELLS = mapValues(TONE_DOTS, cell);
|
||||
export const PUNCTUATION_CELLS = mapValues(PUNCTUATION_DOTS, (cells) => cells.map(cell).join(""));
|
||||
|
||||
// Reverso celula -> grafia, mantendo a primeira grafia (setdefault do Python).
|
||||
function first(map) {
|
||||
const reverse = new Map();
|
||||
for (const [spelling, c] of map) if (!reverse.has(c)) reverse.set(c, spelling);
|
||||
return reverse;
|
||||
}
|
||||
|
||||
export const INITIAL_BY_CELL = first(INITIAL_CELLS);
|
||||
export const FINAL_BY_CELL = first(FINAL_CELLS);
|
||||
|
||||
// Final sem inicial usa a grafia isolada com y/w.
|
||||
export const FINAL_STANDALONE_BY_CELL = new Map();
|
||||
for (const [spelling, c] of FINAL_CELLS) {
|
||||
if ("yw".includes(spelling[0]) && !FINAL_STANDALONE_BY_CELL.has(c)) FINAL_STANDALONE_BY_CELL.set(c, spelling);
|
||||
}
|
||||
for (const [c, plain] of FINAL_BY_CELL) {
|
||||
if (!FINAL_STANDALONE_BY_CELL.has(c)) FINAL_STANDALONE_BY_CELL.set(c, plain);
|
||||
}
|
||||
|
||||
export const TONE_BY_CELL = new Map();
|
||||
for (const [tone, c] of TONE_CELLS) TONE_BY_CELL.set(c, tone);
|
||||
export const PUNCTUATION_BY_CELL = new Map();
|
||||
for (const [ch, cells] of PUNCTUATION_DOTS) PUNCTUATION_BY_CELL.set(cells.map(cell).join(""), ch);
|
||||
+100
-51
@@ -1,6 +1,8 @@
|
||||
import { state } from './state.js';
|
||||
import { getTranslation } from './i18n.js';
|
||||
import { triggerRealtimePreview } from './stl.js';
|
||||
import { showToast, announce } from './ui.js';
|
||||
import { encode as translateEncode, decode as translateDecode } from './translator.js';
|
||||
|
||||
let dom = {};
|
||||
|
||||
@@ -13,6 +15,19 @@ export function getAlphabet() {
|
||||
return checkedInput ? checkedInput.value : "North American";
|
||||
}
|
||||
|
||||
function setAriaDisabled(el, disabled) {
|
||||
if (!el) return;
|
||||
el.setAttribute("aria-disabled", disabled ? "true" : "false");
|
||||
}
|
||||
|
||||
// Keeps aria-disabled of copy/save/download in sync with the output and STL state.
|
||||
export function updateActionStates() {
|
||||
const hasOutput = !!(dom.output_textbox && dom.output_textbox.value.length > 0);
|
||||
setAriaDisabled(dom.copy_button, !hasOutput);
|
||||
setAriaDisabled(dom.save_button, !hasOutput);
|
||||
setAriaDisabled(dom.download_stl_button, !state.last_stl_blob);
|
||||
}
|
||||
|
||||
export function switchConversionMode(mode) {
|
||||
state.conversion_mode = mode ? mode : state.conversion_mode;
|
||||
|
||||
@@ -24,30 +39,44 @@ export function switchConversionMode(mode) {
|
||||
const output_textbox = dom.output_textbox;
|
||||
const warning = dom.warning;
|
||||
|
||||
if (!text_to_braille_tab || !braille_to_text_tab || !input_label || !input_textbox || !output_label || !output_textbox || !warning) {
|
||||
if (!text_to_braille_tab || !braille_to_text_tab || !input_label || !input_textbox || !output_label || !output_textbox) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (state.conversion_mode === "text-to-braille") {
|
||||
text_to_braille_tab.classList.add("tab-active");
|
||||
braille_to_text_tab.classList.remove("tab-active");
|
||||
const toBraille = state.conversion_mode === "text-to-braille";
|
||||
const active = toBraille ? text_to_braille_tab : braille_to_text_tab;
|
||||
const inactive = toBraille ? braille_to_text_tab : text_to_braille_tab;
|
||||
active.classList.add("tab-active");
|
||||
inactive.classList.remove("tab-active");
|
||||
active.setAttribute("aria-selected", "true");
|
||||
inactive.setAttribute("aria-selected", "false");
|
||||
active.setAttribute("tabindex", "0");
|
||||
inactive.setAttribute("tabindex", "-1");
|
||||
const workbench = document.getElementById("workbench");
|
||||
if (workbench) workbench.setAttribute("aria-labelledby", active.id);
|
||||
|
||||
input_label.innerHTML = `<i class="fas fa-pen-alt mr-1"></i> ${getTranslation("input_label_text_to_braille")}`;
|
||||
const brailleGlyph = '<span class="label-icon" aria-hidden="true">⠿</span> ';
|
||||
if (toBraille) {
|
||||
input_label.innerHTML = `<i class="fas fa-pen-alt label-icon" aria-hidden="true"></i> `;
|
||||
input_label.append(getTranslation("input_label_text_to_braille"));
|
||||
input_textbox.placeholder = getTranslation("input_placeholder_text_to_braille");
|
||||
output_label.innerHTML = `<span class="mr-1 font-bold">⠿</span> ${getTranslation("output_label_text_to_braille")}`;
|
||||
output_label.innerHTML = brailleGlyph;
|
||||
output_label.append(getTranslation("output_label_text_to_braille"));
|
||||
output_textbox.placeholder = getTranslation("output_placeholder_text_to_braille");
|
||||
|
||||
warning.classList.add("hidden");
|
||||
} else {
|
||||
text_to_braille_tab.classList.remove("tab-active");
|
||||
braille_to_text_tab.classList.add("tab-active");
|
||||
|
||||
input_label.innerHTML = `<span class="mr-1 font-bold">⠿</span> ${getTranslation("input_label_braille_to_text")}`;
|
||||
input_label.innerHTML = brailleGlyph;
|
||||
input_label.append(getTranslation("input_label_braille_to_text"));
|
||||
input_textbox.placeholder = getTranslation("input_placeholder_braille_to_text");
|
||||
output_label.innerHTML = `<i class="fas fa-text-width mr-1"></i> ${getTranslation("output_label_braille_to_text")}`;
|
||||
output_label.innerHTML = `<i class="fas fa-text-width label-icon" aria-hidden="true"></i> `;
|
||||
output_label.append(getTranslation("output_label_braille_to_text"));
|
||||
output_textbox.placeholder = getTranslation("output_placeholder_braille_to_text");
|
||||
}
|
||||
// The field that holds Braille uses the Braille font/size.
|
||||
input_textbox.classList.toggle("braille-text", !toBraille);
|
||||
output_textbox.classList.toggle("braille-text", toBraille);
|
||||
|
||||
if (getAlphabet() === "Brazilian") {
|
||||
if (warning) {
|
||||
if (!toBraille && getAlphabet() === "Brazilian") {
|
||||
warning.classList.remove("hidden");
|
||||
} else {
|
||||
warning.classList.add("hidden");
|
||||
@@ -56,66 +85,80 @@ export function switchConversionMode(mode) {
|
||||
|
||||
const chineseTip = document.getElementById("chinese_input_tip_container");
|
||||
if (chineseTip) {
|
||||
if (getAlphabet() === "Chinese") {
|
||||
chineseTip.classList.remove("hidden");
|
||||
} else {
|
||||
chineseTip.classList.add("hidden");
|
||||
}
|
||||
chineseTip.classList.toggle("hidden", getAlphabet() !== "Chinese");
|
||||
}
|
||||
|
||||
if (mode) {
|
||||
clearInput();
|
||||
}
|
||||
updateCharCount();
|
||||
updateActionStates();
|
||||
}
|
||||
|
||||
export function clearInput() {
|
||||
if (dom.input_textbox) dom.input_textbox.value = "";
|
||||
if (dom.output_textbox) dom.output_textbox.value = "";
|
||||
updateCharCount();
|
||||
updateActionStates();
|
||||
}
|
||||
|
||||
export function updateCharCount() {
|
||||
if (!dom.char_count || !dom.input_textbox) return;
|
||||
const count = dom.input_textbox.value.length;
|
||||
if (state.page_language === "pt-BR") {
|
||||
dom.char_count.innerText = count + (count !== 1 ? " caracteres" : " caracter");
|
||||
} else if (state.page_language === "en") {
|
||||
dom.char_count.innerText = count + (count !== 1 ? " characters" : " character");
|
||||
} else if (state.page_language === "zh") {
|
||||
dom.char_count.innerText = count + " 个字符";
|
||||
}
|
||||
const tpl = getTranslation(count === 1 ? "char_count_one" : "char_count_other") || "{n}";
|
||||
dom.char_count.textContent = tpl.replace("{n}", count);
|
||||
}
|
||||
|
||||
export function copyOutput() {
|
||||
const output_textbox = dom.output_textbox;
|
||||
const copy_button = dom.copy_button;
|
||||
if (!output_textbox || !copy_button) return;
|
||||
|
||||
if (!navigator.clipboard) {
|
||||
output_textbox.select();
|
||||
document.execCommand("copy");
|
||||
} else {
|
||||
const output = output_textbox.value;
|
||||
navigator.clipboard.writeText(output).then(() => {
|
||||
console.log(getTranslation("console_copy_success") || "Copied");
|
||||
}).catch(err => {
|
||||
console.error(getTranslation("console_copy_error") || "Error", err);
|
||||
});
|
||||
|
||||
const output = output_textbox.value;
|
||||
if (output.length === 0) {
|
||||
showToast(getTranslation("toast_nothing_to_copy"), "info");
|
||||
return;
|
||||
}
|
||||
|
||||
const originalText = copy_button.innerText;
|
||||
const copyText = getTranslation("copy_button_feedback") || "Copied!";
|
||||
copy_button.innerHTML = `<i class="fas fa-check mr-1"></i> ${copyText}`;
|
||||
const labelEl = document.getElementById("copy_button_text") || copy_button;
|
||||
const iconEl = copy_button.querySelector("i");
|
||||
const showCopied = () => {
|
||||
const copyText = getTranslation("copy_button_feedback") || "Copied!";
|
||||
const originalIcon = iconEl ? iconEl.className : "";
|
||||
const originalText = getTranslation("copy_button") || labelEl.textContent;
|
||||
labelEl.textContent = copyText;
|
||||
if (iconEl) iconEl.className = "fas fa-check";
|
||||
announce(copyText);
|
||||
setTimeout(() => {
|
||||
labelEl.textContent = getTranslation("copy_button") || originalText;
|
||||
if (iconEl) iconEl.className = originalIcon;
|
||||
}, 2000);
|
||||
};
|
||||
const fallback = () => {
|
||||
try {
|
||||
output_textbox.select();
|
||||
if (document.execCommand("copy")) { showCopied(); return; }
|
||||
} catch (e) { console.error(e); }
|
||||
showToast(getTranslation("console_copy_error") || "Error", "error");
|
||||
};
|
||||
|
||||
setTimeout(() => {
|
||||
copy_button.innerHTML = originalText;
|
||||
}, 2000);
|
||||
if (!navigator.clipboard) {
|
||||
fallback();
|
||||
} else {
|
||||
navigator.clipboard.writeText(output).then(showCopied).catch(err => {
|
||||
console.error(getTranslation("console_copy_error") || "Error", err);
|
||||
fallback();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export function saveOutput() {
|
||||
if (!dom.output_textbox) return;
|
||||
const text = dom.output_textbox.value;
|
||||
if (text.length === 0) { return; }
|
||||
if (text.length === 0) {
|
||||
showToast(getTranslation("toast_nothing_to_save"), "info");
|
||||
return;
|
||||
}
|
||||
|
||||
const blob = new Blob([text], { type: 'text/plain' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
@@ -126,6 +169,7 @@ export function saveOutput() {
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
URL.revokeObjectURL(url);
|
||||
showToast(getTranslation("toast_saved"), "success");
|
||||
}
|
||||
|
||||
function adjustBrailleSize(braille) {
|
||||
@@ -170,12 +214,12 @@ async function checkBrailleSize(braille) {
|
||||
const adjusted = adjustBrailleSize(braille);
|
||||
if (isNaN(adjusted)) {
|
||||
if (state.conversion_mode === "text-to-braille") {
|
||||
const response = await axios.post("/api/decode", {
|
||||
const response = await translateDecode({
|
||||
braille: adjusted,
|
||||
alphabet: getAlphabet()
|
||||
});
|
||||
if (dom.input_textbox) {
|
||||
dom.input_textbox.value = response.data.decoded;
|
||||
dom.input_textbox.value = response.decoded;
|
||||
}
|
||||
}
|
||||
alert(getTranslation("alert_auto_adjust_success"));
|
||||
@@ -199,11 +243,11 @@ export async function convert() {
|
||||
const alphabet = getAlphabet();
|
||||
try {
|
||||
if (state.conversion_mode === "text-to-braille") {
|
||||
const response = await axios.post("/api/encode", {
|
||||
const response = await translateEncode({
|
||||
text: text,
|
||||
alphabet: alphabet
|
||||
});
|
||||
const braille = await checkBrailleSize(response.data.encoded);
|
||||
const braille = await checkBrailleSize(response.encoded);
|
||||
if (braille === -1) {
|
||||
// Alert already handled inside checkBrailleSize
|
||||
} else if (!isNaN(braille)) {
|
||||
@@ -211,6 +255,9 @@ export async function convert() {
|
||||
alert(`${getTranslation("alert_manual_correct_prefix")} ${braille}`);
|
||||
} else {
|
||||
dom.output_textbox.value = braille;
|
||||
const cells = (String(braille).match(/[\u2800-\u28FF]/g) || []).length;
|
||||
announce((getTranslation("status_converted") || "").replace("{n}", cells));
|
||||
updateActionStates();
|
||||
triggerRealtimePreview(60);
|
||||
}
|
||||
} else {
|
||||
@@ -221,16 +268,18 @@ export async function convert() {
|
||||
dom.output_textbox.value = "";
|
||||
alert(`${getTranslation("alert_manual_correct_prefix")} ${adjusted_braille}`);
|
||||
} else {
|
||||
const response = await axios.post("/api/decode", {
|
||||
const response = await translateDecode({
|
||||
braille: text,
|
||||
alphabet: alphabet
|
||||
});
|
||||
dom.output_textbox.value = response.data.decoded;
|
||||
dom.output_textbox.value = response.decoded;
|
||||
announce(getTranslation("status_text_converted"));
|
||||
updateActionStates();
|
||||
triggerRealtimePreview(60);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
alert(getTranslation("alert_general_error"));
|
||||
showToast(getTranslation("alert_general_error"), "error");
|
||||
}
|
||||
}
|
||||
+43
-17
@@ -6,25 +6,41 @@ export function getTranslation(key) {
|
||||
return dict[key];
|
||||
}
|
||||
|
||||
const HTML_LANG = { "pt-BR": "pt-BR", "en": "en", "zh": "zh-CN" };
|
||||
const LANG_LABEL = { "pt-BR": "Português", "en": "English", "zh": "中文" };
|
||||
const OG_LOCALE = { "pt-BR": "pt_BR", "en": "en_US", "zh": "zh_CN" };
|
||||
const DATE_LOCALE = { "pt-BR": "pt-BR", "en": "en-US", "zh": "zh-CN" };
|
||||
|
||||
function setMeta(selector, value) {
|
||||
if (value === undefined || value === "") return;
|
||||
const el = document.querySelector(selector);
|
||||
if (el) el.setAttribute("content", value);
|
||||
}
|
||||
|
||||
export function setLanguage(lang, onLanguageChanged) {
|
||||
state.page_language = lang;
|
||||
document.documentElement.lang = lang;
|
||||
document.documentElement.lang = HTML_LANG[lang] || lang;
|
||||
|
||||
const dict = translations[lang] || translations["pt-BR"];
|
||||
|
||||
if (dict.page_title) {
|
||||
document.title = dict.page_title;
|
||||
}
|
||||
const metaDesc = document.querySelector('meta[name="description"]');
|
||||
if (metaDesc && dict.meta_description) {
|
||||
metaDesc.setAttribute("content", dict.meta_description);
|
||||
}
|
||||
setMeta('meta[name="description"]', dict.meta_description);
|
||||
setMeta('meta[property="og:title"]', dict.og_title);
|
||||
setMeta('meta[property="og:description"]', dict.meta_description);
|
||||
setMeta('meta[property="og:locale"]', OG_LOCALE[lang]);
|
||||
setMeta('meta[name="twitter:title"]', dict.og_title);
|
||||
setMeta('meta[name="twitter:description"]', dict.meta_description);
|
||||
|
||||
document.querySelectorAll("[data-i18n]").forEach(elem => {
|
||||
const key = elem.getAttribute("data-i18n");
|
||||
if (dict[key] !== undefined) {
|
||||
elem.textContent = dict[key];
|
||||
}
|
||||
// Elements whose translation is empty (e.g. paper_lang_note in pt-BR) are hidden.
|
||||
if (dict[key] === "") elem.hidden = true;
|
||||
else if (elem.hidden && dict[key] !== undefined) elem.hidden = false;
|
||||
});
|
||||
|
||||
document.querySelectorAll("[data-i18n-placeholder]").forEach(elem => {
|
||||
@@ -33,6 +49,23 @@ export function setLanguage(lang, onLanguageChanged) {
|
||||
elem.setAttribute("placeholder", dict[key]);
|
||||
}
|
||||
});
|
||||
|
||||
document.querySelectorAll("[data-i18n-aria-label]").forEach(elem => {
|
||||
const key = elem.getAttribute("data-i18n-aria-label");
|
||||
if (dict[key] !== undefined) {
|
||||
elem.setAttribute("aria-label", dict[key]);
|
||||
}
|
||||
});
|
||||
|
||||
document.querySelectorAll("time[datetime]").forEach(elem => {
|
||||
try {
|
||||
const d = new Date(elem.getAttribute("datetime") + "T12:00:00Z");
|
||||
elem.textContent = new Intl.DateTimeFormat(DATE_LOCALE[lang] || lang, {
|
||||
year: "numeric", month: "long", day: "numeric", timeZone: "UTC"
|
||||
}).format(d);
|
||||
} catch (e) { /* keep existing text */ }
|
||||
});
|
||||
|
||||
updateLangMenu(lang);
|
||||
if (onLanguageChanged) {
|
||||
onLanguageChanged();
|
||||
@@ -41,22 +74,15 @@ export function setLanguage(lang, onLanguageChanged) {
|
||||
|
||||
function updateLangMenu(lang) {
|
||||
const labelElem = document.querySelector("#current-lang-label");
|
||||
if (!labelElem) return;
|
||||
|
||||
if (lang === "pt-BR") {
|
||||
labelElem.innerHTML = "🇧🇷 Português";
|
||||
} else if (lang === "en") {
|
||||
labelElem.innerHTML = "🇺🇸 English";
|
||||
} else if (lang === "zh") {
|
||||
labelElem.innerHTML = "🇨🇳 中文";
|
||||
if (labelElem && LANG_LABEL[lang]) {
|
||||
labelElem.textContent = LANG_LABEL[lang];
|
||||
}
|
||||
|
||||
const buttons = document.querySelectorAll("#lang_dropdown button[data-lang]");
|
||||
buttons.forEach(btn => {
|
||||
document.querySelectorAll("#lang_dropdown button[data-lang]").forEach(btn => {
|
||||
if (btn.getAttribute("data-lang") === lang) {
|
||||
btn.className = "w-full text-left flex items-center gap-3 px-4 py-2 bg-blue-50 text-blue-600 font-semibold";
|
||||
btn.setAttribute("aria-current", "true");
|
||||
} else {
|
||||
btn.className = "w-full text-left flex items-center gap-3 px-4 py-2 text-gray-700 hover:bg-gray-50";
|
||||
btn.removeAttribute("aria-current");
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
{"s":{"一":"yi1","丁":"ding1","丂":"kao3","七":"qi1","丄":"shang4","丅":"xia4","丆":"han3","万":"wan4","丈":"zhang4","三":"san1","上":"shang4","下":"xia4","丌":"ji1","不":"bu4","与":"yu3","丏":"mian3","丐":"gai4","丑":"chou3","丒":"chou3","专":"zhuan1","且":"qie3","丕":"pi1","世":"shi4","丗":"shi4","丘":"qiu1","丙":"bing3","业":"ye4","丛":"cong2","东":"dong1","丝":"si1","丞":"cheng2","丟":"diu1","丠":"qiu1","両":"liang3","丢":"diu1","丣":"you3","两":"liang3","严":"yan2","並":"bing4","丧":"sang4","丨":"gun3","丩":"jiu1","个":"ge4","丫":"ya1","丬":"qiang2","中":"zhong1","丮":"ji3","丯":"jie4","丰":"feng1","丱":"guan4","串":"chuan4","丳":"chan3","临":"lin2","丵":"zhuo2","丶":"zhu3","丷":"ba1","丸":"wan2","丹":"dan1","为":"wei4","主":"zhu3","丼":"jing3","丽":"li4","举":"ju3","丿":"pie3","乀":"fu2","乁":"yi2","乂":"yi4","乃":"nai3","乄":"wu3","久":"jiu3","乆":"jiu3","乇":"tuo1","么":"me5","义":"yi4","乊":"yi1","之":"zhi1","乌":"wu1","乍":"zha4","乎":"hu1","乏":"fa2","乐":"le4","乑":"yin2","乒":"ping1","乓":"pang1","乔":"qiao2","乕":"hu3","乖":"guai1","乗":"cheng2","乘":"cheng2","乙":"yi3","乚":"yin3","乛":"ya5","乜":"mie1","九":"jiu3","乞":"qi3","也":"ye3","习":"xi2","乡":"xiang1","乢":"gai4","乣":"jiu3","乤":"xia4","乥":"hu4","书":"shu1","乧":"dou3","乨":"shi3","乩":"ji1","乪":"nang2","乫":"jia1","乬":"ju4","乭":"shi2","乮":"mao3","乯":"hu1","买":"mai3","乱":"luan4","乲":"zi1","乳":"ru3","乴":"xue2","乵":"yan3","乶":"fu3","乷":"sha1","乸":"na3","乹":"gan1","乺":"suo3","乻":"yu2","乼":"cui5","乽":"zhe3","乾":"qian2","乿":"zhi4","亀":"gui1","亁":"gan1","亂":"luan4","亃":"lin3","亄":"yi4","亅":"jue2","了":"le5","亇":"ma5","予":"yu3","争":"zheng1","亊":"shi4","事":"shi4","二":"er4","亍":"chu4","于":"yu2","亏":"kui1","亐":"yu2","云":"yun2","互":"hu4","亓":"qi2","五":"wu3","井":"jing3","亖":"si4","亗":"sui4","亘":"gen4","亙":"gen4","亚":"ya4","些":"xie1","亜":"ya4","亝":"qi2","亞":"ya4","亟":"ji2","亠":"tou2","亡":"wang2","亢":"kang4","亣":"da4","交":"jiao1","亥":"hai4","亦":"yi4","产":"chan3","亨":"heng1","亩":"mu3","亪":"ye5","享":"xiang3","京":"jing1","亭":"ting2","亮":"liang4","亯":"xiang3","亰":"jing1","亱":"ye4","亲":"qin1","亳":"bo2","亴":"you4","亵":"xie4","亶":"dan3","亷":"lian2","亸":"duo3","亹":"wei3","人":"ren2","亻":"ren2","亼":"ji2","亽":"ji2","亾":"wang2","亿":"yi4","什":"shen2","仁":"ren2","仂":"le4","仃":"ding1","仄":"ze4","仅":"jin3","仆":"pu1","仇":"chou2","仈":"ba1","仉":"zhang3","今":"jin1","介":"jie4","仌":"bing1","仍":"reng2","从":"cong2","仏":"fo2","仐":"san3","仑":"lun2","仒":"bing1","仓":"cang1","仔":"zai3","仕":"shi4","他":"ta1","仗":"zhang4","付":"fu4","仙":"xian1","仚":"xian1","仛":"tuo1","仜":"hong2","仝":"tong2","仞":"ren4","仟":"qian1","仠":"gan3","仡":"ge1","仢":"bo2","代":"dai4","令":"ling4","以":"yi3","仦":"chao4","仧":"chang2","仨":"sa1","仩":"chang2","仪":"yi2","仫":"mu4","们":"men5","仭":"ren4","仮":"fan3","仯":"chao4","仰":"yang3","仱":"qian2","仲":"zhong4","仳":"pi3","仴":"wo4","仵":"wu3","件":"jian4","价":"jia4","仸":"yao3","仹":"feng1","仺":"cang1","任":"ren4","仼":"wang2","份":"fen4","仾":"di1","仿":"fang3","伀":"zhong1","企":"qi3","伂":"pei4","伃":"yu2","伄":"diao4","伅":"dun4","伆":"wu4","伇":"yi4","伈":"xin3","伉":"kang4","伊":"yi1","伋":"ji2","伌":"ai4","伍":"wu3","伎":"ji4","伏":"fu2","伐":"fa2","休":"xiu1","伒":"jin4","伓":"pi1","伔":"dan3","伕":"fu1","伖":"tang3","众":"zhong4","优":"you1","伙":"huo3","会":"hui4","伛":"yu3","伜":"cui4","伝":"yun2","伞":"san3","伟":"wei3","传":"chuan2","伡":"che1","伢":"ya2","伣":"qian4","伤":"shang1","伥":"chang1","伦":"lun2","伧":"cang1","伨":"xun4","伩":"xin4","伪":"wei3","伫":"zhu4","伬":"ze5","伭":"xian2","伮":"nu3","伯":"bo2","估":"gu1","伱":"ni3","伲":"ni4","伳":"xie4","伴":"ban4","伵":"xu4","伶":"ling2","伷":"zhou4","伸":"shen1","伹":"qu1","伺":"ci4","伻":"beng1","似":"shi4","伽":"ga1","伾":"pi1","伿":"yi4","佀":"si4","佁":"yi3","佂":"zheng1","佃":"dian4","佄":"han1","佅":"mai4","但":"dan4","佇":"zhu4","佈":"bu4","佉":"qu1","佊":"bi3","佋":"zhao1","佌":"ci3","位":"wei4","低":"di1","住":"zhu4","佐":"zuo3","佑":"you4","佒":"yang3","体":"ti3","佔":"zhan4","何":"he2","佖":"bi4","佗":"tuo2","佘":"she2","余":"yu2","佚":"yi4","佛":"fu2","作":"zuo4","佝":"gou1","佞":"ning4","佟":"tong2","你":"ni3","佡":"xian1","佢":"qu2","佣":"yong1","佤":"wa3","佥":"qian1","佦":"shi5","佧":"ka3","佨":"bao1","佩":"pei4","佪":"hui2","佫":"he4","佬":"lao3","佭":"xiang2","佮":"ge2","佯":"yang2","佰":"bai3","佱":"fa3","佲":"ming3","佳":"jia1","佴":"er4","併":"bing4","佶":"ji2","佷":"hen3","佸":"huo2","佹":"gui3","佺":"quan2","佻":"tiao1","佼":"jiao3","佽":"ci4","佾":"yi4","使":"sLine truncated
|
||||
+66
-36
@@ -1,7 +1,7 @@
|
||||
import { state, updatePlateWidth } from './state.js';
|
||||
import { getTranslation } from './i18n.js';
|
||||
import { showToast, highlightInput } from './ui.js';
|
||||
import { convert } from './converter.js';
|
||||
import { showToast, highlightInput, announce } from './ui.js';
|
||||
import { convert, updateActionStates } from './converter.js';
|
||||
import { buildClientSTL } from './client_stl_generator.js';
|
||||
|
||||
let dom = {};
|
||||
@@ -11,6 +11,7 @@ export function initStlDOM(elements) {
|
||||
}
|
||||
|
||||
let realtimeDebounceTimer = null;
|
||||
let firstStlDone = false;
|
||||
|
||||
export function triggerRealtimePreview(delay = 80) {
|
||||
if (!dom.stl_preview || dom.stl_preview.classList.contains("hidden")) {
|
||||
@@ -45,6 +46,7 @@ export function updateRealtimeModel() {
|
||||
points_only: state.points_only
|
||||
});
|
||||
state.last_stl_blob = new Blob([arrayBuffer], { type: "model/stl" });
|
||||
updateActionStates();
|
||||
if (typeof window.renderSTLPreview === "function") {
|
||||
window.renderSTLPreview(arrayBuffer.slice(0), false);
|
||||
}
|
||||
@@ -73,27 +75,45 @@ export function applyPointsOnlyState() {
|
||||
const disabled_inputs = [dom.input_separate_plates, dom.input_rounded, dom.input_plate_thickness];
|
||||
disabled_inputs.forEach((input) => {
|
||||
input.disabled = state.points_only;
|
||||
const card = input.closest(".bg-white");
|
||||
const card = input.closest(".option-card, .bg-white");
|
||||
if (card) {
|
||||
card.classList.toggle("opacity-50", state.points_only);
|
||||
card.classList.toggle("pointer-events-none", state.points_only);
|
||||
if (state.points_only) card.setAttribute("aria-disabled", "true");
|
||||
else card.removeAttribute("aria-disabled");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function setFieldError(inputEl, message) {
|
||||
if (!inputEl) return;
|
||||
const err = document.getElementById(`${inputEl.id}_error`);
|
||||
if (message) {
|
||||
inputEl.setAttribute("aria-invalid", "true");
|
||||
if (err) { err.textContent = message; err.classList.remove("hidden"); }
|
||||
} else {
|
||||
inputEl.removeAttribute("aria-invalid");
|
||||
if (err) { err.textContent = ""; err.classList.add("hidden"); }
|
||||
}
|
||||
}
|
||||
|
||||
export function updateInputs() {
|
||||
if (!dom.input_resolution || !dom.input_plate_thickness || !dom.input_separate_plates || !dom.input_symbols_per_line || !dom.select_text_alignment || !dom.input_rounded || !dom.input_points_only || !dom.output_plate_width) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (state.symbols_per_line < 8) { state.symbols_per_line = 8; }
|
||||
if (state.symbols_per_line > 50) { state.symbols_per_line = 50; }
|
||||
|
||||
if (state.plate_thickness < 2) { state.plate_thickness = 2; }
|
||||
if (state.plate_thickness > 100) { state.plate_thickness = 100; }
|
||||
|
||||
if (state.resolution < 15) { state.resolution = 15; }
|
||||
if (state.resolution > 50) { state.resolution = 50; }
|
||||
const clamp = (key, min, max, inputEl) => {
|
||||
const original = parseInt(inputEl.value);
|
||||
let outOfRange = !isNaN(original) && (original < min || original > max);
|
||||
if (state[key] < min) { state[key] = min; outOfRange = true; }
|
||||
if (state[key] > max) { state[key] = max; outOfRange = true; }
|
||||
setFieldError(inputEl, outOfRange
|
||||
? (getTranslation("field_range_error") || "{min}-{max}").replace("{min}", min).replace("{max}", max)
|
||||
: "");
|
||||
};
|
||||
clamp("symbols_per_line", 8, 50, dom.input_symbols_per_line);
|
||||
clamp("plate_thickness", 2, 100, dom.input_plate_thickness);
|
||||
clamp("resolution", 15, 50, dom.input_resolution);
|
||||
|
||||
dom.input_resolution.value = state.resolution;
|
||||
dom.input_plate_thickness.value = state.plate_thickness;
|
||||
@@ -137,12 +157,13 @@ export async function generateSTL() {
|
||||
}
|
||||
if (braille.length === 0) { return; }
|
||||
|
||||
const stlText = document.getElementById("stl_button_text");
|
||||
stl_button.disabled = true;
|
||||
const genText = getTranslation("generating_loader") || "Generating...";
|
||||
stl_button.innerHTML = `<i class="fas fa-spinner fa-spin mr-1"></i>${genText}`;
|
||||
stl_button.setAttribute("aria-busy", "true");
|
||||
if (stlText) stlText.textContent = getTranslation("generating_loader") || "Generating...";
|
||||
if (dom.stl_preview) dom.stl_preview.classList.add("is-loading");
|
||||
|
||||
try {
|
||||
let arrayBuffer = null;
|
||||
const optionsPayload = {
|
||||
braille: braille,
|
||||
resolution: state.resolution,
|
||||
@@ -154,45 +175,48 @@ export async function generateSTL() {
|
||||
points_only: state.points_only
|
||||
};
|
||||
|
||||
// 1. Ultra-fast Client-Side Generation (Instant, 0 latency, 0 server load)
|
||||
try {
|
||||
const t0 = performance.now();
|
||||
arrayBuffer = buildClientSTL(braille, optionsPayload);
|
||||
const elapsed = performance.now() - t0;
|
||||
console.log(`[InBraille] Client STL generated in ${elapsed.toFixed(1)}ms`);
|
||||
} catch (clientErr) {
|
||||
console.warn('[InBraille] Client-side STL generator encountered error, falling back to server API:', clientErr);
|
||||
}
|
||||
|
||||
// 2. Server API fallback if client generation is unavailable or fails
|
||||
if (!arrayBuffer) {
|
||||
const response = await axios.post("/api/to-stl", optionsPayload, { responseType: 'arraybuffer' });
|
||||
arrayBuffer = response.data;
|
||||
}
|
||||
// Geracao 100% no navegador; qualquer erro cai no catch abaixo (toast).
|
||||
const t0 = performance.now();
|
||||
const arrayBuffer = buildClientSTL(braille, optionsPayload);
|
||||
console.log(`[InBraille] Client STL generated in ${(performance.now() - t0).toFixed(1)}ms`);
|
||||
|
||||
state.last_stl_blob = new Blob([arrayBuffer], { type: "model/stl" });
|
||||
|
||||
const empty = document.getElementById("stl_empty");
|
||||
if (empty) empty.classList.add("hidden");
|
||||
if (dom.stl_preview) {
|
||||
dom.stl_preview.classList.remove("hidden");
|
||||
}
|
||||
if (typeof window.renderSTLPreview === "function") {
|
||||
window.renderSTLPreview(arrayBuffer.slice(0), true);
|
||||
}
|
||||
updateActionStates();
|
||||
if (dom.stl_preview) {
|
||||
dom.stl_preview.scrollIntoView({ behavior: "smooth", block: "nearest" });
|
||||
const reduce = window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
|
||||
dom.stl_preview.scrollIntoView({ behavior: reduce ? "auto" : "smooth", block: "nearest" });
|
||||
}
|
||||
announce(getTranslation("status_stl_ready"));
|
||||
if (!firstStlDone) {
|
||||
firstStlDone = true;
|
||||
const title = document.getElementById("stl_preview_title");
|
||||
if (title) title.focus({ preventScroll: true });
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
alert(getTranslation("alert_stl_error"));
|
||||
showToast(getTranslation("alert_stl_error"), "error");
|
||||
} finally {
|
||||
stl_button.disabled = false;
|
||||
const genDoneText = getTranslation("stl_button_default") || "Generate & Preview STL";
|
||||
stl_button.innerHTML = `<i class="fas fa-cube mr-2"></i>${genDoneText}`;
|
||||
stl_button.removeAttribute("aria-busy");
|
||||
if (stlText) stlText.textContent = getTranslation("stl_button_default") || "Generate & Preview STL";
|
||||
if (dom.stl_preview) dom.stl_preview.classList.remove("is-loading");
|
||||
}
|
||||
}
|
||||
|
||||
export function downloadSTL() {
|
||||
if (!state.last_stl_blob) { return; }
|
||||
if (!state.last_stl_blob) {
|
||||
showToast(getTranslation("toast_generate_first"), "info");
|
||||
return;
|
||||
}
|
||||
|
||||
const url = window.URL.createObjectURL(state.last_stl_blob);
|
||||
const link = document.createElement('a');
|
||||
@@ -206,7 +230,13 @@ export function downloadSTL() {
|
||||
|
||||
export function toggleAdvancedOptions() {
|
||||
if (dom.advanced_options && dom.advanced_options_arrow) {
|
||||
dom.advanced_options.classList.toggle("hidden");
|
||||
dom.advanced_options_arrow.classList.toggle("rotate-180");
|
||||
const nowHidden = dom.advanced_options.classList.toggle("hidden");
|
||||
dom.advanced_options_arrow.classList.toggle("rotate-180", !nowHidden);
|
||||
if (dom.advanced_options_toggle) dom.advanced_options_toggle.setAttribute("aria-expanded", String(!nowHidden));
|
||||
}
|
||||
}
|
||||
|
||||
export function openAdvancedOptionsOnDesktop() {
|
||||
if (!dom.advanced_options || !window.matchMedia || !window.matchMedia("(min-width: 1024px)").matches) return;
|
||||
if (dom.advanced_options.classList.contains("hidden")) toggleAdvancedOptions();
|
||||
}
|
||||
@@ -0,0 +1,550 @@
|
||||
// Tradutor texto <-> Braille 100% no navegador.
|
||||
// Porte fiel de src/translation/{encoder,decoder,translator}.py (e dos limites de
|
||||
// src/web/schemas.py). encode(payload)/decode(payload) devolvem o mesmo objeto que
|
||||
// response.data devolvia em POST /api/encode e /api/decode.
|
||||
//
|
||||
// Tudo que o Python faz com str (code points, isalpha, isupper, rstrip...) e reproduzido aqui
|
||||
// de forma explicita; try/except do Python viram try/catch com a mesma granularidade.
|
||||
import {
|
||||
BRAZILIAN, NORTH_AMERICAN, BLANK, INITIAL_CELLS, FINAL_CELLS, TONE_CELLS, PUNCTUATION_CELLS,
|
||||
BUZZING_INITIALS, YU_INITIALS, ACCENTS, INITIAL_BY_CELL, FINAL_BY_CELL, FINAL_STANDALONE_BY_CELL,
|
||||
TONE_BY_CELL, PUNCTUATION_BY_CELL,
|
||||
} from "./braille_data.js";
|
||||
|
||||
export const MAX_TEXT_LENGTH = 5000;
|
||||
const ALPHABETS = ["Brazilian", "North American", "Chinese"];
|
||||
|
||||
// ---------- helpers que imitam o Python ----------
|
||||
|
||||
const PY_WHITESPACE = /[\t\n\v\f\r\x1c-\x1f \x85\xa0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]+$/;
|
||||
const rstrip = (s) => s.replace(PY_WHITESPACE, "");
|
||||
const chars = (s) => Array.from(s);
|
||||
|
||||
const RE_ALPHA = /^\p{L}$/u; // Python isalpha: categorias L*
|
||||
// Python isdigit/isnumeric usam Numeric_Type, que \p{Nd}/\p{N} nao cobrem sozinhos (ex.: ², ①, 一, 〇).
|
||||
// Faixas extras geradas a partir do unicodedata do Python 3.12 (Unicode 15).
|
||||
const DIGIT_EXTRA = [[0xb2,0xb3],[0xb9,0xb9],[0x1369,0x1371],[0x19da,0x19da],[0x2070,0x2070],[0x2074,0x2079],[0x2080,0x2089],[0x2460,0x2468],[0x2474,0x247c],[0x2488,0x2490],[0x24ea,0x24ea],[0x24f5,0x24fd],[0x24ff,0x24ff],[0x2776,0x277e],[0x2780,0x2788],[0x278a,0x2792],[0x10a40,0x10a43],[0x10e60,0x10e68],[0x11052,0x1105a],[0x1f100,0x1f10a]];
|
||||
const NUMERIC_EXTRA = [[0x3405,0x3405],[0x3483,0x3483],[0x382a,0x382a],[0x3b4d,0x3b4d],[0x4e00,0x4e00],[0x4e03,0x4e03],[0x4e07,0x4e07],[0x4e09,0x4e09],[0x4e5d,0x4e5d],[0x4e8c,0x4e8c],[0x4e94,0x4e94],[0x4e96,0x4e96],[0x4ebf,0x4ec0],[0x4edf,0x4edf],[0x4ee8,0x4ee8],[0x4f0d,0x4f0d],[0x4f70,0x4f70],[0x5104,0x5104],[0x5146,0x5146],[0x5169,0x5169],[0x516b,0x516b],[0x516d,0x516d],[0x5341,0x5341],[0x5343,0x5345],[0x534c,0x534c],[0x53c1,0x53c4],[0x56db,0x56db],[0x58f1,0x58f1],[0x58f9,0x58f9],[0x5e7a,0x5e7a],[0x5efe,0x5eff],[0x5f0c,0x5f0e],[0x5f10,0x5f10],[0x62fe,0x62fe],[0x634c,0x634c],[0x67d2,0x67d2],[0x6f06,0x6f06],[0x7396,0x7396],[0x767e,0x767e],[0x8086,0x8086],[0x842c,0x842c],[0x8cae,0x8cae],[0x8cb3,0x8cb3],[0x8d30,0x8d30],[0x9621,0x9621],[0x9646,0x9646],[0x964c,0x964c],[0x9678,0x9678],[0x96f6,0x96f6],[0xf96b,0xf96b],[0xf973,0xf973],[0xf978,0xf978],[0xf9b2,0xf9b2],[0xf9d1,0xf9d1],[0xf9d3,0xf9d3],[0xf9fd,0xf9fd],[0x20001,0x20001],[0x20064,0x20064],[0x200e2,0x200e2],[0x20121,0x20121],[0x2092a,0x2092a],[0x20983,0x20983],[0x2098c,0x2098c],[0x2099c,0x2099c],[0x20aea,0x20aea],[0x20afd,0x20afd],[0x20b19,0x20b19],[0x22390,0x22390],[0x22998,0x22998],[0x23b1b,0x23b1b],[0x2626d,0x2626d],[0x2f890,0x2f890]];
|
||||
const inRanges = (ranges, cp) => ranges.some(([lo, hi]) => cp >= lo && cp <= hi);
|
||||
const RE_ND = /^\p{Nd}$/u;
|
||||
const RE_N = /^\p{N}$/u;
|
||||
|
||||
const isAlpha = (c) => RE_ALPHA.test(c);
|
||||
const isDigit = (c) => RE_ND.test(c) || inRanges(DIGIT_EXTRA, c.codePointAt(0));
|
||||
const isNumeric = (c) => RE_N.test(c) || inRanges(NUMERIC_EXTRA, c.codePointAt(0));
|
||||
|
||||
const RE_UPPER = /^(?:\p{Lu}|\p{Uppercase})$/u;
|
||||
const RE_LOWER_OR_TITLE = /^(?:\p{Ll}|\p{Lowercase}|\p{Lt})$/u;
|
||||
|
||||
// str.isupper(): ha ao menos um caractere "cased" e nenhum minusculo/titlecase.
|
||||
function isUpper(s) {
|
||||
let cased = false;
|
||||
for (const c of s) {
|
||||
if (RE_LOWER_OR_TITLE.test(c)) return false;
|
||||
if (RE_UPPER.test(c)) cased = true;
|
||||
}
|
||||
return cased;
|
||||
}
|
||||
const charIsUpper = (c) => RE_UPPER.test(c) && !RE_LOWER_OR_TITLE.test(c);
|
||||
|
||||
// list[i] do Python: IndexError (excecao) fora do intervalo.
|
||||
function at(list, index) {
|
||||
if (index < 0 || index >= list.length) throw new RangeError("list index out of range");
|
||||
return list[index];
|
||||
}
|
||||
|
||||
// list.index(x): ValueError (excecao) se nao existir.
|
||||
function indexOrThrow(list, value, from = 0) {
|
||||
const i = list.indexOf(value, from);
|
||||
if (i === -1) throw new Error("value not in list");
|
||||
return i;
|
||||
}
|
||||
|
||||
// ---------- encoders ----------
|
||||
|
||||
export function encodeNorthAmerican(text) {
|
||||
let braille = "";
|
||||
for (const phrase of text.split("\n")) {
|
||||
const words = phrase.replaceAll('"', "'").split(" ");
|
||||
for (const word of words) {
|
||||
for (const letter of word) {
|
||||
try {
|
||||
const i = indexOrThrow(NORTH_AMERICAN.normal, letter.toLowerCase());
|
||||
braille += at(NORTH_AMERICAN.braille, i);
|
||||
} catch (e) { /* pass */ }
|
||||
}
|
||||
braille += " ";
|
||||
}
|
||||
braille = rstrip(braille) + "\n";
|
||||
}
|
||||
return rstrip(braille);
|
||||
}
|
||||
|
||||
export function encodeBrazilian(text) {
|
||||
let treated = "";
|
||||
for (const phrase of text.split("\n")) {
|
||||
for (const word of phrase.split(" ")) {
|
||||
const w = chars(word);
|
||||
for (let index = 0; index < w.length; index++) {
|
||||
const letter = w[index];
|
||||
let lastAlpha = false;
|
||||
let nextAlpha = false;
|
||||
if (index > 0) lastAlpha = isAlpha(w[index - 1]);
|
||||
if (index < w.length - 1) nextAlpha = isAlpha(w[index + 1]);
|
||||
if (lastAlpha && letter === "(") treated += " ";
|
||||
treated += letter;
|
||||
if (nextAlpha && letter === ")") treated += " ";
|
||||
}
|
||||
treated += " ";
|
||||
}
|
||||
treated = rstrip(treated) + "\n";
|
||||
}
|
||||
|
||||
let braille = "";
|
||||
for (const phrase of treated.split("\n")) {
|
||||
for (const word of phrase.split(" ")) {
|
||||
try {
|
||||
const w = chars(word);
|
||||
if (w.length === 0) throw new RangeError("string index out of range");
|
||||
const isNumber = isNumeric(w[0]);
|
||||
if (isNumber) braille += "⠼";
|
||||
const upperWord = isUpper(word);
|
||||
if (!isNumber && upperWord) braille += "⠨⠨";
|
||||
let lastLetter = null;
|
||||
for (const letter of w) {
|
||||
const i = indexOrThrow(BRAZILIAN.normal, letter.toLowerCase());
|
||||
if (!isNumber && isNumeric(letter)) braille += "⠼";
|
||||
if (charIsUpper(letter) && !upperWord) braille += "⠨";
|
||||
if (lastLetter) {
|
||||
if (isNumeric(lastLetter) && isAlpha(letter)) braille += "⠂";
|
||||
}
|
||||
braille += at(BRAZILIAN.braille, i);
|
||||
lastLetter = letter;
|
||||
}
|
||||
braille += " ";
|
||||
} catch (e) { /* pass */ }
|
||||
}
|
||||
braille = rstrip(braille) + "\n";
|
||||
}
|
||||
return rstrip(braille).replaceAll(" ", "⠀");
|
||||
}
|
||||
|
||||
// ---------- pinyin (porte do pypinyin 0.55: mmseg + TONE3 + neutro 5) ----------
|
||||
|
||||
let pinyinData = null; // { singles: {}, keys: string[] (ordenado UTF-16), diffs: Map }
|
||||
let pinyinPromise = null;
|
||||
|
||||
async function loadPinyinData() {
|
||||
if (pinyinData) return pinyinData;
|
||||
if (!pinyinPromise) {
|
||||
pinyinPromise = (async () => {
|
||||
const url = new URL("./pinyin_data.json", import.meta.url);
|
||||
let json;
|
||||
if (typeof process !== "undefined" && process.versions && process.versions.node && url.protocol === "file:") {
|
||||
const fs = await import("node:fs/promises");
|
||||
json = JSON.parse(await fs.readFile(url, "utf8"));
|
||||
} else {
|
||||
const res = await fetch(url);
|
||||
if (!res.ok) throw new Error("pinyin data unavailable");
|
||||
json = await res.json();
|
||||
}
|
||||
pinyinData = { singles: json.s, keys: json.k.split("\n"), diffs: new Map(Object.entries(json.d)) };
|
||||
return pinyinData;
|
||||
})().catch((err) => { pinyinPromise = null; throw err; });
|
||||
}
|
||||
return pinyinPromise;
|
||||
}
|
||||
|
||||
// Primeiro indice cuja chave >= word (ordem por unidades UTF-16, igual a do arquivo).
|
||||
function lowerBound(keys, word) {
|
||||
let lo = 0;
|
||||
let hi = keys.length;
|
||||
while (lo < hi) {
|
||||
const mid = (lo + hi) >> 1;
|
||||
if (keys[mid] < word) lo = mid + 1; else hi = mid;
|
||||
}
|
||||
return lo;
|
||||
}
|
||||
const isPhrase = (d, word) => { const i = lowerBound(d.keys, word); return i < d.keys.length && d.keys[i] === word; };
|
||||
const isPrefix = (d, word) => { const i = lowerBound(d.keys, word); return i < d.keys.length && d.keys[i].startsWith(word); };
|
||||
|
||||
// pypinyin.seg.mmseg.Seg.cut com seg = Seg(p_set, no_non_phrases=True) (modo estrito).
|
||||
function mmsegCut(d, text) {
|
||||
const out = [];
|
||||
const t = chars(text);
|
||||
let pos = 0;
|
||||
while (pos < t.length) {
|
||||
let lastValid = "";
|
||||
let lastValidIndex = 0;
|
||||
let broke = false;
|
||||
for (let index = 0; pos + index < t.length; index++) {
|
||||
const word = t.slice(pos, pos + index + 1).join("");
|
||||
if (isPrefix(d, word)) {
|
||||
if (isPhrase(d, word)) {
|
||||
lastValid = word;
|
||||
lastValidIndex = index + 1;
|
||||
}
|
||||
} else {
|
||||
if (lastValid) {
|
||||
out.push(lastValid);
|
||||
pos += lastValidIndex;
|
||||
} else {
|
||||
out.push(t[pos]);
|
||||
pos += 1;
|
||||
}
|
||||
broke = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!broke) {
|
||||
if (lastValid) {
|
||||
out.push(lastValid);
|
||||
pos += lastValidIndex;
|
||||
} else {
|
||||
// estrito: o resto nao e uma frase, sai caractere a caractere
|
||||
for (const c of t.slice(pos)) out.push(c);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function singleReading(d, han) {
|
||||
const r = d.singles[han];
|
||||
return r === undefined ? han : r;
|
||||
}
|
||||
|
||||
// pypinyin.pinyin(chunk, style=TONE3, neutral_tone_with_five=True) achatado e unido.
|
||||
function hanChunkToPinyin(d, chunk) {
|
||||
let out = "";
|
||||
for (const segment of mmsegCut(d, chunk)) {
|
||||
if (isPhrase(d, segment)) {
|
||||
const diff = d.diffs.get(segment);
|
||||
if (diff !== undefined) {
|
||||
out += diff.split(" ").join("");
|
||||
continue;
|
||||
}
|
||||
}
|
||||
for (const han of segment) out += singleReading(d, han);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const RE_HAN_TEST = /[一-鿿]/u;
|
||||
const RE_HAN_CHAR = /^[一-鿿]$/u;
|
||||
|
||||
async function hanziToPinyin(text) {
|
||||
const d = await loadPinyinData();
|
||||
const parts = [];
|
||||
const t = chars(text);
|
||||
if (t.length === 0) return "";
|
||||
let key = RE_HAN_CHAR.test(t[0]);
|
||||
let buffer = t[0];
|
||||
const flush = () => parts.push(key ? hanChunkToPinyin(d, buffer) : buffer);
|
||||
for (const c of t.slice(1)) {
|
||||
const k = RE_HAN_CHAR.test(c);
|
||||
if (k === key) buffer += c;
|
||||
else { flush(); key = k; buffer = c; }
|
||||
}
|
||||
flush();
|
||||
return parts.join("");
|
||||
}
|
||||
|
||||
// ---------- encoder chines ----------
|
||||
|
||||
function encodeWord(word) {
|
||||
const cells = [];
|
||||
let buffer = "";
|
||||
for (const ch of word) {
|
||||
if (PUNCTUATION_CELLS.has(ch)) {
|
||||
if (buffer) { cells.push(encodePinyin(buffer)); buffer = ""; }
|
||||
cells.push(PUNCTUATION_CELLS.get(ch));
|
||||
} else {
|
||||
buffer += ch;
|
||||
}
|
||||
}
|
||||
if (buffer) cells.push(encodePinyin(buffer));
|
||||
return cells.join("");
|
||||
}
|
||||
|
||||
function stripAccents(segment) {
|
||||
const plain = [];
|
||||
const tones = new Map();
|
||||
for (const ch of segment) {
|
||||
if (ACCENTS.has(ch)) {
|
||||
const [base, tone] = ACCENTS.get(ch);
|
||||
if (tone) tones.set(plain.length, tone);
|
||||
plain.push(base);
|
||||
} else {
|
||||
plain.push(ch);
|
||||
}
|
||||
}
|
||||
return [plain, tones];
|
||||
}
|
||||
|
||||
// plain e uma lista de caracteres (code points), como a str do Python.
|
||||
function parseSyllables(plain, tones) {
|
||||
const slice = (a, b) => plain.slice(a, b).join("");
|
||||
const result = [];
|
||||
let index = 0;
|
||||
const length = plain.length;
|
||||
while (index < length) {
|
||||
const ch = plain[index];
|
||||
if (ch === "'" || ch === "’" || ch === " " || isDigit(ch)) { index += 1; continue; }
|
||||
|
||||
const start = index;
|
||||
let initial = "";
|
||||
if (INITIAL_CELLS.has(slice(index, index + 2))) {
|
||||
initial = slice(index, index + 2);
|
||||
index += 2;
|
||||
} else if (INITIAL_CELLS.has(slice(index, index + 1))) {
|
||||
initial = plain[index];
|
||||
index += 1;
|
||||
}
|
||||
|
||||
let rest = slice(index, plain.length);
|
||||
if (YU_INITIALS.includes(initial) && chars(rest).slice(0, 1).join("") === "u") {
|
||||
rest = "ü" + chars(rest).slice(1).join("");
|
||||
}
|
||||
const restChars = chars(rest);
|
||||
|
||||
let final = "";
|
||||
for (let size = 4; size >= 1; size--) {
|
||||
const candidate = restChars.slice(0, size).join("");
|
||||
if (FINAL_CELLS.has(candidate)) {
|
||||
final = candidate;
|
||||
index += size;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
let tone = "";
|
||||
if (index < length && "012345".includes(plain[index])) {
|
||||
tone = plain[index];
|
||||
index += 1;
|
||||
}
|
||||
if (!tone) {
|
||||
for (let position = start; position < index; position++) {
|
||||
if (tones.has(position)) { tone = tones.get(position); break; }
|
||||
}
|
||||
}
|
||||
|
||||
if (!initial && !final) { index = start + 1; continue; }
|
||||
result.push([initial, final, tone]);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function encodePinyin(segment) {
|
||||
const [plain, tones] = stripAccents(segment);
|
||||
return parseSyllables(plain, tones).map(([i, f, t]) => encodeSyllable(i, f, t)).join("");
|
||||
}
|
||||
|
||||
function encodeSyllable(initial, final, tone) {
|
||||
let cells = "";
|
||||
if (BUZZING_INITIALS.includes(initial) && final === "i") {
|
||||
cells += INITIAL_CELLS.get(initial);
|
||||
} else if (initial === "d" && final === "e" && (tone === "" || tone === "5" || tone === "0")) {
|
||||
cells += INITIAL_CELLS.get("d");
|
||||
tone = "";
|
||||
} else {
|
||||
if (initial) cells += INITIAL_CELLS.get(initial);
|
||||
if (final) cells += FINAL_CELLS.get(final);
|
||||
}
|
||||
if (TONE_CELLS.has(tone)) cells += TONE_CELLS.get(tone);
|
||||
return cells;
|
||||
}
|
||||
|
||||
export async function encodeChinese(text) {
|
||||
if (RE_HAN_TEST.test(text)) text = await hanziToPinyin(text);
|
||||
return text.split("\n").map((line) => line.split(" ").map(encodeWord).join(BLANK)).join("\n");
|
||||
}
|
||||
|
||||
// ---------- decoders ----------
|
||||
|
||||
export function decodeNorthAmerican(braille) {
|
||||
let text = "";
|
||||
for (const phrase of braille.split("\n")) {
|
||||
const words = phrase.replaceAll('"', "'").split(" ");
|
||||
for (const word of words) {
|
||||
for (const letter of word) {
|
||||
try {
|
||||
const i = indexOrThrow(NORTH_AMERICAN.braille, letter);
|
||||
text += at(NORTH_AMERICAN.normal, i);
|
||||
} catch (e) { /* pass */ }
|
||||
}
|
||||
text += " ";
|
||||
}
|
||||
text = rstrip(text) + "\n";
|
||||
}
|
||||
return rstrip(text);
|
||||
}
|
||||
|
||||
export function decodeBrazilian(braille) {
|
||||
let text = "";
|
||||
for (const phrase of braille.split("\n")) {
|
||||
for (const word of phrase.split("⠀")) {
|
||||
try {
|
||||
let treated = word;
|
||||
if (word.length === 0) throw new RangeError("string index out of range");
|
||||
let isNumber = word[0] === "⠼";
|
||||
if (isNumber) treated = treated.slice(1);
|
||||
|
||||
if (word.startsWith("⠣⠄")) { text += "("; treated = treated.slice(2); }
|
||||
if (word.startsWith("⠷⠄")) { text += "["; treated = treated.slice(2); }
|
||||
if (word.endsWith("⠄⠜")) treated = treated.slice(0, -2);
|
||||
if (word.endsWith("⠄⠾")) treated = treated.slice(0, -2);
|
||||
|
||||
let isUpperCase = false;
|
||||
if (!isNumber && word.startsWith("⠨⠨")) {
|
||||
isUpperCase = true;
|
||||
treated = treated.slice(2);
|
||||
}
|
||||
|
||||
let lastLetter = null;
|
||||
for (const letter of treated) {
|
||||
if (letter === "⠠" || letter === "⠨") { lastLetter = letter; continue; }
|
||||
if (letter === "⠂" && lastLetter === "⠠") { text += "/"; continue; }
|
||||
if (letter === "⠴" && lastLetter === "⠸") { text += "%"; continue; }
|
||||
if (isNumber && letter === "⠂") { isNumber = false; continue; }
|
||||
|
||||
let index = BRAZILIAN.braille.indexOf(letter);
|
||||
if (index === -1) { lastLetter = letter; continue; }
|
||||
|
||||
if (isNumber) index = indexOrThrow(BRAZILIAN.braille.slice(38), letter) + 38;
|
||||
|
||||
if (isUpperCase || lastLetter === "⠨") text += at(BRAZILIAN.normal, index).toUpperCase();
|
||||
else text += at(BRAZILIAN.normal, index);
|
||||
lastLetter = letter;
|
||||
}
|
||||
|
||||
if (word.endsWith("⠄⠜")) text += ")";
|
||||
if (word.endsWith("⠄⠾")) text += "]";
|
||||
} catch (e) { /* pass */ }
|
||||
text += " ";
|
||||
}
|
||||
text = rstrip(text) + "\n";
|
||||
}
|
||||
return rstrip(text);
|
||||
}
|
||||
|
||||
const YU_FINALS = new Map([["ü", "u"], ["üe", "ue"], ["üan", "uan"], ["ün", "un"]]);
|
||||
const I_OR_YU_START = ["i", "ü"];
|
||||
|
||||
function matchPunctuation(w, index) {
|
||||
for (const size of [3, 2, 1]) {
|
||||
const chunk = w.slice(index, index + size).join("");
|
||||
if (PUNCTUATION_BY_CELL.has(chunk)) return [PUNCTUATION_BY_CELL.get(chunk), size];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function renderSyllable(initial, finalCell, tone) {
|
||||
if (initial && finalCell === null) {
|
||||
let syllable;
|
||||
if (BUZZING_INITIALS.includes(initial)) syllable = initial + "i";
|
||||
else if (initial === "d") syllable = "de";
|
||||
else syllable = initial;
|
||||
return syllable + tone;
|
||||
}
|
||||
if (finalCell === null) return tone;
|
||||
|
||||
if (!initial) {
|
||||
const f = FINAL_STANDALONE_BY_CELL.has(finalCell) ? FINAL_STANDALONE_BY_CELL.get(finalCell) : FINAL_BY_CELL.get(finalCell);
|
||||
return f + tone;
|
||||
}
|
||||
|
||||
let final = FINAL_BY_CELL.get(finalCell);
|
||||
if (I_OR_YU_START.includes(final[0])) {
|
||||
initial = ({ g: "j", k: "q", h: "x" })[initial] ?? initial;
|
||||
}
|
||||
if (YU_INITIALS.includes(initial) && YU_FINALS.has(final)) final = YU_FINALS.get(final);
|
||||
if (final === "o" && !["", "b", "p", "m", "f"].includes(initial)) final = "e";
|
||||
return initial + final + tone;
|
||||
}
|
||||
|
||||
function decodeWord(word) {
|
||||
const w = chars(word);
|
||||
let output = "";
|
||||
let index = 0;
|
||||
const length = w.length;
|
||||
while (index < length) {
|
||||
const punctuation = matchPunctuation(w, index);
|
||||
if (punctuation) { output += punctuation[0]; index += punctuation[1]; continue; }
|
||||
|
||||
const initial = INITIAL_BY_CELL.get(w[index]);
|
||||
const hasInitial = initial !== undefined;
|
||||
if (hasInitial) index += 1;
|
||||
|
||||
let finalCell = null;
|
||||
if (index < length && FINAL_BY_CELL.has(w[index])) { finalCell = w[index]; index += 1; }
|
||||
|
||||
let tone = "";
|
||||
if (index < length && TONE_BY_CELL.has(w[index])) { tone = TONE_BY_CELL.get(w[index]); index += 1; }
|
||||
|
||||
if (!hasInitial && finalCell === null) { index += 1; continue; }
|
||||
output += renderSyllable(initial || "", finalCell, tone);
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
export function decodeChinese(braille) {
|
||||
return braille.split("\n")
|
||||
.map((line) => line.split(BLANK).filter((word) => word).map(decodeWord).join(" "))
|
||||
.join("\n");
|
||||
}
|
||||
|
||||
// ---------- fachada (translator.py) ----------
|
||||
|
||||
export async function encodeText(text, alphabet = "North American") {
|
||||
switch (alphabet) {
|
||||
case "Brazilian": return encodeBrazilian(text);
|
||||
case "North American": return encodeNorthAmerican(text);
|
||||
case "Chinese": return encodeChinese(text);
|
||||
default: return "Alphabet not found.";
|
||||
}
|
||||
}
|
||||
|
||||
export function decodeText(braille, alphabet = "North American") {
|
||||
switch (alphabet) {
|
||||
case "Brazilian": return decodeBrazilian(braille);
|
||||
case "North American": return decodeNorthAmerican(braille);
|
||||
case "Chinese": return decodeChinese(braille);
|
||||
default: return "Alphabet not found.";
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- API compativel com POST /api/encode e /api/decode ----------
|
||||
|
||||
export class ValidationError extends Error {
|
||||
constructor(message) {
|
||||
super(message);
|
||||
this.name = "ValidationError";
|
||||
this.status = 422;
|
||||
}
|
||||
}
|
||||
|
||||
function validate(payload, field) {
|
||||
if (payload === null || typeof payload !== "object") throw new ValidationError("invalid payload");
|
||||
const value = payload[field];
|
||||
if (typeof value !== "string") throw new ValidationError(`${field}: string required`);
|
||||
if (chars(value).length > MAX_TEXT_LENGTH) throw new ValidationError(`${field}: at most ${MAX_TEXT_LENGTH} characters`);
|
||||
const alphabet = payload.alphabet;
|
||||
if (alphabet !== undefined && alphabet !== null && !ALPHABETS.includes(alphabet)) {
|
||||
throw new ValidationError("alphabet: invalid value");
|
||||
}
|
||||
return [value, alphabet ? alphabet : "North American"];
|
||||
}
|
||||
|
||||
/** @returns {Promise<{encoded: string}>} mesmo objeto de response.data de /api/encode */
|
||||
export async function encode(payload) {
|
||||
const [text, alphabet] = validate(payload, "text");
|
||||
return { encoded: await encodeText(text, alphabet) };
|
||||
}
|
||||
|
||||
/** @returns {Promise<{decoded: string}>} mesmo objeto de response.data de /api/decode */
|
||||
export async function decode(payload) {
|
||||
const [braille, alphabet] = validate(payload, "braille");
|
||||
return { decoded: decodeText(braille, alphabet) };
|
||||
}
|
||||
+49
-12
@@ -1,30 +1,67 @@
|
||||
export function showToast(message, severity = "info", duration = 4000) {
|
||||
import { getTranslation } from './i18n.js';
|
||||
|
||||
const ICONS = {
|
||||
info: "fa-circle-info",
|
||||
warning: "fa-triangle-exclamation",
|
||||
error: "fa-circle-xmark",
|
||||
success: "fa-circle-check"
|
||||
};
|
||||
|
||||
export function announce(msg) {
|
||||
const el = document.getElementById("sr_status");
|
||||
if (!el || !msg) return;
|
||||
el.textContent = "";
|
||||
setTimeout(() => { el.textContent = msg; }, 50);
|
||||
}
|
||||
|
||||
export function showToast(message, severity = "info", duration = 6000) {
|
||||
let container = document.getElementById("toast-container");
|
||||
if (!container) {
|
||||
container = document.createElement("div");
|
||||
container.id = "toast-container";
|
||||
container.setAttribute("aria-live", "polite");
|
||||
document.body.appendChild(container);
|
||||
}
|
||||
|
||||
const icons = {
|
||||
info: "fa-circle-info",
|
||||
warning: "fa-triangle-exclamation",
|
||||
error: "fa-circle-xmark",
|
||||
success: "fa-circle-check"
|
||||
};
|
||||
duration = Math.max(duration, 6000);
|
||||
|
||||
const toast = document.createElement("div");
|
||||
toast.className = `toast toast-${severity}`;
|
||||
toast.setAttribute("role", "alert");
|
||||
toast.innerHTML = `<i class="fas ${icons[severity] || icons.info}"></i><span>${message}</span>`;
|
||||
toast.setAttribute("role", severity === "error" ? "alert" : "status");
|
||||
|
||||
const icon = document.createElement("i");
|
||||
icon.className = `fas ${ICONS[severity] || ICONS.info}`;
|
||||
icon.setAttribute("aria-hidden", "true");
|
||||
const text = document.createElement("span");
|
||||
text.className = "toast__text";
|
||||
text.textContent = message;
|
||||
const close = document.createElement("button");
|
||||
close.type = "button";
|
||||
close.className = "toast__close";
|
||||
close.setAttribute("aria-label", getTranslation("toast_close") || "Close");
|
||||
close.innerHTML = '<span aria-hidden="true">×</span>';
|
||||
toast.append(icon, text, close);
|
||||
container.appendChild(toast);
|
||||
|
||||
requestAnimationFrame(() => toast.classList.add("show"));
|
||||
|
||||
setTimeout(() => {
|
||||
let timer = null;
|
||||
let removed = false;
|
||||
const dismiss = () => {
|
||||
if (removed) return;
|
||||
removed = true;
|
||||
clearTimeout(timer);
|
||||
toast.classList.remove("show");
|
||||
setTimeout(() => toast.remove(), 300);
|
||||
}, duration);
|
||||
};
|
||||
const start = () => { clearTimeout(timer); timer = setTimeout(dismiss, duration); };
|
||||
const pause = () => clearTimeout(timer);
|
||||
toast.addEventListener("mouseenter", pause);
|
||||
toast.addEventListener("mouseleave", start);
|
||||
toast.addEventListener("focusin", pause);
|
||||
toast.addEventListener("focusout", start);
|
||||
close.addEventListener("click", dismiss);
|
||||
start();
|
||||
return toast;
|
||||
}
|
||||
|
||||
export function highlightInput(inputTextbox) {
|
||||
|
||||
+41
-4
@@ -6,14 +6,28 @@ import { OrbitControls } from "three/addons/controls/OrbitControls.js";
|
||||
// After the model's 90° rotation this protrusion is along -Y, so any surface whose
|
||||
// Y is below (plate_front = minY + 0.65) belongs to a dot / orientation marker.
|
||||
const APPARENT_THICKNESS = 0.65;
|
||||
const PLATE_COLOR = new THREE.Color(0x8b5cf6); // purple
|
||||
const DOT_COLOR = new THREE.Color(0xf59e0b); // amber
|
||||
const PLATE_LIGHT = 0x3a5bd9;
|
||||
const PLATE_DARK = 0x5b78e8;
|
||||
const BG_LIGHT = 0xeef1f6;
|
||||
const BG_DARK = 0x151e30;
|
||||
const PLATE_COLOR = new THREE.Color(PLATE_LIGHT);
|
||||
const DOT_COLOR = new THREE.Color(0xf2a93b); // amber, same as the UI dots
|
||||
|
||||
const reduceMotion = () => !!(window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches);
|
||||
|
||||
function isDarkNow() {
|
||||
const t = document.documentElement.dataset.theme;
|
||||
if (t === "dark") return true;
|
||||
if (t === "light") return false;
|
||||
return !!(window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches);
|
||||
}
|
||||
|
||||
let state = null;
|
||||
|
||||
function init(container) {
|
||||
const scene = new THREE.Scene();
|
||||
scene.background = new THREE.Color(0xf3f4f6);
|
||||
scene.background = new THREE.Color(isDarkNow() ? BG_DARK : BG_LIGHT);
|
||||
PLATE_COLOR.set(isDarkNow() ? PLATE_DARK : PLATE_LIGHT);
|
||||
|
||||
const camera = new THREE.PerspectiveCamera(
|
||||
40,
|
||||
@@ -29,7 +43,8 @@ function init(container) {
|
||||
container.appendChild(renderer.domElement);
|
||||
|
||||
const controls = new OrbitControls(camera, renderer.domElement);
|
||||
controls.enableDamping = true;
|
||||
controls.enableDamping = !reduceMotion();
|
||||
controls.autoRotate = false;
|
||||
controls.dampingFactor = 0.08;
|
||||
|
||||
// Lighting
|
||||
@@ -100,6 +115,28 @@ function frameModel() {
|
||||
controls.update();
|
||||
}
|
||||
|
||||
// Recolors the vertices already painted with the plate color (dots keep amber).
|
||||
function repaintPlate() {
|
||||
if (!state || !state.mesh) return;
|
||||
const colors = state.mesh.geometry.getAttribute("color");
|
||||
const position = state.mesh.geometry.attributes.position;
|
||||
if (!colors) return;
|
||||
state.mesh.geometry.computeBoundingBox();
|
||||
const threshold = state.mesh.geometry.boundingBox.min.y + APPARENT_THICKNESS - 0.01;
|
||||
for (let i = 0; i < position.count; i++) {
|
||||
const c = position.getY(i) < threshold ? DOT_COLOR : PLATE_COLOR;
|
||||
colors.setXYZ(i, c.r, c.g, c.b);
|
||||
}
|
||||
colors.needsUpdate = true;
|
||||
}
|
||||
|
||||
window.setPreviewTheme = function (isDark) {
|
||||
PLATE_COLOR.set(isDark ? PLATE_DARK : PLATE_LIGHT);
|
||||
if (!state) return;
|
||||
state.scene.background = new THREE.Color(isDark ? BG_DARK : BG_LIGHT);
|
||||
repaintPlate();
|
||||
};
|
||||
|
||||
window.renderSTLPreview = function (arrayBuffer, resetCamera = false) {
|
||||
const container = document.getElementById("stl_preview_canvas");
|
||||
if (!container) { return; }
|
||||
|
||||
+851
-213
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,46 @@
|
||||
"""Gera public/modules/pinyin_data.json a partir do pypinyin (mesma versão do requirements.txt).
|
||||
|
||||
Uso: python3 scripts/gerar-dados-pinyin.py
|
||||
O JSON guarda o resultado já convertido para Style.TONE3 + neutral_tone_with_five,
|
||||
exatamente como o encoder Python chama pinyin(), para que o JS reproduza a saída.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
|
||||
from pypinyin import Style
|
||||
from pypinyin.constants import PHRASES_DICT
|
||||
from pypinyin.converter import UltimateConverter
|
||||
|
||||
conv = UltimateConverter(neutral_tone_with_five=True)
|
||||
|
||||
|
||||
def convert(words):
|
||||
return [p[0] for p in conv.convert(words, Style.TONE3, False, "default", True)]
|
||||
|
||||
|
||||
singles = {}
|
||||
for cp in range(0x4E00, 0xA000):
|
||||
ch = chr(cp)
|
||||
r = convert(ch)
|
||||
if r != [ch]:
|
||||
singles[ch] = r[0] if len(r) == 1 else " ".join(r)
|
||||
assert len(r) == 1, ch
|
||||
|
||||
# Frases: só guarda a leitura quando difere da concatenação das leituras individuais.
|
||||
diffs = {}
|
||||
for key in PHRASES_DICT:
|
||||
r = convert(key)
|
||||
per_char = []
|
||||
for ch in key:
|
||||
per_char.extend(convert(ch))
|
||||
if r != per_char:
|
||||
diffs[key] = " ".join(r)
|
||||
assert " " not in "".join(r)
|
||||
|
||||
keys = sorted(PHRASES_DICT.keys(), key=lambda s: s.encode("utf-16-be"))
|
||||
data = {"s": singles, "k": "\n".join(keys), "d": diffs}
|
||||
out = os.path.join(os.path.dirname(__file__), "..", "public", "modules", "pinyin_data.json")
|
||||
with open(out, "w", encoding="utf8") as fp:
|
||||
json.dump(data, fp, ensure_ascii=False, separators=(",", ":"))
|
||||
print(len(singles), len(keys), len(diffs), os.path.getsize(out))
|
||||
@@ -0,0 +1,156 @@
|
||||
#!/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 });
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
"""Lado Python do teste de paridade: executa o tradutor de referência (src/translation).
|
||||
|
||||
Uso: python3 scripts/paridade-tradutor.py casos.json saida.json
|
||||
casos.json: lista de {"op": "encode"|"decode", "alphabet": str, "input": str}
|
||||
saida.json: lista de strings (ou {"error": true}) na mesma ordem.
|
||||
O domínio/tradução não depende de VTK; só precisa de pypinyin (requirements.txt).
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
|
||||
from src.translation import translator # noqa: E402
|
||||
|
||||
|
||||
def run(case):
|
||||
try:
|
||||
fn = translator.encode if case["op"] == "encode" else translator.decode
|
||||
return fn(case["input"], case["alphabet"])
|
||||
except Exception:
|
||||
return {"error": True}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
with open(sys.argv[1], encoding="utf8") as fp:
|
||||
cases = json.load(fp)
|
||||
with open(sys.argv[2], "w", encoding="utf8") as fp:
|
||||
json.dump([run(c) for c in cases], fp, ensure_ascii=False)
|
||||
print(len(cases))
|
||||
Reference in new issue
Block a user