diff --git a/docs/.vuepress/config.js b/docs/.vuepress/config.js index fd56a54..d51b2ec 100644 --- a/docs/.vuepress/config.js +++ b/docs/.vuepress/config.js @@ -22,6 +22,11 @@ module.exports = { lang: 'fr-FR', title: 'Léon Docs', description: 'Documentation de Léon - Documentation principale de votre assistant personnel open source Léon.' + }, + '/pt-BR/': { + lang: 'pt-BR', + title: 'Leon Docs', + description: 'Documentação do Leon - Documentação principal do seu assistente pessoal open-source Leon.' } }, themeConfig: { @@ -32,7 +37,8 @@ module.exports = { editLinks: true, locales: { '/': require('./config.en-US'), - '/fr-FR/': require('./config.fr-FR') + '/fr-FR/': require('./config.fr-FR'), + '/pt-BR/': require('./config.pt-BR') } }, plugins: { diff --git a/docs/.vuepress/config.pt-BR.js b/docs/.vuepress/config.pt-BR.js new file mode 100644 index 0000000..60b8257 --- /dev/null +++ b/docs/.vuepress/config.pt-BR.js @@ -0,0 +1,37 @@ + +module.exports = { + selectText: 'Idiomas', + label: 'Português (BR)', + editLinkText: 'Edite esta página no GitHub', + nav: require('./nav/nav.pt-BR.js'), + sidebar: { + '/pt-BR/how-to/': [ + { + title: 'Manual', + collapsable: false, + children: [ + '' + ] + } + ], + '/pt-BR/': [ + { + title: 'Guia', + collapsable: false, + children: [ + '', + 'glossary', + 'architecture', + 'configuration', + 'offline', + 'bridges', + 'clients', + 'packages-modules', + 'collaborative-logger', + 'scripts', + 'tests' + ] + } + ] + } +}; diff --git a/docs/.vuepress/nav/nav.pt-BR.js b/docs/.vuepress/nav/nav.pt-BR.js new file mode 100644 index 0000000..a5a1a3b --- /dev/null +++ b/docs/.vuepress/nav/nav.pt-BR.js @@ -0,0 +1,35 @@ +module.exports = [ + { + text: 'Guia', + link: '/pt-BR/' + }, + { + text: 'Manual', + link: '/pt-BR/how-to/' + }, + { + text: 'Links', + items: [ + { text: 'Website', link: 'https://getleon.ai' }, + { text: 'Fique Ligado', items: [ + { text: 'Blog', link: 'https://blog.getleon.ai' }, + { text: 'Roadmap', link: 'https://roadmap.getleon.ai' }, + { text: 'Changelog', link: 'https://changelog.getleon.ai' }, + { text: '#LeonAI', link: 'https://twitter.com/hashtag/LeonAI' } + ] + }, + { text: 'Contribuindo', items: [ + { text: 'Contribua', link: 'https://github.com/leon-ai/leon/blob/develop/.github/CONTRIBUTING.md' } + ] + }, + { text: 'Ajuda', items: [ + { text: 'Issues', link: 'https://github.com/leon-ai/leon/issues' } + ] + } + ], + }, + { + text: 'Faça uma Doação', + link: 'https://donate.getleon.ai' + } +]; diff --git a/docs/pt-BR/README.md b/docs/pt-BR/README.md new file mode 100644 index 0000000..f326859 --- /dev/null +++ b/docs/pt-BR/README.md @@ -0,0 +1,118 @@ +# Introdução + +## O que é Leon? + +Leon é um **assistente pessoal de código aberto** que vive no seu servidor. + +Ele faz coisas quando você pedir. + +Você pode falar com ele e ele pode falar com você. +Você também pode lhe mandar mensagens e ele também, a você. +Se você quiser, Leon pode se comunicar com você offline, para proteger sua privacidade. + +Você pode pensar nele como um segundo cérebro. + +::: tip +Leon ainda é um jovem. Se você desejar, pode ajudar [contribuindo](https://github.com/leon-ai/leon/blob/develop/.github/CONTRIBUTING.md) <3 +::: + +## Demo + +O Vídeo está disponível [aqui](http://www.youtube.com/watch?v=p7GRGiicO1c). + +## Motivações + + +1. Como desenvolvedores (ou não), nós **amamos criar** coisas, especialmente aquelas que podem **ajudar** na sua **vida diária**. Então, ao invés de construir um projeto dedicado para cada coisa, Leon pode nos ajudar através da sua estrutura de **packages/modules** (skills). Nós cremos que é melhor que manter suas ideias em backlog pra sempre, certo? +2. Com sua estrutura genérica, **todo mundo** pode **criar** seu próprio **módulo** e **compartilhá-lo**. Assim, há apenas um núcleo (to rule them all). +3. Leon usa **conceitos de IA**, o que é legal. +4. **Privacidade é importante**, então você pode configurar Leon para falar com ele **offline**. Você já pode lhe enviar **textos**, **sem** nenhum **serviço de terceiros**. +5. Por último, mas não menos importante: **código aberto** é ótimo! + +## Prerequisitos + +- **[Node.js](https://nodejs.org/) >= 10** +> O núcleo do Leon é desenvolvido usando o Node.js +- **npm >= 5** +> o npm é o gerenciador de pacotes do Node.js. Leon precisa dele para as dependências do seu núcleo. +- **[Python](https://www.python.org/downloads/) 3.6.x** +> Hoje em dia, os módulos do Leon são escritos exclusivamente em Python. +- **[Pipenv](https://docs.pipenv.org)** +> Pipenv permite que os módulos sejam executados num ambiente dedicado. Ele também já traz um gerenciador de pacotes embutido para as dependencias dos seus módulos. +- **SO's Suportados: Linux, macOS and Windows** +> Precisa explicação? :) + +::: tip +Você pode ler a página de [Como Fazer...](/how-to/) para instalar os pré-requisitos. +::: + +## Installation + +### Download + +Você tem duas opções principais para baixar o Leon: + +#### 1. Git + +Você pode clonar o [repositório do GitHub](https://github.com/leon-ai/leon) de diferentes branches. + +##### Master Branch + +A branch `master` é usada como um snapshot da última release: + +```bash +git clone -b master https://github.com/leon-ai/leon.git leon +``` + +##### Develop Branch + +A branch `develop` é a branch padrão. Aqui é onde as últimas modificações são combinadas. O que significa que nessa branch você vai ter acesso às últimas modificações antecipadamente, mas tenha em mente que não serão tão estáveis quanto a `master`: + +```bash +git clone https://github.com/leon-ai/leon.git leon +``` + +#### 2. Arquivos de Release + +Você também pode baixar a última versão seguindo [este link](https://github.com/leon-ai/leon/releases/latest). + +### Install + +Depois de ter instalado todos os pré-requisitos, e ter baixado o Leon, você pode instalar assim: + +```bash +# Go to the project root +cd leon + +# Install +npm install +``` + +## Uso + +Assegure-se que todo o processo ocorreu bem com o comando: + +```bash +npm run check +``` + +Isto deve lhe retornar um relatório sobre o quanto Leon está instalado/configurado. Não se preocupe se você tiver alguns avisos no relatório. Possivelmente, isto é porque você ainda não [configurou o Leon](/configuration.md) + +Se o relatório mencionar que *Leon can run correctly*, então você pode montar e iniciar o Leon + +```bash +# Build +npm run build + +# Run +npm start + +# Go to http://localhost:1337 +# Hooray! Leon is running +``` + +Nessa altura, você já pode comunicar-se com ele por texto e pedir a ele para fazer coisas. + +::: tip +Para ver o que ele pode fazer, cheque a [lista de pacotes](https://github.com/leon-ai/leon/tree/develop/packages). +::: diff --git a/docs/pt-BR/architecture.md b/docs/pt-BR/architecture.md new file mode 100644 index 0000000..5338955 --- /dev/null +++ b/docs/pt-BR/architecture.md @@ -0,0 +1,30 @@ +# Arquitetura + +Assegure-se de ler o [glossário](/pt-BR/glossary.md) para entender melhor esta seção. + +## Diagrama Arquitetural de Alto Nível + +![Diagrama Arquitetural de Alto Nível do Leon](/assets/img/high-level_architecture_schema.svg "Leon's High-Level Architecture Schema") + +## Cenário + +Este Cenário descreve os passos do esquema acima. Note que a maior parte das interações são feitas através de WebSockets. + +1. Cliente (web app, etc.) faz uma solicitação HTTP GET para buscar alguma informação sobre Leon. +2. A [API HTTP](/pt-BR/glossary.md#api) retorna as informações ao cliente. +3. Usuário fala ao microfone. +4. . + - a. Se o servidor de [hotwords](/pt-BR/offline.md#hotword) está iniciado, Leon ouve (offline) se o usuário está o chamando ao dizer "`Leon`". + - b. Se Leon entende o usuário lhe chamando, ele emite a mensagem para o servidor principal usando um WebSocket. Agora Leon está escutando (offline) o usuário. + - c. O Usuário diz `Hello!` para Leon, o cliente transforma a entrada de áudio em um blob de áudio. +5. O [ASR](/pt-BR/glossary.md#asr) transforma o blob de áudio em um arquivo de ondas (wave). +6. O parser [STT](/pt-BR/glossary.md#stt) transforma o wave em uma string (`Hello`). +7. . + - a. O usuário recebe o texto, que é encaminhado ao [NLU](/pt-BR/glossary.md#nlu). + - b. Ou digita `Hello!` com o teclado (ignorando os passos 1. à 7.a.). O texto `Hello!` é encaminhado ao NLU. +8. O NLU classifica o texto e seleciona uma classificação. +9. Se o [logger colaborativo](/pt-BR/collaborative-logger.md) está ativado, a classificação é enviada a ele. +10. O [Cérebro](/pt-BR/glossary.md#cerebro) cria um processo filho e executa o [módulo](/pt-BR/glossary.md#modulos) escolhido. +11. Se o [sincronizador](/pt-BR/glossary.md#sincronizador) está ativado e o módulo tem essa opção, ele sincroniza o conteúdo +12. O Cérebro gera uma [resposta](/pt-BR/glossary.md#respostas) e encaminha ao sintetizador [TTS](/pt-BR/glossary.md#tts). +13. O sintetizador TTS transforma a resposta em texto (e envia a resposta ao usuário como texto) para o buffer de áudio, que é então reproduzido pelo cliente. diff --git a/docs/pt-BR/bridges.md b/docs/pt-BR/bridges.md new file mode 100644 index 0000000..2b3b7c8 --- /dev/null +++ b/docs/pt-BR/bridges.md @@ -0,0 +1,19 @@ +# Bridges + +Bridges são uma parte do Leon que permite fazer conexões entre seu core e seus módulos. Você pode pensar neles como conectores também. As bridges também executam os módulos do Leon. +Na verdade, o core cria um [processo filho do Node.js](https://nodejs.org/api/child_process.html) que executa o módulo em questão. + +No futuro, nós gostaríamos da possibilidade de escrever módulos para o Leon um outras linguagens e não somente em Python. + +::: tip +As Bridges podem ser encontradas na pasta `bridges`. +::: + +## Python + +A bridge de Python é a razão pela qual Leon precisa do Python para funcionar hoje. Pois há somente uma bridge disponível até agora. + +Se você deseja executar um módulo separadamente, sem um processo filho, execute o seguinte comando partindo do diretório raiz do projeto: +```bash +PIPENV_PIPFILE=bridges/python/Pipfile pipenv run python bridges/python/main.py {LANG} {PACKAGE} {MODULE} "{STRING}" +``` diff --git a/docs/pt-BR/clients.md b/docs/pt-BR/clients.md new file mode 100644 index 0000000..3ff71fe --- /dev/null +++ b/docs/pt-BR/clients.md @@ -0,0 +1,37 @@ +# Clients + +Clients são o que os usuários vêem e usam explicitamente. É graças aos clientes que você pode interagir com o Leon. + +## Web App + +![App Web Leon](/assets/img/web-app_client_en.png "Leon's Web App") + +O app web é o único cliente hoje. Ele lhe permite interagir com Leon através do seu Browser. + +Uma vez que Leon está instalado, você pode acessar o cliente seguindo uma das secções seguintes: + +### Development + +```bash +# Rode o servidor em development +npm run dev:server + +# Rode o web app development +npm run dev:app + +# Vá para http://localhost:4242 +# Aeww! Leon está rodando +``` + +### Production + +```bash +# Build +npm run build + +# Run +npm start + +# Vá para http://localhost:1337 +# Aeww! Leon está rodando +``` diff --git a/docs/pt-BR/collaborative-logger.md b/docs/pt-BR/collaborative-logger.md new file mode 100644 index 0000000..8c6870e --- /dev/null +++ b/docs/pt-BR/collaborative-logger.md @@ -0,0 +1,22 @@ +# Collaborative Logger + +O Logger Colaborativo ajuda a a melhorar o entendimento do Leon. Para cada consulta que você submete ao Leon, ele envia uma solicitação HTTP para um servidor Leon externo, se o Logger Colaborativo estiver habilitado. + +Aqui estão as informações que o Leon armazena: + +- Sua Versão (número). +- Colculta (texto). +- Idioma. +- Pacote que o Leon usou. +- Módulo que o Leon usou. +- Sua confiança sobre seu entendimento. +- Timestamp atual. + +O logger colaborativo está **ativado por padrão**. Se você deseja desativá-lo, simplesmente configure a variável de ambiente `LEON_LOGGER` no seu arquivo `.env` para `FALSE` e reinicie o servidor. + +::: tip +Se você está curioso sobre o código, você pode encontrar: + +- Parte do código que interage com o logger na [NLU do Leon](https://github.com/leon-ai/leon/blob/develop/server/src/core/nlu.js). +- O código fonte do Logger Colaborativo no seu [repositório no GitHub](https://github.com/leon-ai/leon-logger). +::: diff --git a/docs/pt-BR/configuration.md b/docs/pt-BR/configuration.md new file mode 100644 index 0000000..e36dfe4 --- /dev/null +++ b/docs/pt-BR/configuration.md @@ -0,0 +1,131 @@ +# Configuração + +Esta seção deve ajudá-lo a configurar opções como dar uma voz ao Leon, entender a sua voz etc. + +::: warning +Estes arquivos devem ficar na sua máquina. Nunca os envie para um repositório remoto. Por padrão, eles já estão sendo ignorados graças ao `.gitignore`. +::: + +## Variáveis de Ambiente + +| Variável | Descrição | Valores | +| ----------------------------|-------------|---------| +| `LEON_LANG` | Idioma de fala e de entendimento do Leon. **Se você mudar o idioma**, rode: `npm run train expressions`. | `en-US` (padrão); `fr-FR` | +| `LEON_NODE_ENV` | Ambiente. | `development` (padrão); `production`; `testing` | +| `LEON_SERVER_HOST` | host do Server. | `localhost` (padrão) | +| `LEON_SERVER_PORT` | porta do Server. | `1337` (padrão) | +| `LEON_WEBAPP_HOST` | host do Web app. | `localhost` (padrão) | +| `LEON_WEBAPP_PORT` | porta do Web app. | `4242` (padrão) | +| `LEON_TIME_ZONE` | Fuso horário do Leon. | Seu fuso horário atual (padrão); [Moment Timezone](https://momentjs.com/timezone/) | +| `LEON_AFTER_SPEECH` | Ativar/Desativar escuta automática depois de falar. Torna desnecessário dizer `Leon` para dar outro comando quando você já falou uma vez. | `true`; `false` (padrão) | +| `LEON_STT` | Ativar/Desativar STT. | `true`; `false` (padrão) | +| `LEON_STT_PROVIDER` | Provedor STT. | `deepspeech` (padrão); `google-cloud-stt`; `watson-stt` | +| `LEON_TTS` | Ativar/Desativar TTS. | `true`; `false` (padrão) | +| `LEON_TTS_PROVIDER` | Provedor TTS. | `flite` (padrão); `google-cloud-tts`; `amazon-polly`; `watson-tts` | +| `LEON_LOGGER` | Ativar/Desativar logger colaborativo. | `true` (padrão); `false` | +| `PIPENV_PIPFILE` | Caminho do Pipfile. Não mude, à menos que você saiba o que está fazendo. | `bridges/python/Pipfile` (padrão) | +| `PIPENV_VENV_IN_PROJECT` | Cria o virtualenv no mesmo nível que o Pipfile. Não mude, à menos que você saiba o que está fazendo. | `true` (padrão) | + +## Voz + +O Leon tem vários provedores para o seu STT e TTS. Você pode configurar um (ou vários) e escolher o seu favorito. + +::: tip +Para ativar o STT e/ou o TTS do Leon, no seu arquivo `.env`, **você deve configurar `LEON_STT=true` e/ou `LEON_TTS=true`** + +Também, **você também precisa inquirir o provedor, configurando `LEON_STT_PROVIDER={SUA ESCOLHA DE PROVEDOR STT}` and/or `LEON_TTS_PROVIDER={SUA ESCOLHA DE PROVEDOR TTS}`**. +Cheque a seção [variáveis de ambiente](/configuration.md#variaveis-de-ambiente) para saber os valores para os provedores. +::: + +### Offline + +Confira [esta seção](/offline.md). + +### Amazon + +#### Amazon Polly (TTS) + +1. [Um um novo usuário IAM](https://console.aws.amazon.com/iam/home#/users$new?step=details) no console AWS. Escolha um `User name`, na seção `Access type`, marque `Programmatic access` e entao clique `Next`. +2. Na seção de permissões, escolha `Attach existing policies directly` e procure por `Polly`. Então, marque o item `AmazonPollyFullAccess`. Clique `Next` (e pule a seção 'tag'). +3. Clique no botão `Create user`. +4. Você deverá ver um `Access key ID` e um `Secret access key`. Copie Ambos e cole no arquivo `server/src/config/voice/amazon.json` do Leon. + +### Google Cloud + +Usando esse provedor, as credenciais são as mesmas para STT e TTS + +#### Google Cloud STT & Google Cloud TTS + +1. [Crie ou selecione um projeto](https://console.cloud.google.com/cloud-resource-manager) no GCP (Google Cloud Platform). +2. Ative a [STT API](https://console.cloud.google.com/apis/library/speech.googleapis.com) e/ou a [TTS API](https://console.cloud.google.com/apis/library/texttospeech.googleapis.com). +3. [Crie uma service account key](https://console.cloud.google.com/apis/credentials/serviceaccountkey). +4. Faça o Download do arquivo JSON e copie seu conteúdo para o arquivo `server/src/config/voice/google-cloud.json`. + +::: tip +A variável de ambiente `GOOGLE_APPLICATION_CREDENTIALS` é usada pelo Google para carregar as credenciais. +O Leon cria e configura o valor desta variável para você. +::: + +### Watson + +O IBM Watson tem credenciais para cada serviço STT e TTS. + +#### Watson STT + +1. [Clique aqui](https://console.bluemix.net/catalog/services/speech-to-text) para obter suas credenciais. +2. Clique em `Create` (ou `Sign up to Create` se você ainda não tiver uma conta). +3. Clique em `Manage` no menu da esquerda, e então em `Show Credentials`. +4. Copie `API Key` e `URL`, e então cole no arquivo `server/src/config/voice/watson-stt.json`. + +#### Watson TTS + +1. [Click here](https://console.bluemix.net/catalog/services/text-to-speech) to get your credentials. +2. Click on `Create` (or `Sign up to Create` if you do not have an account yet). +3. Click on `Manage` in the left menu, then on `Show Credentials`. +4. Copy `API Key` and `URL`, then paste them to the following Leon's file: `server/src/config/voice/watson-tts.json`. + +## Synchronizer + +Se um módulo tem essa opção, assim que um módulo tiver sido processado, você pode sincronizar seu conteúdo através de diferentes métodos. + +> Por exemplo, o módulo *YouTube* do pacote *[Video Downloader Package](https://github.com/leon-ai/leon/tree/develop/packages/videodownloader)* lhe permite sincronizar seus vídeos baixados na sua conta do Google Drive ou no seu dispositivo. + +::: tip +Para determinar se um módulo inclui esta opção, simplesmente verifique sua configuração usando este arquivo: `packages/{PACKAGE NAME}/config/config.json`. + +**Neste arquivo, defina a chave `enabled` como `true`** para ativar o sincronizador para um módulo específico. +::: + +| Método | Descrição | +| --------------------|--------------------------- +| `direct` | Sincronizar conteúdo com o seu dispositivo atual. | +| `google-drive` | Sincronizar conteúdo com o Google Drive. | + +### Direct + +```json +"synchronization": { + "enabled": true, + "method": "direct", + "email": "" +} +``` +> *`packages/{PACKAGE NAME}/config/config.json`* + +### Google Drive + +1. [Crie ou Selecione um projeto](https://console.cloud.google.com/cloud-resource-manager) no GCP (Google Cloud Platform). +2. Ative a [Google Drive API](https://console.developers.google.com/apis/library/drive.googleapis.com). +3. [Crie uma service account key](https://console.cloud.google.com/apis/credentials/serviceaccountkey). +4. Faça o Download do arquivo JSON e copie seu conteúdo para o arquivo `server/src/config/synchronizer/google-drive.json`. + +```json +"synchronization": { + "enabled": true, + "method": "google-drive", + "email": "{YOUR GOOGLE EMAIL ADDRESS}" +} +``` +> *`packages/{PACKAGE NAME}/config/config.json`* + +Um email é enviado para este endereço, uma vez que o Leon tenha sincronizado seu conteúdo com o Google Drive. diff --git a/docs/pt-BR/glossary.md b/docs/pt-BR/glossary.md new file mode 100644 index 0000000..632e77c --- /dev/null +++ b/docs/pt-BR/glossary.md @@ -0,0 +1,99 @@ +# Glossário + +Alguns termos da documentação podem ser desconhecidos para você. Esta seção lhe ajudará a ter um melhor entendimento desses termos e como eles estão relacionados ao Leon. + +## API + +API (ou *Application Programming Interface*/*Interface de Programação de Aplicação*) é uma interface que permite a comunicação entre nós diferentes de um projeto. Esses nós podem ser um pacote, biblioteca, serviço etc. + +Exemplos de API's do Leon: +- A [HTTP API](https://github.com/leon-ai/leon/tree/develop/server/src/api) permite trocar dados entre servidor e cliente. +- A [WebSocket API](https://github.com/leon-ai/leon/blob/develop/server/src/core/server.js) permite ter uma comunicação bidirecional entre servidor e cliente. +- A biblioteca [Python API](https://github.com/leon-ai/leon/blob/develop/bridges/python/utils.py) permite desenvolvedores pegar funções para trabalhar em modulos do Leon. + +## ASR + +ASR (ou *Automatic Speech Recognition*/*Reconhecimento Automático de Fala*) é o uso de técnicas computacionais e de software para identificar e processar a voz humana. + +Leon usa o ASR para que sua voz seja compreensível para ele. + +> Anexos: +> - [app/js/main.es6.js](https://github.com/leon-ai/leon/blob/develop/app/js/main.es6.js) *web app ASR*. +> - [server/src/core/asr.js](https://github.com/leon-ai/leon/blob/develop/server/src/core/asr.js) *servidor ASR*. + +## Respostas + +As respostas são sentenças que o Leon pode lhe entregar. +Cada [pacote](/glossary.md#pacotes) tem seu próprio set de respostas com diferentes traduções. + +> Anexo: [packages/checker/data/answers/en.json](https://github.com/leon-ai/leon/blob/develop/packages/checker/data/answers/en.json) *exemplo de respostas em inglês do pacote `Checker`*. + +## Cérebro + +O Cérebro do Leon é a maior parte do seu núcleo. Aqui é onde ele executa seus [módulos](/glossary.md#modulos), fala escolhe sentenças etc. + +> Anexo: [server/src/core/brain.js](https://github.com/leon-ai/leon/blob/develop/server/src/core/brain.js) *Cérebro do Leon*. + +## Classificador + +Um classificador é um tipo especial de modelo. Uma vez que tenha sido treinado, ele retorna um resultado com base num algoritmo e então esse resultado é usado para tomar decisões. + +O Leon usa classificadores para ter um resultado armazenado da fase de treinamento de [expressões](/glossary.md#expressoes). + +## Expressões + +As expressões são o conjunto de dados que Leon usa para treinar seu aprendizado. +Cada [pacote](/glossary.md#pacotes) tem seu próprio conjunto de dados com as diferentes traduções. + +> Anexo: [packages/checker/data/expressions/en.json](https://github.com/leon-ai/leon/blob/develop/packages/checker/data/expressions/en.json) *exemplo das expressões em inglês do pacote `Checker`*. + +## Modules + +Módulos são as habilidades de Leon. É graças a eles que Leon pode fazer coisas. + +::: tip +Quanto mais módulos Leon tem, mais habilidoso ele se torna. +Não deixe de [contribuir](https://github.com/leon-ai/leon/blob/develop/.github/CONTRIBUTING.md)! <3 +::: + +## NLU + +NLU (ou *Natural Language Understanding*/*Entendimento Natural de Linguagem*) ajuda os computadores a entender linguagem humana. + +O Leon usa o NLU para carregar o [classificador](/glossary.md#classificador), classificar o que você diz a ele e escolher a classificação correta, tomando decisões que ele julga mais precisas. + +> Anexo: [server/src/core/nlu.js](https://github.com/leon-ai/leon/blob/develop/server/src/core/nlu.js) *NLU do Leon*. + +## Pacotes + +Os pacotes do Leon contêm um ou uma infinidade de [modules](/glossary.md#modulos). Você pode considerar pacotes como uma espécie de módulo. É onde as [respostas](/glossary.md#respostas) e [expressões](/glossary.md#expressions) são armazenadas. + +> Anexo: [packages/leon](https://github.com/leon-ai/leon/tree/develop/packages/leon) *exemplo do pacote `Leon` contendo módulos relacionados a ele mesmo*. + +::: tip +A lista completa de pacotes está disponível [aqui](https://github.com/leon-ai/leon/tree/develop/packages). +::: + +## STT + +STT (ou *Speech-To-Text*/*Fala-Para-Texto*) transforma um fluxo de áudio (fala) numa string (texto). + +Leon tem vários parsers STT. Você pode escolher um (ou vários) e [configurá-lo](/configuration.md#voz). + +> Anexo: [server/src/stt/stt.js](https://github.com/leon-ai/leon/blob/develop/server/src/stt/stt.js) *STT do Leon*. + +## Sincronizador + +Se o [módulo](/glossary.md#modulos) requisitado lhe oferecer essa escolha, o sincronizador lhe permite sincronizar seu conteúdo de diferentes formas(Google Drive, on your current device, etc). + +Você pode [configurar](/configuration.md#sincronizador) seu método favorito para cada módulo que incluir esta funcionalidade. + +> Anexo: [server/src/core/synchronizer.js](https://github.com/leon-ai/leon/blob/develop/server/src/core/synchronizer.js) *Sincronizador do Leon*. + +## TTS + +TTS (ou *Text-To-Speech*/*Texto-Para-Fala*) transforma uma string (texto) em um fluxo de áudio (fala). + +Leon tem vários sintetizadores TTS, você pode escolher um (ou vários) e [configurá-los](/ configuration.md # voice). + +> Anexo: [server/src/tts/tts.js](https://github.com/leon-ai/leon/blob/develop/server/src/tts/tts.js) *TTS do Leon*. diff --git a/docs/pt-BR/how-to/README.md b/docs/pt-BR/how-to/README.md new file mode 100644 index 0000000..4961157 --- /dev/null +++ b/docs/pt-BR/how-to/README.md @@ -0,0 +1,86 @@ +# Como Fazer... + +## Como Instalar o Node.js + +### Usando nvm (recomendado) + +[nvm](https://github.com/creationix/nvm) (Node Version Manager) lhe permite baixar, instalar e gerenciar versões do Node.js. Com nvm, você pode facilmente trocar entre diferentes versões instaladas no seu sistema. Você pode obtê-lo nos seguintes links: + +- Para [Linux/macOS](https://github.com/creationix/nvm#install-script) +- Para [Windows](https://github.com/coreybutler/nvm-windows#installation--upgrades) + +### Forma Tradicional + +De outra forma, você pode obter o instalador do Node.js correspondente ao seu sistema [aqui](https://nodejs.org/en/download/). + +### O Node.js está instalado? + +Confira se o Node.js está corretamente instalado com o seguinte comando: + +```bash +node --version +``` + +## Como Instalar o Python + +::: tip +O Python já pode estar instalado no seu sistema. Você pode checar com `python --version` ou `python3 --version`. +::: + +### Usando pyenv (recomendado) + +[pyenv](https://github.com/pyenv/pyenv) é um gerenciador de versões simples, que permite fazer praticamente o mesmo que o nvm faz para o Node.js. + +- Para [Linux](https://github.com/pyenv/pyenv-installer#installation--update--uninstallation) +- Para [macOS](https://github.com/pyenv/pyenv#homebrew-on-macos) + +### Forma Tradicional + +De outra forma, você pode obter o instalador do Python correspondente ao seu sistema [aqui](https://www.python.org/downloads/). +Depois de rodar o instalador, marque `Add Python to PATH`, e então instale. + +### O Python está instalado? + +Certifique-se que o Python está instalado com o seguinte comando: + +```bash +python --version +``` +ou +```bash +python3 --version +``` + +## Como Instalar o Pipenv + +::: warning +Antes de instalar o Pipenv, certifique-se de ter o Python instalado. +::: + +### Usando o pip (Linux/Windows) + +[pip](https://pip.pypa.io/en/stable/installing/) é um gerenciador de pacotes para Python. Ele permite baixar e instalar pacotes Python packages com facilidade. Nós podemos usar o pip para instalar o Pipenv graças ao comando abaixo: + +```bash +pip install pipenv --user +``` + +### Usando Homebrew (macOS) + +[Homebrew](https://brew.sh/) é um gerenciador de pacotes para macOS. Você pode facilmente instalar pacotes com ele. Para instalar o Pipenv, simplesmente execute o seguinte comando: + +```bash +brew install pipenv +``` + +### Forma Tradicional + +Bem, não há muito a ser dito aqui. Siga [este guia](https://pipenv.readthedocs.io/en/latest/install/). + +### Is Pipenv installed? + +Certifique-se que o Pipenv está instalado com este comando: + +```bash +pipenv --version +``` diff --git a/docs/pt-BR/offline.md b/docs/pt-BR/offline.md new file mode 100644 index 0000000..044a046 --- /dev/null +++ b/docs/pt-BR/offline.md @@ -0,0 +1,91 @@ +# Offline + +Nesta seção, você verá como configurar os nós offline do Leon. + +Com esses provedores STT/TTS e esse nó de hotword, tudo estará sendo executado em sua máquina, nada solicita um terceiro. +Para configurá-los todos ao mesmo tempo, basta executar o seguinte comando: + +```bash +npm run setup: offline +``` + +::: warning +- Os nós offline não estão disponíveis no Windows. +- O STT offline e o TTS offline funcionam apenas para a linguagem `en-US`. +::: + +## DeepSpeech (STT) + +Para o STT offline, Leon usa o [DeepSpeech] (https://github.com/mozilla/DeepSpeech), que é uma implementação do TensforFlow da arquitetura DeepSpeech do Baidu. + +Tudo já está pronto para ser usado, você só precisa executar um comando para baixar e configurar o modelo pré-treinado (~ 2 GB). +Se você deseja instalar apenas o STT offline, execute o seguinte comando: + +```bash +npm run setup: offline-stt +``` + +Então, no seu arquivo `.env`, configure` LEON_STT = true` e `LEON_STT_PROVIDER = deepspeech`. + +::: tip +O Leon roda a versão CPU por padrão. +Você pode baixar a versão GPU para tornar o reconhecimento mais rápido com: `npm install deepspeech-gpu`. +Para instalá-lo corretamente em sua máquina, você pode seguir [este link](https://medium.com/@taylordenouden/installing-tensorflow-gpu-on-ubuntu-18-04-89a142325138). +Depois de instalado, Leon detecta automaticamente e já executa a versão GPU. +::: + +## Flite (TTS) + +Para o TTS offline, Leon usa o [CMU Flite] (http://www.festvox.org/flite/), que é um mecanismo de síntese de texto para fala de código aberto pequeno e rápido desenvolvido na CMU (*Carnegie Mellon University*) + +Da mesma forma, aqui tudo já está pronto, você só precisa executar um comando para baixar o binário e configurar. +Se você deseja instalar apenas o TTS offline, execute o seguinte comando: + +```bash +npm run setup: offline-tts +``` + +Então, no seu arquivo `.env`, configure` LEON_TTS = true` e `LEON_TTS_PROVIDER = flite`. + +::: tip +Essa voz pode ser ... bem engraçada :) +::: + +## Hotword + +O nó de hotwords é um processo independente do Node.js que permite que o Leon escute a hotword `Leon`. Uma vez que Leon ouve seu nome, ele pode processar seu pedido. + +### Configuração + +::: danger +O serviço de hotword precisa do **Node.js 8** para ser instalado e executado. +::: + +::: tip +Use o [nvm](/how-to/#using-nvm-recommended) para alternar facilmente entre suas versões do Node.js. +::: + +Se você deseja instalar apenas o hotword offline, execute o seguinte comando: + +```bash +npm run setup: offline-hotword +``` + +### Uso + +Certifique-se de que o servidor do Leon esteja em execução e, a partir da raiz do projeto, execute o seguinte comando: + +```bash +npm run wake + +# Agora diga "Leon" +``` + +### Idiomas + +O nó de hotword suporta os seguintes idiomas: + +- `en-US` +- `fr-FR` + +Para mudar o idioma, simplesmente mude o idioma do projeto através da variável de ambiente [`LEON_LANG`] (/configuration.md#environment-variables) e execute novamente o servidor principal e o serviço de hotword. diff --git a/docs/pt-BR/packages-modules.md b/docs/pt-BR/packages-modules.md new file mode 100644 index 0000000..49695f0 --- /dev/null +++ b/docs/pt-BR/packages-modules.md @@ -0,0 +1,478 @@ +# Packages & Modules + +Modules are the skills of Leon, this is thanks to them Leon is able to do things according to what you say. In this section you will have a deeper look into modules. + +## Packages + +Packages contain an infinity of modules. A package is nothing more than a **folder containing modules**, you can consider them as a category of modules. + +> E.g. the *[Checker](https://github.com/leon-ai/leon/tree/develop/packages/checker)* package contains modules such as the *[Is It Down](https://github.com/leon-ai/leon/blob/develop/packages/checker/isitdown.py)* one because this package includes modules related to the "checking" purposes. + +The full packages list is available [here](https://github.com/leon-ai/leon/tree/develop/packages). + +### Directory Structure + +Packages are listed in the `packages` directory. Let's take the [*Video Downloader*](https://github.com/leon-ai/leon/tree/develop/packages/videodownloader) package as example. + +Note the **package name must be lowercase and in English**. + +::: vue +videodownloader +├── `config` +│ ├── config.json +│ └── config.sample.json +├── `data` +│ ├── answers +│ │ ├── en.json +│ │ └── fr.json +│ ├── db +│ └── expressions +│ ├── en.json +│ └── fr.json +├── `test` +│ └── youtube.spec.js +├── README.md +├── \_\_init\_\_.py +├── version.txt +└── youtube.py +::: + +- [`packages/videodownloader`](https://github.com/leon-ai/leon/tree/develop/packages/videodownloader): package name. +- `packages/videodownloader/config/config.json`: package configuration. It contains the configuration of each of its module. +- [`packages/videodownloader/config/config.sample.json`](https://github.com/leon-ai/leon/tree/develop/packages/videodownloader/config/config.sample.json): sample configuration file. This file is copied during the setup to generate the file above. +- [`packages/videodownloader/data/answers`](https://github.com/leon-ai/leon/tree/develop/packages/videodownloader/data/answers): folder containing answers translations of each module. +- [`packages/videodownloader/data/db`](https://github.com/leon-ai/leon/tree/develop/packages/videodownloader/data/db): folder containing the package database. +- [`packages/videodownloader/data/expressions`](https://github.com/leon-ai/leon/tree/develop/packages/videodownloader/data/expressions): folder containing understanding dataset of each module. Those dataset are used to train the understanding model. +- [`packages/videodownloader/test`](https://github.com/leon-ai/leon/tree/develop/packages/videodownloader/test): folder containing tests of each module. +- [`packages/videodownloader/README.md`](https://github.com/leon-ai/leon/tree/develop/packages/videodownloader/README.md): file containing package/modules purposes. +- [`packages/videodownloader/__init__.py`](https://github.com/leon-ai/leon/tree/develop/packages/videodownloader/__init__.py): empty file allowing to load the package as a Python package. +- [`packages/videodownloader/version.txt`](https://github.com/leon-ai/leon/tree/develop/packages/videodownloader/version.txt): file containing the package version. +- [`packages/videodownloader/youtube.py`](https://github.com/leon-ai/leon/tree/develop/packages/videodownloader/youtube.py): *YouTube* module. + +Each package: +- Has its own version. +- Has its own configuration (for each module). +- Has its own dataset (for each module). +- Has its own tests (for each module). + +### Versioning + +- Leon's packages follow the [SemVer](https://semver.org). +- Each new module increases the *MINOR* version number of a package *(e.g. 1.0.0 -> 1.1.0)*. +- Each time a *MAJOR* or *MINOR* version number of a package is increased, then increase the *MINOR* one of the whole project *(e.g. 1.0.0 -> 2.0.0 | 1.1.0 -> 1.1.0)*. +- Each time a *PATCH* version number of a package is increased, then increase the *PATCH* version number of the whole project *(e.g. 1.0.0 -> 1.0.1 -> 1.0.1)*. + +## Modules + +**Modules are the skills of Leon**. + +When Leon understands what you told him, he: +1. Triggers a module. +2. Do the module job. +3. Returns you the output of that module. + +Each module has its own purpose and its own configuration. Do not hesitate to browse the [packages list](https://github.com/leon-ai/leon/tree/develop/packages) to understand their goals. + +Today, modules are written in Python but in the future they could also support other languages thanks to the [bridges](/bridges.md). + +### Configuration + +Let's take the [*Video Downloader*](https://github.com/leon-ai/leon/tree/develop/packages/videodownloader) package again as example. +```json +{ + "youtube": { + "api_key": "YOUR_GOOGLE_API_KEY", + "playlist_id": "PLAYLIST_ID", + "options": { + "synchronization": { + "enabled": true, + "method": "direct", + "email": "" + } + } + } +} +``` +> *`packages/videodownloader/config/config.json`* + +In each package configuration file, you can add new keys/value as much as you want while you are creating a module. + +In this example, the keys `api_key` and `playlist_id` have been added to the *YouTube* module configuration. +It allows the module to pick the values to request the YouTube API. + +To have access to these properties, you can use the [utils.config(key)](#config-key) function. + +Options are used when it needs interaction between a module and the core. They can be used for the [synchronizer](/configuration.md#synchronizer) for example. + +::: tip +Do not hesitate to take a look at the other modules to have a better understanding. +::: + +### Dataset & Translations + +To reply and understand you, Leon needs his dataset and translations. +Indeed, his dataset are divided into two parts: [expressions](/glossary.md#expressions) and [answers](/glossary.md#answers). + +- Every module has their own expressions and answers. +- Each of these dataset has their own translations. +- Translations are represented by the filename of these dataset, such as `en.json`, `fr.json`, etc. + +#### Expressions + +Expressions are the data used to train the Leon's understanding. When you execute the [training script](/scripts.md), all of the expressions of each module are browsed to generate the [classifier](/glossary.md#classifier). + +Note that each module expression has its own confidence. + +> ```json +> { +> "whoami": [ +> "Who are you?", +> "How they call you?", +> "What's your name?", +> "Tell me who you are", +> "Introduce yourself" +> ] +> } +> ``` + +> E.g. [*Who Am I* module English expressions](https://github.com/leon-ai/leon/blob/develop/packages/leon/data/expressions/en.json) belonging to the *Leon* package. + +##### Fallbacks + +Despite the expressions you wrote, it might be possible Leon still does not understand some of them. This is where fallbacks jump in the game. + +In the [`core/langs.json`](https://github.com/leon-ai/leon/blob/develop/core/langs.json) file, you can find the list of the supported languages with several properties: + +- `short`: the short language code. +- `min_confidence`: the minimum confidence of the Leon's comprehension. If the confidence is smaller than the given one, Leon replies you he is not sure about what you said. +- `fallbacks`: force the module selection. Use the `words` key to determine on which words you want Leon pick up a module. And use the `package` and `module` keys to define which module should be executed on the given words. + +#### Answers + +Answers are the data used by Leon to provide you results binded with the modules outputs. In addition, answers contains sub properties to have different kind of answers per module. + +> ```json +> { +> "greeting": { +> "default": [ +> "Hello there!" +> ], +> "morning_good_day": [ +> "Good morning, I hope your day will be full of joy and productivity!" +> ], +> "morning": [ +> "Good morning!" +> ], +> "too_late": [ +> "Hello! I'm feeling grateful you still talk to me, but you should get some sleep now." +> ] +> } +> } +> ``` + +> E.g. part of the [*Greeting* module English answers](https://github.com/leon-ai/leon/blob/develop/packages/leon/data/answers/en.json) belonging to the *Leon* package. + +## Create a Module + +::: tip +- Creating a module is one of the best way to contribute in Leon! Before doing that, please make sure you review [this document](https://github.com/leon-ai/leon/blob/develop/.github/CONTRIBUTING.md) <3 +- For example, you could think about creating a todo list module *(for such module, the Leon's NLP should be improved)*. Check out the [roadmap](https://roadmap.getleon.ai) to see what is in the pipeline. +- Don't hesitate to [open an issue](https://github.com/leon-ai/leon/issues/new/choose) if you have any questions. +::: + +Each module is included in a package *(e.g. `packages/{PACKAGE NAME}/{MODULE NAME}.py`)*. + +### Steps + +Here are the basics steps to create a module. For those steps, we will take a tweets grabber module as example. + +#### 1. Define the Purpose + +- I want to create a tweets grabber module. When I say or write: +``` +Grab my latest tweets +``` +- I want Leon tells me my 5 latest tweets with the stats of each. +- It seems this module does not correspond to any existing package (category). So I create the *Twitter* package by creating the `packages/twitter` folder. +- To do so, I make sure it follows the [package directory structure](#directory-structure) and contains the required files mentioned in that structure. + +#### 2. Name Your Module + +- I choose to name my module `Tweets Grabber`. + +#### 3. Write the Code + +- To request the Twitter API, I need API credentials. So I set the Twitter API key(s) in the `packages/twitter/config/config.json` file I previously created in the step 1. +- In addition, I create the `packages/twitter/tweetsgrabber.py` file, define my module function and I write the code for my module. +- While I'm writing the code, from the project root directory I use the following command: +```bash +PIPENV_PIPFILE=bridges/python/Pipfile pipenv run python bridges/python/main.py en twitter tweetsgrabber "Grab my latest tweets" +# It executes my module on the fly +``` + +#### 4. Write the Tests + +- Now that I'm satisfied with my module, I create the `packages/twitter/test/tweetsgrabber.spec.js` file. +- I write my [module tests](#test-a-module) in that file. + +#### 5. Share + +- I share my module to the world by [contributing](https://github.com/leon-ai/leon/blob/develop/.github/CONTRIBUTING.md). + +### Naming Convention + +- The module filename must contains only lowercase alphabetic characters and must use the English language. +> E.g. *Meaning of Life* module filename: `meaningoflife.py` +- The module function name must be the same as the filename. +> E.g. *Meaning of Life* function: `def meaningoflife(string):` + +### Module Function + +In the module file, you must name the module function by the name of the module. This function takes the input string (query) as parameter. + +``` +What is the meaning of life? +``` + +```python +#!/usr/bin/env python +# -*- coding:utf-8 -*- + +import utils + +def meaningoflife(string): + """Leon says what's the meaning of life""" + + # string: What is the meaning of life? + + return utils.output('end', 'meaning_of_life', utils.translate('meaning_of_life')) +``` + +### Persistent Data + +Leon uses [TinyDB](https://github.com/msiemens/tinydb) to deal with packages databases. Each package can have its own database and the database is managed by modules. + +For more information, you can refer to the: +- [utils.db()](#db-dbtype-tinydb) function. +- [TinyDB](https://tinydb.readthedocs.io) documentation. +- [YouTube module](https://github.com/leon-ai/leon/blob/develop/packages/videodownloader/youtube.py) as example. + +### Outputs + +Every module does something, and the outputs allow the core to understand what the module did and what is the state of its execution. +This is thanks to the outputs that Leon knows what to do next. + +The core understands two types of outputs: +- `inter`, which are the intermediate outputs. You can have **as many intermediate outputs as you want**. +- `end`, which is the final output. You must **only have one final output**, that allows Leon to know that the module execution is done. + +Outputs are represented by the [utils.output()](#output-type-code-speech) function. + +## Test a Module + +### End-to-End + +Modules come with their own tests. They are represented by a unique file for every module that can be found at: `packages/{PACKAGE NAME}/test/{MODULE NAME}.spec.js`. + +As you may noticed, JavaScript is used to test modules because the core is written in JavaScript and we do end-to-end tests by processing a query to the NLU. Then the Leon's brain is executed and returns the output. This is the output, especially the code, that you need to consider. + +Leon uses [Jest](https://jestjs.io/) as a testing framework. + +Here are two tests examples of the *Is It Down* module: + +```js +// You must use describe() with the following name syntax: {PACKAGE NAME}:{MODULE NAME} +describe('checker:isitdown', async () => { + // Each test must be represented by the test() + test('detects invalid domain name', async () => { + global.nlu.brain.execute = jest.fn() + // The string you want to test + global.nlu.process('Check if github is up') + + const [obj] = global.nlu.brain.execute.mock.calls + await global.brain.execute(obj[0]) + + // Grab the code and verify if it is the expected one + expect(global.brain.finalOutput.code).toBe('invalid_domain_name') + }) + + test('detects down domain name', async () => { + global.nlu.brain.execute = jest.fn() + global.nlu.process('Check if fakedomainnametotestleon.fr is up') + + const [obj] = global.nlu.brain.execute.mock.calls + await global.brain.execute(obj[0]) + + expect(global.brain.interOutput.code).toBe('down') + expect(global.brain.finalOutput.code).toBe('done') + }) +}) +``` +*These tests can be found in [`packages/checker/test/isitdown.spec.js`](https://github.com/leon-ai/leon/blob/develop/packages/checker/test/isitdown.spec.js)* + +Once you finished to write your tests, you can execute the following command to run them: + +```bash +npm run test:module {PACKAGE NAME}:{MODULE NAME} + +# E.g. +npm run test:module checker:isitdown +``` + +### On The Fly + +To test the behavior of your module while you are creating it, you can run this following command **from the project root**: + +```bash +PIPENV_PIPFILE=bridges/python/Pipfile pipenv run python bridges/python/main.py {LANG} {PACKAGE NAME} {MODULE NAME} "{QUERY}" + +# E.g. +PIPENV_PIPFILE=bridges/python/Pipfile pipenv run python bridges/python/main.py en checker isitdown "Check github.com is up" +``` + +## Utils Functions + +Utils functions are available in [bridges/python/utils.py](https://github.com/leon-ai/leon/blob/develop/bridges/python/utils.py). + +To use the following functions, do not forget to import the Python *utils* module at the beginning of your Leon's module: + +```python +import utils + +# utils.myFunc() +``` + +::: tip +You can also [contribute](https://github.com/leon-ai/leon/blob/develop/.github/CONTRIBUTING.md) by improving these functions or by adding new ones to make the modules creation even better. +::: + +### translate(key, d = { }) + +Randomly pick up a module answer from the `packages/{PACKAGE NAME}/data/answers/{LANG}.json` file via the given key, do string interpolation via the given data object and return the plain string answer. + +- `key`: module answer key to pick up the right string. +- `d`: data object for string interpolation. + +```json +{ + "greeting": { + "morning_good_day": [ + "Good morning, I wish you a very pleasant day!", + "Good morning, I hope your day will be full of joy and productivity!" + ], + "funny_hello": [ + "%fun_hello%, yes I try to be fun here." + ] + } +} +``` + +```python +utils.translate('morning_good_day') + +# >> Good morning, I wish you a very pleasant day! +# OR >> Good morning, I hope your day will be full of joy and productivity! +``` + +```python +fun_hello = 'Heeey' +utils.translate('funny_hello', { 'fun_hello': fun_hello }) + +# >> Heeey, yes I try to be fun here. +``` + +### output(type, code, speech = '') + +Communicate the module data to the core. + +- `type` (inter|end): output type to inform the core if the module execution is done or not. The `end` type must appears one time. +- `code`: output code to provide an additional information about the type of output. Usually used by the modules tests. +- `speech`: plain string answer. + +```python +utils.output('inter', 'just_a_code', 'This is an intermediate answer.') + +# >> + +utils.output('end', 'done', utils.translate('done_answer')) + +# >> +``` + +### finddomains(string) + +Find one or multiple domain name(s) substring from a string. + +- `string`: input string. + +```python +utils.finddomains('Go on github.com and mozilla.org please') + +# >> ['github.com', 'mozilla.org'] +``` + +### http(method, url) + +Send HTTP request with the user-agent `Leon/{VERSION NUMBER}`. It uses the [Request](http://docs.python-requests.org) Python library. + +- `method`: HTTP method. +- `url`: URL to request. + +```python +utils.http('GET', 'https://getleon.ai') + +# >> cf. http://docs.python-requests.org/en/master/user/advanced/#request-and-response-objects +``` + +### config(key) + +Get a module configuration from the `packages/{PACKAGE NAME}/config/config.json` file. + +- `key`: module configuration key. + +```json +{ + "anawesomemodule": { + "api_key": "my-super-api-key", + "options": {} + } +} +``` + +```python +utils.config('api_key') + +# >> my-super-api-key +``` + +### info() + +Returns information from the current query. + +```python +utils.info() + +# >> { 'lang': 'en', 'package': 'checker', 'module': 'isitdown' } +``` + +### createdldir() + +Create the downloads folder of the current module. When Leon needs to download something, it is saved into: `downloads/{PACKAGE NAME}/{MODULE NAME}`. + +```python +utils.createdldir() + +# >> +``` + +### db(dbtype = 'tinydb') + +Create a new dedicated database for a specific package. + +- `dbtype` (tinydb): database type. Only supports [TinyDB](https://tinydb.readthedocs.io) today. + +```python +utils.db() + +# >> { 'db': db_instance, 'query': Query, 'operations': operations } +``` diff --git a/docs/pt-BR/scripts.md b/docs/pt-BR/scripts.md new file mode 100644 index 0000000..8de3625 --- /dev/null +++ b/docs/pt-BR/scripts.md @@ -0,0 +1,56 @@ +# Scripts + +Aqui estão os scripts disponíveis que vc pode encontrar no [package.json](https://github.com/leon-ai/leon/blob/develop/package.json). + +Esses scripts **devem ser executados a partir do diretório raiz do projeto**. + +## Principais + +| Script | Propósito | +| ----------------------------------------|--------------------------------------------------------| +| `npm run wake` | Iniciar o processo de hotwords. | +| `npm start` | Rodar Leon em produção depois da build. | +| `npm run train expressions en|fr` | Trainar o entendimento do Leon. | +| `npm run check` | Verificar o quanto do Leon está instalado/configurado. | + +## Configuração + +| Script | Propósito | +| ----------------------------------------|---------------------------------------------| +| `npm run setup:offline` | Configurar todos os nós offline. | +| `npm run setup:offline-stt` | Configurar o STT offline. | +| `npm run setup:offline-tts` | Configurar o TTS offline. | +| `npm run setup:offline-hotword` | Configurar o nó de hotwords. | +| `npm run preinstall` | Acionado antes que `npm install` inicie. | +| `npm run postinstall` | Acionado depois que `npm install` termina. | + +## Build + +| Script | Propósito | +| ----------------------------------------|-----------------------------------------------| +| `npm run delete-dist:server` | Exclir a pasta de distribuição do servidor. | +| `npm run build` | Build Leon (aplicativo da web + servidor). | +| `npm run build:app` | Build o aplicativo da web. | +| `npm run build:server` | Build o servidor. | + +## Desenvolvimento + +| Script | Propósito | +| -------------------------------------------|----------------------------------------------------------------------------------------| +| `npm run dev:app` | Executar o aplicativo da web em desenvolvimento. | +| `npm run dev:server` | Executar o servidor em desenvolvimento. | +| `npm run prepare-release {VERSION NUMBER}` | Incrememtar a versão de Leon e gerar o changelog de acordo com as mensagens de commit. | +| `npm run commitmsg` | Acionado no commit. | + +## Teste + +| Script | Propósito | +| ---------------------------------------------------|---------------------------------------------------------------------------------| +| `npm run lint` | Verificar a sintaxe do código do projeto. | +| `npm test` | Executar todos os testes. | +| `npm run test:unit` | Executar testes unitários. | +| `npm run test:e2e` | Executar todos os tipos de testes end-to-end. | +| `npm run test:e2e:modules` | Executar todos os testes de módulos. | +| `npm run test:e2e:nlp-modules` | Executar testes para assegurar que todas as expressões sejam compreensíveis. | +| `npm run test:json` | Executar testes para verificar se todos os arquivos JSON estão em conformidade. | +| `npm run test:module {PACKAGE NAME}:{MODULE NAME}` | Executar testes de um determinado módulo. | diff --git a/docs/pt-BR/tests.md b/docs/pt-BR/tests.md new file mode 100644 index 0000000..2ebe072 --- /dev/null +++ b/docs/pt-BR/tests.md @@ -0,0 +1,35 @@ +# Testes + +Para garantir a qualidade do projeto, Leon tem testes automatizados. Como a codebase muda regularmente, os testes devem garantir que não haja regressão por causa dessas novas alterações. + +No Leon, existem vários tipos de testes, vamos mostrá-los nas próximas seções. Note que todos os testes são escritos em JavaScript. + +## Unidade + +Softwares são feitos de pequenas partes e a finalidade desses testes é assegurar o funcionamento dessas partes do projeto. + +Leon usa testes unitários para testar as partes do seu núcleo. + +Testes unitários podem ser: +- Encontrados na pasta `test/unit`. +- Executados via: `npm run test:unit`. + +## End-to-End + +Testes de end-to-end ou testes de integração asseguram o correto funcionamento de todo o comportamento de um recurso dedicado. Ele testa várias partes de uma só vez e espera por um resultado específico. + +Leon usa testes de end-to-end para testar seus módulos e sua PNL. + +Testes de ponta a ponta podem ser: +- Encontrados na pasta `test/e2e` e no arquivo `packages/{NOME DO PACOTE}/test/{NOME DO MÓDULO}.spec.js`. +- Executados via: `npm run test:e2e`. + +## JSON + +Os testes "JSON" estão relacionados à estrutura do Leon e não são necessariamente para softwares em geral. + +Leon os utiliza para garantir que todos os arquivos JSON sejam válidos e respeitem regras específicas, como sintaxe, pontuação etc. + +Os testes "JSON" podem ser: +- Encontrados na pasta `test/json`. +- Executados via: `npm run test:json`. diff --git a/package-lock.json b/package-lock.json index b6cba9e..650949c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -6374,6 +6374,7 @@ "resolved": "https://registry.npmjs.org/minipass/-/minipass-2.3.5.tgz", "integrity": "sha512-Gi1W4k059gyRbyVUZQ4mEqLm0YIUiGYfvxhF6SIlk3ui1WVxMTGfGdQ2SInh3PDrRTVvPKgULkpJtT4RH10+VA==", "dev": true, + "optional": true, "requires": { "safe-buffer": "^5.1.2", "yallist": "^3.0.0"