def update(self, key, value, secs): self.paused = True time_cache = get_time(secs) self.cache[key] = utils.Dictionary({'time_set': time_cache, 'data': value}) logger.debug("Updated key {0} with the values {1} to cache {2} // ProcessTime: {3}".format(key, value, self.name, time.process_time())) self.paused = False return key
def add(self, key, value, secs): # Awaits the running cleaner to end, before it edits the cache self.__wait_until_complete() self.paused = True time_cache = get_time(secs) self.cache[key] = utils.Dictionary({'time_set': time_cache, 'data': value}) if not self._is_cached(key): logger.error("Key wasn't added properly") raise KeyNotAddedError logger.debug("Added {0} to cache {1} // ProcessTime: {2}".format(key, self.name, self.process_time())) self.paused = False return key
def main(user_input, indicators, data, config, session_state): utils.genHeroSection( title1="Onda", title2="Covid", subtitle="Veja e compare a evolução da curva de contágio da Covid-19 em sua cidade, estado ou país.", logo="https://i.imgur.com/Oy7IiGB.png", header=False ) # Prompt User to Select Heatmap Location view = st.selectbox("Selecione a sua visão", options=["Cidade", "Estado", "País"], index=1) # Load City/State/Country Heatmap if view == "Estado": load_states_heatmap(copy.deepcopy(loading_cached_states())) elif view == "Cidade": my_dict = utils.Dictionary() load_cities_heatmap(my_dict, session_state) elif view == "País": load_countries_heatmap(config)
def plot_inloco(place_id, df, decoration=False): fig = go.Figure() names = utils.Dictionary().get_place_names_by_id(place_id) state_id = int(str(place_id)[:2]) # Add traces if place_id > 10000: # city clean_df = (df.query('state_num_id == "%s"' % state_id).query( 'city_name == "%s"' % names[0]).reset_index()) x_values = translate_dates(clean_df["dt"]) # Redo this in case of isolated not being the index anymore if clean_df.index.name == "isolated": y_values = clean_df.index else: y_values = clean_df["isolated"] name = names[0] + f" ({names[2]})" else: # state clean_df = df.query('state_num_id == "%s"' % state_id).reset_index() x_values = translate_dates(clean_df["dt"]) y_values = clean_df["isolated"] name = names[0] # Generate fig fig.add_trace(go.Scatter(x=x_values, y=y_values, name=name)) # Use alert color fig.update_traces(line={"color": get_alert_color(y_values.iloc[-1])}) if decoration: fig.update_layout(updatemenus=[dict(active=0)]) fig.update_layout(template="plotly_white") return fig
def main(session_state): # GOOGLE ANALYTICS SETUP if os.getenv("IS_DEV") == "FALSE": utils.setup_google_analytics() # Amplitude: Get user info user_analytics = amplitude.gen_user(utils.get_server_session()) opening_response = user_analytics.safe_log_event("opened farol", session_state, is_new_page=True) config = yaml.load(open("configs/config.yaml", "r"), Loader=yaml.FullLoader) utils.localCSS("style.css") st.write( """<iframe src="https://www.googletagmanager.com/ns.html?id=GTM-MKWTV7X" height="0" width="0" style="display:none;visibility:hidden"></iframe>""", unsafe_allow_html=True, ) utils.genHeroSection( title1="Farol", title2="Covid", subtitle="Entenda e controle a Covid-19 em sua cidade e estado.", logo="https://i.imgur.com/CkYDPR7.png", header=True, explain=True) # TEMPORARY BANNER FC escolasegura_logo = utils.load_image("imgs/escolasegura_favicon.png") st.write( f"""<div> <div class="base-wrapper flex flex-column" style="background-color:#0090A7"> <div class="white-span header p1" style="font-size:30px;"><img class="icon-cards" src="data:image/png;base64,{escolasegura_logo}" alt="Fonte: Impulso"> COMO PLANEJAR UMA REABERTURA SEGURA?</div> <span class="white-span">Veja guias e protocolos para facilitar uma reabertura planejada da rede pública de ensino, respeitando boas práticas de distanciamento e segurança sanitária para controle da Covid-19. <br><b>Acesse o Escola Segura: <a target="_blank" style="color:#FFFFFF;" href="http://escolasegura.coronacidades.org">http://escolasegura.coronacidades.org</a></b></span> </div>""", unsafe_allow_html=True, ) st.write( """ <div class="base-wrapper primary-span"> <span class="section-header">Selecione seu estado ou município no mapa abaixo:</span> </div>""", unsafe_allow_html=True, ) # GET DATA dfs, cnes_sources = get_data(config) # REGION/CITY USER INPUT user_input = dict() user_input["state_name"] = st.selectbox("Estado", utils.filter_place(dfs, "state")) user_input["health_region_name"] = st.selectbox( "Região de Saúde", utils.filter_place(dfs, "health_region", state_name=user_input["state_name"]), ) user_input["city_name"] = st.selectbox( "Município", utils.filter_place( dfs, "city", state_name=user_input["state_name"], health_region_name=user_input["health_region_name"], ), ) changed_city = user_analytics.safe_log_event( "picked farol place", session_state, event_args={ "state": user_input["state_name"], "city": user_input["city_name"] }, ) user_input, data = update_user_input_places(user_input, dfs, config) # GENERATE MAPS map_place_id = utils.Dictionary().get_state_alphabetical_id_by_name( user_input["state_name"]) if os.getenv("IS_LOCAL").upper() == "TRUE": map_url = config["br"]["api"]["mapserver_local"] else: map_url = config["br"]["api"]["mapserver_external"] st.write( f""" <div class="brazil-map-div"> <div class="alert-levels-map-overlay"> </div> <div> <iframe id="map" src="resources/iframe-gen.html?url={map_url}maps/map-iframe?place_id=BR" class="map-br" scrolling="no"> </iframe> </div> </div> """, unsafe_allow_html=True, ) st.write( f""" <iframe id="map-state" src="resources/iframe-gen.html?url={map_url}maps/map-iframe?place_id={map_place_id}" class="map-state" scrolling="no"> </iframe> """, unsafe_allow_html=True, ) st.write( f""" <div class="selectors-box" id="selectors-box"> </div> <iframe src="resources/select-box-mover.html?place_id={user_input["state_name"]}{user_input["health_region_name"]}{user_input["city_name"]}" height="0px"> </iframe>""", unsafe_allow_html=True, ) # SOURCES PARAMS user_input = utils.get_sources(user_input, data, cnes_sources, ["beds", "icu_beds"]) # POPULATION PARAMS try: user_input["population_params"] = { "N": int(data["population"].fillna(0).values[0]), "D": int(data["deaths"].fillna(0).values[0]), "I": int(data["active_cases"].fillna(0).values[0]), "I_confirmed": int(data["confirmed_cases"].fillna(0).values[0]), "I_compare": int(data["confirmed_cases"].fillna(0).values[0]), } except: user_input["population_params"] = { "N": int(data["population"].fillna(0).values[0]), "D": int(data["deaths"].fillna(0).values[0]), "I": 0, "I_confirmed": int(data["confirmed_cases"].fillna(0).values[0]), "I_compare": int(data["confirmed_cases"].fillna(0).values[0]), } user_input["Rt"] = { "best": data["rt_low_95"].values[0], "worst": data["rt_high_95"].values[0], "is_valid": data["rt_most_likely"].apply(str).values[0], } user_input["last_updated_cases"] = data[ "last_updated_subnotification"].max() # Update session values to standard ones if changed city or opened page or reseted values if (session_state.state_name != user_input["state_name"] or session_state.health_region_name != user_input["health_region_name"] or session_state.city_name != user_input["city_name"] or session_state.number_beds is None or session_state.reset): session_state.state_name = user_input["state_name"] session_state.health_region_name = user_input["health_region_name"] session_state.city_name = user_input["city_name"] session_state.state_num_id = user_input["state_num_id"] session_state.health_region_id = user_input["health_region_id"] session_state.city_id = user_input["city_id"] session_state.number_beds = int( user_input["number_beds"] * config["br"]["simulacovid"]["resources_available_proportion"]) session_state.number_icu_beds = int( user_input["number_icu_beds"] * config["br"]["simulacovid"]["resources_available_proportion"]) session_state.number_cases = user_input["population_params"][ "I_confirmed"] session_state.number_deaths = user_input["population_params"]["D"] session_state.reset = True if data["confirmed_cases"].sum() == 0: st.write( f"""<div class="base-wrapper"> Seu município ou Região de Saúde ainda não possui casos reportados oficialmente. Portanto, simulamos como se o primeiro caso ocorresse hoje. <br><br>Caso queria, você pode mudar esse número abaixo: </div>""", unsafe_allow_html=True, ) user_input["population_params"]["I"] = 1 else: infectious_period = ( config["br"]["seir_parameters"]["severe_duration"] + config["br"]["seir_parameters"]["critical_duration"]) placeholder_value_pls_solve_this = 0 # TEMPORARY BANNER - TODO: remove after done if user_input["state_name"] in ["Mato Grosso", "Espírito Santo"]: st.write(""" <div> <div class="base-wrapper flex flex-column" style="background-color:#0090A7"> <div class="white-span header p1" style="font-size:30px;">⚠️ ATENÇÃO: Os municípios e regionais de saúde de MT e ES estão desatualizados</div> <span class="white-span">Utilizamos dados abertos das secretarias estaduais para os cálculos dos indicadores. Esses dados são capturados diariamente por voluntários do Brasil.io, que vêm enfrenteando problemas na atualização dos dados desses estados. Estamos resolvendo a situação e iremos retornar com os indicadores o mais breve possível.</b></span> </div> <div>""", unsafe_allow_html=True) # DIMENSIONS CARDS dimensions = DimensionCards utils.genAnalysisDimmensionsSection(dimensions) # INDICATORS CARDS indicators = IndicatorCards indicators = update_indicators(indicators, data, config, user_input, session_state) data["overall_alert"] = data["overall_alert"].map( config["br"]["farolcovid"]["categories"]) if "state" in user_input["place_type"]: # Add disclaimer to cities in state alert levels total_alert_regions = (dfs["health_region"][ dfs["health_region"]["state_num_id"] == data["state_num_id"]. unique()[0]].assign(overall_alert=lambda df: df["overall_alert"]. map(config["br"]["farolcovid"]["categories"])) ["overall_alert"].value_counts()) utils.genKPISection( place_type=user_input["place_type"], locality=user_input["locality"], alert=data["overall_alert"].values[0], indicators=indicators, n_colapse_regions=total_alert_regions[ total_alert_regions.index.isin(["altíssimo", "alto"])].sum(), ) elif "city" in user_input["place_type"]: utils.genKPISection( place_type=user_input["place_type"], locality=user_input["locality"], alert=data["overall_alert"].values[0], indicators=indicators, rt_type=data["rt_place_type"].values[0], ) else: utils.genKPISection( place_type=user_input["place_type"], locality=user_input["locality"], alert=data["overall_alert"].values[0], indicators=indicators, ) # AVAILABLE CAPACITY DISCLAIMER st.write( """ <div class='base-wrapper'> <i>* Utilizamos %s% do total de leitos UTI reportados por %s em %s para cálculo da projeção de dias para atingir capacidade máxima.<br><b>Para municípios, utilizamos os recursos da respectiva regional de saúde.</b> Leitos enfermaria contém os tipos: cirúrgicos, clínicos e hospital-dia; sendo considerado %s% já ocupado.</i> </div> """ % ( str( int(config["br"]["simulacovid"] ["resources_available_proportion"] * 100)), user_input["author_number_beds"], user_input["last_updated_number_beds"], str( int(config["br"]["simulacovid"] ["resources_available_proportion"] * 100)), ), unsafe_allow_html=True, ) # TODO: remove comment on this later! # utils.gen_pdf_report() # INDICATORS PLOTS if st.button("Confira a evolução de indicadores-chave"): opening_response = user_analytics.log_event("picked key_indicators", dict()) if st.button("Esconder"): pass st.write( f""" <div class="base-wrapper"> <span class="section-header primary-span">CÁLCULO DA TAXA DE CONTÁGIO EM {user_input["locality"]}</span> <br><br> <b>A taxa de contágio, conhecida como número de reprodução efetivo (Rt), traduz a dinâmica de disseminação da Covid-19 a cada dia.</b> <br>O valor pode ser lido como o número médio de novas infecções diárias causadas por uma única pessoa infectada. Para mais informações, visite a página de Modelos no menu lateral. </div> """, unsafe_allow_html=True, ) try: fig2 = plots.plot_rt_wrapper(user_input[user_input["place_type"]], user_input["place_type"], config) st.plotly_chart(fig2, use_container_width=True) except: st.write( """<div class="base-wrapper"><b>Seu município, regional ou estado não possui mais de 30 dias de dados de casos confirmados.</b>""", unsafe_allow_html=True, ) st.write( "<div class='base-wrapper'><i>Em breve:</i> gráficos de subnotificação e média móvel (últimos 7 dias) de novos casos por 100k habitantes.</div>", unsafe_allow_html=True, ) utils.stylizeButton( name="Confira a evolução de indicadores-chave", style_string= """border: 1px solid var(--main-white);box-sizing: border-box;border-radius: 15px; width: auto;padding: 0.5em;text-transform: uppercase;font-family: var(--main-header-font-family);color: var(--main-white);background-color: var(--main-primary);font-weight: bold;text-align: center;text-decoration: none;font-size: 18px;animation-name: fadein;animation-duration: 3s;margin-top: 1em;""", session_state=session_state, ) # AMBASSADOR SECTION utils.gen_ambassador_section() # PDF-REPORT GEN BUTTON # if st.button("Gerar Relatório PDF"): # user_analytics.log_event("generated pdf") # st.write( # """<div class="base-wrapper">Aguarde um momento por favor...</div>""", # unsafe_allow_html=True, # ) # st.markdown( # pdfgen.gen_pdf_report(user_input, indicators, data, config), # unsafe_allow_html=True, # ) # TOOLS products = ProductCards utils.genProductsSection(products) # SELECTION BUTTONS # TODO: limpar esse código! está 100% repetido!!! if session_state.continuation_selection is None: session_state.continuation_selection = [False, False, False, False] simula_button_name = "Clique Aqui" # Simula covid 0space saude_button_name = "Clique Aqui " # Saude em ordem 1space distancia_button_name = "Clique_Aqui" # Distanciamento social onda_button_name = "Clique_Aqui " # onda covid if st.button(simula_button_name): # SIMULA session_state.continuation_selection = [True, False, False, False] if st.button(distancia_button_name): # DISTANCIAMENTO session_state.continuation_selection = [False, True, False, False] if st.button(saude_button_name): # SAUDE session_state.continuation_selection = [False, False, True, False] if st.button(onda_button_name): # ONDA session_state.continuation_selection = [False, False, False, True] utils.stylizeButton( name=simula_button_name, style_string="""border: 1px solid black;""", session_state=session_state, others={"ui_binSelect": 1}, ) utils.stylizeButton( name=distancia_button_name, style_string="""border: 1px solid black;""", session_state=session_state, others={"ui_binSelect": 2}, ) utils.stylizeButton( name=saude_button_name, style_string="""border: 1px solid black;""", session_state=session_state, others={"ui_binSelect": 3}, ) utils.stylizeButton( name=onda_button_name, style_string="""border: 1px solid black;""", session_state=session_state, others={"ui_binSelect": 4}, ) if session_state.continuation_selection[0]: user_analytics.safe_log_event( "picked simulacovid", session_state, event_args={ "state": session_state.state_name, "health_region": session_state.health_region_name, "city": session_state.city_name, }, alternatives=[ "picked saude_em_ordem", "picked simulacovid", "picked onda", "picked distanciamento", ], ) # Downloading the saved data from memory sm.main(user_input, indicators, data, config, session_state) # TODO: remove comment on this later! # utils.gen_pdf_report() elif session_state.continuation_selection[1]: user_analytics.safe_log_event( "picked distanciamento", session_state, event_args={ "state": session_state.state_name, "health_region": session_state.health_region_name, "city": session_state.city_name, }, alternatives=[ "picked saude_em_ordem", "picked simulacovid", "picked onda", "picked distanciamento", ], ) ds.main(user_input, indicators, data, config, session_state) elif session_state.continuation_selection[2]: user_analytics.safe_log_event( "picked saude_em_ordem", session_state, event_args={ "state": session_state.state_name, "health_region": session_state.health_region_name, "city": session_state.city_name, }, alternatives=[ "picked saude_em_ordem", "picked simulacovid", "picked onda", "picked distanciamento", ], ) so.main(user_input, indicators, data, config, session_state) elif session_state.continuation_selection[3]: user_analytics.safe_log_event( "picked onda", session_state, event_args={ "state": session_state.state_name, "health_region": session_state.health_region_name, "city": session_state.city_name, }, alternatives=[ "picked saude_em_ordem", "picked simulacovid", "picked onda", "picked distanciamento", ], ) oc.main(user_input, indicators, data, config, session_state) # BIG TABLE gen_big_table(config, dfs, user_input["state_name"]) # FOOTER utils.gen_whatsapp_button(config["impulso"]["contact"]) utils.gen_footer() user_analytics.conclude_user_session(session_state)
if not best_acc or acc > best_acc: with open(MODEL_PATH % (dev_loss, acc), 'wb') as f: torch.save(model, f) best_acc = acc stop_counter = 0 else: for param_group in optimizer.param_groups: param_group['lr'] = param_group['lr'] * 0.2 if EARLY_STOP != 0: stop_counter += 1 return stop_counter dictionary = utils.Dictionary(path=DICT_PATH) n_token = len(dictionary) best_dev_loss = None best_acc = None model = Classifier({ 'dropout': DROPOUT, 'n_tokens': n_token, 'n_layers': N_LAYERS, 'hidden_dim': HIDDEN_DIM, 'embed_dim': EMBED_DIM, 'pooling': POOLING, 'dictionary': dictionary, 'pretrained_wordvec': PRETRAINED_WORDVEC,
def main(session_state): # GOOGLE ANALYTICS SETUP if os.getenv("IS_DEV") == "FALSE": utils.setup_google_analytics() # Amplitude: Get user info user_analytics = amplitude.gen_user(utils.get_server_session()) opening_response = user_analytics.safe_log_event("opened farol", session_state, is_new_page=True) config = yaml.load(open("configs/config.yaml", "r"), Loader=yaml.FullLoader) utils.localCSS("style.css") st.write( """<iframe src="https://www.googletagmanager.com/ns.html?id=GTM-MKWTV7X" height="0" width="0" style="display:none;visibility:hidden"></iframe>""", unsafe_allow_html=True, ) utils.genHeroSection( title1="Farol", title2="Covid", subtitle="Entenda e controle a Covid-19 em sua cidade e estado.", logo="https://i.imgur.com/CkYDPR7.png", header=True, explain=True) if os.getenv("IS_HEROKU") == "TRUE": urlpath = os.getenv("urlpath") elif os.getenv("IS_DEV") == "TRUE": urlpath = 'http://localhost:8501/' else: urlpath = 'https://farolcovid.coronacidades.org/' # urlpath = 'http://localhost:8501/' vaccine_logo = utils.load_image("imgs/vaccine.png") st.write( f"""<div> <div class="base-wrapper flex flex-column" style="background-color:#0090A7"> <div class="white-span header p1" style="font-size:30px;"><img class="icon-cards" src="data:image/png;base64,{vaccine_logo}" alt="Fonte: Impulso">QUER SABER MAIS SOBRE A VACINAÇÃO?</div> <span class="white-span">Acompanhe nossos novos dados e descobra como avança a vacinação no seu município ou estado!<br><br> <a class="btn-ambassador" href="{urlpath}?page=4" target="_self"> Veja aqui! </a> <br><br><span class="white-span">Saiba quando podemos controlar a pandemia no Brasil no nosso estudo realizado com dados inéditos obtidos pela Lei de Acesso à Informação.<br><br> <a class="btn-ambassador" href="{urlpath}?page=3" target="_self"> Ler aqui! </a> </div>""", unsafe_allow_html=True, ) st.write( """ <div class="base-wrapper primary-span"> <span class="section-header">Selecione seu estado ou município no mapa abaixo:</span> </div>""", unsafe_allow_html=True, ) # PEGA BASE DA API # GET DATA dfs, cnes_sources = get_data(config) map_url = "https://helper.coronacidades.org/" col1, col2 = st.beta_columns([0.6, 0.35]) with col2: # REGIAO/CIDADE SELECAO USUARIO # REGION/CITY USER INPUT user_input = dict() user_input["state_name"] = st.selectbox( "Estado", utils.filter_place(dfs, "state")) user_input["health_region_name"] = st.selectbox( "Região de Saúde", utils.filter_place(dfs, "health_region", state_name=user_input["state_name"]), ) user_input["city_name"] = st.selectbox( "Município", utils.filter_place( dfs, "city", state_name=user_input["state_name"], health_region_name=user_input["health_region_name"], ), ) changed_city = user_analytics.safe_log_event( "picked farol place", session_state, event_args={ "state": user_input["state_name"], "city": user_input["city_name"] }, ) user_input, data = update_user_input_places(user_input, dfs, config) map_place_id = utils.Dictionary().get_state_alphabetical_id_by_name( user_input["state_name"]) st.write( f""" <div class="brazil-map-div"> <br><br> <iframe id="map-state" src="{map_url}maps/map-iframe?place_id={map_place_id}" class="map-state" scrolling="no"> </iframe> </div> """, unsafe_allow_html=True, ) with col1: # GENERATE MAPS # st.write( # f""" # <div class="brazil-map-div"> # <div class="alert-levels-map-overlay"> # </div> # <div> # <iframe id="map" src="resources/iframe-gen.html?url={map_url}maps/map-iframe?place_id=BR" class="map-br" scrolling="no"> # </iframe> # </div> # </div> # """, # unsafe_allow_html=True, # ) st.write( f""" <div class="brazil-map-div"> <iframe id="map" src="{map_url}maps/map-iframe?place_id=BR" class="map-br" scrolling="no"> </iframe> </div> """, unsafe_allow_html=True, ) # st.write( # f""" # """, # unsafe_allow_html=True, # ) # st.write( # f""" # <iframe id="map-state" src="resources/iframe-gen.html?url={map_url}maps/map-iframe?place_id={map_place_id}" class="map-state" scrolling="no"> # </iframe> # """, # unsafe_allow_html=True, # ) # st.write( # f""" # <div class="selectors-box" id="selectors-box"> # </div> # <iframe src="resources/select-box-mover.html?place_id={user_input["state_name"]}{user_input["health_region_name"]}{user_input["city_name"]}" height="0px"> # </iframe>""", # unsafe_allow_html=True, # ) # SOURCES PARAMS user_input = utils.get_sources(user_input, data, cnes_sources, ["beds", "icu_beds"]) # POPULATION PARAMS try: user_input["population_params"] = { "N": int(data["population"].fillna(0).values[0]), "D": int(data["deaths"].fillna(0).values[0]), "I": int(data["active_cases"].fillna(0).values[0]), "I_confirmed": int(data["confirmed_cases"].fillna(0).values[0]), "I_compare": int(data["confirmed_cases"].fillna(0).values[0]), } except: user_input["population_params"] = { "N": int(data["population"].fillna(0).values[0]), "D": int(data["deaths"].fillna(0).values[0]), "I": 0, "I_confirmed": int(data["confirmed_cases"].fillna(0).values[0]), "I_compare": int(data["confirmed_cases"].fillna(0).values[0]), } user_input["Rt"] = { "best": data["rt_low_95"].values[0], "worst": data["rt_high_95"].values[0], "is_valid": data["rt_most_likely"].apply(str).values[0], } user_input["last_updated_cases"] = data[ "last_updated_subnotification"].max() # Update session values to standard ones if changed city or opened page or reseted values if (session_state.state_name != user_input["state_name"] or session_state.health_region_name != user_input["health_region_name"] or session_state.city_name != user_input["city_name"] or session_state.number_beds is None or session_state.reset): session_state.state_name = user_input["state_name"] session_state.health_region_name = user_input["health_region_name"] session_state.city_name = user_input["city_name"] session_state.state_num_id = user_input["state_num_id"] session_state.health_region_id = user_input["health_region_id"] session_state.city_id = user_input["city_id"] session_state.number_beds = int( user_input["number_beds"] * config["br"]["simulacovid"]["resources_available_proportion"]) session_state.number_icu_beds = int( user_input["number_icu_beds"] * config["br"]["simulacovid"]["resources_available_proportion"]) session_state.number_cases = user_input["population_params"][ "I_confirmed"] session_state.number_deaths = user_input["population_params"]["D"] session_state.reset = True if data["confirmed_cases"].sum() == 0: st.write( f"""<div class="base-wrapper"> Seu município ou Região de Saúde ainda não possui casos reportados oficialmente. Portanto, simulamos como se o primeiro caso ocorresse hoje. <br><br>Caso queria, você pode mudar esse número abaixo: </div>""", unsafe_allow_html=True, ) user_input["population_params"]["I"] = 1 else: infectious_period = ( config["br"]["seir_parameters"]["severe_duration"] + config["br"]["seir_parameters"]["critical_duration"]) placeholder_value_pls_solve_this = 0 # ALERT BANNER # Aqui ele cria uma lista só com os estados que todas as cidades estao sem o overall_alert para criar um alerta para o estado states_list = dfs["city"].groupby(["state_name"]).agg({ "overall_alert": "count", "state_name": "max" }) states_list = states_list.loc[states_list['overall_alert'] < 1] # Adiciona forcadamente MT para a lista states_list = states_list.append( { 'state_name': 'Mato Grosso', 'overall_alert': 0 }, ignore_index=True) states_list = states_list['state_name'].to_list() utils.noOverallalert(user_input, data, states_list) # DIMENSIONS CARDS dimensions = DimensionCards utils.genAnalysisDimmensionsSection(dimensions) # INDICATORS CARDS indicators = IndicatorCards indicators = update_indicators(indicators, data, config, user_input, session_state) data["overall_alert"] = data["overall_alert"].map({ 0: "novo normal", 1: "moderado", 2: "alto", 3: "altíssimo" }) if "state" in user_input["place_type"]: # Add disclaimer to cities in state alert levels total_alert_regions = (dfs["health_region"][ dfs["health_region"]["state_num_id"] == data["state_num_id"].unique()[0]].assign( overall_alert=lambda df: df["overall_alert"].map({ 0: "novo normal", 1: "moderado", 2: "alto", 3: "altíssimo" }))["overall_alert"].value_counts()) utils.genKPISection( place_type=user_input["place_type"], locality=user_input["locality"], alert=data["overall_alert"].values[0], indicators=indicators, n_colapse_regions=total_alert_regions[ total_alert_regions.index.isin(["altíssimo", "alto"])].sum(), ) elif "city" in user_input["place_type"]: utils.genKPISection( place_type=user_input["place_type"], locality=user_input["locality"], alert=data["overall_alert"].values[0], indicators=indicators, rt_type=data["rt_place_type"].values[0], ) else: utils.genKPISection( place_type=user_input["place_type"], locality=user_input["locality"], alert=data["overall_alert"].values[0], indicators=indicators, ) # AVAILABLE CAPACITY DISCLAIMER # TODO -> VOLTAR PARA PROJECAO DE LEITOS # """ # <div class='base-wrapper'> # <i>* Utilizamos 100% do total de leitos UTI reportados por %s em %s # para cálculo da projeção de dias para atingir capacidade máxima.<br><b>Para municípios, utilizamos os recursos da respectiva regional de saúde.</b> # Leitos enfermaria contém os tipos: cirúrgicos, clínicos e hospital-dia; sendo considerado %s% já ocupado.</i> # </div> # """ st.write( """ <div class='base-wrapper' <i>* <b>Vacinação</b> </i> <li>“A porcentagem da população vacinada em seu local” - Total de pessoas que tomaram ao menos uma dose, dividido pelo total da população do local.<br> <li>“Porcentagem da população imunizada” - Total de pessoas que receberam todas as doses recomendadas do imunizante, dividido pelo total da população do local.<br> <li>“Total da população sem vacinar” - Número absoluto de habitantes do local que ainda não recebeu nenhuma dose do imunizante.<br> <i>Para mais detalhes e explicação completa confira nossa página de Metodologia no menu lateral.</i> </div> """, unsafe_allow_html=True, ) st.write( """ <div class='base-wrapper'> <i>* <b>Mudamos o indicador afim de refinarmos ajustes no cálculo de projeção de leitos.</b> Entendemos que a projeção apresentada não capturava a situação da 2ª onda observada nos municípios, regionais e estados, logo substituímos este indicador por ora para revisão dos cálculos. Os valores de referência se baseiam nas estatísticas de países da OCDE, <a target="_blank" style="color:#0068c9;" href="https://docs.google.com/spreadsheets/d/1MKFOHRCSg4KMx5Newi7TYCrjtNyPwMQ38GE1wQ6as70/edit?usp=sharing">veja mais aqui</a></b>. As simulações personalizadas ainda podem ser realizadas através do SimulaCovid mais abaixo.<br> <li> Leitos Enfermaria: Consideramos %s% do total reportado por %s em %s dos tipos Cirúrgico, Clínico e Hospital-dia. Para municípios, utilizamos os recursos da respectiva regional de saúde.<br> <li> Leitos UTI: Consideramos 100% do total de leitos UTI reportado por %s em %s. Para municípios, utilizamos os recursos da respectiva regional de saúde.</i> </div> """ % ( str( int(config["br"]["simulacovid"] ["resources_available_proportion"] * 100)), user_input["author_number_beds"], user_input["last_updated_number_beds"], user_input[ "author_number_icu_beds"], # remover na volta de projecao user_input[ "last_updated_number_icu_beds"], # remover na volta de projecao ), unsafe_allow_html=True, ) # TODO: remove comment on this later! # utils.gen_pdf_report() # INDICATORS PLOTS if st.button("Confira a evolução de indicadores-chave"): opening_response = user_analytics.log_event("picked key_indicators", dict()) if st.button("Esconder"): pass st.write( f""" <div class="base-wrapper"> <span class="section-header primary-span">CÁLCULO DA TAXA DE CONTÁGIO EM {user_input["locality"]}</span> <br><br> <b>A taxa de contágio, conhecida como número de reprodução efetivo (Rt), traduz a dinâmica de disseminação da Covid-19 a cada dia.</b> <br>O valor pode ser lido como o número médio de novas infecções diárias causadas por uma única pessoa infectada. Para mais informações, visite a página de Modelos no menu lateral. </div> """, unsafe_allow_html=True, ) try: fig2 = plots.plot_rt_wrapper(user_input[user_input["place_type"]], user_input["place_type"], config) st.plotly_chart(fig2, use_container_width=True) except: st.write( """<div class="base-wrapper"><b>Seu município, regional ou estado não possui mais de 30 dias de dados de casos confirmados.</b>""", unsafe_allow_html=True, ) st.write( "<div class='base-wrapper'><i>Em breve:</i> gráficos de subnotificação e média móvel (últimos 7 dias) de novos casos por 100k habitantes.</div>", unsafe_allow_html=True, ) utils.stylizeButton( name="Confira a evolução de indicadores-chave", style_string= """border: 1px solid var(--main-white);box-sizing: border-box;border-radius: 15px; width: auto;padding: 0.5em;text-transform: uppercase;font-family: var(--main-header-font-family);color: var(--main-white);background-color: var(--main-primary);font-weight: bold;text-align: center;text-decoration: none;font-size: 18px;animation-name: fadein;animation-duration: 3s;margin-top: 1em;""", session_state=session_state, ) # AMBASSADOR SECTION utils.gen_ambassador_section() # PDF-REPORT GEN BUTTON # if st.button("Gerar Relatório PDF"): # user_analytics.log_event("generated pdf") # st.write( # """<div class="base-wrapper">Aguarde um momento por favor...</div>""", # unsafe_allow_html=True, # ) # st.markdown( # pdfgen.gen_pdf_report(user_input, indicators, data, config), # unsafe_allow_html=True, # ) # TOOLS products = ProductCards utils.genProductsSection(products) # SELECTION BUTTONS # TODO: limpar esse código! está 100% repetido!!! if session_state.continuation_selection is None: session_state.continuation_selection = [False, False, False, False] simula_button_name = "Clique Aqui" # Simula covid 0space saude_button_name = "Clique Aqui " # Saude em ordem 1space distancia_button_name = "Clique_Aqui" # Distanciamento social onda_button_name = "Clique_Aqui " # onda covid if st.button(simula_button_name): # SIMULA session_state.continuation_selection = [True, False, False, False] if st.button(distancia_button_name): # DISTANCIAMENTO session_state.continuation_selection = [False, True, False, False] if st.button(saude_button_name): # SAUDE session_state.continuation_selection = [False, False, True, False] if st.button(onda_button_name): # ONDA session_state.continuation_selection = [False, False, False, True] utils.stylizeButton( name=simula_button_name, style_string="""border: 1px solid black;""", session_state=session_state, others={"ui_binSelect": 1}, ) utils.stylizeButton( name=distancia_button_name, style_string="""border: 1px solid black;""", session_state=session_state, others={"ui_binSelect": 2}, ) utils.stylizeButton( name=saude_button_name, style_string="""border: 1px solid black;""", session_state=session_state, others={"ui_binSelect": 3}, ) utils.stylizeButton( name=onda_button_name, style_string="""border: 1px solid black;""", session_state=session_state, others={"ui_binSelect": 4}, ) if session_state.continuation_selection[0]: user_analytics.safe_log_event( "picked simulacovid", session_state, event_args={ "state": session_state.state_name, "health_region": session_state.health_region_name, "city": session_state.city_name, }, alternatives=[ "picked saude_em_ordem", "picked simulacovid", "picked onda", "picked distanciamento", ], ) # Downloading the saved data from memory sm.main(user_input, indicators, data, config, session_state) # TODO: remove comment on this later! # utils.gen_pdf_report() elif session_state.continuation_selection[1]: user_analytics.safe_log_event( "picked distanciamento", session_state, event_args={ "state": session_state.state_name, "health_region": session_state.health_region_name, "city": session_state.city_name, }, alternatives=[ "picked saude_em_ordem", "picked simulacovid", "picked onda", "picked distanciamento", ], ) ds.main(user_input, indicators, data, config, session_state) elif session_state.continuation_selection[2]: user_analytics.safe_log_event( "picked saude_em_ordem", session_state, event_args={ "state": session_state.state_name, "health_region": session_state.health_region_name, "city": session_state.city_name, }, alternatives=[ "picked saude_em_ordem", "picked simulacovid", "picked onda", "picked distanciamento", ], ) so.main(user_input, indicators, data, config, session_state) elif session_state.continuation_selection[3]: user_analytics.safe_log_event( "picked onda", session_state, event_args={ "state": session_state.state_name, "health_region": session_state.health_region_name, "city": session_state.city_name, }, alternatives=[ "picked saude_em_ordem", "picked simulacovid", "picked onda", "picked distanciamento", ], ) oc.main(user_input, indicators, data, config, session_state) # CHAMA FUNCAO QUE GERA TABELA ID big_table # CALL FUNCTION TO GENERATE ID big_table gen_big_table(config, dfs, user_input["state_name"]) # CHAMA FUNCOES DO UTILS PARA O FOOTER # CALL FUNCTIONS IN UTILS TO FOOTER utils.gen_whatsapp_button(config["impulso"]["contact"]) utils.gen_footer() user_analytics.conclude_user_session(session_state)
def main(user_input, indicators, data, config, session_state): utils.genHeroSection( title1="Onda", title2="Covid", subtitle= "Veja e compare a evolução da curva de contágio da Covid-19 em seu estado ou município.", logo="https://i.imgur.com/Oy7IiGB.png", header=False) try: # load data # print("loading br cases") br_cases = loading_cached() # print("finished laoding br cases") my_dict = utils.Dictionary() # ONDA POR ESTADO da.prepare_heatmap(br_cases, place_type="state_id") st.write("") pass except Exception as e: st.write(str(e)) # ONDA POR MUNICIPIO st.write( """ <div class="base-wrapper"> <span class="section-header primary-span">ONDA MORTES DIÁRIAS POR MUNICÍPIO</span> <br><br> <span class="ambassador-question"><b>Selecione seu estado e município para prosseguir</b></span> </div>""", unsafe_allow_html=True, ) dfs, places_ids = get_data(loader.config) state_name = st.selectbox("Estado ", utils.filter_place(dfs, "state")) city_name = st.selectbox( "Município ", utils.filter_place(dfs, "city", state_name=state_name, health_region_name="Todos"), ) deaths_or_cases = (st.selectbox( "Qual análise você quer ver: Número de mortes ou Taxa de letalidade (mortes por casos)?", ["Mortes", "Letalidade"]) == "Mortes por casos") # print("checking") if city_name != "Todos": # the user selected something # print("passed") br_cases = br_cases[br_cases["state_name"] == state_name] # .reset_index() # gen_banners() uf = my_dict.get_state_alphabetical_id_by_name(state_name) da.prepare_heatmap( br_cases, place_type="city_name", group=uf, your_city=city_name, deaths_per_cases=deaths_or_cases, ) # print("finished preparation") # ONDA POR PAÍS st.write("") da.prepare_heatmap( loader.read_data( "br", loader.config, endpoint=config["br"]["api"]["endpoints"]["analysis"]["owid"], ), place_type="country_pt", )
def admin_handler(bot, call, gl): if call.message: cid = call.message.chat.id spl_data = call.data.split() reason = spl_data[0].split('=')[1] kb = telebot.types.InlineKeyboardMarkup(row_width=4) if reason == 'stats': pass if reason == 'channels': if len(spl_data) < 2: b1 = telebot.types.InlineKeyboardButton("Promote Post", callback_data='admin=channels promote_post=True') b2 = telebot.types.InlineKeyboardButton("Publish Channels", callback_data='admin=channels publish_channels=True') b3 = telebot.types.InlineKeyboardButton("Update Channels List", callback_data='admin=channels update_ch_list=True') kb.row(b1, b2) kb.add(b3) return bot.edit_message_text("Choose an Option:", cid, call.message.message_id, call.id, reply_markup=kb) else: func = spl_data[1].split('=')[0] if func == 'publish_channels': arg = spl_data[1].split('=')[1] if arg == 'True': all_channels = channels.search({'channel_tier': {'$ne': None}}) bts = [] kb = telebot.types.InlineKeyboardMarkup(row_width=2) for i in all_channels: btn = telebot.types.InlineKeyboardButton(i['channel_name'], callback_data='admin=channels ' 'publish_channels=%d' % i['channel_id']) bts.append(btn) kb.add(*bts) back = telebot.types.InlineKeyboardButton("🔙", callback_data='admin=channels') kb.add(back) txt = 'Publish channels by tapping the button' return bot.edit_message_text(txt, chat_id=cid, message_id=call.message.message_id, parse_mode='markdown', reply_markup=kb) else: channel = channels.get({'channel_id': int(arg)}) if channel['channel_private_link'] is None: if channel['channel_username'] is None: txt = 'Channel {} missing Link'.format(channel['channel_name']) return bot.answer_callback_query(call.id, text=txt, show_alert=True) capt = '📢 %(hch)s%(ch_name)s \n\n🏷 %(desc)s' % { 'hch': '👁🗨' if channel['channel_id'] in config.CHANNELS else '', 'ch_name': channel['channel_name'], 'desc': channel['channel_info'][:(191 - len(channel['channel_name']))] if channel['channel_info'] is not None else ''} rating = '(+18)' if '#explicit' in channel['channel_tags'] else '(+16)' if \ '#questionable' in channel['channel_tags'] else '' s = bot.send_photo(chat_id=config.PUB_CHANNEL, photo=channel['channel_profile_pic'], caption=capt, disable_notification=True).wait() if isinstance(s, tuple): print(s) txt = 'Channel {} with Invalid Profile Pic.'.format(channel['channel_name']) show_alert = True else: join_btn = telebot.types.InlineKeyboardButton('Join Now! ' + rating, url=channel['channel_private_link'] if channel[ 'channel_private_link'] is not None else 't.me/' + channel['channel_username']) header = '**Join Now!**'.replace(" ", "%20") text = '\nJoin now __{0}__, an amazing channel!\n\n' \ 't.me/HalksPUB/{1}'.format(channel['channel_name'], s.message_id).replace( "/", "%2F").replace("?", "%3F").replace(" ", "%20").replace( "\n", "%0A").replace(",", "%2C").replace("=", "%3D").replace("+", "%2B") url = 'https://t.me/share/url?url={0}&text={1}'.format(header, text) share_btn = telebot.types.InlineKeyboardButton("Share with Friends!", url=url) kb.add(share_btn) kb.add(join_btn) bot.edit_message_reply_markup(chat_id=config.PUB_CHANNEL, message_id=s.message_id, reply_markup=kb) txt = 'Channel {} Published'.format(channel['channel_name']) show_alert = None channels.update({'channel_id': int(arg)}, {'$set': {'pub_id': s.message_id}}) return bot.answer_callback_query(call.id, text=txt, show_alert=show_alert) elif func == 'update_ch_list': bot.answer_callback_query(call.id, 'Updating channels...') sfw_channels = channels.search({'channel_tier': 'SFW'}) nsfw_channels = channels.search({'channel_tier': 'NSFW'}) other_channels = channels.search({'channel_tier': 'OTHER'}) other_txt = """\` [👁🗨](t.me/halksnet)_@Hαlks_*NET* _Eastern Media Network_ *Cosplays, Asians & Others*\n\n""" nsfw_txt = """\` [👁🗨](t.me/halksnet)_@Hαlks_*NET* _Eastern Media Network_ *Hentai, Ecchi and kinky anime*\n\n""" sfw_txt = """\` [👁🗨](t.me/halksnet)_@Hαlks_*NET* _Eastern Media Network_ *Anime artworks, news & fanbase:*\n\n""" ot = [] for i in other_channels: t = '%(view)s [%(rt)s %(ch_halk)s %(ch_name)s](%(ch_link)s)' % { 'ch_halk': '👁🗨' if i['channel_id'] in config.CHANNELS else '', 'ch_link': i['channel_private_link'] if i['channel_private_link'] is not None else 't.me/' + i['channel_username'], 'ch_name': i['channel_name'], 'rt': '🔞' if '#explicit' in i['channel_tags'] else '', 'view': '[|👁|](t.me/HalksPUB/%s)' % i['pub_id'] if 'pub_id' in i else '' } ot.append(t) other_txt += '\n'.join(ot) + '\n\n📋_Channels with 👁🗨 are Hαlk\'s Franchise Channels._\n' \ 'ℹ️ @HalksNET' sf = [] for i in sfw_channels: t = '%(view)s [%(ch_halk)s %(ch_name)s](%(ch_link)s)' % { 'ch_halk': '👁🗨' if i['channel_id'] in config.CHANNELS else '', 'ch_link': i['channel_private_link'] if i['channel_private_link'] is not None else 't.me/' + i['channel_username'], 'ch_name': i['channel_name'], 'view': '[|👁|](t.me/HalksPUB/%s)' % i['pub_id'] if 'pub_id' in i else '' } sf.append(t) sfw_txt += '\n'.join(sf) + '\n\n📋_Channels with 👁🗨 are Hαlk\'s Franchise Channels._\n' \ 'ℹ️ @HalksNET' nsf = [] for i in nsfw_channels: t = '%(view)s [%(rt)s %(ch_halk)s %(ch_name)s](%(ch_link)s)' % { 'ch_halk': '👁🗨' if i['channel_id'] in config.CHANNELS else '', 'ch_link': i['channel_private_link'] if i['channel_private_link'] is not None else 't.me/' + i['channel_username'], 'ch_name': i['channel_name'], 'rt': '🔞' if '#explicit' in i['channel_tags'] else '', 'view': '[|👁|](t.me/HalksPUB/%s)' % i['pub_id'] if 'pub_id' in i else '' } nsf.append(t) nsfw_txt += '\n'.join(nsf) + '\n\n📋_Channels with 👁🗨 are Hαlk\'s Franchise Channels._\n' \ 'ℹ️ @HalksNET' with open('etc/published_list.json', 'r') as r: updt_msg = json.loads(r.read()) if updt_msg.get('sfw_mid', None) is None: sfw_mid = bot.send_message(config.HALKSNET_CHANNEL, sfw_txt, parse_mode='markdown').wait() else: sfw_mid = bot.edit_message_text(text=sfw_txt, chat_id=config.HALKSNET_CHANNEL, message_id=updt_msg.get('sfw_mid', None), parse_mode='markdown').wait() header = '**Take a Look!**'.replace( "/", "%2F").replace("?", "%3F").replace(" ", "%20").replace( "\n", "%0A").replace(",", "%2C").replace("=", "%3D") text = '\nWe have the best anime media right here! Join us, and see our channels!\n\n' \ 't.me/HalksNET/{0}'.format(updt_msg.get('other_mid')).replace( "/", "%2F").replace("?", "%3F").replace(" ", "%20").replace( "\n", "%0A").replace(",", "%2C").replace("=", "%3D") url = 'https://t.me/share/url?url={0}&text={1}'.format(header, text) kb = telebot.types.InlineKeyboardMarkup(row_width=1) kb.add(telebot.types.InlineKeyboardButton("Share these Channels!", url=url)) bot.edit_message_reply_markup(chat_id=config.HALKSNET_CHANNEL, message_id=sfw_mid.message_id, reply_markup=kb) if isinstance(sfw_mid, tuple): # 'not updated message' pass else: updt_msg.update({'sfw_mid': sfw_mid.message_id}) if updt_msg.get('nsfw_mid', None) is None: nsfw_mid = bot.send_message(config.HALKSNET_CHANNEL, nsfw_txt, parse_mode='markdown').wait() else: nsfw_mid = bot.edit_message_text(text=nsfw_txt, chat_id=config.HALKSNET_CHANNEL, message_id=updt_msg.get('nsfw_mid', None), parse_mode='markdown').wait() header = '**Take a Look!**'.replace( "/", "%2F").replace("?", "%3F").replace(" ", "%20").replace( "\n", "%0A").replace(",", "%2C").replace("=", "%3D") text = '\nWe have the best anime lewds! Join us, and see our channels!\n\n' \ 't.me/HalksNET/{0}'.format(updt_msg.get('nsfw_mid')).replace( "/", "%2F").replace("?", "%3F").replace(" ", "%20").replace( "\n", "%0A").replace(",", "%2C").replace("=", "%3D") url = 'https://t.me/share/url?url={0}&text={1}'.format(header, text) kb = telebot.types.InlineKeyboardMarkup(row_width=1) kb.add(telebot.types.InlineKeyboardButton("Share these Channels!", url=url)) bot.edit_message_reply_markup(chat_id=config.HALKSNET_CHANNEL, message_id=nsfw_mid.message_id, reply_markup=kb) if isinstance(nsfw_mid, tuple): # 'not updated message' pass else: updt_msg.update({'nsfw_mid': nsfw_mid.message_id}) if updt_msg.get('other_mid', None) is None: other_mid = bot.send_message(config.HALKSNET_CHANNEL, other_txt, parse_mode='markdown').wait() else: other_mid = bot.edit_message_text(text=other_txt, chat_id=config.HALKSNET_CHANNEL, message_id=updt_msg.get('other_mid', None), parse_mode='markdown').wait() header = '**Take a Look!**'.replace("/", "%2F").replace("?", "%3F").replace( " ", "%20").replace("\n", "%0A").replace(",", "%2C").replace("=", "%3D") text = '\nWe have some good Eastern stuff right here! Join us, and see our channels!\n\n' \ 't.me/HalksNET/{0}'.format(updt_msg.get('other_mid')).replace( "/", "%2F").replace("?", "%3F").replace(" ", "%20").replace( "\n", "%0A").replace(",", "%2C").replace("=", "%3D") url = 'https://t.me/share/url?url={0}&text={1}'.format(header, text) kb = telebot.types.InlineKeyboardMarkup(row_width=1) kb.add(telebot.types.InlineKeyboardButton("Share these Channels!", url=url)) bot.edit_message_reply_markup(chat_id=config.HALKSNET_CHANNEL, message_id=other_mid.message_id, reply_markup=kb) if isinstance(other_mid, tuple): # 'not updated message' pass else: updt_msg.update({'other_mid': other_mid.message_id}) cover_msg = """\` [👁🗨](t.me/halksnet)_@Hαlks_*NET* _Eastern Media Network_ The best, hand selected Eastern (_Nippon_) based channels. We have selected channels, for your joy! _See our lists_: [▪️ Anime Artworks, news & fanbase](https://t.me/HalksNET/%(sfw)s) [▪️ Hentai, Ecchi & Kinky Anime](https://t.me/HalksNET/%(nsfw)s) [▪️ Cosplays, Asians & Others](https://t.me/HalksNET/%(other)s) _Come join us now! (っ´▽`)っ_""" % {'sfw': updt_msg.get('sfw_mid', None), 'nsfw': updt_msg.get('nsfw_mid', None), 'other': updt_msg.get('other_mid', None)} if updt_msg.get('cover', None) is None: cover = bot.send_message(config.HALKSNET_CHANNEL, cover_msg, parse_mode='markdown').wait() else: cover = bot.edit_message_text(text=cover_msg, chat_id=config.HALKSNET_CHANNEL, message_id=updt_msg.get('cover', None), parse_mode='markdown').wait() kb = telebot.types.InlineKeyboardMarkup(row_width=1) bt1 = telebot.types.InlineKeyboardButton("See our Publisher!", url='https://t.me/HalksPUB') bt2 = telebot.types.InlineKeyboardButton("Join your Channel!", callback_data='join_channel=True') kb.add(bt2) kb.add(bt1) bot.edit_message_reply_markup(chat_id=config.HALKSNET_CHANNEL, message_id=updt_msg.get('cover', None), reply_markup=kb) if isinstance(cover, tuple): # 'not updated message' pass else: updt_msg.update({'cover': cover.message_id}) with open('etc/published_list.json', 'w') as r: dump = json.dumps(updt_msg) r.write(dump) return elif func == 'promote_post': sfw_channels = channels.search({'channel_tier': 'SFW'}) nsfw_channels = channels.search({'channel_tier': 'NSFW'}) other_channels = channels.search({'channel_tier': 'OTHER'}) other_txt = """\` [👁🗨](t.me/halksnet)_@Hαlks_*NET* _Eastern Media Network_ We have the best cosplays, and other Eastern media for you! *Check these out:*\n\n""" nsfw_txt = """\` [👁🗨](t.me/halksnet)_@Hαlks_*NET* _Eastern Media Network_ We have the best and most exciting hentai and ecchi for you! *Check these out:*\n\n""" sfw_txt = """\` [👁🗨](t.me/halksnet)_@Hαlks_*NET* _Eastern Media Network_ We have the best anime and Japanese media channels for you! *Check these out:*\n\n""" ot = [] for i in other_channels: t = '▪️ [%(rt)s %(ch_name)s](%(ch_link)s)' % { 'ch_link': i['channel_private_link'] if i['channel_private_link'] is not None else 't.me/' + i['channel_username'], 'ch_name': i['channel_name'], 'rt': '🔞' if '#explicit' in i['channel_tags'] else '' } ot.append(t) other_txt += '\n'.join(ot) sf = [] for i in sfw_channels: t = '▪️ [%(ch_name)s](%(ch_link)s)' % { 'ch_link': i['channel_private_link'] if i['channel_private_link'] is not None else 't.me/' + i['channel_username'], 'ch_name': i['channel_name'] } sf.append(t) sfw_txt += '\n'.join(sf) nsf = [] for i in nsfw_channels: t = '▪️ [%(rt)s %(ch_name)s](%(ch_link)s)' % { 'ch_link': i['channel_private_link'] if i['channel_private_link'] is not None else 't.me/' + i['channel_username'], 'ch_name': i['channel_name'], 'rt': '🔞' if '#explicit' in i['channel_tags'] else '' } nsf.append(t) nsfw_txt += '\n'.join(nsf) import time kb = telebot.types.InlineKeyboardMarkup() b1 = telebot.types.InlineKeyboardButton("👁🗨 Join us now!", url='t.me/HalksNET') kb.add(b1) for channel in sfw_channels: bot.send_message(channel['channel_id'], sfw_txt, parse_mode='markdown', reply_markup=kb).wait() time.sleep(1) for channel in nsfw_channels: bot.send_message(channel['channel_id'], nsfw_txt, parse_mode='markdown', reply_markup=kb).wait() time.sleep(1) for channel in other_channels: bot.send_message(channel['channel_id'], other_txt, parse_mode='markdown', reply_markup=kb).wait() time.sleep(1) return if reason == 'broadcast': pass if reason == 'admin_broadcast': msg = spl_data[1].split('=')[1] if msg == 'waiting': txt = 'Please, send the message title be sent to admins.' gl.send_admin_message = utils.Dictionary({'queue': 'title', 'message': utils.Dictionary({ 'type': None, 'caption': None, 'text': None, 'file_id': None, 'title': None })}) return bot.edit_message_text(txt, cid, call.message.message_id, call.id) if reason == 'add_networkers': # This part is to know if the call stack for adding admins was previously made. # Here, we get the whole deep link cache. cache_view = deep_link_cache.view() # Here, we get all deep link calls that have the 'add_admin' call ly = {i: cache_view[i]['data'] for i in cache_view if 'call' in cache_view[i]['data'] and cache_view[i]['data']['call'] == 'add_networker'} # Finally, generates the code if the editing channel has not been previously cached to add admin; uses # The previous code otherwise. codes = [i for i in ly] code = codes[0] if len(ly) > 0 else utils.str_generator(8) label = '**Join Us!**' ttxt = '\n' \ 'Become now a part of our network by clicking on this following link:\n' \ 't.me/LilianRobot?start=%s' % code l_txt = 'https://t.me/share/url?url={label}&text={txt}'.format( label=label.replace(" ", "%20"), txt=ttxt.replace(" ", "%20").replace("/", "%2F").replace(":", "%3A").replace("?", "%3F"). replace("=", "%3D").replace('\n', '%0A')) txt = '[Click Here and share](%s) the invite.\n\n' \ 'Remember, this link will automatically expire in height hours, and will no longer be available' \ ' to add new admins.' % l_txt if code not in ly: deep_link_cache.add(code, {'call': 'add_networker'}, (8 * 60 * 60)) bot.send_message(chat_id=cid, text=txt, parse_mode='markdown')
def main(session_state): # ==== GOOGLE ANALYTICS SETUP ==== GOOGLE_ANALYTICS_CODE = os.getenv("GOOGLE_ANALYTICS_CODE") if GOOGLE_ANALYTICS_CODE: import pathlib from bs4 import BeautifulSoup GA_JS = (""" window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', '%s'); """ % GOOGLE_ANALYTICS_CODE) index_path = pathlib.Path(st.__file__).parent / "static" / "index.html" soup = BeautifulSoup(index_path.read_text(), features="lxml") if not soup.find(id="google-analytics-loader"): script_tag_import = soup.new_tag( "script", src="https://www.googletagmanager.com/gtag/js?id=%s" % GOOGLE_ANALYTICS_CODE, ) soup.head.append(script_tag_import) script_tag_loader = soup.new_tag("script", id="google-analytics-loader") script_tag_loader.string = GA_JS soup.head.append(script_tag_loader) index_path.write_text(str(soup)) # ==== # Amplitude: Get user info user_analytics = amplitude.gen_user(utils.get_server_session()) opening_response = user_analytics.safe_log_event("opened farol", session_state, is_new_page=True) utils.localCSS("style.css") utils.genHeroSection( title1="Farol", title2="Covid", subtitle="Entenda e controle a Covid-19 em sua cidade e estado.", logo="https://i.imgur.com/CkYDPR7.png", header=True) config = yaml.load(open("configs/config.yaml", "r"), Loader=yaml.FullLoader) #TEMPORARY BANNER FC st.write( """ <div> <div class="base-wrapper flex flex-column" style="background-color:#0090A7"> <div class="white-span header p1" style="font-size:30px;">O FAROLCOVID ESTÁ DE CARA NOVA!</div> <span class="white-span">Aprimoramos a plataforma e adicionamos novas ferramentas para acompanhamento da crise da Covid-19 no Brasil. <b>Que tal explorar com a gente?</b></span> <br><div style="margin-top: 15px;"></div> <div> <a href="#novidades" class="info-btn">Entenda como navegar</a> </div> <div id="novidades" class="nov-modal-window"> <div> <a href="#" title="Close" class="info-btn-close" style="color: white;">×</a> <div style="margin: 10px 15px 15px 15px;"> <h1 class="primary-span">Saiba como cada ferramenta apoia a resposta ao coronavírus</h1> <p class="darkblue-span uppercase"> <b>Farol Covid</b> </p> <img class="img-modal" src=%s alt="Ícone Farol Covid"> <div> <p> Acompanhe as 4 dimensões:</p> - Situação da Doença (número de novos casos por habitante);</br> - Controle da Doença (ritmo de contágio)</br> - Capacidade do sistema (número de leitos e capacidade UTI)</br> - Confiança de dados (taxa de subnotificação)</br> <p> E descubra o nível de alerta do estado, regional de saúde ou município.</p> </div> <div> <p class="darkblue-span uppercase"> <b>SimulaCovid</b> </p> <img class="img-modal" src=%s alt="Ícone SimulaCovid"> <p style="height:100px;">Simule o que pode acontecer com o sistema de saúde local se o ritmo de contágio aumentar ou diminuir e planeje suas ações para evitar a sobrecarga hospitalar.</p> </div> <div> <p class="darkblue-span uppercase"> <b>Distanciamento Social</b> </p> <img class="img-modal" src=%s alt="Ícone Distanciamento Social"> <p style="height:100px;">Acompanhe a atualização diária do índice e descubra como está a circulação de pessoas e o distanciamento social no seu estado ou município. </p> </div> <div> <p class="darkblue-span uppercase"> <b>Saúde em Ordem</b> </p> <img class="img-modal" src=%s alt="Ícone Saúde em Ordem"> <p> Entenda quais atividades deveriam reabrir primeiro na sua região, considerando: </p> - Segurança Sanitária: quais setores trazem menor risco de exposição à Covid-19 para os trabalhadores.</br> - Contribuição Econômica: quais setores movimentam mais a economia daquele estado ou regional de saúde.</br> <p> </p> </div> <div> <p class="darkblue-span uppercase"> <b>Onda Covid</b> </p> <img class="img-modal" src=%s alt="Ícone Onda Covid"> <p>Com base no número de óbitos de Covid-19 registrados, acompanhe se seu município já saiu do pico da doença. </p> </div> </div> </div> </div> </div>""" % (config["br"]["icons"]["farolcovid_logo"], config["br"]["icons"]["simulacovid_logo"], config["br"]["icons"]["distanciamentosocial_logo"], config["br"]["icons"]["saudeemordem_logo"], config["br"]["icons"]["ondacovid_logo"]), unsafe_allow_html=True, ) st.write( """ <div class="base-wrapper primary-span"> <span class="section-header">Selecione seu estado ou município no mapa abaixo:</span> </div>""", unsafe_allow_html=True, ) # GET DATA dfs = get_data(config) # REGION/CITY USER INPUT user_input = dict() user_input["state_name"] = st.selectbox("Estado", utils.filter_place(dfs, "state")) user_input["health_region_name"] = st.selectbox( "Região de Saúde", utils.filter_place(dfs, "health_region", state_name=user_input["state_name"]), ) user_input["city_name"] = st.selectbox( "Município", utils.filter_place( dfs, "city", state_name=user_input["state_name"], health_region_name=user_input["health_region_name"], ), ) changed_city = user_analytics.safe_log_event( "picked farol place", session_state, event_args={ "state": user_input["state_name"], "city": user_input["city_name"] }, ) user_input, data = update_user_input_places(user_input, dfs, config) # GENERATE MAPS map_place_id = utils.Dictionary().get_state_alphabetical_id_by_name( user_input["state_name"]) if os.getenv("IS_LOCAL") == "TRUE": map_url = config["br"]["api"]["mapserver_local"] else: map_url = config["br"]["api"]["mapserver_external"] st.write( f""" <div class="brazil-map-div"> <div class="alert-levels-map-overlay"> </div> <div> <iframe id="map" src="resources/iframe-gen.html?url={map_url}map-iframe?place_id=BR" class="map-br" scrolling="no"> </iframe> </div> </div> """, unsafe_allow_html=True, ) st.write( f""" <iframe id="map-state" src="resources/iframe-gen.html?url={map_url}map-iframe?place_id={map_place_id}" class="map-state" scrolling="no"> </iframe> """, unsafe_allow_html=True, ) st.write( f""" <div class="selectors-box" id="selectors-box"> </div> <iframe src="resources/select-box-mover.html?place_id={user_input["state_name"]}{user_input["health_region_name"]}{user_input["city_name"]}" height="0px"> </iframe>""", unsafe_allow_html=True, ) # SOURCES PARAMS user_input = utils.get_sources(user_input, data, dfs["city"], ["beds", "icu_beds"]) # POPULATION PARAMS try: user_input["population_params"] = { "N": int(data["population"].fillna(0).values[0]), "D": int(data["deaths"].fillna(0).values[0]), "I": int(data["active_cases"].fillna(0).values[0]), "I_confirmed": int(data["confirmed_cases"].fillna(0).values[0]), "I_compare": int(data["confirmed_cases"].fillna(0).values[0]), } except: user_input["population_params"] = { "N": int(data["population"].fillna(0).values[0]), "D": int(data["deaths"].fillna(0).values[0]), "I": 0, "I_confirmed": int(data["confirmed_cases"].fillna(0).values[0]), "I_compare": int(data["confirmed_cases"].fillna(0).values[0]), } user_input["Rt"] = { "best": data["rt_low_95"].values[0], "worst": data["rt_high_95"].values[0], "is_valid": data["rt_most_likely"].apply(str).values[0], } user_input["last_updated_cases"] = data[ "last_updated_subnotification"].max() # Update session values to standard ones if changed city or opened page or reseted values if (session_state.state_name != user_input["state_name"] or session_state.health_region_name != user_input["health_region_name"] or session_state.city_name != user_input["city_name"] or session_state.number_beds is None or session_state.reset): session_state.state_name = user_input["state_name"] session_state.health_region_name = user_input["health_region_name"] session_state.city_name = user_input["city_name"] session_state.state_num_id = user_input["state_num_id"] session_state.health_region_id = user_input["health_region_id"] session_state.city_id = user_input["city_id"] session_state.number_beds = int( user_input["number_beds"] * config["br"]["simulacovid"]["resources_available_proportion"]) session_state.number_icu_beds = int( user_input["number_icu_beds"] * config["br"]["simulacovid"]["resources_available_proportion"]) session_state.number_cases = user_input["population_params"][ "I_confirmed"] session_state.number_deaths = user_input["population_params"]["D"] session_state.reset = True if data["confirmed_cases"].sum() == 0: st.write( f"""<div class="base-wrapper"> Seu município ou Região de Saúde ainda não possui casos reportados oficialmente. Portanto, simulamos como se o primeiro caso ocorresse hoje. <br><br>Caso queria, você pode mudar esse número abaixo: </div>""", unsafe_allow_html=True, ) user_input["population_params"]["I"] = 1 else: infectious_period = ( config["br"]["seir_parameters"]["severe_duration"] + config["br"]["seir_parameters"]["critical_duration"]) placeholder_value_pls_solve_this = 0 # DIMENSIONS CARDS dimensions = DimensionCards utils.genAnalysisDimmensionsSection(dimensions) # INDICATORS CARDS indicators = IndicatorCards indicators = update_indicators(indicators, data, config, user_input, session_state) data["overall_alert"] = data["overall_alert"].map( config["br"]["farolcovid"]["categories"]) if "state" in user_input["place_type"]: # Add disclaimer to cities in state alert levels total_alert_regions = dfs["health_region"][ dfs["health_region"]["state_num_id"] == data["state_num_id"]. unique()[0]].assign(overall_alert=lambda df: df[ "overall_alert"].map(config["br"]["farolcovid"]["categories"]) )["overall_alert"].value_counts() utils.genKPISection( place_type=user_input["place_type"], locality=user_input["locality"], alert=data["overall_alert"].values[0], indicators=indicators, n_colapse_regions=total_alert_regions[ total_alert_regions.index.isin(["altíssimo", "alto"])].sum(), ) else: utils.genKPISection( place_type=user_input["place_type"], locality=user_input["locality"], alert=data["overall_alert"].values[0], indicators=indicators, ) # AVAILABLE CAPACITY DISCLAIMER st.write( """ <div class='base-wrapper'> <i>* Utilizamos %s% da capacidade hospitalar reportada por %s em %s para cálculo da projeção de dias para atingir capacidade máxima.<br><b>Para municípios, utilizamos os recursos da respectiva regional de saúde.</b> São considerados leitos os tipos: cirúrgicos, clínicos e hospital-dia. A capacidade de UTI é dada pelo total de leitos UTI Covid adulto.</i> </div> """ % ( str( int(config["br"]["simulacovid"] ["resources_available_proportion"] * 100)), user_input["author_number_beds"], user_input["last_updated_number_beds"], ), unsafe_allow_html=True, ) # TODO: remove comment on this later! # utils.gen_pdf_report() # INDICATORS PLOTS if st.button("Confira a evolução de indicadores-chave"): opening_response = user_analytics.log_event("picked key_indicators", dict()) if st.button("Esconder"): pass st.write( f""" <div class="base-wrapper"> <span class="section-header primary-span">CÁLCULO DO RITMO DE CONTÁGIO EM {user_input["locality"]}</span> <br><br> O ritmo de contágio, conhecido como número de reprodução efetivo (Rt), traduz a dinâmica de disseminação do Covid a cada dia. <br>O valor pode ser lido como o número médio de novas infecções diárias causadas por uma única pessoa infectada. Para mais informações, visite a página de Metodologia. </div> """, unsafe_allow_html=True, ) try: fig2 = plots.plot_rt_wrapper(user_input[user_input["place_type"]], user_input["place_type"]) st.plotly_chart(fig2, use_container_width=True) except: st.write( """<div class="base-wrapper"><b>Seu município, regional ou estado não possui mais de 30 dias de dados de casos confirmados.</b>""", unsafe_allow_html=True, ) st.write( "<div class='base-wrapper'><i>Em breve:</i> gráficos de subnotificação e média móvel de novos casos por 100k habitantes.</div>", unsafe_allow_html=True, ) utils.stylizeButton( name="Confira a evolução de indicadores-chave", style_string= """border: 1px solid var(--main-white);box-sizing: border-box;border-radius: 15px; width: auto;padding: 0.5em;text-transform: uppercase;font-family: var(--main-header-font-family);color: var(--main-white);background-color: var(--main-primary);font-weight: bold;text-align: center;text-decoration: none;font-size: 18px;animation-name: fadein;animation-duration: 3s;margin-top: 1em;""", session_state=session_state, ) # AMBASSADOR SECTION utils.gen_ambassador_section() # indicators["hospital_capacity"].left_display = user_input["number_beds"] # indicators["hospital_capacity"].right_display = user_input["number_icu_beds"] # indicators["subnotification_rate"].left_display = user_input["population_params"][ # "D" # ] # PDF-REPORT GEN BUTTON # if st.button("Gerar Relatório PDF"): # user_analytics.log_event("generated pdf") # st.write( # """<div class="base-wrapper">Aguarde um momento por favor...</div>""", # unsafe_allow_html=True, # ) # st.markdown( # pdfgen.gen_pdf_report(user_input, indicators, data, config), # unsafe_allow_html=True, # ) # TOOLS products = ProductCards # products[2].recommendation = f'Risco {data["overall_alert"].values[0]}' utils.genProductsSection(products) # SELECTION BUTTONS # TODO: limpar esse código! está 100% repetido!!! if session_state.continuation_selection is None: session_state.continuation_selection = [False, False, False, False] simula_button_name = "Clique Aqui" # Simula covid 0space saude_button_name = "Clique Aqui " # Saude em ordem 1space distancia_button_name = "Clique_Aqui" # Distanciamento social onda_button_name = "Clique_Aqui " # onda covid if st.button(simula_button_name): # SIMULA session_state.continuation_selection = [True, False, False, False] if st.button(distancia_button_name): # DISTANCIAMENTO session_state.continuation_selection = [False, True, False, False] if st.button(saude_button_name): # SAUDE session_state.continuation_selection = [False, False, True, False] if st.button(onda_button_name): # ONDA session_state.continuation_selection = [False, False, False, True] utils.stylizeButton( name=simula_button_name, style_string="""border: 1px solid black;""", session_state=session_state, others={"ui_binSelect": 1}, ) utils.stylizeButton( name=distancia_button_name, style_string="""border: 1px solid black;""", session_state=session_state, others={"ui_binSelect": 2}, ) utils.stylizeButton( name=saude_button_name, style_string="""border: 1px solid black;""", session_state=session_state, others={"ui_binSelect": 3}, ) utils.stylizeButton( name=onda_button_name, style_string="""border: 1px solid black;""", session_state=session_state, others={"ui_binSelect": 4}, ) if session_state.continuation_selection[0]: user_analytics.safe_log_event( "picked simulacovid", session_state, event_args={ "state": session_state.state_name, "health_region": session_state.health_region_name, "city": session_state.city_name, }, alternatives=[ "picked saude_em_ordem", "picked simulacovid", "picked onda", "picked distanciamento", ], ) # Downloading the saved data from memory user_input["number_beds"] = session_state.number_beds user_input["number_icu_beds"] = session_state.number_icu_beds user_input["number_deaths"] = session_state.number_deaths user_input["number_cases"] = session_state.number_cases sm.main(user_input, indicators, data, config, session_state) # TODO: remove comment on this later! # utils.gen_pdf_report() elif session_state.continuation_selection[1]: user_analytics.safe_log_event( "picked distanciamento", session_state, event_args={ "state": session_state.state_name, "health_region": session_state.health_region_name, "city": session_state.city_name, }, alternatives=[ "picked saude_em_ordem", "picked simulacovid", "picked onda", "picked distanciamento", ], ) ds.main(user_input, indicators, data, config, session_state) elif session_state.continuation_selection[2]: user_analytics.safe_log_event( "picked saude_em_ordem", session_state, event_args={ "state": session_state.state_name, "health_region": session_state.health_region_name, "city": session_state.city_name, }, alternatives=[ "picked saude_em_ordem", "picked simulacovid", "picked onda", "picked distanciamento", ], ) so.main(user_input, indicators, data, config, session_state) elif session_state.continuation_selection[3]: user_analytics.safe_log_event( "picked onda", session_state, event_args={ "state": session_state.state_name, "health_region": session_state.health_region_name, "city": session_state.city_name, }, alternatives=[ "picked saude_em_ordem", "picked simulacovid", "picked onda", "picked distanciamento", ], ) oc.main(user_input, indicators, data, config, session_state) # BIG TABLE gen_big_table(config, dfs) # FOOTER utils.gen_whatsapp_button(config["impulso"]["contact"]) utils.gen_footer() user_analytics.conclude_user_session(session_state)