示例#1
0
def handler(body):
    """
        Tabela com dados por estado por estado
        type -> case or death

    """
    _type = body.get('type', 'case')
    field = CaseReport.total_cases if _type == 'case' else CaseReport.total_deaths
    sub = CaseReport.select().order_by(CaseReport.date_report.desc()).limit(1)
    response = list(
        CaseReport.select(States.name, field.alias('total_data')).join(
            sub, on=(sub.c.date_report == CaseReport.date_report)).join(
                States, on=(States.id == CaseReport.state_id)).order_by(
                    CaseReport.date_report.asc()).dicts().execute())
    names = ['Sudeste', 'Sul', 'Norte', 'Nordeste', 'Centro-Oeste']
    arr = [0, 0, 0, 0, 0]
    for i in response:
        region = define_region(i['name'])
        arr[region] += i['total_data']

    total = reduce(lambda a, b: a + b, arr)
    return {
        'dataseries': [{
            'name': name,
            'y': arr[i] / total,
            'value': arr[i]
        } for i, name in enumerate(names)]
    }
def handler():
    """
        Tabela com dados por estado por estado

    """
    sub = CaseReport.select().order_by(CaseReport.date_report.desc()).limit(1)
    response = list(
        CaseReport.select(
            States.name, CaseReport.total_deaths_per_100k,
            CaseReport.total_cases_per_100k).join(
                sub, on=(sub.c.date_report == CaseReport.date_report)).join(
                    States, on=(States.id == CaseReport.state_id)).order_by(
                        CaseReport.date_report.asc()).dicts().execute())

    cases = [i['total_cases_per_100k'] for i in response]
    deaths = [i['total_deaths_per_100k'] for i in response]

    return {
        'categories': [i['name'] for i in response],
        'series': [{
            'name': 'Casos por 100 Mil habitantes',
            'data': cases,
            'type': 'column'
        }, {
            'name': 'Mortes por 100 Mil habitantes',
            'data': deaths,
            'type': 'column'
        }]
    }
def handler(body) -> dict:
    """
        Serie temporal de casos e mortes

        type -> 'day' or 'week'
        period -> None, 'ytd', 'mtd' ...
        init_date -> data inicial or None
        end_date -> data final or None
        state -> id do estado or 0 para total

    """
    type = body.get('type', 'day')
    period = body.get('period', None)
    init_date = body.get('init_date', None)
    end_date = body.get('end_date', None)
    state = body.get('state', 0)
    where = []
    if period:
        init_date, end_date = get_period(period)

    if init_date and end_date:
        where = [
            CaseReport.date_report >= init_date,
            CaseReport.date_report <= end_date
        ]

    if type == 'day':
        response = CaseReport.select(
            CaseReport.date_report,
            CaseReport.total_cases, CaseReport.total_deaths).where(
                CaseReport.state_id == state, *where).order_by(
                    CaseReport.date_report.asc()).dicts().execute()
    else:
        response = CaseReport.select(
            fn.MAX(CaseReport.date_report).alias('date_report'),
            fn.SUM(CaseReport.total_cases).alias('total_cases'),
            fn.SUM(CaseReport.total_deaths).alias('total_deaths')).where(
                CaseReport.state_id == state, *where).order_by(
                    fn.MAX(CaseReport.date_report).asc()).group_by(
                        CaseReport.epi_week).dicts().execute()
    cases = [[mktime(i.get('date_report').timetuple()),
              i.get('total_cases')] for i in response]
    deaths = [[
        mktime(i.get('date_report').timetuple()),
        i.get('total_deaths')
    ] for i in response]
    return {
        'dataSeries': [{
            'id': 0,
            'name': 'Casos',
            'data': cases,
            'type': 'spline'
        }, {
            'id': 1,
            'name': 'Mortes',
            'data': deaths,
            'type': 'spline'
        }]
    }
示例#4
0
def handler() -> dict:
    """
        Função responsável por salvar o csv com os dados diarios na base

    """
    data = requests.get('https://raw.githubusercontent.com/wcota/covid19br/master/cases-brazil-states.csv').content

    df = pd.read_csv(StringIO(data.decode('utf-8')), sep=',', encoding='utf-8')
    states_response = States.select().dicts().execute()
    states = {i.get('name'): i.get('id') for i in states_response}

    df['state_id'] = df['state'].apply(lambda x: states.get(x, 0))
    df['tests'] = df['tests'].fillna(0)
    df['newDeaths'] = df['newDeaths'].fillna(0)
    df['deaths'] = df['deaths'].fillna(0)
    df['totalCases'] = df['totalCases'].fillna(0)
    df['newCases'] = df['newCases'].fillna(0)
    df['recovered'] = df['recovered'].fillna(0)
    df['suspects'] = df['suspects'].fillna(0)
    df['tests_per_100k_inhabitants'] = df['tests_per_100k_inhabitants'].fillna(0)
    df = df.rename(columns={
        'date': 'date_report',
        'newDeaths': 'new_deaths',
        'deaths': 'total_deaths',
        'totalCases': 'total_cases',
        'newCases': 'new_cases',
        'deaths_per_100k_inhabitants': 'total_deaths_per_100k',
        'totalCases_per_100k_inhabitants': 'total_cases_per_100k',
        'tests_per_100k_inhabitants': 'tests_per_100k',
        'deaths_by_totalCases': 'deaths_by_cases',
    })
    df = df.drop(['state', 'country', 'city', 'deathsMS', 'totalCasesMS'], 1)
    df = df.dropna(subset=['state_id'])
    df = df.drop_duplicates(subset=['state_id', 'date_report'], keep='last')
    dataset = df.to_dict(orient="records")

    try:
        CaseReport.insert_many(dataset).on_conflict(conflict_target=[CaseReport.state_id, CaseReport.date_report],
                                                    preserve=[CaseReport.new_cases, CaseReport.new_deaths,
                                                              CaseReport.total_deaths, CaseReport.total_cases,
                                                              CaseReport.total_cases_per_100k,
                                                              CaseReport.total_deaths_per_100k,
                                                              CaseReport.tests_per_100k, CaseReport.tests,
                                                              CaseReport.suspects, CaseReport.recovered],
                                                    action="update").execute()
    except Exception as e:
        print(e)
        return {'status': 500}

    return {'status': 400}
示例#5
0
def handler(body) -> dict:
    """
        Serie temporal de Letalidade
        days -> dias da simulacao
        state -> id do estado or 0 para total

    """
    days = body.get('days', 15)
    state = body.get('state', 0)

    response = CaseReport.select(
        CaseReport.date_report, CaseReport.total_cases,
        CaseReport.total_deaths).where(CaseReport.state_id == state).order_by(
            CaseReport.date_report.asc()).dicts().execute()

    total_deaths = response[-1].get('total_deaths', 0)
    total_cases = response[-1].get('total_cases', 0)
    last_day = response[-1].get('date_report', 0)

    days_to_double_cases = 0
    days_to_double_deaths = 0
    for d, i in enumerate(response[::-1]):
        if total_cases >= 2 * i['total_cases']:
            days_to_double_cases = d
            break

    for d, i in enumerate(response[::-1]):
        if total_deaths >= 2 * i['total_deaths']:
            days_to_double_deaths = d
            break

    cases = []
    deaths = []
    date = tomorrow(last_day)

    for i in range(1, days + 1):
        date_time = datetime.timestamp(datetime.strptime(date, '%Y-%m-%d'))
        future_total_cases = total_cases * (2**(i / days_to_double_cases))
        future_total_deaths = total_deaths * (2**(i / days_to_double_deaths))
        cases.append([date_time, future_total_cases])
        deaths.append([date_time, future_total_deaths])
        date = tomorrow(date)

    return {
        'dataSeries': [
            {
                'id': 0,
                'name': 'Casos',
                'data': cases,
                'type': 'spline'
            },
            {
                'id': 1,
                'name': 'Mortes',
                'data': deaths,
                'type': 'spline'
            },
        ]
    }
def handler():
    """
        Tabela com dados por estado por estado

    """
    sub = CaseReport.select().order_by(CaseReport.date_report.desc()).limit(1)
    response = list(
        CaseReport.select(
            States.name, CaseReport.total_cases, CaseReport.new_cases,
            CaseReport.total_deaths, CaseReport.new_deaths, CaseReport.tests,
            CaseReport.tests_per_100k, CaseReport.suspects,
            CaseReport.total_deaths_per_100k, CaseReport.total_cases_per_100k,
            CaseReport.deaths_by_cases).join(
                sub, on=(sub.c.date_report == CaseReport.date_report)).join(
                    States, on=(States.id == CaseReport.state_id)).order_by(
                        CaseReport.date_report.asc()).dicts().execute())

    return {'data': response}
示例#7
0
def handler(body):
    """
        Painel com informações básicas

    """
    state = body.get('state', 0)

    response = list(
        CaseReport.select(
            CaseReport.date_report, CaseReport.total_cases,
            CaseReport.total_deaths, CaseReport.new_cases,
            CaseReport.new_deaths).where(
                CaseReport.state_id == state).order_by(
                    CaseReport.date_report.asc()).dicts().execute())

    first_case_day = response[0].get('date_report', None)
    last_date = response[-1].get('date_report', None)
    total_cases = response[-1].get('total_cases', 0)
    total_deaths = response[-1].get('total_deaths', 0)
    new_cases = response[-1].get('new_deaths', 0)
    new_deaths = response[-1].get('new_deaths', 0)
    lethality = total_deaths / total_cases if total_cases != 0 else None
    first_death_day = next((i for i in response if i.get('total_deaths')),
                           None).get('date_report')
    days_to_double = 0
    for d, i in enumerate(response[::-1]):
        if total_cases >= 2 * i['total_cases']:
            days_to_double = d
            break

    return {
        'first_case_day': first_case_day,
        'first_death_day': first_death_day,
        'total_cases': total_cases,
        'total_deaths': total_deaths,
        'new_cases': new_cases,
        'new_deaths': new_deaths,
        'lethality': lethality,
        'days_to_double': days_to_double,
        'last_date': last_date
    }