Exemplo n.º 1
0
def data_download(area_stats: pd.DataFrame):
    df = area_stats[[
        'Ward Name', 'total_population', 'mean_age', 'median_age'
    ]]
    df.columns = ['Ward', 'Population', 'Average Age', 'Median Age']
    df = df.sort_values('Population', ascending=False).reset_index(drop=True)
    df['Pop. to Average Ward'] = df['Population'].apply(
        lambda x: ((x - avg_ward_pop) / x) * 100).apply(lambda x: f'{x:+.1f}%')
    formatted_pop = []
    for x in df['Population']:
        formatted = f'{int(x):,.0f}'
        formatted_pop.append(formatted)
    df['Population'] = formatted_pop
    df['Median Age'] = df['Median Age'].astype(int)
    df['Ward Average'] = avg_ward_pop
    df = df[[
        'Ward', 'Population', 'Average Age', 'Median Age',
        'Pop. to Average Ward'
    ]]
    csv = df.to_csv().encode('utf-8')
    st.download_button(label="Download ward data as CSV",
                       data=csv,
                       file_name=f'drive_time_analysis - {address_input}.csv',
                       mime='text/csv')
    st.dataframe(df)
Exemplo n.º 2
0
def make_concepts_zip(max_level=0):
    current_page = 0
    files_full_list = []
    nb_new_files = -1
    counter = 0
    while nb_new_files != 0:
        counter += 1
        if counter > 200:  #security
            break

        current_page += 1
        new_files_list = retrieve_concepts(max_level, current_page)
        nb_new_files = len(new_files_list)

        if nb_new_files > 0:
            files_full_list = files_full_list + new_files_list
            st.write(str(len(files_full_list)) + " files collected.")

    st.write("All files collected.")

    if st.button('Make Zip'):
        zip_file = make_zip('concepts.zip', files_full_list)
        if zip_file == False:
            st.error("The zip file could not be created.")
            return False
        else:
            st.success("Zip file created.")
            with open("concepts.zip", "rb") as final_zip:
                st.download_button(
                    label="Download zipped files",
                    data=final_zip,
                    file_name='concepts.zip',
                    mime='application/zip',
                )
Exemplo n.º 3
0
    def test_just_label(self, data):
        """Test that it can be called with label and string or bytes data."""
        st.download_button("the label", data=data)

        c = self.get_delta_from_queue().new_element.download_button
        self.assertEqual(c.label, "the label")
        self.assertEqual(c.disabled, False)
def cv_downloader():
    """A Main Page Streamlit button for Downloading my CV
    :return:
    """
    with open("./data/2022 Adam Fletcher CV.pdf", "rb") as cv_file:
        st.download_button(label='Download CV',
                           data=cv_file,
                           file_name="Adam Fletcher CV.pdf")
Exemplo n.º 5
0
def compute_download_button(state, attr, setter, compute_label, download_label, filename=None, value0=None):
    """
    A button that the first click computes something and 
    the second click this something is downloaded.
    
    Parameters
    ----------
    
    state : SessionObject
        An object containing stateful attributes, that is, 
        attributes that retain their values during a given
        Streamlit session.   
    attr : str
        The name of the attribute in `state` used to store
        the value computed during the button's first click.  
    setter : callable
        The callable (e.g. function) used to compute the 
        value to be stored in `state.attr` and later 
        downloaded. Currently this callable does not accept
        any arguments.
    compute_label : str
        The button label when in compute mode (i.e. when the 
        click calls `setter`).
    download_label : str
        The button label when in download mode (i.e. the 
        second click).
    filename : str
        The name given to the file to be downloaded.
    value0 : almost anything
        The value of `state.attr` when the button is on 
        compute mode (first click).    
    """
    
    def build(s):
        setattr(s, attr,  setter())
        
    def reset(s):
        setattr(s, attr, value0)
    
    if getattr(state, attr) == value0:
        st.button(compute_label, on_click=build, args=(state,))
    else:
        st.download_button(download_label, getattr(state, attr), file_name=filename, mime='text/plain', on_click=reset, args=(state,))
Exemplo n.º 6
0
def ui_download_raw_data(m):
    st.sidebar.header(f'Information for Material {m}')
    material = st.sidebar.selectbox(f'Material {m}:', material_names)
    excitation = st.sidebar.selectbox(
        f'Excitation {m}:',
        excitations + ("Arbitrary-Periodic", "Non-Periodic"))

    header(material, excitation)
    file = ""
    st.download_button(f'Download CSV',
                       file,
                       material + "-" + excitation + ".csv",
                       "text/csv",
                       key=m)
    st.write(
        "Data Info: Four Wire V-I Method; R10 ; 25C ; 10/6 Windings ; Princeton Measured"
    )

    st.sidebar.markdown("""---""")
    st.markdown("""---""")
Exemplo n.º 7
0
            st.success("Uploaded video file saved on the server")

        #Step 2:
        if upsampling:
            print("inside upsampling")
            os.system(
                "python ../upsampling/upsample.py --input_dir=data/original/ --output_dir=data/upsampled --device=cuda:0"
            )

        #Step 3: Event Generation
        file_path = process_dir(args["output_dir"], args["input_dir"], args)

        #Step 4: Download Option
        with open(file_path, "rb") as file:
            btn = st.download_button(label="Download Events",
                                     data=file,
                                     file_name=os.path.basename(file_path))
            if btn:
                st.markdown(
                    ':beer::beer::beer::beer::beer::beer::beer::beer::beer::beer::beer:'
                )

elif add_selectbox == "Live Webcam":
    st.title("ESIM Web App Playground")
    # st.markdown(':camera::movie_camera::camera::movie_camera::camera::movie_camera::camera::movie_camera::camera::movie_camera:')
    st.sidebar.subheader('ESIM Settings')
    ct_options = [
        '0.1', '0.2', '0.3', '0.4', '0.5', '0.6', '0.7', '0.8', '0.9', '1.0',
        '1.1', '1.2', '1.3', '1.4', '1.5', '1.6', '1.7', '1.8', '1.9', '2.0'
    ]
    st.sidebar.subheader('Positive Contrast Threshold')
Exemplo n.º 8
0
        sub_task_mode = st.selectbox(f"Select the mode to perform {sub_task}",
                                     ("Default mode", "Manual mode"))
        if sub_task_mode == "Default mode":
            st.markdown("""
    **Following are the Default Parameters**
    - **Date**: today
    - **Top company count**: 20
    - **Verbosity** (level of detail loging): detail """)
            if st.button("Continue"):
                with st.spinner("Running the query"):
                    result = sa.relative_momentum(save=False)
                st.dataframe(result)
                st.download_button(
                    "Download result",
                    data=result.to_csv(index=False).encode("utf-8"),
                    mime="text/csv",
                    file_name=
                    f"momentum_result_{datetime.datetime.now().strftime('%d-%m-%Y')}_top_20.csv",
                )

        elif sub_task_mode == "Manual mode":
            sub_task_para_date = st.date_input(label="Input desire date")
            sub_task_para_date = sub_task_para_date.strftime("%d/%m/%Y")
            sub_task_para_count = st.number_input(
                label="Input top company count", value=20)
            sub_task_para_verbosity = st.number_input(
                label="Input Verbosity (level 0: Minimal, 1: Detail)",
                value=1,
                min_value=0,
                max_value=1,
            )
Exemplo n.º 9
0
import streamlit as st
import pandas as pd
import openpyxl as xl
import shutil

st.title("Excel sheet spliter")

st.write("Choose our Template")
with open("pivot.xlsx", "rb") as file:
    st.download_button("Template Excel file",
                       data=file,
                       file_name="pivot.xlsx",
                       mime="application/octet-stream")

st.write("or")

uploaded_file = st.file_uploader("Choose a XLSX file", type="xlsx")

# st.write(uploaded_file)

if uploaded_file is not None:
    df = pd.read_excel(uploaded_file)
    # st.dataframe(df)
    # st.table(df)
    # st.write(uploaded_file)

    workbook = xl.load_workbook(uploaded_file)
    # sheet_1 = workbook['Overview']
    # st.write(workbook.sheetnames)
    sheet = st.selectbox("Select tab", workbook.sheetnames)
def convert_screenshots_to_pdf(output_folder_screenshot_path):
    ''' Convert PNG Image to PDF '''
    output_pdf_path = output_folder_screenshot_path + '\demo.pdf'
    with open(output_pdf_path, "wb") as f:
        f.write(
            img2pdf.convert(
                sorted(glob.glob(f"{output_folder_screenshot_path}/*.png"))))
    st.write('Pdf Created!')
    st.write('pdf saved at: ' + output_pdf_path)


if __name__ == "__main__":
    video_url = st.text_input('Enter URL of any youtube video')
    root_dir = os.getcwd()
    output_dir = root_dir + "\output"
    output_pdf_path = output_dir + '\demo.pdf'

    if st.button("convert"):
        root_dir = os.getcwd()
        output_dir = root_dir + "\output"
        output_folder_screenshot_path = initialize_output_folder()
        detect_unique_screenshots(video_url, output_folder_screenshot_path)
        convert_screenshots_to_pdf(output_folder_screenshot_path)

    with open(output_pdf_path, "rb") as pdf_file:
        PDFbyte = pdf_file.read()
    st.download_button(label="Download_PDF",
                       data=PDFbyte,
                       file_name="download_converted_file.pdf",
                       mime='application/octet-stream')
Exemplo n.º 11
0
    with col6:
        st.metric(label=f"{df_close_stats.iloc[2][0]}",
                  value=int(df_close_stats.iloc[2][1]))

    with col7:
        st.metric(label=f"{df_close_stats.iloc[3][0]}",
                  value=int(df_close_stats.iloc[3][1]))

    with col8:
        st.metric(label=f"{df_close_stats.iloc[4][0]}",
                  value=int(df_close_stats.iloc[4][1]))

    st.subheader("Antalet skapade ärenden")
    st.area_chart(df_errands_per_date)

    st.subheader("Antalet skapade ärenden per kategori")
    st.plotly_chart(df_errands_per_category)

    st.subheader("Antal skapade ärenden per medlem")
    st.dataframe(df_top_reporter)

    st.subheader("Öppna ärenden just nu")
    st.dataframe(df_open_now_details)
    st.download_button(
        "Ladda ner öppna ärenden",
        convert_df_for_download(df_open_now_details),
        file_name="oppna_arenden.csv",
        mime="text/csv",
    )
def run(beam: Beam):
    sol = Solver(beam)
    x = sol.generate_expanded_x_solutions()
    r = sol.generate_R_solutions(x)
    st.latex(r"\textup{Flex}_{generic} = " +
             sp.latex(sol.generate_Flex_matrix()))
    st.latex(r"\textup{P}_{generic} = " + sp.latex(sol.generate_P_vector_Q()))
    st.latex(
        sp.latex(sol.generate_reduced_Flex_matrix_and_P_vector()[0]) +
        r"\cdot \vec{X}_{rid} = " +
        sp.latex(sol.generate_reduced_Flex_matrix_and_P_vector()[1]))
    st.latex(r"\hookrightarrow \textup{X}_{expanded} = " + sp.latex(x))
    st.latex(r"\hookrightarrow \textup{R} = " + sp.latex(r))

    # -- CALCULATING BENDING MOMENT --
    M = BendingMoment(beam, x, r)
    V = Shear(beam, x, r)

    # storing x,y coordinates of inviluppo plot
    M_cords_x = M.s_func
    M_cords_y_pos, M_cords_y_neg = M.inviluppo()

    V_cords_x = V.s_func
    V_cords_y_pos, V_cords_y_neg = V.inviluppo()

    # PLOTTING
    # BENDING MOMENT
    st.pyplot(M.plot_inviluppo()[0])

    with st.expander(
            "👉 Click to see plots where Q = 1 is applied in each span"):
        st.write("Bending Moment")
        for span in range(len(beam.spans)):
            st.pyplot(M.plot_span_Q_1(span)[0])
        st.pyplot(M.plot_beam_Q_1()[0])

    # table results for bending moment
    M_df_results = Table.create_dataframe(
        header=Table.make_header(len(beam.spans)),
        rows=Table.make_body(M_cords_x, M_cords_y_pos, M_cords_y_neg,
                             beam.spans_cum_lenght()),
        index=["s", "M_neg", "M_pos"],
    )
    st.table(M_df_results)
    st.warning(
        "If Bending Moment values aren't 0.0 when the support is Simple, it's a problem due to approximation!"
    )

    df_results_M_latex = M_df_results.style.to_latex(position="H",
                                                     hrules=True,
                                                     siunitx=True)
    st.download_button(
        "💾 Save results as a LaTeX table",
        data=df_results_M_latex,
        mime="text/latex",
        file_name="results_M_table.tex",
    )

    # SHEAR
    st.pyplot(V.plot_inviluppo()[0])

    with st.expander(
            "👉 Click to see plots where Q = 1 is applied in each span"):
        st.write("Bending Voment")
        for span in range(len(beam.spans)):
            st.pyplot(V.plot_span_Q_1(span)[0])
        st.pyplot(V.plot_beam_Q_1()[0])

    # table results for bending moment
    V_df_results = Table.create_dataframe(
        header=Table.make_header(len(beam.spans)),
        rows=Table.make_body(V_cords_x, V_cords_y_pos, V_cords_y_neg,
                             beam.spans_cum_lenght()),
        index=["s", "V_pos", "V_neg"],
    )
    st.table(V_df_results)
    st.warning("If Shear values aren't")

    df_results_V_latex = V_df_results.style.to_latex(position="H",
                                                     hrules=True,
                                                     siunitx=True)
    st.download_button(
        "💾 Save results as a LaTeX table",
        data=df_results_V_latex,
        mime="text/latex",
        file_name="results_V_table.tex",
    )
Exemplo n.º 13
0
#Ausgaben:             

if confirm and not searchterm:
    st.write(" ")
elif confirm and searchterm:

    st.markdown("##### Ausgeben und Speichern der Daten:")
    
    st.info("Bitte beachten Sie: Ein Klick auf einen der Download-Buttons setzt die Anzeige zurück. Um die Anzeige und Downloadmöglichkeiten weiterhin zu "
            "nutzen, klicken Sie einfach erneut auf 'Los!' und führen Ihre Suche noch einmal aus.") 

    st.download_button(
        label="Download XML",
        data=r1.text,
        file_name='data.xml',
        mime='text/xml',
        #key='letsgo',
        #on_click='table()',
    )
               
    st.markdown("##### Darstellung als Tabelle:")
    
    df = table()
    
    #st.session_state["df"]=df 
    st.dataframe(df)

    def convert_df(df): 
        return df.to_csv().encode('utf-8')
    
    
Exemplo n.º 14
0
def ui_core_loss_db(m):
    st.sidebar.header(f'Information for Material {m}')
    material = st.sidebar.selectbox(f'Material {m}:', material_names)
    excitation = st.sidebar.selectbox(f'Excitation {m}:', excitations)
    xaxis = st.sidebar.selectbox(f'Select X-axis for Plotting {m}:', ['Flux Density', 'Frequency'])

    [Fmin, Fmax] = st.sidebar.slider(
        f'Frequency Range {m} (Hz)',
        c.streamlit.freq_min,
        c.streamlit.freq_max,
        (c.streamlit.freq_min, c.streamlit.freq_max),
        step=c.streamlit.freq_step
    )
    [Bmin, Bmax] = st.sidebar.slider(
        f'Flux Density Range {m} (mT)',
        c.streamlit.flux_min,
        c.streamlit.flux_max,
        (c.streamlit.flux_min, c.streamlit.flux_max),
        step=c.streamlit.flux_step
    )

    if excitation in ('Datasheet', 'Sinusoidal'):
        st.title(f"Core Loss Database {m}:")
        header(material, excitation, Fmin, Fmax, Bmin, Bmax)
        df = load_dataframe(material, excitation, Fmin,Fmax, Bmin, Bmax)

        if df.empty:
            st.write("Warning: No Data in Range")
        else:
            col1, col2 = st.columns(2)
            with col1:
                st.subheader(xaxis+' - Power Loss')
                if xaxis == 'Frequency':
                    st.plotly_chart(power_loss_scatter_plot(df, x='Frequency', color_prop='Flux_Density'), use_container_width=True)
                else:
                    st.plotly_chart(power_loss_scatter_plot(df, x='Flux_Density', color_prop='Frequency'), use_container_width=True)
            with col2:          # to be replaced with data driven error graphs
                st.subheader(xaxis+' - Estimated Error')    
                if xaxis == 'Frequency':
                    st.plotly_chart(power_loss_scatter_plot(df, x='Frequency', color_prop='Flux_Density'), use_container_width=True)
                else:
                    st.plotly_chart(power_loss_scatter_plot(df, x='Flux_Density', color_prop='Frequency'), use_container_width=True)
            file = df.to_csv().encode('utf-8')
            st.download_button("Download CSV",file, material+"-"+excitation+".csv","text/csv",key=m)
            st.write("CSV Column: [Index; Frequency (Hz); Flux Density (mT); Duty Ratio; Power Loss (kW/m^3)]")
            st.write("Data Info: Core Shape - ? ; Temperature - ? ; Method - ? ; Winding Turns - ?; Princeton Measured")

    if excitation == 'Triangle':
        Duty = st.sidebar.multiselect(f'Duty Ratio {m}', c.streamlit.duty_ratios_triangle, c.streamlit.duty_ratios_triangle)
        Margin = st.sidebar.slider(f'Duty Ratio Margin {m}', 0.0, 1.0, 0.01, step=0.01)

        header(material, excitation, Fmin, Fmax, Bmin, Bmax, Duty)
        df = load_dataframe(material, excitation, Fmin,Fmax, Bmin, Bmax, Duty, Margin)

        if df.empty:
            st.write("Warning: No Data in Range")
        else:
            col1, col2 = st.columns(2)
            with col1:
                st.subheader(xaxis+' - Power Loss')
                if xaxis == 'Frequency':
                    st.plotly_chart(power_loss_scatter_plot(df, x='Frequency', color_prop='Duty_Ratio'), use_container_width=True)
                else:
                    st.plotly_chart(power_loss_scatter_plot(df, x='Flux_Density', color_prop='Duty_Ratio'), use_container_width=True)
            with col2:
                st.subheader(xaxis+' - Estimated Error')    
                if xaxis == 'Frequency':
                    st.plotly_chart(power_loss_scatter_plot(df, x='Frequency', color_prop='Duty_Ratio'), use_container_width=True)
                else:
                    st.plotly_chart(power_loss_scatter_plot(df, x='Flux_Density', color_prop='Duty_Ratio'), use_container_width=True)
            file = df.to_csv().encode('utf-8')
            st.download_button("Download CSV",file,material+"-"+excitation+".csv","text/csv",key=m)
            st.write("CSV Column: [Index; Frequency (Hz); Flux Density (mT); Duty Ratio; Power Loss (kW/m^3)]")
            st.write("Data Info: Core Shape - ? ; Temperature - ? ; Method - ? ; Winding Turns - ?; Princeton Measured")

    if excitation == 'Trapezoidal':
        Duty = st.sidebar.multiselect(f'Duty Ratio {m}', c.streamlit.duty_ratios_trapezoid, c.streamlit.duty_ratios_trapezoid)
        Margin = st.sidebar.slider(f'Duty Ratio Margin {m}', 0.0, 1.0, 0.01, step=0.01)

        header(material, excitation, Fmin, Fmax, Bmin, Bmax, Duty)
        st.header("Note: D=0.2332 means **20% Up + 30% Flat + 30% Down + 20% Flat** from left to right")

        df = load_dataframe(material, excitation, Fmin,Fmax, Bmin, Bmax, Duty, Margin)

        if df.empty:
            st.write("Warning: No Data in Range")
        else:
            col1, col2 = st.columns(2)
            with col1:
                st.subheader(xaxis+' - Power Loss')
                if xaxis == 'Frequency':
                    st.plotly_chart(power_loss_scatter_plot(df, x='Frequency', color_prop='Duty_Ratio'), use_container_width=True)
                else:
                    st.plotly_chart(power_loss_scatter_plot(df, x='Flux_Density', color_prop='Duty_Ratio'), use_container_width=True)
            with col2:
                st.subheader(xaxis+' - Estimated Error')    
                if xaxis == 'Frequency':
                    st.plotly_chart(power_loss_scatter_plot(df, x='Frequency', color_prop='Duty_Ratio'), use_container_width=True)
                else:
                    st.plotly_chart(power_loss_scatter_plot(df, x='Flux_Density', color_prop='Duty_Ratio'), use_container_width=True)
            file = df.to_csv().encode('utf-8')
            st.download_button("Download CSV",file,material+"-"+excitation+".csv","text/csv",key=m)
            st.write("CSV Column: [Index; Frequency (Hz); Flux Density (mT); Duty Ratio; Power Loss (kW/m^3)]")
            st.write("Data Info: Core Shape - ? ; Temperature - ? ; Method - ? ; Winding Turns - ?; Princeton Measured")

    st.sidebar.markdown("""---""")
    st.markdown("""---""")
    )

    st.markdown(
        """If you then sell this mined HNT, the difference between the mined price and sell price will be realized as a capital gain/loss.
    Some more details [here](https://cryptotrader.tax/blog/how-to-handle-cryptocurrency-mining-on-your-taxes)."""
    )

    st.markdown(
        """Check us out on [Github](https://github.com/evandiewald/helium-taxable-mining-earnings)"""
    )

year = st.selectbox("Select Year", [2021, 2020])
mode = st.radio("Export Mode", ["By Wallet", "By Hotspot"])
address = st.text_input("Address")

submit = st.button("Submit")
if submit:
    with st.spinner("Processing...this may take a while"):
        if mode == "By Wallet":
            df, total_wallet_earnings = export_wallet_taxes(address, year=year)
            st.metric(f"Total Wallet Earnings for {year}",
                      value=f"$ {np.round(total_wallet_earnings, 2)}")
        elif mode == "By Hotspot":
            df, total_hotspot_earnings, hotspot_name = export_hotspot_taxes(
                address, year=year)
            st.metric(f"Total Earnings for {hotspot_name} in {year}",
                      value=f"$ {np.round(total_hotspot_earnings, 2)}")
        st.dataframe(df)
        download_button = st.download_button("Download CSV",
                                             data=df.to_string(),
                                             file_name=f"{address}.csv")
Exemplo n.º 16
0
    def test_just_disabled(self):
        """Test that it can be called with disabled param."""
        st.download_button("the label", data="juststring", disabled=True)

        c = self.get_delta_from_queue().new_element.download_button
        self.assertEqual(c.disabled, True)
Exemplo n.º 17
0
    def test_url_exist(self):
        """Test that file url exist in proto."""
        st.download_button("the label", data="juststring")

        c = self.get_delta_from_queue().new_element.download_button
        self.assertTrue("/media/" in c.url)
Exemplo n.º 18
0
fig1 = terrain_plot(x_terrain, y_terrain, z_terrain, z, N, xp, yp, zp,
                    color_scale, show_scale, show_contours, project_contours,
                    show_plane)
st.write(fig1)

fig2 = elevation_profile_plot(profile_x, profile_z)
st.write(fig2)

with st.sidebar:
    # Expander to extract and download data
    exp5 = st.expander('Extract and Download Data')
    with exp5:
        st.download_button('Download Elevation Profile as CSV',
                           data=pd.DataFrame({
                               'x': profile_x,
                               'z': profile_z
                           }).to_csv(index=False, header=None),
                           file_name='elevation_profile.csv',
                           mime='text/csv')

    st.title('About')
    st.markdown('''
    This 3D Terrain Generator web-based application is developed by Yared W. Bekele. The source code is available on [GitHub](https://github.com/yaredwb/3DTerrain).
  ''')
    st.markdown('''
    [GitHub](https://github.com/yaredwb)
    [LinkedIn](https://www.linkedin.com/in/yaredworku/)
    [Twitter](https://twitter.com/yaredwb)
    [Website](https://yaredwb.com)
  ''')
Exemplo n.º 19
0
import pandas as pd
from io import BytesIO
from pyxlsb import open_workbook as open_xlsb
import streamlit as st

def to_excel(df):
    output = BytesIO()
    writer = pd.ExcelWriter(output, engine='xlsxwriter')
    df.to_excel(writer, index=False, sheet_name='Sheet1')
    workbook = writer.book
    worksheet = writer.sheets['Sheet1']
    format1 = workbook.add_format({'num_format': '0.00'}) 
    worksheet.set_column('A:A', None, format1)  
    writer.save()
    processed_data = output.getvalue()
    return processed_data
df_xlsx = to_excel(df)
st.download_button(label='📥 Download Current Result',
                                data=df_xlsx ,
                                file_name= 'df_test.xlsx')
         'Report a bug': "https://github.com/yesdeepakmittal/COVID19-Pandemic-in-India/issues/new",
         'About': '''
                  # Impact of Covid19
                  This data analysis is an attempt find which location of India has most cases 
                  and how Covid19 cases increased overtime. The result might not be accurate. 

                  - Check the shared code on [Github](https://github.com/yesdeepakmittal/COVID19-Pandemic-in-India/) and do not forget to hit the star⭐ button.
                  ---
                  '''
     }
 )

with open('report.pdf','rb') as file:
    st.download_button(
        label = 'Download Complete Report',
        data = file,
        file_name='report.pdf',
        mime='pdf'
    )

st.title('Impact of Covid19')
st.subheader('*Analysing the impact of Covid19 on different part of India*')
st.write('''*👉This data analysis is for educational purpose only and may not 
    indicate accurate information. Please use other sources for accurate data.*''')


from analysis import Visualize
obj = Visualize()

fig = obj.save_funnel()
col1, col2 = st.columns(2)
col1.plotly_chart(fig, width=400,height=500)
Exemplo n.º 21
0
    def test_disabled_parameter_id_download_button(self):
        st.download_button("my_widget", data="")

        with self.assertRaises(errors.DuplicateWidgetID):
            st.download_button("my_widget", data="", disabled=True)
def main():

    df = pd.read_csv('Downloads/dpae-par-departement-x-grand-secteur.csv',
                     sep=';')
    df = df.fillna(0)
    cols = [
        'Code région', 'Région', 'Code ancienne région', 'Ancienne région',
        'Code département', 'Département', 'Durée de contrat',
        'Nature de contrat', 'Année', 'Trimestre', 'Dernier jour du trimestre',
        'DPAE (brut)', 'DPAE (cvs)'
    ]
    df[cols] = df[cols].replace('_calage_', 'CVS', regex=True)
    df["Grand secteur d'activité"] = df["Grand secteur d'activité"].replace(
        '_calage_', '404_CVS', regex=True)
    df["Grand secteur d'activité"] = df["Grand secteur d'activité"].str[4:]
    df[['DPAE (brut)', 'DPAE (cvs)']] = df[['DPAE (brut)',
                                            'DPAE (cvs)']].astype(int)
    df = df.rename(columns={'Code région': 'code'})
    df[['code', 'Année']] = df[['code', 'Année']].astype(str)

    #st.dataframe(df)
    #aggregating by region for the map
    df2 = df[['code', 'Région', 'DPAE (brut)',
              'DPAE (cvs)']].groupby(['Région',
                                      'code']).agg('sum').reset_index()

    st.markdown('#')

    json_fr = f"regions.geojson"

    fr = folium.Map(location=[46.232192999999995, 2.209666999999996],
                    tiles="CartoDB positron",
                    name='Carte de France',
                    zoom_start=5)

    folium.Choropleth(geo_data=json_fr,
                      name="choropleth",
                      data=df2,
                      columns=['code', "DPAE (brut)", 'DPAE (cvs)'],
                      key_on="properties.code",
                      fill_color='YlOrRd',
                      fill_opacity=0.8,
                      line_opacity=0.1,
                      legend_name='DPAE (brut)').add_to(fr)
    folium.features.GeoJson(
        'regions.geojson',
        name="Régions",
        popup=folium.features.GeoJsonPopup(fields=["nom"])).add_to(fr)

    folium_static(fr)
    st.markdown(
        "<p style='color:red;'>Lorsque vous dézommez sur la carte, vous pourrez également voir les DOM-TOM </p>",
        unsafe_allow_html=True)

    st.markdown('<hr>', unsafe_allow_html=True)

    region_choice = st.sidebar.multiselect("Région",
                                           df["Région"].sort_values().unique())
    if len(region_choice) == 0:
        departement_choice = st.sidebar.multiselect(
            "Département", df["Département"].sort_values().unique())
    else:
        departement_choice = st.sidebar.multiselect(
            "Département", (df["Département"][df['Région'].isin(region_choice)]
                            ).sort_values().unique())

    year_choice = st.sidebar.multiselect("Année",
                                         df["Année"].sort_values().unique(),
                                         default=['2020'])
    #if len(year_choice)>0:
    #   trimestre_choice = st.sidebar.multiselect("Trimestre", (df["Trimestre"][df['Année'].isin(year_choice)]).sort_values().unique())
    #else:
    #  st.sidebar.warning("Choisissez une année avant de pouvoir choisir un trimestre")

    activity_area = st.sidebar.multiselect(
        "Secteur d'activité",
        df["Grand secteur d'activité"].sort_values().unique())
    contract_type = st.sidebar.multiselect("Nature de contrat",
                                           df["Nature de contrat"].unique())

    pie = px.pie(
        df[df['Région'].isin(region_choice)
           | df["Département"].isin(departement_choice)
           | df["Année"].isin(year_choice)
           | df["Grand secteur d'activité"].isin(activity_area)],
        values='DPAE (brut)',
        names="Nature de contrat",
        title=
        "Proportion par type de contrat (filtres rattachés : Région, Département, Année, Secteur)"
    )
    st.plotly_chart(pie)

    st.markdown(
        "<center>Une très grande proportion de CDD parmi tous les DPAE, les entreprises semblent avoir du mal à faire signer des CDI en France ! </center>",
        unsafe_allow_html=True)

    st.markdown('#')
    st.markdown('<hr>', unsafe_allow_html=True)

    bar1 = px.bar(
        df[df['Région'].isin(region_choice)
           | df["Département"].isin(departement_choice)
           | df["Année"].isin(year_choice)
           | df["Nature de contrat"].isin(contract_type)],
        x="Grand secteur d'activité",
        y="DPAE (brut)",
        title=
        "Proportion par type de contrat (filtres rattachés : Région, Département, Année, Nature Contrat)"
    )
    st.plotly_chart(bar1)

    st.markdown('#')
    st.markdown('<hr>', unsafe_allow_html=True)

    df3 = df[['Année', 'Région', 'DPAE (brut)',
              'DPAE (cvs)']].groupby(['Région',
                                      'Année']).agg('sum').reset_index()

    lin = alt.Chart(df).mark_line().encode(
        x="Année", y="DPAE (brut)", color="Nature de contrat").properties(
            title='Évolution DPAE depuis 2000', height=700, width=800)

    st.altair_chart(lin)
    st.write("La pandémie du Coronavirus a eu un réel impact sur l'emploi")
    st.info("Fact : La précarité a augmenté de 7,5% sur l'année 2020")

    st.markdown('#')
    st.markdown('#')
    st.markdown('<hr>', unsafe_allow_html=True)

    minimum = df[
        'DPAE (brut)'][df['Région'].isin(region_choice)
                       | df["Département"].isin(departement_choice)
                       | df["Année"].isin(year_choice)
                       | df["Grand secteur d'activité"].isin(activity_area)
                       | df["Nature de contrat"].isin(contract_type)].min()
    maximum = df[
        'DPAE (brut)'][df['Région'].isin(region_choice)
                       | df["Département"].isin(departement_choice)
                       | df["Année"].isin(year_choice)
                       | df["Grand secteur d'activité"].isin(activity_area)
                       | df["Nature de contrat"].isin(contract_type)].max()

    col1, col2 = st.columns(2)
    col1.metric('Minimum enregistré sur un trimestre', value=minimum)
    col2.metric('Maximum enregistré sur un trimestre', value=maximum)

    st.markdown('#')
    st.markdown('#')
    st.markdown('<hr>', unsafe_allow_html=True)

    st.dataframe((df[df['Région'].isin(region_choice)
                     | df["Département"].isin(departement_choice)
                     | df["Année"].isin(year_choice)
                     | df["Grand secteur d'activité"].isin(activity_area)
                     | df["Nature de contrat"].isin(contract_type)]).head())
    st.success("Vous pouvez utilisez tous les filtres sur le dataframe")

    @st.cache
    def convert_df(df):
        return df.to_csv().encode('utf-8')

    csv = convert_df(df)

    st.download_button(label="Download cleaned data as CSV",
                       data=csv,
                       file_name='2000_2021_dpae_par_departement.csv',
                       mime='text/csv')

    st.sidebar.markdown('#')

    link2 = '[METADATA](https://open.urssaf.fr/explore/dataset/dpae-par-region-x-na38/information/?dataChart=eyJxdWVyaWVzIjpbeyJjaGFydHMiOlt7InR5cGUiOiJjb2x1bW4iLCJmdW5jIjoiU1VNIiwieUF4aXMiOiJkcGFlX2N2cyIsInNjaWVudGlmaWNEaXNwbGF5Ijp0cnVlLCJjb2xvciI6InJhbmdlLVBhaXJlZCIsInBvc2l0aW9uIjoiY2VudGVyIn1dLCJ4QXhpcyI6ImRlcm5pZXJfam91cl9kdV90cmltZXN0cmUiLCJtYXhwb2ludHMiOiIiLCJ0aW1lc2NhbGUiOiJtb250aCIsInNvcnQiOiIiLCJzZXJpZXNCcmVha2Rvd24iOiJuYXR1cmVfZGVfY29udHJhdCIsInNlcmllc0JyZWFrZG93blRpbWVzY2FsZSI6IiIsInN0YWNrZWQiOiJub3JtYWwiLCJjb25maWciOnsiZGF0YXNldCI6ImRwYWUtcGFyLXJlZ2lvbi14LW5hMzgiLCJvcHRpb25zIjp7fX19XSwiZGlzcGxheUxlZ2VuZCI6dHJ1ZSwiYWxpZ25Nb250aCI6dHJ1ZSwic2luZ2xlQXhpcyI6dHJ1ZSwidGltZXNjYWxlIjoiIn0%3D)'
    st.sidebar.markdown(link2, unsafe_allow_html=True)

    st.sidebar.markdown("##")

    link = '[GitHub](https://github.com/AkramBensalemPSB/PSB)'
    st.sidebar.markdown(link, unsafe_allow_html=True)

    st.sidebar.write('PAR BENSALEM AKRAM TRADEMARKS')
Exemplo n.º 23
0
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import streamlit as st

st.download_button(
    "Download button label",
    data="Hello world!",
    file_name="hello.txt",
)

st.download_button(
    "Download button label", data="Hello world!", file_name="hello.txt", disabled=True
)

st.download_button(
    "Download RAR archive file",
    data=b"bytes",
    file_name="archive.rar",
    mime="application/vnd.rar",
)
st.write(f"J$_{'s'}$$_{'c'}$ = {maxpcemeta[5]:.3f} mA/cm$^{2}$")
st.write(f"V$_{'o'}$$_{'c'}$ = {maxpcemeta[6]:.3f} V")
st.write(f"FF = {maxpcemeta[4]:.3f}")
st.write(f"PCE = {maxpcemeta[3] * 100:.3f} %")

st.write("## Plots & Data")

c = alt.Chart(df_2).mark_line(point=True).encode(
    x="Voltage (V)", y="Current Density (mA/cm2)"
)
with st.expander("J-V Curve"):
    st.altair_chart(c, use_container_width=True)


    csv = df_2.to_csv(index=False).encode('utf-8')
    st.download_button("Download J-V Data", data=csv, file_name=f"jv_{bandgap}_{cell_temperature}.csv", mime='text/csv')
    # display dataframe
    st.dataframe(df_2)


c_pce = alt.Chart(df).mark_line(point=True).encode(
    x="Bandgap (eV)", y="PCE (%)"
)

c_voc = alt.Chart(df).mark_line(point=True).encode(
    x="Bandgap (eV)", y="Voc (V)"
)

c_jsc = alt.Chart(df).mark_line(point=True).encode(
    x="Bandgap (eV)", y="Jsc (mA/cm2)"
)
Exemplo n.º 25
0
def app_main():

    # Design settings:
    four_columns = np.array([0.40, 0.28, 0.22, 0.10])
    three_columns = np.array([0.40, 0.36, 0.24])
    two_columns = np.array(
        [three_columns[0] + three_columns[1], three_columns[2]])

    # Persistent attributes:
    session = ss.get(map_counter=0, ai_counter=0, prep2_counter=0, post2=None)

    # Count articles:

    # Place title and buttion:
    col1, col2 = st.columns(two_columns + np.array([0.09, -0.09]))
    with col1:
        st.markdown('### Matérias por estágio de captura')
    with col2:
        run_mapper = st.button('Mapear')
        if run_mapper:
            session.map_counter += 1

    # Count articles along the capture pipeline:
    df, error_msgs = counts_dataframe(session.map_counter)
    # Display counts DataFrame:
    try:
        fmt_funcs = generate_formatters(df)
        st.dataframe(
            df.style.format(fmt_funcs).applymap(
                ff.style_below_step, props='background-color:pink;'))
    except:
        st.dataframe(df)
    for msg in error_msgs:
        st.error(msg)

    hh.html('<hr />')

    # Run IA:

    # Place title and button:
    col1, col2 = st.columns(two_columns + np.array([0.05, -0.05]))
    with col1:
        st.markdown('### Pré-ordenamento')
    with col2:
        run_ai = st.button('Executar IA')

    # Display progress bar state:
    if session.ai_counter == 0:
        ai_bar = st.progress(0)
    else:
        ai_bar = st.progress(100)

    # Run AI:
    if run_ai:
        session.ai_counter += 1
        rp.run_python_process()
        progress_bar(ai_bar, 75)

    hh.html('<hr />')

    # Link to sheet & others:

    ranking_sheet_url = 'https://docs.google.com/spreadsheets/d/11dnbTxiighjkq8LzmKZAJ8PsrI2EOG6yNw4InWPhTGE'
    vetos_url = 'https://www.in.gov.br/consulta/-/buscar/dou?q=%22decidi+vetar%22&s=do1&exactDate=day&orgPrin=Presid%C3%AAncia+da+Rep%C3%BAblica'
    slack_url = 'https://app.slack.com/client/TGM1R75MM/CK41CADJA'

    col1, col2, col3, col4 = st.columns(four_columns)
    with col1:
        st.markdown('### Links importantes')
    with col2:
        external_link('Planilha de matérias', ranking_sheet_url)
    with col3:
        external_link('Vetos de hoje', vetos_url)
    with col4:
        external_link('Slack', slack_url)

    hh.html('<hr />')

    # Generate posts:

    # Place title and buttons:
    col1, col2, col3 = st.columns(three_columns)
    with col1:
        st.markdown('### Preparação do boletim')
    with col2:
        preformatted_sec1 = c1.gen_preformatted_post(
            '../templates/modelo_zap_materias_dou_1.txt')
        filename_sec1 = c1.gen_post_filename('dou_1_')
        st.download_button('Modelo da seção 1',
                           preformatted_sec1,
                           file_name=filename_sec1,
                           mime='text/plain')
    with col3:
        filename_sec2 = f2.gen_post_filename('dou_2_')
        compute_download_button(session, 'post2', f2.etl_section2_post,
                                'Preparar seção 2', 'Baixar seção 2',
                                filename_sec2)
Exemplo n.º 26
0
def customize_plot():
    st.set_page_config(
        page_title="Extaedio",
        page_icon="🧊",
        layout="wide",
        initial_sidebar_state="expanded",
    )

    step = 1

    st.title("Ex Taedio: Dataframe (CSV) plotting dashboard")

    reporting_mode = st.checkbox(label="Switch to report mode", value=False)
    st.info("""
        **About report mode:**  Report mode allows you to reproduce a plot made 
        by somebody else by loading a JSON configuration file that you got from another user.
        """)
    if reporting_mode:
        report_path = st.file_uploader(
            label="Select JSON file containing plot parameters and options")
        if report_path is None:
            return
        report = json.loads(report_path.getvalue())
    else:
        report = {}

    st.markdown("""___""")

    col_set_1, col_set_2 = st.columns(2)
    col_set_1.header(f"Settings:")
    col_set_2.header("")
    ui_modes = [
        "no_choice_all_help",
        "no_choice_some_help",
        "all_choices",
    ]
    ui_lvl_beg = "no_choice_all_help"
    ui_lvl_nrm = "no_choice_some_help"
    ui_lvl_xp = "all_choices"
    ui_mode = col_set_1.selectbox(
        label="User interface mode",
        options=ui_modes,
        index=get_final_index(default_index=1,
                              options=ui_modes,
                              key="ui_mode",
                              overrides=report),
        format_func=lambda x: {
            ui_lvl_beg: "Beginner",
            ui_lvl_nrm: "Normal",
            ui_lvl_xp: "Expert",
        }.get(x, "Unknown"),
    )

    help_levels = ["none", "mandatory", "all"]
    param_help_level = col_set_2.selectbox(
        label="Show help related to plot parameters:",
        options=help_levels,
        format_func=lambda x: {
            "none": "Never",
            "mandatory":
            "When waiting for non optional parameters (recommended)",
            "all": "Always",
        }.get(x, "all"),
        index=get_final_index(
            default_index=0
            if ui_mode == ui_lvl_xp else 1 if ui_mode == ui_lvl_nrm else 2,
            options=help_levels,
            key="param_help_level",
            overrides=report,
        ),
    )

    real_time_render = col_set_2.checkbox(
        label="""
        Realtime rendering: build plot as soon as a parameter is changed, may render the UI unresponsive. Disabled for animations
        """,
        value=report.get("real_time_render", False),
    )

    show_info = col_set_2.checkbox(
        label="Show information panels (blue panels with hints and tips).",
        value=report.get("show_info", ui_mode == ui_lvl_beg),
    )

    use_side_bar = col_set_2.checkbox(
        label="Plot settings to side bar",
        value=report.get("use_side_bar", True),
    )
    if show_info:
        col_set_2.info("""
            **Plot settings to side bar**:Put the plot setttings in the sidebar instead 
            of with all the other settings (Recommended).
            """)

    show_advanced_plots = col_set_2.checkbox(
        label="Show advanced plots.",
        value=report.get("show_advanced_plots", ui_mode == ui_lvl_xp),
    )
    if show_info:
        col_set_2.info(
            """**Show advanced plots.**: Expand the list of available plots.
        Includes among others PCA3D, LDA, density plots, ...""")

    if report:
        col_set_2.warning(
            "Avoid modifying the dataframe while in report mode, some columns may be needed later"
        )
    show_dw_options = col_set_2.checkbox(
        label="Show dataframe customization options.",
        value=report.get("show_dw_options", False),
    )
    if show_info:
        col_set_2.info(
            "**Show dataframe customization options**: Add widgets to sort, filter and clean the dataframe."
        )

    show_advanced_settings = col_set_2.checkbox(
        label="Show plot advanced parameters",
        value=report.get("show_advanced_settings", ui_mode == ui_lvl_xp),
    )
    if show_info:
        col_set_2.info("""**Show plot customization advanced parameters**: 
            Add widgets to further customize the plots.  
            Usefull if the rendering takes too long when changing a parameter.
            """)

    st.markdown("""___""")

    if "dataframe" in report:
        df = pd.DataFrame.from_dict(report.get("dataframe", {}))
        dw_options = {}
    else:
        df = amp_st_functs.load_dataframe(step=step, show_info=show_info)
        step += 1
    if df is None:
        return

    dw_options = {}

    if show_dw_options:
        st.header(f"Step {step} - Data wrangling")
        st.subheader("Source dataframe")
        col_head_count, col_df_desc_title, col_df_data_title = st.columns(
            [2, 2, 1])
        col_head, col_df_desc, col_df_data_ = st.columns([2, 2, 1])
        line_display_count = col_head_count.number_input(
            label="Dataframe lines to display",
            min_value=5,
            max_value=1000,
            value=5)
        col_head.dataframe(df.head(line_display_count))
        col_df_desc_title.markdown("Data frame numerical columns description")
        col_df_desc.dataframe(df.describe())

        col_df_data_title.markdown("Dataframe's column types")
        col_df_data_.dataframe(
            pd.DataFrame({
                "column": df.columns,
                "type": [d for d in df.dtypes.to_list()],
            }).astype(str))

        st.subheader(f"Sort")
        if show_info:
            st.info("""
            Select columns to sort the dataframe, if multiple columns are selected,
            sort will be applied in the displayed order.
            """)
        dw_options["sort_columns"] = st.multiselect(
            label="Sort by", options=df.columns.to_list())
        dw_options["invert_sort"] = st.checkbox(label="Reverse sort?",
                                                value=False)

        st.subheader("Filter dataframe")
        if show_info:
            st.info("""Select which columns and rows will be filtered.  
                Only date and string columns can be filtered at the moment""")

        col_filter_columns, col_filter_rows = st.columns(2)
        dw_options["kept_columns"] = col_filter_columns.multiselect(
            label="Columns to keep",
            options=df.columns.to_list(),
            default=df.columns.to_list(),
        )

        filter_columns = col_filter_rows.multiselect(
            label="Select which columns you want to use to filter the rows:",
            options=df.select_dtypes(
                include=["object", "datetime", "number"]).columns.to_list(),
            default=None,
        )
        if filter_columns and show_info:
            st.info(
                """For each selected column select all the values that will be included.
                Less rows means faster dashboard""")
        dw_options["filters"] = {}
        for column in filter_columns:
            st.subheader(f"{column}: ")
            select_all = st.checkbox(label=f"{column} Select all:")
            elements = list(df[column].unique())
            dw_options["filters"][column] = st.multiselect(
                label=f"Select which {column} to include",
                options=elements,
                default=None if not select_all else elements,
            )

        st.subheader("Bin numerical columns")
        if show_info:
            st.info("""Select which columns will be binned.  
                Numeric columns only""")
        bin_columns = st.multiselect(
            label="Select which columns you want replace by bins:",
            options=df.select_dtypes(include=[np.number]).columns.to_list(),
            default=None,
        )
        if bin_columns and show_info:
            st.info("""For each selected column select the bin value""")
        dw_options["binners"] = {}
        for column in bin_columns:
            st.subheader(f"{column}: ")
            dw_options["binners"][column] = st.number_input(
                label="Bin count:",
                min_value=1,
                max_value=len(df[column].unique()),
                value=10,
            )

        st.subheader("Clean")
        if show_info:
            st.info(
                "Some plots like PCA won't work if NA values are present in the dataframe"
            )
        clr_1, clr_2 = st.columns(2)
        dw_options["remove_na"] = clr_1.checkbox(
            label="Remove rows with NA values", value=False)
        dw_options["remove_duplicates"] = clr_2.checkbox(
            label="Remove duplicates", value=False)

        df = wrangle_the_data(df=df, dw_options=dw_options)

        df = df.reset_index(drop=True)

        st.subheader("Transformed dataframe")
        col_tr_head_title, col_tr_df_desc_title, col_tr_df_data_title = st.columns(
            [2, 2, 1])
        col_tr_head, col_tr_df_desc, col_tr_df_data_ = st.columns([2, 2, 1])

        col_tr_head_title.markdown("dataframe first rows")
        col_tr_head.dataframe(df.head(line_display_count))
        col_tr_df_desc_title.markdown(
            "Data frame numerical columns description")
        col_tr_df_desc.dataframe(df.describe())

        col_tr_df_data_title.markdown("Dataframe's column types")
        col_tr_df_data_.dataframe(
            pd.DataFrame({
                "column": df.columns,
                "type": [d for d in df.dtypes.to_list()],
            }).astype(str))

    qs = st.sidebar if use_side_bar else st
    if use_side_bar:
        pass
    else:
        st.header(f"Step {step} - Plot customization")
        step += 1

    qs.subheader("Plot selection")

    # Select type
    plot_options = amp_consts.ALL_PLOTS if show_advanced_plots else amp_consts.BASIC_PLOTS
    plot_type = qs.selectbox(
        label="Plot type: ",
        options=plot_options,
        index=get_final_index(
            default_index=0,
            options=plot_options,
            key="plot_type",
            overrides=report,
        ),
    )
    st.header(
        f"Step {step} - &darr; Plot {plot_type}{' customization (Widgets in sidebar)' if use_side_bar else ''} &darr;"
    )
    step += 1

    st.write(get_plot_help_digest(plot_type))
    if plot_type in [amp_consts.PLOT_LDA_2D, amp_consts.PLOT_NCA]:
        qs.warning(
            "If plotting fails, make sure that no variable is colinear with your target"
        )
    comment = report.get("comment", "")
    param_help_level = "mandatory"
    if comment:
        st.subheader("A word from the creator")
        st.markdown(comment)

    params = get_plot_docstring(plot_type).split("\nParameters")[1].split(
        "\n")[2:]
    params_dict = defaultdict(list)
    current_key = ""
    for l in params:
        if l.startswith("    "):
            params_dict[current_key].append(l.replace("    ", " "))
        else:
            current_key = l
    plot_data_dict = {}

    param_initializer = ParamInitializer(
        parent=qs,
        params_doc=params_dict,
        overrides=report.get("params", {}),
        show_help=param_help_level,
    )

    # Select mode
    is_anim = (report.get("is_anim", False)
               if report else plot_type in amp_consts.PLOT_HAS_ANIM
               and qs.checkbox(label="Build animation", value=False))

    if is_anim:
        if report:
            plot_data_dict["time_column"] = param_initializer(
                widget_params={},
                param_name="time_column",
                doc_override=
                "A column from the dataframe used as key to build frames",
                lock=True,
            )
            plot_data_dict["animation_group"] = param_initializer(
                param_name="animation_group",
                widget_params=dict(
                    label="Animation category group",
                    options=[amp_consts.NONE_SELECTED] + df.select_dtypes(
                        include=["object", "datetime"]).columns.to_list(),
                    index=0,
                ),
            )
        else:
            amp_st_functs.set_anim_data(
                df=df,
                show_info=show_info,
                plot_data_dict=plot_data_dict,
                param_initializer=param_initializer,
                qs=qs,
            )

    qs.subheader("Basic parameters")
    num_columns = df.select_dtypes(include=[np.number]).columns.to_list()
    cat_columns = df.select_dtypes(
        include=["object", "datetime", "int64"]).columns.to_list()
    supervision_columns = df.select_dtypes(
        include=["object", "number"]).columns.to_list()
    all_columns = df.columns.to_list()

    if plot_type in amp_consts.PLOT_HAS_X:
        if plot_type in [amp_consts.PLOT_SCATTER, amp_consts.PLOT_LINE]:
            x_columns = [amp_consts.PICK_ONE] + all_columns
        elif plot_type in [amp_consts.PLOT_SCATTER_3D]:
            x_columns = [amp_consts.PICK_ONE] + all_columns
        elif plot_type in [amp_consts.PLOT_BAR]:
            x_columns = [amp_consts.PICK_ONE] + cat_columns
        elif plot_type in [amp_consts.PLOT_BOX, amp_consts.PLOT_VIOLIN]:
            x_columns = [amp_consts.NONE_SELECTED] + cat_columns
        elif plot_type == amp_consts.PLOT_HISTOGRAM:
            x_columns = [amp_consts.PICK_ONE] + all_columns
        elif plot_type in [
                amp_consts.PLOT_DENSITY_HEATMAP,
                amp_consts.PLOT_DENSITY_CONTOUR,
        ]:
            x_columns = [amp_consts.PICK_ONE] + num_columns
        else:
            x_columns = []
    else:
        x_columns = []

    if plot_type in amp_consts.PLOT_HAS_Y:
        if plot_type in [amp_consts.PLOT_SCATTER, amp_consts.PLOT_LINE]:
            y_columns = [amp_consts.PICK_ONE] + all_columns
        elif plot_type in [amp_consts.PLOT_SCATTER_3D]:
            y_columns = [amp_consts.PICK_ONE] + all_columns
        elif plot_type in [amp_consts.PLOT_BAR]:
            y_columns = [amp_consts.PICK_ONE] + all_columns
        elif plot_type in [amp_consts.PLOT_BOX, amp_consts.PLOT_VIOLIN]:
            y_columns = [amp_consts.PICK_ONE] + all_columns
        elif plot_type == amp_consts.PLOT_HISTOGRAM:
            y_columns = [amp_consts.PICK_ONE] + all_columns
        elif plot_type in [
                amp_consts.PLOT_DENSITY_HEATMAP,
                amp_consts.PLOT_DENSITY_CONTOUR,
        ]:
            y_columns = [amp_consts.PICK_ONE] + num_columns
        else:
            y_columns = []
    else:
        y_columns = []

    if plot_type in amp_consts.PLOT_HAS_Z:
        if plot_type in [amp_consts.PLOT_SCATTER_3D]:
            z_columns = [amp_consts.PICK_ONE] + all_columns
        else:
            z_columns = []
    else:
        z_columns = []

    # Customize X axis
    if plot_type in amp_consts.PLOT_HAS_X:
        plot_data_dict["x"] = param_initializer(
            param_name="x",
            widget_params=dict(label="X axis", options=x_columns, index=0),
        )
        if (show_advanced_settings and plot_data_dict["x"] in num_columns
                and plot_type not in [
                    amp_consts.PLOT_PARALLEL_CATEGORIES,
                    amp_consts.PLOT_PARALLEL_COORDINATES,
                    amp_consts.PLOT_SCATTER_MATRIX,
                ]):
            plot_data_dict["log_x"] = param_initializer(
                widget_type="checkbox",
                param_name="log_x",
                widget_params=dict(label="Log X axis?"),
            )
        if plot_data_dict["x"] == amp_consts.PICK_ONE:
            return

    if plot_type == amp_consts.PLOT_HISTOGRAM:
        plot_data_dict["histfunc"] = param_initializer(
            param_name="histfunc",
            widget_params=dict(
                label="Histogram function",
                options=["count", "sum", "avg", "min", "max"],
                format_func=lambda x: {
                    "count": "Count",
                    "sum": "Sum",
                    "avg": "Average",
                    "min": "Minimum",
                    "max": "Maximum",
                }.get(x, "Unknown histogram mode"),
            ),
        )
    elif plot_type in amp_consts.PLOT_HAS_Y:
        # Customize Y axis
        plot_data_dict["y"] = param_initializer(
            param_name="y",
            widget_params=dict(label="Y axis", options=y_columns, index=0),
        )
        if (show_advanced_settings and plot_data_dict["y"] in num_columns
                and plot_type not in [
                    amp_consts.PLOT_PARALLEL_CATEGORIES,
                    amp_consts.PLOT_PARALLEL_COORDINATES,
                    amp_consts.PLOT_SCATTER_MATRIX,
                ]):
            plot_data_dict["log_y"] = param_initializer(
                widget_type="checkbox",
                param_name="log_y",
                widget_params=dict(label="Log Y axis?"),
            )
        if plot_data_dict["y"] == amp_consts.PICK_ONE:
            return

    if plot_type == amp_consts.PLOT_SCATTER_3D:
        plot_data_dict["z"] = param_initializer(
            param_name="z",
            widget_params=dict(label="Z axis", options=z_columns, index=0),
        )
        if show_advanced_settings and plot_data_dict["z"] in num_columns:
            plot_data_dict["log_z"] = param_initializer(
                widget_type="checkbox",
                param_name="log_z",
                widget_params=dict(label="Log Z axis?"),
            )
        else:
            plot_data_dict["log_z"] = False
        if plot_data_dict["z"] == amp_consts.PICK_ONE:
            return

    # Target for supervised machine learning
    if plot_type in amp_consts.PLOT_HAS_TARGET:
        plot_data_dict["target"] = param_initializer(
            param_name="target",
            widget_params=dict(
                label="ML target:",
                options=[amp_consts.PICK_ONE] + supervision_columns,
                index=0,
            ),
        )
        if plot_data_dict["target"] == amp_consts.PICK_ONE:
            return
        elif (plot_data_dict["target"]
              in df.select_dtypes(include=[np.float]).columns.to_list()
              and show_info):
            qs.info("Non discrete columns will be rounded")

    # Color column
    if plot_type in amp_consts.PLOT_HAS_COLOR:
        plot_data_dict["color"] = param_initializer(
            param_name="color",
            widget_params=dict(
                label="Use this column for color:",
                options=[amp_consts.NONE_SELECTED] + all_columns,
                index=0 if plot_type not in amp_consts.PLOT_HAS_TARGET else
                all_columns.index(plot_data_dict["target"]) + 1,
            ),
        )

    # Ignored columns
    if plot_type in amp_consts.PLOT_HAS_IGNORE_COLUMNS:
        default_ignored_columns = ([plot_data_dict["target"]] if plot_type
                                   in amp_consts.PLOT_HAS_TARGET else [])
        if is_anim:
            default_ignored_columns.append(plot_data_dict["time_column"])
        plot_data_dict["ignore_columns"] = param_initializer(
            widget_type="multiselect",
            param_name="ignore_columns",
            widget_params=dict(
                label="Ignore this columns when building the model:",
                options=all_columns,
                default=default_ignored_columns,
            ),
            doc_override="""
                This columns will be omitted when building the model, 
                but available for display.  
                Use this to avoid giving the answer to the question when building models.
                """,
        )
    if show_advanced_settings:
        qs.subheader("Advanced parameters:")
        # Common data
        available_marginals = [
            amp_consts.NONE_SELECTED,
            "rug",
            "box",
            "violin",
            "histogram",
        ]
        # Solver selection
        if plot_type in amp_consts.PLOT_HAS_SOLVER:
            plot_data_dict["solver"] = param_initializer(
                param_name="solver",
                widget_params=dict(
                    label="Solver",
                    options=["svd", "eigen"],
                    index=0,
                    format_func=lambda x: {
                        "svd": "Singular value decomposition",
                        "eigen": "Eigenvalue decomposition",
                    }.get(x, "svd"),
                ),
            )
        # About NCA
        if plot_type in amp_consts.PLOT_HAS_NCOMP:
            plot_data_dict["n_components"] = param_initializer(
                widget_type="number_input",
                param_name="n_components",
                widget_params=dict(
                    label="Number of components",
                    min_value=2,
                    max_value=len(num_columns),
                    value=2,
                ),
            )
        if plot_type in amp_consts.PLOT_HAS_INIT:
            plot_data_dict["init"] = param_initializer(
                param_name="init",
                widget_params=dict(
                    label="Linear transformation init",
                    options=["auto", "pca", "lda", "identity", "random"],
                    index=0,
                ),
            )
            if plot_data_dict["init"] == "auto":
                qs.markdown("""
                    Depending on n_components, the most reasonable initialization will be 
                    chosen. If n_components <= n_classes we use ‘lda’, as it uses labels 
                    information. If not, but n_components < min(n_features, n_samples), 
                    we use ‘pca’, as it projects data in meaningful directions 
                    (those of higher variance). Otherwise, we just use ‘identity’.
                    """)
            elif plot_data_dict["init"] == "pca":
                qs.markdown(
                    """n_components principal components of the inputs passed to 
                    fit will be used to initialize the transformation.""")
            elif plot_data_dict["init"] == "lda":
                qs.markdown("""
                    min(n_components, n_classes) most discriminative components of
                    the inputs passed to fit will be used to initialize the transformation. 
                    (If n_components > n_classes, the rest of the components will be zero.)
                    """)
            elif plot_data_dict["init"] == "identity":
                qs.markdown("""
                    If n_components is strictly smaller than the dimensionality 
                    of the inputs passed to 
                    fit, the identity matrix will be truncated to the first n_components rows.
                    """)
            elif plot_data_dict["init"] == "random":
                qs.markdown("""
                    The initial transformation will be a random array of shape 
                    (n_components, n_features). 
                    Each value is sampled from the standard normal distribution.
                    """)
            qs.markdown("___")
        # Dot text
        if plot_type in amp_consts.PLOT_HAS_TEXT:
            plot_data_dict["text"] = param_initializer(
                param_name="text",
                widget_params=dict(
                    label="Text display column",
                    options=[amp_consts.NONE_SELECTED] + cat_columns,
                    index=0,
                ),
            )
        # Dot size
        if plot_type in amp_consts.PLOT_HAS_SIZE:
            plot_data_dict["size"] = param_initializer(
                param_name="size",
                widget_params=dict(
                    label="Use this column to select what dot size represents:",
                    options=[amp_consts.NONE_SELECTED] + num_columns,
                    index=0,
                ),
            )
            plot_data_dict["size_max"] = param_initializer(
                widget_type="number_input",
                param_name="size_max",
                widget_params=dict(label="Max dot size",
                                   min_value=11,
                                   max_value=100,
                                   value=60),
            )
        if plot_type in amp_consts.PLOT_HAS_COMPONENT_LIMIT:
            plot_data_dict["dimensions"] = param_initializer(
                widget_type="number_input",
                param_name="dimensions",
                widget_params=dict(
                    label="PC count",
                    min_value=1,
                    max_value=100,
                    value=6,
                ),
            )
        if plot_type in amp_consts.PLOT_HAS_SHAPE:
            plot_data_dict["symbol"] = param_initializer(
                param_name="symbol",
                widget_params=dict(
                    label="Select a column for the dot symbols",
                    options=[amp_consts.NONE_SELECTED] + cat_columns,
                    index=0,
                ),
            )
        if plot_type in amp_consts.PLOT_HAS_TREND_LINE:
            allowed = plot_data_dict["x"] in df.select_dtypes(
                include=np.number)
            options = ([amp_consts.NONE_SELECTED, "ols", "lowess"]
                       if allowed is True else [amp_consts.NONE_SELECTED])
            plot_data_dict["trendline"] = param_initializer(
                param_name="trendline",
                widget_params=dict(
                    label="Trend line mode",
                    options=options,
                    format_func=lambda x: {
                        "ols": "Ordinary Least Squares ",
                        "lowess": "Locally Weighted scatterplot Smoothing",
                    }.get(x, x),
                ),
            )
            if allowed is not True:
                qs.info("Trend line needs numeric X axis")

        # Facet
        if plot_type in amp_consts.PLOT_HAS_FACET:
            plot_data_dict["facet_col"] = param_initializer(
                param_name="facet_col",
                widget_params=dict(
                    label="Use this column to split the plot in columns:",
                    options=[amp_consts.NONE_SELECTED] + cat_columns,
                    index=0,
                ),
            )
            if plot_data_dict["facet_col"] != amp_consts.NONE_SELECTED:
                plot_data_dict["facet_col_wrap"] = param_initializer(
                    widget_type="number_input",
                    param_name="facet_col_wrap",
                    widget_params=dict(
                        label="Wrap columns when more than x",
                        min_value=1,
                        max_value=20,
                        value=4,
                    ),
                )
            else:
                plot_data_dict["facet_col_wrap"] = 4
            plot_data_dict["facet_row"] = param_initializer(
                param_name="facet_row",
                widget_params=dict(
                    label="Use this column to split the plot in lines:",
                    options=[amp_consts.NONE_SELECTED] + cat_columns,
                    index=0,
                ),
            )
        # Histogram specific parameters
        if plot_type in amp_consts.PLOT_HAS_MARGINAL and is_anim:
            plot_data_dict["marginal"] = param_initializer(
                param_name="marginal",
                widget_params=dict(label="Marginal",
                                   options=available_marginals,
                                   index=0),
            )
            plot_data_dict["orientation"] = param_initializer(
                param_name="orientation",
                widget_params=dict(
                    label="orientation",
                    options=["v", "h"],
                    format_func=lambda x: {
                        "v": "vertical",
                        "h": "horizontal"
                    }.get(x, "unknown value"),
                    index=0,
                ),
            )
        if plot_type in amp_consts.PLOT_HAS_BAR_MODE:
            plot_data_dict["barmode"] = param_initializer(
                param_name="barmode",
                widget_params=dict(
                    label="bar mode",
                    options=[
                        "group",
                        "overlay",
                        "relative",
                    ],
                    index=2,
                ),
            )
        if plot_type in amp_consts.PLOT_HAS_MARGINAL_XY and is_anim:
            plot_data_dict["marginal_x"] = param_initializer(
                param_name="marginal_x",
                widget_params=dict(label="Marginals for X axis",
                                   options=available_marginals,
                                   index=0),
            )
            plot_data_dict["marginal_y"] = param_initializer(
                param_name="marginal_y",
                widget_params=dict(label="Marginals for Y axis",
                                   options=available_marginals,
                                   index=0),
            )
        # Box plots and histograms
        if plot_type in amp_consts.PLOT_HAS_POINTS:
            plot_data_dict["points"] = param_initializer(
                param_name="points",
                widget_params=dict(
                    label="Select which points are displayed",
                    options=["none", "outliers", "suspectedoutliers", "all"],
                    index=1,
                ),
            )
            plot_data_dict["points"] = (plot_data_dict["points"]
                                        if plot_data_dict["points"] != "none"
                                        else False)
        # Box plots
        if plot_type == amp_consts.PLOT_BOX:
            plot_data_dict["notched"] = param_initializer(
                param_name="notched",
                widget_type="checkbox",
                widget_params=dict(label="Use notches?", value=False),
            )
        # Violin plots
        if plot_type == amp_consts.PLOT_VIOLIN:
            plot_data_dict["box"] = param_initializer(
                param_name="box",
                widget_type="checkbox",
                widget_params=dict(
                    label="Show boxes",
                    value=False,
                ),
            )
            plot_data_dict["violinmode"] = param_initializer(
                param_name="violinmode",
                widget_params=dict(label="Violin display mode",
                                   options=["group", "overlay"]),
            )
        # Density heat map
        if plot_type in amp_consts.PLOT_HAS_BINS:
            plot_data_dict["nbinsx"] = param_initializer(
                widget_type="number_input",
                param_name="nbinsx",
                widget_params=dict(
                    label="Number of bins in the X axis",
                    min_value=1,
                    max_value=1000,
                    value=20,
                ),
            )
            plot_data_dict["nbinsy"] = param_initializer(
                widget_type="number_input",
                param_name="nbinsy",
                widget_params=dict(
                    label="Number of bins in the Y axis",
                    min_value=1,
                    max_value=1000,
                    value=20,
                ),
            )
        # Density contour map
        if plot_type == amp_consts.PLOT_DENSITY_CONTOUR:
            plot_data_dict["fill_contours"] = param_initializer(
                param_name="fill_contours",
                widget_params=dict(label="Fill contours", value=False),
            )
        # PCA loadings
        if plot_type in amp_consts.PLOT_HAS_LOADINGS:
            plot_data_dict["show_loadings"] = param_initializer(
                param_name="show_loadings",
                widget_type="checkbox",
                widget_params=dict(label="Show loadings", value=False),
            )
        # Correlation plot
        if plot_type == amp_consts.PLOT_CORR_MATRIX:
            plot_data_dict["corr_method"] = param_initializer(
                param_name="corr_method",
                widget_params=dict(
                    label="Correlation method",
                    options=["pearson", "kendall", "spearman"],
                    format_func=lambda x: {
                        "pearson":
                        "pearson : standard correlation coefficient",
                        "kendall":
                        "kendall : Kendall Tau correlation coefficient",
                        "spearman": "spearman : Spearman rank correlation",
                    }.get(x),
                ),
            )
        # Matrix plot
        if plot_type == amp_consts.PLOT_SCATTER_MATRIX:
            plot_data_dict["matrix_diag"] = param_initializer(
                param_name="matrix_diag",
                widget_params=dict(
                    label="diagonal",
                    options=["Nothing", "Histogram", "scatter"],
                    index=1,
                ),
            )
            plot_data_dict["matrix_up"] = param_initializer(
                param_name="matrix_up",
                widget_params=dict(
                    label="Upper triangle",
                    options=["Nothing", "scatter", "2D histogram"],
                    index=1,
                ),
            )
            plot_data_dict["matrix_down"] = param_initializer(
                param_name="matrix_down",
                widget_params=dict(
                    label="Lower triangle",
                    options=["Nothing", "scatter", "2D histogram"],
                    index=1,
                ),
            )

        # Hover data
        if plot_type in amp_consts.PLOT_HAS_CUSTOM_HOVER_DATA:
            plot_data_dict["hover_name"] = param_initializer(
                param_name="hover_name",
                widget_params=dict(
                    label="Hover name:",
                    options=[amp_consts.NONE_SELECTED] + cat_columns,
                    index=0,
                ),
            )
            plot_data_dict["hover_data"] = param_initializer(
                widget_type="multiselect",
                param_name="hover_data",
                widget_params=dict(
                    label="Add columns to hover data",
                    options=df.columns.to_list(),
                    default=[],
                ),
            )
    else:
        if plot_type == amp_consts.PLOT_SCATTER_MATRIX:
            plot_data_dict["matrix_diag"] = "Histogram"
            plot_data_dict["matrix_up"] = "scatter"
            plot_data_dict["matrix_down"] = "scatter"
        if plot_type == amp_consts.PLOT_PCA_2D:
            plot_data_dict["show_loadings"] = False
        if plot_type == amp_consts.PLOT_CORR_MATRIX:
            plot_data_dict["corr_method"] = "pearson"

    if show_advanced_settings:
        plot_data_dict["height"] = int(
            param_initializer(
                param_name="height",
                widget_params=dict(
                    label="Plot height in pixels",
                    options=[
                        400,
                        600,
                        700,
                        800,
                        900,
                        1000,
                        1200,
                        1400,
                        1600,
                        1800,
                        2000,
                    ],
                    index=3,
                ),
            ))
        # Template
        available_templates = list(pio.templates.keys())
        plot_data_dict["template"] = param_initializer(
            param_name="template",
            widget_params=dict(
                label="Plot template (theme): ",
                options=available_templates,
                index=available_templates.index(pio.templates.default),
            ),
        )
    else:
        plot_data_dict["height"] = 800
        plot_data_dict["template"] = pio.templates.default

    if not reporting_mode:
        report_comment = st.text_area(
            label="Add a comment to your report (markdown accepted)")
    else:
        report_comment = ""

    if plot_type in amp_consts.PLOT_HAS_MODEL_DATA:
        show_variance_ratio = st.checkbox(
            label="Show explained variance",
            value=report.get("show_variance_ratio", False),
        )
        show_additional_model_data = st.checkbox(
            label=(lambda x: {
                amp_consts.PLOT_PCA_2D: "Components details",
                amp_consts.PLOT_PCA_3D: "Components details",
                amp_consts.PLOT_NCA: "Linear transformation learned",
            }.get(x, "Error"))(plot_type),
            value=report.get("show_additional_model_data", False),
        )
        show_class_means = st.checkbox(label="Class means", value=False)
    else:
        show_variance_ratio = False
        show_additional_model_data = False

    if (not reporting_mode and (is_anim or not real_time_render)
            and not st.button(label="Render", key="render_plot")):
        if is_anim and show_info:
            st.info("""Since animations may tak long to initialize, 
                the rendering starts only when you click on the **render** button above"""
                    )
        return

    if plot_type in amp_consts.PLOT_HAS_PROGRESS_DISPLAY:
        progress = st.progress(0)

        def update_progress(step, total):
            progress.progress(min(100, int(step / total * 100)))

    else:
        update_progress = None

    if plot_type in amp_consts.PLOT_NEEDS_NA_DROP and df.isnull().values.any():
        st.markdown("NA values found in will be removed:")
        for c in all_columns:
            if df[c].isnull().values.any():
                st.markdown(f"- {c} has {df[c].isnull().sum()} NA values")
        df = df.dropna(axis="index")

    fig_data = build_plot(
        is_anim=is_anim,
        plot_type=plot_type,
        df=df.copy(),
        progress=update_progress,
        **plot_data_dict,
    )

    if fig_data:
        if "figure" in fig_data:
            html = fig_data.get("figure", None).to_html()
            # b64 = base64.b64encode(html.encode()).decode()
            # href = f"""<a href="data:file/html;base64,{b64}">
            # Download plot as HTML file</a>
            # (Does not work on windows)
            # - right-click and save as &lt;some_name&gt;.html"""
            # st.markdown(href, unsafe_allow_html=True)
            st.plotly_chart(figure_or_data=fig_data.get("figure", None),
                            use_container_width=True)

            st.download_button(
                label="Download plot configuration as json",
                key="dwl_btn",
                data=str(
                    json.dumps({
                        "params":
                        plot_data_dict,
                        "plot_type":
                        plot_type,
                        "is_anim":
                        is_anim,
                        "dataframe":
                        df.to_dict(),
                        "comment":
                        report_comment,
                        "ui_mode":
                        ui_mode,
                        "param_help_level":
                        param_help_level,
                        "real_time_render":
                        real_time_render,
                        "show_info":
                        show_info,
                        "use_side_bar":
                        use_side_bar,
                        "show_advanced_plots":
                        show_advanced_plots,
                        "show_dw_options":
                        show_dw_options,
                        "show_advanced_settings":
                        show_advanced_settings,
                        "show_variance_ratio":
                        show_variance_ratio,
                        "show_additional_model_data":
                        show_additional_model_data,
                    })),
                file_name="plot_configuration.json",
                mime="file/json;base64,{b64}",
            )
            st.markdown("")

        if "model_data" in fig_data:
            model_data = fig_data.get("model_data", None)
            if hasattr(model_data,
                       "explained_variance_ratio_") and show_variance_ratio:
                df_ev = pd.DataFrame.from_dict({
                    "pc": [
                        f"PC{i}" for i in range(
                            len(model_data.explained_variance_ratio_))
                    ],
                    "exp_var_per":
                    model_data.explained_variance_ratio_ * 100,
                })
                df_ev = df_ev.assign(cumulative=df_ev["exp_var_per"].cumsum())
                ev_fig = go.Figure()
                ev_fig.add_trace(
                    go.Bar(
                        x=df_ev["pc"],
                        y=df_ev["exp_var_per"],
                        name="individual",
                    ))
                ev_fig.add_trace(
                    go.Scatter(
                        x=df_ev["pc"],
                        y=df_ev["cumulative"],
                        name="cumulative",
                    ))
                ev_fig.update_layout(
                    height=plot_data_dict["height"],
                    template=plot_data_dict["template"],
                    title=
                    "Explained variance by different principal components",
                    xaxis_title="Principal component",
                    yaxis_title="Explained variance in percent",
                )
                st.plotly_chart(figure_or_data=ev_fig,
                                use_container_width=True)
            if (hasattr(model_data, "components_")
                    and "column_names" in fig_data
                    and show_additional_model_data):
                st.write(
                    pd.DataFrame.from_dict({
                        f"PC{i+1}": pc_data
                        for i, pc_data in enumerate(model_data.components_)
                    }).set_index(pd.Series(fig_data["column_names"])))
            if (hasattr(model_data, "means_") and "class_names" in fig_data
                    and "column_names" in fig_data and show_class_means):
                st.write(
                    pd.DataFrame.from_dict({
                        col: pc_data
                        for col, pc_data in zip(fig_data["column_names"],
                                                model_data.means_.T)
                    }))
    else:
        st.warning("No plot")
Exemplo n.º 27
0
# missing_codes.to_excel("C:/Users/Darragh/Documents/Python/Work/distribution/output/Missing_Codes_Monthly_Youtube.xlsx")

with st.expander('Missing title with Fugget/FAIT'):
    df=summary_missing_codes[summary_missing_codes['Custom ID'].str.contains('fait') | summary_missing_codes['Asset Title'].str.contains('Fugget')\
         | summary_missing_codes['Asset Title'].str.contains('fugget')| summary_missing_codes['Custom ID'].str.contains('FAIT')]\
        .sort_values(by=['Partner Revenue'], ascending=False)
    df['New Show Name'] = 'Fugget About It'
    df['New Show'] = 'FAIT'
    cols_to_move = ['Custom ID', 'New Show', 'New Show Name']
    cols = cols_to_move + [col for col in df if col not in cols_to_move]
    df = df[cols]
    st.write(df)
    csv = convert_df(df)
    st.download_button(label="Download data as CSV",
                       data=csv,
                       file_name='df.csv',
                       mime='text/csv',
                       key='fugget')

with st.expander('Missing title with Barney'):
    df=summary_missing_codes[summary_missing_codes['Custom ID'].str.contains('barn') | summary_missing_codes['Asset Title'].str.contains('Barney')\
         | summary_missing_codes['Asset Title'].str.contains('BARNEY')| summary_missing_codes['Custom ID'].str.contains('BARN')]\
        .sort_values(by=['Partner Revenue'], ascending=False)
    df['New Show Name'] = 'Barney & Friends'
    df['New Show'] = 'BARN'
    cols_to_move = ['Custom ID', 'New Show', 'New Show Name']
    cols = cols_to_move + [col for col in df if col not in cols_to_move]
    df = df[cols]
    st.write(df)
    csv = convert_df(df)
    st.download_button(label="Download data as CSV",
Exemplo n.º 28
0
        X_train, X_test, y_train, y_test = train_test_split(
            X, Y, test_size=(1 - split_size / 100), random_state=seed_number)

        st.write('**Training set**')
        df1 = pd.DataFrame(X_train)
        # data_1 = data_1.loc[:1000]  # FOR TESTING PURPOSE, COMMENT THIS OUT FOR PRODUCTION

        df2 = pd.DataFrame(y_train)
        # data_1 = data_1.loc[:1000]  # FOR TESTING PURPOSE, COMMENT THIS OUT FOR PRODUCTION

        frames1 = [df1, df2]
        Train = pd.concat(frames1, axis=1)
        st.write('Data Dimension: ' + str(Train.shape[0]) + ' rows and ' +
                 str(Train.shape[1]) + ' columns.')
        st.write(Train)
        st.download_button('Download CSV', Train.to_csv(), 'Train.csv',
                           'text/csv')

        st.write('**Test set**')
        df3 = pd.DataFrame(X_test)
        df4 = pd.DataFrame(y_test)
        frames2 = [df3, df4]
        Test = pd.concat(frames2, axis=1)
        st.write('Data Dimension: ' + str(Test.shape[0]) + ' rows and ' +
                 str(Test.shape[1]) + ' columns.')
        st.write(Test)
        st.download_button('Download CSV', Test.to_csv(), 'Test.csv',
                           'text/csv')

        if add_selectbox == 'Classification':
            if DA:
                seed(2)
import streamlit as st
import numpy as np
import webbrowser
from PIL import Image

url = "https://github.com/NavinBondade/Identifying-Nine-Tomato-Disease-With-Deep-Learning"
st.set_page_config(page_title='Tomato Diseases Identification Tool', initial_sidebar_state = 'auto')
st.title("Nine Tomato Diseases Identification Tool")
st.write("A machine learning powered system that tells accurately whether a tomato plant is infected with Bacterial Spot, Early Blight, Late Blight, Leaf Mold, Septoria Leaf Spot, Spider Mites, Target Spot, Tomato Yellow Leaf Curl Virus, Tomato Mosaic Virus, Healthy. Check out code here [link](%s)." % url)

with open("Pictures.zip", "rb") as fp:
    col1, col2, col3 = st.columns(3)
    with col2:
        btn = st.download_button(
        label="Download Test Data",
        data=fp,
        file_name="Pictures.zip",
        mime="application/zip"
        )

 

hide_streamlit_style = """
            <style>
            #MainMenu {visibility: hidden;}
            footer {visibility: hidden;}
            </style>
            """
st.markdown(hide_streamlit_style, unsafe_allow_html=True)        

file = st.sidebar.file_uploader("Upload Image", type=['jpeg','jpg','png'])
Exemplo n.º 30
0
    ]].fillna(value=0)
    data['Teeth_condition'] = data[['Dentist_Recommendation']].apply(teeth_con,
                                                                     axis=1)
    data[['ENT_Issue']] = data[['ENT_Issue']].fillna(value=0)
    data['ENT_condition'] = data[['ENT_Issue']].apply(ent_con, axis=1)
    selectm = st.sidebar.selectbox('Visualization type',
                                   ['Bar plot', 'Pie chart'],
                                   key='64')
    data['Health_condition'] = data[[
        'eye_condition', 'Teeth_condition', 'ENT_condition', 'bp_condition',
        'bmi_condition'
    ]].apply(health_con, axis=1)
    data_he = data[data['Health_condition'] != 'NA']

    st.download_button(label='Download excel',
                       data=data.to_csv(),
                       file_name='final_analysis.csv')
    school_count = data_he['Health_condition'].value_counts()
    school_count = pd.DataFrame({
        'Health_condition': school_count.index,
        'Number of Students': school_count.values
    })
    if selectm == 'Bar plot':
        select = st.sidebar.selectbox('Visualization based on', [
            'Sex', 'Class', 'Blood Group', ' School ID', 'bp_condition',
            'height_condition', 'bmi_condition'
        ],
                                      key='25')
        st.markdown("### Histogram based on Overall Health Condition")
        fig = px.histogram(data_he,
                           x=select,