import streamlit as st
import numpy as np
import plotly.express as px
import pandas as pd
import plotly.graph_objects as go

st.set_page_config(page_title="Plotly Graphing Libraries",layout='wide')

import streamlit as st

uploaded_files = st.file_uploader("Choose a CSV file", accept_multiple_files=True)
for uploaded_file in uploaded_files:
    bytes_data = uploaded_file.read()
    st.write("filename:", uploaded_file.name)
    st.write(bytes_data)
    
    if st.checkbox("FileDetails"):

        filevalue = uploaded_file.getvalue()
        st.write(filevalue)
        st.write(uploaded_file.name)
        st.write(uploaded_file.type)
        st.write(uploaded_file.size)
        #st.write(uploaded_file.last_modified)
        #st.write(uploaded_file.charset)
        st.write(uploaded_file.getbuffer())
        st.write(uploaded_file.getbuffer().nbytes)
        st.write(uploaded_file.getbuffer().tobytes())
        st.write(uploaded_file.getbuffer().tolist())
        st.write(uploaded_file.getbuffer().itemsize)
        st.write(uploaded_file.getbuffer().ndim)
        st.write(uploaded_file.getbuffer().shape)
        st.write(uploaded_file.getbuffer().strides)
        st.write(uploaded_file.getbuffer().suboffsets)
        st.write(uploaded_file.getbuffer().readonly)
        st.write(uploaded_file.getbuffer().c_contiguous)
        st.write(uploaded_file.getbuffer().f_contiguous)
        st.write(uploaded_file.getbuffer().contiguous)
        st.write(uploaded_file.getbuffer().itemsize)
        st.write(uploaded_file.getbuffer().nbytes)
        st.write(uploaded_file.getbuffer().ndim)
        st.write(uploaded_file.getbuffer().shape)
        st.write(uploaded_file.getbuffer().strides)
        st.write(uploaded_file.getbuffer().suboffsets)
        st.write(uploaded_file.getbuffer().readonly)
        st.write(uploaded_file.getbuffer().c_contiguous)
        st.write(uploaded_file.getbuffer().f_contiguous)
        st.write(uploaded_file.getbuffer().contiguous)
        st.write(uploaded_file.getbuffer().itemsize)
        st.write(uploaded_file.getbuffer().nbytes)
        st.write(uploaded_file.getbuffer().ndim)
        st.write(uploaded_file.getbuffer().shape)
        st.write(uploaded_file.getbuffer().strides)
        st.write(uploaded_file.getbuffer().suboffsets)
        st.write(uploaded_file.getbuffer().readonly)
        st.write(uploaded_file.getbuffer().c_contiguous)
        st.write(uploaded_file.getbuffer().f_contiguous)
        myDF = pd.DataFrame(uploaded_file.getbuffer().tolist())
        

        st.markdown("# Treemaps from upload data file: https://plotly.com/python/treemaps/")
        #df = myDF.query("year == 2007")
        df = myDF
        fig = px.treemap(df, path=[px.Constant("time"), 'message', 'name'], values='content',
                        color='lifeExp', hover_data=['iso_alpha'],
                        color_continuous_scale='RdBu',
                        color_continuous_midpoint=np.average(df['name'], weights=df['content']))  # todo - debug this and get it working with the data
        fig.update_layout(margin = dict(t=50, l=25, r=25, b=25))
        #fig.show()
        st.plotly_chart(fig, use_container_width=True)
        
        
    
   
#show replace     
    if st.checkbox("replace"):
        mydf = st.dataframe(df)
        columns = st.selectbox("Select  column", df.columns)
        old_values = st.multiselect("Current Values",list(df[columns].unique()),list(df[columns].unique()))
        with st.form(key='my_form'):
            col1,col2 = st.beta_columns(2)
            st_input = st.number_input if is_numeric_dtype(df[columns]) else st.text_input
        with col1:
            old_val = st_input("old value")
        with col2:
            new_val = st_input("new value")
            if st.form_submit_button("Replace"):
                df[columns]=df[columns].replace(old_val,new_val)
                st.success("{} replace with {} successfully ".format(old_val,new_val))
                excel = df.to_excel(r"F:\book2.xlsx", index = False, header=True,encoding="utf-8")
                df =pd.read_excel(r"F:\book2.xlsx")       
                mydf.add_rows(df)    

st.markdown("WebGL Rendering with 1,000,000 Points")
import plotly.graph_objects as go
import numpy as np
N = 1000000
fig = go.Figure()
fig.add_trace(
    go.Scattergl(
        x = np.random.randn(N),
        y = np.random.randn(N),
        mode = 'markers',
        marker = dict(
            line = dict(
                width = 1,
                color = 'DarkSlateGrey')
        )
    )
)
#fig.show()
st.plotly_chart(fig, use_container_width=True)



st.markdown("# WebGL Graph - ScatterGL")
fig = go.Figure()
trace_num = 10
point_num = 5000
for i in range(trace_num):
    fig.add_trace(
        go.Scattergl(
                x = np.linspace(0, 1, point_num),
                y = np.random.randn(point_num)+(i*5)
        )
    )
fig.update_layout(showlegend=False)
#fig.show()
st.plotly_chart(fig, use_container_width=True)


st.markdown("# Treemaps: https://plotly.com/python/treemaps/")
df = px.data.gapminder().query("year == 2007")
fig = px.treemap(df, path=[px.Constant("world"), 'continent', 'country'], values='pop',
                  color='lifeExp', hover_data=['iso_alpha'],
                  color_continuous_scale='RdBu',
                  color_continuous_midpoint=np.average(df['lifeExp'], weights=df['pop']))
fig.update_layout(margin = dict(t=50, l=25, r=25, b=25))
#fig.show()
st.plotly_chart(fig, use_container_width=True)


st.markdown("# Sunburst: https://plotly.com/python/sunburst-charts/")


st.markdown("# Life Expectancy Sunburst")
df = px.data.gapminder().query("year == 2007")
fig = px.sunburst(df, path=['continent', 'country'], values='pop',
                  color='lifeExp', hover_data=['iso_alpha'],
                  color_continuous_scale='RdBu',
                  color_continuous_midpoint=np.average(df['lifeExp'], weights=df['pop']))
st.plotly_chart(fig, use_container_width=True)


st.markdown("# Coffee Aromas and Tastes Sunburst")
df1 = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/718417069ead87650b90472464c7565dc8c2cb1c/sunburst-coffee-flavors-complete.csv')
df2 = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/718417069ead87650b90472464c7565dc8c2cb1c/coffee-flavors.csv')
fig = go.Figure()
fig.add_trace(go.Sunburst(
    ids=df1.ids,
    labels=df1.labels,
    parents=df1.parents,
    domain=dict(column=0)
))
fig.add_trace(go.Sunburst(
    ids=df2.ids,
    labels=df2.labels,
    parents=df2.parents,
    domain=dict(column=1),
    maxdepth=2
))
fig.update_layout(
    grid= dict(columns=2, rows=1),
    margin = dict(t=0, l=0, r=0, b=0)
)
st.plotly_chart(fig, use_container_width=True)





# Sunburst
#data = dict(
#    character=["Eve", "Cain", "Seth", "Enos", "Noam", "Abel", "Awan", "Enoch", "Azura"],
#    parent=["", "Eve", "Eve", "Seth", "Seth", "Eve", "Eve", "Awan", "Eve" ],
#    value=[10, 14, 12, 10, 2, 6, 6, 4, 4])
#fig = px.sunburst(
#    data,
#    names='character',
#    parents='parent',
#    values='value',
#)
#fig.show()
#st.plotly_chart(fig, use_container_width=True)


df = px.data.tips()
fig = px.treemap(df, path=[px.Constant("all"), 'sex', 'day', 'time'], 
                 values='total_bill', color='time',
                  color_discrete_map={'(?)':'lightgrey', 'Lunch':'gold', 'Dinner':'darkblue'})
fig.update_layout(margin = dict(t=50, l=25, r=25, b=25))
#fig.show()
fig.update_traces(marker=dict(cornerradius=5))

st.plotly_chart(fig, use_container_width=True)


df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/96c0bd/sunburst-coffee-flavors-complete.csv')
fig = go.Figure(go.Treemap(
    ids = df.ids,
    labels = df.labels,
    parents = df.parents,
    pathbar_textfont_size=15,
    root_color="lightgrey"
))
fig.update_layout(
    uniformtext=dict(minsize=10, mode='hide'),
    margin = dict(t=50, l=25, r=25, b=25)
)
#fig.show()
st.plotly_chart(fig, use_container_width=True)


df = pd.read_pickle('bloom_dataset.pkl')
fig = px.treemap(df, path=[px.Constant("ROOTS"), 'Macroarea', 'Family', 'Genus', 'Language', 'dataset_name'],
                 values='num_bytes', maxdepth=4)
fig.update_traces(root_color="pink")
fig.update_layout(margin = dict(t=50, l=25, r=25, b=25))

st.plotly_chart(fig, use_container_width=True)