commit a9aec5abe49d763c42c069e83b317caf545e733d Author: Lucas Rayan Date: Mon Nov 2 00:15:01 2026 -0300 Recover InBraille from the production image (1.3.1) and move it to Gitea 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 diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..a1bdd28 --- /dev/null +++ b/.dockerignore @@ -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 diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..6313b56 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +* text=auto eol=lf diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml new file mode 100644 index 0000000..519b15d --- /dev/null +++ b/.gitea/workflows/ci.yml @@ -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-. 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- + 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" diff --git a/.gitea/workflows/release.yml b/.gitea/workflows/release.yml new file mode 100644 index 0000000..5ff0f51 --- /dev/null +++ b/.gitea/workflows/release.yml @@ -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-; 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 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..0eb1397 --- /dev/null +++ b/.gitignore @@ -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 diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..23084a3 --- /dev/null +++ b/CHANGELOG.md @@ -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 diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..aaaff23 --- /dev/null +++ b/Dockerfile @@ -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"] diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..2fd1a7e --- /dev/null +++ b/LICENSE @@ -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. diff --git a/README.md b/README.md new file mode 100644 index 0000000..6305be9 --- /dev/null +++ b/README.md @@ -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-`), 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-`. To release: update the CHANGELOG, commit, then `git tag vX.Y.Z && git push gitea vX.Y.Z`. + +--- + +[![Listed on SkipTheCAD](https://skipthecad.com/badge/listed-dark.svg)](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: . diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..4be97a1 --- /dev/null +++ b/SECURITY.md @@ -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). diff --git a/docker-compose.dev.yaml b/docker-compose.dev.yaml new file mode 100644 index 0000000..15992a5 --- /dev/null +++ b/docker-compose.dev.yaml @@ -0,0 +1,9 @@ +services: + app: + build: + context: . + dockerfile: Dockerfile + ports: + - "3000:3000" + environment: + PORT: "3000" diff --git a/docker-compose.yaml b/docker-compose.yaml new file mode 100644 index 0000000..1c99192 --- /dev/null +++ b/docker-compose.yaml @@ -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 diff --git a/google21a790a2c23c0ec5.html b/google21a790a2c23c0ec5.html new file mode 100644 index 0000000..bb39133 --- /dev/null +++ b/google21a790a2c23c0ec5.html @@ -0,0 +1 @@ +google-site-verification: google21a790a2c23c0ec5.html \ No newline at end of file diff --git a/index.html b/index.html new file mode 100644 index 0000000..7103854 --- /dev/null +++ b/index.html @@ -0,0 +1,629 @@ + + + + + + InBraille - Conversor de Texto para Braille e Impressão 3D STL | Acessibilidade Tátil + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+ + +
+
+ + + 🇧🇷 Português + + +
+ + + +
+
+
+
+
+ +
+
+
+
+

Transforme texto em Braille facilmente

+

+ 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. +

+ + Experimente agora + +
+
+ ⠿ +
+
+
+ + +
+

Conversor

+ +
+ + +
+ +
+ +
+
+ + +
+
+ + +
+
+ + +
+
+ + + + +
+ +
+
+ + + + +
+ + 0 caracteres +
+
+ +
+ + + + +
+ + +
+
+
+ +
+ +
+ +
+

Exportar para Impressão 3D

+ +
+
+
+ +
+
+

+ 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. +

+
+
+
+ +
+
+
+ +
+
+

+ Indicador de orientação: + 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. +

+
+
+
+ +
+ +
+ + + +
+
+

+ Opções Avançadas +

+ +
+ + +
+
+
+ +
+

Sobre o InBraille

+ +
+

+ 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. +

+ +

+ 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. +

+ +

+ 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. +

+ +

+ 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. +

+ +
+
+
+
+ +
+
+
+

Neurodiversidade na Tecnologia

+ +

+ 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. +

+ +

+ 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. +

+
+
+
+ +
+

+ Saiba mais +

+

+ Veja mais sobre essa ferramenta na página dela no + + Ciência Embarcada + +

+
+
+
+ +
+

+ + Perguntas Frequentes (FAQ) +

+ +
+
+ + O que é o InBraille e para que serve? + + +

+ 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. +

+
+ +
+ + Como exportar e imprimir Braille em uma impressora 3D? + + +

+ Digite seu texto no conversor, clique em Converter e em seguida em Gerar e Visualizar STL. Você pode inspecionar o modelo interativamente em 3D, ajustar parâmetros como espessura da placa e modo "Apenas os Pontos", e clicar em Baixar STL para salvar o arquivo pronto para seu fatiador 3D (como Cura ou PrusaSlicer). +

+
+ +
+ + O InBraille é gratuito para escolas, universidades e projetos sociais? + + +

+ 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. +

+
+ +
+ + Quais alfabetos Braille são suportados? + + +

+ O sistema conta com suporte a três convenções: o Alfabeto Brasileiro (com normas do Ministério da Educação), o Norte-Americano (English Braille) e o Chinês (com suporte a conversão automática de Pinyin numerado e caracteres Hanzi). +

+
+ +
+ + Por que existe um indicador de orientação na peça 3D? + + +

+ 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. +

+
+
+
+
+ + + + + + + + + diff --git a/main.py b/main.py new file mode 100644 index 0000000..b286d25 --- /dev/null +++ b/main.py @@ -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) diff --git a/public/android-chrome-192x192.png b/public/android-chrome-192x192.png new file mode 100644 index 0000000..315d5d8 Binary files /dev/null and b/public/android-chrome-192x192.png differ diff --git a/public/android-chrome-512x512.png b/public/android-chrome-512x512.png new file mode 100644 index 0000000..6fe37cf Binary files /dev/null and b/public/android-chrome-512x512.png differ diff --git a/public/apple-touch-icon.png b/public/apple-touch-icon.png new file mode 100644 index 0000000..6960182 Binary files /dev/null and b/public/apple-touch-icon.png differ diff --git a/public/favicon-16x16.png b/public/favicon-16x16.png new file mode 100644 index 0000000..3cf05f1 Binary files /dev/null and b/public/favicon-16x16.png differ diff --git a/public/favicon-32x32.png b/public/favicon-32x32.png new file mode 100644 index 0000000..b2fa545 Binary files /dev/null and b/public/favicon-32x32.png differ diff --git a/public/favicon.ico b/public/favicon.ico new file mode 100644 index 0000000..168b780 Binary files /dev/null and b/public/favicon.ico differ diff --git a/public/fonts/NotoSansSymbols2-Braille.woff2 b/public/fonts/NotoSansSymbols2-Braille.woff2 new file mode 100644 index 0000000..c960b36 Binary files /dev/null and b/public/fonts/NotoSansSymbols2-Braille.woff2 differ diff --git a/public/icon.svg b/public/icon.svg new file mode 100644 index 0000000..b43eafa --- /dev/null +++ b/public/icon.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/public/index.js b/public/index.js new file mode 100644 index 0000000..f17c8d5 --- /dev/null +++ b/public/index.js @@ -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); +}); \ No newline at end of file diff --git a/public/locales/en.js b/public/locales/en.js new file mode 100644 index 0000000..b8874ce --- /dev/null +++ b/public/locales/en.js @@ -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." +}; diff --git a/public/locales/pt_br.js b/public/locales/pt_br.js new file mode 100644 index 0000000..b409453 --- /dev/null +++ b/public/locales/pt_br.js @@ -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." +}; diff --git a/public/locales/zh.js b/public/locales/zh.js new file mode 100644 index 0000000..be27033 --- /dev/null +++ b/public/locales/zh.js @@ -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 文件出错,请重试。" +}; diff --git a/public/modules/client_stl_generator.js b/public/modules/client_stl_generator.js new file mode 100644 index 0000000..aaf3434 --- /dev/null +++ b/public/modules/client_stl_generator.js @@ -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); +} diff --git a/public/modules/converter.js b/public/modules/converter.js new file mode 100644 index 0000000..6195ce1 --- /dev/null +++ b/public/modules/converter.js @@ -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 = ` ${getTranslation("input_label_text_to_braille")}`; + input_textbox.placeholder = getTranslation("input_placeholder_text_to_braille"); + output_label.innerHTML = `⠿ ${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 = `⠿ ${getTranslation("input_label_braille_to_text")}`; + input_textbox.placeholder = getTranslation("input_placeholder_braille_to_text"); + output_label.innerHTML = ` ${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 = ` ${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")); + } +} diff --git a/public/modules/i18n.js b/public/modules/i18n.js new file mode 100644 index 0000000..68b191c --- /dev/null +++ b/public/modules/i18n.js @@ -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"); + } +} diff --git a/public/modules/state.js b/public/modules/state.js new file mode 100644 index 0000000..3795c1f --- /dev/null +++ b/public/modules/state.js @@ -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(); +} diff --git a/public/modules/stl.js b/public/modules/stl.js new file mode 100644 index 0000000..08ff4d8 --- /dev/null +++ b/public/modules/stl.js @@ -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 = `${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 = `${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"); + } +} diff --git a/public/modules/ui.js b/public/modules/ui.js new file mode 100644 index 0000000..c3b50dc --- /dev/null +++ b/public/modules/ui.js @@ -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 = `${message}`; + 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); +} diff --git a/public/preview.js b/public/preview.js new file mode 100644 index 0000000..eb5a382 --- /dev/null +++ b/public/preview.js @@ -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(); +}; diff --git a/public/site.webmanifest b/public/site.webmanifest new file mode 100644 index 0000000..ab355b9 --- /dev/null +++ b/public/site.webmanifest @@ -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" +} \ No newline at end of file diff --git a/public/style.css b/public/style.css new file mode 100644 index 0000000..e2b3de3 --- /dev/null +++ b/public/style.css @@ -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); +} \ No newline at end of file diff --git a/public/translations.js b/public/translations.js new file mode 100644 index 0000000..f83aa73 --- /dev/null +++ b/public/translations.js @@ -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 +}; diff --git a/pytest.ini b/pytest.ini new file mode 100644 index 0000000..3f45d54 --- /dev/null +++ b/pytest.ini @@ -0,0 +1,5 @@ +[pytest] +pythonpath = . +testpaths = tests +filterwarnings = + ignore::DeprecationWarning diff --git a/requirements-dev.txt b/requirements-dev.txt new file mode 100644 index 0000000..9b5d281 --- /dev/null +++ b/requirements-dev.txt @@ -0,0 +1,3 @@ +-r requirements.txt +pytest==9.1.1 +httpx==0.28.1 diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..09f1002 --- /dev/null +++ b/requirements.txt @@ -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 diff --git a/robots.txt b/robots.txt new file mode 100644 index 0000000..78524a2 --- /dev/null +++ b/robots.txt @@ -0,0 +1,4 @@ +User-agent: * +Allow: / + +Sitemap: https://inbraille.cienciaembarcada.com.br/sitemap.xml diff --git a/scripts/plano-imagem.sh b/scripts/plano-imagem.sh new file mode 100755 index 0000000..3c74464 --- /dev/null +++ b/scripts/plano-imagem.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash +# Uso: scripts/plano-imagem.sh +# 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-. +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" diff --git a/scripts/release-notes.sh b/scripts/release-notes.sh new file mode 100755 index 0000000..7664192 --- /dev/null +++ b/scripts/release-notes.sh @@ -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 [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 diff --git a/scripts/smoke-imagem.sh b/scripts/smoke-imagem.sh new file mode 100755 index 0000000..533e2c2 --- /dev/null +++ b/scripts/smoke-imagem.sh @@ -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 +# +# 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 } +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('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 ] diff --git a/sitemap.xml b/sitemap.xml new file mode 100644 index 0000000..836f854 --- /dev/null +++ b/sitemap.xml @@ -0,0 +1,24 @@ + + + + https://inbraille.cienciaembarcada.com.br/ + + + + + + + https://inbraille.cienciaembarcada.com.br/en + + + + + + + https://inbraille.cienciaembarcada.com.br/zh + + + + + + diff --git a/src/__init__.py b/src/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/config.py b/src/config.py new file mode 100644 index 0000000..fcbef09 --- /dev/null +++ b/src/config.py @@ -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") diff --git a/src/domain/__init__.py b/src/domain/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/domain/alphabets.py b/src/domain/alphabets.py new file mode 100644 index 0000000..d078935 --- /dev/null +++ b/src/domain/alphabets.py @@ -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=[ + '⠁', '⠃', '⠉', '⠙', '⠑', '⠋', '⠛', '⠓', '⠊', '⠚', '⠅', '⠇', '⠍', '⠝', '⠕', '⠏', '⠟', '⠗', '⠎', '⠞', '⠥', '⠧', '⠺', '⠭', '⠽', '⠵', '⠴', '⠂', '⠆', '⠒', '⠲', '⠢', '⠖', '⠶', '⠦', '⠔', '⠮', '⠹', '⠯', '⠫', '⠼', '⠈', '⠩', '⠷', '⠾', '⠪', '⠻', '⠸', '⠬', '⠤', '⠡', '⠌', '⠳', '⠿', '⠣', '⠜', '⠨', '⠠', '⠰', '⠱', '⠄', '⠐' + ], +) diff --git a/src/domain/braille_codes.py b/src/domain/braille_codes.py new file mode 100644 index 0000000..3271bc3 --- /dev/null +++ b/src/domain/braille_codes.py @@ -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)) diff --git a/src/domain/chinese_braille.py b/src/domain/chinese_braille.py new file mode 100644 index 0000000..28318b8 --- /dev/null +++ b/src/domain/chinese_braille.py @@ -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() +} diff --git a/src/domain/dimensions.py b/src/domain/dimensions.py new file mode 100644 index 0000000..7abc249 --- /dev/null +++ b/src/domain/dimensions.py @@ -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 diff --git a/src/modeling/__init__.py b/src/modeling/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/modeling/mesh_engine.py b/src/modeling/mesh_engine.py new file mode 100644 index 0000000..2a54758 --- /dev/null +++ b/src/modeling/mesh_engine.py @@ -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).""" diff --git a/src/modeling/mesh_serializer.py b/src/modeling/mesh_serializer.py new file mode 100644 index 0000000..2d95266 --- /dev/null +++ b/src/modeling/mesh_serializer.py @@ -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).""" diff --git a/src/modeling/model_builder.py b/src/modeling/model_builder.py new file mode 100644 index 0000000..3917dc9 --- /dev/null +++ b/src/modeling/model_builder.py @@ -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) diff --git a/src/modeling/options.py b/src/modeling/options.py new file mode 100644 index 0000000..538d5c1 --- /dev/null +++ b/src/modeling/options.py @@ -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 diff --git a/src/modeling/stl_service.py b/src/modeling/stl_service.py new file mode 100644 index 0000000..e6da94d --- /dev/null +++ b/src/modeling/stl_service.py @@ -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 diff --git a/src/rendering/__init__.py b/src/rendering/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/rendering/vtk_mesh_engine.py b/src/rendering/vtk_mesh_engine.py new file mode 100644 index 0000000..b336f64 --- /dev/null +++ b/src/rendering/vtk_mesh_engine.py @@ -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) diff --git a/src/rendering/vtk_stl_serializer.py b/src/rendering/vtk_stl_serializer.py new file mode 100644 index 0000000..c34863c --- /dev/null +++ b/src/rendering/vtk_stl_serializer.py @@ -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(" 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) \ No newline at end of file diff --git a/src/translation/encoder.py b/src/translation/encoder.py new file mode 100644 index 0000000..495d39d --- /dev/null +++ b/src/translation/encoder.py @@ -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) \ No newline at end of file diff --git a/src/translation/translator.py b/src/translation/translator.py new file mode 100644 index 0000000..270cba1 --- /dev/null +++ b/src/translation/translator.py @@ -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) diff --git a/src/web/__init__.py b/src/web/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/web/api_routes.py b/src/web/api_routes.py new file mode 100644 index 0000000..0c4a78e --- /dev/null +++ b/src/web/api_routes.py @@ -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 diff --git a/src/web/app.py b/src/web/app.py new file mode 100644 index 0000000..1c958c3 --- /dev/null +++ b/src/web/app.py @@ -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 diff --git a/src/web/job_queue.py b/src/web/job_queue.py new file mode 100644 index 0000000..b854639 --- /dev/null +++ b/src/web/job_queue.py @@ -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() diff --git a/src/web/page_routes.py b/src/web/page_routes.py new file mode 100644 index 0000000..2b6d773 --- /dev/null +++ b/src/web/page_routes.py @@ -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 diff --git a/src/web/schemas.py b/src/web/schemas.py new file mode 100644 index 0000000..40ab270 --- /dev/null +++ b/src/web/schemas.py @@ -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 diff --git a/src/web/security.py b/src/web/security.py new file mode 100644 index 0000000..7efce0e --- /dev/null +++ b/src/web/security.py @@ -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) diff --git a/tests/test_api.py b/tests/test_api.py new file mode 100644 index 0000000..f32092a --- /dev/null +++ b/tests/test_api.py @@ -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" diff --git a/tests/test_job_queue.py b/tests/test_job_queue.py new file mode 100644 index 0000000..9e63fc7 --- /dev/null +++ b/tests/test_job_queue.py @@ -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())