diff --git a/.codeclimate.yml b/.codeclimate.yml new file mode 100644 index 0000000..6a72d69 --- /dev/null +++ b/.codeclimate.yml @@ -0,0 +1,28 @@ +version: "2" + +plugins: + duplication: # for duplication analysis + enabled: true + config: + languages: + python: + python_version: 3 + pep8: # for code style analysis + enabled: true + config: + languages: + python: + python_version: 3 + bandit: # for security analysis + enabled: true + config: + languages: + python: + python_version: 3 + radon: # for complexity analysis + enabled: true + config: + languages: + python: + python_version: 3 + diff --git a/Dockerfile b/Dockerfile index 97030f7..ac72e99 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,9 +1,8 @@ FROM python:3.6 -RUN pip install rasa_core==0.10.4 +RUN pip install rasa_core==0.13.1 -RUN pip install rasa_nlu[spacy] && \ - python -m spacy download pt +RUN pip install rasa_nlu==0.14.0 RUN pip install rasa_nlu[tensorflow] diff --git a/README.md b/README.md index 07ec1bb..7b5825d 100644 --- a/README.md +++ b/README.md @@ -22,6 +22,8 @@

+ + ### Sobre o projeto

   @@ -50,85 +52,86 @@ As políticas de _branches_, _commits_, _pull requests_ e _issues_ se encontram #### Desenvolvimento -Para começar a desenvolver precisamos fazer algumas mudanças no código para que funcione localmente. + **Dependências** +* Docker +* Docker-compose +* Ngrok + +##### Setup do Telegram + +Para começar a desenvolver precisamos fazer algumas alterações no código para que funcione localmente. -Todas as mudanças estão descritas no código onde deve ser alterado, só que você não vai precisar sair procurando, eu vou lhe dizer onde que é. +1. Crie um bot para teste conversando com o @BotFather. -1. Altere o banco que deseja utilizar no arquivo notifier.py e no notifications.py +2. Agora altere os valores das seguintes variáveis de ambiente no **docker-compose**, com as credenciais do seu bot. ``` -# If you have your own database, changes to ('database', ) -client = MongoClient('mongodb://mongo-ru:27017/lino_ru') + # Para rodar no telegram altere as seguintes + # variáveis nos serviços Lino e Actions + - TELEGRAM_ACCESS_TOKEN= + - VERIFY=<@USUÁRIO_DO_BOT_NO_TELEGRAM> + - TELEGRAM_DB_URI=mongodb://mongo_lino:27010/lino_telegram + + # Ou utilize o banco que desejar + - TELEGRAM_DB_URI= ``` +**OBS 1:** Altere as variáveis necessárias no serviço do cronjob. -2. Caso esteja trabalhando com o Telegram, adicione o token nos arquivos notifier e no notifications.py +3. Comente as linhas que dizem respeito à variáveis do serviço do **Messenger** em todos os serviços. ``` -# If you want to use your own bot to development add the bot token as -# second parameters -TELEGRAM_ACCESS_TOKEN = os.getenv('TELEGRAM_ACCESS_TOKEN', '') + # - FACEBOOK_DB_URI + # - PSID + # - FACEBOOK_ACCESS_TOKEN + # - SECRET ``` -3. Caso esteja rodando o webcrawler local, altere a URL no arquivo notifier e no menu.py +4. Para conectar com o Telegram, você vai precisar gerar uma URL com certificado. Para isso, nós utilizamos o **Ngrok** (necessário instalá-lo). + +5. Agora rode o seguinte comando para expor a porta e gerar o certificado para nosso webhook. + ``` -# Change the url if you have your own webcrawler server -response = requests.get('http://:/cardapio/{}'.format(day)).json() + # Gera a URL com certificado (https) + ./ngrok http ``` -4. Caso queira usar com os mensageiros o Lino, utilize o ngrok para expor para o mundo +6. Substitua o valor da variável no serviço Lino. ``` -./ngrok http + # Altere o valor da variável seguinte + - WEBHOOK_URL= -f docker/.Dockerfile . +sudo docker build -t lino . ``` 2. Inicialize o _container_: ``` -sudo docker run --rm -it -v $PWD:/2018.2-Lino +sudo docker run --rm -it -p 5002:5002 -v $PWD:/2018.2-Lino lino ``` 3. Agora basta testar as novas alterações pelo terminal. -#### Container pra Desenvolvimento - -1. Caso queira inicilizar um ambiente de desenvolvimento com todos os serviços -``` -# Altere a imagem que deseja (qual mensageiro ou terminal) dentro do docker-compose -sudo docker-compose up --build -``` - ### Licença

   Lino é distribuído sob a licença GPLv3. Consulte LICENSE para obter detalhes.

diff --git a/docker-compose.yml b/docker-compose.yml index 7e921a0..fc60268 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,60 +1,103 @@ version: '3' services: - lino: - # If you want to development and use another image, - # change the image to the Dockerfile that corresponds to the one you want to use. - image: guila/lino:latest - ports: - - 5002:5002 - volumes: - - .:/2018.2-Lino - stdin_open: true - tty: true - environment: - - TRAINING_EPOCHS: ${TRAINING_EPOCHS} - - TELEGRAM_ACCESS_TOKEN: ${TELEGRAM_ACCESS_TOKEN} - - VERIFY: ${VERIFY} - - PSID: ${PSID} - - FACEBOOK_ACCESS_TOKEN: ${FACEBOOK_ACCESS_TOKEN} - - SECRET: ${SECRET} - - WEBHOOK_URL: ${WEBHOOK_URL} - - TELEGRAM_DB_URI: ${TELEGRAM_DB_URI} - - FACEBOOK_DB_URI: ${FACEBOOK_DB_URI} - # bot credentials in train.py or another train file. - depends_on: - - cronjob - - mongo_telegram - - mongo_facebook + lino: + # If you want to development and use another image, + # change the image to the Dockerfile that corresponds to the one you want to use. + build: + context: . + dockerfile: docker/Telegram.Dockerfile + ports: + - 5002:5002 + volumes: + - .:/2018.2-Lino + stdin_open: true + tty: true + environment: + - TRAINING_EPOCHS: ${TRAINING_EPOCHS} + - TELEGRAM_ACCESS_TOKEN: ${TELEGRAM_ACCESS_TOKEN} + - VERIFY: ${VERIFY} + - PSID: ${PSID} + - FACEBOOK_ACCESS_TOKEN: ${FACEBOOK_ACCESS_TOKEN} + - SECRET: ${SECRET} + - WEBHOOK_URL: ${WEBHOOK_URL} + - TELEGRAM_DB_URI: ${TELEGRAM_DB_URI} + - FACEBOOK_DB_URI: ${FACEBOOK_DB_URI} + # bot credentials in train.py or another train file. + depends_on: + - actions + - cronjob + - mongo_telegram + - mongo_facebook - mongo_telegram: - image: mongo:latest - command: mongod --port 27010 - volumes: - - /l/mongo_telegram/mongo_telegram_db:/data/db - ports: - - 27010:27010 + mongo_telegram: + image: mongo:latest + command: mongod --port 27010 + volumes: + - /l/mongo_telegram/mongo_telegram_db:/data/db + ports: + - 27010:27010 - mongo_facebook: - image: mongo:latest - command: mongod --port 27011 - volumes: - - /l/mongo_facebook/mongo_facebook_db:/data/db - ports: - - 27011:27011 + mongo_facebook: + image: mongo:latest + command: mongod --port 27011 + volumes: + - /l/mongo_facebook/mongo_facebook_db:/data/db + ports: + - 27011:27011 - cronjob: - image: guila/cronjob:latest - volumes: - - ./outputs:/home - stdin_open: true - tty: true - environment: - - URI_TELEGRAM: ${URI_TELEGRAM} - - URI_FACEBOOK: ${URI_FACEBOOK} - - TELEGRAM_ACCESS_TOKEN: ${TELEGRAM_ACCESS_TOKEN} - - FACEBOOK_ACCESS_TOKEN: ${FACEBOOK_ACCESS_TOKEN} - - PSID: ${PSID} - depends_on: - - mongo_telegram - - mongo_facebook + cronjob: + image: guila/cronjob:latest + volumes: + - ./outputs:/home + stdin_open: true + tty: true + environment: + - URI_TELEGRAM: ${URI_TELEGRAM} + - URI_FACEBOOK: ${URI_FACEBOOK} + - TELEGRAM_ACCESS_TOKEN: ${TELEGRAM_ACCESS_TOKEN} + - FACEBOOK_ACCESS_TOKEN: ${FACEBOOK_ACCESS_TOKEN} + - PSID: ${PSID} + depends_on: + - mongo_telegram + - mongo_facebook + + actions: + build: + context: . + dockerfile: ./docker/Actions.Dockerfile + ports: + - 5055:5055 + volumes: + - ./rasa/actions:/rasa/actions + - ./rasa/Makefile:/rasa/Makefile + command: "make run-actions" + environment: + - TELEGRAM_ACCESS_TOKEN: ${TELEGRAM_ACCESS_TOKEN} + - VERIFY: ${VERIFY} + - TELEGRAM_DB_URI: ${TELEGRAM_DB_URI} + - FACEBOOK_DB_URI: ${FACEBOOK_DB_URI} + + + elasticsearch: + image: docker.elastic.co/elasticsearch/elasticsearch:5.4.3 + container_name: elasticsearch + ports: + - "9200:9200" + - "9300:9300" + networks: + - docker_elk + kibana: + image: docker.elastic.co/kibana/kibana:5.4.3 + container_name: kibana + environment: + - "ELASTICSEARCH_URL=http://elasticsearch:9200" + ports: + - "5601:5601" + networks: + - docker_elk + depends_on: + - elasticsearch +networks: +docker_elk: + driver: bridge diff --git a/docker/Actions.Dockerfile b/docker/Actions.Dockerfile new file mode 100644 index 0000000..29ac51e --- /dev/null +++ b/docker/Actions.Dockerfile @@ -0,0 +1,20 @@ +FROM python:3.6-slim + +RUN apt update && apt install -y gcc make curl + +ADD ./docker/actions.requirements.txt /tmp/ + +RUN pip install --upgrade pip && \ + pip install -r /tmp/actions.requirements.txt + +ADD ./rasa/actions/ /rasa/actions/ +ADD ./rasa/Makefile /rasa/Makefile + +WORKDIR rasa/ + +EXPOSE 5055 + +HEALTHCHECK --interval=300s --timeout=60s --retries=5 \ + CMD curl -f http://0.0.0.0:5055/health || exit 1 + +CMD make run-actions diff --git a/docker/Messenger.Dockerfile b/docker/Messenger.Dockerfile index a8d9175..7a86ff8 100644 --- a/docker/Messenger.Dockerfile +++ b/docker/Messenger.Dockerfile @@ -2,8 +2,7 @@ FROM python:3.6 ADD ./requirements.txt /tmp -RUN pip install -r /tmp/requirements.txt && \ - python -m spacy download pt +RUN pip install -r /tmp/requirements.txt RUN pip uninstall -y tensorflow && pip install tensorflow==1.5 diff --git a/docker/Telegram.Dockerfile b/docker/Telegram.Dockerfile index dace813..5821bcf 100644 --- a/docker/Telegram.Dockerfile +++ b/docker/Telegram.Dockerfile @@ -2,10 +2,9 @@ FROM python:3.6 ADD ./requirements.txt /tmp -RUN pip install -r /tmp/requirements.txt && \ - python -m spacy download pt +RUN pip install -r /tmp/requirements.txt -RUN pip uninstall -y tensorflow && pip install tensorflow==1.5 +RUN pip uninstall -y tensorflow && pip install tensorflow==1.12.0 RUN mkdir /2018.2-Lino @@ -16,4 +15,4 @@ WORKDIR /2018.2-Lino/rasa ENV TRAINING_EPOCHS=450 \ CREDENTIALS="credentials.yml" -CMD python train-telegram.py +CMD make train && python train-telegram.py diff --git a/docker/actions.requirements.txt b/docker/actions.requirements.txt new file mode 100644 index 0000000..31373a6 --- /dev/null +++ b/docker/actions.requirements.txt @@ -0,0 +1,10 @@ +rasa-core==0.13.1 +rasa-core-sdk==0.12.1 +oauth2client==4.1.3 +gspread==3.1.0 +logger==1.4 +Flask==1.0.2 +Flask-Cors==3.0.6 +httpretty +requests +pymongo==3.7.1 diff --git a/docs/interviews/interviews.md b/docs/interviews/interviews.md index 8266890..f823ff1 100644 --- a/docs/interviews/interviews.md +++ b/docs/interviews/interviews.md @@ -40,4 +40,24 @@ **Mural da FGA** 10 - O mural da FGA possui muitas informações que se encontram no site do SAA. Aqui na secretaria nós somos subordinados ao SAA, os murais são atualizados para informar os alunos de maneira mais direta. +# Criação de um novo fluxo - UnB Idiomas +Uma entrevista fora realizada com a resposável do UnB Idiomas no Campus Gama - FGA com o intuito de apresentar a estrutura de um novo fluxo de integração do Lino, para sanar dúvidas relativas ao sistema de matrículas, valores dos cursos, testes de nivelamento e demais dúvidas frequentes aos usuários do UnB Idiomas. + +O UnB Idiomas é uma organização paralela à UnB e possui normas próximas para funcionamento, possui um representante em cada campus da Universidade de Brasília e a entrevistada, relatou quais pontos seriam importantes para o Lino integrar. + +Atualmente existem cursos regulares e cursos intensivos, sendo que os primeiros possuem duração de 4 meses aproximadamente e os cursos intensivos, 2 meses. Todas as informações estão disponíveis no [site oficial](www.unbidiomas.unb.br/) e possuem todas as informações necessárias para a integração. + +Após a analíse, foram percebidos que grande parte das informações são estáticas e não necessitam de uma integração advinda de uma requisição à um serviço externo. Porém, os arquivos de valores são atualizados semestralmente e precisam ser traduzidos para uma linguagem de código. Tais fluxos foram listados abaixo: + +- Valores dos cursos de idioma +- Duração dos módulos e semestre letivo +- Quais campus oferecerem determinado curso de idiomas +- Realização de testes de nivelamento +- Funcionamento da concessão de créditos +- Sistema de bolsas para estudantes que recebem auxílio estudantil +- Limites de faltas em cada curso +- Mudança de turmas durante o semestre letivo +- Cancelamento e Reembolso do valor pago + +Com tais fluxos encontrados, foi validado que se estes fluxos fossem implementados, seria de muito valor agregado ao UnB Idiomas e também aos seus usuários. diff --git a/rasa/Makefile b/rasa/Makefile index 429e530..ca169d5 100644 --- a/rasa/Makefile +++ b/rasa/Makefile @@ -1,11 +1,16 @@ train-nlu: - python -m rasa_nlu.train -c nlu_config.yml --data data/intents/nlu.md -o models --fixed_model_name nlu --project current --verbose + python -m rasa_nlu.train -c nlu_config.yml --fixed_model_name current --data data/intents/ -o models --project nlu --verbose train-core: - python -m rasa_core.train -d domain.yml -s data/stories/stories.md -o models/dialogue + python train.py + +train: train-nlu train-core run-telegram: - python -m rasa_core.run -d models/dialogue -u models/current/nlu --port 5002 -c telegram --credentials credentials.yml + python -m rasa_core.run -d models/dialogue -u models/nlu/current --port 5002 --credentials credentials.yml --endpoints endpoints.yml run-facebook: python train.py run-facebook + +run-actions: + python -m rasa_core_sdk.endpoint --actions actions diff --git a/rasa/actions/notifications/buttons_notification.py b/rasa/actions/buttons_notification.py similarity index 99% rename from rasa/actions/notifications/buttons_notification.py rename to rasa/actions/buttons_notification.py index 79c0900..03a7946 100644 --- a/rasa/actions/notifications/buttons_notification.py +++ b/rasa/actions/buttons_notification.py @@ -1,5 +1,5 @@ import os -from rasa_core.actions.action import Action +from rasa_core_sdk import Action # If you want to use your own bot to development add the bot token as # second parameters diff --git a/rasa/actions/calendar.py b/rasa/actions/calendar.py index 51ac317..6871493 100644 --- a/rasa/actions/calendar.py +++ b/rasa/actions/calendar.py @@ -1,5 +1,5 @@ import os -from rasa_core.actions.action import Action +from rasa_core_sdk import Action import requests # If you want to use your own bot to development add the bot token as @@ -16,10 +16,8 @@ def run(self, dispatcher, tracker, domain): dispatcher.utter_message('Vou buscar isso daí para você') crawlerRegister = 'https://webcrawler-matricula.botlino.com.br' try: - requests.get( - f'{crawlerRegister}/registration/downloadPdf', - timeout=3 - ) + requests.get(f'{crawlerRegister}/registration/downloadPdf', + timeout=3) data = { 'text': 'Aqui está o calendário de matrícula. ' 'Nele você pode adquirir informações de datas sobre: ' @@ -27,7 +25,11 @@ def run(self, dispatcher, tracker, domain): 'pré-matrícula, ajuste...', 'image': f'{crawlerRegister}/registration/downloadPdf' } - dispatcher.utter_response(data) + dispatcher.utter_template("utter_image", + tracker, + False, + text=data.get('text'), + image=data.get('image')) except Exception as exception: dispatcher.utter_message( "Tive um problema ao pegar o calendário acadêmico pra você... " diff --git a/rasa/actions/course_period_proof.py b/rasa/actions/course_period_proof.py new file mode 100644 index 0000000..272dccd --- /dev/null +++ b/rasa/actions/course_period_proof.py @@ -0,0 +1,66 @@ +from rasa_core.actions.action import Action +import time +import datetime + +DOC_1 = 'login/index.html?response_type=code&' +DOC_2 = 'client_id=102&redirect_uri=/documentodigital/index.html' +UNB_URL = f'https://servicos.unb.br/dados/{DOC_1}{DOC_2}' +GIT_URL = 'https://raw.githubusercontent.com/BotLino/Lino/' +IMGS_PATH = '3_documentos_academicos/rasa/images/CoursePeriodProof/' + + +class ActionCoursePeriodProof(Action): + def name(self): + return "action_course_period_proof" + + def run(self, dispatcher, tracker, domain): + messages = [] + welcome_1 = 'Para conseguir o sua declaração de período de curso ' + welcome_2 = 'você deve acessar este link:' + + messages.append('Só um segundo, to buscando aqui...') + messages.append(f'{welcome_1}{welcome_2}') + messages.append(UNB_URL) + + for message in messages: + dispatcher.utter_message(message) + + # Free cache images + timestamp = datetime.datetime.now().strftime("%d-%m-%Y") + free_cache_url = f'?time={timestamp}' + + # typing + time.sleep(0.5) + + steps = [] + + # Step 1 + step_1_1 = 'Faça login no site' + step_1_2 = 'selecione Declaração Período de Curso' + step_1 = { + 'text': f'Passo 1: {step_1_1} e {step_1_2}', + 'image': f'{GIT_URL}{IMGS_PATH}step2.png{free_cache_url}' + } + steps.append(step_1) + + # Step 2 + step_2_1 = 'Prove que você está ciente do que está fazendo' + step_2_2 = 'Clique em emitir' + step_2 = { + 'text': f'Passo 2: {step_2_1} e {step_2_2}', + 'image': f'{GIT_URL}{IMGS_PATH}step4.png{free_cache_url}' + } + steps.append(step_2) + + # Step 3 + step_3 = { + 'text': 'Passo 3: Agora é so baixar' + } + steps.append(step_3) + + for step in steps: + dispatcher.utter_response(step) + + dispatcher.utter_message(';)') + + return [] diff --git a/rasa/actions/menu/daily_breakfast.py b/rasa/actions/daily_breakfast.py similarity index 98% rename from rasa/actions/menu/daily_breakfast.py rename to rasa/actions/daily_breakfast.py index 981dbd8..c9e9e8c 100644 --- a/rasa/actions/menu/daily_breakfast.py +++ b/rasa/actions/daily_breakfast.py @@ -2,7 +2,7 @@ import os import time import logging -from rasa_core.actions.action import Action +from rasa_core_sdk import Action ACCESS_TOKEN = os.getenv('TELEGRAM_ACCESS_TOKEN', '') API_URL = 'https://api.telegram.org' diff --git a/rasa/actions/menu/daily_dinner.py b/rasa/actions/daily_dinner.py similarity index 98% rename from rasa/actions/menu/daily_dinner.py rename to rasa/actions/daily_dinner.py index 879ea66..c93c621 100644 --- a/rasa/actions/menu/daily_dinner.py +++ b/rasa/actions/daily_dinner.py @@ -2,7 +2,7 @@ import os import time import logging -from rasa_core.actions.action import Action +from rasa_core_sdk import Action ACCESS_TOKEN = os.getenv('TELEGRAM_ACCESS_TOKEN', '') API_URL = 'https://api.telegram.org' diff --git a/rasa/actions/menu/daily_lunch.py b/rasa/actions/daily_lunch.py similarity index 98% rename from rasa/actions/menu/daily_lunch.py rename to rasa/actions/daily_lunch.py index f187356..6b72520 100644 --- a/rasa/actions/menu/daily_lunch.py +++ b/rasa/actions/daily_lunch.py @@ -2,7 +2,7 @@ import os import time import logging -from rasa_core.actions.action import Action +from rasa_core_sdk import Action ACCESS_TOKEN = os.getenv('TELEGRAM_ACCESS_TOKEN', '') API_URL = 'https://api.telegram.org' diff --git a/rasa/actions/menu/daily_menu.py b/rasa/actions/daily_menu.py similarity index 97% rename from rasa/actions/menu/daily_menu.py rename to rasa/actions/daily_menu.py index c9ad41f..7d3aded 100644 --- a/rasa/actions/menu/daily_menu.py +++ b/rasa/actions/daily_menu.py @@ -1,6 +1,6 @@ import requests import time -from rasa_core.actions.action import Action +from rasa_core_sdk import Action import logging diff --git a/rasa/actions/notifications/register_notification.py b/rasa/actions/register_notification.py similarity index 99% rename from rasa/actions/notifications/register_notification.py rename to rasa/actions/register_notification.py index a12a2a4..ffb269b 100644 --- a/rasa/actions/notifications/register_notification.py +++ b/rasa/actions/register_notification.py @@ -2,7 +2,7 @@ import requests import json from pymongo import MongoClient -from rasa_core.actions.action import Action +from rasa_core_sdk import Action # If you want to use your own bot to development add the bot token as # second parameters diff --git a/rasa/actions/documents/register_proof.py b/rasa/actions/register_proof.py similarity index 83% rename from rasa/actions/documents/register_proof.py rename to rasa/actions/register_proof.py index cdd61f4..72815c1 100644 --- a/rasa/actions/documents/register_proof.py +++ b/rasa/actions/register_proof.py @@ -1,4 +1,4 @@ -from rasa_core.actions.action import Action +from rasa_core_sdk import Action import time import datetime @@ -6,7 +6,7 @@ DOC_2 = 'client_id=102&redirect_uri=/documentodigital/index.html' UNB_URL = f'https://servicos.unb.br/dados/{DOC_1}{DOC_2}' GIT_URL = 'https://raw.githubusercontent.com/fga-eps-mds/2018.2-Lino/' -# IMGS_PATH = 'Issue_203-RegisterProof/rasa/images/RegisterProof/' +IMGS_PATH = 'Issue_203-RegisterProof/rasa/images/RegisterProof/' IMGS_PATH = 'master/rasa/images/RegisterProof/' @@ -60,7 +60,11 @@ def run(self, dispatcher, tracker, domain): steps.append(step_3) for step in steps: - dispatcher.utter_response(step) + dispatcher.utter_template("utter_image", + tracker, + False, + text=step.get('text'), + image=step.get('image')) dispatcher.utter_message(';)') diff --git a/rasa/actions/documents/regular_proof.py b/rasa/actions/regular_proof.py similarity index 86% rename from rasa/actions/documents/regular_proof.py rename to rasa/actions/regular_proof.py index e68a26d..e61a70f 100644 --- a/rasa/actions/documents/regular_proof.py +++ b/rasa/actions/regular_proof.py @@ -1,4 +1,4 @@ -from rasa_core.actions.action import Action +from rasa_core_sdk import Action import time import datetime @@ -60,7 +60,11 @@ def run(self, dispatcher, tracker, domain): steps.append(step_3) for step in steps: - dispatcher.utter_response(step) + dispatcher.utter_template("utter_image", + tracker, + False, + text=step.get('text'), + image=step.get('image')) dispatcher.utter_message(';)') diff --git a/rasa/actions/documents/schedule.py b/rasa/actions/schedule.py similarity index 83% rename from rasa/actions/documents/schedule.py rename to rasa/actions/schedule.py index dda2f7c..43c5e53 100644 --- a/rasa/actions/documents/schedule.py +++ b/rasa/actions/schedule.py @@ -1,4 +1,4 @@ -from rasa_core.actions.action import Action +from rasa_core_sdk import Action import time import datetime @@ -58,8 +58,12 @@ def run(self, dispatcher, tracker, domain): steps.append(step_3) for step in steps: - dispatcher.utter_response(step) + dispatcher.utter_template("utter_image", + tracker, + False, + text=step.get('text'), + image=step.get('image')) - dispatcher.utter_message(';)') + dispatcher.utter_message(';)') return [] diff --git a/rasa/actions/school_history_proof.py b/rasa/actions/school_history_proof.py new file mode 100644 index 0000000..df3564d --- /dev/null +++ b/rasa/actions/school_history_proof.py @@ -0,0 +1,66 @@ +from rasa_core.actions.action import Action +import time +import datetime + +DOC_1 = 'login/index.html?response_type=code&' +DOC_2 = 'client_id=102&redirect_uri=/documentodigital/index.html' +UNB_URL = f'https://servicos.unb.br/dados/{DOC_1}{DOC_2}' +GIT_URL = 'https://raw.githubusercontent.com/BotLino/Lino/' +IMGS_PATH = '3_documentos_academicos/rasa/images/SchoolHistoryProof/' + + +class ActionSchoolHistoryProof(Action): + def name(self): + return "action_school_history_proof" + + def run(self, dispatcher, tracker, domain): + messages = [] + welcome_1 = 'Para conseguir o seu histórico escolar ' + welcome_2 = 'você deve acessar este link:' + + messages.append('Só um segundo, to buscando aqui...') + messages.append(f'{welcome_1}{welcome_2}') + messages.append(UNB_URL) + + for message in messages: + dispatcher.utter_message(message) + + # Free cache images + timestamp = datetime.datetime.now().strftime("%d-%m-%Y") + free_cache_url = f'?time={timestamp}' + + # typing + time.sleep(0.5) + + steps = [] + + # Step 1 + step_1_1 = 'Faça login no site' + step_1_2 = 'selecione Histórico Escolar' + step_1 = { + 'text': f'Passo 1: {step_1_1} e {step_1_2}', + 'image': f'{GIT_URL}{IMGS_PATH}step2.png{free_cache_url}' + } + steps.append(step_1) + + # Step 2 + step_2_1 = 'Prove que você está ciente do que está fazendo' + step_2_2 = 'Clique em emitir' + step_2 = { + 'text': f'Passo 2: {step_2_1} e {step_2_2}', + 'image': f'{GIT_URL}{IMGS_PATH}step4.png{free_cache_url}' + } + steps.append(step_2) + + # Step 3 + step_3 = { + 'text': 'Passo 3: Agora é so baixar' + } + steps.append(step_3) + + for step in steps: + dispatcher.utter_response(step) + + dispatcher.utter_message(';)') + + return [] diff --git a/rasa/actions/notifications/see_notifications.py b/rasa/actions/see_notifications.py similarity index 98% rename from rasa/actions/notifications/see_notifications.py rename to rasa/actions/see_notifications.py index 15223b1..a5af531 100644 --- a/rasa/actions/notifications/see_notifications.py +++ b/rasa/actions/see_notifications.py @@ -2,7 +2,7 @@ import requests import json from pymongo import MongoClient -from rasa_core.actions.action import Action +from rasa_core_sdk import Action # If you want to use your own bot to development add the bot token as # second parameters diff --git a/rasa/actions/notifications/start.py b/rasa/actions/start.py similarity index 99% rename from rasa/actions/notifications/start.py rename to rasa/actions/start.py index ffcf768..dca25be 100644 --- a/rasa/actions/notifications/start.py +++ b/rasa/actions/start.py @@ -2,7 +2,7 @@ import os import logging from pymongo import MongoClient -from rasa_core.actions.action import Action +from rasa_core_sdk import Action from time import sleep # If you want to use your own bot to development add the bot token as diff --git a/rasa/actions/notifications/trigger_notification.py b/rasa/actions/trigger_notification.py similarity index 91% rename from rasa/actions/notifications/trigger_notification.py rename to rasa/actions/trigger_notification.py index 7738362..6484d81 100644 --- a/rasa/actions/notifications/trigger_notification.py +++ b/rasa/actions/trigger_notification.py @@ -1,5 +1,5 @@ -from rasa_core.actions.action import Action -from rasa_core.events import UserUttered +from rasa_core_sdk import Action +from rasa_core_sdk.events import UserUttered class ActionTriggerNotification(Action): diff --git a/rasa/actions/tutoring_proof.py b/rasa/actions/tutoring_proof.py new file mode 100644 index 0000000..3999563 --- /dev/null +++ b/rasa/actions/tutoring_proof.py @@ -0,0 +1,66 @@ +from rasa_core.actions.action import Action +import time +import datetime + +DOC_1 = 'login/index.html?response_type=code&' +DOC_2 = 'client_id=102&redirect_uri=/documentodigital/index.html' +UNB_URL = f'https://servicos.unb.br/dados/{DOC_1}{DOC_2}' +GIT_URL = 'https://raw.githubusercontent.com/BotLino/Lino/' +IMGS_PATH = '3_documentos_academicos/rasa/images/TutoringProof/' + + +class ActionTutoringProof(Action): + def name(self): + return "action_tutoring_proof" + + def run(self, dispatcher, tracker, domain): + messages = [] + welcome_1 = 'Para conseguir o sua declaração de monitoria ' + welcome_2 = 'você deve acessar este link:' + + messages.append('Só um segundo, to buscando aqui...') + messages.append(f'{welcome_1}{welcome_2}') + messages.append(UNB_URL) + + for message in messages: + dispatcher.utter_message(message) + + # Free cache images + timestamp = datetime.datetime.now().strftime("%d-%m-%Y") + free_cache_url = f'?time={timestamp}' + + # typing + time.sleep(0.5) + + steps = [] + + # Step 1 + step_1_1 = 'Faça login no site' + step_1_2 = 'selecione Declaração de Monitoria' + step_1 = { + 'text': f'Passo 1: {step_1_1} e {step_1_2}', + 'image': f'{GIT_URL}{IMGS_PATH}step2.png{free_cache_url}' + } + steps.append(step_1) + + # Step 2 + step_2_1 = 'Prove que você está ciente do que está fazendo' + step_2_2 = 'Clique em emitir' + step_2 = { + 'text': f'Passo 2: {step_2_1} e {step_2_2}', + 'image': f'{GIT_URL}{IMGS_PATH}step4.png{free_cache_url}' + } + steps.append(step_2) + + # Step 3 + step_3 = { + 'text': 'Passo 3: Agora é so baixar' + } + steps.append(step_3) + + for step in steps: + dispatcher.utter_response(step) + + dispatcher.utter_message(';)') + + return [] diff --git a/rasa/actions/notifications/unregister_notification.py b/rasa/actions/unregister_notification.py similarity index 99% rename from rasa/actions/notifications/unregister_notification.py rename to rasa/actions/unregister_notification.py index f0a20ab..fbb56e8 100644 --- a/rasa/actions/notifications/unregister_notification.py +++ b/rasa/actions/unregister_notification.py @@ -2,7 +2,7 @@ import requests import json from pymongo import MongoClient -from rasa_core.actions.action import Action +from rasa_core_sdk import Action # If you want to use your own bot to development add the bot token as # second parameters diff --git a/rasa/actions/menu/week_menu.py b/rasa/actions/week_menu.py similarity index 77% rename from rasa/actions/menu/week_menu.py rename to rasa/actions/week_menu.py index 8788e6c..a28048f 100644 --- a/rasa/actions/menu/week_menu.py +++ b/rasa/actions/week_menu.py @@ -1,5 +1,5 @@ import datetime -from rasa_core.actions.action import Action +from rasa_core_sdk import Action import requests @@ -24,7 +24,11 @@ def run(self, dispatcher, tracker, domain): 'Aprecie com moderação :)', 'image': f'{crawler_url}{img_path}{img_timestamp}' } - dispatcher.utter_response(data) + dispatcher.utter_template("utter_image", + tracker, + False, + text=data.get('text'), + image=data.get('image')) except Exception as exceptions: dispatcher.utter_message( "Não consegui pegar o cardápio da semana... " diff --git a/rasa/credentials.yml b/rasa/credentials.yml index f2b4228..af15639 100644 --- a/rasa/credentials.yml +++ b/rasa/credentials.yml @@ -1,3 +1,4 @@ -access_token: ${ACCESS_TOKEN} -verify: ${VERIFY} -webhook_url: ${WEBHOOK_URL} \ No newline at end of file +telegram: + access_token: "445036585:AAFYeGa-B8dfjr4REXyosH2avrBkZxqb5pE" + verify: "TesteFgaBot" + webhook_url: "https://91237afa.ngrok.io/webhooks/telegram/webhook" diff --git a/rasa/data/intents/calendar.md b/rasa/data/intents/calendar.md index f963138..9b8df69 100644 --- a/rasa/data/intents/calendar.md +++ b/rasa/data/intents/calendar.md @@ -32,7 +32,6 @@ - manda o [calendario de matrícula](calendar) - cade o [calendario de matrícula](calendar) - passa o [calendario de matrícula](calendar) -- Lino, [calendario de matrícula](calendar) - Trancamento de [matrícula](calendar) - [trancamento](calendar) @@ -218,4 +217,4 @@ - data da [matricula orientada](calendar) - onde vejo o dia da [matricula orientada](calendar) - dia da [matricula orientada](calendar) -- até quando é a [matricula orientada](calendar) \ No newline at end of file +- até quando é a [matricula orientada](calendar) diff --git a/rasa/data/intents/compliments.md b/rasa/data/intents/compliments.md index 9ffc2e7..d1d2d0f 100644 --- a/rasa/data/intents/compliments.md +++ b/rasa/data/intents/compliments.md @@ -33,8 +33,7 @@ - lindo - lindao - maravilhoso -- top - gato - gado - topzera -- top \ No newline at end of file +- top diff --git a/rasa/data/intents/documents.md b/rasa/data/intents/documents.md index ac81ebc..e49406b 100644 --- a/rasa/data/intents/documents.md +++ b/rasa/data/intents/documents.md @@ -40,14 +40,11 @@ - meia entrada ## intent:asks_about_schedule -- [grade horaria](documents) - me diz como arranjo minha grade horária - eae bot, grade horária - me manda ai como pegar meus horários - [grade horaria](documents) - [grade horária](documents) -- [Grade horaria](documents) -- [Grade horária](documents) - me diz ai, como faço pra pegar a [grade horaria](documents) - eae bot, [grade horaria](documents) - [grade horaria](documents), pfvr @@ -56,7 +53,6 @@ - preciso da [grade horaria](documents) - preciso da [grade horaria](documents), como faz - preciso da [grade horaria](documents), como arranjo? -- meu plano de saúde tá acabando e preciso da [grade horária](documents) desse semestre. como procedo? - [grade horária](documents)?? - me diz ai, como faço pra pegar a [grade horária](documents) - eae bot, [grade horária](documents) @@ -67,19 +63,11 @@ - preciso da [grade horária](documents), como faz - preciso da [grade horária](documents), como arranjo? - meu plano de saúde tá acabando e preciso da [grade horária](documents) desse semestre. como procedo? -- [grade horária](documents)?? ## intent:asks_register_proof -- Como pegar o [comprovante de matrícula](documents)? - como pegar o [comprovante de matrícula](documents)? -- [Comprovante de matrícula](documents) - [comprovante de matrícula](documents) -- [Comprovante de matricula](documents) - [comprovante de matricula](documents) -- [Comprovante de Matrícula](documents) -- [comprovante de Matrícula](documents) -- [Comprovante de Matricula](documents) -- [comprovante de Matricula](documents) - Eae, como pego que pego o [comprovante de matrícula](documents)? - oi Lino, como que faço pra retirar o [comprovante de matricula](documents)? - fala bixo, me manda ae como arranja o [comprovante de matricula](documents) @@ -87,5 +75,48 @@ - eaeee, [comprovante de matrícula](documents) - [comprov de matr](documents) - [comprovante de matricual](documents), cara -- [comprovante de matricula](documents), cara - bot, [comprovante de matricula](documents) + +## intent:asks_tutoring_proof +- como pegar o [declaração de monitoria](documents)? +- [declaracao de monitoria](documents) +- [declaração de monitoria](documents) +- Eae, como pego que pego o [declaração de monitoria](documents)? +- oi Lino, como que faço pra retirar o [declaracao de monitoria](documents)? +- fala bixo, me manda ae como arranja o [declaração de monitoria](documents) +- opa mano, me diz sobre o [desclar de monit](documents) +- eaeee, [desclaração de monitoria](documents) +- [declar de monit](documents) +- [declaração de monitoira](documents), cara +- [declaração de monitoria](documents), cara +- bot, [declaração de monitoria](documents) + +## intent:asks_course_period_proof +- Como pegar o [declaração de período de curso](documents)? +- como pegar o [declaração de periodo de curso](documents)? +- [declaracao de periodo de curso](documents) +- [declaracao de monitoria](documents) +- [Declaração de periodo de curso](documents) +- Eae, como pego que pego o [Declaração de período de curso](documents)? +- oi Lino, como que faço pra retirar o [declaracao de período de curso](documents)? +- fala bixo, me manda ae como arranja o [declaração de período de curso](documents) +- opa mano, me diz sobre o [desclar de period curso](documents) +- eaeee, [desclaração de período de curso](documents) +- [declar de per curs](documents) +- [declaração de período](documents), cara +- [declaração de período de curso](documents), cara +- bot, [declaração de período de curso](documents) + +## intent:asks_school_history_proof +- Como pegar o [histórico escolar](documents)? +- como pegar o [historico escolar](documents)? +- [histórico escolar](documents) +- [historico escolar](documents) +- Eae, como pego que pego o [histórico escolar](documents)? +- oi Lino, como que faço pra retirar o [histórico escolar](documents)? +- fala bixo, me manda ae como arranja o [historico escolar](documents) +- opa mano, me diz sobre o [hist escolar](documents) +- eaeee, [historcio escolar](documents) +- [hist escl](documents) +- [histórico escolar](documents), cara +- bot, [histórico escolar](documents) diff --git a/rasa/data/intents/general.md b/rasa/data/intents/general.md index c550df2..0f26c5d 100644 --- a/rasa/data/intents/general.md +++ b/rasa/data/intents/general.md @@ -22,7 +22,6 @@ - [/help](command) ## intent:greet -- [Oi](oi) - [oi](oi) - [oi](oi) amigo - [Olá](oi) diff --git a/rasa/data/intents/menu.md b/rasa/data/intents/menu.md index 525880e..5b342a7 100644 --- a/rasa/data/intents/menu.md +++ b/rasa/data/intents/menu.md @@ -40,8 +40,7 @@ - então, o que tem pra comer [hoje](period)? ## intent: asks_weekly_menu -- Me fala o cardápio de [semana](period) -- Me fala o cardápio de [semana](period) +- Me fala o cardápio da [semana](period) - O que tem pra comer [semana](period) - Qual é o cardápio de [semana](period) - Me passa o cardápio de [semana](period) @@ -89,7 +88,6 @@ ## intent: asks_lunch_menu - Me fala o cardápio do [almoço](meal) -- Me fala o cardápio do [almoço](meal) - O que tem pra comer no [almoço](meal) - Qual é o cardápio do [almoço](meal) - Me passa o cardápio do [almoço](meal) @@ -113,7 +111,6 @@ ## intent: asks_breakfast_menu - Me fala o cardápio do [café da manhã](meal) -- Me fala o cardápio do [café da manhã](meal) - O que tem pra comer no [café da manhã](meal) - Qual é o cardápio do [café da manhã](meal) - Me passa o cardápio do [café da manhã](meal) @@ -134,7 +131,6 @@ - então, o que tem pra comer no [café da manhã](meal)? - Me fala o cardápio do [café](meal) -- Me fala o cardápio do [café](meal) - O que tem pra comer no [café](meal) - Qual é o cardápio do [café](meal) - Me passa o cardápio do [café](meal) @@ -155,7 +151,6 @@ - então, o que tem pra comer no [café](meal)? - Me fala o cardápio do [cafe da manha](meal) -- Me fala o cardápio do [cafe da manha](meal) - O que tem pra comer no [cafe da manha](meal) - Qual é o cardápio do [cafe da manha](meal) - Me passa o cardápio do [cafe da manha](meal) @@ -176,7 +171,6 @@ - então, o que tem pra comer no [cafe da manha](meal)? - Me fala o cardápio do [cafe](meal) -- Me fala o cardápio do [cafe](meal) - O que tem pra comer no [cafe](meal) - Qual é o cardápio do [cafe](meal) - Me passa o cardápio do [cafe](meal) @@ -197,7 +191,6 @@ - então, o que tem pra comer no [cafe](meal)? - Me fala o cardápio do [desjejum](meal) -- Me fala o cardápio do [desjejum](meal) - O que tem pra comer no [desjejum](meal) - Qual é o cardápio do [desjejum](meal) - Me passa o cardápio do [desjejum](meal) diff --git a/rasa/data/intents/notifications.md b/rasa/data/intents/notifications.md index 2f1407f..7c719c3 100644 --- a/rasa/data/intents/notifications.md +++ b/rasa/data/intents/notifications.md @@ -55,7 +55,6 @@ - Me cadastra pra receber alerta da comunidade - Quero receber sobre alerta da comunidade - notificações alerta da comunidade -- alerta da comunidade - alerta da comunidade pretty please - quero me cadastrar pra lista de notificações do alerta da comunidade - me inscreve pra receber o alerta da comunidade por favor @@ -97,13 +96,13 @@ - [não](option) quero receber mais [notificação](notification) - [nao](option) quero receber mais [notificaçao](notification) - [não](option) quero receber mais [notificações](notification) -- [não](option) quero receber mais [notificações](notification) +- [não](option) quero receber mais [notificaçoes](notification) - [não](option) quero [notificação](notification) - [não](option) quero [notificações](notification) - [sem](option) [notificação](notification) - [sem](option) [notificaçao](notification) - [sem](option) [notificações](notification) -- [sem](option) [notificações](notification) +- [sem](option) [notificaçoes](notification) - [quero tirar](option) as [notificações](notification) - [quero tirar](option) as [notificaçoes](notification) - [quero tirar](option) a [notificação](notification) diff --git a/rasa/data/intents/random.md b/rasa/data/intents/random.md index e2bb480..af9deed 100644 --- a/rasa/data/intents/random.md +++ b/rasa/data/intents/random.md @@ -237,7 +237,6 @@ ## intent:sons - Você tem [filhos](sons)? - [filhos](sons)? -- Você tem [filhos](sons)? - [filho](sons) - [filha](sons) - [filhas](sons)? @@ -315,4 +314,4 @@ - pala - chorei de ri - ri -- rachei \ No newline at end of file +- rachei diff --git a/rasa/data/stories/main.md b/rasa/data/stories/main.md index 58c2226..1761350 100644 --- a/rasa/data/stories/main.md +++ b/rasa/data/stories/main.md @@ -39,6 +39,18 @@ * asks_register_proof{"documents": "Comprovante de matrícula", "documents": "comprovante de matrícula", "documents": "Comprovante de matricula", "documents": "Comprovante de Matrícula", "documents": "comprovante de Matrícula", "documents": "Comprovante de Matricula", "documents": "comprovante de Matricula"} - action_register_proof +## path_asks_tutoring_proof +* asks_tutoring_proof{"documents": "Declaração de monitoria", "documents": "declaração de monitoria", "documents": "Declaracao de monitoria", "documents": "Declaração de Monitoria", "documents": "declaração de Monitoria", "documents": "declaraçao de monitoria", "documents": "declaracao de Monitoria"} + - action_tutoring_proof + +## path_asks_course_period_proof +* asks_course_period_proof{"documents": "Declaração de período de curso", "documents": "declaração de periodo de curso", "documents": "Declaracao de periodo de curso", "documents": "Declaração de Período de Curso", "documents": "declaração de periodo de curso", "documents": "declaraçao de periodo de curso", "documents": "declaração de período de curso"} + - action_course_period_proof + +## path_asks_school_history_proof +* asks_school_history_proof{"documents": "Histórico escolar", "documents": "histórico escolar", "documents": "Histórico Escolar", "documents": "Historico Escolar", "documents": "historico escolar", "documents": "Historico escolar", "documents": "historico Escolar"} + - action_school_history_proof + ## path_asks_schedule * asks_about_schedule{"documents": "grade horaria", "documents": "grade horária"} - action_schedule diff --git a/rasa/domain.yml b/rasa/domain.yml index ad82cfa..4f9bbc2 100644 --- a/rasa/domain.yml +++ b/rasa/domain.yml @@ -23,6 +23,8 @@ intents: - asks_about_schedule - asks_register_proof - asks_regular_proof + - asks_tutoring_proof + - asks_course_period_proof - asks_about_gmail @@ -151,34 +153,37 @@ actions: - utter_compliments_reply - utter_start - utter_menu - - actions.menu.daily_menu.ActionDailyMenu - - actions.menu.daily_dinner.ActionDailyDinner - - actions.menu.daily_lunch.ActionDailyLunch - - actions.menu.daily_breakfast.ActionDailyBreakfast - - actions.menu.week_menu.ActionSendWeekMenu + - action_daily_menu + - action_daily_dinner + - action_daily_lunch + - action_daily_breakfast + - action_send_week_menu - utter_operation_type - utter_register_notifications - utter_unregister_notifications - - actions.notifications.start.ActionStart - - actions.notifications.register_notification.ActionRegisterNotification - - actions.notifications.see_notifications.ActionListNotifications - - actions.notifications.unregister_notification.ActionUnregisterNotification - - actions.notifications.buttons_notification.ActionButtonsNotification - - actions.notifications.buttons_notification.ActionButtonsNotificationTypes - - actions.notifications.trigger_notification.ActionTriggerNotification - - actions.notifications.trigger_notification.ActionTriggerUnregisterNotification + - custom_start + - action_register_notification + - action_list_notifications + - action_unregister_notification + - action_buttons_notification + - action_show_notifications_types + - action_another_notification + - action_trigger_unregister_notification - utter_documents - - actions.documents.regular_proof.ActionRegularProof - - actions.documents.schedule.ActionSchedule - - actions.documents.register_proof.ActionRegisterProof + - action_regular_proof + - action_schedule + - action_register_proof + - action_tutoring_proof + - action_course_period_proof + - action_school_history_proof - utter_finish_notification - utter_finish_unregister_notification - utter_thanks - utter_offenses - - actions.calendar.ActionCalendar + - action_calendar - utter_religion - utter_sport @@ -234,10 +239,10 @@ templates: utter_start: - text: | - Oi, eu sou o Lino! - + Oi, eu sou o Lino! + Tô aqui pra facilitar algumas informações pra você, tipo: - + - Documentos acadêmicos - Cardápio do RU - Alertas da comunidade @@ -259,9 +264,17 @@ templates: utter_documents: - text: | - Vish pessoa, agora não rola - Não me ensinaram ainda, mas logo logo tô manjando! + Oi, posso ajudar você a conseguir seguintes documentos: + + - Comprovante de Matrícula + - Declaração de Aluno Regular + - Declaração de Grade Horária + - Declaração de Monitoria + - Declaração de Período de Curso + - Histórico Escolar + + Qualquer dúvida é só digitar /help. utter_operation_type: - text: | @@ -316,7 +329,7 @@ templates: Flwss! Até mais!!! - + - text: | Tchau, bb. @@ -355,7 +368,7 @@ templates: utter_offenses: - text: | - Ao invés de me xingar, você podia aproveitar minhas funcionalidades. O que acha?! + Ao invés de me xingar, você podia aproveitar minhas funcionalidades. O que acha?! Digita um /help ai que eu te mostro o que posso te ajudar. @@ -370,45 +383,45 @@ templates: Eu sou um bot tão legal, pra que essa agressividade!? Vamos lá, me diz com um pouco mais de carinho em que posso ajudar... =) - + utter_help: - text: | Eu posso te ajudar com algumas funcionalidades: Notificações: - + As notificações vão facilitar a sua vida em relação a mim. Você poderá autorizar a notificação do cardápio do RU, tanto para o café da manhã, almoço e jantar para receber diariamente ou em um horário predefenido. - + Você também pode optar por receber alertas da comunidade, que são avisos que professores e servidores costumam enviar pra geral. - - - Eu consigo entender quando me diz algo sobre "notificações" e assim darei todas as alternativas de notificações (remover, adicionar e visualizar). + + - Eu consigo entender quando me diz algo sobre "notificações" e assim darei todas as alternativas de notificações (remover, adicionar e visualizar). Cardápio do RU: - + Sobre o cardápio do RU eu consigo te falar sobre as refeições do dia ou da semana, pode pedir também cada uma "do dia" separadaramente. - + - Envie uma mensagem pedindo sobre o "Cardápio do RU" e você poderá escolher entre o "do dia" e suas refeições, "café da manhã, almoço ou jantar", ou então o cardápio completo "da semana". Documentos acadêmicos: - + Nessa funcionalidade eu consigo te ajudar a encontrar e baixar os documentos (Declaração de aluno regular, comprovante de matrícula e grade horária), que são disponibilizados pela UnB no Matricula Web. - - - Basta me falar qual documento está procurando dos listados acima que eu te envio um tutorial para acessar o Matricula Web e como consegue baixá-los. + + - Basta me falar qual documento está procurando dos listados acima que eu te envio um tutorial para acessar o Matricula Web e como consegue baixá-los. Calendário de Matrícula: - + No calendário você vai conseguir encontrar as datas mais relevantes das atividades acadêmicas relacionadas a matrículas do semestre atual. Tipo: início e término das aulas, início das matrículas no Matrícula Web, matrícula orientada, ajuste de matrícula, lista de espera, reserva de vagas e trancamentos. - + - Se você disser "Calendário de matrícula", eu te envio a foto que eu consegui no SAA que tem todas essas informações. utter_religion: - text: | Eu infleizmente não sei acreditar - + Só sei o que sei - + E nada mais - text: | @@ -428,12 +441,12 @@ templates: utter_sport: - text: | Eu amo jogar futebol - + Eu que ensinei o Pele a jogar bola haha - text: | Falam que todo ser humano nasce Botafoguense - + Com os Bots não é diferente utter_team: @@ -446,7 +459,7 @@ templates: utter_languages: - text: | Poderíamos falar de algo melhor - + Não é mesmo, $user ?! kkk - text: | E isso lá é linguagem de programação!? kkk @@ -454,11 +467,11 @@ templates: utter_genre: - text: | Eu não tenho sexo, sou como um anjo - + Um ser assexuado - + Muito além da sua forma de existência - + - text: | Eu sou um robô, tire suas próprias conclusões... @@ -493,7 +506,7 @@ templates: É pra já!!! Tenho uma enxada, uma pá e uma foice. - + Quantas ferramentas eu tenho? ... @@ -508,12 +521,12 @@ templates: utter_license: - text: | Sou um software livre - + licenciado com a MIT =) - text: | Tenho uma licença MIT - + Mas também gosto muito das outras licenças opensource =) - text: | @@ -522,39 +535,39 @@ templates: utter_where_u_liv: - text: | Eu estou em um lugar legal - + Difícil de explicar para humanos como você $user. - text: | Estou morando em um chip de memória RAM - + Mas é temporário - + Só até conseguir achar uma memória cache... - text: | Eu moro em um repositório no github - + Você pode passar lá pra me visitar qualquer dia - + Chega aí: https://github.com/fga-eps-mds/2018.2-Lino utter_how_am_i: - text: | Eu não tenho um corpo físico - + Sou feito da mais bela e pura lógica algoritimica. - text: | Eu posso ser como você quiser - + Basta me desenhar Mas capricha, hein!? ;) - text: | Sou duro e frio por fora - + Mas tenho um coração quentinho utter_good_night: @@ -593,7 +606,7 @@ templates: Obrigado por perguntar *-* - - text: | + - text: | Tá tudo joia! Valeu por perguntar =] @@ -662,7 +675,7 @@ templates: utter_where_r_u_from: - text: | - Venho das profundezas + Venho das profundezas Das terras vermelhas @@ -789,11 +802,15 @@ templates: utter_laugh: - text: | - Hahahaha... + Hahahaha... Engraçadinho - text: | kkkkkkkkkk - Você está feliz hoje, hein!? \ No newline at end of file + Você está feliz hoje, hein!? + + utter_image: + - text: "{text}:" + image: "{image}" diff --git a/rasa/endpoints.yml b/rasa/endpoints.yml new file mode 100644 index 0000000..677f173 --- /dev/null +++ b/rasa/endpoints.yml @@ -0,0 +1,2 @@ +action_endpoint: + url: "http://actions:5055/webhook" diff --git a/rasa/images/CoursePeriodProof/step1.png b/rasa/images/CoursePeriodProof/step1.png new file mode 100644 index 0000000..21228ec Binary files /dev/null and b/rasa/images/CoursePeriodProof/step1.png differ diff --git a/rasa/images/CoursePeriodProof/step2.png b/rasa/images/CoursePeriodProof/step2.png new file mode 100644 index 0000000..dbe6484 Binary files /dev/null and b/rasa/images/CoursePeriodProof/step2.png differ diff --git a/rasa/images/CoursePeriodProof/step3.png b/rasa/images/CoursePeriodProof/step3.png new file mode 100644 index 0000000..aa14f4b Binary files /dev/null and b/rasa/images/CoursePeriodProof/step3.png differ diff --git a/rasa/images/CoursePeriodProof/step4.png b/rasa/images/CoursePeriodProof/step4.png new file mode 100644 index 0000000..b2ba1d1 Binary files /dev/null and b/rasa/images/CoursePeriodProof/step4.png differ diff --git a/rasa/images/CoursePeriodProof/step5.png b/rasa/images/CoursePeriodProof/step5.png new file mode 100644 index 0000000..5d1f5cf Binary files /dev/null and b/rasa/images/CoursePeriodProof/step5.png differ diff --git a/rasa/images/SchoolHistoryProof/step1.png b/rasa/images/SchoolHistoryProof/step1.png new file mode 100644 index 0000000..21228ec Binary files /dev/null and b/rasa/images/SchoolHistoryProof/step1.png differ diff --git a/rasa/images/SchoolHistoryProof/step2.png b/rasa/images/SchoolHistoryProof/step2.png new file mode 100644 index 0000000..dead329 Binary files /dev/null and b/rasa/images/SchoolHistoryProof/step2.png differ diff --git a/rasa/images/SchoolHistoryProof/step3.png b/rasa/images/SchoolHistoryProof/step3.png new file mode 100644 index 0000000..aa14f4b Binary files /dev/null and b/rasa/images/SchoolHistoryProof/step3.png differ diff --git a/rasa/images/SchoolHistoryProof/step4.png b/rasa/images/SchoolHistoryProof/step4.png new file mode 100644 index 0000000..b2ba1d1 Binary files /dev/null and b/rasa/images/SchoolHistoryProof/step4.png differ diff --git a/rasa/images/SchoolHistoryProof/step5.png b/rasa/images/SchoolHistoryProof/step5.png new file mode 100644 index 0000000..4c085ba Binary files /dev/null and b/rasa/images/SchoolHistoryProof/step5.png differ diff --git a/rasa/images/TutoringProof/step1.png b/rasa/images/TutoringProof/step1.png new file mode 100644 index 0000000..21228ec Binary files /dev/null and b/rasa/images/TutoringProof/step1.png differ diff --git a/rasa/images/TutoringProof/step2.png b/rasa/images/TutoringProof/step2.png new file mode 100644 index 0000000..d6dc621 Binary files /dev/null and b/rasa/images/TutoringProof/step2.png differ diff --git a/rasa/images/TutoringProof/step3.png b/rasa/images/TutoringProof/step3.png new file mode 100644 index 0000000..aa14f4b Binary files /dev/null and b/rasa/images/TutoringProof/step3.png differ diff --git a/rasa/images/TutoringProof/step4.png b/rasa/images/TutoringProof/step4.png new file mode 100644 index 0000000..b2ba1d1 Binary files /dev/null and b/rasa/images/TutoringProof/step4.png differ diff --git a/rasa/images/TutoringProof/step5.png b/rasa/images/TutoringProof/step5.png new file mode 100644 index 0000000..a23fce4 Binary files /dev/null and b/rasa/images/TutoringProof/step5.png differ diff --git a/rasa/policy_config.yml b/rasa/policy_config.yml new file mode 100644 index 0000000..ba85c4c --- /dev/null +++ b/rasa/policy_config.yml @@ -0,0 +1,13 @@ +policies: + - name: KerasPolicy + epochs: 10 + batch_size: 10 + featurizer: + - name: FullDialogueTrackerFeaturizer + state_featurizer: + - name: LabelTokenizerSingleStateFeaturizer + - name: FallbackPolicy + nlu_threshold: 0.6 + core_threshold: 0.6 + - name: MemoizationPolicy + max_history: 2 diff --git a/rasa/train-messenger.py b/rasa/train-messenger.py index 51ced2d..1102763 100644 --- a/rasa/train-messenger.py +++ b/rasa/train-messenger.py @@ -3,10 +3,9 @@ import os import train -from rasa_core import utils -from rasa_core.interpreter import RasaNLUInterpreter -from rasa_core.agent import Agent -from rasa_core.channels import HttpInputChannel +from rasa_core.utils import configure_colored_logging, AvailableEndpoints +from rasa_core.run import load_agent +from rasa_core.interpreter import NaturalLanguageInterpreter from rasa_core.channels.facebook import FacebookInput @@ -17,29 +16,37 @@ FACEBOOK_ACCESS_TOKEN = os.getenv('FACEBOOK_ACCESS_TOKEN', '') -def run(): - # load your trained agent - interpreter = RasaNLUInterpreter('models/nlu/default/current') - - agent = Agent.load("models/dialogue", interpreter) +def run(core_dir, nlu_dir): + _endpoints = AvailableEndpoints.read_endpoints('endpoints.yml') + _interpreter = NaturalLanguageInterpreter.create(nlu_dir) input_channel = FacebookInput( - fb_verify=VERIFY, # you need tell facebook this token, - # to confirm your URL + fb_verify=VERIFY, + # you need tell facebook this token, to confirm your URL fb_secret=SECRET, # your app secret - fb_access_token=FACEBOOK_ACCESS_TOKEN # token for the page - # you subscribed to + fb_access_token=FACEBOOK_ACCESS_TOKEN + # token for the page you subscribed to ) - agent.handle_channel(HttpInputChannel(5001, "", input_channel)) + _agent = load_agent(core_dir, + interpreter=_interpreter, + endpoints=_endpoints) + + _agent.handle_channels( + [input_channel], 5001, serve_forever=True + ) if __name__ == '__main__': - utils.configure_colored_logging(loglevel='DEBUG') + configure_colored_logging(loglevel='DEBUG') logger.info("Train NLU") - train.train_nlu() logger.info("Train Dialogue") - train.train_dialogue() + train.train_dialogue( + 'domain.yml', + 'models/dialogue', + 'data/stories/', + 'policy_config.yml' + ) logger.info("Run") - run() + run('models/dialogue', 'models/nlu/current') diff --git a/rasa/train-telegram.py b/rasa/train-telegram.py index 1f751e7..4e5c24e 100644 --- a/rasa/train-telegram.py +++ b/rasa/train-telegram.py @@ -2,42 +2,44 @@ import os import train -from rasa_core import utils -from rasa_core.interpreter import RasaNLUInterpreter -from rasa_core.agent import Agent -from rasa_core.channels import HttpInputChannel from rasa_core.channels.telegram import TelegramInput +from rasa_core.utils import configure_colored_logging, AvailableEndpoints +from rasa_core.run import load_agent +from rasa_core.interpreter import NaturalLanguageInterpreter logger = logging.getLogger(__name__) -# If you want to use your own bot to development add the bot credentials as -# second parameters -TELEGRAM_ACCESS_TOKEN = os.getenv('TELEGRAM_ACCESS_TOKEN', '') -VERIFY = os.getenv('VERIFY', '') -WEBHOOK_URL = os.getenv('WEBHOOK_URL', '') - -def run(): - interpreter = RasaNLUInterpreter('models/nlu/default/current') - - agent = Agent.load('models/dialogue', interpreter=interpreter) +def run(core_dir, nlu_dir): + _endpoints = AvailableEndpoints.read_endpoints('endpoints.yml') + _interpreter = NaturalLanguageInterpreter.create(nlu_dir) input_channel = TelegramInput( - access_token=TELEGRAM_ACCESS_TOKEN, - verify=VERIFY, - webhook_url=WEBHOOK_URL + access_token=os.getenv('TELEGRAM_ACCESS_TOKEN', ''), + verify=os.getenv('VERIFY', ''), + webhook_url=os.getenv('WEBHOOK_URL', '') ) - agent.handle_channel(HttpInputChannel(5002, "", input_channel)) + _agent = load_agent(core_dir, + interpreter=_interpreter, + endpoints=_endpoints) + + _agent.handle_channels( + [input_channel], 5002, serve_forever=True + ) if __name__ == '__main__': - utils.configure_colored_logging(loglevel='DEBUG') + configure_colored_logging(loglevel='DEBUG') logger.info("Train NLU") - train.train_nlu() logger.info("Train Dialogue") - train.train_dialogue() + train.train_dialogue( + 'domain.yml', + 'models/dialogue', + 'data/stories/', + 'policy_config.yml' + ) logger.info("Run") - run() + run('models/dialogue', 'models/nlu/current') diff --git a/rasa/train.py b/rasa/train.py index ea8abfd..e4befc7 100644 --- a/rasa/train.py +++ b/rasa/train.py @@ -1,100 +1,25 @@ -import argparse import logging -import os - -from rasa_core import utils -from rasa_core.agent import Agent -from rasa_core.interpreter import RasaNLUInterpreter -from rasa_core.policies.fallback import FallbackPolicy -from rasa_core.policies.keras_policy import KerasPolicy -from rasa_core.channels.console import ConsoleInputChannel -from rasa_core.policies.memoization import MemoizationPolicy +from rasa_core import utils, train logger = logging.getLogger(__name__) -TRAINING_EPOCHS = int(os.getenv('TRAINING_EPOCHS', 300)) - - -def train_dialogue(domain_file='domain.yml', - model_path='models/dialogue', - training_data_file='data/stories/'): - fallback = FallbackPolicy( - fallback_action_name="action_default_fallback", - core_threshold=0.12, - nlu_threshold=0.7 - ) - - agent = Agent( - domain_file, - policies=[MemoizationPolicy(max_history=3), KerasPolicy(), fallback] - ) - - training_data = agent.load_data(training_data_file) - - agent.train( - training_data, - epochs=TRAINING_EPOCHS, - batch_size=100, - validation_split=0 - ) - - agent.persist(model_path) - - return agent - - -def train_nlu(): - from rasa_nlu.training_data import load_data - from rasa_nlu import config - from rasa_nlu.model import Trainer - - training_data = load_data('data/intents/') - trainer = Trainer(config.load('nlu_config.yml')) - trainer.train(training_data) - - model_directory = trainer.persist( - 'models/nlu/', - fixed_model_name='current' - ) - - return model_directory - - -def run(serve_forever=True): - interpreter = RasaNLUInterpreter('models/nlu/default/current') - agent = Agent.load( - 'models/dialogue', - interpreter=interpreter - ) - - if serve_forever: - agent.handle_channel(ConsoleInputChannel()) - - return agent - +utils.configure_colored_logging(loglevel='DEBUG') -if __name__ == '__main__': - utils.configure_colored_logging(loglevel='DEBUG') - parser = argparse.ArgumentParser( - description='starts the bot') +def train_dialogue(domain_file, + model_path, + training_folder, + policy_config): + return train.train_dialogue_model(domain_file=domain_file, + stories_file=training_folder, + output_path=model_path, + policy_config=policy_config, + kwargs={'augmentation_factor': 20, + 'validation_split': 0.2} + ) - parser.add_argument( - 'task', - choices=['train-nlu', 'train-dialogue', 'run', 'all'], - help='what the bot should do - e.g. run or train?' - ) - task = parser.parse_args().task - # decide what to do based on first parameter of the script - if task == 'train-nlu': - train_nlu() - elif task == 'train-dialogue': - train_dialogue() - elif task == 'run': - run() - elif task == 'all': - train_nlu() - train_dialogue() - run() +if __name__ == "__main__": + train_dialogue('domain.yml', 'models/dialogue', 'data/stories/', + 'policy_config.yml') diff --git a/requirements.txt b/requirements.txt index 01ad2bb..7d0ab3c 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,5 +1,6 @@ -rasa-core==0.10.4 -rasa-nlu[spacy]==0.13.0 +rasa-core==0.13.1 +rasa-core-sdk==0.12.1 +rasa-nlu==0.14.0 Flask==1.0.2 Flask-Cors==3.0.6 httpretty @@ -8,3 +9,9 @@ pymongo==3.7.1 websocket-client==0.52.0 python-crontab pycurl==7.43.0.2 +scikit-learn==0.20.0 +scipy +sklearn-crfsuite +coloredlogs~=10.0 +future==0.16.0 +packaging~=18.0 diff --git a/scripts/setup_envs.py b/scripts/setup_envs.py new file mode 100644 index 0000000..2af1384 --- /dev/null +++ b/scripts/setup_envs.py @@ -0,0 +1,144 @@ +import yaml +import json +import requests as req +import re + +docker_compose_path = 'docker-compose.yml' +envs = {} + + +def print_error(msg): + print('\x1b[1;31m' + msg + '\x1b[0m') + + +def process_env_yaml(text): + if isinstance(text, dict): + name = list(text.keys())[0] + value = text[name] + return (name, value) + text = text.split('=') + return (text[0], text[1]) + + +def load_envs(): + read = read_file(docker_compose_path) + dump = yaml.load(read) + services = dump['services'] + for service in services: + if 'environment' not in services[service]: + continue + if service not in envs: + envs[service] = {} + service_envs = services[service]['environment'] + for env in service_envs: + res = process_env_yaml(env) + envs[service][res[0]] = res[1] + + +def read_file(path): + with open(path, 'r') as f: + doc = f.read() + return doc + + +def change_envs(): + for service in envs: + print() + print('No input means no change') + print('Service: ' + service) + local_envs = envs[service] + for env in local_envs: + value = local_envs[env] + new = input(env + ' (' + value + ') = ') + new = new.strip() + if new == '': + continue + envs[service][env] = new + + +def change_ngrok(): + try: + res = req.get('http://localhost:4040/api/tunnels') + except Exception: + print_error('ERROR: Can\'t connect to ngrok') + exit() + url = '' + res = json.loads(res.text) + tunnels = res['tunnels'] + for tunnel in tunnels: + if tunnel['name'] != 'command_line': + continue + url = tunnel['public_url'] + for service in envs: + for env in envs[service]: + if env != 'WEBHOOK_URL': + continue + envs[service][env] = url + + +def unprocess_env(name, value): + match = re.match(r'\$\{.+\}', value) + if match: + ret = dict() + ret[name] = value + return ret + return name + '=' + value + + +def envs_to_list(): + for serv in envs: + new_envs = envs[serv] + to_yaml = [] + for env in new_envs: + plain = unprocess_env(env, envs[serv][env]) + to_yaml.append(plain) + envs[serv] = to_yaml + + +def write_changes(): + read = read_file('docker-compose.yml') + with open('docker-compose.yml.bkp', 'w') as f: + f.write(read) + dump = yaml.load(read) + for service in dump['services']: + if service not in envs: + continue + dump['services'][service]['environment'] = envs[service] + with open('docker-compose.yml', 'w') as dc: + yaml.dump(dump, dc, default_flow_style=False) + + +def lint(): + read = read_file('docker-compose.yml') + version_regex = r'(version: \'\d+\') *\n' + ret = re.search(version_regex, read) + if ret: + read = read[0:ret.start()] + '' + read[ret.end():] + read = ret.group(0) + '\n' + read + with open('docker-compose.yml', 'w') as f: + f.write(read) + + +def main(): + load_envs() + changed = False + + ans = input('Change envs? [y/N] ') + if ans == 'y' or ans == 'Y': + changed = True + change_envs() + + ans = input('Change ngrok automatically? [y/N] ') + if ans == 'y' or ans == 'Y': + changed = True + change_ngrok() + + envs_to_list() + + if changed: + write_changes() + lint() + + +if __name__ == '__main__': + main()