Giter Site home page Giter Site logo

alertadenguecaptura's Introduction

AlertaDengueCaptura

codecovflujo de trabajo de ejemploBuild Status

Rotinas para captura de dados.

Este repositório contém uma framework para a captura automática de dados de forma distribuída em dois diferentes aplicativos:

Crawlclima

Requisitos(Debian)

Para configurar o ambiente e instalar a app veja o README no diretório crawclima.

Utilities contain some tools and modules to update tables with initial data for use in the AlertaDengueCaptura.


Downloader

  • As rotinas disponíveis neste pacote são projetadas para capturar e processar imagens de satélite de forma fácil e conveniente. Além disso, existem rotinas para combinar dados raster com camadas de shapefiles para imagens mais informativas mais....
  • Verifique o notebook examples.ipynb para ver como funciona em detalhes.

Requisitos(Debian)

Para configurar o ambiente e instalar a app veja o README no diretório downloader_app.

No diretório notebooks há mais notebooks experimentais para testar os acessos e visualizar os dados.

Rodar o Downloader App em container(Docker)

Consulte o README no diretório docker/satellite.

Esta app encontra-se em fase de desenvolvimento, contribua...


alertadenguecaptura's People

Contributors

claudia-codeco avatar eltonn avatar esloch avatar fccoelho avatar felipebottega avatar flavioamieiro avatar israelst avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

alertadenguecaptura's Issues

Dockerize celery and cron

  • Passar celery e as tasks de crawlclima para container
  • Resolver problemas nas dependências dos pacotes
  • Corrigir a falha na task pega-temperatura

Containerized downloader_app

  • Containerized downloader_app is part of issue #50 .
  • The sequence of PR #57 .
  • Create a structure for dockerfiles.
  • Pass the tests into the container.
  • Run the application in celery from crontab.

Modulo logging

Trocar o get_task_logger no tiff_downloader.py pelas funcionalidades do módulo logging.

Use poetry

  • Migrate setup.cfg to pyproject.toml


Building crawlclima
dsaTraceback (most recent call last):
  File "/opt/conda/bin/mamba", line 7, in <module>
    from mamba.mamba import main
  File "/opt/conda/lib/python3.9/site-packages/mamba/mamba.py", line 51, in <module>
    from mamba import repoquery as repoquery_api
  File "/opt/conda/lib/python3.9/site-packages/mamba/repoquery.py", line 12, in <module>
    def _repoquery(query_type, q, pool, fmt=api.QueryFormat.JSON):
AttributeError: module 'libmambapy' has no attribute 'QueryFormat'Traceback (most recent call last):
  File "/opt/conda/bin/mamba", line 7, in <module>
    from mamba.mamba import main
  File "/opt/conda/lib/python3.9/site-packages/mamba/mamba.py", line 51, in <module>
    from mamba import repoquery as repoquery_api
  File "/opt/conda/lib/python3.9/site-packages/mamba/repoquery.py", line 12, in <module>
    def _repoquery(query_type, q, pool, fmt=api.QueryFormat.JSON):
AttributeError: module 'libmambapy' has no attribute 'QueryFormat'Step 1/16 : FROM condaforge/mambaforge

Traceback (most recent call last):
  File "/opt/conda/bin/mamba", line 7, in <module>
    from mamba.mamba import main
  File "/opt/conda/lib/python3.9/site-packages/mamba/mamba.py", line 51, in <module>
    from mamba import repoquery as repoquery_api
  File "/opt/conda/lib/python3.9/site-packages/mamba/repoquery.py", line 12, in <module>
    def _repoquery(query_type, q, pool, fmt=api.QueryFormat.JSON):
AttributeError: module 'libmambapy' has no attribute 'QueryFormat
 

Incluir os municipios do MA, RS e SP nas capturas de tweet

Problema

A tabela tweet não tem os tweets para os municípios do Rio Grande do Sul , Maranhão e São Paulo.
Isso acontece porque eles não estão no arquivo municipios (aqui no AlertaDengueCaptura).

É preciso baixar os dados históricos e manter a captura semanal

Solução imediata
Acrescentar todos os municipios do MA no arquivo municipios
Acrescentar os municipios de SP: 3549805, 3506003 e 3552205 no arquivo municipios
Acrescentar o municipio do RS: 4314902 no arquivo municipios

Solucao ideal
Atualizar a lista de municipios via consulta à tabela notificacao

Bugfix earthengine-api

The 2.0.0 release no longer retrieves discovery documents dynamically on each call to discovery.build(). Instead, discovery documents are retrieved from the client library itself.

See:
https://github.com/googleapis/google-api-python-client/blob/master/UPGRADING.md
https://github.com/google/earthengine-api/issues/157

==================================== ERRORS ====================================
________ ERROR collecting downloader_app/tests/test_tiff_downloader.py _________
downloader_app/tests/test_tiff_downloader.py:9: in <module>
    from downloader_app import tiff_downloader as td
downloader_app/tiff_downloader.py:36: in <module>
    ee.Initialize()
/opt/conda/lib/python3.7/site-packages/ee/__init__.py:123: in Initialize
    http_transport=http_transport)
/opt/conda/lib/python3.7/site-packages/ee/data.py:199: in initialize
    _install_cloud_api_resource()
/opt/conda/lib/python3.7/site-packages/ee/data.py:273: in _install_cloud_api_resource
    http_transport=_http_transport)
/opt/conda/lib/python3.7/site-packages/ee/_cloud_api_utils.py:151: in build_cloud_resource
    cache_discovery=False)
/opt/conda/lib/python3.7/site-packages/googleapiclient/_helpers.py:134: in positional_wrapper
    return wrapped(*args, **kwargs)
/opt/conda/lib/python3.7/site-packages/googleapiclient/discovery.py:282: in build
    static_discovery=static_discovery,
/opt/conda/lib/python3.7/site-packages/googleapiclient/discovery.py:387: in _retrieve_discovery_doc
    raise UnknownApiNameOrVersion("name: %s  version: %s" % (serviceName, version))
E   googleapiclient.errors.UnknownApiNameOrVersion: name: earthengine  version: v1alpha
=============================== warnings summary ===============================
/opt/conda/lib/python3.7/site-packages/rasterstats/io.py:24
/opt/conda/lib/python3.7/site-packages/rasterstats/io.py:24
  /opt/conda/lib/python3.7/site-packages/rasterstats/io.py:24: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated since Python 3.3,and in 3.9 it will stop working
    from collections import Iterable, Mapping

/opt/conda/lib/python3.7/site-packages/holoviews/operation/datashader.py:5
  /opt/conda/lib/python3.7/site-packages/holoviews/operation/datashader.py:5: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated since Python 3.3,and in 3.9 it will stop working
    from collections import Callable

-- Docs: https://docs.pytest.org/en/stable/warnings.html
=========================== short test summary info ============================
ERROR downloader_app/tests/test_tiff_downloader.py - googleapiclient.errors.U...
!!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!
========================= 3 warnings, 1 error in 8.92s =========================
make: *** [docker/satellite/Makefile:53: test_downloader_app] Error 2
Error: Process completed with exit code 2.

Documentar processo de criação do banco de dados

Enquanto eu estava tentando reproduzir um bug no ambiente de produção (o celery não parecia estar executando as tarefas) tentei executar o código na minha máquina e tive dificuldade na hora de criar o banco de dados. Existe um script em dbschema/Banco_de_dados_do_Alerta_Dengue_create.sql, mas executando ele com psql < dbschema/Banco_de_dados_do_Alerta_Dengue_create.sql eu tive um erro. Seria bom se no README esse processo estivesse documentado.

Tabela Clima_WU ainda tem dados faltantes

A Tabela Clima_WU ainda tem dados faltantes referentes a datas no passado recente. Verificar se os dados não existem mesmo ou se foi um problema de captura.

Exemplo
SELECT * FROM "Municipio"."Estacao_wu" AS e
INNER JOIN "Municipio"."Clima_wu" AS c
ON e.estacao_id = c."Estacao_wu_estacao_id" WHERE e.estacao_id = SBFZ

onde faltam dados para os dias de novembro de 2017.
Tem outras estações com o mesmo problema.

Create README files

  • Create README for application use:
    • Crawlclima
    • Downloader_app
  • Standardize the parameters in the Makefile for the Crawlclima app.

Tratamento de daldos faltantes

O sistema deve ser capaz de lidar com falta de dados ou erro na captura.
Devemos ter uma estrutura que possa reconhecer a "posição/janela temporal" faltante e lidar de acordo.
Sugestão para dados climáticos:
"Buraco simples" (não há apenas o ultimo dado, ou há erro em te, mas há dados em te-1 e te+1): interpolação, quando possível, adotando a escala temporal adequada.

  • Se o buraco for na escala horária, interpolar com os dados da série temporal daquele dia.
  • Se o buraco for um dia inteiro, ou uma parcela suficientemente grande do día (definir este intervalo limite), interpolar as variáveis de interesse na escala diária. Isto é, pegar a série temporal de temperatura mínima de cada dia e fazer a interpolação nesta escala, por exemplo.
  • Semana inteira faltando, ou intervalo suficientemente grande (a definir): repetir dado da semana anterior. Ou fazer interpolação com os dados agregados em escala semanal? Como iremos guardar o dado semanal usado nos relatórios, isso também seria possível.

Embora a sugestão tenha sido feita para dados climáticos, esta estrutura pode ser adaptada para os demais dados.
Importante: o módulo responsável deve reportar o erro e medida adotada, que devem ser registrados no log de execução.

Celerybeat instability

Celerybeat seems to be very unstable and is not sending the capture tasks to the worker.

I proposed we move to having separate cronjobs to start each capture defined on the celerybeat configuration and use monit to check that the worker stays up to handle the capture tasks.

Error starting celery when up containers

Traceback

Traceback (most recent call last):
File "/opt/conda/bin/celery", line 33, in
sys.exit(load_entry_point('celery', 'console_scripts', 'celery')())
File "/opt/conda/lib/python3.7/site-packages/celery/main.py", line 14, in main
from celery.bin.celery import main as _main
File "/opt/conda/lib/python3.7/site-packages/celery/bin/celery.py", line 15, in
from celery.bin.amqp import amqp
File "/opt/conda/lib/python3.7/site-packages/celery/bin/amqp.py", line 7, in
from click_repl import register_repl
File "/opt/conda/lib/python3.7/site-packages/click_repl/init.py", line 6, in
import click._bashcomplete

problem capturing climate data

Problem capturing data from stations SBGL and SBJR . I checked the wu site, and there is data in the source. At least 15 days already.

Automatizar captura de dados

@israelst, neste repositório existe o início de uma aplicação celery para automatizar a captura de dados para o projeto. Atualmente, estamos usando scripts isolados no repositório AlertaDengueAnalise. É uma boa oportunidade para você se familiarizar com o Celery, se já não te for familiar. Qualquer dúvida pergunte ao nosso celery master: @flavioamieiro .

O código deste repo tem que rodar diariamente no servidor de dados. No módulo de tasks já existe uma pronta para captura dos dados climáticos do CEMADEN, falta portar os scripts de captura do weather underground e dos tweets . Estes scripts devem virar tasks do módulo
tasks.py

Script de verificação do upload precisa verificar datas

@flavioamieiro: nos DBFs do ES a coluna DT_NOTIFIC tem várias datas com formatação errada.
(só confirmei isso no dbf de 2015.)
O nosso validador de Upload vai ter que monitorar isso também.
Estes registros com datas mal formatadas, estão "aparentemente" sendo ignorados pelo load SINAN, pois as contagens de casos para os municípios do ES estão muito baixas.

Acho que nosso validador de DBF vai ter que evoluir para uma espécie de sinan-lint.

Fix the captura_clima manual capture tool (from Utilities)

  • The captura_clima tool makes it possible to obtain data from REDEMET weather stations manually.

Error when not getting the return data

Reproduce:

09:02 $ python utilities/captura_clima.py -c SBAF -i 2021-09-28 -f 2021-10-09
Date 2021-09-28 00:00:00 has already been captured from station SBAF 
Date 2021-09-29 00:00:00 has already been captured from station SBAF 
Date 2021-09-30 00:00:00 has already been captured from station SBAF 
Fetching data from SBAF at 2021-10-01 00:00:00.

Traceback:

  File "/work_lab/fiocruz/repositories/AlertaDengueCaptura/utilities/captura_clima.py", line 51, in <module>
    res = capture(station, date)
  File "/work_lab/fiocruz/InfoDengue/AlertaDengueCaptura-dockerize-celery/crawlclima/redemet/rmet.py", line 192, in capture
    f.write("{}".format(resp_data["data"]["data"]))
KeyError: 'data'

Falha ao capturar dados REDEMET

  • O endpoint de redemet está retornando à mensagem:
    SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Nome ou serviço desconhecido
  • Foi testado a captura pelo endpoint por meio de um script da redemet e também via wget
    nos dois casos foi registrado a mesma mensagem. (Os mesmos testes funcionam para a captura em máquina local).

Possivelmente estamos com o servidor restringido para a captura dos dados.
Solicitei via formulário de autoatendimento redemet a verificação desta ocorrência no recebimento dos dados, o prazo estimado de resposta é de 30 dias a partir da data de hoje.

Redefinir a tabela Clima_Satelite

Sugestão, para ficar uma tabela generica para todos os dados de satelite.

CREATE TABLE "Municipio"."Clima_Satelite"
(
id bigserial NOT NULL,
data date NOT NULL,
"municipio_geocodigo" integer NOT NULL,
"satelite", string NOT NULL, # info sobre a fonte do dado
"nomevar" string NOT NULL, # variavel coletada (tmin, tmax, enso, etc)
"coordx" integer NOT NULL,
"coordy" integer NOT NULL,
"valorvar" numeric(4,2) NOT NULL, # valor mensurado

nao sei essa parte:

CONSTRAINT "Clima_Satelite_pk" PRIMARY KEY (id),
REFERENCES "Municipio"."Localidade" (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
)

Documentar configuração dos Bancos

A instalação e configuração dos bancos para uso precisa ser documentada. No caso do PostgreSQL é bem complicado pois exige a criação de tabelas usuário e direitos de acesso.

Idealmente toda a configuração do postgres deveria ser feita em um arquivo SQL a ser executado após a instalação.

Update to Celery 5.0.5

Specific

As tarefas não estão sendo inicializadas

[2021-01-08 07:52:07,271: WARNING/MainProcess] /opt/conda/lib/python3.8/site-packages/celery/app/utils.py:204: CDeprecationWarning: 
    The 'BROKER_URL' setting is deprecated and scheduled for removal in
    version 6.0.0. Use the broker_url instead

  deprecated.warn(description=f'The {setting!r} setting',

[2021-01-08 07:52:07,271: WARNING/MainProcess] /opt/conda/lib/python3.8/site-packages/celery/app/utils.py:204: CDeprecationWarning: 
    The 'CELERY_RESULT_BACKEND' setting is deprecated and scheduled for removal in
    version 6.0.0. Use the result_backend instead

  deprecated.warn(description=f'The {setting!r} setting',

[2021-01-08 07:52:07,271: WARNING/MainProcess] /opt/conda/lib/python3.8/site-packages/celery/app/utils.py:204: CDeprecationWarning: 
    The 'CELERY_ALWAYS_EAGER' setting is deprecated and scheduled for removal in
    version 6.0.0. Use the task_always_eager instead

  deprecated.warn(description=f'The {setting!r} setting',

[2021-01-08 07:52:07,272: WARNING/MainProcess] /opt/conda/lib/python3.8/site-packages/celery/app/utils.py:204: CDeprecationWarning: 
    The 'CELERY_ANNOTATIONS' setting is deprecated and scheduled for removal in
    version 6.0.0. Use the task_annotations instead

  deprecated.warn(description=f'The {setting!r} setting',

[2021-01-08 07:52:07,272: WARNING/MainProcess] /opt/conda/lib/python3.8/site-packages/celery/app/utils.py:204: CDeprecationWarning: 
    The 'CELERYD_MAX_TASKS_PER_CHILD' setting is deprecated and scheduled for removal in
    version 6.0.0. Use the worker_max_tasks_per_child instead

  deprecated.warn(description=f'The {setting!r} setting',

[2021-01-08 07:52:07,272: WARNING/MainProcess] /opt/conda/lib/python3.8/site-packages/celery/app/utils.py:204: CDeprecationWarning: 
    The 'CELERY_TIMEZONE' setting is deprecated and scheduled for removal in
    version 6.0.0. Use the timezone instead

  deprecated.warn(description=f'The {setting!r} setting',

[2021-01-08 07:52:07,272: WARNING/MainProcess] /opt/conda/lib/python3.8/site-packages/celery/app/utils.py:204: CDeprecationWarning: 
    The 'CELERY_IMPORTS' setting is deprecated and scheduled for removal in
    version 6.0.0. Use the imports instead

  deprecated.warn(description=f'The {setting!r} setting',

[2021-01-08 07:52:07,272: WARNING/MainProcess] Please run `celery upgrade settings path/to/settings.py` to avoid these warnings and to allow a smoother upgrade to Celery 6.0.

Enable Continuous capture of Satellite images

Continuing from the work done in PR #42 , We need to automate the weekly capture of images through the creation of dedicated celery task which will run weekly.
The images downloaded should be stored in the filesystem.

Once this is done a new issue can be opened to implement the postprocessing of the images to generate the data to be inserted in the table Clima_Satelite. This table schema may need to be redesigned, to conform with the data available. Issue #22 has an older proposal.

Configure new endpoint for API-REDEMET

Objetivos / Objectivos / Purpose

Geral / General

  • Atualizar a nova versão da api-redemet.

Específicos / Specific

  • Mudar para o novo endpoint de captiura.
  • Criar uma chave {api_key} requerida no parâmetro de consulta.
  • Extrair as variáveis de retorno do formato JSON.

Justificativa / Justification

  • Resolver a falha na captura dos dados no host que vem ocorrendo
    desde o mês de fevereiro.

Preventing generation of duplicates

@flavioamieiro
A failure to identify unique records for the upsert operations, can lead to the introduction of duplicates in the database.
To avoid newer duplicates we must change the unique record definition to:
número de notificação + data notificação + Cid + código do município

Then to validate after the end of the upsert operation we must check that the number of records in the databases associated with a particular state/city and year must be equal to the number of records in the DBF just imported. This is because each DBF is an update of an year's records.

This can be implemented as a final validation of the import process.

Fix missing geojson data

Objetivos / Objectivos / Purpose

Geral / General

https://github.com/carolinabigonha/br-atlas

After the capture from br-atlas of the json files to the geos/ directory these geocodes are not found in the geojson.

1504752 is not in this geojson: pa.
4220000 is not in this geojson: sc.
4212650 is not in this geojson: sc.
4314548 is not in this geojson: rs.
5006275 is not in this geojson: ms.

Específicos / Specific

  • Funcionalidades [desejadas / deseadas] / Desired functionalities
    Create new app to capture missing geocodes

Justificativa / Justification

Error parsing METAR

Objetivos / Objectivos / Purpose

Geral / General

  • Criar filtro para limpar informações complementares em raw_metar.
  • Verificar os dados parseados.

Justificativa / Justification

*Traceback:

Error parsing METAR: 2020-07-01 17:00:00 - METAR SBLB 011700Z AUTO 35027KT 9999 NCD 24/21 Q1008 W23/S4
capture_celery-worker_1  | Traceback (most recent call last):
capture_celery-worker_1  |   File "/AlertaDengueCaptura/crawlclima/redemet/rmet.py", line 66, in parse_page
capture_celery-worker_1  |     m = Metar(raw_metar)
capture_celery-worker_1  |   File "/opt/conda/lib/python3.7/site-packages/metar/Metar.py", line 417, in __init__
capture_celery-worker_1  |     raise ParserError("Unparsed groups in body: "+code)
capture_celery-worker_1  | metar.Metar.ParserError: Unparsed groups in body: W23/S4
capture_celery-worker_1  | [2020-07-02 17:22:23,417: ERROR/ForkPoolWorker-2] crawlclima.tasks.fetch_redemet[16cc094d-8cb9-40cd-9314-04232efe3759]: Error parsing METAR: 2020-07-01 18:00:00 - METAR SBLB 011800Z AUTO 35027KT 9999 NCD 24/21 Q1008 W23/S4
capture_celery-worker_1  | [2020-07-03 18:52:07,040: ERROR/ForkPoolWorker-3] crawlclima.tasks.fetch_redemet[84e77c25-c212-4f8c-9c22-4247b084dfa2]: Error parsing METAR: 2020-06-23 23:00:00 - METAR SBPV 240000Z 00000KT 9999 FEW025 25/21Q1008
capture_celery-worker_1  | Traceback (most recent call last):
capture_celery-worker_1  |   File "/AlertaDengueCaptura/crawlclima/redemet/rmet.py", line 66, in parse_page
capture_celery-worker_1  |     m = Metar(raw_metar)
capture_celery-worker_1  |   File "/opt/conda/lib/python3.7/site-packages/metar/Metar.py", line 417, in __init__
capture_celery-worker_1  |     raise ParserError("Unparsed groups in body: "+code)
capture_celery-worker_1  | metar.Metar.ParserError: Unparsed groups in body: 25/21Q1008
capture_celery-worker_1  | [2020-07-02 19:16:05,431: ERROR/ForkPoolWorker-6] crawlclima.tasks.fetch_redemet[2594eacf-c418-48e6-82d8-22886220c290]: Error parsing METAR: 2020-07-01 14:00:00 - METAR SBLB 011400Z AUTO -3632KT 9999 NCD 24/21 Q1010
capture_celery-worker_1  | Traceback (most recent call last):
capture_celery-worker_1  |   File "/AlertaDengueCaptura/crawlclima/redemet/rmet.py", line 66, in parse_page
capture_celery-worker_1  |     m = Metar(raw_metar)
capture_celery-worker_1  |   File "/opt/conda/lib/python3.7/site-packages/metar/Metar.py", line 417, in init
capture_celery-worker_1  |     raise ParserError("Unparsed groups in body: "+code)
capture_celery-worker_1  | metar.Metar.ParserError: Unparsed groups in body: -3632KT

Adicinar normalização da coluna "cid10_codigo"

@flavioamieiro, durante a importação dos primeiros dados de chikungunya, verifiquei que a coluna "cid10_codigo" não está normalizando os valores.

alguns registros estão como "A92.0" enquanto a maioria está como "A920". Proponho padronizar sem o ponto. Assim que este bug estiver consertado teremos que re-importar estes dados: MRJCHIK*

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.