Ejemplo n.º 1
0
def generate():
    page_count = 10
    page_num = 1
    game_list = []
    while page_num <= page_count:
        print(f"\n__PS4__ Page No: {page_num}\n")
        try:
            url = f"{PS_STORE}/{PS4_STORE}/{page_num}?{STORE_FILTERS}"
            page = requests.get(url)
            soup = BeautifulSoup(page.content, "html.parser")
            if page_num == 1:
                page_count = get_page_count(soup)

            games = soup.find_all("div", class_="grid-cell--game")
            for game in games:
                game_list.append(get_game_details(game))
            page_num += 1
            sleep(1)
            # break
        except Exception as e:
            print(e)
            sleep(5)
            print(f"failed on page no {page_num}, retrying...")

    #sort by price
    game_list = sorted(game_list, key=itemgetter("price"))

    utils.generate_csv("ps4", game_list, ["title", "price", "url"])
    utils.generate_html("ps4", game_list)
Ejemplo n.º 2
0
def generate():
    page_count = get_page_count()
    page_no = 1
    game_list = []
    while page_no <= page_count:
        print(f"__XBOX__ Page No: {page_no}")
        try:
            url = BASE_URL + str(page_no)
            page = requests.get(url)
            soup = BeautifulSoup(page.content, 'html.parser')
            games = soup.find_all('a', class_='Game')
            for game in games:
                game_url = f"{MARKET_PLACE}{game['href']}"
                game_title, price = get_game_details(game_url)
                game_detail = {'title': game_title, 'price': price, 'url': game_url}
                # print(game_title, price)
                game_list.append(game_detail)
            page_no += 1
        except Exception as e:
            print(e)
            sleep(5)
            print(f'failed on page no {page_no}, retrying...')

    #sort by price
    game_list = sorted(game_list, key=itemgetter('price'))

    utils.generate_csv('xbox', game_list, ['title', 'price', 'url'])
    utils.generate_html('xbox', game_list)
Ejemplo n.º 3
0
def generate():
    category_names = CATEGORIES.keys()
    store_names = STORES.keys()
    for store_name in store_names:
        for category_name in category_names:
            print(f'__CEX__ {store_name} => {category_name}')
            category_id = CATEGORIES[category_name]
            store_id = STORES[store_name]
            games = get_games(category_id, store_id)
            if games:
                utils.generate_csv(f'cex-{store_name}-{category_name}', games,
                                   ['title', 'price', 'url'])
                utils.generate_html(f'cex-{store_name}-{category_name}', games)
Ejemplo n.º 4
0
def atp_generate_certificate(request, course_id):
    log.info("atp_generate_certificate start: " +
             str(datetime.datetime.now().strftime("%s")))
    context = {}
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="certificate.pdf"'
    user = request.user
    username = user.username
    course_key = SlashSeparatedCourseKey.from_deprecated_string(course_id)
    course = get_course_by_id(course_key)
    categorie = course.categ
    course_factory = CourseGradeFactory().get_persisted(user, course)
    is_passed = course_factory.passed
    courseoverview = CourseOverview.get_from_id(course_key)
    course_title = courseoverview.display_name_with_default
    _temp_score = int(course_factory.percent * 1000)
    score = str(float(_temp_score / 10)) + '%'
    url = 'https://' + settings.FEATURES['LMS_BASE']

    if configuration_helpers.get_value('logo_couleur'):
        logo_path = configuration_helpers.get_value('logo_couleur')
    else:
        logo_path = '/media/certificates/images/logo-amundi.jpg'
    if configuration_helpers.get_value(
            'amundi_brand') and configuration_helpers.get_value(
                'amundi_brand') == "true":
        amundi_academy = '/media/certificates/images/logo-amundi-academy.jpg'
    else:
        amundi_academy = ''
    if configuration_helpers.get_value('primary_color'):
        primary_color = configuration_helpers.get_value('primary_color')
    else:
        primary_color = ''
    if configuration_helpers.get_value('secondary_color'):
        secondary_color = configuration_helpers.get_value('secondary_color')
    else:
        secondary_color = ''

    course_img_path = courseoverview.image_urls['raw']
    course_img_path = url + course_img_path
    template_path = '/certificates/template.html'
    certif_img_path = url + '/media/certificates/images/tampon.png'

    #return HttpResponse(pdf)
    return generate_html(username, score, course_img_path, template_path,
                         course_title, categorie, certif_img_path, logo_path,
                         amundi_academy, course.language,
                         user.first_name + ' ' + user.last_name, primary_color,
                         secondary_color)
def run_app():
    css.hide_menu()
    css.limit_plot_size()

    # Get cached country data
    countries = fetch_country_data()

    if countries.stale:
        st.caching.clear_cache()
        countries = fetch_country_data()

    st.markdown(
        body=generate_html(text=f"Corona Calculator", bold=True, tag="h1"),
        unsafe_allow_html=True,
    )
    st.markdown(
        body=generate_html(
            tag="h2",
            text="A tool to help you visualize the impact of social distancing <br>",
        ),
        unsafe_allow_html=True,
    )

    st.markdown(
        body=generate_html(
            text="<strong>Disclaimer:</strong> <em>The creators of this application are not healthcare professionals. "
            "The illustrations provided were estimated using best available data but might not accurately reflect reality.</em>",
            color="gray",
            font_size="12px",
        ),
        unsafe_allow_html=True,
    )
    st.markdown(
        body=generate_html(
            tag="h4",
            text=f"<u><a href=\"{NOTION_MODELLING_DOC}\" target=\"_blank\" style=color:{COLOR_MAP['pink']};>"
            "Methodology</a></u> <span> &nbsp;&nbsp;&nbsp;&nbsp</span>"
            f"<u><a href=\"{MEDIUM_BLOGPOST}\" target=\"_blank\" style=color:{COLOR_MAP['pink']};>"
            "Blogpost</a> </u>"
            "<hr>",
        ),
        unsafe_allow_html=True,
    )

    sidebar = Sidebar(countries)
    country = sidebar.country
    country_data = countries.country_data[country]
    _historical_df = countries.historical_country_data
    historical_data = _historical_df.loc[_historical_df.index == country]
    number_cases_confirmed = country_data["Confirmed"]
    population = country_data["Population"]
    num_hospital_beds = country_data["Num Hospital Beds"]

    st.subheader(f"How has the disease spread in {country}?")
    st.write(
        "The number of reported cases radically underestimates the true cases, because people do not show symptoms for "
        "several days, not everybody gets tested, and the tests take a few days to return results. "
        "The extent depends upon your country's testing strategy."
        " This estimate (14% reporting) is from China ([source](https://science.sciencemag.org/content/early/2020/03/13/science.abb3221))."
    )
    # Estimate true cases
    true_cases_estimator = models.TrueInfectedCasesModel(
        constants.ReportingRate.default
    )
    estimated_true_cases = true_cases_estimator.predict(number_cases_confirmed)

    reported_vs_true_cases(int(number_cases_confirmed), estimated_true_cases)

    st.markdown(
        f"Given the prevalence of the infection in your country, the probability of being infected at this time is "
        f"**{estimated_true_cases / population:.3%}**. Even if you show no symptoms, the probability of being infected is "
        f"**{models.get_probability_of_infection_give_asymptomatic(population, estimated_true_cases, constants.AsymptomaticRate.default):.3%}**. "
        f"Note that these probabilities are on a country-wide basis and so may not apply to your situation."
    )

    # Plot historical data
    fig = graphing.plot_historical_data(historical_data)
    st.write(fig)

    asymptomatic_cases_estimator = models.AsymptomaticCasesModel(
        constants.AsymptomaticRate.default
    )

    contact_rate = sidebar.contact_rate

    asymptomatic_sir_model = models.AsymptomaticSIRModel(
        transmission_rate_per_contact=constants.TransmissionRatePerContact.default_per_symptom_state,
        contact_rate=contact_rate,
        asymptomatic_cases_model=asymptomatic_cases_estimator,
        recovery_rate=constants.RecoveryRate.default,
        normal_death_rate=constants.MortalityRate.default,
        critical_death_rate=constants.CriticalDeathRate.default,
        hospitalization_rate=constants.HospitalizationRate.default,
        hospital_capacity=num_hospital_beds
    )

    df = models.get_predictions(
        cases_estimator=true_cases_estimator,
        sir_model=asymptomatic_sir_model,
        num_diagnosed=number_cases_confirmed,
        num_recovered=country_data["Recovered"],
        num_deaths=country_data["Deaths"],
        area_population=population,
    )

    st.subheader("How will my actions affect the spread?")
    st.write(
        "The critical factor for controlling spread is how many others infected people interact with each day. "
        "This has a dramatic effect upon the dynamics of the disease. "
    )
    st.write(
        "**Play with the slider to the left to see how this changes the dynamics of disease spread**"
    )

    df_base = df[~df.Status.isin(["Need Hospitalization"])]
    base_graph = graphing.infection_graph(df_base, df_base.Forecast.max(), sidebar.contact_rate)
    st.warning(graph_warning)
    st.write(base_graph)

    st.subheader("How will this affect my healthcare system?")
    st.write(
        "The important variable for hospitals is the peak number of people who require hospitalization"
        " and ventilation at any one time."
    )

    # Do some rounding to avoid beds sounding too precise!
    approx_num_beds = round(num_hospital_beds / 100) * 100
    st.write(
        f"Your country has around **{approx_num_beds:,}** beds. Bear in mind that most of these "
        "are probably already in use for people sick for other reasons."
    )
    st.write(
        "It's hard to know exactly how many ventilators are present per country, but there will certainly be a worldwide "
        "shortage. Many countries are scrambling to buy them [(source)](https://www.reuters.com/article/us-health-coronavirus-draegerwerk-ventil/germany-italy-rush-to-buy-life-saving-ventilators-as-manufacturers-warn-of-shortages-idUSKBN210362)."
    )

    peak_occupancy = df.loc[df.Status == "Need Hospitalization"]["Forecast"].max()
    percent_beds_at_peak = min(100 * num_hospital_beds / peak_occupancy, 100)

    num_beds_comparison_chart = graphing.num_beds_occupancy_comparison_chart(
        num_beds_available=approx_num_beds, max_num_beds_needed=peak_occupancy, contact_rate=sidebar.contact_rate
    )

    st.write(num_beds_comparison_chart)

    st.markdown(
        f"At peak, **{int(peak_occupancy):,}** people will need hospital beds. ** {percent_beds_at_peak:.1f}% ** of people "
        f"who need a bed in hospital will have access to one given your country's historical resources. This does "
        f"not take into account any special measures that may have been taken in the last few months."
    )

    st.subheader("How severe will the impact be?")

    num_dead = df[df.Status == "Dead"].Forecast.iloc[-1]
    num_recovered = df[df.Status == "Recovered"].Forecast.iloc[-1]
    st.markdown(
        f"If the average person in your country adopts the selected behavior, we estimate that **{int(num_dead):,}** "
        f"people will die."
    )

    st.markdown(
        f"The graph above below a breakdown of casualties and hospitalizations by age group."
    )

    outcomes_by_age_group = models.get_status_by_age_group(num_dead, num_recovered)
    fig = graphing.age_segregated_mortality(
        outcomes_by_age_group.loc[:, ["Dead", "Need Hospitalization"]], contact_rate=sidebar.contact_rate
    )
    st.write(fig)

    st.write(
        f"Parameters by age group, including demographic distribution, are [worldwide numbers](https://population.un.org/wpp/DataQuery/) "
        f"so they may be slightly different in your country."
    )
    st.write(
        f"We've used mortality rates from this [recent paper from Imperial College](https://www.imperial.ac.uk/media/imperial-college/medicine/sph/ide/gida-fellowships/Imperial-College-COVID19-NPI-modelling-16-03-2020.pdf?fbclid=IwAR3TzdPTcLiOZN5r2dMd6_08l8kG0Mmr0mgP3TdzimpqB8H96T47ECBUfTM). "
        f"However, we've adjusted them according to the [maximum mortality rate recorded in Wuhan](https://wwwnc.cdc.gov/eid/article/26/6/20-0233_article)"
        f" when your country's hospitals are overwhelmed: if more people who need them lack hospital beds, more people will die."
    )
    st.write("<hr>", unsafe_allow_html=True)
    st.write(
        "Like this? [Click here to share it on Twitter](https://ctt.ac/u5U39), and "
        "[let us know your feedback via Google Form](https://forms.gle/J6ZFFgh4rVQm4y8G7)"
    )

    utils.insert_github_logo()
Ejemplo n.º 6
0
    def __init__(self, countries):
        country = st.sidebar.selectbox(
            "What country do you live in?",
            options=countries.countries,
            index=countries.default_selection,
        )
        self.country = country

        transmission_probability = constants.TransmissionRatePerContact.default
        country_data = countries.country_data[country]
        date_last_fetched = countries.last_modified

        st.sidebar.markdown(
            body=generate_html(
                text=f"Statistics refreshed as of ",
                line_height=0,
                font_family="Arial",
                font_size="12px",
            ),
            unsafe_allow_html=True,
        )

        st.sidebar.markdown(
            body=generate_html(text=f"{date_last_fetched}",
                               bold=True,
                               line_height=0),
            unsafe_allow_html=True,
        )

        st.sidebar.markdown(
            body=generate_html(
                text=
                f'Population: {int(country_data["Population"]):,}<br>Infected: {int(country_data["Confirmed"]):,}<br>'
                f'Recovered: {int(country_data["Recovered"]):,}<br>Dead: {int(country_data["Deaths"]):,}',
                line_height=0,
                font_family="Arial",
                font_size="0.9rem",
                tag="p",
            ),
            unsafe_allow_html=True,
        )
        # Horizontal divider line
        st.sidebar.markdown("-------")
        st.sidebar.markdown(
            body=generate_html(
                text=f"Play with the numbers",
                line_height=0,
                color=COLOR_MAP["pink"],
                bold=True,
                font_size="16px",
            ),
            unsafe_allow_html=True,
        )

        st.sidebar.markdown(
            body=generate_html(
                text=
                f"Change the degree of social distancing to see the effect upon disease "
                f"spread and access to hospital beds. Since many cases of coronavirus do not "
                f"show symptoms, social distancing is important even for those who do not "
                f"appear to be infected!",
                line_height=0,
                font_size="12px",
            ) + "<br>",
            unsafe_allow_html=True,
        )

        st.sidebar.markdown(
            body=generate_html(
                text=f"How many people come into contact with each person who:",
                line_height=0,
                font_size="12px",
            ) + "<br>",
            unsafe_allow_html=True,
        )

        slider_person_descriptions = {
            constants.SymptomState.ASYMPTOMATIC: "has no symptoms",
            constants.SymptomState.SYMPTOMATIC: "has symptoms",
        }

        self.contact_rate = {
            state: st.sidebar.slider(
                label=description,
                min_value=constants.AverageDailyContacts.min,
                max_value=constants.AverageDailyContacts.max,
                value=constants.AverageDailyContacts.default[state],
            )
            for state, description in slider_person_descriptions.items()
        }

        st.sidebar.markdown(
            body=generate_html(
                text=
                f"We're using an estimated transmission probability of {transmission_probability * 100:.1f}%. "
                f"This probability is diminished by 45% for asymptomatic cases, "
                f" see our <a href='https://www.notion.so/coronahack/Modelling-d650e1351bf34ceeb97c82bd24ae04cc'> methods for details</a>.",
                line_height=0,
                font_size="10px",
            ),
            unsafe_allow_html=True,
        )
Ejemplo n.º 7
0
    def __init__(self, countries):
        country = st.sidebar.selectbox(
            "What country/state do you live in?",
            options=countries.countries,
            index=countries.default_selection,
        )
        self.country = country

        transmission_probability = constants.TransmissionRatePerContact.default
        country_data = countries.country_data[country]
        date_last_fetched = countries.last_modified

        st.sidebar.markdown(
            body=generate_html(
                text=f"Statistics refreshed as of ",
                line_height=0,
                font_family="Arial",
                font_size="12px",
            ),
            unsafe_allow_html=True,
        )

        st.sidebar.markdown(
            body=generate_html(text=f"{date_last_fetched}",
                               bold=True,
                               line_height=0),
            unsafe_allow_html=True,
        )

        st.sidebar.markdown(
            body=generate_html(
                text=
                f'Population: {int(country_data["Population"]):,}<br>Infected: {int(country_data["Confirmed"]):,}<br>'
                f'Recovered: {int(country_data["Recovered"]):,}<br>Dead: {int(country_data["Deaths"]):,}',
                line_height=0,
                font_family="Arial",
                font_size="0.9rem",
                tag="p",
            ),
            unsafe_allow_html=True,
        )
        # Horizontal divider line
        st.sidebar.markdown("-------")
        st.sidebar.markdown(
            body=generate_html(
                text=f"Simulate social distancing",
                line_height=0,
                color=COLOR_MAP["pink"],
                bold=True,
                font_size="16px",
            ),
            unsafe_allow_html=True,
        )

        st.sidebar.markdown(
            body=generate_html(
                text=
                f"Change the degree of social distancing to see the effect upon disease "
                f"spread and access to hospital beds.",
                line_height=0,
                font_size="12px",
            ) + "<br>",
            unsafe_allow_html=True,
        )

        st.sidebar.markdown(
            body=generate_html(
                text=
                f"General degree of social distancing is in the range 10-20 ",
                line_height=0,
                font_size="12px",
            ) + "<br>",
            unsafe_allow_html=True,
        )

        self.contact_rate = st.sidebar.slider(
            label=
            "How many people does an infected individual meet on a daily basis?",
            min_value=constants.AverageDailyContacts.min,
            max_value=constants.AverageDailyContacts.max,
            value=constants.AverageDailyContacts.default,
        )

        horizon = {
            "3  months": 90,
            "6 months": 180,
            "12  months": 365,
            "24 months": 730,
        }
        _num_days_for_prediction = st.sidebar.radio(
            label="Time period for prediction",
            options=list(horizon.keys()),
            index=1,
        )

        self.num_days_for_prediction = horizon[_num_days_for_prediction]

        st.sidebar.markdown(
            body=generate_html(
                text=
                f"We're using an estimated transmission probability of {transmission_probability * 100:.1f}%,"
                f" see our <a href='https://www.notion.so/coronahack/Modelling-d650e1351bf34ceeb97c82bd24ae04cc'> methods for details</a>.",
                line_height=0,
                font_size="10px",
            ),
            unsafe_allow_html=True,
        )
Ejemplo n.º 8
0
def run_app():
    ############################### Data Load ##################################

    css.hide_menu()

    css.limit_plot_size()

    # Get cached country data
    countries = _fetch_country_data()

    global_data = _fetch_global_data()

    if countries.stale:
        st.caching.clear_cache()

        countries = _fetch_country_data()

    if global_data.stale:
        st.caching.clear_cache()

        global_data = _fetch_global_data()

    ################## Heading Section ####################################

    utils.img_html(
        alt_text='Fractal',
        href='https://fractal.ai',
        src=
        'https://i2.wp.com/fractal.ai/wp-content/uploads/2018/02/header-black-logo.png?fit=126%2C43&ssl=1',
        attributes=dict(width=125, height=43, target='_blank'))

    st.markdown(
        body=generate_html(text=f"Australia COVID-19 Simulator",
                           bold=True,
                           tag="h1"),
        unsafe_allow_html=True,
    )
    st.markdown(
        body=generate_html(
            tag="h2",
            text=
            "A tool to help you visualize the impact of social distancing <br>",
        ),
        unsafe_allow_html=True,
    )

    st.markdown(
        body=generate_html(
            text=
            "<strong>Disclaimer:</strong> <em>The creators of this application are not healthcare professionals. "
            "The illustrations provided were estimated using best available data but might not accurately reflect reality.</em>",
            color="gray",
            font_size="12px",
        ),
        unsafe_allow_html=True,
    )

    ### Add side bar
    sidebar = Sidebar(countries)

    ###################### historical and forecast chart ##############################

    ### Get selected country
    country = sidebar.country

    country_data = countries.country_data[country]

    _historical_df = countries.historical_country_data

    if country == "Australia":

        historical_data_custom = data_utils.make_historical_data(
            _historical_df)

        try:

            forecasted_data = forecast_utils.get_forecasts(
                country, constants.FORECAST_HORIZON)

            historical_plot_df = data_utils.prep_plotting_data(
                forecasted_data, historical_data_custom)

            # fig = graphing.plot_historical_data(historical_data_plot, con_flag=True)

            fig = graphing.plot_time_series_forecasts(historical_plot_df,
                                                      country_flag=True,
                                                      country_name=country)

        except Exception as exc:

            print("Error", exc)

    else:

        historical_data_custom = _historical_df.loc[_historical_df.index ==
                                                    country]

        try:

            forecasted_data = forecast_utils.get_forecasts(
                country, constants.FORECAST_HORIZON)

            historical_plot_df = data_utils.prep_plotting_data(
                forecasted_data, historical_data_custom)

            # fig = graphing.plot_historical_data(historical_data_plot)

            fig = graphing.plot_time_series_forecasts(historical_plot_df,
                                                      country_flag=False,
                                                      country_name=country)

        except Exception as exc:

            print(exc)

    historical_data = _historical_df.loc[_historical_df.index == country]

    number_cases_confirmed = country_data["Confirmed"]

    population = country_data["Population"]

    num_hospital_beds = country_data["Num Hospital Beds"]

    age_data = constants.AGE_DATA.loc[constants.AGE_DATA["State"] ==
                                      country, :]

    st.subheader(
        f"How is the disease likely to spread in {country} in the next week?")

    # Estimate true cases
    true_cases_estimator = models.TrueInfectedCasesModel(
        constants.ReportingRate.default)
    # estimated_true_cases = true_cases_estimator.predict(number_cases_confirmed)

    try:

        week1_est = historical_plot_df.tail(1)

        reported_vs_true_cases(
            int(number_cases_confirmed), week1_est["confirmed"].tolist()[0],
            graphing.abbreviate(week1_est["lower_bound"].tolist()[0],
                                round_factor=0),
            graphing.abbreviate(week1_est["upper_bound"].tolist()[0],
                                round_factor=0))

        # Plot historical data
        st.write(fig)

        print("Historical Data with Forecasts plotted")

    except Exception as exc:

        print(exc)

        st.markdown(
            f"Something went wrong :( Forecasts unavailable. Contact admin")

    ###################### SIR Model and Simulator ##############################

    # Predict infection spread
    sir_model = models.SIRModel(
        transmission_rate_per_contact=constants.TransmissionRatePerContact.
        default,
        contact_rate=sidebar.contact_rate,
        recovery_rate=constants.RecoveryRate.default,
        normal_death_rate=constants.MortalityRate.default,
        critical_death_rate=constants.CriticalDeathRate.default,
        hospitalization_rate=constants.HospitalizationRate.default,
        hospital_capacity=num_hospital_beds,
    )

    df = models.get_predictions(cases_estimator=true_cases_estimator,
                                sir_model=sir_model,
                                num_diagnosed=number_cases_confirmed,
                                num_recovered=country_data["Recovered"],
                                num_deaths=country_data["Deaths"],
                                area_population=population,
                                max_days=sidebar.num_days_for_prediction)

    st.subheader("How will my actions affect the spread?")

    st.write(
        "**Use the slider in the sidebar to see how this changes the dynamics of disease spread**"
    )

    df_base = df[~df.Status.
                 isin(["Need Hospitalization", "Recovered", "Susceptible"])]

    base_graph = graphing.infection_graph(df_base, df_base.Forecast.max(),
                                          population * 0.5, population * 0.75)
    # st.warning(graph_warning)
    st.write(base_graph)

    print("Infections Graph Plotted")

    ###################### Effect on hospitals ##############################

    st.subheader("How will this affect my healthcare system?")

    # Do some rounding to avoid beds sounding too precise!
    approx_num_beds = round(num_hospital_beds / 100) * 100

    st.write(
        f"{country} has around **{approx_num_beds:,}** beds. Bear in mind that most of these "
        "are probably already in use for people sick for other reasons.")

    peak_occupancy = df.loc[df.Status ==
                            "Need Hospitalization"]["Forecast"].max()

    percent_beds_at_peak = min(100 * num_hospital_beds / peak_occupancy, 100)

    num_beds_comparison_chart = graphing.num_beds_occupancy_comparison_chart(
        num_beds_available=approx_num_beds, max_num_beds_needed=peak_occupancy)

    st.write(num_beds_comparison_chart)

    st.markdown(
        f"At peak, **{int(peak_occupancy):,}** people will need hospital beds. At least ** {100 - percent_beds_at_peak:.1f}% ** of "
        f" people who need a bed in hospital might not have access given historical resources of {country}."
    )

    ###################### Death Charts ##############################

    st.subheader("How severe will the impact be?")

    num_dead = df[df.Status == "Dead"].Forecast.iloc[-1]

    num_recovered = df[df.Status == "Recovered"].Forecast.iloc[-1]

    glob_hist = global_data.historical_country_data

    uk_data = glob_hist.loc[(glob_hist.index == "UK") | \
                            (glob_hist.index == "United Kingdom"), :].copy()

    uk_death_mirror = get_uk_death_mirror(uk_data, country_data["Deaths"])

    death_plot = graphing.plot_death_timeseries(df[df.Status == "Dead"],
                                                uk_death_mirror,
                                                country_name=country)

    st.markdown(
        f"If the average person in {country} adopts the selected behavior, we estimate that **{int(num_dead):,}** "
        f"people will die.")

    st.markdown(f"This graph illustrates predicted deaths.")

    outcomes_by_age_group = models.get_status_by_age_group(
        num_dead, num_recovered, age_data)

    fig = graphing.age_segregated_mortality(
        outcomes_by_age_group.loc[:, ["Dead"]])

    st.write(death_plot)

    print("Deaths Graph Plotted")

    st.markdown("-------")
    st.markdown(body=generate_html("We'd love to hear from you!",
                                   tag='h2',
                                   color='#0090c4'),
                unsafe_allow_html=True)
    user_input = st.text_input("Enter your email to contact us")
    utils.contact_us(user_input)

    ###################### Credits ##############################

    st.subheader("References and Credits:")

    st.markdown(
        body=generate_html(
            tag="h4",
            text=
            f"<u><a href=\"{NOTION_MODELLING_DOC}\" target=\"_blank\" style=color:{COLOR_MAP['pink']};>"
            "Methodology</a></u> <span> &nbsp;&nbsp;&nbsp;&nbsp</span>"
            "<hr>",
        ),
        unsafe_allow_html=True,
    )

    st.markdown(
        body=generate_html(
            tag="h4",
            text=
            f"<u><a href=\"https://github.com/CSSEGISandData/COVID-19\" target=\"_blank\" style=color:{COLOR_MAP['pink']};>"
            "2019 Novel Coronavirus COVID-19 (2019-nCoV) Data Repository by Johns Hopkins CSSE</a></u> <span> &nbsp;&nbsp;&nbsp;&nbsp</span>"
            "<hr>",
        ),
        unsafe_allow_html=True,
    )

    print("complete....")
def run_app():

    css.hide_menu()
    css.limit_plot_size()

    # Get cached country data
    countries = _fetch_country_data()

    if countries.stale:
        st.caching.clear_cache()
        countries = _fetch_country_data()

    st.markdown(
        body=generate_html(text=f"Corona Calculator", bold=True, tag="h1"),
        unsafe_allow_html=True,
    )
    st.markdown(
        body=generate_html(
            tag="h2",
            text=
            "A tool to help you visualize the impact of social distancing <br>",
        ),
        unsafe_allow_html=True,
    )

    st.markdown(
        body=generate_html(
            text=
            "<strong>Disclaimer:</strong> <em>The creators of this application are not healthcare professionals. "
            "The illustrations provided were estimated using best available data but might not accurately reflect reality.</em>",
            color="gray",
            font_size="12px",
        ),
        unsafe_allow_html=True,
    )
    st.markdown(
        body=generate_html(
            tag="h4",
            text=
            f"<u><a href=\"{NOTION_MODELLING_DOC}\" target=\"_blank\" style=color:{COLOR_MAP['pink']};>"
            "Methodology</a></u> <span> &nbsp;&nbsp;&nbsp;&nbsp</span>"
            f"<u><a href=\"{MEDIUM_BLOGPOST}\" target=\"_blank\" style=color:{COLOR_MAP['pink']};>"
            "Blogpost</a> </u>"
            "<hr>",
        ),
        unsafe_allow_html=True,
    )

    sidebar = Sidebar(countries)
    country = sidebar.country
    country_data = countries.country_data[country]
    number_cases_confirmed = country_data["Confirmed"]
    population = country_data["Population"]
    num_hospital_beds = country_data["Num Hospital Beds"]

    sir_model = models.SIRModel(
        transmission_rate_per_contact=constants.TransmissionRatePerContact.
        default,
        contact_rate=sidebar.contact_rate,
        recovery_rate=constants.RecoveryRate.default,
        normal_death_rate=constants.MortalityRate.default,
        critical_death_rate=sidebar.severe_mortality_rate,
        hospitalization_rate=constants.HospitalizationRate.default,
        hospital_capacity=num_hospital_beds,
    )
    true_cases_estimator = models.TrueInfectedCasesModel(
        constants.AscertainmentRate.default)

    df = models.get_predictions(
        true_cases_estimator,
        sir_model,
        number_cases_confirmed,
        population,
        sidebar.num_days_for_prediction,
    )

    reported_vs_true_cases(
        number_cases_confirmed,
        true_cases_estimator.predict(number_cases_confirmed))

    st.write(
        "The number of reported cases radically underestimates the true cases, because people do not show symptoms for "
        "several days, not everybody gets tested, and the tests take a few days to  return results. "
        "The extent depends upon your country's testing strategy."
        " We estimated the above using numbers from Japan ([source](https://www.ncbi.nlm.nih.gov/pubmed/32033064))."
    )

    st.subheader("How will the disease spread?")
    st.write(
        "The critical factor for controlling spread is how many others infected people interact with each day. "
        "This has a dramatic effect upon the dynamics of the disease. ")
    st.write(
        "**Play with the slider to the left to see how this changes the dynamics of disease spread**"
    )

    df_base = df[~df.Status.isin(["Need Hospitalization", "Need Ventilation"])]
    base_graph = graphing.infection_graph(df_base, df.Forecast.max())
    st.warning(graph_warning)
    st.write(base_graph)

    hospital_graph = graphing.hospitalization_graph(
        df[df.Status.isin(["Infected", "Need Hospitalization"])],
        num_hospital_beds,
        max(num_hospital_beds, df.Forecast.max()),
    )

    st.write(
        "Note that we use a fixed estimate of the mortality rate here, of 1% [(source)](https://institutefordiseasemodeling.github.io/nCoV-public/analyses/first_adjusted_mortality_estimates_and_risk_assessment/2019-nCoV-preliminary_age_and_time_adjusted_mortality_rates_and_pandemic_risk_assessment.html). "
        "In reality, the mortality rate will be highly dependent upon the load upon the healthcare system and "
        "the availability of treatment. Some estimates ([like this one](https://www.thelancet.com/journals/laninf/article/PIIS1473-3099(20)30195-X/fulltext)) are closer to 6%."
    )

    st.subheader("How will this affect my healthcare system?")
    st.write(
        "The important variable for hospitals is the peak number of people who require hospitalization"
        " and ventilation at any one time.")

    # Do some rounding to avoid beds sounding too precise!
    st.write(
        f"Your country has around **{round(num_hospital_beds / 100) * 100:,}** beds. Bear in mind that most of these "
        "are probably already in use for people sick for other reasons.")
    st.write(
        "It's hard to know how many ventilators are present per country, but there will certainly be a worldwide "
        "shortage. Many countries are scrambling to buy them [(source)](https://www.reuters.com/article/us-health-coronavirus-draegerwerk-ventil/germany-italy-rush-to-buy-life-saving-ventilators-as-manufacturers-warn-of-shortages-idUSKBN210362)."
    )

    st.warning(graph_warning)
    st.write(hospital_graph)
    peak_occupancy = df.loc[df.Status ==
                            "Need Hospitalization"]["Forecast"].max()
    percent_beds_at_peak = min(100 * num_hospital_beds / peak_occupancy, 100)

    st.markdown(
        f"At peak, **{peak_occupancy:,}** people will need hospital beds. ** {percent_beds_at_peak:.1f} % ** of people "
        f"who need a bed in hospital will have access to one given your country's historical resources. This does "
        f"not take into account any special measures that may have been taken in the last few months."
    )
Ejemplo n.º 10
0
def process(select):
    database = get_db()
    now = datetime.now()
    todo = {}

    for subscribtion in select:
        if subscribtion.user.username not in todo:
            obj = {
                'subs': [],
                'archive': subscribtion.user.archive,
                'user': subscribtion.user
            }
            todo[subscribtion.user.username] = obj
        todo[subscribtion.user.username]['subs'] += [subscribtion]

    for username, value in todo.items():
        start_time = datetime.now()
        log_info(username)
        log_info(value)

        till_tries_again = now - timedelta(hours=2)
        user = value['user']
        #update before it can go to shit
        q = user.update(last_sent=till_tries_again).where(
            UserModel.id == user.id)
        q.execute()

        subs_encoded = ""
        for sub in value['subs']:
            subs_encoded += sub.subreddit + " ; "

        report = ReportModel(user=user,
                             processing_stage=0,
                             processing_time=get_milliseconds_from(start_time),
                             to_email=user.kindle_email,
                             was_requested=user.has_requested,
                             was_successful=False,
                             attachment_size=0,
                             attachment_title=get_title(),
                             article_shortlinks='',
                             subs=subs_encoded,
                             is_recurrent=user.is_recurrent)
        report.save()

        try:
            thisdir = os.path.dirname(os.path.realpath(__file__))
            title = get_title()
            output_path = os.path.join(thisdir,
                                       'kinddit_output/' + title + '.html')

            articles = encode_articles_for(value['subs'], value['archive'])

            prepend_archives = ""
            for article in articles:
                if not article['archived']:
                    prepend_archives = serialise_article_for_archive(
                        article) + prepend_archives

            archive = prepend_archives + value['archive']

            q = user.update(archive=archive).where(UserModel.id == user.id)
            q.execute()

            articles_encoded = ""
            for article in articles:
                articles_encoded += article['link'] + " ; "

            #make a list of subs, articles
            #update report.stage
            q = report.update(processing_stage=5, processing_time=get_milliseconds_from(start_time), article_shortlinks=articles_encoded )\
                        .where(ReportModel.id == report.id)
            q.execute()

            #generate book.html
            size = generate_html(username, articles, output_path, title)


            q = report.update(processing_stage=10, processing_time=get_milliseconds_from(start_time),attachment_size=size )\
                        .where(ReportModel.id == report.id)
            q.execute()

            #update before it can go to shit
            hasrequested = user.is_recurrent == False and user.has_requested == True
            if hasrequested:
                hasrequested = False
            q = user.update(has_requested=hasrequested).where(
                UserModel.id == user.id)
            q.execute()

            if not is_debug():
                send_kindler(value['user'].kindle_email, output_path)
            else:
                log_info(
                    "Didnt send kindler through e-mail. it's waiting in the folter."
                )
            #send email
            #update success=True, processing_time
            q = report.update(processing_stage=15, processing_time=get_milliseconds_from(start_time), was_successful=True, was_requested=False )\
                        .where(ReportModel.id == report.id)
            q.execute()

            if not is_debug():
                os.remove(output_path)

            log_info("Sent for: " + username)
        except Exception as e:
            log_error("Unexpected error while sending.")
            import traceback
            log_error(
                traceback.format_exception(
                    None,  # <- type(e) by docs, but ignored 
                    e,
                    e.__traceback__), )

        delay_between_users()
    def __init__(self, countries):
        country = st.sidebar.selectbox(
            "What country do you live in?",
            options=countries.countries,
            index=countries.default_selection,
        )
        self.country = country

        transmission_probability = constants.TransmissionRatePerContact.default
        country_data = countries.country_data[country]
        date_last_fetched = countries.last_modified

        st.sidebar.markdown(
            body=generate_html(
                text=f"Statistics refreshed as of ", line_height=0, font_family="Arial"
            ),
            unsafe_allow_html=True,
        )

        st.sidebar.markdown(
            body=generate_html(
                text=f"{date_last_fetched}",
                bold=True,
                color=COLOR_MAP["pink"],
                line_height=0,
            ),
            unsafe_allow_html=True,
        )

        st.sidebar.markdown(
            body=generate_html(
                text=f'Population: {int(country_data["Population"]):,}<br>Infected: {country_data["Confirmed"]}<br>'
                f'Recovered: {country_data["Recovered"]}<br>Dead: {country_data["Deaths"]}',
                line_height=0,
                font_family="Arial",
                font_size="0.9rem",
                tag="p",
            ),
            unsafe_allow_html=True,
        )
        # Horizontal divider line
        st.sidebar.markdown("-------")

        st.sidebar.markdown(
            f"We're using an estimated transmission probability of {transmission_probability * 100:.1f}%"
        )

        self.contact_rate = st.sidebar.slider(
            label="Number of people infected people come into contact with daily",
            min_value=constants.AverageDailyContacts.min,
            max_value=constants.AverageDailyContacts.max,
            value=constants.AverageDailyContacts.default,
        )

        horizon = {
            "3  months": 90,
            "6 months": 180,
            "12  months": 365,
            "24 months": 730,
        }
        _num_days_for_prediction = st.sidebar.radio(
            label="What period of time would you like to predict for?",
            options=list(horizon.keys()),
            index=1,
        )

        self.num_days_for_prediction = horizon[_num_days_for_prediction]