Recover InBraille from the production image (1.3.1) and move it to Gitea
Release / Plano (reaproveitar a imagem?) (push) Successful in 8s
CI / Trivy (dependências, segredos e configuração) (push) Failing after 8s
Release / ci (push) Failing after 9s
CI / Testes e imagem Docker (linux/arm64) (push) Skipped
Release / Publica a imagem (linux/arm64) (push) Skipped
Release / Cria a release no Gitea (push) Skipped
The GitHub account was suspended and the repository had no backup. The deployed code (src/, public/, index.html, main.py, requirements.txt) was extracted from the production image 1.3.1. The tests, Dockerfile, compose files, SECURITY.md, CHANGELOG.md and README were rebuilt from the records of the work sessions that created them; LICENSE, .gitignore, robots.txt and sitemap.xml were recreated. CI now runs on Gitea Actions. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
No files matched your search
@@ -0,0 +1,18 @@
|
||||
.git
|
||||
.gitea
|
||||
.gitattributes
|
||||
.env
|
||||
.env.*
|
||||
.venv
|
||||
venv
|
||||
__pycache__
|
||||
*.pyc
|
||||
.pytest_cache
|
||||
.vscode
|
||||
.idea
|
||||
docs
|
||||
*.md
|
||||
LICENSE
|
||||
docker-compose*.yaml
|
||||
.dockerignore
|
||||
scripts
|
||||
@@ -0,0 +1 @@
|
||||
* text=auto eol=lf
|
||||
@@ -0,0 +1,94 @@
|
||||
name: CI
|
||||
|
||||
# Documentação e configuração de ferramenta não mudam nada que a suíte teste.
|
||||
# Na main não roda por push: o release.yml é quem a chama, e só quando a imagem
|
||||
# precisa ser reconstruída; rodar nos dois repetiria a mesma suíte no mesmo commit.
|
||||
# Sem gatilho de pull_request: o push da branch já valida o mesmo commit, e os
|
||||
# dois juntos rodariam tudo duas vezes (o repositório não recebe PR de fork).
|
||||
#
|
||||
# A imagem é construída aqui uma única vez, em arm64 (a arquitetura do servidor),
|
||||
# testada e publicada como inputs-<hash>. Ao fazer o merge, o release encontra
|
||||
# essa tag e só aplica os nomes novos, sem rodar nem construir nada de novo.
|
||||
on:
|
||||
push:
|
||||
branches-ignore: [main]
|
||||
paths-ignore: ['**.md', 'LICENSE', '.claude/**', '.wolf/**', 'docs/**', 'docker-compose*.yaml', 'scripts/release-notes.sh']
|
||||
schedule:
|
||||
- cron: '0 9 * * 1' # toda segunda: reavalia com a base de vulnerabilidades nova
|
||||
workflow_call:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: ci-${{ gitea.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
# Trivy roda pela imagem oficial: o trivy-action clona o repositório do Trivy
|
||||
# do mesmo servidor do workflow, que aqui é o Gitea. O workspace do job não é
|
||||
# visível ao daemon, então os arquivos entram no container com `docker cp`.
|
||||
seguranca:
|
||||
name: Trivy (dependências, segredos e configuração)
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Repositório
|
||||
run: |
|
||||
cid=$(docker create --network host -v trivy-cache:/root/.cache/ -w /src aquasec/trivy:0.70.0 \
|
||||
fs --scanners vuln,secret,misconfig --severity HIGH,CRITICAL --exit-code 1 .)
|
||||
docker cp . "$cid:/src"
|
||||
docker start -a "$cid"
|
||||
status=$(docker inspect -f '{{.State.ExitCode}}' "$cid")
|
||||
docker rm "$cid" >/dev/null
|
||||
exit "$status"
|
||||
|
||||
imagem:
|
||||
name: Testes e imagem Docker (linux/arm64)
|
||||
needs: [seguranca]
|
||||
runs-on: ubuntu-24.04-arm
|
||||
timeout-minutes: 40
|
||||
env:
|
||||
REGISTRY: git.lucasrguerra.dev.br
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
# Conteúdo já publicado (re-push, tag num commit já validado): nada a fazer.
|
||||
- id: plano
|
||||
run: scripts/plano-imagem.sh "$REGISTRY" "${{ gitea.repository }}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
# pytest dentro do estágio `test` do Dockerfile: ele instala as dependências (VTK
|
||||
# incluído) uma vez, e as camadas ficam no daemon do runner para o build abaixo.
|
||||
- name: Testes (pytest)
|
||||
if: ${{ steps.plano.outputs.reuse != 'true' }}
|
||||
run: docker build --target test -t inbraille:test .
|
||||
|
||||
- name: Build
|
||||
if: ${{ steps.plano.outputs.reuse != 'true' }}
|
||||
run: docker build --target runtime --build-arg VERSION="${{ gitea.ref_name }}" --build-arg REVISION="${{ gitea.sha }}" -t inbraille:ci .
|
||||
|
||||
- name: Trivy na imagem
|
||||
if: ${{ steps.plano.outputs.reuse != 'true' }}
|
||||
run: |
|
||||
docker run --rm --network host -v trivy-cache:/root/.cache/ -e DOCKER_HOST=tcp://127.0.0.1:2375 aquasec/trivy:0.70.0 \
|
||||
image --severity HIGH,CRITICAL --ignore-unfixed --exit-code 1 inbraille:ci
|
||||
|
||||
- name: A imagem sobe e responde
|
||||
if: ${{ steps.plano.outputs.reuse != 'true' }}
|
||||
run: scripts/smoke-imagem.sh inbraille:ci
|
||||
|
||||
# O login fica por último: testes, build, Trivy e smoke não precisam de credencial.
|
||||
- if: ${{ steps.plano.outputs.reuse != 'true' }}
|
||||
uses: docker/login-action@v4
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ gitea.actor }}
|
||||
password: ${{ secrets.REGISTRY_TOKEN }}
|
||||
|
||||
# Passou em tudo: publica a mesma imagem que foi testada, sem reconstruir.
|
||||
- name: Publica inputs-<hash>
|
||||
if: ${{ steps.plano.outputs.reuse != 'true' }}
|
||||
run: |
|
||||
tag="${{ steps.plano.outputs.image }}:inputs-${{ steps.plano.outputs.inputs }}"
|
||||
docker tag inbraille:ci "$tag"
|
||||
docker push "$tag"
|
||||
@@ -0,0 +1,129 @@
|
||||
name: Release
|
||||
|
||||
# Publica a imagem no registro de containers do Gitea depois de um merge em main,
|
||||
# e de novo com tag semver quando uma tag v* é enviada. O servidor só faz pull.
|
||||
# Precisa do secret REGISTRY_TOKEN no repositório (token do Gitea com write:package):
|
||||
# o registro recusa o token do job.
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
tags: ['v*']
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
group: release
|
||||
cancel-in-progress: false
|
||||
|
||||
env:
|
||||
REGISTRY: git.lucasrguerra.dev.br
|
||||
|
||||
jobs:
|
||||
# A imagem só depende dos arquivos que entram no build, não da documentação nem
|
||||
# da configuração de ferramentas. O push da branch já a construiu, testou e
|
||||
# publicou como inputs-<hash>; quando essa tag existe (o caso normal de um
|
||||
# merge, uma tag num commit validado, um merge só de docs), não há o que
|
||||
# construir: as tags novas apontam para o manifesto existente.
|
||||
plano:
|
||||
name: Plano (reaproveitar a imagem?)
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
inputs: ${{ steps.plano.outputs.inputs }}
|
||||
reuse: ${{ steps.plano.outputs.reuse }}
|
||||
image: ${{ steps.plano.outputs.image }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- id: plano
|
||||
run: scripts/plano-imagem.sh "$REGISTRY" "${{ gitea.repository }}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
# Nada é publicado sem a suíte completa passar antes. Pulada quando a imagem é
|
||||
# reaproveitada: o mesmo conteúdo já passou por ela.
|
||||
ci:
|
||||
needs: plano
|
||||
if: ${{ needs.plano.outputs.reuse != 'true' }}
|
||||
uses: ./.gitea/workflows/ci.yml
|
||||
# Workflows reutilizáveis não herdam os secrets sozinhos: o login no registro precisa deles.
|
||||
secrets: inherit
|
||||
|
||||
publicar:
|
||||
name: Publica a imagem (linux/arm64)
|
||||
needs: [plano, ci]
|
||||
# ci é pulado, e não bem-sucedido, quando a imagem é reaproveitada.
|
||||
if: ${{ !cancelled() && needs.plano.result == 'success' && (needs.ci.result == 'success' || needs.plano.outputs.reuse == 'true') }}
|
||||
# O único runner é arm64 e o servidor de destino (Oracle) também, então a
|
||||
# imagem é construída nativamente, sem emulação.
|
||||
runs-on: ubuntu-24.04-arm
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
# Se o ci chamado acima acabou de publicar a imagem (push direto na main),
|
||||
# o plano lá de cima está desatualizado: confere de novo antes de construir.
|
||||
- id: replano
|
||||
run: scripts/plano-imagem.sh "$REGISTRY" "${{ gitea.repository }}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- uses: docker/setup-buildx-action@v4
|
||||
|
||||
- name: Autentica no registro
|
||||
uses: docker/login-action@v4
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ gitea.actor }}
|
||||
password: ${{ secrets.REGISTRY_TOKEN }}
|
||||
|
||||
- name: Metadados
|
||||
id: meta
|
||||
uses: docker/metadata-action@v6
|
||||
with:
|
||||
images: ${{ needs.plano.outputs.image }}
|
||||
tags: |
|
||||
type=semver,pattern={{version}}
|
||||
type=semver,pattern={{major}}.{{minor}}
|
||||
type=raw,value=latest
|
||||
type=sha,format=long
|
||||
|
||||
- name: Build e push
|
||||
if: ${{ steps.replano.outputs.reuse != 'true' }}
|
||||
uses: docker/build-push-action@v7
|
||||
with:
|
||||
context: .
|
||||
platforms: linux/arm64
|
||||
push: true
|
||||
tags: |
|
||||
${{ steps.meta.outputs.tags }}
|
||||
${{ needs.plano.outputs.image }}:inputs-${{ needs.plano.outputs.inputs }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
cache-from: type=registry,ref=${{ needs.plano.outputs.image }}:buildcache
|
||||
cache-to: type=registry,ref=${{ needs.plano.outputs.image }}:buildcache,mode=max
|
||||
|
||||
# Mesmo manifesto, nomes novos: nenhuma camada é lida nem escrita.
|
||||
- name: Aplica as tags à imagem existente
|
||||
if: ${{ steps.replano.outputs.reuse == 'true' }}
|
||||
run: |
|
||||
tags=$(jq -cr '.tags | map("-t " + .) | join(" ")' <<< '${{ steps.meta.outputs.json }}')
|
||||
docker buildx imagetools create $tags "${{ needs.plano.outputs.image }}:inputs-${{ needs.plano.outputs.inputs }}"
|
||||
|
||||
# Cria a entrada em "Releases" quando a execução é de uma tag v*. Roda depois
|
||||
# de publicar a imagem, com as notas da seção do CHANGELOG.md.
|
||||
release:
|
||||
name: Cria a release no Gitea
|
||||
needs: [plano, publicar]
|
||||
# Explícito, como o publicar: o ci acima é pulado quando a imagem é
|
||||
# reaproveitada, e o success() implícito pularia este job também.
|
||||
if: ${{ !cancelled() && needs.publicar.result == 'success' && startsWith(gitea.ref, 'refs/tags/v') }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: Release
|
||||
env:
|
||||
TAG: ${{ gitea.ref_name }}
|
||||
TOKEN: ${{ gitea.token }}
|
||||
API: ${{ gitea.server_url }}/api/v1/repos/${{ gitea.repository }}
|
||||
IMAGE: ${{ needs.plano.outputs.image }}
|
||||
run: |
|
||||
scripts/release-notes.sh "$TAG" "$IMAGE" > notes.md
|
||||
pre=false; case "$TAG" in *-*) pre=true ;; esac
|
||||
jq -n --arg tag "$TAG" --arg name "InBraille ${TAG#v}" --rawfile body notes.md --argjson pre "$pre" \
|
||||
'{tag_name:$tag, name:$name, body:$body, prerelease:$pre}' > release.json
|
||||
curl -fsS -X POST "$API/releases" -H "Authorization: token $TOKEN" \
|
||||
-H 'Content-Type: application/json' -d @release.json
|
||||
@@ -0,0 +1,29 @@
|
||||
# Local-only documentation (design specs, notes)
|
||||
docs/
|
||||
|
||||
# Environment and secrets
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
|
||||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
|
||||
# Virtual environments
|
||||
.venv/
|
||||
venv/
|
||||
env/
|
||||
|
||||
# Tests and tooling caches
|
||||
.pytest_cache/
|
||||
.coverage
|
||||
htmlcov/
|
||||
.mypy_cache/
|
||||
.ruff_cache/
|
||||
|
||||
# Editors and OS
|
||||
.vscode/
|
||||
.idea/
|
||||
.DS_Store
|
||||
@@ -0,0 +1,63 @@
|
||||
# Changelog
|
||||
|
||||
Everything notable in InBraille is recorded here. The format follows
|
||||
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project follows
|
||||
[Semantic Versioning](https://semver.org/).
|
||||
|
||||
> **Note on history.** The original Git history and the project files that are not part of
|
||||
> the container image were lost with the previous GitHub account. This repository was
|
||||
> rebuilt on 2026-11-02 from the production image `1.3.1` (the exact deployed code in `src/`,
|
||||
> `public/`, `index.html` and `main.py`) and from the records of the work sessions that created
|
||||
> the tests, the Dockerfile, the CI and the documentation. Entries for 1.2.0 and 1.3.0 left no
|
||||
> record and are described only by what the code shows.
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [1.3.2] - 2026-11-02
|
||||
|
||||
### Changed
|
||||
|
||||
- The code, the container image and the releases now live on Gitea (`git.lucasrguerra.dev.br`);
|
||||
the deployment pulls the image from its registry instead of GitHub Container Registry.
|
||||
- CI moved from GitHub Actions to the Gitea runners (`.gitea/workflows`): Trivy on the
|
||||
repository and on the image, the pytest suite in a Dockerfile `test` stage, an arm64 image build
|
||||
and a smoke test that exercises the pages, the SEO files, the API (including a real STL
|
||||
generation) and the production isolation (`--read-only`, no capabilities, non-root). The image is
|
||||
built once per content hash and reused by the release.
|
||||
- Dockerfile split into `base`, `test` and `runtime` stages; the runtime image is unchanged
|
||||
(Python 3.14, non-root user 10001, read-only friendly).
|
||||
- `SECURITY.md`: vulnerabilities are reported by e-mail instead of GitHub Security Advisories.
|
||||
- `.gitattributes` forces LF line endings.
|
||||
|
||||
### Fixed
|
||||
|
||||
- `/robots.txt` and `/sitemap.xml` returned **500** in production since the image never contained
|
||||
those files (the Dockerfile did not copy them). Both files are now part of the repository and the
|
||||
image, with the `hreflang` alternates for `pt-BR`, `en` and `zh`.
|
||||
|
||||
## [1.3.1]
|
||||
|
||||
- Fixed returning visitors running stale frontend code after a deploy: HTML and `/public` assets are now served with `Cache-Control: no-cache` so browsers revalidate them.
|
||||
- Release workflow now also pins `INBRAILLE_VERSION` for the Coolify preview environment, which was stuck on 1.1.0.
|
||||
|
||||
## [1.3.0] and [1.2.0]
|
||||
|
||||
No changelog was kept for these releases, so nothing is claimed here beyond what survived: the
|
||||
sources of the live plate preview (`public/preview.js`) and of the browser-side STL generator
|
||||
(`public/modules/client_stl_generator.js`) are part of the deployed code.
|
||||
|
||||
## [1.1.0]
|
||||
|
||||
- STL generation now goes through a bounded FIFO queue instead of rejecting requests when busy.
|
||||
|
||||
## [1.0.0]
|
||||
|
||||
- First tagged release, published as a Docker image on GitHub Container Registry.
|
||||
- Security hardening of the API and the container (see SECURITY.md).
|
||||
- Dependencies upgraded; all Trivy findings (critical, high and medium) resolved.
|
||||
|
||||
[Unreleased]: https://git.lucasrguerra.dev.br/lucasrguerra/inbraille/compare/v1.3.2...HEAD
|
||||
[1.3.2]: https://git.lucasrguerra.dev.br/lucasrguerra/inbraille/compare/v1.3.1...v1.3.2
|
||||
[1.3.1]: https://git.lucasrguerra.dev.br/lucasrguerra/inbraille/releases/tag/v1.3.1
|
||||
[1.1.0]: https://git.lucasrguerra.dev.br/lucasrguerra/inbraille/releases/tag/v1.1.0
|
||||
[1.0.0]: https://git.lucasrguerra.dev.br/lucasrguerra/inbraille/releases/tag/v1.0.0
|
||||
@@ -0,0 +1,67 @@
|
||||
# syntax=docker/dockerfile:1
|
||||
|
||||
# ── base: Python and the runtime libraries VTK needs (shared by test and runtime) ──
|
||||
FROM python:3.14-slim-trixie AS base
|
||||
|
||||
ENV PYTHONUNBUFFERED=1 \
|
||||
PYTHONDONTWRITEBYTECODE=1 \
|
||||
PIP_NO_CACHE_DIR=1 \
|
||||
PIP_DISABLE_PIP_VERSION_CHECK=1 \
|
||||
PORT=3000 \
|
||||
# The container is only reachable through the reverse proxy, so trust its X-Forwarded-For
|
||||
# (needed for per-client rate limiting).
|
||||
FORWARDED_ALLOW_IPS="*"
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Runtime libraries required by VTK.
|
||||
RUN apt-get update && apt-get upgrade -y && apt-get install -y --no-install-recommends \
|
||||
libgl1 \
|
||||
libglib2.0-0 \
|
||||
libsm6 \
|
||||
libxext6 \
|
||||
libxrender1 \
|
||||
libosmesa6 \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# ── test: `docker build --target test .` runs the pytest suite (used by CI) ──
|
||||
FROM base AS test
|
||||
COPY requirements.txt requirements-dev.txt pytest.ini ./
|
||||
# --prefer-binary: never compile from source (required on ARM64 where some wheels are missing)
|
||||
RUN pip install --prefer-binary -r requirements-dev.txt
|
||||
COPY main.py index.html google21a790a2c23c0ec5.html robots.txt sitemap.xml ./
|
||||
COPY src ./src
|
||||
COPY public ./public
|
||||
COPY tests ./tests
|
||||
RUN python -m pytest -q
|
||||
|
||||
# ── runtime: the image that ships ──
|
||||
FROM base AS runtime
|
||||
|
||||
ARG VERSION=dev
|
||||
ARG REVISION=unknown
|
||||
LABEL org.opencontainers.image.title="InBraille" \
|
||||
org.opencontainers.image.description="Text to Braille converter with STL export for 3D printing" \
|
||||
org.opencontainers.image.source="https://git.lucasrguerra.dev.br/lucasrguerra/inbraille" \
|
||||
org.opencontainers.image.licenses="MIT" \
|
||||
org.opencontainers.image.version="${VERSION}" \
|
||||
org.opencontainers.image.revision="${REVISION}"
|
||||
|
||||
COPY requirements.txt .
|
||||
# pip/setuptools (and the libraries vendored inside pip) are build tools: remove them from the runtime image.
|
||||
RUN pip install --prefer-binary -r requirements.txt \
|
||||
&& pip uninstall -y pip setuptools wheel
|
||||
|
||||
COPY main.py index.html google21a790a2c23c0ec5.html robots.txt sitemap.xml ./
|
||||
COPY src ./src
|
||||
COPY public ./public
|
||||
|
||||
RUN useradd --system --uid 10001 --no-create-home --shell /usr/sbin/nologin inbraille
|
||||
USER 10001
|
||||
|
||||
EXPOSE 3000
|
||||
|
||||
HEALTHCHECK --interval=30s --timeout=10s --start-period=20s --retries=3 \
|
||||
CMD ["python", "-c", "import os,urllib.request as u; u.urlopen('http://127.0.0.1:%s/' % os.environ.get('PORT','3000'), timeout=5)"]
|
||||
|
||||
CMD ["python", "main.py"]
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2025 Lucas Rayan Guerra
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,122 @@
|
||||
# InBraille
|
||||
|
||||
## Introduction
|
||||
|
||||
This repository contains the code for the InBraille project.
|
||||
|
||||
InBraille is an innovative Brazilian tool from Pernambuco that converts texts to Braille and exports them in both ASCII format and in STL plates for 3D printing. With this solution, it is possible to increase accessibility and inclusion, allowing anyone to create tactile materials for people with visual impairments.
|
||||
|
||||
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 signs and educational materials in Braille in an accessible and personalized way. 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 to those who need it.
|
||||
|
||||
### Supported Braille Alphabets:
|
||||
|
||||
- **Brazilian Braille** (with native warning regarding ambiguous characters)
|
||||
- **North American Braille**
|
||||
- **Chinese (Mandarin) Braille** (supporting Pinyin and Chinese characters input, with localized input assistance)
|
||||
|
||||
---
|
||||
|
||||
## Key Features
|
||||
|
||||
1. **Unified HTML Template**: Single, consolidated `index.html` structure served for all routes.
|
||||
2. **Dynamic Client-Side Localization (i18n)**: Fully translates the interface dynamically without page reloads across Portuguese, English, and Chinese.
|
||||
3. **Modular Frontend (SOLID Principles)**: Deconstructed frontend architecture divided into clean, single-responsibility ES Modules:
|
||||
- `state.js`: Centralized application state tracking.
|
||||
- `i18n.js`: Localized DOM translations and menu management.
|
||||
- `ui.js`: Reusable visual components (toasts, focus highlights).
|
||||
- `converter.js`: Conversion flows and line-length validators.
|
||||
- `stl.js`: 3D parameters control and STL file compiler.
|
||||
- `index.js`: Orchestrator entry point.
|
||||
4. **Standardized Premium UI Warnings**: Consistent, modern side-border alert cards for warnings and tips.
|
||||
|
||||
---
|
||||
|
||||
## Backend Architecture (`src/`)
|
||||
|
||||
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/`)
|
||||
Core representations and mathematical constants of the Braille system:
|
||||
- `alphabets.py`: Mappings for Brazilian and North American character-to-cell associations.
|
||||
- `chinese_braille.py`: Constants and lists representing tones, initial and final syllables, and punctuation for Chinese Braille.
|
||||
- `braille_codes.py`: Converts characters to 6-dot/8-dot binary matrices and Unicode Braille patterns.
|
||||
- `dimensions.py`: Defines dimensions of Braille cells (dot radius, height, horizontal and vertical spacing).
|
||||
|
||||
### 2. Translation Engine (`src/translation/`)
|
||||
Core encoders/decoders translating between text and Unicode Braille:
|
||||
- `translator.py`: Router that delegates request conversion depending on selected alphabet.
|
||||
- `encoder.py` / `decoder.py`: Translate between standard characters/Hanzi/Pinyin and Braille Unicode cells (PT/EN/ZH). The Chinese translation parses Chinese Hanzi or pinyin using `pypinyin` to analyze polyphonic contexts, compiling them into syllables (initial + final + tone combinations) according to official Chinese Braille rules.
|
||||
|
||||
### 3. 3D Modeling and Mesh Engine (`src/modeling/`)
|
||||
Decoupled geometry generation and composition system:
|
||||
- `mesh_engine.py`: Defines the abstract `MeshEngine` wrapper interface, decoupling layout modeling logic from the underlying 3D graphics library.
|
||||
- `model_builder.py`: Composites the physical shapes. Places plate bases, rounded borders, spherical dot caps, orientation markers, and orientation bars (in "dots only" mode).
|
||||
- `options.py`: Defines settings configuration (symbols per line, plate thickness, resolution).
|
||||
- `stl_service.py`: Standardizes generation inputs and exports binary STL models.
|
||||
|
||||
### 4. 3D Rendering & Serializer (`src/rendering/`)
|
||||
Concrete implementation of the graphics pipeline:
|
||||
- `vtk_mesh_engine.py`: VTK-based implementation of `MeshEngine` drawing cubes, spheres, cylinders, and sphere-cap clips.
|
||||
- `vtk_stl_serializer.py`: Serializes VTK PolyData objects into raw binary STL file format.
|
||||
|
||||
### 5. Web API Layers (`src/web/`)
|
||||
Web service routing and schemas:
|
||||
- `app.py`: Initiates the FastAPI application instance.
|
||||
- `api_routes.py`: Implements REST API controllers (`/api/encode`, `/api/decode`, `/api/to-stl`).
|
||||
- `schemas.py`: Pydantic request body schemas.
|
||||
- `page_routes.py`: Serves static assets and maps `/`, `/en`, and `/zh` requests dynamically to serve the root `index.html` template.
|
||||
|
||||
---
|
||||
|
||||
## Running the code
|
||||
|
||||
### Docker (recommended)
|
||||
|
||||
Tagged releases are published to the Gitea container registry (`linux/arm64`):
|
||||
|
||||
```bash
|
||||
docker run -d -p 3000:3000 --read-only --tmpfs /tmp --cap-drop ALL git.lucasrguerra.dev.br/lucasrguerra/inbraille:latest
|
||||
```
|
||||
|
||||
Pin a version (for example `:1.0.0`) in production. The service will be available at `http://localhost:3000`.
|
||||
|
||||
### From source
|
||||
|
||||
Requires Python 3.14.
|
||||
|
||||
```bash
|
||||
python -m venv .venv
|
||||
source .venv/bin/activate # Windows (PowerShell): .\.venv\Scripts\Activate.ps1
|
||||
pip install -r requirements-dev.txt
|
||||
python main.py
|
||||
pytest # run the test suite
|
||||
```
|
||||
|
||||
The API has the following endpoints:
|
||||
|
||||
- `/api/encode`: Translates a text to braille.
|
||||
- `/api/decode`: Translates a braille to text.
|
||||
- `/api/to-stl`: Exports the braille text to plate in STL format.
|
||||
|
||||
Requests are validated and rate limited; see [SECURITY.md](SECURITY.md) for the limits and for how to report a vulnerability.
|
||||
|
||||
## Releases
|
||||
|
||||
The code, the container image and the releases live on Gitea. CI (`.gitea/workflows`) runs on the Gitea runners:
|
||||
|
||||
- `ci.yml` (branches and every Monday): Trivy on the repository, the pytest suite inside the Dockerfile `test` stage, the arm64 image build, Trivy on the image and a smoke test (`scripts/smoke-imagem.sh`: pages, `robots.txt` and `sitemap.xml`, the encode/decode/STL API, security headers, read-only non-root container).
|
||||
- `release.yml` (`main` and `vX.Y.Z` tags): if the registry already holds the image for the same content (`inputs-<hash>`), nothing is rebuilt and only the new tags are applied. On a tag it creates the Gitea release with the [CHANGELOG](CHANGELOG.md) notes.
|
||||
|
||||
Image tags: `latest`, `X.Y.Z`, `X.Y` and `sha-<commit>`. To release: update the CHANGELOG, commit, then `git tag vX.Y.Z && git push gitea vX.Y.Z`.
|
||||
|
||||
---
|
||||
|
||||
[](https://skipthecad.com/generators/inbraille/)
|
||||
|
||||
## License and Credits
|
||||
|
||||
InBraille is released under the [MIT License](LICENSE). Anyone may use, modify and sell prints made with it.
|
||||
|
||||
Built with [FastAPI](https://fastapi.tiangolo.com/), [VTK](https://vtk.org/) and [pypinyin](https://github.com/mozillazg/python-pinyin). The Braille glyphs use the Noto Sans Symbols 2 font (SIL Open Font License).
|
||||
|
||||
Developed by [Lucas Rayan Guerra](https://git.lucasrguerra.dev.br/lucasrguerra) at [Ciência Embarcada](https://cienciaembarcada.com.br). Source: <https://git.lucasrguerra.dev.br/lucasrguerra/inbraille>.
|
||||
@@ -0,0 +1,16 @@
|
||||
# Security Policy
|
||||
|
||||
## Reporting a vulnerability
|
||||
|
||||
Please report vulnerabilities privately by e-mail to
|
||||
[contato@lucasrguerra.dev.br](mailto:contato@lucasrguerra.dev.br)
|
||||
instead of opening a public issue. You can expect an answer within a few days.
|
||||
|
||||
## Hardening in place
|
||||
|
||||
- Strict input validation: size, line count, alphabet, Braille-only characters for STL generation.
|
||||
- Cost budget for STL generation (filled cells × resolution), per-client rate limits and a bounded FIFO queue (2 running, up to 20 waiting, 3 per client, 60 s max wait; otherwise `503` with `Retry-After`).
|
||||
- Request body cap, no interactive API docs, generic error messages (details only in server logs).
|
||||
- Security headers (CSP, `nosniff`, `X-Frame-Options`, ...) and path-confined static file serving.
|
||||
- Container runs as a non-root user with a read-only filesystem and no capabilities.
|
||||
- Dependencies pinned, scanned with Trivy on every push and before every release (Gitea Actions).
|
||||
@@ -0,0 +1,9 @@
|
||||
services:
|
||||
app:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
ports:
|
||||
- "3000:3000"
|
||||
environment:
|
||||
PORT: "3000"
|
||||
@@ -0,0 +1,20 @@
|
||||
# Production: runs a published release image (used by Coolify). Pin the version with INBRAILLE_VERSION.
|
||||
# For local development use: docker compose -f docker-compose.dev.yaml up --build
|
||||
services:
|
||||
app:
|
||||
image: git.lucasrguerra.dev.br/lucasrguerra/inbraille:${INBRAILLE_VERSION:-latest}
|
||||
container_name: inbraille
|
||||
ports:
|
||||
- "3000"
|
||||
environment:
|
||||
PORT: "3000"
|
||||
read_only: true
|
||||
tmpfs:
|
||||
- /tmp
|
||||
cap_drop:
|
||||
- ALL
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
mem_limit: 3g
|
||||
pids_limit: 256
|
||||
restart: unless-stopped
|
||||
@@ -0,0 +1 @@
|
||||
google-site-verification: google21a790a2c23c0ec5.html
|
||||
@@ -0,0 +1,629 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="pt-BR">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>InBraille - Conversor de Texto para Braille e Impressão 3D STL | Acessibilidade Tátil</title>
|
||||
<meta name="description" content="Ferramenta brasileira pública e gratuita de tecnologia assistiva que converte texto em Braille e gera arquivos STL para impressão 3D de placas táteis inclusivas.">
|
||||
<meta name="keywords" content="braille, conversor de braille, braille para texto, texto para braille, impressão 3d braille, stl braille, tecnologia assistiva, inclusão visual, acessibilidade, ufrpe, etiquetas em braille, gerador de braille 3d, braille translator, 3d print braille, assistive technology">
|
||||
<meta name="author" content="Lucas Rayan Guerra">
|
||||
<meta name="creator" content="Lucas Rayan Guerra, Laboratório de Tecnologia 3D e Inclusiva - UFRPE">
|
||||
<meta name="publisher" content="Ciência Embarcada / InBraille">
|
||||
<meta name="application-name" content="InBraille">
|
||||
<meta name="robots" content="index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1">
|
||||
<meta name="theme-color" content="#3b82f6">
|
||||
<meta name="color-scheme" content="light">
|
||||
|
||||
<!-- Canonical and Internationalization (hreflang) -->
|
||||
<link rel="canonical" href="https://inbraille.cienciaembarcada.com.br/">
|
||||
<link rel="alternate" hreflang="pt-BR" href="https://inbraille.cienciaembarcada.com.br/">
|
||||
<link rel="alternate" hreflang="en" href="https://inbraille.cienciaembarcada.com.br/en">
|
||||
<link rel="alternate" hreflang="zh" href="https://inbraille.cienciaembarcada.com.br/zh">
|
||||
<link rel="alternate" hreflang="x-default" href="https://inbraille.cienciaembarcada.com.br/">
|
||||
|
||||
<!-- Open Graph / Facebook / WhatsApp / LinkedIn -->
|
||||
<meta property="og:type" content="website">
|
||||
<meta property="og:site_name" content="InBraille">
|
||||
<meta property="og:locale" content="pt_BR">
|
||||
<meta property="og:locale:alternate" content="en_US">
|
||||
<meta property="og:locale:alternate" content="zh_CN">
|
||||
<meta property="og:url" content="https://inbraille.cienciaembarcada.com.br/">
|
||||
<meta property="og:title" content="InBraille - Conversor de Texto para Braille e Modelagem 3D STL">
|
||||
<meta property="og:description" content="Ferramenta gratuita de utilidade pública para converter textos em Braille e gerar placas 3D em STL para impressão e inclusão de pessoas com deficiência visual.">
|
||||
<meta property="og:image" content="https://inbraille.cienciaembarcada.com.br/public/android-chrome-512x512.png">
|
||||
<meta property="og:image:secure_url" content="https://inbraille.cienciaembarcada.com.br/public/android-chrome-512x512.png">
|
||||
<meta property="og:image:type" content="image/png">
|
||||
<meta property="og:image:width" content="512">
|
||||
<meta property="og:image:height" content="512">
|
||||
<meta property="og:image:alt" content="Logotipo do InBraille - Conversor para Braille e STL">
|
||||
|
||||
<!-- Twitter Cards -->
|
||||
<meta name="twitter:card" content="summary_large_image">
|
||||
<meta name="twitter:title" content="InBraille - Conversor de Texto para Braille e Impressão 3D STL">
|
||||
<meta name="twitter:description" content="Converta texto para Braille e exporte modelos 3D STL prontos para impressão. Ferramenta pública e gratuita de acessibilidade tátil.">
|
||||
<meta name="twitter:image" content="https://inbraille.cienciaembarcada.com.br/public/android-chrome-512x512.png">
|
||||
|
||||
<!-- Favicons and PWA Manifest -->
|
||||
<link rel="icon" type="image/x-icon" href="/public/favicon.ico">
|
||||
<link rel="apple-touch-icon" sizes="180x180" href="/public/apple-touch-icon.png">
|
||||
<link rel="icon" type="image/png" sizes="32x32" href="/public/favicon-32x32.png">
|
||||
<link rel="icon" type="image/png" sizes="16x16" href="/public/favicon-16x16.png">
|
||||
<link rel="manifest" href="/public/site.webmanifest">
|
||||
|
||||
<!-- Fonts & Stylesheet Preloading -->
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link rel="preload" href="/public/fonts/NotoSansSymbols2-Braille.woff2" as="font" type="font/woff2" crossorigin>
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Noto+Sans+Symbols+2&display=swap">
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
|
||||
<link rel="stylesheet" href="/public/style.css">
|
||||
<script src="https://cdn.tailwindcss.com"></script>
|
||||
|
||||
<!-- Schema.org JSON-LD Structured Data -->
|
||||
<script type="application/ld+json">
|
||||
{
|
||||
"@context": "https://schema.org",
|
||||
"@graph": [
|
||||
{
|
||||
"@type": "WebApplication",
|
||||
"@id": "https://inbraille.cienciaembarcada.com.br/#webapp",
|
||||
"name": "InBraille",
|
||||
"alternateName": "InBraille Conversor e Modelador 3D",
|
||||
"url": "https://inbraille.cienciaembarcada.com.br/",
|
||||
"description": "Ferramenta pública e gratuita de tecnologia assistiva desenvolvida para converter texto em Braille e gerar arquivos STL para impressão 3D de placas e etiquetas táteis acessíveis.",
|
||||
"applicationCategory": "AccessibilityApplication, UtilitiesApplication, EducationalApplication",
|
||||
"operatingSystem": "All",
|
||||
"isAccessibleForFree": true,
|
||||
"offers": {
|
||||
"@type": "Offer",
|
||||
"price": "0",
|
||||
"priceCurrency": "BRL"
|
||||
},
|
||||
"inLanguage": ["pt-BR", "en", "zh"],
|
||||
"author": {
|
||||
"@type": "Person",
|
||||
"name": "Lucas Rayan Guerra",
|
||||
"url": "https://linkedin.com/in/lucasrguerra/"
|
||||
},
|
||||
"sourceOrganization": {
|
||||
"@type": "EducationalOrganization",
|
||||
"name": "Universidade Federal Rural de Pernambuco (UFRPE)",
|
||||
"department": "Departamento de Computação - Laboratório de Tecnologia 3D e Inclusiva"
|
||||
},
|
||||
"featureList": [
|
||||
"Conversão bidirecional: Texto para Braille e Braille para Texto",
|
||||
"Suporte aos alfabetos Braille Brasileiro, Norte-Americano e Chinês (com Pinyin e Hanzi)",
|
||||
"Geração paramétrica de arquivos 3D no formato STL prontos para fatiadores e impressão 3D",
|
||||
"Visualização 3D interativa no navegador via WebGL / Three.js",
|
||||
"Modo Apenas os Pontos (sem placa) para sobreposição em peças pré-existentes",
|
||||
"Customização de alinhamento, espessura, resolução e símbolos por linha",
|
||||
"Marcador de orientação espacial para leitura tátil correta"
|
||||
]
|
||||
},
|
||||
{
|
||||
"@type": "FAQPage",
|
||||
"@id": "https://inbraille.cienciaembarcada.com.br/#faq",
|
||||
"mainEntity": [
|
||||
{
|
||||
"@type": "Question",
|
||||
"name": "O que é o InBraille?",
|
||||
"acceptedAnswer": {
|
||||
"@type": "Answer",
|
||||
"text": "O InBraille é uma ferramenta brasileira, aberta e gratuita de utilidade pública desenvolvida para promover a acessibilidade e a inclusão social de pessoas com deficiência visual. Ele converte textos comuns para o sistema Braille e gera automaticamente modelos 3D no formato STL prontos para impressão 3D."
|
||||
}
|
||||
},
|
||||
{
|
||||
"@type": "Question",
|
||||
"name": "Como converter texto para Braille e gerar um modelo 3D STL?",
|
||||
"acceptedAnswer": {
|
||||
"@type": "Answer",
|
||||
"text": "Basta digitar ou colar seu texto na área de entrada, escolher o padrão de alfabeto desejado (Brasileiro, Norte-Americano ou Chinês) e clicar em 'Converter'. Em seguida, clique em 'Gerar e Visualizar STL' para pré-visualizar a placa em 3D e fazer o download do arquivo STL para sua impressora 3D."
|
||||
}
|
||||
},
|
||||
{
|
||||
"@type": "Question",
|
||||
"name": "O InBraille é gratuito para uso educacional e profissional?",
|
||||
"acceptedAnswer": {
|
||||
"@type": "Answer",
|
||||
"text": "Sim, o InBraille é uma ferramenta de código aberto e 100% gratuita, ideal para escolas, universidades, famílias, makers e instituições que necessitam criar materiais didáticos e sinalização tátil em Braille."
|
||||
}
|
||||
},
|
||||
{
|
||||
"@type": "Question",
|
||||
"name": "Quais alfabetos Braille são suportados?",
|
||||
"acceptedAnswer": {
|
||||
"@type": "Answer",
|
||||
"text": "O InBraille suporta o Braille Brasileiro (Português), o Braille Norte-Americano (Inglês) e o Braille Chinês (com conversão inteligente de Pinyin tonificado ou caracteres Hanzi)."
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
</script>
|
||||
</head>
|
||||
<body class="bg-gray-50 font-sans">
|
||||
<header class="bg-white shadow-md sticky top-0 z-10">
|
||||
<div class="max-w-6xl mx-auto px-4 py-4 flex justify-between items-center">
|
||||
<div class="flex items-center space-x-2">
|
||||
<a href="/" class="flex items-center space-x-2 text-2xl font-bold text-gray-800" aria-label="InBraille Início">
|
||||
<span class="text-blue-500 text-2xl braille-symbol" aria-hidden="true">⠎⠞⠇</span>
|
||||
<span>InBraille</span>
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center space-x-4">
|
||||
<details class="lang-menu relative" id="lang_dropdown">
|
||||
<summary class="flex items-center gap-2 bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-lg transition duration-200 cursor-pointer select-none">
|
||||
<i class="fas fa-globe"></i>
|
||||
<span id="current-lang-label">🇧🇷 Português</span>
|
||||
<i class="fas fa-chevron-down text-xs lang-caret transition-transform duration-200"></i>
|
||||
</summary>
|
||||
<div class="absolute right-0 mt-2 w-52 bg-white rounded-lg shadow-lg border border-gray-100 py-1 z-20 overflow-hidden">
|
||||
<button data-lang="pt-BR" class="w-full text-left flex items-center gap-3 px-4 py-2 text-gray-700 hover:bg-gray-50"><span class="text-lg">🇧🇷</span> Português</button>
|
||||
<button data-lang="en" class="w-full text-left flex items-center gap-3 px-4 py-2 text-gray-700 hover:bg-gray-50"><span class="text-lg">🇺🇸</span> English</button>
|
||||
<button data-lang="zh" class="w-full text-left flex items-center gap-3 px-4 py-2 text-gray-700 hover:bg-gray-50"><span class="text-lg">🇨🇳</span> 中文</button>
|
||||
</div>
|
||||
</details>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main class="max-w-6xl mx-auto px-4 py-8">
|
||||
<section class="bg-blue-50 rounded-xl p-6 mb-8">
|
||||
<div class="flex flex-col md:flex-row items-center">
|
||||
<div class="md:w-2/3 mb-6 md:mb-0">
|
||||
<h1 class="text-3xl sm:text-4xl font-extrabold text-gray-800 mb-4" data-i18n="hero_title">Transforme texto em Braille facilmente</h1>
|
||||
<p class="text-gray-600 mb-4 text-justify" data-i18n="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.
|
||||
</p>
|
||||
<a href="#conversor" class="bg-blue-500 hover:bg-blue-600 text-white px-6 py-3 rounded-lg font-medium transition duration-200 inline-block shadow-sm hover:shadow">
|
||||
<i class="fas fa-magic mr-2"></i><span data-i18n="try_now">Experimente agora</span>
|
||||
</a>
|
||||
</div>
|
||||
<div class="md:w-1/3 flex justify-center">
|
||||
<span class="braille-hero text-purple-600" style="
|
||||
font-size: 14rem;
|
||||
padding-bottom: 1rem;
|
||||
" aria-label="Símbolo Braille com 6 pontos táteis em formato circular">⠿</span>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
|
||||
<section id="conversor" class="bg-white rounded-xl shadow-md p-6 mb-8">
|
||||
<h2 class="text-2xl font-bold text-gray-800 mb-6 text-center" data-i18n="converter_title">Conversor</h2>
|
||||
|
||||
<div class="flex border-b mb-6">
|
||||
<button class="tab-active py-2 px-4 mr-2" id="text_to_braille_tab">
|
||||
<i class="fas fa-text-width mr-2"></i><span data-i18n="tab_text_to_braille">Texto → Braille</span>
|
||||
</button>
|
||||
<button class="py-2 px-4 text-gray-600" id="braille_to_text_tab">
|
||||
<span class="mr-2 braille-symbol" aria-hidden="true">⠿</span><span data-i18n="tab_braille_to_text">Braille → Texto</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="mb-6">
|
||||
<label class="block text-gray-700 font-medium mb-2" data-i18n="alphabet_label">Alfabeto Braille</label>
|
||||
<div class="flex flex-wrap gap-4">
|
||||
<div class="flex items-center" id="option_brazilian_container">
|
||||
<input
|
||||
type="radio"
|
||||
id="brazilian"
|
||||
name="alphabet"
|
||||
value="Brazilian"
|
||||
checked
|
||||
class="mr-2"
|
||||
>
|
||||
<label for="brazilian" data-i18n="alphabet_brazilian">Brasileiro</label>
|
||||
</div>
|
||||
<div class="flex items-center" id="option_north_american_container">
|
||||
<input
|
||||
type="radio"
|
||||
id="north-american"
|
||||
name="alphabet"
|
||||
value="North American"
|
||||
class="mr-2"
|
||||
>
|
||||
<label for="north-american" data-i18n="alphabet_north_american">Norte Americano</label>
|
||||
</div>
|
||||
<div class="flex items-center" id="option_chinese_container">
|
||||
<input
|
||||
type="radio"
|
||||
id="chinese"
|
||||
name="alphabet"
|
||||
value="Chinese"
|
||||
class="mr-2"
|
||||
>
|
||||
<label for="chinese" data-i18n="alphabet_chinese">Chinês</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="bg-blue-50 border-l-4 border-blue-400 p-3 mt-3 rounded-r-lg hidden" id="chinese_input_tip_container">
|
||||
<p class="text-sm text-blue-700 text-justify">
|
||||
<i class="fas fa-keyboard mr-1"></i>
|
||||
<span data-i18n="chinese_input_tip">您可以输入带声调数字的拼音(如 ni3 hao3)或中文汉字(如 你好)。系统会自动识别并转换。词与词之间请用空格分隔。</span>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="bg-amber-50 border-l-4 border-amber-400 p-3 mt-3 rounded-r-lg hidden" id="warning">
|
||||
<p class="text-sm text-amber-700 text-justify">
|
||||
<i class="fas fa-exclamation-triangle mr-1"></i>
|
||||
<span data-i18n="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 "ç".</span>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid md:grid-cols-2 gap-6 mb-6">
|
||||
<div class="text-area-container border-2 border-gray-200 rounded-lg p-4">
|
||||
<label for="input_text" id="input_label">
|
||||
<i class="fas fa-pen-alt mr-1"></i>
|
||||
Digite seu texto
|
||||
</label>
|
||||
|
||||
<textarea
|
||||
class="w-full h-40 p-2 focus:outline-none resize-none braille-text"
|
||||
id="input_text"
|
||||
placeholder="Digite o texto que deseja converter para Braille..."
|
||||
></textarea>
|
||||
|
||||
<div class="flex justify-between items-center mt-2">
|
||||
<button class="text-blue-500 hover:text-blue-700 text-sm" id="clear_button">
|
||||
<i class="fas fa-eraser mr-1"></i><span data-i18n="clear_button">Limpar</span>
|
||||
</button>
|
||||
<span class="text-gray-500 text-sm" id="char_count">0 caracteres</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="text-area-container border-2 border-gray-200 rounded-lg p-4">
|
||||
<label for="output_text" id="output_label">
|
||||
<span class="mr-1 braille-symbol" aria-hidden="true">⠿</span>
|
||||
Resultado em Braille
|
||||
</label>
|
||||
|
||||
<textarea
|
||||
class="w-full h-40 p-2 focus:outline-none resize-none braille-text"
|
||||
id="output_text"
|
||||
readonly
|
||||
placeholder="O resultado em Braille aparecerá aqui..."
|
||||
></textarea>
|
||||
|
||||
<div class="flex justify-end space-x-2 mt-2">
|
||||
<button class="bg-gray-200 hover:bg-gray-300 text-gray-700 px-3 py-1 rounded text-sm" id="copy_button">
|
||||
<i class="fas fa-copy mr-1"></i><span id="copy_button_text" data-i18n="copy_button">Copiar</span>
|
||||
</button>
|
||||
<button class="bg-blue-500 hover:bg-blue-600 text-white px-3 py-1 rounded text-sm" id="save_button">
|
||||
<i class="fas fa-download mr-1"></i><span data-i18n="save_button">Salvar</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="text-center mb-8">
|
||||
<button class="bg-green-500 hover:bg-green-600 text-white px-8 py-3 rounded-lg font-medium text-lg transition duration-200" id="convert_button">
|
||||
<i class="fas fa-exchange-alt mr-2"></i><span data-i18n="convert_button">Converter</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="border-t pt-6">
|
||||
<h3 class="text-xl font-bold text-gray-800 mb-4 text-center" data-i18n="export_3d_title">Exportar para Impressão 3D</h3>
|
||||
|
||||
<div id="stl-alert" class="bg-amber-50 border-l-4 border-amber-400 p-4 mb-6 rounded-r-lg fade-in">
|
||||
<div class="flex">
|
||||
<div class="flex-shrink-0">
|
||||
<i class="fas fa-info-circle text-amber-500 text-xl"></i>
|
||||
</div>
|
||||
<div class="ml-3">
|
||||
<p class="text-sm text-amber-700 text-justify">
|
||||
<span class="font-semibold text-justify" data-i18n="compass_alert_title">Atenção:</span>
|
||||
<span data-i18n="stl_alert_text">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.</span>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="bg-blue-50 border-l-4 border-blue-400 p-4 mb-6 rounded-r-lg">
|
||||
<div class="flex">
|
||||
<div class="flex-shrink-0">
|
||||
<i class="fas fa-compass text-blue-500 text-xl"></i>
|
||||
</div>
|
||||
<div class="ml-3">
|
||||
<p class="text-sm text-blue-700 text-justify">
|
||||
<span class="font-semibold" data-i18n="compass_alert_title">Indicador de orientação:</span>
|
||||
<span data-i18n="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.</span>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="text-center mb-6">
|
||||
<button class="bg-purple-500 hover:bg-purple-600 text-white px-8 py-3 rounded-lg font-medium text-lg transition duration-200" id="stl_button">
|
||||
<i class="fas fa-cube mr-2"></i><span id="stl_button_text" data-i18n="stl_button">Gerar e Visualizar STL</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div id="stl_preview" class="hidden mb-6 fade-in">
|
||||
<div class="flex flex-col sm:flex-row justify-between items-start sm:items-center mb-3 gap-2">
|
||||
<h4 class="text-lg font-medium text-gray-700">
|
||||
<i class="fas fa-cube mr-2 text-purple-500"></i><span data-i18n="stl_preview_title">Pré-visualização 3D</span>
|
||||
</h4>
|
||||
<button class="bg-green-500 hover:bg-green-600 text-white px-5 py-2 rounded-lg font-medium transition duration-200" id="download_stl_button">
|
||||
<i class="fas fa-download mr-2"></i><span data-i18n="download_stl_button">Baixar STL</span>
|
||||
</button>
|
||||
</div>
|
||||
<div id="stl_preview_canvas" class="w-full h-96 rounded-lg overflow-hidden border border-gray-200 bg-gray-100"></div>
|
||||
<p class="text-xs text-gray-500 mt-2 text-center" data-i18n="preview_instructions">
|
||||
Arraste para girar, role para dar zoom.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="bg-gray-50 rounded-lg p-4">
|
||||
<div class="flex justify-between items-center cursor-pointer" id="advanced_options_toggle">
|
||||
<h4 class="text-lg font-medium text-gray-700">
|
||||
<i class="fas fa-cog mr-2"></i><span data-i18n="advanced_options_title">Opções Avançadas</span>
|
||||
</h4>
|
||||
<i class="fas fa-chevron-down transition-transform duration-200" id="advanced_options_arrow"></i>
|
||||
</div>
|
||||
|
||||
<div class="mt-4 hidden" id="advanced_options">
|
||||
<div class="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
|
||||
<div class="bg-white p-4 rounded-lg shadow-sm ring-1 ring-purple-100 md:col-span-2 lg:col-span-3">
|
||||
<div class="flex justify-between items-center mb-2">
|
||||
<label class="font-medium" data-i18n="points_only_title">
|
||||
Apenas os Pontos (sem placa)
|
||||
</label>
|
||||
<label class="switch">
|
||||
<input type="checkbox" id="input_points_only">
|
||||
<span class="slider"></span>
|
||||
</label>
|
||||
</div>
|
||||
<p class="text-sm text-gray-500 text-justify" data-i18n="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.</p>
|
||||
</div>
|
||||
|
||||
<div class="bg-white p-4 rounded-lg shadow-sm">
|
||||
<div class="flex justify-between items-center mb-2">
|
||||
<label class="font-medium" data-i18n="separate_plates_title">Placas Separadas</label>
|
||||
<label class="switch">
|
||||
<input type="checkbox" id="input_separate_plates">
|
||||
<span class="slider"></span>
|
||||
</label>
|
||||
</div>
|
||||
<p class="text-sm text-gray-500" data-i18n="separate_plates_desc">Cada linha em uma placa separada</p>
|
||||
</div>
|
||||
|
||||
<div class="bg-white p-4 rounded-lg shadow-sm">
|
||||
<div class="flex justify-between items-center mb-2">
|
||||
<label class="font-medium" data-i18n="rounded_edges_title">Bordas Arredondadas</label>
|
||||
<label class="switch">
|
||||
<input type="checkbox" id="input_rounded">
|
||||
<span class="slider"></span>
|
||||
</label>
|
||||
</div>
|
||||
<p class="text-sm text-gray-500" data-i18n="rounded_edges_desc">Cantos arredondados nas placas</p>
|
||||
</div>
|
||||
|
||||
<div class="bg-white p-4 rounded-lg shadow-sm">
|
||||
<label class="font-medium block mb-2" data-i18n="text_alignment_title">Alinhamento do Texto</label>
|
||||
<select
|
||||
id="select_text_alignment"
|
||||
class="w-full p-2 border rounded"
|
||||
>
|
||||
<option value="center" data-i18n="align_center">Centro</option>
|
||||
<option value="left" data-i18n="align_left">Esquerda</option>
|
||||
<option value="right" data-i18n="align_right">Direita</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div class="bg-white p-4 rounded-lg shadow-sm">
|
||||
<label class="font-medium block mb-2" data-i18n="symbols_per_line_title">Símbolos por Linha</label>
|
||||
<input
|
||||
type="number"
|
||||
id="input_symbols_per_line"
|
||||
class="w-full p-2 border rounded"
|
||||
min="8"
|
||||
max="50"
|
||||
value="22"
|
||||
>
|
||||
<p class="text-xs text-gray-500 mt-1">
|
||||
<span id="symbols_per_line_desc_prefix" data-i18n="symbols_per_line_desc_prefix">Valor entre 8 e 50 (largura da placa: </span>
|
||||
<span id="plate_width">0</span>
|
||||
<span id="symbols_per_line_desc_suffix" data-i18n="symbols_per_line_desc_suffix"> mm)</span>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="bg-white p-4 rounded-lg shadow-sm">
|
||||
<label class="font-medium block mb-2" data-i18n="plate_thickness_title">Espessura da Placa (mm)</label>
|
||||
<input
|
||||
type="number"
|
||||
id="input_plate_thickness"
|
||||
class="w-full p-2 border rounded"
|
||||
min="2"
|
||||
max="100"
|
||||
value="3"
|
||||
>
|
||||
<p class="text-xs text-gray-500 mt-1" data-i18n="plate_thickness_desc">Valor entre 2 e 100</p>
|
||||
</div>
|
||||
|
||||
<div class="bg-white p-4 rounded-lg shadow-sm">
|
||||
<label class="font-medium block mb-2" data-i18n="point_resolution_title">Resolução dos Pontos</label>
|
||||
<input
|
||||
type="number"
|
||||
id="input_resolution"
|
||||
class="w-full p-2 border rounded"
|
||||
min="15"
|
||||
max="50"
|
||||
value="20"
|
||||
>
|
||||
<p class="text-xs text-gray-500 mt-1" data-i18n="point_resolution_desc">Valor entre 15 e 50</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="bg-white rounded-xl shadow-md p-6 mb-8">
|
||||
<h2 class="text-2xl font-bold text-gray-800 mb-4" data-i18n="about_title">Sobre o InBraille</h2>
|
||||
|
||||
<div class="prose max-w-none">
|
||||
<p class="mb-4 text-justify" data-i18n="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.
|
||||
</p>
|
||||
|
||||
<p class="mb-4 text-justify" data-i18n="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.
|
||||
</p>
|
||||
|
||||
<p class="mb-4 text-justify" data-i18n="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.
|
||||
</p>
|
||||
|
||||
<p class="mb-4 text-justify" data-i18n="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.
|
||||
</p>
|
||||
|
||||
<div class="bg-indigo-50 rounded-lg p-4 mb-4 border-l-4 border-indigo-400">
|
||||
<div class="flex items-start">
|
||||
<div class="flex-shrink-0">
|
||||
<div class="neurodiversity-badge text-white rounded-full p-2">
|
||||
<i class="fas fa-brain text-xl"></i>
|
||||
</div>
|
||||
</div>
|
||||
<div class="ml-3">
|
||||
<h3 class="text-lg font-semibold text-indigo-800" data-i18n="neurodiversity_title">Neurodiversidade na Tecnologia</h3>
|
||||
|
||||
<p class="text-gray-700 mt-2 text-justify" data-i18n="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.
|
||||
</p>
|
||||
|
||||
<p class="text-gray-700 mt-2 text-justify" data-i18n="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.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="bg-blue-50 p-4 rounded-lg mt-6 border-l-4 border-blue-400">
|
||||
<h3 class="font-bold text-lg mb-2 flex items-center">
|
||||
<i class="fas fa-book mr-2 text-blue-600"></i> <span data-i18n="learn_more_title">Saiba mais</span>
|
||||
</h3>
|
||||
<p class="text-justify">
|
||||
<span data-i18n="learn_more_p1">Veja mais sobre essa ferramenta na página dela no</span>
|
||||
<a href="https://cienciaembarcada.com.br/inbraille/" target="_blank" rel="noopener noreferrer" class="text-blue-600 hover:underline">
|
||||
Ciência Embarcada <i class="fas fa-external-link-alt ml-1 text-sm"></i>
|
||||
</a>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="bg-white rounded-xl shadow-md p-6 mb-8" id="faq">
|
||||
<h2 class="text-2xl font-bold text-gray-800 mb-6 flex items-center">
|
||||
<i class="fas fa-question-circle text-blue-500 mr-2"></i>
|
||||
<span>Perguntas Frequentes (FAQ)</span>
|
||||
</h2>
|
||||
|
||||
<div class="space-y-4">
|
||||
<details class="faq-item border border-gray-200 rounded-lg p-4 group" open>
|
||||
<summary class="flex justify-between items-center cursor-pointer font-semibold text-gray-800 select-none">
|
||||
<span>O que é o InBraille e para que serve?</span>
|
||||
<i class="fas fa-chevron-down text-blue-500 text-sm faq-chevron transition-transform duration-200"></i>
|
||||
</summary>
|
||||
<p class="mt-3 text-gray-600 text-justify">
|
||||
O InBraille é uma ferramenta brasileira, gratuita e de código aberto voltada para a acessibilidade. Ele converte textos comuns para o sistema Braille e gera automaticamente modelos 3D no formato STL prontos para fatiadores e impressão 3D de placas, sinalizações e etiquetas táteis.
|
||||
</p>
|
||||
</details>
|
||||
|
||||
<details class="faq-item border border-gray-200 rounded-lg p-4 group">
|
||||
<summary class="flex justify-between items-center cursor-pointer font-semibold text-gray-800 select-none">
|
||||
<span>Como exportar e imprimir Braille em uma impressora 3D?</span>
|
||||
<i class="fas fa-chevron-down text-blue-500 text-sm faq-chevron transition-transform duration-200"></i>
|
||||
</summary>
|
||||
<p class="mt-3 text-gray-600 text-justify">
|
||||
Digite seu texto no conversor, clique em <strong>Converter</strong> e em seguida em <strong>Gerar e Visualizar STL</strong>. Você pode inspecionar o modelo interativamente em 3D, ajustar parâmetros como espessura da placa e modo "Apenas os Pontos", e clicar em <strong>Baixar STL</strong> para salvar o arquivo pronto para seu fatiador 3D (como Cura ou PrusaSlicer).
|
||||
</p>
|
||||
</details>
|
||||
|
||||
<details class="faq-item border border-gray-200 rounded-lg p-4 group">
|
||||
<summary class="flex justify-between items-center cursor-pointer font-semibold text-gray-800 select-none">
|
||||
<span>O InBraille é gratuito para escolas, universidades e projetos sociais?</span>
|
||||
<i class="fas fa-chevron-down text-blue-500 text-sm faq-chevron transition-transform duration-200"></i>
|
||||
</summary>
|
||||
<p class="mt-3 text-gray-600 text-justify">
|
||||
Sim, 100% gratuito e livre! O projeto foi criado com foco em utilidade pública e impacto social para democratizar a criação de recursos didáticos e sinalização inclusiva por educadores, profissionais e entusiastas da cultura maker.
|
||||
</p>
|
||||
</details>
|
||||
|
||||
<details class="faq-item border border-gray-200 rounded-lg p-4 group">
|
||||
<summary class="flex justify-between items-center cursor-pointer font-semibold text-gray-800 select-none">
|
||||
<span>Quais alfabetos Braille são suportados?</span>
|
||||
<i class="fas fa-chevron-down text-blue-500 text-sm faq-chevron transition-transform duration-200"></i>
|
||||
</summary>
|
||||
<p class="mt-3 text-gray-600 text-justify">
|
||||
O sistema conta com suporte a três convenções: o <strong>Alfabeto Brasileiro</strong> (com normas do Ministério da Educação), o <strong>Norte-Americano</strong> (English Braille) e o <strong>Chinês</strong> (com suporte a conversão automática de Pinyin numerado e caracteres Hanzi).
|
||||
</p>
|
||||
</details>
|
||||
|
||||
<details class="faq-item border border-gray-200 rounded-lg p-4 group">
|
||||
<summary class="flex justify-between items-center cursor-pointer font-semibold text-gray-800 select-none">
|
||||
<span>Por que existe um indicador de orientação na peça 3D?</span>
|
||||
<i class="fas fa-chevron-down text-blue-500 text-sm faq-chevron transition-transform duration-200"></i>
|
||||
</summary>
|
||||
<p class="mt-3 text-gray-600 text-justify">
|
||||
Para evitar que a peça tátil seja colada ou lida de cabeça para baixo, cada placa gerada inclui uma marca de referência geométrica no canto inferior esquerdo (ou uma barra inferior no modo apenas pontos). Mantendo essa marca para baixo e à esquerda, garante-se que a leitura do Braille seja perfeitamente fiel.
|
||||
</p>
|
||||
</details>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
<footer class="bg-gray-800 text-white py-8">
|
||||
<div class="max-w-6xl mx-auto px-4">
|
||||
<div class="flex flex-col md:flex-row justify-between items-center">
|
||||
<div class="mb-4 md:mb-0">
|
||||
<div class="flex items-center space-x-2">
|
||||
<span class="text-xl font-bold">
|
||||
<span class="text-blue-500 text-2xl braille-symbol" aria-hidden="true">⠎⠞⠇</span>InBraille
|
||||
</span>
|
||||
</div>
|
||||
<p class="text-gray-400 mt-2" data-i18n="footer_text">Ferramenta de conversão para Braille</p>
|
||||
</div>
|
||||
|
||||
<div class="flex space-x-4">
|
||||
<a href="https://github.com/lucasrguerra/InBraille" class="text-gray-400 hover:text-white transition duration-200">
|
||||
<i class="fab fa-github text-xl"></i>
|
||||
</a>
|
||||
<a href="https://linkedin.com/in/lucasrguerra/" class="text-gray-400 hover:text-white transition duration-200">
|
||||
<i class="fab fa-linkedin text-xl"></i>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="border-t border-gray-700 mt-6 pt-6 text-center md:text-left">
|
||||
<p class="text-gray-400">
|
||||
<span data-i18n="developed_by">Desenvolvido por</span>
|
||||
<a href="https://linkedin.com/in/lucasrguerra/" target="_blank" rel="noopener noreferrer" class="text-blue-400 hover:underline">
|
||||
Lucas Guerra
|
||||
</a>
|
||||
</p>
|
||||
<a href="https://skipthecad.com/generators/inbraille/" target="_blank" rel="noopener" class="inline-block mt-4">
|
||||
<img src="https://skipthecad.com/badge/listed-dark.svg" alt="Listed on SkipTheCAD" width="220" height="56" loading="lazy">
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
<script src="https://unpkg.com/axios@1.7.9/dist/axios.min.js" integrity="sha384-jLwhcmGu/RL8PSTUEl/559f8QVLL4QqM+HBvoZlt4F7XCdsdoDGAwW4nPFfoM7lU" crossorigin="anonymous"></script>
|
||||
<script type="importmap">
|
||||
{
|
||||
"imports": {
|
||||
"three": "https://unpkg.com/three@0.160.0/build/three.module.js",
|
||||
"three/addons/": "https://unpkg.com/three@0.160.0/examples/jsm/"
|
||||
}
|
||||
}
|
||||
</script>
|
||||
<script type="module" src="/public/preview.js"></script>
|
||||
<script type="module" src="/public/index.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,11 @@
|
||||
import uvicorn
|
||||
|
||||
from src.config import Settings
|
||||
from src.web.app import create_app
|
||||
|
||||
|
||||
app = create_app()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
uvicorn.run(app, host="0.0.0.0", port=Settings.PORT, log_level="info", proxy_headers=True)
|
||||
|
After Width: | Height: | Size: 14 KiB |
|
After Width: | Height: | Size: 32 KiB |
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 606 B |
|
After Width: | Height: | Size: 1.4 KiB |
|
After Width: | Height: | Size: 15 KiB |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="2000" zoomAndPan="magnify" viewBox="0 0 1500 1499.999933" height="2000" preserveAspectRatio="xMidYMid meet" version="1.0"><defs><g/><clipPath id="dda7ab62cc"><path d="M 750 0 C 335.785156 0 0 335.785156 0 750 C 0 1164.214844 335.785156 1500 750 1500 C 1164.214844 1500 1500 1164.214844 1500 750 C 1500 335.785156 1164.214844 0 750 0 Z M 750 0 " clip-rule="nonzero"/></clipPath><clipPath id="57c6b7cb04"><path d="M 483 708.355469 L 1018.8125 708.355469 L 1018.8125 1432.855469 L 483 1432.855469 Z M 483 708.355469 " clip-rule="nonzero"/></clipPath></defs><g clip-path="url(#dda7ab62cc)"><rect x="-150" width="1800" fill="#ffffff" y="-149.999993" height="1799.99992" fill-opacity="1"/></g><path fill="#ffffff" d="M 930.640625 1016.375 L 923.390625 1016.375 L 923.390625 1076.03125 L 923.390625 1033.007812 C 923.164062 1032.90625 922.941406 1032.800781 922.714844 1032.703125 C 918.003906 998.121094 888.382812 971.46875 852.523438 971.46875 L 839.59375 971.46875 C 839.59375 971.46875 839.59375 1061.597656 839.59375 1064.207031 C 839.59375 1067.75 839.59375 984.757812 839.59375 991.886719 C 839.59375 955.808594 810.355469 926.5625 774.292969 926.5625 L 755.796875 926.5625 L 755.796875 1057.722656 L 755.796875 769.894531 C 755.796875 742.117188 733.289062 719.597656 705.523438 719.597656 C 677.757812 719.597656 655.246094 742.117188 655.246094 769.894531 L 655.246094 1135.164062 C 545.9375 1045.082031 537.746094 1064.113281 516.035156 1079.292969 C 493.277344 1095.207031 487.722656 1126.566406 503.632812 1149.332031 L 644.671875 1351.179688 C 662.242188 1376.433594 684.785156 1421.613281 795.394531 1421.613281 L 867.039062 1421.613281 C 944.433594 1421.613281 1007.183594 1358.421875 1007.183594 1280.476562 L 1007.183594 1092.945312 C 1007.183594 1050.65625 972.914062 1016.375 930.640625 1016.375 " fill-opacity="1" fill-rule="nonzero"/><g clip-path="url(#57c6b7cb04)"><path fill="#1d1d1b" d="M 543.269531 1077.671875 C 537.109375 1077.671875 533.15625 1080.613281 527.144531 1085.089844 C 525.628906 1086.21875 524.082031 1087.363281 522.464844 1088.496094 C 513.914062 1094.476562 508.203125 1103.425781 506.386719 1113.703125 C 504.5625 1123.976562 506.855469 1134.347656 512.832031 1142.902344 L 653.867188 1344.746094 C 655.082031 1346.492188 656.308594 1348.308594 657.578125 1350.195312 C 674.6875 1375.597656 698.121094 1410.382812 795.394531 1410.382812 L 867.035156 1410.382812 C 938.125 1410.382812 995.960938 1352.109375 995.960938 1280.476562 L 995.960938 1092.945312 C 995.960938 1058.25 968.785156 1029.78125 934.613281 1027.722656 L 934.613281 1076.027344 C 934.613281 1082.230469 929.585938 1087.257812 923.390625 1087.257812 C 917.191406 1087.257812 912.167969 1082.230469 912.167969 1076.027344 L 912.167969 1036.496094 C 911.894531 1035.765625 911.699219 1035 911.597656 1034.21875 C 907.59375 1004.847656 882.199219 982.695312 852.523438 982.695312 L 850.816406 982.695312 L 850.816406 1064.316406 C 850.816406 1070.515625 845.789062 1075.542969 839.59375 1075.542969 C 833.394531 1075.542969 828.371094 1070.515625 828.371094 1064.316406 L 828.371094 991.886719 C 828.371094 962.058594 804.109375 937.789062 774.292969 937.789062 L 767.019531 937.789062 L 767.019531 1057.722656 C 767.019531 1063.921875 761.996094 1068.949219 755.796875 1068.949219 C 749.601562 1068.949219 744.574219 1063.921875 744.574219 1057.722656 L 744.574219 769.894531 C 744.574219 748.347656 727.054688 730.824219 705.523438 730.824219 C 683.984375 730.824219 666.46875 748.347656 666.46875 769.894531 L 666.46875 1135.164062 C 666.46875 1139.507812 663.960938 1143.464844 660.035156 1145.316406 C 656.101562 1147.167969 651.460938 1146.589844 648.109375 1143.828125 C 603.046875 1106.691406 572.058594 1085.683594 553.367188 1079.597656 C 549.289062 1078.273438 546.054688 1077.671875 543.269531 1077.671875 Z M 867.035156 1432.839844 L 795.394531 1432.839844 C 686.179688 1432.839844 656.621094 1388.957031 638.960938 1362.742188 C 637.757812 1360.953125 636.597656 1359.230469 635.457031 1357.59375 L 494.433594 1155.765625 C 485.019531 1142.292969 481.417969 1125.964844 484.28125 1109.785156 C 487.148438 1093.601562 496.140625 1079.507812 509.605469 1070.09375 C 511.035156 1069.09375 512.402344 1068.074219 513.746094 1067.074219 C 539.875 1047.628906 561.230469 1045.765625 644.023438 1111.617188 L 644.023438 769.894531 C 644.023438 735.96875 671.613281 708.371094 705.523438 708.371094 C 739.429688 708.371094 767.019531 735.96875 767.019531 769.894531 L 767.019531 915.335938 L 774.292969 915.335938 C 805.210938 915.335938 831.910156 933.777344 843.96875 960.242188 L 852.523438 960.242188 C 883.988281 960.242188 911.960938 978.347656 925.667969 1005.148438 L 930.640625 1005.148438 C 979.035156 1005.148438 1018.40625 1044.535156 1018.40625 1092.945312 L 1018.40625 1280.476562 C 1018.40625 1364.492188 950.5 1432.839844 867.035156 1432.839844 " fill-opacity="1" fill-rule="nonzero"/Line truncated
|
||||
|
After Width: | Height: | Size: 18 KiB |
@@ -0,0 +1,197 @@
|
||||
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';
|
||||
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
// Gather all DOM elements
|
||||
const elements = {
|
||||
text_to_braille_tab: document.querySelector("#text_to_braille_tab"),
|
||||
braille_to_text_tab: document.querySelector("#braille_to_text_tab"),
|
||||
warning: document.querySelector("#warning"),
|
||||
input_textbox: document.querySelector('#input_text'),
|
||||
input_label: document.querySelector('#input_label'),
|
||||
char_count: document.querySelector('#char_count'),
|
||||
output_textbox: document.querySelector('#output_text'),
|
||||
output_label: document.querySelector('#output_label'),
|
||||
copy_button: document.querySelector('#copy_button'),
|
||||
save_button: document.querySelector('#save_button'),
|
||||
convert_button: document.querySelector('#convert_button'),
|
||||
stl_button: document.querySelector('#stl_button'),
|
||||
stl_preview: document.querySelector('#stl_preview'),
|
||||
download_stl_button: document.querySelector('#download_stl_button'),
|
||||
advanced_options: document.querySelector("#advanced_options"),
|
||||
advanced_options_arrow: document.querySelector("#advanced_options_arrow"),
|
||||
advanced_options_toggle: document.querySelector("#advanced_options_toggle"),
|
||||
output_plate_width: document.querySelector("#plate_width"),
|
||||
input_resolution: document.querySelector("#input_resolution"),
|
||||
input_plate_thickness: document.querySelector("#input_plate_thickness"),
|
||||
input_separate_plates: document.querySelector("#input_separate_plates"),
|
||||
input_symbols_per_line: document.querySelector("#input_symbols_per_line"),
|
||||
select_text_alignment: document.querySelector("#select_text_alignment"),
|
||||
input_rounded: document.querySelector("#input_rounded"),
|
||||
input_points_only: document.querySelector("#input_points_only")
|
||||
};
|
||||
|
||||
// Initialize modules with DOM references
|
||||
initConverterDOM(elements);
|
||||
initStlDOM(elements);
|
||||
|
||||
// Initial value setup
|
||||
if (elements.input_resolution) elements.input_resolution.value = state.resolution;
|
||||
if (elements.input_plate_thickness) elements.input_plate_thickness.value = state.plate_thickness;
|
||||
if (elements.input_separate_plates) elements.input_separate_plates.checked = !state.unique_plate;
|
||||
if (elements.input_symbols_per_line) elements.input_symbols_per_line.value = state.symbols_per_line;
|
||||
if (elements.select_text_alignment) elements.select_text_alignment.value = state.text_alignment;
|
||||
if (elements.input_rounded) elements.input_rounded.checked = state.rounded;
|
||||
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();
|
||||
|
||||
// Event listeners registration
|
||||
if (elements.text_to_braille_tab) {
|
||||
elements.text_to_braille_tab.addEventListener("click", () => switchConversionMode("text-to-braille"));
|
||||
}
|
||||
if (elements.braille_to_text_tab) {
|
||||
elements.braille_to_text_tab.addEventListener("click", () => switchConversionMode("braille-to-text"));
|
||||
}
|
||||
let liveTypeDebounce = null;
|
||||
if (elements.input_textbox) {
|
||||
elements.input_textbox.addEventListener("input", () => {
|
||||
updateCharCount();
|
||||
if (elements.stl_preview && !elements.stl_preview.classList.contains("hidden")) {
|
||||
clearTimeout(liveTypeDebounce);
|
||||
liveTypeDebounce = setTimeout(async () => {
|
||||
if (state.conversion_mode === "text-to-braille") {
|
||||
await convert();
|
||||
} else {
|
||||
triggerRealtimePreview(60);
|
||||
}
|
||||
}, 250);
|
||||
}
|
||||
});
|
||||
}
|
||||
if (elements.output_textbox) {
|
||||
elements.output_textbox.addEventListener("input", () => {
|
||||
triggerRealtimePreview(60);
|
||||
});
|
||||
}
|
||||
const alphabetRadios = document.querySelectorAll('input[name="alphabet"]');
|
||||
alphabetRadios.forEach(radio => {
|
||||
radio.addEventListener("change", () => {
|
||||
if (elements.stl_preview && !elements.stl_preview.classList.contains("hidden")) {
|
||||
convert();
|
||||
}
|
||||
});
|
||||
});
|
||||
if (elements.copy_button) {
|
||||
elements.copy_button.addEventListener("click", copyOutput);
|
||||
}
|
||||
if (elements.save_button) {
|
||||
elements.save_button.addEventListener("click", saveOutput);
|
||||
}
|
||||
if (elements.convert_button) {
|
||||
elements.convert_button.addEventListener("click", convert);
|
||||
}
|
||||
if (elements.stl_button) {
|
||||
elements.stl_button.addEventListener("click", generateSTL);
|
||||
}
|
||||
if (elements.download_stl_button) {
|
||||
elements.download_stl_button.addEventListener("click", downloadSTL);
|
||||
}
|
||||
if (elements.advanced_options_toggle) {
|
||||
elements.advanced_options_toggle.addEventListener("click", toggleAdvancedOptions);
|
||||
}
|
||||
|
||||
if (elements.input_resolution) {
|
||||
elements.input_resolution.addEventListener("input", updateParameters);
|
||||
}
|
||||
if (elements.input_plate_thickness) {
|
||||
elements.input_plate_thickness.addEventListener("input", updateParameters);
|
||||
}
|
||||
if (elements.input_separate_plates) {
|
||||
elements.input_separate_plates.addEventListener("input", updateParameters);
|
||||
}
|
||||
if (elements.input_symbols_per_line) {
|
||||
elements.input_symbols_per_line.addEventListener("input", updateParameters);
|
||||
elements.input_symbols_per_line.addEventListener("change", () => {
|
||||
if (elements.output_textbox) elements.output_textbox.value = "";
|
||||
});
|
||||
}
|
||||
if (elements.select_text_alignment) {
|
||||
elements.select_text_alignment.addEventListener("input", updateParameters);
|
||||
}
|
||||
if (elements.input_rounded) {
|
||||
elements.input_rounded.addEventListener("input", updateParameters);
|
||||
}
|
||||
if (elements.input_points_only) {
|
||||
elements.input_points_only.addEventListener("input", () => {
|
||||
updateParameters();
|
||||
applyPointsOnlyState();
|
||||
});
|
||||
}
|
||||
|
||||
if (elements.input_resolution) elements.input_resolution.addEventListener("blur", updateInputs);
|
||||
if (elements.input_plate_thickness) elements.input_plate_thickness.addEventListener("blur", updateInputs);
|
||||
if (elements.input_separate_plates) elements.input_separate_plates.addEventListener("blur", updateInputs);
|
||||
if (elements.input_symbols_per_line) {
|
||||
elements.input_symbols_per_line.addEventListener("blur", () => {
|
||||
updateInputs();
|
||||
if (elements.output_textbox) elements.output_textbox.value = "";
|
||||
});
|
||||
}
|
||||
if (elements.select_text_alignment) elements.select_text_alignment.addEventListener("blur", updateInputs);
|
||||
if (elements.input_rounded) elements.input_rounded.addEventListener("blur", updateInputs);
|
||||
|
||||
// Helper to switch language and update dependent components
|
||||
function changeLanguage(lang, callback) {
|
||||
setLanguage(lang, () => {
|
||||
switchConversionMode();
|
||||
updateInputs();
|
||||
if (callback) callback();
|
||||
});
|
||||
}
|
||||
|
||||
// Language switcher click handlers
|
||||
document.querySelectorAll("#lang_dropdown button[data-lang]").forEach(button => {
|
||||
button.addEventListener("click", (e) => {
|
||||
const selectedLang = e.currentTarget.getAttribute("data-lang");
|
||||
|
||||
changeLanguage(selectedLang, () => {
|
||||
let newPath = "/";
|
||||
if (selectedLang === "en") newPath = "/en";
|
||||
else if (selectedLang === "zh") newPath = "/zh";
|
||||
|
||||
window.history.pushState(null, "", newPath);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// Clear button listener
|
||||
const clearBtn = document.querySelector("#clear_button");
|
||||
if (clearBtn) {
|
||||
clearBtn.addEventListener("click", clearInput);
|
||||
}
|
||||
|
||||
// Alphabet radio listener
|
||||
document.querySelectorAll('input[name="alphabet"]').forEach(radio => {
|
||||
radio.addEventListener("change", () => switchConversionMode());
|
||||
});
|
||||
|
||||
// Determine and set initial language and default alphabet
|
||||
const path = window.location.pathname;
|
||||
let initialLang = "pt-BR";
|
||||
if (path.startsWith("/en")) {
|
||||
initialLang = "en";
|
||||
const radio = document.getElementById("north-american");
|
||||
if (radio) radio.checked = true;
|
||||
} else if (path.startsWith("/zh")) {
|
||||
initialLang = "zh";
|
||||
const radio = document.getElementById("chinese");
|
||||
if (radio) radio.checked = true;
|
||||
} else {
|
||||
const radio = document.getElementById("brazilian");
|
||||
if (radio) radio.checked = true;
|
||||
}
|
||||
changeLanguage(initialLang);
|
||||
});
|
||||
@@ -0,0 +1,84 @@
|
||||
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."
|
||||
};
|
||||
@@ -0,0 +1,84 @@
|
||||
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."
|
||||
};
|
||||
@@ -0,0 +1,84 @@
|
||||
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 文件出错,请重试。"
|
||||
};
|
||||
@@ -0,0 +1,424 @@
|
||||
/**
|
||||
* Client-Side Parametric STL Generator for InBraille.
|
||||
* Generates binary STL 3D models directly in the user's browser in milliseconds,
|
||||
* eliminating server CPU load, network latency, and queue timeouts.
|
||||
*/
|
||||
|
||||
export const Dimensions = {
|
||||
dots_radius: 1,
|
||||
dots_spacing: 2.7,
|
||||
dots_apparent_thickness: 0.65,
|
||||
cells_width: 4.7,
|
||||
cells_height: 7.4,
|
||||
cells_h_spacing: 6.6,
|
||||
cells_v_spacing: 10.8
|
||||
};
|
||||
|
||||
const BRAILLE_CODE_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) {
|
||||
if (BRAILLE_CODE_MAP[character]) {
|
||||
return BRAILLE_CODE_MAP[character];
|
||||
}
|
||||
const val = character.charCodeAt(0) - 0x2800;
|
||||
if (val >= 0 && val <= 0xff) {
|
||||
let bits = '';
|
||||
for (let b = 0; b < 6; b++) {
|
||||
bits += (val >> b) & 1 ? '1' : '0';
|
||||
}
|
||||
return bits;
|
||||
}
|
||||
return '000000';
|
||||
}
|
||||
|
||||
function createBox(w, h, d) {
|
||||
const hw = w / 2, hh = h / 2, hd = d / 2;
|
||||
const verts = [
|
||||
[-hw, -hh, -hd], [hw, -hh, -hd], [hw, hh, -hd], [-hw, hh, -hd],
|
||||
[-hw, -hh, hd], [hw, -hh, hd], [hw, hh, hd], [-hw, hh, hd]
|
||||
];
|
||||
const faces = [
|
||||
[0, 2, 1], [0, 3, 2], // bottom (-z)
|
||||
[4, 5, 6], [4, 6, 7], // top (+z)
|
||||
[0, 1, 5], [0, 5, 4], // front (-y)
|
||||
[2, 3, 7], [2, 7, 6], // back (+y)
|
||||
[0, 4, 7], [0, 7, 3], // left (-x)
|
||||
[1, 2, 6], [1, 6, 5] // right (+x)
|
||||
];
|
||||
return { verts, faces };
|
||||
}
|
||||
|
||||
function createCap(radius, apparentThickness, resolution = 16) {
|
||||
const cutZ = radius - apparentThickness;
|
||||
const nRings = Math.max(3, Math.floor(resolution / 2));
|
||||
const nSegs = Math.max(8, resolution);
|
||||
const verts = [];
|
||||
const faces = [];
|
||||
|
||||
// Base center vertex at (0, 0, 0)
|
||||
verts.push([0, 0, 0]);
|
||||
|
||||
// Ring 0: base circle at z = 0
|
||||
const baseR = Math.sqrt(Math.max(0, radius * radius - cutZ * cutZ));
|
||||
for (let j = 0; j < nSegs; j++) {
|
||||
const theta = (j * 2 * Math.PI) / nSegs;
|
||||
verts.push([baseR * Math.cos(theta), baseR * Math.sin(theta), 0]);
|
||||
}
|
||||
// Base disk triangles (normal pointing -z)
|
||||
for (let j = 0; j < nSegs; j++) {
|
||||
const next = (j + 1) % nSegs;
|
||||
faces.push([0, 1 + next, 1 + j]);
|
||||
}
|
||||
|
||||
// Dome rings from z=0 up to the apex
|
||||
const ringStarts = [1];
|
||||
for (let i = 1; i <= nRings; i++) {
|
||||
const ringZ = (i * apparentThickness) / nRings;
|
||||
const zOrig = ringZ + cutZ;
|
||||
const r = Math.sqrt(Math.max(0, radius * radius - zOrig * zOrig));
|
||||
const rStart = verts.length;
|
||||
ringStarts.push(rStart);
|
||||
|
||||
if (i === nRings) {
|
||||
// Apex point at (0, 0, apparentThickness)
|
||||
verts.push([0, 0, apparentThickness]);
|
||||
const prevStart = ringStarts[i - 1];
|
||||
for (let j = 0; j < nSegs; j++) {
|
||||
const next = (j + 1) % nSegs;
|
||||
faces.push([prevStart + j, prevStart + next, rStart]);
|
||||
}
|
||||
} else {
|
||||
for (let j = 0; j < nSegs; j++) {
|
||||
const theta = (j * 2 * Math.PI) / nSegs;
|
||||
verts.push([r * Math.cos(theta), r * Math.sin(theta), ringZ]);
|
||||
}
|
||||
const prevStart = ringStarts[i - 1];
|
||||
for (let j = 0; j < nSegs; j++) {
|
||||
const next = (j + 1) % nSegs;
|
||||
faces.push([prevStart + j, prevStart + next, rStart + j]);
|
||||
faces.push([prevStart + next, rStart + next, rStart + j]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return { verts, faces };
|
||||
}
|
||||
|
||||
function createCylinder(radius, height, resolution = 16) {
|
||||
const verts = [];
|
||||
const faces = [];
|
||||
const hh = height / 2;
|
||||
const nSegs = Math.max(8, resolution);
|
||||
|
||||
// Bottom center at (-radius, 0, -hh)
|
||||
verts.push([-radius, 0, -hh]); // index 0
|
||||
// Top center at (-radius, 0, hh)
|
||||
verts.push([-radius, 0, hh]); // index 1
|
||||
|
||||
for (let i = 0; i < nSegs; i++) {
|
||||
const theta = (i * 2 * Math.PI) / nSegs;
|
||||
const x = -radius + radius * Math.cos(theta);
|
||||
const y = radius * Math.sin(theta);
|
||||
verts.push([x, y, -hh]); // 2 + i * 2
|
||||
verts.push([x, y, hh]); // 2 + i * 2 + 1
|
||||
}
|
||||
|
||||
for (let i = 0; i < nSegs; i++) {
|
||||
const next = (i + 1) % nSegs;
|
||||
const b1 = 2 + i * 2;
|
||||
const t1 = 2 + i * 2 + 1;
|
||||
const b2 = 2 + next * 2;
|
||||
const t2 = 2 + next * 2 + 1;
|
||||
|
||||
// Bottom cap (normal pointing -z)
|
||||
faces.push([0, b2, b1]);
|
||||
// Top cap (normal pointing +z)
|
||||
faces.push([1, t1, t2]);
|
||||
// Side quads
|
||||
faces.push([b1, b2, t1]);
|
||||
faces.push([b2, t2, t1]);
|
||||
}
|
||||
return { verts, faces };
|
||||
}
|
||||
|
||||
function translateMesh(mesh, dx, dy, dz, rotXDeg = 0) {
|
||||
const rad = rotXDeg * (Math.PI / 180);
|
||||
const cos = Math.cos(rad), sin = Math.sin(rad);
|
||||
const newVerts = mesh.verts.map(([x, y, z]) => {
|
||||
const ny = y * cos - z * sin;
|
||||
const nz = y * sin + z * cos;
|
||||
return [x + dx, ny + dy, nz + dz];
|
||||
});
|
||||
return { verts: newVerts, faces: mesh.faces };
|
||||
}
|
||||
|
||||
function mergeMeshes(meshes) {
|
||||
let totalVerts = 0;
|
||||
let totalFaces = 0;
|
||||
for (let i = 0; i < meshes.length; i++) {
|
||||
totalVerts += meshes[i].verts.length;
|
||||
totalFaces += meshes[i].faces.length;
|
||||
}
|
||||
|
||||
const allVerts = new Array(totalVerts);
|
||||
const allFaces = new Array(totalFaces);
|
||||
|
||||
let vOffset = 0;
|
||||
let fOffset = 0;
|
||||
for (let i = 0; i < meshes.length; i++) {
|
||||
const m = meshes[i];
|
||||
const mv = m.verts;
|
||||
const mf = m.faces;
|
||||
const currentVOffset = vOffset;
|
||||
|
||||
for (let j = 0; j < mv.length; j++) {
|
||||
allVerts[vOffset + j] = mv[j];
|
||||
}
|
||||
for (let j = 0; j < mf.length; j++) {
|
||||
const face = mf[j];
|
||||
allFaces[fOffset + j] = [face[0] + currentVOffset, face[1] + currentVOffset, face[2] + currentVOffset];
|
||||
}
|
||||
|
||||
vOffset += mv.length;
|
||||
fOffset += mf.length;
|
||||
}
|
||||
return { verts: allVerts, faces: allFaces };
|
||||
}
|
||||
|
||||
function buildCell(code, radius, spacing, apparentThickness, resolution, pointsOnly) {
|
||||
const dot = createCap(radius, apparentThickness, resolution);
|
||||
const dotPositions = [
|
||||
[0, 2 * spacing],
|
||||
[0, spacing],
|
||||
[0, 0],
|
||||
[spacing, 2 * spacing],
|
||||
[spacing, spacing],
|
||||
[spacing, 0]
|
||||
];
|
||||
const parts = [];
|
||||
for (let i = 0; i < dotPositions.length; i++) {
|
||||
if (code[i] === '1') {
|
||||
const [x, y] = dotPositions[i];
|
||||
parts.push(translateMesh(dot, x, y, 0));
|
||||
}
|
||||
}
|
||||
return parts.length > 0 ? mergeMeshes(parts) : { verts: [], faces: [] };
|
||||
}
|
||||
|
||||
function meshToBinarySTL(mesh) {
|
||||
const triangleCount = mesh.faces.length;
|
||||
const buffer = new ArrayBuffer(84 + triangleCount * 50);
|
||||
const view = new DataView(buffer);
|
||||
view.setUint32(80, triangleCount, true); // little-endian triangle count
|
||||
|
||||
let offset = 84;
|
||||
const verts = mesh.verts;
|
||||
const faces = mesh.faces;
|
||||
|
||||
for (let i = 0; i < triangleCount; i++) {
|
||||
const face = faces[i];
|
||||
const v0 = verts[face[0]];
|
||||
const v1 = verts[face[1]];
|
||||
const v2 = verts[face[2]];
|
||||
|
||||
// Normal via cross product (v1 - v0) x (v2 - v0)
|
||||
const d1x = v1[0] - v0[0], d1y = v1[1] - v0[1], d1z = v1[2] - v0[2];
|
||||
const d2x = v2[0] - v0[0], d2y = v2[1] - v0[1], d2z = v2[2] - v0[2];
|
||||
let nx = d1y * d2z - d1z * d2y;
|
||||
let ny = d1z * d2x - d1x * d2z;
|
||||
let nz = d1x * d2y - d1y * d2x;
|
||||
const len = Math.hypot(nx, ny, nz);
|
||||
if (len > 1e-12) {
|
||||
nx /= len; ny /= len; nz /= len;
|
||||
} else {
|
||||
nx = 0; ny = 0; nz = 0;
|
||||
}
|
||||
|
||||
view.setFloat32(offset, nx, true);
|
||||
view.setFloat32(offset + 4, ny, true);
|
||||
view.setFloat32(offset + 8, nz, true);
|
||||
view.setFloat32(offset + 12, v0[0], true);
|
||||
view.setFloat32(offset + 16, v0[1], true);
|
||||
view.setFloat32(offset + 20, v0[2], true);
|
||||
view.setFloat32(offset + 24, v1[0], true);
|
||||
view.setFloat32(offset + 28, v1[1], true);
|
||||
view.setFloat32(offset + 32, v1[2], true);
|
||||
view.setFloat32(offset + 36, v2[0], true);
|
||||
view.setFloat32(offset + 40, v2[1], true);
|
||||
view.setFloat32(offset + 44, v2[2], true);
|
||||
// Attribute bytes (uint16) are initialized to 0
|
||||
offset += 50;
|
||||
}
|
||||
return buffer;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the complete Braille 3D model and exports as a binary STL ArrayBuffer.
|
||||
*/
|
||||
export function buildClientSTL(braille, options = {}) {
|
||||
const resolution = Math.max(12, Math.min(50, options.resolution || 20));
|
||||
const plateThickness = Math.max(2, Math.min(100, options.plate_thickness || 2));
|
||||
let uniquePlate = options.unique_plate !== undefined ? options.unique_plate : false;
|
||||
const symbolsPerLine = Math.max(8, Math.min(50, options.symbols_per_line || 22));
|
||||
const textAlignment = options.text_alignment || 'left';
|
||||
let rounded = options.rounded !== undefined ? options.rounded : false;
|
||||
let pointsOnly = options.points_only !== undefined ? options.points_only : false;
|
||||
|
||||
if (pointsOnly) {
|
||||
uniquePlate = true;
|
||||
rounded = false;
|
||||
}
|
||||
|
||||
const rules = Dimensions;
|
||||
const rawPhrases = braille.split('\n');
|
||||
const phrases = rawPhrases.length > 0 ? rawPhrases : [''];
|
||||
const numberOfPhrases = phrases.length;
|
||||
const plateWidth = ((symbolsPerLine - 1) * rules.cells_h_spacing) + rules.cells_width;
|
||||
const letterReferenceZ = pointsOnly ? 0 : plateThickness;
|
||||
const referenceZ = plateThickness / 2;
|
||||
const plateHeight = rules.cells_v_spacing;
|
||||
const borderSize = rules.cells_width;
|
||||
const borderCylinderXRef = -0.7;
|
||||
const borderPlateXRef = -(0.7 + (borderSize / 2));
|
||||
|
||||
const borderCylinder = createCylinder(borderSize, plateThickness, resolution);
|
||||
|
||||
const charCache = {};
|
||||
const sceneParts = [];
|
||||
|
||||
for (let phraseIndex = 0; phraseIndex < phrases.length; phraseIndex++) {
|
||||
const phrase = phrases[phraseIndex];
|
||||
const phraseParts = [];
|
||||
const thisPhraseWidth = ((Math.max(1, phrase.length) - 1) * rules.cells_h_spacing) + rules.cells_width;
|
||||
|
||||
if (!uniquePlate) {
|
||||
const thisPlateHeight = rules.cells_v_spacing * 2;
|
||||
const platePosX = plateWidth / 2;
|
||||
const platePosY = (plateHeight - rules.cells_height) / 2;
|
||||
const finalPlateWidth = plateWidth + rules.cells_v_spacing;
|
||||
|
||||
const thisPlate = createBox(finalPlateWidth, thisPlateHeight, plateThickness);
|
||||
phraseParts.push(translateMesh(thisPlate, platePosX, platePosY, referenceZ));
|
||||
|
||||
// Corner marker
|
||||
const marker = createCap(1.6, rules.dots_apparent_thickness, resolution);
|
||||
const cornerX = platePosX - (finalPlateWidth / 2) + 3.0;
|
||||
const cornerY = platePosY - (thisPlateHeight / 2) + 3.0;
|
||||
phraseParts.push(translateMesh(marker, cornerX, cornerY, plateThickness));
|
||||
|
||||
if (rounded) {
|
||||
const halfPlateHeight = thisPlateHeight / 2;
|
||||
const borderPlate = createBox(borderSize, thisPlateHeight - borderSize * 2, plateThickness);
|
||||
|
||||
phraseParts.push(translateMesh(borderCylinder, borderCylinderXRef, platePosY + halfPlateHeight - borderSize, referenceZ));
|
||||
phraseParts.push(translateMesh(borderCylinder, borderCylinderXRef + finalPlateWidth, platePosY + halfPlateHeight - borderSize, referenceZ));
|
||||
phraseParts.push(translateMesh(borderCylinder, borderCylinderXRef, platePosY - halfPlateHeight + borderSize, referenceZ));
|
||||
phraseParts.push(translateMesh(borderCylinder, borderCylinderXRef + finalPlateWidth, platePosY - halfPlateHeight + borderSize, referenceZ));
|
||||
phraseParts.push(translateMesh(borderPlate, borderPlateXRef - borderSize, platePosY, referenceZ));
|
||||
phraseParts.push(translateMesh(borderPlate, borderPlateXRef + finalPlateWidth, platePosY, referenceZ));
|
||||
}
|
||||
}
|
||||
|
||||
for (let letterIndex = 0; letterIndex < phrase.length; letterIndex++) {
|
||||
const letter = phrase[letterIndex];
|
||||
if (letter === '⠀' || letter === ' ') continue;
|
||||
|
||||
let letterPosY = -rules.dots_radius;
|
||||
let letterPosX = (letterIndex * rules.cells_h_spacing) + rules.dots_radius;
|
||||
let letterPosZ = letterReferenceZ;
|
||||
|
||||
if (uniquePlate) {
|
||||
letterPosY -= phraseIndex * rules.cells_v_spacing;
|
||||
}
|
||||
|
||||
if (textAlignment === 'center') {
|
||||
letterPosX += (plateWidth - thisPhraseWidth) / 2;
|
||||
} else if (textAlignment === 'right') {
|
||||
letterPosX += plateWidth - thisPhraseWidth;
|
||||
}
|
||||
|
||||
if (!charCache[letter]) {
|
||||
charCache[letter] = buildCell(codeFor(letter), rules.dots_radius, rules.dots_spacing, rules.dots_apparent_thickness, resolution, pointsOnly);
|
||||
}
|
||||
if (charCache[letter].verts.length > 0) {
|
||||
phraseParts.push(translateMesh(charCache[letter], letterPosX, letterPosY, letterPosZ));
|
||||
}
|
||||
}
|
||||
|
||||
if (phraseParts.length > 0) {
|
||||
const phraseMesh = mergeMeshes(phraseParts);
|
||||
const phrasePosZ = uniquePlate ? 0 : phraseIndex * (plateThickness + rules.cells_v_spacing);
|
||||
sceneParts.push(translateMesh(phraseMesh, 0, 0, phrasePosZ));
|
||||
}
|
||||
}
|
||||
|
||||
if (uniquePlate && !pointsOnly) {
|
||||
const borderYRef = rules.cells_v_spacing + ((rules.cells_v_spacing - rules.cells_height) / 2);
|
||||
const finalPlateHeight = (numberOfPhrases * rules.cells_v_spacing) + rules.cells_v_spacing;
|
||||
const platePosX = plateWidth / 2;
|
||||
const platePosY = borderYRef - (finalPlateHeight / 2);
|
||||
const finalPlateWidth = plateWidth + rules.cells_v_spacing;
|
||||
|
||||
const plate = createBox(finalPlateWidth, finalPlateHeight, plateThickness);
|
||||
sceneParts.push(translateMesh(plate, platePosX, platePosY, referenceZ));
|
||||
|
||||
// Corner marker
|
||||
const marker = createCap(1.6, rules.dots_apparent_thickness, resolution);
|
||||
const cornerX = platePosX - (finalPlateWidth / 2) + 3.0;
|
||||
const cornerY = platePosY - (finalPlateHeight / 2) + 3.0;
|
||||
sceneParts.push(translateMesh(marker, cornerX, cornerY, plateThickness));
|
||||
|
||||
if (rounded) {
|
||||
const borderPlate = createBox(borderSize, finalPlateHeight - borderSize * 2, plateThickness);
|
||||
sceneParts.push(translateMesh(borderCylinder, borderCylinderXRef, borderYRef - borderSize, referenceZ));
|
||||
sceneParts.push(translateMesh(borderCylinder, borderCylinderXRef + finalPlateWidth, borderYRef - borderSize, referenceZ));
|
||||
sceneParts.push(translateMesh(borderCylinder, borderCylinderXRef, borderYRef - finalPlateHeight + borderSize, referenceZ));
|
||||
sceneParts.push(translateMesh(borderCylinder, borderCylinderXRef + finalPlateWidth, borderYRef - finalPlateHeight + borderSize, referenceZ));
|
||||
sceneParts.push(translateMesh(borderPlate, borderPlateXRef - borderSize, platePosY, referenceZ));
|
||||
sceneParts.push(translateMesh(borderPlate, borderPlateXRef + finalPlateWidth, platePosY, referenceZ));
|
||||
}
|
||||
}
|
||||
|
||||
if (pointsOnly && sceneParts.length > 0) {
|
||||
// Add orientation bar below lowest dots
|
||||
const preMesh = mergeMeshes(sceneParts);
|
||||
let xMin = Infinity, xMax = -Infinity, yMin = Infinity;
|
||||
for (let i = 0; i < preMesh.verts.length; i++) {
|
||||
const v = preMesh.verts[i];
|
||||
if (v[0] < xMin) xMin = v[0];
|
||||
if (v[0] > xMax) xMax = v[0];
|
||||
if (v[1] < yMin) yMin = v[1];
|
||||
}
|
||||
const barWidth = xMax - xMin;
|
||||
if (barWidth > 0 && isFinite(barWidth)) {
|
||||
const barDepth = 1.2;
|
||||
const barHeight = rules.dots_apparent_thickness;
|
||||
const barGap = 0.8;
|
||||
const bar = createBox(barWidth, barDepth, barHeight);
|
||||
sceneParts.push(translateMesh(
|
||||
bar,
|
||||
(xMin + xMax) / 2,
|
||||
yMin - barGap - (barDepth / 2),
|
||||
barHeight / 2
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
const combinedMesh = sceneParts.length > 0 ? mergeMeshes(sceneParts) : { verts: [], faces: [] };
|
||||
// Final rotate 90 degrees around X axis: (x, y, z) -> (x, -z, y)
|
||||
const finalRotatedMesh = translateMesh(combinedMesh, 0, 0, 0, 90);
|
||||
return meshToBinarySTL(finalRotatedMesh);
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
import { state } from './state.js';
|
||||
import { getTranslation } from './i18n.js';
|
||||
import { triggerRealtimePreview } from './stl.js';
|
||||
|
||||
let dom = {};
|
||||
|
||||
export function initConverterDOM(elements) {
|
||||
dom = elements;
|
||||
}
|
||||
|
||||
export function getAlphabet() {
|
||||
const checkedInput = document.querySelector('input[name="alphabet"]:checked');
|
||||
return checkedInput ? checkedInput.value : "North American";
|
||||
}
|
||||
|
||||
export function switchConversionMode(mode) {
|
||||
state.conversion_mode = mode ? mode : state.conversion_mode;
|
||||
|
||||
const text_to_braille_tab = dom.text_to_braille_tab;
|
||||
const braille_to_text_tab = dom.braille_to_text_tab;
|
||||
const input_label = dom.input_label;
|
||||
const input_textbox = dom.input_textbox;
|
||||
const output_label = dom.output_label;
|
||||
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) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (state.conversion_mode === "text-to-braille") {
|
||||
text_to_braille_tab.classList.add("tab-active");
|
||||
braille_to_text_tab.classList.remove("tab-active");
|
||||
|
||||
input_label.innerHTML = `<i class="fas fa-pen-alt mr-1"></i> ${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_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_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_textbox.placeholder = getTranslation("output_placeholder_braille_to_text");
|
||||
|
||||
if (getAlphabet() === "Brazilian") {
|
||||
warning.classList.remove("hidden");
|
||||
} else {
|
||||
warning.classList.add("hidden");
|
||||
}
|
||||
}
|
||||
|
||||
const chineseTip = document.getElementById("chinese_input_tip_container");
|
||||
if (chineseTip) {
|
||||
if (getAlphabet() === "Chinese") {
|
||||
chineseTip.classList.remove("hidden");
|
||||
} else {
|
||||
chineseTip.classList.add("hidden");
|
||||
}
|
||||
}
|
||||
|
||||
if (mode) {
|
||||
clearInput();
|
||||
}
|
||||
}
|
||||
|
||||
export function clearInput() {
|
||||
if (dom.input_textbox) dom.input_textbox.value = "";
|
||||
if (dom.output_textbox) dom.output_textbox.value = "";
|
||||
updateCharCount();
|
||||
}
|
||||
|
||||
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 + " 个字符";
|
||||
}
|
||||
}
|
||||
|
||||
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 originalText = copy_button.innerText;
|
||||
const copyText = getTranslation("copy_button_feedback") || "Copied!";
|
||||
copy_button.innerHTML = `<i class="fas fa-check mr-1"></i> ${copyText}`;
|
||||
|
||||
setTimeout(() => {
|
||||
copy_button.innerHTML = originalText;
|
||||
}, 2000);
|
||||
}
|
||||
|
||||
export function saveOutput() {
|
||||
if (!dom.output_textbox) return;
|
||||
const text = dom.output_textbox.value;
|
||||
if (text.length === 0) { return; }
|
||||
|
||||
const blob = new Blob([text], { type: 'text/plain' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = `inbraille_output.txt`;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
|
||||
function adjustBrailleSize(braille) {
|
||||
const initial_string = String(braille).replaceAll("\n", "⠀");
|
||||
let adjusted_braille = "";
|
||||
let actual_phrase = "";
|
||||
|
||||
const words = initial_string.split("⠀");
|
||||
const number_of_words = words.length;
|
||||
for (let index = 0; index < number_of_words; index++) {
|
||||
const word = words[index];
|
||||
const word_length = word.length;
|
||||
if (word_length > state.symbols_per_line) { return word_length; }
|
||||
|
||||
if ((word_length + actual_phrase.length) > state.symbols_per_line) {
|
||||
adjusted_braille += actual_phrase.slice(0, -1) + "\n";
|
||||
actual_phrase = "";
|
||||
}
|
||||
|
||||
actual_phrase += word + "⠀";
|
||||
}
|
||||
|
||||
if (actual_phrase.length > 0) {
|
||||
adjusted_braille += actual_phrase.slice(0, -1);
|
||||
} else {
|
||||
adjusted_braille = adjusted_braille.slice(0, -1);
|
||||
}
|
||||
|
||||
return adjusted_braille;
|
||||
}
|
||||
|
||||
async function checkBrailleSize(braille) {
|
||||
const phrases = braille.split("\n");
|
||||
const number_of_phrases = phrases.length;
|
||||
for (let index = 0; index < number_of_phrases; index++) {
|
||||
const phrase = phrases[index];
|
||||
const phrase_length = phrase.length;
|
||||
if (phrase_length > state.symbols_per_line) {
|
||||
const adjust = confirm(getTranslation("confirm_line_exceeds"));
|
||||
|
||||
if (adjust) {
|
||||
const adjusted = adjustBrailleSize(braille);
|
||||
if (isNaN(adjusted)) {
|
||||
if (state.conversion_mode === "text-to-braille") {
|
||||
const response = await axios.post("/api/decode", {
|
||||
braille: adjusted,
|
||||
alphabet: getAlphabet()
|
||||
});
|
||||
if (dom.input_textbox) {
|
||||
dom.input_textbox.value = response.data.decoded;
|
||||
}
|
||||
}
|
||||
alert(getTranslation("alert_auto_adjust_success"));
|
||||
} else {
|
||||
alert(`${getTranslation("alert_word_exceeds_prefix")} ${adjusted}`);
|
||||
return -1;
|
||||
}
|
||||
return adjusted;
|
||||
}
|
||||
return phrase_length;
|
||||
}
|
||||
}
|
||||
return phrases.join("\n");
|
||||
}
|
||||
|
||||
export async function convert() {
|
||||
if (!dom.input_textbox || !dom.output_textbox) return;
|
||||
const text = dom.input_textbox.value;
|
||||
if (text.length === 0) { return; }
|
||||
|
||||
const alphabet = getAlphabet();
|
||||
try {
|
||||
if (state.conversion_mode === "text-to-braille") {
|
||||
const response = await axios.post("/api/encode", {
|
||||
text: text,
|
||||
alphabet: alphabet
|
||||
});
|
||||
const braille = await checkBrailleSize(response.data.encoded);
|
||||
if (braille === -1) {
|
||||
// Alert already handled inside checkBrailleSize
|
||||
} else if (!isNaN(braille)) {
|
||||
dom.output_textbox.value = "";
|
||||
alert(`${getTranslation("alert_manual_correct_prefix")} ${braille}`);
|
||||
} else {
|
||||
dom.output_textbox.value = braille;
|
||||
triggerRealtimePreview(60);
|
||||
}
|
||||
} else {
|
||||
const adjusted_braille = await checkBrailleSize(text);
|
||||
if (adjusted_braille === -1) {
|
||||
// Already handled
|
||||
} else if (!isNaN(adjusted_braille)) {
|
||||
dom.output_textbox.value = "";
|
||||
alert(`${getTranslation("alert_manual_correct_prefix")} ${adjusted_braille}`);
|
||||
} else {
|
||||
const response = await axios.post("/api/decode", {
|
||||
braille: text,
|
||||
alphabet: alphabet
|
||||
});
|
||||
dom.output_textbox.value = response.data.decoded;
|
||||
triggerRealtimePreview(60);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
alert(getTranslation("alert_general_error"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import translations from '../translations.js';
|
||||
import { state } from './state.js';
|
||||
|
||||
export function getTranslation(key) {
|
||||
const dict = translations[state.page_language] || translations["pt-BR"];
|
||||
return dict[key];
|
||||
}
|
||||
|
||||
export function setLanguage(lang, onLanguageChanged) {
|
||||
state.page_language = lang;
|
||||
document.documentElement.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);
|
||||
}
|
||||
|
||||
document.querySelectorAll("[data-i18n]").forEach(elem => {
|
||||
const key = elem.getAttribute("data-i18n");
|
||||
if (dict[key] !== undefined) {
|
||||
elem.textContent = dict[key];
|
||||
}
|
||||
});
|
||||
|
||||
document.querySelectorAll("[data-i18n-placeholder]").forEach(elem => {
|
||||
const key = elem.getAttribute("data-i18n-placeholder");
|
||||
if (dict[key] !== undefined) {
|
||||
elem.setAttribute("placeholder", dict[key]);
|
||||
}
|
||||
});
|
||||
updateLangMenu(lang);
|
||||
if (onLanguageChanged) {
|
||||
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 = "🇨🇳 中文";
|
||||
}
|
||||
|
||||
const buttons = document.querySelectorAll("#lang_dropdown button[data-lang]");
|
||||
buttons.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";
|
||||
} else {
|
||||
btn.className = "w-full text-left flex items-center gap-3 px-4 py-2 text-gray-700 hover:bg-gray-50";
|
||||
}
|
||||
});
|
||||
|
||||
const details = document.querySelector("#lang_dropdown");
|
||||
if (details) {
|
||||
details.removeAttribute("open");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
export const state = {
|
||||
page_language: "pt-BR",
|
||||
conversion_mode: "text-to-braille",
|
||||
resolution: 20,
|
||||
plate_thickness: 2,
|
||||
unique_plate: true,
|
||||
symbols_per_line: 22,
|
||||
text_alignment: "center",
|
||||
rounded: false,
|
||||
points_only: false,
|
||||
plate_width: 143.3, // calculated default
|
||||
last_stl_blob: null
|
||||
};
|
||||
|
||||
export function calculatePlateWidth() {
|
||||
return ((state.symbols_per_line - 1) * 6.6) + 4.7;
|
||||
}
|
||||
|
||||
export function updatePlateWidth() {
|
||||
state.plate_width = calculatePlateWidth();
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
import { state, updatePlateWidth } from './state.js';
|
||||
import { getTranslation } from './i18n.js';
|
||||
import { showToast, highlightInput } from './ui.js';
|
||||
import { convert } from './converter.js';
|
||||
import { buildClientSTL } from './client_stl_generator.js';
|
||||
|
||||
let dom = {};
|
||||
|
||||
export function initStlDOM(elements) {
|
||||
dom = elements;
|
||||
}
|
||||
|
||||
let realtimeDebounceTimer = null;
|
||||
|
||||
export function triggerRealtimePreview(delay = 80) {
|
||||
if (!dom.stl_preview || dom.stl_preview.classList.contains("hidden")) {
|
||||
return;
|
||||
}
|
||||
clearTimeout(realtimeDebounceTimer);
|
||||
realtimeDebounceTimer = setTimeout(() => {
|
||||
updateRealtimeModel();
|
||||
}, delay);
|
||||
}
|
||||
|
||||
export function updateRealtimeModel() {
|
||||
if (!dom.stl_preview || dom.stl_preview.classList.contains("hidden")) {
|
||||
return;
|
||||
}
|
||||
let braille = dom.output_textbox ? dom.output_textbox.value : "";
|
||||
if (state.conversion_mode === "braille-to-text" && dom.input_textbox) {
|
||||
braille = dom.input_textbox.value;
|
||||
}
|
||||
if (!braille || braille.trim().length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const arrayBuffer = buildClientSTL(braille, {
|
||||
resolution: state.resolution,
|
||||
plate_thickness: state.plate_thickness,
|
||||
unique_plate: state.unique_plate,
|
||||
symbols_per_line: state.symbols_per_line,
|
||||
text_alignment: state.text_alignment,
|
||||
rounded: state.rounded,
|
||||
points_only: state.points_only
|
||||
});
|
||||
state.last_stl_blob = new Blob([arrayBuffer], { type: "model/stl" });
|
||||
if (typeof window.renderSTLPreview === "function") {
|
||||
window.renderSTLPreview(arrayBuffer.slice(0), false);
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn("[InBraille] Real-time preview update skipped:", err);
|
||||
}
|
||||
}
|
||||
|
||||
export function updateParameters() {
|
||||
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) {
|
||||
return;
|
||||
}
|
||||
state.resolution = parseInt(dom.input_resolution.value) || 20;
|
||||
state.plate_thickness = parseInt(dom.input_plate_thickness.value) || 3;
|
||||
state.unique_plate = !dom.input_separate_plates.checked;
|
||||
state.symbols_per_line = parseInt(dom.input_symbols_per_line.value) || 22;
|
||||
state.text_alignment = dom.select_text_alignment.value || "center";
|
||||
state.rounded = dom.input_rounded.checked;
|
||||
state.points_only = dom.input_points_only.checked;
|
||||
updatePlateWidth();
|
||||
triggerRealtimePreview(60);
|
||||
}
|
||||
|
||||
export function applyPointsOnlyState() {
|
||||
if (!dom.input_separate_plates || !dom.input_rounded || !dom.input_plate_thickness) return;
|
||||
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");
|
||||
if (card) {
|
||||
card.classList.toggle("opacity-50", state.points_only);
|
||||
card.classList.toggle("pointer-events-none", state.points_only);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
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; }
|
||||
|
||||
dom.input_resolution.value = state.resolution;
|
||||
dom.input_plate_thickness.value = state.plate_thickness;
|
||||
dom.input_separate_plates.checked = !state.unique_plate;
|
||||
dom.input_symbols_per_line.value = state.symbols_per_line;
|
||||
dom.select_text_alignment.value = state.text_alignment;
|
||||
dom.input_rounded.checked = state.rounded;
|
||||
dom.input_points_only.checked = state.points_only;
|
||||
dom.output_plate_width.innerHTML = state.plate_width.toFixed(1);
|
||||
}
|
||||
|
||||
export async function generateSTL() {
|
||||
const input_textbox = dom.input_textbox;
|
||||
const output_textbox = dom.output_textbox;
|
||||
const stl_button = dom.stl_button;
|
||||
if (!input_textbox || !output_textbox || !stl_button) return;
|
||||
|
||||
if (state.conversion_mode === "braille-to-text") {
|
||||
if (input_textbox.value.trim().length === 0) {
|
||||
showToast(getTranslation("toast_enter_braille"), "warning");
|
||||
highlightInput(input_textbox);
|
||||
return;
|
||||
}
|
||||
} else if (output_textbox.value.trim().length === 0) {
|
||||
if (input_textbox.value.trim().length === 0) {
|
||||
showToast(getTranslation("toast_enter_text"), "warning");
|
||||
highlightInput(input_textbox);
|
||||
return;
|
||||
}
|
||||
|
||||
showToast(getTranslation("toast_converting"), "info");
|
||||
await convert();
|
||||
if (output_textbox.value.trim().length === 0) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
let braille = output_textbox.value;
|
||||
if (state.conversion_mode === "braille-to-text") {
|
||||
braille = input_textbox.value;
|
||||
}
|
||||
if (braille.length === 0) { return; }
|
||||
|
||||
stl_button.disabled = true;
|
||||
const genText = getTranslation("generating_loader") || "Generating...";
|
||||
stl_button.innerHTML = `<i class="fas fa-spinner fa-spin mr-1"></i>${genText}`;
|
||||
|
||||
try {
|
||||
let arrayBuffer = null;
|
||||
const optionsPayload = {
|
||||
braille: braille,
|
||||
resolution: state.resolution,
|
||||
plate_thickness: state.plate_thickness,
|
||||
unique_plate: state.unique_plate,
|
||||
symbols_per_line: state.symbols_per_line,
|
||||
text_alignment: state.text_alignment,
|
||||
rounded: state.rounded,
|
||||
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;
|
||||
}
|
||||
|
||||
state.last_stl_blob = new Blob([arrayBuffer], { type: "model/stl" });
|
||||
|
||||
if (dom.stl_preview) {
|
||||
dom.stl_preview.classList.remove("hidden");
|
||||
}
|
||||
if (typeof window.renderSTLPreview === "function") {
|
||||
window.renderSTLPreview(arrayBuffer.slice(0), true);
|
||||
}
|
||||
if (dom.stl_preview) {
|
||||
dom.stl_preview.scrollIntoView({ behavior: "smooth", block: "nearest" });
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
alert(getTranslation("alert_stl_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}`;
|
||||
}
|
||||
}
|
||||
|
||||
export function downloadSTL() {
|
||||
if (!state.last_stl_blob) { return; }
|
||||
|
||||
const url = window.URL.createObjectURL(state.last_stl_blob);
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
link.setAttribute('download', 'output.stl');
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
window.URL.revokeObjectURL(url);
|
||||
}
|
||||
|
||||
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");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
export function showToast(message, severity = "info", duration = 4000) {
|
||||
let container = document.getElementById("toast-container");
|
||||
if (!container) {
|
||||
container = document.createElement("div");
|
||||
container.id = "toast-container";
|
||||
document.body.appendChild(container);
|
||||
}
|
||||
|
||||
const icons = {
|
||||
info: "fa-circle-info",
|
||||
warning: "fa-triangle-exclamation",
|
||||
error: "fa-circle-xmark",
|
||||
success: "fa-circle-check"
|
||||
};
|
||||
|
||||
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>`;
|
||||
container.appendChild(toast);
|
||||
|
||||
requestAnimationFrame(() => toast.classList.add("show"));
|
||||
|
||||
setTimeout(() => {
|
||||
toast.classList.remove("show");
|
||||
setTimeout(() => toast.remove(), 300);
|
||||
}, duration);
|
||||
}
|
||||
|
||||
export function highlightInput(inputTextbox) {
|
||||
const container = inputTextbox.closest(".text-area-container") || inputTextbox;
|
||||
inputTextbox.scrollIntoView({ behavior: "smooth", block: "center" });
|
||||
inputTextbox.focus({ preventScroll: true });
|
||||
|
||||
container.classList.remove("input-attention");
|
||||
void container.offsetWidth; // Force reflow
|
||||
container.classList.add("input-attention");
|
||||
setTimeout(() => container.classList.remove("input-attention"), 1900);
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
import * as THREE from "three";
|
||||
import { STLLoader } from "three/addons/loaders/STLLoader.js";
|
||||
import { OrbitControls } from "three/addons/controls/OrbitControls.js";
|
||||
|
||||
// The dots stick out 0.65 mm beyond the plate's front face (apparent thickness).
|
||||
// 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
|
||||
|
||||
let state = null;
|
||||
|
||||
function init(container) {
|
||||
const scene = new THREE.Scene();
|
||||
scene.background = new THREE.Color(0xf3f4f6);
|
||||
|
||||
const camera = new THREE.PerspectiveCamera(
|
||||
40,
|
||||
container.clientWidth / container.clientHeight,
|
||||
0.1,
|
||||
5000
|
||||
);
|
||||
camera.up.set(0, 0, 1);
|
||||
|
||||
const renderer = new THREE.WebGLRenderer({ antialias: true });
|
||||
renderer.setPixelRatio(window.devicePixelRatio);
|
||||
renderer.setSize(container.clientWidth, container.clientHeight);
|
||||
container.appendChild(renderer.domElement);
|
||||
|
||||
const controls = new OrbitControls(camera, renderer.domElement);
|
||||
controls.enableDamping = true;
|
||||
controls.dampingFactor = 0.08;
|
||||
|
||||
// Lighting
|
||||
scene.add(new THREE.AmbientLight(0xffffff, 0.8));
|
||||
const keyLight = new THREE.DirectionalLight(0xffffff, 1.0);
|
||||
keyLight.position.set(0.5, -1, 1);
|
||||
scene.add(keyLight);
|
||||
const fillLight = new THREE.DirectionalLight(0xffffff, 0.45);
|
||||
fillLight.position.set(-1, 0.5, 0.5);
|
||||
scene.add(fillLight);
|
||||
|
||||
state = { scene, camera, renderer, controls, container, mesh: null };
|
||||
|
||||
function animate() {
|
||||
state.rafId = requestAnimationFrame(animate);
|
||||
controls.update();
|
||||
renderer.render(scene, camera);
|
||||
}
|
||||
animate();
|
||||
|
||||
const resize = () => {
|
||||
if (!container.clientWidth || !container.clientHeight) { return; }
|
||||
camera.aspect = container.clientWidth / container.clientHeight;
|
||||
camera.updateProjectionMatrix();
|
||||
renderer.setSize(container.clientWidth, container.clientHeight);
|
||||
};
|
||||
window.addEventListener("resize", resize);
|
||||
state.resize = resize;
|
||||
}
|
||||
|
||||
function paintByHeight(geometry) {
|
||||
geometry.computeBoundingBox();
|
||||
const box = geometry.boundingBox;
|
||||
// The plate's front face sits exactly at (min.y + APPARENT_THICKNESS);
|
||||
// Threshold ensures the full dome of every dot is colored with DOT_COLOR.
|
||||
const threshold = box.min.y + APPARENT_THICKNESS - 0.01;
|
||||
|
||||
const position = geometry.attributes.position;
|
||||
const colors = new Float32Array(position.count * 3);
|
||||
for (let i = 0; i < position.count; i++) {
|
||||
const color = position.getY(i) < threshold ? DOT_COLOR : PLATE_COLOR;
|
||||
colors[i * 3] = color.r;
|
||||
colors[i * 3 + 1] = color.g;
|
||||
colors[i * 3 + 2] = color.b;
|
||||
}
|
||||
geometry.setAttribute("color", new THREE.BufferAttribute(colors, 3));
|
||||
}
|
||||
|
||||
function frameModel() {
|
||||
const { camera, controls, mesh, container } = state;
|
||||
|
||||
const box = new THREE.Box3().setFromObject(mesh);
|
||||
const size = box.getSize(new THREE.Vector3());
|
||||
const aspect = container.clientWidth / container.clientHeight;
|
||||
const fov = (camera.fov * Math.PI) / 180;
|
||||
|
||||
// We look along -Y: on screen the width is X and the height is Z.
|
||||
const fitHeight = (size.z / 2) / Math.tan(fov / 2);
|
||||
const fitWidth = (size.x / 2) / (Math.tan(fov / 2) * aspect);
|
||||
const distance = Math.max(fitHeight, fitWidth) * 1.15;
|
||||
|
||||
controls.target.set(0, 0, 0);
|
||||
// Mostly a front view (looking along +Y), with a slight tilt so the dots read as 3D.
|
||||
camera.position.set(distance * 0.08, -distance, distance * 0.16);
|
||||
camera.near = Math.max(distance / 1000, 0.01);
|
||||
camera.far = distance * 100;
|
||||
camera.updateProjectionMatrix();
|
||||
controls.update();
|
||||
}
|
||||
|
||||
window.renderSTLPreview = function (arrayBuffer, resetCamera = false) {
|
||||
const container = document.getElementById("stl_preview_canvas");
|
||||
if (!container) { return; }
|
||||
if (!state) { init(container); }
|
||||
|
||||
const isFirstLoad = !state.mesh;
|
||||
|
||||
if (state.mesh) {
|
||||
state.scene.remove(state.mesh);
|
||||
state.mesh.geometry.dispose();
|
||||
state.mesh.material.dispose();
|
||||
state.mesh = null;
|
||||
}
|
||||
|
||||
const geometry = new STLLoader().parse(arrayBuffer);
|
||||
geometry.computeVertexNormals();
|
||||
geometry.center();
|
||||
paintByHeight(geometry);
|
||||
|
||||
const material = new THREE.MeshStandardMaterial({
|
||||
vertexColors: true,
|
||||
metalness: 0.1,
|
||||
roughness: 0.55,
|
||||
side: THREE.DoubleSide
|
||||
});
|
||||
const mesh = new THREE.Mesh(geometry, material);
|
||||
state.scene.add(mesh);
|
||||
state.mesh = mesh;
|
||||
|
||||
if (isFirstLoad || resetCamera) {
|
||||
frameModel();
|
||||
}
|
||||
state.resize();
|
||||
};
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"name": "InBraille - Conversor de Texto para Braille e Modelagem STL 3D",
|
||||
"short_name": "InBraille",
|
||||
"description": "Ferramenta pública e gratuita que converte textos para Braille e exporta em formato STL para impressão 3D.",
|
||||
"start_url": "/",
|
||||
"scope": "/",
|
||||
"icons": [
|
||||
{"src": "/public/android-chrome-192x192.png", "sizes": "192x192", "type": "image/png"},
|
||||
{"src": "/public/android-chrome-512x512.png", "sizes": "512x512", "type": "image/png"}
|
||||
],
|
||||
"theme_color": "#3b82f6",
|
||||
"background_color": "#f9fafb",
|
||||
"display": "standalone"
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
.text-area-container {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.text-area-container label {
|
||||
position: absolute;
|
||||
top: -10px;
|
||||
left: 10px;
|
||||
background: white;
|
||||
padding: 0 5px;
|
||||
font-size: 0.9rem;
|
||||
color: #4b5563;
|
||||
}
|
||||
|
||||
.switch {
|
||||
position: relative;
|
||||
display: inline-block;
|
||||
width: 60px;
|
||||
height: 34px;
|
||||
}
|
||||
|
||||
.switch input {
|
||||
opacity: 0;
|
||||
width: 0;
|
||||
height: 0;
|
||||
}
|
||||
|
||||
.slider {
|
||||
position: absolute;
|
||||
cursor: pointer;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
background-color: #ccc;
|
||||
transition: .4s;
|
||||
border-radius: 34px;
|
||||
}
|
||||
|
||||
.slider:before {
|
||||
position: absolute;
|
||||
content: "";
|
||||
height: 26px;
|
||||
width: 26px;
|
||||
left: 4px;
|
||||
bottom: 4px;
|
||||
background-color: white;
|
||||
transition: .4s;
|
||||
border-radius: 50%;
|
||||
}
|
||||
|
||||
input:checked + .slider {
|
||||
background-color: #3b82f6;
|
||||
}
|
||||
|
||||
input:checked + .slider:before {
|
||||
transform: translateX(26px);
|
||||
}
|
||||
|
||||
input:disabled + .slider {
|
||||
background-color: #e5e7eb;
|
||||
}
|
||||
|
||||
.tab-active {
|
||||
border-bottom: 3px solid #3b82f6;
|
||||
color: #3b82f6;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.tooltip {
|
||||
position: relative;
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
.tooltip .tooltiptext {
|
||||
visibility: hidden;
|
||||
width: 200px;
|
||||
background-color: #555;
|
||||
color: #fff;
|
||||
text-align: center;
|
||||
border-radius: 6px;
|
||||
padding: 5px;
|
||||
position: absolute;
|
||||
z-index: 1;
|
||||
bottom: 125%;
|
||||
left: 50%;
|
||||
margin-left: -100px;
|
||||
opacity: 0;
|
||||
transition: opacity 0.3s;
|
||||
}
|
||||
|
||||
.tooltip:hover .tooltiptext {
|
||||
visibility: visible;
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
@keyframes fadeIn {
|
||||
from { opacity: 0; transform: translateY(10px); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
|
||||
.fade-in {
|
||||
animation: fadeIn 0.3s ease-out forwards;
|
||||
}
|
||||
|
||||
.neurodiversity-badge {
|
||||
background: linear-gradient(135deg, #6366f1, #8b5cf6);
|
||||
}
|
||||
|
||||
/* Language dropdown menu */
|
||||
.lang-menu > summary {
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
.lang-menu > summary::-webkit-details-marker {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.lang-menu[open] > summary .lang-caret {
|
||||
transform: rotate(180deg);
|
||||
}
|
||||
|
||||
/* MUI-like snackbar/alert toasts */
|
||||
#toast-container {
|
||||
position: fixed;
|
||||
bottom: 24px;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
z-index: 1000;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
align-items: center;
|
||||
width: auto;
|
||||
max-width: min(92vw, 480px);
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.toast {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 12px 18px;
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 6px 18px rgba(0, 0, 0, 0.18);
|
||||
font-size: 0.92rem;
|
||||
line-height: 1.35;
|
||||
color: #fff;
|
||||
opacity: 0;
|
||||
transform: translateY(24px);
|
||||
transition: opacity 0.3s ease, transform 0.3s ease;
|
||||
pointer-events: auto;
|
||||
}
|
||||
|
||||
.toast.show {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
|
||||
.toast i {
|
||||
font-size: 1.15rem;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.toast-info { background-color: #2563eb; }
|
||||
.toast-warning { background-color: #d97706; }
|
||||
.toast-error { background-color: #dc2626; }
|
||||
.toast-success { background-color: #16a34a; }
|
||||
|
||||
/* Attention pulse for a required input */
|
||||
.input-attention {
|
||||
animation: inputPulse 0.9s ease-in-out 0s 2;
|
||||
}
|
||||
|
||||
@keyframes inputPulse {
|
||||
0%, 100% { box-shadow: 0 0 0 0 rgba(239, 68, 68, 0); }
|
||||
50% { box-shadow: 0 0 0 4px rgba(239, 68, 68, 0.45); }
|
||||
}
|
||||
|
||||
/* Braille font definition with circular dots */
|
||||
@font-face {
|
||||
font-family: 'Noto Sans Symbols 2';
|
||||
font-style: normal;
|
||||
font-weight: 400 700;
|
||||
font-display: swap;
|
||||
src: url('/public/fonts/NotoSansSymbols2-Braille.woff2') format('woff2'),
|
||||
url('https://fonts.gstatic.com/s/notosanssymbols2/v25/I_uyMoGduATTei9eI8daxVHDyfisHr71-jrBWXPM4Q.woff2') format('woff2');
|
||||
unicode-range: U+2800-28FF;
|
||||
}
|
||||
|
||||
.braille-font,
|
||||
.braille-symbol,
|
||||
.braille-text,
|
||||
#input_text,
|
||||
#output_text {
|
||||
font-family: 'Noto Sans Symbols 2', 'Apple Braille', 'Segoe UI Symbol', sans-serif;
|
||||
}
|
||||
|
||||
.braille-symbol {
|
||||
font-weight: normal;
|
||||
letter-spacing: 0.05em;
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
.braille-hero {
|
||||
font-family: 'Noto Sans Symbols 2', 'Apple Braille', 'Segoe UI Symbol', sans-serif;
|
||||
font-weight: 400;
|
||||
line-height: 80%;
|
||||
color: #a024b4;
|
||||
user-select: none;
|
||||
display: inline-block;
|
||||
transition: transform 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
|
||||
}
|
||||
|
||||
.braille-hero:hover {
|
||||
transform: scale(1.06);
|
||||
}
|
||||
|
||||
/* FAQ Accordion Styling */
|
||||
details.faq-item summary::-webkit-details-marker {
|
||||
display: none;
|
||||
}
|
||||
details.faq-item summary {
|
||||
list-style: none;
|
||||
}
|
||||
details.faq-item[open] summary .faq-chevron {
|
||||
transform: rotate(180deg);
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import ptBR from './locales/pt_br.js';
|
||||
import en from './locales/en.js';
|
||||
import zh from './locales/zh.js';
|
||||
|
||||
export default {
|
||||
"pt-BR": ptBR,
|
||||
"en": en,
|
||||
"zh": zh
|
||||
};
|
||||
@@ -0,0 +1,5 @@
|
||||
[pytest]
|
||||
pythonpath = .
|
||||
testpaths = tests
|
||||
filterwarnings =
|
||||
ignore::DeprecationWarning
|
||||
@@ -0,0 +1,3 @@
|
||||
-r requirements.txt
|
||||
pytest==9.1.1
|
||||
httpx==0.28.1
|
||||
@@ -0,0 +1,27 @@
|
||||
annotated-doc==0.0.5
|
||||
annotated-types==0.8.0
|
||||
anyio==4.15.1
|
||||
click==8.5.0
|
||||
contourpy==1.4.0
|
||||
cycler==0.12.1
|
||||
fastapi==0.143.0
|
||||
fonttools==4.66.1
|
||||
h11==0.16.0
|
||||
idna==3.20
|
||||
kiwisolver==1.5.1
|
||||
matplotlib==3.11.2
|
||||
numpy==2.5.4
|
||||
opentelemetry-api==1.45.1
|
||||
packaging==26.3
|
||||
pillow==12.3.0
|
||||
pydantic==2.14.1
|
||||
pydantic_core==2.50.1
|
||||
pyparsing==3.3.3
|
||||
pypinyin==0.55.0
|
||||
python-dateutil==2.9.0.post0
|
||||
six==1.17.0
|
||||
starlette==1.8.0
|
||||
typing-inspection==0.4.4
|
||||
typing_extensions==4.16.0
|
||||
uvicorn==0.54.0
|
||||
vtk==9.7.1
|
||||
@@ -0,0 +1,4 @@
|
||||
User-agent: *
|
||||
Allow: /
|
||||
|
||||
Sitemap: https://inbraille.cienciaembarcada.com.br/sitemap.xml
|
||||
@@ -0,0 +1,21 @@
|
||||
#!/usr/bin/env bash
|
||||
# Uso: scripts/plano-imagem.sh <registro> <repositório>
|
||||
# Imprime inputs=, image= e reuse= (para $GITHUB_OUTPUT). O hash cobre só os
|
||||
# arquivos que entram no build da imagem, não a documentação nem a configuração
|
||||
# de ferramentas. reuse=true quando o registro já tem inputs-<hash>.
|
||||
set -euo pipefail
|
||||
registry=$1; ns=${2,,}
|
||||
|
||||
inputs=$(git ls-tree -r HEAD \
|
||||
| awk -F' ' '$2 !~ /^(\.gitea|\.github|\.claude|\.wolf|docs)\// && $2 !~ /^(README.*|CHANGELOG\.md|SECURITY\.md|LICENSE|\.gitignore|\.gitattributes|docker-compose.*\.yaml|scripts\/release-notes\.sh)$/' \
|
||||
| sha256sum | cut -c1-16)
|
||||
token=$(curl -fsS "https://$registry/v2/token?service=container_registry&scope=repository:$ns:pull" | jq -r .token)
|
||||
code=$(curl -s -o /dev/null -w '%{http_code}' -I \
|
||||
-H "Authorization: Bearer $token" \
|
||||
-H 'Accept: application/vnd.oci.image.index.v1+json,application/vnd.docker.distribution.manifest.list.v2+json,application/vnd.oci.image.manifest.v1+json' \
|
||||
"https://$registry/v2/$ns/manifests/inputs-$inputs")
|
||||
echo "inputs-$inputs -> HTTP $code" >&2
|
||||
reuse=false; [ "$code" = 200 ] && reuse=true
|
||||
echo "inputs=$inputs"
|
||||
echo "image=$registry/$ns"
|
||||
echo "reuse=$reuse"
|
||||
@@ -0,0 +1,39 @@
|
||||
#!/usr/bin/env bash
|
||||
# Imprime as notas de uma release: a imagem publicada (quando houver) e a seção
|
||||
# do CHANGELOG.md daquela versão (ou o log de commits desde a tag anterior, se
|
||||
# não houver seção).
|
||||
#
|
||||
# scripts/release-notes.sh v1.2.3 [git.exemplo.com/dono/projeto]
|
||||
set -euo pipefail
|
||||
|
||||
tag=${1:?uso: release-notes.sh <tag> [imagem]}
|
||||
image=${2:-}
|
||||
version=${tag#v}
|
||||
|
||||
if [ -n "$image" ]; then
|
||||
echo "## Imagem"
|
||||
echo
|
||||
echo '```'
|
||||
echo "$image:$version"
|
||||
echo '```'
|
||||
echo
|
||||
fi
|
||||
|
||||
section=""
|
||||
if [ -f CHANGELOG.md ]; then
|
||||
section=$(awk -v head="## [$version]" '
|
||||
index($0, head) == 1 { found = 1; next }
|
||||
found && /^## \[/ { exit }
|
||||
found && /^\[[^]]+\]: / { next }
|
||||
found { print }
|
||||
' CHANGELOG.md)
|
||||
fi
|
||||
|
||||
if [ -n "$(printf '%s' "$section" | tr -d '[:space:]')" ]; then
|
||||
printf '%s\n' "$section"
|
||||
else
|
||||
previous=$(git describe --tags --abbrev=0 "$tag^" 2>/dev/null || true)
|
||||
echo "## Mudanças${previous:+ desde $previous}"
|
||||
echo
|
||||
git log --no-merges --format='- %s (%h)' "${previous:+$previous..}$tag"
|
||||
fi
|
||||
@@ -0,0 +1,76 @@
|
||||
#!/usr/bin/env bash
|
||||
# Teste de fumaça da imagem do InBraille, do jeito que ela roda em produção
|
||||
# (--read-only, sem capabilities, usuário sem privilégios): as páginas e os arquivos de
|
||||
# SEO respondem, a API codifica, decodifica e GERA um STL de verdade (VTK e as bibliotecas
|
||||
# gráficas da imagem), os cabeçalhos de segurança estão lá e nada interno vaza.
|
||||
#
|
||||
# scripts/smoke-imagem.sh <imagem>
|
||||
#
|
||||
# Cada falha é impressa e o script sai com 1 no fim, para mostrar tudo de uma vez.
|
||||
set -uo pipefail
|
||||
|
||||
imagem=${1:?uso: smoke-imagem.sh <imagem>}
|
||||
app=inbraille-smoke-${GITHUB_RUN_ID:-$$}
|
||||
falhas=0
|
||||
falhou() { echo "FALHOU $1"; falhas=$((falhas + 1)); }
|
||||
|
||||
# Os daemons dos runners persistem entre jobs: limpa sempre, inclusive se falhar.
|
||||
trap 'docker rm -f "$app" >/dev/null 2>&1' EXIT
|
||||
|
||||
docker run -d --name "$app" --read-only --tmpfs /tmp --cap-drop ALL \
|
||||
--security-opt no-new-privileges:true "$imagem" >/dev/null || exit 1
|
||||
|
||||
ip=""
|
||||
for _ in $(seq 1 40); do
|
||||
ip=$(docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' "$app" 2>/dev/null)
|
||||
[ -n "$ip" ] && curl -fsS -o /dev/null "http://$ip:3000/" 2>/dev/null && break
|
||||
sleep 1
|
||||
done
|
||||
base=http://$ip:3000
|
||||
curl -fsS -o /dev/null "$base/" || { echo "FALHOU /: sem resposta"; docker logs "$app" | tail -20; exit 1; }
|
||||
|
||||
status() { [ "$(curl -s -o /dev/null -w '%{http_code}' "$base$2")" = "$1" ] || falhou "$2: esperado $1"; }
|
||||
|
||||
# Páginas (a mesma index.html atende os três idiomas) e arquivos de SEO.
|
||||
status 200 /
|
||||
status 200 /en
|
||||
status 200 /zh
|
||||
status 200 /robots.txt
|
||||
status 200 /sitemap.xml
|
||||
status 200 /google21a790a2c23c0ec5.html
|
||||
status 200 /public/index.js
|
||||
curl -s "$base/sitemap.xml" | python3 -c 'import sys,xml.dom.minidom as m; m.parseString(sys.stdin.read())' 2>/dev/null || falhou "/sitemap.xml: XML inválido"
|
||||
curl -s "$base/robots.txt" | grep -qi '^sitemap:' || falhou "/robots.txt: sem a linha Sitemap"
|
||||
|
||||
# Nada interno vaza, e a documentação interativa da API fica desligada.
|
||||
for p in /docs /openapi.json /main.py /src/config.py /public/../main.py /Dockerfile; do status 404 "$p"; done
|
||||
|
||||
# API: ida e volta do texto, e um STL pequeno de verdade.
|
||||
enc=$(curl -s -X POST "$base/api/encode" -H 'Content-Type: application/json' -d '{"text":"ola","alphabet":"Brazilian"}')
|
||||
printf %s "$enc" | grep -q '⠕' || falhou "/api/encode: resposta sem Braille ($enc)"
|
||||
stl=$(mktemp); trap 'rm -f "$stl"; docker rm -f "$app" >/dev/null 2>&1' EXIT
|
||||
code=$(curl -s -o "$stl" -w '%{http_code}' -X POST "$base/api/to-stl" -H 'Content-Type: application/json' -d '{"braille":"⠓⠑⠇⠇⠕","resolution":15}')
|
||||
[ "$code" = 200 ] || falhou "/api/to-stl: esperado 200, veio $code"
|
||||
# STL binário: 80 bytes de cabeçalho + 4 de contagem de triângulos + 50 bytes por triângulo.
|
||||
python3 - "$stl" <<'PY' || falhou "/api/to-stl: o STL gerado é inválido"
|
||||
import struct,sys,os
|
||||
b=open(sys.argv[1],'rb').read()
|
||||
n=struct.unpack('<I',b[80:84])[0]
|
||||
sys.exit(0 if n>0 and len(b)==84+50*n else 1)
|
||||
PY
|
||||
|
||||
# Limites: corpo grande demais é recusado.
|
||||
[ "$(head -c 70000 /dev/zero | curl -s -o /dev/null -w '%{http_code}' -X POST "$base/api/encode" --data-binary @-)" = 413 ] || falhou "/api/encode: corpo de 70 KB deveria dar 413"
|
||||
|
||||
# Cabeçalhos de segurança.
|
||||
head=$(curl -sI "$base/")
|
||||
grep -qi "^content-security-policy:.*frame-ancestors 'none'" <<< "$head" || falhou "/: CSP sem frame-ancestors"
|
||||
grep -qi '^x-content-type-options: nosniff' <<< "$head" || falhou "/: sem X-Content-Type-Options"
|
||||
grep -qi '^x-frame-options: DENY' <<< "$head" || falhou "/: sem X-Frame-Options"
|
||||
grep -qi '^cache-control: .*no-cache' <<< "$head" || falhou "/: sem Cache-Control no-cache (as páginas precisam revalidar)"
|
||||
|
||||
# Roda sem privilégios.
|
||||
[ "$(docker exec "$app" id -u)" = 10001 ] || falhou "o processo não roda como o usuário 10001"
|
||||
|
||||
[ "$falhas" = 0 ] && echo "ok: páginas, SEO, API (incl. STL), cabeçalhos e isolamento conferidos"
|
||||
[ "$falhas" = 0 ]
|
||||
@@ -0,0 +1,24 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">
|
||||
<url>
|
||||
<loc>https://inbraille.cienciaembarcada.com.br/</loc>
|
||||
<xhtml:link rel="alternate" hreflang="pt-BR" href="https://inbraille.cienciaembarcada.com.br/"/>
|
||||
<xhtml:link rel="alternate" hreflang="en" href="https://inbraille.cienciaembarcada.com.br/en"/>
|
||||
<xhtml:link rel="alternate" hreflang="zh" href="https://inbraille.cienciaembarcada.com.br/zh"/>
|
||||
<xhtml:link rel="alternate" hreflang="x-default" href="https://inbraille.cienciaembarcada.com.br/"/>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://inbraille.cienciaembarcada.com.br/en</loc>
|
||||
<xhtml:link rel="alternate" hreflang="pt-BR" href="https://inbraille.cienciaembarcada.com.br/"/>
|
||||
<xhtml:link rel="alternate" hreflang="en" href="https://inbraille.cienciaembarcada.com.br/en"/>
|
||||
<xhtml:link rel="alternate" hreflang="zh" href="https://inbraille.cienciaembarcada.com.br/zh"/>
|
||||
<xhtml:link rel="alternate" hreflang="x-default" href="https://inbraille.cienciaembarcada.com.br/"/>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://inbraille.cienciaembarcada.com.br/zh</loc>
|
||||
<xhtml:link rel="alternate" hreflang="pt-BR" href="https://inbraille.cienciaembarcada.com.br/"/>
|
||||
<xhtml:link rel="alternate" hreflang="en" href="https://inbraille.cienciaembarcada.com.br/en"/>
|
||||
<xhtml:link rel="alternate" hreflang="zh" href="https://inbraille.cienciaembarcada.com.br/zh"/>
|
||||
<xhtml:link rel="alternate" hreflang="x-default" href="https://inbraille.cienciaembarcada.com.br/"/>
|
||||
</url>
|
||||
</urlset>
|
||||
@@ -0,0 +1,17 @@
|
||||
"""Application settings. The port can be overridden with the PORT env var."""
|
||||
import os
|
||||
|
||||
|
||||
# Base dir is always resolved relative to this file, not the working directory.
|
||||
# This prevents breakage when the app is launched from a different cwd (e.g. Docker).
|
||||
_BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
|
||||
class Settings:
|
||||
PORT = int(os.getenv("PORT", "3000"))
|
||||
TEMPLATE_HTML = os.path.join(_BASE_DIR, "index.html")
|
||||
STATIC_DIR = os.path.join(_BASE_DIR, "public")
|
||||
GOOGLE_VERIFICATION_FILE = "google21a790a2c23c0ec5.html"
|
||||
GOOGLE_VERIFICATION_HTML = os.path.join(_BASE_DIR, GOOGLE_VERIFICATION_FILE)
|
||||
ROBOTS_TXT = os.path.join(_BASE_DIR, "robots.txt")
|
||||
SITEMAP_XML = os.path.join(_BASE_DIR, "sitemap.xml")
|
||||
@@ -0,0 +1,34 @@
|
||||
"""Braille alphabet tables: parallel lists mapping printable characters to their
|
||||
Braille counterparts. Kept as data only - no logic lives here.
|
||||
|
||||
NOTE: tables are copied verbatim from the original project data (including a pre-existing
|
||||
missing comma in the North American list that merges ":" and "'" into a single entry),
|
||||
so encoding/decoding results stay byte-identical.
|
||||
"""
|
||||
from dataclasses import dataclass
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Alphabet:
|
||||
normal: list[str]
|
||||
braille: list[str]
|
||||
|
||||
|
||||
BRAZILIAN = Alphabet(
|
||||
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=[
|
||||
'⠁', '⠃', '⠉', '⠙', '⠑', '⠋', '⠛', '⠓', '⠊', '⠚', '⠅', '⠇', '⠍', '⠝', '⠕', '⠏', '⠟', '⠗', '⠎', '⠞', '⠥', '⠧', '⠺', '⠭', '⠽', '⠵', '⠷', '⠿', '⠌', '⠬', '⠾', '⠫', '⠡', '⠣', '⠹', '⠜', '⠪', '⠯', '⠚', '⠁', '⠃', '⠉', '⠙', '⠑', '⠋', '⠛', '⠓', '⠊', '⠖', '⠢', '⠄', '⠂', '⠆', '⠒', '⠣⠄', '⠄⠜', '⠷⠄', '⠄⠾', '⠤', '⠖', '⠠⠂', '⠔', '⠯', '⠰', '⠸⠴', '⠶', '⠪', '⠕'
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
NORTH_AMERICAN = Alphabet(
|
||||
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=[
|
||||
'⠁', '⠃', '⠉', '⠙', '⠑', '⠋', '⠛', '⠓', '⠊', '⠚', '⠅', '⠇', '⠍', '⠝', '⠕', '⠏', '⠟', '⠗', '⠎', '⠞', '⠥', '⠧', '⠺', '⠭', '⠽', '⠵', '⠴', '⠂', '⠆', '⠒', '⠲', '⠢', '⠖', '⠶', '⠦', '⠔', '⠮', '⠹', '⠯', '⠫', '⠼', '⠈', '⠩', '⠷', '⠾', '⠪', '⠻', '⠸', '⠬', '⠤', '⠡', '⠌', '⠳', '⠿', '⠣', '⠜', '⠨', '⠠', '⠰', '⠱', '⠄', '⠐'
|
||||
],
|
||||
)
|
||||
@@ -0,0 +1,80 @@
|
||||
"""Maps each supported Braille character to its 6-dot code (dot1..dot6)."""
|
||||
|
||||
BRAILLE_CODES = {
|
||||
'⠁': '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',
|
||||
}
|
||||
|
||||
|
||||
def code_for(character: str) -> str:
|
||||
"""Return the 6-dot code (dot1..dot6) for a Braille character.
|
||||
|
||||
Uses the explicit map above (which keeps the historical ``⣄`` override) and falls
|
||||
back to deriving the code straight from the Unicode code point, so any Braille cell
|
||||
— including those produced by the Chinese code — can be turned into a 3D model.
|
||||
"""
|
||||
mapped = BRAILLE_CODES.get(character)
|
||||
if mapped is not None:
|
||||
return mapped
|
||||
value = ord(character) - 0x2800
|
||||
return "".join("1" if (value >> bit) & 1 else "0" for bit in range(6))
|
||||
@@ -0,0 +1,139 @@
|
||||
"""Mainland Chinese (Mandarin) Braille tables.
|
||||
|
||||
Source: Australian Braille Authority, "Chinese (Mandarin) and UEB" (May 2024),
|
||||
based on the official Chinese braille transcription system. Data only — the
|
||||
encoding/decoding logic lives in src/translation/encoder.py and src/translation/decoder.py.
|
||||
|
||||
A Mandarin syllable is written with up to three cells: initial + final + tone.
|
||||
Dot patterns below use dot numbers 1-6; _cell() turns them into Unicode braille.
|
||||
"""
|
||||
|
||||
|
||||
def _cell(dots: str) -> str:
|
||||
value = 0
|
||||
for dot in dots:
|
||||
value |= 1 << (int(dot) - 1)
|
||||
return chr(0x2800 + value)
|
||||
|
||||
|
||||
BLANK = _cell("") # empty cell, used as the space between words
|
||||
|
||||
|
||||
# 1. Initials / consonants (dot patterns). g/j, k/q and h/x deliberately share a
|
||||
# cell — the ambiguity is resolved by the following final.
|
||||
_INITIAL_DOTS = {
|
||||
"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",
|
||||
}
|
||||
|
||||
# 2. Finals / vowels (dot patterns). Both the standalone spelling (with y/w) and the
|
||||
# post-consonant spelling map to the same cell.
|
||||
_FINAL_DOTS = {
|
||||
"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",
|
||||
}
|
||||
|
||||
# 3. Tones, written after the syllable. Neutral tone (5/0) has no cell.
|
||||
_TONE_DOTS = {"1": "1", "2": "2", "3": "3", "4": "23"}
|
||||
|
||||
# 5. Punctuation, in dot-pattern cells (some are multi-cell).
|
||||
_PUNCTUATION_DOTS = {
|
||||
",": ["5"],
|
||||
",": ["5"],
|
||||
"、": ["4"],
|
||||
";": ["56"],
|
||||
";": ["56"],
|
||||
":": ["36"],
|
||||
":": ["36"],
|
||||
".": ["5", "23"],
|
||||
"。": ["5", "23"],
|
||||
"?": ["5", "3"],
|
||||
"?": ["5", "3"],
|
||||
"!": ["56", "2"],
|
||||
"!": ["56", "2"],
|
||||
"-": ["36"],
|
||||
"…": ["5", "5", "5"],
|
||||
}
|
||||
|
||||
# Initials whose "-i" final is not written (the buzzing/retroflex -i).
|
||||
BUZZING_INITIALS = ("zh", "ch", "sh", "r", "z", "c", "s")
|
||||
|
||||
# Initials after which a written "u..." final is actually the "ü..." series.
|
||||
YU_INITIALS = ("j", "q", "x")
|
||||
|
||||
# Accented pinyin vowel -> (base vowel, tone number).
|
||||
ACCENTS = {
|
||||
"ā": ("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"),
|
||||
"ü": ("ü", ""),
|
||||
}
|
||||
|
||||
|
||||
# Pre-computed Unicode-braille lookups used by the encoder.
|
||||
INITIAL_CELLS = {name: _cell(dots) for name, dots in _INITIAL_DOTS.items()}
|
||||
FINAL_CELLS = {name: _cell(dots) for name, dots in _FINAL_DOTS.items()}
|
||||
TONE_CELLS = {tone: _cell(dots) for tone, dots in _TONE_DOTS.items()}
|
||||
PUNCTUATION_CELLS = {
|
||||
char: "".join(_cell(dots) for dots in cells)
|
||||
for char, cells in _PUNCTUATION_DOTS.items()
|
||||
}
|
||||
|
||||
|
||||
def _first(mapping):
|
||||
"""Reverse a spelling->cell map to cell->spelling, keeping the first spelling."""
|
||||
reverse = {}
|
||||
for spelling, cell in mapping.items():
|
||||
reverse.setdefault(cell, spelling)
|
||||
return reverse
|
||||
|
||||
|
||||
# Reverse lookups used by the decoder (cell -> canonical spelling).
|
||||
INITIAL_BY_CELL = _first(INITIAL_CELLS)
|
||||
FINAL_BY_CELL = _first(FINAL_CELLS)
|
||||
|
||||
# When a final has no preceding initial it is spelled with its y/w standalone form.
|
||||
FINAL_STANDALONE_BY_CELL = {}
|
||||
for _spelling, _cell_char in FINAL_CELLS.items():
|
||||
if _spelling[0] in "yw":
|
||||
FINAL_STANDALONE_BY_CELL.setdefault(_cell_char, _spelling)
|
||||
for _cell_char, _plain in FINAL_BY_CELL.items():
|
||||
FINAL_STANDALONE_BY_CELL.setdefault(_cell_char, _plain)
|
||||
|
||||
TONE_BY_CELL = {cell: tone for tone, cell in TONE_CELLS.items()}
|
||||
PUNCTUATION_BY_CELL = {
|
||||
"".join(_cell(dots) for dots in cells): char
|
||||
for char, cells in _PUNCTUATION_DOTS.items()
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
"""Physical dimensions (in millimetres) of a Braille cell and its dots."""
|
||||
|
||||
|
||||
class Dimensions:
|
||||
dots_radius = 1
|
||||
dots_spacing = 2.7
|
||||
dots_apparent_thickness = 0.65
|
||||
cells_width = 4.7
|
||||
cells_height = 7.4
|
||||
cells_h_spacing = 6.6
|
||||
cells_v_spacing = 10.8
|
||||
@@ -0,0 +1,49 @@
|
||||
"""Port (abstraction) for the 3D primitives the model builder needs.
|
||||
|
||||
The builder depends only on this interface, never on a concrete 3D library, so the
|
||||
rendering backend (VTK today) can be swapped without touching the modeling logic.
|
||||
Meshes are opaque handles from the builder's point of view.
|
||||
"""
|
||||
from abc import ABC, abstractmethod
|
||||
|
||||
|
||||
class MeshEngine(ABC):
|
||||
@abstractmethod
|
||||
def create_scene(self):
|
||||
"""Create an empty scene that meshes can be added to."""
|
||||
|
||||
@abstractmethod
|
||||
def add(self, scene, mesh):
|
||||
"""Add a mesh to a scene."""
|
||||
|
||||
@abstractmethod
|
||||
def finalize(self, scene):
|
||||
"""Combine everything added to a scene into a single mesh and return it."""
|
||||
|
||||
@abstractmethod
|
||||
def translate(self, mesh, x, y, z, rotate_x=0.0):
|
||||
"""Return a copy of mesh translated by (x, y, z) then rotated around X."""
|
||||
|
||||
@abstractmethod
|
||||
def create_sphere(self, radius, resolution):
|
||||
"""Create a full sphere centered at the origin."""
|
||||
|
||||
@abstractmethod
|
||||
def create_cap(self, radius, apparent_thickness, resolution):
|
||||
"""Create a spherical cap of the given apparent thickness, base at z=0."""
|
||||
|
||||
@abstractmethod
|
||||
def create_plate(self, width, height, depth):
|
||||
"""Create a rectangular box centered at the origin."""
|
||||
|
||||
@abstractmethod
|
||||
def create_cylinder(self, radius, height, resolution):
|
||||
"""Create a cylinder used for rounded plate borders."""
|
||||
|
||||
@abstractmethod
|
||||
def bounds(self, mesh):
|
||||
"""Return the axis-aligned bounds (xmin, xmax, ymin, ymax, zmin, zmax)."""
|
||||
|
||||
@abstractmethod
|
||||
def copy(self, mesh):
|
||||
"""Return an independent copy of a mesh (for reusing a template)."""
|
||||
@@ -0,0 +1,8 @@
|
||||
"""Port (abstraction) for turning a finished mesh into serialized bytes."""
|
||||
from abc import ABC, abstractmethod
|
||||
|
||||
|
||||
class MeshSerializer(ABC):
|
||||
@abstractmethod
|
||||
def serialize(self, mesh) -> bytes:
|
||||
"""Serialize a mesh into the bytes of a 3D file (binary STL)."""
|
||||
@@ -0,0 +1,239 @@
|
||||
"""Builds the 3D mesh of a Braille text: plate, cells, orientation markers and the
|
||||
points-only orientation bar. Pure geometry composition — it talks only to a MeshEngine,
|
||||
so it has no knowledge of the underlying 3D library.
|
||||
"""
|
||||
from src.domain.braille_codes import code_for
|
||||
from src.domain.dimensions import Dimensions
|
||||
from src.modeling.mesh_engine import MeshEngine
|
||||
from src.modeling.options import ModelOptions
|
||||
|
||||
|
||||
class BrailleModelBuilder:
|
||||
def __init__(self, engine: MeshEngine, dimensions=Dimensions):
|
||||
self._engine = engine
|
||||
self._dimensions = dimensions
|
||||
|
||||
def build(self, braille: str, options: ModelOptions):
|
||||
engine = self._engine
|
||||
rules = self._dimensions
|
||||
|
||||
resolution = options.resolution
|
||||
plate_thickness = options.plate_thickness
|
||||
unique_plate = options.unique_plate
|
||||
symbols_per_line = options.symbols_per_line
|
||||
text_alignment = options.text_alignment
|
||||
rounded = options.rounded
|
||||
points_only = options.points_only
|
||||
|
||||
scene = engine.create_scene()
|
||||
|
||||
# Geometry for a given character is identical everywhere it appears, so build each
|
||||
# distinct character only once per request and reuse it for every occurrence.
|
||||
char_cache = {}
|
||||
|
||||
if points_only:
|
||||
# No plate is generated: caps rest on z=0, the layout is single-block and
|
||||
# plate-related options (separate plates / rounded borders) don't apply.
|
||||
unique_plate = True
|
||||
rounded = False
|
||||
|
||||
phrases = braille.split("\n")
|
||||
number_of_phrases = len(phrases)
|
||||
plate_width = ((symbols_per_line - 1) * rules.cells_h_spacing) + rules.cells_width
|
||||
letter_reference_z = 0 if points_only else (plate_thickness - (rules.dots_radius - rules.dots_apparent_thickness))
|
||||
reference_z = plate_thickness / 2
|
||||
plate_height = rules.cells_v_spacing
|
||||
border_size = rules.cells_width
|
||||
border_cylinder = engine.create_cylinder(border_size, plate_thickness, resolution)
|
||||
border_cylinder_x_reference = (border_size - 0.7) - border_size
|
||||
border_plate_x_reference = -(0.7 + (border_size / 2))
|
||||
|
||||
for phrase_index, phrase in enumerate(phrases):
|
||||
phrase_scene = engine.create_scene()
|
||||
this_phrase_width = ((len(phrase) - 1) * rules.cells_h_spacing) + rules.cells_width
|
||||
|
||||
if not unique_plate:
|
||||
this_plate_height = rules.cells_v_spacing * 2
|
||||
|
||||
plate_position_x = plate_width / 2
|
||||
plate_position_y = ((plate_height - rules.cells_height) / 2)
|
||||
|
||||
final_plate_width = plate_width + rules.cells_v_spacing
|
||||
this_plate = engine.create_plate(final_plate_width, this_plate_height, plate_thickness)
|
||||
engine.add(phrase_scene, engine.translate(this_plate, plate_position_x, plate_position_y, reference_z))
|
||||
|
||||
# Orientation marker: a raised dot on the bottom-left corner of the plate.
|
||||
engine.add(phrase_scene, self._corner_marker(
|
||||
plate_position_x - (final_plate_width / 2),
|
||||
plate_position_y - (this_plate_height / 2),
|
||||
plate_thickness,
|
||||
resolution
|
||||
))
|
||||
|
||||
if rounded:
|
||||
half_plate_height = this_plate_height / 2
|
||||
border_plate = engine.create_plate(border_size, (this_plate_height - (border_size * 2)), plate_thickness)
|
||||
|
||||
engine.add(phrase_scene, engine.translate(engine.copy(border_cylinder),
|
||||
border_cylinder_x_reference,
|
||||
(plate_position_y + half_plate_height - border_size),
|
||||
reference_z
|
||||
))
|
||||
engine.add(phrase_scene, engine.translate(engine.copy(border_cylinder),
|
||||
border_cylinder_x_reference + final_plate_width,
|
||||
(plate_position_y + half_plate_height - border_size),
|
||||
reference_z
|
||||
))
|
||||
engine.add(phrase_scene, engine.translate(engine.copy(border_cylinder),
|
||||
border_cylinder_x_reference,
|
||||
(plate_position_y - half_plate_height + border_size),
|
||||
reference_z
|
||||
))
|
||||
engine.add(phrase_scene, engine.translate(engine.copy(border_cylinder),
|
||||
border_cylinder_x_reference + final_plate_width,
|
||||
(plate_position_y - half_plate_height + border_size),
|
||||
reference_z
|
||||
))
|
||||
engine.add(phrase_scene, engine.translate(engine.copy(border_plate),
|
||||
(border_plate_x_reference - border_size),
|
||||
plate_position_y,
|
||||
reference_z
|
||||
))
|
||||
engine.add(phrase_scene, engine.translate(engine.copy(border_plate),
|
||||
(border_plate_x_reference + final_plate_width),
|
||||
plate_position_y,
|
||||
reference_z
|
||||
))
|
||||
|
||||
for letter_index, letter in enumerate(phrase):
|
||||
if letter == "⠀":
|
||||
continue
|
||||
|
||||
letter_position_y = -(rules.dots_radius)
|
||||
letter_position_x = (letter_index * rules.cells_h_spacing) + rules.dots_radius
|
||||
letter_position_z = letter_reference_z
|
||||
if unique_plate:
|
||||
letter_position_y -= (phrase_index * rules.cells_v_spacing)
|
||||
|
||||
if text_alignment == "center":
|
||||
letter_position_x += (plate_width - this_phrase_width) / 2
|
||||
elif text_alignment == "right":
|
||||
letter_position_x += (plate_width - this_phrase_width)
|
||||
|
||||
if letter not in char_cache:
|
||||
char_cache[letter] = self._character_to_cell(letter, resolution, points_only)
|
||||
letter_in_3d = char_cache[letter]
|
||||
engine.add(phrase_scene, engine.translate(letter_in_3d, letter_position_x, letter_position_y, letter_position_z))
|
||||
|
||||
phrase_mesh = engine.finalize(phrase_scene)
|
||||
phrase_position_z = phrase_index * (plate_thickness + rules.cells_v_spacing)
|
||||
if unique_plate:
|
||||
phrase_position_z = 0
|
||||
engine.add(scene, engine.translate(phrase_mesh, 0, 0, phrase_position_z))
|
||||
|
||||
if unique_plate and not points_only:
|
||||
border_y_reference = (rules.cells_v_spacing + ((rules.cells_v_spacing - rules.cells_height) / 2))
|
||||
plate_height = (number_of_phrases * rules.cells_v_spacing) + rules.cells_v_spacing
|
||||
plate_position_x = plate_width / 2
|
||||
plate_position_y = border_y_reference - (plate_height / 2)
|
||||
|
||||
final_plate_width = plate_width + rules.cells_v_spacing
|
||||
plate = engine.create_plate(final_plate_width, plate_height, plate_thickness)
|
||||
engine.add(scene, engine.translate(plate, plate_position_x, plate_position_y, reference_z))
|
||||
|
||||
# Orientation marker: a raised dot on the bottom-left corner so the plate isn't
|
||||
# read/printed upside down.
|
||||
engine.add(scene, self._corner_marker(
|
||||
plate_position_x - (final_plate_width / 2),
|
||||
plate_position_y - (plate_height / 2),
|
||||
plate_thickness,
|
||||
resolution
|
||||
))
|
||||
|
||||
if rounded:
|
||||
border_plate = engine.create_plate(border_size, (plate_height - (border_size * 2)), plate_thickness)
|
||||
|
||||
engine.add(scene, engine.translate(engine.copy(border_cylinder),
|
||||
border_cylinder_x_reference,
|
||||
(border_y_reference - border_size),
|
||||
reference_z
|
||||
))
|
||||
engine.add(scene, engine.translate(engine.copy(border_cylinder),
|
||||
(border_cylinder_x_reference + final_plate_width),
|
||||
(border_y_reference - border_size),
|
||||
reference_z
|
||||
))
|
||||
engine.add(scene, engine.translate(engine.copy(border_cylinder),
|
||||
border_cylinder_x_reference,
|
||||
(border_y_reference - plate_height + border_size),
|
||||
reference_z
|
||||
))
|
||||
engine.add(scene, engine.translate(engine.copy(border_cylinder),
|
||||
(border_cylinder_x_reference + final_plate_width),
|
||||
(border_y_reference - plate_height + border_size),
|
||||
reference_z
|
||||
))
|
||||
engine.add(scene, engine.translate(engine.copy(border_plate),
|
||||
(border_plate_x_reference - border_size),
|
||||
plate_position_y,
|
||||
reference_z
|
||||
))
|
||||
engine.add(scene, engine.translate(engine.copy(border_plate),
|
||||
(border_plate_x_reference + final_plate_width),
|
||||
plate_position_y,
|
||||
reference_z
|
||||
))
|
||||
|
||||
if points_only:
|
||||
# Add a thin orientation bar below the lowest dots so the user knows which
|
||||
# side is "down" and doesn't glue the points upside down.
|
||||
combined = engine.finalize(scene)
|
||||
bounds = engine.bounds(combined)
|
||||
x_min, x_max, y_min = bounds[0], bounds[1], bounds[2]
|
||||
bar_width = x_max - x_min
|
||||
if bar_width > 0:
|
||||
bar_depth = 1.2
|
||||
bar_height = rules.dots_apparent_thickness
|
||||
bar_gap = 0.8
|
||||
bar = engine.create_plate(bar_width, bar_depth, bar_height)
|
||||
engine.add(scene, engine.translate(
|
||||
bar,
|
||||
(x_min + x_max) / 2,
|
||||
y_min - bar_gap - (bar_depth / 2),
|
||||
bar_height / 2
|
||||
))
|
||||
|
||||
final_mesh = engine.finalize(scene)
|
||||
return engine.translate(final_mesh, 0, 0, 0, 90)
|
||||
|
||||
def _character_to_cell(self, character, resolution, points_only):
|
||||
code = code_for(character)
|
||||
return self._build_cell(code, self._dimensions.dots_radius, self._dimensions.dots_spacing, resolution, points_only)
|
||||
|
||||
def _build_cell(self, code, radius, spacing, resolution, points_only):
|
||||
engine = self._engine
|
||||
cell = engine.create_scene()
|
||||
|
||||
# Every dot in a cell is the same shape, so build it once and reuse it.
|
||||
dot = engine.create_cap(radius, self._dimensions.dots_apparent_thickness, resolution) if points_only else engine.create_sphere(radius, resolution)
|
||||
|
||||
dot_positions = [
|
||||
(0, 2 * spacing),
|
||||
(0, spacing),
|
||||
(0, 0),
|
||||
(spacing, 2 * spacing),
|
||||
(spacing, spacing),
|
||||
(spacing, 0),
|
||||
]
|
||||
for index, (x, y) in enumerate(dot_positions):
|
||||
if code[index] == "1":
|
||||
engine.add(cell, engine.translate(dot, x, y, 0))
|
||||
|
||||
return engine.finalize(cell)
|
||||
|
||||
def _corner_marker(self, corner_x, corner_y, plate_thickness, resolution):
|
||||
engine = self._engine
|
||||
inset = 3.0
|
||||
marker_radius = 1.6
|
||||
marker = engine.create_cap(marker_radius, self._dimensions.dots_apparent_thickness, resolution)
|
||||
return engine.translate(marker, corner_x + inset, corner_y + inset, plate_thickness)
|
||||
@@ -0,0 +1,13 @@
|
||||
"""Parameters that control how a Braille STL model is generated."""
|
||||
from dataclasses import dataclass
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ModelOptions:
|
||||
resolution: int = 20
|
||||
plate_thickness: int = 2
|
||||
unique_plate: bool = False
|
||||
symbols_per_line: int = 20
|
||||
text_alignment: str = "left"
|
||||
rounded: bool = False
|
||||
points_only: bool = False
|
||||
@@ -0,0 +1,28 @@
|
||||
"""Use case: turn a Braille string into the bytes of an STL file."""
|
||||
from collections import OrderedDict
|
||||
from src.modeling.mesh_serializer import MeshSerializer
|
||||
from src.modeling.model_builder import BrailleModelBuilder
|
||||
from src.modeling.options import ModelOptions
|
||||
|
||||
|
||||
class StlService:
|
||||
def __init__(self, builder: BrailleModelBuilder, serializer: MeshSerializer, cache_size: int = 128):
|
||||
self._builder = builder
|
||||
self._serializer = serializer
|
||||
self._cache = OrderedDict()
|
||||
self._cache_size = cache_size
|
||||
|
||||
def generate(self, braille: str, options: ModelOptions) -> bytes:
|
||||
cache_key = (braille, options)
|
||||
if cache_key in self._cache:
|
||||
self._cache.move_to_end(cache_key)
|
||||
return self._cache[cache_key]
|
||||
|
||||
mesh = self._builder.build(braille, options)
|
||||
stl_bytes = self._serializer.serialize(mesh)
|
||||
|
||||
if len(self._cache) >= self._cache_size:
|
||||
self._cache.popitem(last=False)
|
||||
self._cache[cache_key] = stl_bytes
|
||||
|
||||
return stl_bytes
|
||||
@@ -0,0 +1,81 @@
|
||||
"""VTK implementation of the MeshEngine port."""
|
||||
import copy
|
||||
|
||||
import vtk
|
||||
|
||||
from src.modeling.mesh_engine import MeshEngine
|
||||
|
||||
|
||||
class VtkMeshEngine(MeshEngine):
|
||||
def create_scene(self):
|
||||
return vtk.vtkAppendPolyData()
|
||||
|
||||
def add(self, scene, mesh):
|
||||
scene.AddInputData(mesh)
|
||||
|
||||
def finalize(self, scene):
|
||||
if scene.GetNumberOfInputConnections(0) == 0:
|
||||
return vtk.vtkPolyData()
|
||||
scene.Update()
|
||||
return scene.GetOutput()
|
||||
|
||||
def translate(self, mesh, x, y, z, rotate_x=0.0):
|
||||
transform = vtk.vtkTransform()
|
||||
transform.Translate(x, y, z)
|
||||
transform.RotateX(rotate_x)
|
||||
transform_filter = vtk.vtkTransformPolyDataFilter()
|
||||
transform_filter.SetTransform(transform)
|
||||
transform_filter.SetInputData(mesh)
|
||||
transform_filter.Update()
|
||||
return transform_filter.GetOutput()
|
||||
|
||||
def create_sphere(self, radius, resolution):
|
||||
sphere = vtk.vtkSphereSource()
|
||||
sphere.SetRadius(radius)
|
||||
sphere.SetThetaResolution(resolution)
|
||||
sphere.SetPhiResolution(resolution)
|
||||
sphere.SetCenter(0, 0, 0)
|
||||
sphere.Update()
|
||||
return sphere.GetOutput()
|
||||
|
||||
def create_cap(self, radius, apparent_thickness, resolution):
|
||||
sphere = self.create_sphere(radius, resolution)
|
||||
|
||||
cut_z = radius - apparent_thickness
|
||||
plane = vtk.vtkPlane()
|
||||
plane.SetOrigin(0, 0, cut_z)
|
||||
plane.SetNormal(0, 0, 1)
|
||||
|
||||
planes = vtk.vtkPlaneCollection()
|
||||
planes.AddItem(plane)
|
||||
|
||||
clipper = vtk.vtkClipClosedSurface()
|
||||
clipper.SetInputData(sphere)
|
||||
clipper.SetClippingPlanes(planes)
|
||||
clipper.Update()
|
||||
|
||||
return self.translate(clipper.GetOutput(), 0, 0, -cut_z)
|
||||
|
||||
def create_plate(self, width, height, depth):
|
||||
plate = vtk.vtkCubeSource()
|
||||
plate.SetXLength(width)
|
||||
plate.SetYLength(height)
|
||||
plate.SetZLength(depth)
|
||||
plate.SetCenter(0, 0, 0)
|
||||
plate.Update()
|
||||
return plate.GetOutput()
|
||||
|
||||
def create_cylinder(self, radius, height, resolution):
|
||||
cylinder = vtk.vtkCylinderSource()
|
||||
cylinder.SetRadius(radius)
|
||||
cylinder.SetHeight(height)
|
||||
cylinder.SetResolution(resolution)
|
||||
cylinder.SetCenter(0, 0, 0)
|
||||
cylinder.Update()
|
||||
return self.translate(cylinder.GetOutput(), -radius, 0, 0, 90)
|
||||
|
||||
def bounds(self, mesh):
|
||||
return mesh.GetBounds()
|
||||
|
||||
def copy(self, mesh):
|
||||
return copy.deepcopy(mesh)
|
||||
@@ -0,0 +1,68 @@
|
||||
"""VTK implementation of the MeshSerializer port.
|
||||
|
||||
Encodes a binary STL fully in memory and returns it as bytes. Nothing is written to
|
||||
disk, so concurrent requests never share (or overwrite) a file on the server.
|
||||
"""
|
||||
import struct
|
||||
|
||||
import numpy as np
|
||||
import vtk
|
||||
from vtk.util import numpy_support
|
||||
|
||||
from src.modeling.mesh_serializer import MeshSerializer
|
||||
|
||||
|
||||
class VtkStlSerializer(MeshSerializer):
|
||||
def serialize(self, mesh) -> bytes:
|
||||
triangulator = vtk.vtkTriangleFilter()
|
||||
triangulator.SetInputData(mesh)
|
||||
triangulator.PassLinesOff()
|
||||
triangulator.PassVertsOff()
|
||||
triangulator.Update()
|
||||
triangles = triangulator.GetOutput()
|
||||
|
||||
header = b"\0" * 80 # 80-byte header (unused)
|
||||
|
||||
points_data = triangles.GetPoints()
|
||||
triangle_count = triangles.GetNumberOfPolys()
|
||||
if points_data is None or triangle_count == 0:
|
||||
return header + struct.pack("<I", 0)
|
||||
|
||||
points = numpy_support.vtk_to_numpy(points_data.GetData()).astype("<f4")
|
||||
# Triangulated polys are stored as [3, i, j, k, 3, i, j, k, ...]
|
||||
connectivity = numpy_support.vtk_to_numpy(triangles.GetPolys().GetData()).reshape(-1, 4)
|
||||
indices = connectivity[:, 1:4]
|
||||
|
||||
v0 = points[indices[:, 0]]
|
||||
v1 = points[indices[:, 1]]
|
||||
v2 = points[indices[:, 2]]
|
||||
|
||||
# Direct vectorized cross-product and normalization
|
||||
d1 = v1 - v0
|
||||
d2 = v2 - v0
|
||||
cx = d1[:, 1] * d2[:, 2] - d1[:, 2] * d2[:, 1]
|
||||
cy = d1[:, 2] * d2[:, 0] - d1[:, 0] * d2[:, 2]
|
||||
cz = d1[:, 0] * d2[:, 1] - d1[:, 1] * d2[:, 0]
|
||||
inv_lengths = 1.0 / np.maximum(np.sqrt(cx * cx + cy * cy + cz * cz), 1e-12)
|
||||
normals = np.empty((triangle_count, 3), dtype="<f4")
|
||||
normals[:, 0] = cx * inv_lengths
|
||||
normals[:, 1] = cy * inv_lengths
|
||||
normals[:, 2] = cz * inv_lengths
|
||||
|
||||
# Each STL record is 50 bytes: normal (12B) + 3 vertices (36B) + attribute (2B).
|
||||
# Packing via structured dtype allocates contiguous memory directly and avoids slow strided slices.
|
||||
stl_dtype = np.dtype([
|
||||
("normal", "<f4", 3),
|
||||
("v0", "<f4", 3),
|
||||
("v1", "<f4", 3),
|
||||
("v2", "<f4", 3),
|
||||
("attr", "<u2"),
|
||||
])
|
||||
records = np.empty(triangle_count, dtype=stl_dtype)
|
||||
records["normal"] = normals
|
||||
records["v0"] = v0
|
||||
records["v1"] = v1
|
||||
records["v2"] = v2
|
||||
records["attr"] = 0
|
||||
|
||||
return header + struct.pack("<I", triangle_count) + records.tobytes()
|
||||
@@ -0,0 +1,200 @@
|
||||
"""Braille -> text decoding strategies (one function per alphabet)."""
|
||||
from src.domain.alphabets import BRAZILIAN, NORTH_AMERICAN
|
||||
from src.domain import chinese_braille as cb
|
||||
|
||||
|
||||
def decode_north_american(braille):
|
||||
text = ""
|
||||
phrases = braille.split("\n")
|
||||
for phrase in phrases:
|
||||
words = phrase.replace('"', "'").split(" ")
|
||||
for word in words:
|
||||
for letter in word:
|
||||
try:
|
||||
index_of_letter = NORTH_AMERICAN.braille.index(letter)
|
||||
text += NORTH_AMERICAN.normal[index_of_letter]
|
||||
except:
|
||||
pass
|
||||
text += " "
|
||||
|
||||
text = text.rstrip() + "\n"
|
||||
|
||||
return text.rstrip()
|
||||
|
||||
|
||||
|
||||
def decode_brazilian(braille):
|
||||
text = ""
|
||||
phrases = braille.split("\n")
|
||||
for phrase in phrases:
|
||||
for word in phrase.split("⠀"):
|
||||
try:
|
||||
treated_word = word
|
||||
|
||||
is_number = word[0] == "⠼"
|
||||
if is_number:
|
||||
treated_word = treated_word[1:]
|
||||
|
||||
if word.startswith("⠣⠄"):
|
||||
text += "("
|
||||
treated_word = treated_word[2:]
|
||||
|
||||
if word.startswith("⠷⠄"):
|
||||
text += "["
|
||||
treated_word = treated_word[2:]
|
||||
|
||||
if word.endswith("⠄⠜"):
|
||||
treated_word = treated_word[:-2]
|
||||
|
||||
if word.endswith("⠄⠾"):
|
||||
treated_word = treated_word[:-2]
|
||||
|
||||
is_upper_case = False
|
||||
if not is_number and word.startswith("⠨⠨"):
|
||||
is_upper_case = True
|
||||
treated_word = treated_word[2:]
|
||||
|
||||
last_letter = None
|
||||
for letter in treated_word:
|
||||
if letter == "⠠" or letter == "⠨":
|
||||
last_letter = letter
|
||||
continue
|
||||
|
||||
if letter == "⠂" and last_letter == "⠠":
|
||||
text += "/"
|
||||
continue
|
||||
|
||||
if letter == "⠴" and last_letter == "⠸":
|
||||
text += "%"
|
||||
continue
|
||||
|
||||
if is_number and letter == "⠂":
|
||||
is_number = False
|
||||
continue
|
||||
|
||||
index_of_letter = -1
|
||||
try:
|
||||
index_of_letter = BRAZILIAN.braille.index(letter)
|
||||
except:
|
||||
last_letter = letter
|
||||
continue
|
||||
|
||||
if is_number:
|
||||
index_of_letter = (BRAZILIAN.braille[38:]).index(letter) + 38
|
||||
|
||||
if is_upper_case or last_letter == "⠨":
|
||||
text += BRAZILIAN.normal[index_of_letter].upper()
|
||||
else:
|
||||
text += BRAZILIAN.normal[index_of_letter]
|
||||
|
||||
last_letter = letter
|
||||
|
||||
if word.endswith("⠄⠜"):
|
||||
text += ")"
|
||||
|
||||
if word.endswith("⠄⠾"):
|
||||
text += "]"
|
||||
|
||||
except:
|
||||
pass
|
||||
|
||||
text += " "
|
||||
|
||||
text = text.rstrip() + "\n"
|
||||
|
||||
return text.rstrip()
|
||||
|
||||
|
||||
# --- Chinese (Mandarin) Decoding ---
|
||||
|
||||
_YU_FINALS = {"ü": "u", "üe": "ue", "üan": "uan", "ün": "un"}
|
||||
_I_OR_YU_START = ("i", "ü")
|
||||
|
||||
|
||||
def _decode_line(line: str) -> str:
|
||||
words = line.split(cb.BLANK)
|
||||
return " ".join(_decode_word(word) for word in words if word)
|
||||
|
||||
|
||||
def _match_punctuation(word: str, index: int):
|
||||
# Try the longest punctuation cell sequence first (up to 3 cells).
|
||||
for size in (3, 2, 1):
|
||||
chunk = word[index:index + size]
|
||||
if chunk in cb.PUNCTUATION_BY_CELL:
|
||||
return cb.PUNCTUATION_BY_CELL[chunk], size
|
||||
return None
|
||||
|
||||
|
||||
def _decode_word(word: str) -> str:
|
||||
output = ""
|
||||
index = 0
|
||||
length = len(word)
|
||||
while index < length:
|
||||
punctuation = _match_punctuation(word, index)
|
||||
if punctuation:
|
||||
output += punctuation[0]
|
||||
index += punctuation[1]
|
||||
continue
|
||||
|
||||
cell = word[index]
|
||||
initial = cb.INITIAL_BY_CELL.get(cell)
|
||||
has_initial = initial is not None
|
||||
if has_initial:
|
||||
index += 1
|
||||
|
||||
final_cell = None
|
||||
if index < length and word[index] in cb.FINAL_BY_CELL:
|
||||
final_cell = word[index]
|
||||
index += 1
|
||||
|
||||
tone = ""
|
||||
if index < length and word[index] in cb.TONE_BY_CELL:
|
||||
tone = cb.TONE_BY_CELL[word[index]]
|
||||
index += 1
|
||||
|
||||
if not has_initial and final_cell is None:
|
||||
index += 1 # unknown cell
|
||||
continue
|
||||
|
||||
output += _render_syllable(initial or "", final_cell, tone)
|
||||
return output
|
||||
|
||||
|
||||
def _render_syllable(initial: str, final_cell, tone: str) -> str:
|
||||
if initial and final_cell is None:
|
||||
# Contracted single-cell syllables.
|
||||
if initial in cb.BUZZING_INITIALS:
|
||||
syllable = initial + "i"
|
||||
elif initial == "d":
|
||||
syllable = "de"
|
||||
else:
|
||||
syllable = initial
|
||||
return syllable + tone
|
||||
|
||||
if final_cell is None:
|
||||
return tone
|
||||
|
||||
if not initial:
|
||||
final = cb.FINAL_STANDALONE_BY_CELL.get(final_cell, cb.FINAL_BY_CELL[final_cell])
|
||||
return final + tone
|
||||
|
||||
final = cb.FINAL_BY_CELL[final_cell]
|
||||
|
||||
# Resolve the shared initial cells using the following final.
|
||||
if final[0] in _I_OR_YU_START:
|
||||
initial = {"g": "j", "k": "q", "h": "x"}.get(initial, initial)
|
||||
|
||||
# After j/q/x the ü-finals are spelled with a plain u.
|
||||
if initial in cb.YU_INITIALS and final in _YU_FINALS:
|
||||
final = _YU_FINALS[final]
|
||||
|
||||
# Disambiguate final cell ⠢ (o vs e) based on phonotactics
|
||||
if final == "o" and initial not in ("", "b", "p", "m", "f"):
|
||||
final = "e"
|
||||
|
||||
return initial + final + tone
|
||||
|
||||
|
||||
def decode_chinese(braille: str) -> str:
|
||||
lines = braille.split("\n")
|
||||
return "\n".join(_decode_line(line) for line in lines)␍
|
||||
@@ -0,0 +1,248 @@
|
||||
"""Text -> Braille encoding strategies (one function per alphabet)."""
|
||||
import re
|
||||
from pypinyin import pinyin, Style
|
||||
|
||||
from src.domain.alphabets import BRAZILIAN, NORTH_AMERICAN
|
||||
from src.domain import chinese_braille as cb
|
||||
|
||||
|
||||
def encode_north_american(text):
|
||||
braille = ""
|
||||
phrases = text.split("\n")
|
||||
for phrase in phrases:
|
||||
words = phrase.replace('"', "'").split(" ")
|
||||
for word in words:
|
||||
for letter in word:
|
||||
try:
|
||||
index_of_letter = NORTH_AMERICAN.normal.index(letter.lower())
|
||||
braille += NORTH_AMERICAN.braille[index_of_letter]
|
||||
except:
|
||||
pass
|
||||
braille += " "
|
||||
|
||||
braille = braille.rstrip() + "\n"
|
||||
|
||||
return braille.rstrip()
|
||||
|
||||
|
||||
|
||||
def encode_brazilian(text):
|
||||
treated_text = ""
|
||||
phrases = text.split("\n")
|
||||
for phrase in phrases:
|
||||
for word in phrase.split(" "):
|
||||
for index, letter in enumerate(word):
|
||||
last_letter_is_alpha = False
|
||||
next_letter_is_alpha = False
|
||||
|
||||
if index > 0:
|
||||
last_letter_is_alpha = word[index - 1].isalpha()
|
||||
|
||||
if index < len(word) - 1:
|
||||
next_letter_is_alpha = word[index + 1].isalpha()
|
||||
|
||||
if last_letter_is_alpha and letter == "(":
|
||||
treated_text += " "
|
||||
|
||||
treated_text += letter
|
||||
|
||||
if next_letter_is_alpha and letter == ")":
|
||||
treated_text += " "
|
||||
|
||||
treated_text += " "
|
||||
|
||||
treated_text = treated_text.rstrip() + "\n"
|
||||
|
||||
braille = ""
|
||||
phrases = treated_text.split("\n")
|
||||
for phrase in phrases:
|
||||
for word in phrase.split(" "):
|
||||
try:
|
||||
is_number = word[0].isnumeric()
|
||||
if is_number:
|
||||
braille += "⠼"
|
||||
|
||||
is_upper_case = word.isupper()
|
||||
if not is_number and is_upper_case:
|
||||
braille += "⠨⠨"
|
||||
|
||||
last_letter = None
|
||||
for letter in word:
|
||||
index_of_letter = BRAZILIAN.normal.index(letter.lower())
|
||||
|
||||
if not is_number and letter.isnumeric():
|
||||
braille += "⠼"
|
||||
|
||||
if letter.isupper() and not is_upper_case:
|
||||
braille += "⠨"
|
||||
|
||||
if last_letter:
|
||||
if last_letter.isnumeric() and letter.isalpha():
|
||||
braille += "⠂"
|
||||
|
||||
braille += BRAZILIAN.braille[index_of_letter]
|
||||
last_letter = letter
|
||||
braille += " "
|
||||
except:
|
||||
pass
|
||||
|
||||
braille = braille.rstrip() + "\n"
|
||||
|
||||
return braille.rstrip().replace(" ", "⠀")
|
||||
|
||||
|
||||
# --- Chinese (Mandarin) Encoding ---
|
||||
|
||||
_HAN_RE = re.compile(r"[一-鿿]")
|
||||
|
||||
|
||||
def _contains_hanzi(text: str) -> bool:
|
||||
return bool(_HAN_RE.search(text))
|
||||
|
||||
|
||||
def _han_chunks(text: str):
|
||||
"""Yield (is_han, chunk) runs so Han characters convert with polyphone context."""
|
||||
for is_han, group in _group_by(text, lambda c: bool(_HAN_RE.match(c))):
|
||||
yield is_han, group
|
||||
|
||||
|
||||
def _group_by(text, key):
|
||||
if not text:
|
||||
return
|
||||
current_key = key(text[0])
|
||||
buffer = text[0]
|
||||
for char in text[1:]:
|
||||
k = key(char)
|
||||
if k == current_key:
|
||||
buffer += char
|
||||
else:
|
||||
yield current_key, buffer
|
||||
current_key, buffer = k, char
|
||||
yield current_key, buffer
|
||||
|
||||
|
||||
def _hanzi_to_pinyin(text: str) -> str:
|
||||
parts = []
|
||||
for is_han, chunk in _han_chunks(text):
|
||||
if is_han:
|
||||
syllables = pinyin(chunk, style=Style.TONE3, neutral_tone_with_five=True)
|
||||
parts.append("".join(s[0] for s in syllables))
|
||||
else:
|
||||
parts.append(chunk)
|
||||
return "".join(parts)
|
||||
|
||||
|
||||
def _encode_line(line: str) -> str:
|
||||
words = line.split(" ")
|
||||
return cb.BLANK.join(_encode_word(word) for word in words)
|
||||
|
||||
|
||||
def _encode_word(word: str) -> str:
|
||||
cells = []
|
||||
buffer = ""
|
||||
for char in word:
|
||||
if char in cb.PUNCTUATION_CELLS:
|
||||
if buffer:
|
||||
cells.append(_encode_pinyin(buffer))
|
||||
buffer = ""
|
||||
cells.append(cb.PUNCTUATION_CELLS[char])
|
||||
else:
|
||||
buffer += char
|
||||
if buffer:
|
||||
cells.append(_encode_pinyin(buffer))
|
||||
return "".join(cells)
|
||||
|
||||
|
||||
def _strip_accents(segment: str):
|
||||
plain = []
|
||||
tones = {}
|
||||
for char in segment:
|
||||
if char in cb.ACCENTS:
|
||||
base, tone = cb.ACCENTS[char]
|
||||
if tone:
|
||||
tones[len(plain)] = tone
|
||||
plain.append(base)
|
||||
else:
|
||||
plain.append(char)
|
||||
return "".join(plain), tones
|
||||
|
||||
|
||||
def _parse_syllables(plain: str, tones: dict):
|
||||
result = []
|
||||
index = 0
|
||||
length = len(plain)
|
||||
while index < length:
|
||||
char = plain[index]
|
||||
if char in "'’ " or char.isdigit():
|
||||
index += 1
|
||||
continue
|
||||
|
||||
start = index
|
||||
initial = ""
|
||||
if plain[index:index + 2] in cb.INITIAL_CELLS:
|
||||
initial = plain[index:index + 2]
|
||||
index += 2
|
||||
elif plain[index:index + 1] in cb.INITIAL_CELLS:
|
||||
initial = plain[index]
|
||||
index += 1
|
||||
|
||||
rest = plain[index:]
|
||||
if initial in cb.YU_INITIALS and rest[:1] == "u":
|
||||
rest = "ü" + rest[1:]
|
||||
|
||||
final = ""
|
||||
for size in range(4, 0, -1):
|
||||
candidate = rest[:size]
|
||||
if candidate in cb.FINAL_CELLS:
|
||||
final = candidate
|
||||
index += size
|
||||
break
|
||||
|
||||
tone = ""
|
||||
if index < length and plain[index] in "012345":
|
||||
tone = plain[index]
|
||||
index += 1
|
||||
if not tone:
|
||||
for position in range(start, index):
|
||||
if position in tones:
|
||||
tone = tones[position]
|
||||
break
|
||||
|
||||
if not initial and not final:
|
||||
index = start + 1
|
||||
continue
|
||||
|
||||
result.append((initial, final, tone))
|
||||
return result
|
||||
|
||||
|
||||
def _encode_pinyin(segment: str) -> str:
|
||||
plain, tones = _strip_accents(segment)
|
||||
return "".join(_encode_syllable(*syllable) for syllable in _parse_syllables(plain, tones))
|
||||
|
||||
|
||||
def _encode_syllable(initial: str, final: str, tone: str) -> str:
|
||||
cells = ""
|
||||
if initial in cb.BUZZING_INITIALS and final == "i":
|
||||
# The buzzing/retroflex -i is not written: only the initial.
|
||||
cells += cb.INITIAL_CELLS[initial]
|
||||
elif initial == "d" and final == "e" and tone in ("", "5", "0"):
|
||||
# Neutral "de" (的/地/得) is contracted to the initial d.
|
||||
cells += cb.INITIAL_CELLS["d"]
|
||||
tone = ""
|
||||
else:
|
||||
if initial:
|
||||
cells += cb.INITIAL_CELLS[initial]
|
||||
if final:
|
||||
cells += cb.FINAL_CELLS[final]
|
||||
|
||||
if tone in cb.TONE_CELLS:
|
||||
cells += cb.TONE_CELLS[tone]
|
||||
return cells
|
||||
|
||||
|
||||
def encode_chinese(text: str) -> str:
|
||||
if _contains_hanzi(text):
|
||||
text = _hanzi_to_pinyin(text)
|
||||
lines = text.split("\n")
|
||||
return "\n".join(_encode_line(line) for line in lines)␍
|
||||
@@ -0,0 +1,33 @@
|
||||
"""Facade that dispatches encoding/decoding to the right alphabet strategy.
|
||||
|
||||
Adding a new alphabet is a matter of registering its functions here (open/closed).
|
||||
"""
|
||||
from src.translation.encoder import encode_brazilian, encode_north_american, encode_chinese
|
||||
from src.translation.decoder import decode_brazilian, decode_north_american, decode_chinese
|
||||
|
||||
|
||||
_ENCODERS = {
|
||||
"Brazilian": encode_brazilian,
|
||||
"North American": encode_north_american,
|
||||
"Chinese": encode_chinese,
|
||||
}
|
||||
|
||||
_DECODERS = {
|
||||
"Brazilian": decode_brazilian,
|
||||
"North American": decode_north_american,
|
||||
"Chinese": decode_chinese,
|
||||
}
|
||||
|
||||
|
||||
def encode(text: str, alphabet: str = "North American") -> str:
|
||||
strategy = _ENCODERS.get(alphabet)
|
||||
if strategy is None:
|
||||
return "Alphabet not found."
|
||||
return strategy(text)
|
||||
|
||||
|
||||
def decode(braille: str, alphabet: str = "North American") -> str:
|
||||
strategy = _DECODERS.get(alphabet)
|
||||
if strategy is None:
|
||||
return "Alphabet not found."
|
||||
return strategy(braille)
|
||||
@@ -0,0 +1,92 @@
|
||||
"""HTTP API routes: text/braille translation and STL generation."""
|
||||
import logging
|
||||
from io import BytesIO
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request
|
||||
from fastapi.concurrency import run_in_threadpool
|
||||
import fastapi.responses as responses
|
||||
|
||||
from src.translation import translator
|
||||
from src.modeling.options import ModelOptions
|
||||
from src.modeling.stl_service import StlService
|
||||
from src.web.job_queue import JobQueue, QueueFull, QueueTimeout
|
||||
from src.web.schemas import Text, Braille, ToSTLRequest
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
def _clamp(value, low, high):
|
||||
if value < low:
|
||||
return low
|
||||
if value > high:
|
||||
return high
|
||||
return value
|
||||
|
||||
|
||||
def _build_options(request: ToSTLRequest) -> ModelOptions:
|
||||
unique_plate = request.unique_plate if request.unique_plate else False
|
||||
symbols_per_line = _clamp(request.symbols_per_line if request.symbols_per_line else 22, 8, 50)
|
||||
text_alignment = request.text_alignment if request.text_alignment else "left"
|
||||
rounded = request.rounded if request.rounded else False
|
||||
points_only = request.points_only if request.points_only else False
|
||||
resolution = _clamp(request.resolution if request.resolution else 20, 15, 50)
|
||||
plate_thickness = _clamp(request.plate_thickness if request.plate_thickness else 2, 2, 100)
|
||||
|
||||
return ModelOptions(
|
||||
resolution=resolution,
|
||||
plate_thickness=plate_thickness,
|
||||
unique_plate=unique_plate,
|
||||
symbols_per_line=symbols_per_line,
|
||||
text_alignment=text_alignment,
|
||||
rounded=rounded,
|
||||
points_only=points_only,
|
||||
)
|
||||
|
||||
|
||||
def build_api_router(stl_service: StlService, stl_queue: JobQueue | None = None) -> APIRouter:
|
||||
# STL generation is CPU bound: a few run at once, the rest wait in a bounded FIFO queue.
|
||||
stl_queue = stl_queue or JobQueue()
|
||||
router = APIRouter(prefix="/api")
|
||||
|
||||
@router.post("/encode")
|
||||
def braille_encode(request: Text):
|
||||
try:
|
||||
alphabet = request.alphabet if request.alphabet else "North American"
|
||||
return {"encoded": translator.encode(request.text, alphabet)}
|
||||
except Exception:
|
||||
logger.exception("Request failed")
|
||||
raise HTTPException(status_code=500, detail="Internal server error")
|
||||
|
||||
@router.post("/decode")
|
||||
def braille_decode(request: Braille):
|
||||
try:
|
||||
alphabet = request.alphabet if request.alphabet else "North American"
|
||||
return {"decoded": translator.decode(request.braille, alphabet)}
|
||||
except Exception:
|
||||
logger.exception("Request failed")
|
||||
raise HTTPException(status_code=500, detail="Internal server error")
|
||||
|
||||
@router.post("/to-stl")
|
||||
async def to_stl(request: ToSTLRequest, http_request: Request):
|
||||
options = _build_options(request)
|
||||
client = http_request.client.host if http_request.client else "unknown"
|
||||
try:
|
||||
async with stl_queue.slot(client):
|
||||
stl_bytes = await run_in_threadpool(stl_service.generate, request.braille, options)
|
||||
except (QueueFull, QueueTimeout):
|
||||
raise HTTPException(
|
||||
status_code=503,
|
||||
detail="Server busy, please try again shortly.",
|
||||
headers={"Retry-After": "10"},
|
||||
)
|
||||
except Exception:
|
||||
logger.exception("Request failed")
|
||||
raise HTTPException(status_code=500, detail="Internal server error")
|
||||
|
||||
return responses.StreamingResponse(
|
||||
BytesIO(stl_bytes),
|
||||
media_type="application/vnd.ms-pkistl",
|
||||
headers={"Content-Disposition": "attachment; filename=output.stl"},
|
||||
)
|
||||
|
||||
return router
|
||||
@@ -0,0 +1,28 @@
|
||||
"""Composition root: build the FastAPI app and wire the dependencies together."""
|
||||
from fastapi import FastAPI
|
||||
|
||||
from src.modeling.model_builder import BrailleModelBuilder
|
||||
from src.modeling.stl_service import StlService
|
||||
from src.rendering.vtk_mesh_engine import VtkMeshEngine
|
||||
from src.rendering.vtk_stl_serializer import VtkStlSerializer
|
||||
from src.web.api_routes import build_api_router
|
||||
from src.web.page_routes import build_page_router
|
||||
from src.web.security import BodyLimitMiddleware, RateLimiter, SecurityHeadersMiddleware
|
||||
|
||||
|
||||
def create_app() -> FastAPI:
|
||||
# Infrastructure implementations of the modeling ports.
|
||||
mesh_engine = VtkMeshEngine()
|
||||
mesh_serializer = VtkStlSerializer()
|
||||
|
||||
# Use cases.
|
||||
stl_service = StlService(BrailleModelBuilder(mesh_engine), mesh_serializer)
|
||||
|
||||
# Interactive docs and the OpenAPI schema are not needed in production.
|
||||
app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None)
|
||||
app.add_middleware(RateLimiter)
|
||||
app.add_middleware(BodyLimitMiddleware)
|
||||
app.add_middleware(SecurityHeadersMiddleware)
|
||||
app.include_router(build_page_router())
|
||||
app.include_router(build_api_router(stl_service))
|
||||
return app
|
||||
@@ -0,0 +1,54 @@
|
||||
"""Bounded FIFO admission queue for CPU-heavy jobs (STL generation).
|
||||
|
||||
At most `concurrency` jobs run at once; the rest wait their turn in arrival order instead of
|
||||
being rejected. The queue itself is bounded (total and per client) and waiting is capped, so a
|
||||
burst or a single abusive client cannot make legitimate requests pile up forever.
|
||||
"""
|
||||
import asyncio
|
||||
from collections import Counter
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
|
||||
class QueueFull(Exception):
|
||||
"""No room left in the queue: the caller should retry later."""
|
||||
|
||||
|
||||
class QueueTimeout(Exception):
|
||||
"""The job waited too long for a free slot."""
|
||||
|
||||
|
||||
class JobQueue:
|
||||
def __init__(self, concurrency: int = 2, max_waiting: int = 20, max_per_client: int = 3, max_wait_seconds: float = 60):
|
||||
self._slots = asyncio.Semaphore(concurrency) # asyncio.Semaphore wakes waiters in FIFO order
|
||||
self._max_waiting = max_waiting
|
||||
self._max_per_client = max_per_client
|
||||
self._max_wait = max_wait_seconds
|
||||
self._waiting = 0
|
||||
self._per_client = Counter()
|
||||
|
||||
@property
|
||||
def waiting(self) -> int:
|
||||
return self._waiting
|
||||
|
||||
@asynccontextmanager
|
||||
async def slot(self, client: str):
|
||||
if self._waiting >= self._max_waiting or self._per_client[client] >= self._max_per_client:
|
||||
raise QueueFull()
|
||||
|
||||
self._waiting += 1
|
||||
self._per_client[client] += 1
|
||||
try:
|
||||
await asyncio.wait_for(self._slots.acquire(), timeout=self._max_wait)
|
||||
except asyncio.TimeoutError:
|
||||
raise QueueTimeout() from None
|
||||
finally:
|
||||
# Also runs when the client disconnects (task cancelled), freeing its place in line.
|
||||
self._waiting -= 1
|
||||
self._per_client[client] -= 1
|
||||
if not self._per_client[client]:
|
||||
del self._per_client[client]
|
||||
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
self._slots.release()
|
||||
@@ -0,0 +1,61 @@
|
||||
"""HTTP routes that serve the HTML pages and static frontend assets."""
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import APIRouter
|
||||
import fastapi.responses as responses
|
||||
|
||||
from src.config import Settings
|
||||
|
||||
|
||||
# The frontend files are not fingerprinted, so browsers must revalidate them (cheap 304 via ETag)
|
||||
# instead of heuristically caching a previous release after a deploy.
|
||||
REVALIDATE = {"Cache-Control": "no-cache"}
|
||||
|
||||
|
||||
def build_page_router() -> APIRouter:
|
||||
router = APIRouter()
|
||||
|
||||
@router.api_route("/", methods=["GET", "HEAD"])
|
||||
@router.api_route("/en", methods=["GET", "HEAD"])
|
||||
@router.api_route("/zh", methods=["GET", "HEAD"])
|
||||
def home():
|
||||
try:
|
||||
return responses.FileResponse(Settings.TEMPLATE_HTML, media_type="text/html; charset=utf-8", headers=REVALIDATE)
|
||||
except Exception:
|
||||
return responses.Response(content="Internal Server Error", status_code=404)
|
||||
|
||||
@router.get(f"/{Settings.GOOGLE_VERIFICATION_FILE}")
|
||||
def google_site_verification():
|
||||
return responses.FileResponse(Settings.GOOGLE_VERIFICATION_HTML, media_type="text/html; charset=utf-8")
|
||||
|
||||
@router.get("/robots.txt")
|
||||
def robots_txt():
|
||||
return responses.FileResponse(Settings.ROBOTS_TXT, media_type="text/plain; charset=utf-8")
|
||||
|
||||
@router.get("/sitemap.xml")
|
||||
def sitemap_xml():
|
||||
return responses.FileResponse(Settings.SITEMAP_XML, media_type="application/xml; charset=utf-8")
|
||||
|
||||
@router.get("/public/{file_path:path}")
|
||||
def static(file_path: str):
|
||||
# Resolve and confine the path so "..", encoded slashes and symlinks cannot escape STATIC_DIR.
|
||||
root = Path(Settings.STATIC_DIR).resolve()
|
||||
target = (root / file_path).resolve()
|
||||
if not target.is_relative_to(root) or not target.is_file():
|
||||
return responses.Response(content="File not found", status_code=404)
|
||||
|
||||
media_types = {
|
||||
".css": "text/css",
|
||||
".js": "text/javascript",
|
||||
".woff2": "font/woff2",
|
||||
".woff": "font/woff",
|
||||
".ttf": "font/ttf",
|
||||
".svg": "image/svg+xml",
|
||||
".png": "image/png",
|
||||
".ico": "image/x-icon",
|
||||
".json": "application/json",
|
||||
".webmanifest": "application/manifest+json",
|
||||
}
|
||||
return responses.FileResponse(target, media_type=media_types.get(target.suffix), headers=REVALIDATE)
|
||||
|
||||
return router
|
||||
@@ -0,0 +1,59 @@
|
||||
"""Pydantic request models for the HTTP API.
|
||||
|
||||
Every field is bounded: these limits are the first line of defence against oversized
|
||||
payloads and against requests that would make the 3D generator burn CPU or memory.
|
||||
"""
|
||||
from pydantic import BaseModel, Field, field_validator, model_validator
|
||||
|
||||
MAX_TEXT_LENGTH = 5000
|
||||
MAX_BRAILLE_LENGTH = 3000
|
||||
MAX_LINES = 100
|
||||
MAX_LINE_LENGTH = 200
|
||||
MAX_STL_COST = 3000 # filled cells x resolution; keeps one request to roughly 10 s and under 1 GB
|
||||
ALPHABET_PATTERN = r"^(Brazilian|North American|Chinese)$"
|
||||
|
||||
_BRAILLE_BLOCK = range(0x2800, 0x2900)
|
||||
|
||||
|
||||
class Text(BaseModel):
|
||||
text: str = Field(max_length=MAX_TEXT_LENGTH)
|
||||
alphabet: str | None = Field(default=None, pattern=ALPHABET_PATTERN)
|
||||
|
||||
|
||||
class Braille(BaseModel):
|
||||
braille: str = Field(max_length=MAX_TEXT_LENGTH)
|
||||
alphabet: str | None = Field(default=None, pattern=ALPHABET_PATTERN)
|
||||
|
||||
|
||||
class ToSTLRequest(BaseModel):
|
||||
braille: str = Field(min_length=1, max_length=MAX_BRAILLE_LENGTH)
|
||||
resolution: int | None = Field(default=None, ge=1, le=1000)
|
||||
plate_thickness: int | None = Field(default=None, ge=0, le=1000)
|
||||
unique_plate: bool | None = None
|
||||
symbols_per_line: int | None = Field(default=None, ge=0, le=1000)
|
||||
text_alignment: str | None = Field(default=None, pattern=r"^(left|center|right)$")
|
||||
rounded: bool | None = None
|
||||
points_only: bool | None = None
|
||||
|
||||
@field_validator("braille")
|
||||
@classmethod
|
||||
def only_braille_cells(cls, value: str) -> str:
|
||||
lines = value.split("\n")
|
||||
if len(lines) > MAX_LINES:
|
||||
raise ValueError(f"at most {MAX_LINES} lines are allowed")
|
||||
for line in lines:
|
||||
if len(line) > MAX_LINE_LENGTH:
|
||||
raise ValueError(f"lines may have at most {MAX_LINE_LENGTH} cells")
|
||||
if any(ord(char) not in _BRAILLE_BLOCK for char in line):
|
||||
raise ValueError("only Braille pattern characters and line breaks are allowed")
|
||||
return value
|
||||
|
||||
@model_validator(mode="after")
|
||||
def bounded_generation_cost(self):
|
||||
resolution = min(max(self.resolution or 20, 15), 50)
|
||||
filled_cells = sum(1 for char in self.braille if char not in ("\n", "\u2800"))
|
||||
if filled_cells * resolution > MAX_STL_COST:
|
||||
raise ValueError(
|
||||
f"model too large: reduce the text or the resolution (filled cells x resolution must be at most {MAX_STL_COST})"
|
||||
)
|
||||
return self
|
||||
@@ -0,0 +1,132 @@
|
||||
"""Cross-cutting protections: security headers, request body cap and per-client rate limit."""
|
||||
import threading
|
||||
import time
|
||||
from collections import defaultdict, deque
|
||||
|
||||
from starlette.responses import JSONResponse, Response
|
||||
from starlette.types import ASGIApp, Message, Receive, Scope, Send
|
||||
|
||||
MAX_BODY_BYTES = 64 * 1024
|
||||
|
||||
CONTENT_SECURITY_POLICY = "; ".join([
|
||||
"default-src 'self'",
|
||||
"script-src 'self' 'unsafe-inline' https://cdn.tailwindcss.com https://unpkg.com",
|
||||
"style-src 'self' 'unsafe-inline' https://cdnjs.cloudflare.com https://fonts.googleapis.com",
|
||||
"font-src 'self' https://cdnjs.cloudflare.com https://fonts.gstatic.com",
|
||||
"img-src 'self' data: https://skipthecad.com",
|
||||
"connect-src 'self'",
|
||||
"object-src 'none'",
|
||||
"base-uri 'self'",
|
||||
"form-action 'self'",
|
||||
"frame-ancestors 'none'",
|
||||
])
|
||||
|
||||
SECURITY_HEADERS = {
|
||||
"Content-Security-Policy": CONTENT_SECURITY_POLICY,
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
"X-Frame-Options": "DENY",
|
||||
"Referrer-Policy": "strict-origin-when-cross-origin",
|
||||
"Permissions-Policy": "camera=(), microphone=(), geolocation=(), payment=()",
|
||||
"Cross-Origin-Opener-Policy": "same-origin",
|
||||
}
|
||||
|
||||
|
||||
class SecurityHeadersMiddleware:
|
||||
def __init__(self, app: ASGIApp):
|
||||
self.app = app
|
||||
|
||||
async def __call__(self, scope: Scope, receive: Receive, send: Send):
|
||||
if scope["type"] != "http":
|
||||
await self.app(scope, receive, send)
|
||||
return
|
||||
|
||||
async def send_with_headers(message: Message):
|
||||
if message["type"] == "http.response.start":
|
||||
headers = list(message.get("headers", []))
|
||||
present = {name.lower() for name, _ in headers}
|
||||
for name, value in SECURITY_HEADERS.items():
|
||||
if name.lower().encode() not in present:
|
||||
headers.append((name.lower().encode(), value.encode()))
|
||||
message["headers"] = headers
|
||||
await send(message)
|
||||
|
||||
await self.app(scope, receive, send_with_headers)
|
||||
|
||||
|
||||
class BodyLimitMiddleware:
|
||||
"""Rejects request bodies above MAX_BODY_BYTES, even when sent chunked."""
|
||||
|
||||
def __init__(self, app: ASGIApp, max_bytes: int = MAX_BODY_BYTES):
|
||||
self.app = app
|
||||
self.max_bytes = max_bytes
|
||||
|
||||
async def __call__(self, scope: Scope, receive: Receive, send: Send):
|
||||
if scope["type"] != "http":
|
||||
await self.app(scope, receive, send)
|
||||
return
|
||||
|
||||
declared = dict(scope["headers"]).get(b"content-length")
|
||||
if declared is not None and declared.isdigit() and int(declared) > self.max_bytes:
|
||||
await Response("Request body too large", status_code=413)(scope, receive, send)
|
||||
return
|
||||
|
||||
received = 0
|
||||
|
||||
async def limited_receive() -> Message:
|
||||
nonlocal received
|
||||
message = await receive()
|
||||
if message["type"] == "http.request":
|
||||
received += len(message.get("body", b""))
|
||||
if received > self.max_bytes:
|
||||
raise _BodyTooLarge()
|
||||
return message
|
||||
|
||||
try:
|
||||
await self.app(scope, limited_receive, send)
|
||||
except _BodyTooLarge:
|
||||
await Response("Request body too large", status_code=413)(scope, receive, send)
|
||||
|
||||
|
||||
class _BodyTooLarge(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class RateLimiter:
|
||||
"""Sliding-window limiter keyed by client address, applied to /api paths only."""
|
||||
|
||||
def __init__(self, app: ASGIApp, limit: int = 60, window_seconds: int = 60, stl_limit: int = 10):
|
||||
self.app = app
|
||||
self.window = window_seconds
|
||||
self.limits = {"default": limit, "stl": stl_limit}
|
||||
self._hits = defaultdict(deque)
|
||||
self._lock = threading.Lock()
|
||||
|
||||
def _allowed(self, key: str, bucket: str) -> bool:
|
||||
now = time.monotonic()
|
||||
with self._lock:
|
||||
hits = self._hits[(key, bucket)]
|
||||
while hits and now - hits[0] > self.window:
|
||||
hits.popleft()
|
||||
if len(hits) >= self.limits[bucket]:
|
||||
return False
|
||||
hits.append(now)
|
||||
if len(self._hits) > 10000:
|
||||
self._hits = defaultdict(deque, {k: v for k, v in self._hits.items() if v and now - v[-1] <= self.window})
|
||||
return True
|
||||
|
||||
async def __call__(self, scope: Scope, receive: Receive, send: Send):
|
||||
if scope["type"] != "http" or not scope["path"].startswith("/api"):
|
||||
await self.app(scope, receive, send)
|
||||
return
|
||||
|
||||
client = (scope.get("client") or ("unknown", 0))[0]
|
||||
bucket = "stl" if scope["path"] == "/api/to-stl" else "default"
|
||||
if not self._allowed(client, bucket):
|
||||
await JSONResponse(
|
||||
{"detail": "Too many requests. Please slow down."},
|
||||
status_code=429,
|
||||
headers={"Retry-After": str(self.window)},
|
||||
)(scope, receive, send)
|
||||
return
|
||||
|
||||
await self.app(scope, receive, send)
|
||||
@@ -0,0 +1,152 @@
|
||||
import time
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from src.web.app import create_app
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def client():
|
||||
return TestClient(create_app())
|
||||
|
||||
|
||||
def test_home_has_security_headers(client):
|
||||
response = client.get("/")
|
||||
assert response.status_code == 200
|
||||
assert "frame-ancestors 'none'" in response.headers["content-security-policy"]
|
||||
assert response.headers["x-content-type-options"] == "nosniff"
|
||||
assert response.headers["x-frame-options"] == "DENY"
|
||||
|
||||
|
||||
def test_google_verification_file(client):
|
||||
response = client.get("/google21a790a2c23c0ec5.html")
|
||||
assert response.status_code == 200
|
||||
assert response.text.startswith("google-site-verification:")
|
||||
|
||||
|
||||
def test_docs_are_disabled(client):
|
||||
for path in ("/docs", "/redoc", "/openapi.json"):
|
||||
assert client.get(path).status_code == 404
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path", [
|
||||
"/public/../.env",
|
||||
"/public/%2e%2e/.env",
|
||||
"/public/..%2f.env",
|
||||
"/public/%2e%2e%2fmain.py",
|
||||
"/public/..%2fsrc%2fconfig.py",
|
||||
"/public//etc/passwd",
|
||||
])
|
||||
def test_static_path_traversal_is_blocked(client, path):
|
||||
response = client.get(path)
|
||||
assert response.status_code == 404
|
||||
assert "PORT" not in response.text and "root:" not in response.text
|
||||
|
||||
|
||||
def test_static_serves_assets(client):
|
||||
assert client.get("/public/style.css").headers["content-type"].startswith("text/css")
|
||||
assert client.get("/public/index.js").headers["content-type"].startswith("text/javascript")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("alphabet", ["Brazilian", "North American", "Chinese"])
|
||||
def test_encode_decode_roundtrip_runs(client, alphabet):
|
||||
text = "ni3 hao3" if alphabet == "Chinese" else "hello"
|
||||
encoded = client.post("/api/encode", json={"text": text, "alphabet": alphabet})
|
||||
assert encoded.status_code == 200
|
||||
braille = encoded.json()["encoded"]
|
||||
assert braille
|
||||
decoded = client.post("/api/decode", json={"braille": braille, "alphabet": alphabet})
|
||||
assert decoded.status_code == 200
|
||||
|
||||
|
||||
def test_unknown_alphabet_rejected(client):
|
||||
assert client.post("/api/encode", json={"text": "a", "alphabet": "Klingon"}).status_code == 422
|
||||
|
||||
|
||||
def test_oversized_text_rejected(client):
|
||||
assert client.post("/api/encode", json={"text": "a" * 5001}).status_code == 422
|
||||
|
||||
|
||||
def test_oversized_body_rejected(client):
|
||||
assert client.post("/api/encode", content=b"x" * (70 * 1024)).status_code == 413
|
||||
|
||||
|
||||
def test_stl_generation(client):
|
||||
response = client.post("/api/to-stl", json={"braille": "⠓⠑⠇⠇⠕", "resolution": 15})
|
||||
assert response.status_code == 200
|
||||
assert len(response.content) > 1000
|
||||
assert response.headers["content-disposition"] == "attachment; filename=output.stl"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("payload", [
|
||||
{"braille": "hello"},
|
||||
{"braille": ""},
|
||||
{"braille": "⠁" * 3001},
|
||||
{"braille": "⠁" * 201},
|
||||
{"braille": "\n".join(["⠁"] * 101)},
|
||||
{"braille": "⠁", "text_alignment": "../../etc"},
|
||||
{"braille": "⠁", "resolution": 10**9},
|
||||
{"braille": "⠁", "plate_thickness": -5},
|
||||
])
|
||||
def test_stl_invalid_input_rejected(client, payload):
|
||||
assert client.post("/api/to-stl", json=payload).status_code == 422
|
||||
|
||||
|
||||
def test_stl_cost_budget_rejects_expensive_models(client):
|
||||
braille = "\n".join(["⠿" * 29] * 10)
|
||||
response = client.post("/api/to-stl", json={"braille": braille, "resolution": 50})
|
||||
assert response.status_code == 422
|
||||
assert "model too large" in response.text
|
||||
|
||||
|
||||
def test_stl_worst_case_within_budget_is_bounded(client):
|
||||
braille = "\n".join(["⠿" * 12] * 5) # 60 filled cells x resolution 50 = budget
|
||||
start = time.monotonic()
|
||||
response = client.post("/api/to-stl", json={"braille": braille, "resolution": 50})
|
||||
assert response.status_code == 200
|
||||
assert time.monotonic() - start < 60
|
||||
|
||||
|
||||
def test_errors_do_not_leak_internals(client, monkeypatch):
|
||||
from src.translation import translator
|
||||
|
||||
def boom(*_):
|
||||
raise RuntimeError("secret /app/internal/path")
|
||||
|
||||
monkeypatch.setattr(translator, "encode", boom)
|
||||
response = client.post("/api/encode", json={"text": "a"})
|
||||
assert response.status_code == 500
|
||||
assert "secret" not in response.text
|
||||
|
||||
|
||||
def test_rate_limit_kicks_in(client):
|
||||
codes = [client.post("/api/to-stl", json={"braille": "⠁", "resolution": 15}).status_code for _ in range(13)]
|
||||
assert 429 in codes
|
||||
|
||||
|
||||
def test_stl_requests_queue_instead_of_failing():
|
||||
import asyncio
|
||||
|
||||
import httpx
|
||||
|
||||
async def scenario():
|
||||
transport = httpx.ASGITransport(app=create_app(), client=("203.0.113.7", 1))
|
||||
payload = {"braille": "⠓⠑⠇⠇⠕", "resolution": 15}
|
||||
async with httpx.AsyncClient(transport=transport, base_url="http://test") as http:
|
||||
responses = await asyncio.gather(*(http.post("/api/to-stl", json=payload) for _ in range(6)))
|
||||
return [r.status_code for r in responses]
|
||||
|
||||
codes = asyncio.run(scenario())
|
||||
# Same client: at most 3 may wait (per-client cap), the rest are told to retry; none fails with 500.
|
||||
assert set(codes) <= {200, 503}
|
||||
assert codes.count(200) >= 3
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path", ["/", "/public/index.js", "/public/modules/stl.js"])
|
||||
def test_frontend_assets_are_revalidated(client, path):
|
||||
# Without Cache-Control browsers heuristically cache the un-versioned JS modules,
|
||||
# so returning visitors keep running the previous release after a deploy.
|
||||
response = client.get(path)
|
||||
assert response.status_code == 200
|
||||
assert response.headers["cache-control"] == "no-cache"
|
||||
@@ -0,0 +1,87 @@
|
||||
import asyncio
|
||||
|
||||
import pytest
|
||||
|
||||
from src.web.job_queue import JobQueue, QueueFull, QueueTimeout
|
||||
|
||||
|
||||
async def _run(queue, client, order, name, hold):
|
||||
async with queue.slot(client):
|
||||
order.append(name)
|
||||
await asyncio.sleep(hold)
|
||||
|
||||
|
||||
def test_jobs_run_in_arrival_order_and_none_is_lost():
|
||||
async def scenario():
|
||||
queue = JobQueue(concurrency=1, max_waiting=10, max_per_client=10)
|
||||
order = []
|
||||
tasks = []
|
||||
for i in range(5):
|
||||
tasks.append(asyncio.create_task(_run(queue, f"c{i}", order, i, 0.01)))
|
||||
await asyncio.sleep(0)
|
||||
await asyncio.gather(*tasks)
|
||||
return order, queue.waiting
|
||||
|
||||
order, waiting = asyncio.run(scenario())
|
||||
assert order == [0, 1, 2, 3, 4]
|
||||
assert waiting == 0
|
||||
|
||||
|
||||
def test_concurrency_is_respected():
|
||||
async def scenario():
|
||||
queue = JobQueue(concurrency=2, max_waiting=10, max_per_client=10)
|
||||
running = peak = 0
|
||||
|
||||
async def job(i):
|
||||
nonlocal running, peak
|
||||
async with queue.slot(f"c{i}"):
|
||||
running += 1
|
||||
peak = max(peak, running)
|
||||
await asyncio.sleep(0.02)
|
||||
running -= 1
|
||||
|
||||
await asyncio.gather(*(job(i) for i in range(6)))
|
||||
return peak
|
||||
|
||||
assert asyncio.run(scenario()) == 2
|
||||
|
||||
|
||||
def test_queue_full_and_per_client_cap():
|
||||
async def scenario():
|
||||
queue = JobQueue(concurrency=1, max_waiting=2, max_per_client=1)
|
||||
order = []
|
||||
first = asyncio.create_task(_run(queue, "a", order, "a", 0.05))
|
||||
await asyncio.sleep(0)
|
||||
second = asyncio.create_task(_run(queue, "b", order, "b", 0.0))
|
||||
await asyncio.sleep(0)
|
||||
with pytest.raises(QueueFull): # client "b" already holds a place in line
|
||||
async with queue.slot("b"):
|
||||
pass
|
||||
third = asyncio.create_task(_run(queue, "c", order, "c", 0.0))
|
||||
await asyncio.sleep(0)
|
||||
with pytest.raises(QueueFull): # the queue itself is full
|
||||
async with queue.slot("d"):
|
||||
pass
|
||||
await asyncio.gather(first, second, third)
|
||||
return order
|
||||
|
||||
assert asyncio.run(scenario()) == ["a", "b", "c"]
|
||||
|
||||
|
||||
def test_wait_timeout_and_cancellation_free_the_place():
|
||||
async def scenario():
|
||||
queue = JobQueue(concurrency=1, max_waiting=5, max_per_client=5, max_wait_seconds=0.05)
|
||||
holder = asyncio.create_task(_run(queue, "a", [], "a", 0.3))
|
||||
await asyncio.sleep(0)
|
||||
with pytest.raises(QueueTimeout):
|
||||
async with queue.slot("b"):
|
||||
pass
|
||||
waiter = asyncio.create_task(_run(queue, "c", [], "c", 0))
|
||||
await asyncio.sleep(0.01)
|
||||
waiter.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await waiter
|
||||
assert queue.waiting == 0
|
||||
await holder
|
||||
|
||||
asyncio.run(scenario())
|
||||