import streamlit as st
import numpy as np
import pandas as pd
import pydeck as pdk
import plotly.express as px

DATA_URL = ("csv1.csv")
st.title("Motor Vehicle Collison in New York")
st.markdown("Dashboard stremlit")


@st.cache(persist=True)
def load_data(nrows):
    data = pd.read_csv(DATA_URL,
                       nrows=nrows,
                       parse_dates=[['CRASH_DATE', 'CRASH_TIME']])
    data.dropna(subset=['LATITUDE', 'LONGITUDE'], inplace=True)
    lowercase = lambda x: str(x).lower()
    data.rename(lowercase, axis='columns', inplace=True)
    data.rename(columns={'crash_date_crash_time': 'date/time'}, inplace=True)
    return data


data = load_data(100000)
original_data = load_data(100000)
st.header("Where are the most people injured in NYC?")
injured_people = st.slider("Number of persons injured in vehicle collison", 0,
                           19)
st.map(
    data.query("injured_persons>=@injured_people")[["latitude", "longitude"
                                                    ]].dropna(how="any"))
def main():
    """Tweet Classifier App with Streamlit """

    # Creates a main title and subheader on your page -
    # these are static across all pages
    display_image('undraw_welcome_cats_thqn', '')
    st.title("Sentiment Analysis on Climate Change")

    st.subheader("Should your business be Eco-friendly?")
    st.markdown("""
        This platform helps you make data-driven decisions. Find out how your customers feel about climate change.
    """)

    df = clean_text(raw)

    data = None
    uploaded_file = st.sidebar.file_uploader("Choose a CSV file", type="csv")

    # Creating sidebar with selection box -
    # you can create multiple pages this way
    options = ["Information", "Insights", "Predictions"]
    selection = st.sidebar.selectbox("Menu", options)

    # Building out the "Insights" page
    if selection == "Insights":
        title = 'Below are some data visualisations and Insights extracted from the tweets'
        display_image('undraw_google_analytics_a57d', title)
        st.write("## **Wordcloud Visualisations**")
        visualize_data(df)

        st.write(
            "### **The barplots below shows the most common words per category**"
        )
        options = st.multiselect(
            'Select tweet category to visualize with BarPlot:',
            ['Pro', 'Anti', 'Neutral', 'News'], ['Pro'])
        for sentiment in options:
            common_words(df, sentiment, f'{sentiment} Tweets')

        st.subheader("Observations")
        st.write("""
            * Climate Change and Global warming appear to be the most popular words amongst these tweets.
                """)

        extract_hash(df)
        #plot_pie(df_pol, 'Political View')
        #plot_pie(df_pol, 'Political View')

        st.subheader("Observations")
        st.write("""
            * Investigating individual words still shows that there is an overlap of most used words between the classes.
            * However, it does become very apparent that there are themes that help formulate or form tweeters opinions on twitter.
            * Seeing words such as Trump, Obama would lead one to believe that there is a political connection to what people tweet about climate change.
            * We can also see the word 'husband' appearing as most common under the pro tweets, this shows that the climate change topic is being discussed amongst families as well, or that people do think about climate change in relation to people close to them.
            * We can then also assume that there is perhaps a social aspect to how people form their opinion on climate change.
            * Hashtags provide more context, as people will most usually tweet under a certain hashtag as a means of making it easier to find information with a theme or specific context.
            """)

    # Building out the "Information" page
    if selection == "Information":
        display_image('undraw_my_code_snippets_lynx',
                      'Find out what users say about your business')

        information_view(pd.read_csv("resources/train.csv"), df)

        if uploaded_file is not None:
            st.markdown("""
                ## Your new dataset.
            """)
            data = pd.read_csv(uploaded_file)
            st.table(data.message.head())

    # Building out the predication page
    if selection == "Predictions":
        model_prediction_view()
def write():
    st.markdown(f'# {PAGE_TITLE}')

    df = read_items()
    st.write(df)
Beispiel #4
0
def main():

    gc.enable()
    ##### Setup #####
    toc = Toc()
    toc.title("Face Generation from Textual Description  👩 👨 📋 ",
              "fgtd")

    # Get device
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

    ##### Face GANS #####
    st.markdown("---")
    st.markdown("## Demo")

    # First load the model
    dcgan, n_dcgan, sagan, n_sagan, dfgan, n_dfgan = load_face_generators(
        device)

    ##### Examples #####
    seen_df = read_csv("examples/seen_text.csv")
    unseen_df = read_csv("examples/unseen_text.csv")

    butt_col1, butt_col2, butt_col3, butt_col4, butt_col5 = st.beta_columns(5)

    with butt_col1:
        if st.button("Example 1"):
            user_input = "The woman has high cheekbones. She has straight hair which is black in colour. She has big lips with arched eyebrows. The smiling, young woman has rosy cheeks and heavy makeup. She is wearing lipstick."

    with butt_col2:
        if st.button("Example 2"):
            user_input = "The man sports a 5 o’clock shadow and mustache. He has a receding hairline. He has big lips and big nose, narrow eyes and a slightly open mouth. The young attractive man is smiling. He’s wearing necktie."

    with butt_col3:
        if st.button("Example 3"):
            user_input = "The man has straight hair. He has arched eyebrows. The man looks young and attractive. He’s wearing necktie."

    with butt_col4:
        if st.button("Trained",
                     help="Get a random example from training set."):
            user_input = get_sample(seen_df)

    with butt_col5:
        if st.button("Unseen",
                     help="Get a random example from untrained text."):
            user_input = get_sample(unseen_df)

    try:
        user_input = st.text_area("Try it yourself!", user_input)
    except NameError:
        user_input = st.text_area(
            "Try it yourself!",
            "The man sports a 5 o’clock shadow. His hair is black in colour. He has big nose with bushy and arched eyebrows. The man looks attractive.",
        )

    st.markdown("---")

    ##### Outputs #####

    ##### DCGAN #####
    toc.header("Deep Convolution GAN", "DCGAN", "face-dcgan")
    output_dcgan = get_output(dcgan,
                              device, (4, 100),
                              user_input=user_input,
                              input_type="face")
    output_ndcgan = get_output(n_dcgan,
                               device, (4, 100),
                               user_input=user_input,
                               input_type="face")

    dc_col1, dc_col2 = st.beta_columns(2)

    with dc_col1:
        st.image(
            [
                output_dcgan,
            ],
            caption=["DCGAN"],
        )

    with dc_col2:
        st.image(
            [
                output_ndcgan,
            ],
            caption=["N DCGAN"],
        )

    dcgan_df = read_csv("history/face/dcgan.csv")
    n_dcgan_df = read_csv("history/face/n-dcgan.csv")
    face_graph(dcgan_df, n_dcgan_df, ["DCGAN", "N DCGAN"])
    st.markdown("---")

    ##### SAGAN #####
    toc.header("Self-Attention GAN", "SAGAN", "sagan")
    output_sagan = get_output(sagan,
                              device, (4, 100),
                              user_input=user_input,
                              input_type="face")
    output_nsagan = get_output(n_sagan,
                               device, (4, 100),
                               user_input=user_input,
                               input_type="face")

    sa_col1, sa_col2 = st.beta_columns(2)

    with sa_col1:
        st.image(
            [
                output_sagan,
            ],
            caption=["SAGAN"],
        )
    with sa_col2:
        st.image(
            [
                output_nsagan,
            ],
            caption=["N SAGAN"],
        )

    sagan_df = read_csv("history/face/sagan.csv")
    n_sagan_df = read_csv("history/face/n-sagan.csv")
    face_graph(sagan_df, n_sagan_df, ["SAGAN", "N SAGAN"])
    st.markdown("---")

    ##### DFGAN #####
    toc.header("Deep Fusion GAN", "DFGAN", "dfgan")
    output_dfgan = get_output(dfgan,
                              device, (4, 100),
                              user_input=user_input,
                              input_type="face")
    output_ndfgan = get_output(n_dfgan,
                               device, (4, 100),
                               user_input=user_input,
                               input_type="face")

    df_col1, df_col2 = st.beta_columns(2)

    with df_col1:
        st.image(
            [
                output_dfgan,
            ],
            caption=["DFGAN"],
        )
    with df_col2:
        st.image(
            [
                output_ndfgan,
            ],
            caption=["N DFGAN"],
        )

    dfgan_df = read_csv("history/face/dfgan.csv")
    n_dfgan_df = read_csv("history/face/n-dfgan.csv")
    face_graph(dfgan_df, n_dfgan_df, ["DFGAN", "N DFGAN"])
    st.markdown("---")

    ##### MNIST GANS #####
    toc.title("MNIST Dataset (Digit and Fashion)", "mnist")

    # Load models
    gan, dcgan, cgan, acgan = load_mnist_generators(device)

    ##### GAN #####
    toc.header("Vanilla GAN", "GAN", "gan")
    st.markdown("Epochs : 20 ")

    gan_output = get_output(gan, device, (64, 100))
    st.image(gan_output)

    gan_df = read_csv("history/mnist/gan.csv")
    mnist_graph(gan_df)
    st.markdown("---")

    ##### DCGAN #####
    toc.header("Deep Convolution GAN (MNIST)", "DCGAN", "mnist-dcgan")
    st.markdown("Epochs : 20 ")

    dcgan_output = get_output(dcgan, device, (64, 100, 1, 1))
    st.image(dcgan_output)

    dcgan_df = read_csv("history/mnist/dcgan.csv")
    mnist_graph(dcgan_df)
    st.markdown("---")

    ##### CGAN #####
    toc.header("Conditional GAN", "CGAN", "cgan")
    st.markdown("Epochs : 20 ")

    cgan_label = st.slider("Slide for different digit images!",
                           min_value=0,
                           max_value=9,
                           value=0)
    cgan_output = get_output(cgan, device, (64, 100), user_input=cgan_label)
    st.image(cgan_output)

    cgan_df = read_csv("history/mnist/cgan.csv")
    mnist_graph(cgan_df)
    st.markdown("---")

    ##### ACGAN #####
    toc.header("Auxilary Conditional GAN", "ACGAN", "acgan")
    st.markdown("Epochs : 20 ")

    acgan_label = st.slider("Slide for different fashion images!",
                            min_value=0,
                            max_value=9,
                            value=0)
    st.text(
        "0: 'T-shirt/top', 1: 'Trouser', 2: 'Pullover', 3: 'Dress', 4: 'Coat', 5: 'Sandal', 6: 'Shirt', 7: 'Sneaker', 8: 'Bag', 9: 'Ankle boot'"
    )
    acgan_output = get_output(acgan, device, (64, 100), user_input=acgan_label)
    st.image(acgan_output)

    acgan_df = read_csv("history/mnist/acgan.csv")
    mnist_graph(acgan_df)
    st.markdown("---")

    ##### TOC #####
    toc.placeholder()
    toc.generate()

    ##### Footer #####
    footer()

    gc.collect()
Beispiel #5
0
import streamlit as st
import pandas as pd
import numpy as np
import plotly.express as px
from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator
import matplotlib.pyplot as plt

st.title("Sentimental Twitter analysis Dashboard")
st.sidebar.title("Sentimental Twitter analysis Dashboard")
st.markdown(
    "This is a dashboard build for sentimental analysis of US Airlines Tweets 🐦"
)
st.sidebar.markdown(
    "This is a dashboard build for sentimental analysis of US Airlines Tweets 🐦"
)

Dataurl = ("Tweets.csv")


@st.cache(persist=True)
def load_dataset():
    data = pd.read_csv("G:\machine learning\intern\projects\Tweets.csv")
    data['tweet_created'] = pd.to_datetime(data['tweet_created'])
    return data


data = load_dataset()

st.sidebar.subheader("Show random any tweet")
random_tweet = st.sidebar.radio('Sentiment',
                                ('positive', 'neutral', 'negative'))
Beispiel #6
0
import streamlit as st
import yfinance as yf
import pandas as pd
import cufflinks as cf
import datetime

# App title
st.markdown('''
# Stock Price App
Shown are the stock price data for query companies!
- Built in `Python` using `streamlit`,`yfinance`, `cufflinks`, `pandas` and `datetime`
''')
st.write('---')

# Sidebar
st.sidebar.subheader('Query parameters')
start_date = st.sidebar.date_input("Start date", datetime.date(2019, 1, 1))
end_date = st.sidebar.date_input("End date", datetime.date(2021, 5, 4))

# Retrieving tickers data
ticker_list = pd.read_csv(
    'https://raw.githubusercontent.com/dataprofessor/s-and-p-500-companies/master/data/constituents_symbols.txt'
)
tickerSymbol = st.sidebar.selectbox('Stock ticker',
                                    ticker_list)  # Select ticker symbol
tickerData = yf.Ticker(tickerSymbol)  # Get ticker data
tickerDf = tickerData.history(
    period='1d', start=start_date,
    end=end_date)  #get the historical prices for this ticker

# Ticker information
    def render(self, df):
        st.markdown(
            '# Percentual de homens e mulheres que ingressaram, evadiram e concluíram, em cada centro da UFRN'
        )
        st.markdown(
            'O gráfico a seguir retrata o percentual de discentes dos sexos feminino e masculino que ingressaram, concluíram e evadiram por cada centro da UFRN.'
        )
        st.markdown('#### Como interpretar o gráfico')
        st.markdown('''
                - Cada barra representa os valores para um dos centros de ensino da UFRN;
                - Na parte superior do gráfico está representado o percentual de discentes do sexo masculino, enquanto na parte inferior está expresso o percentual de discentes do sexo feminino;
                - A barra empilhada representa o percentual dos totais de ingressantes daquele sexo que concluíram e evadiram. A parte mais próxima do eixo X corresponde a de maior valor. Exemplo: se a barra de conclusão estiver mais próximo do eixo X que a barra de evasão, significa que concluíram mais pessoas do que evadiram.
                ''')
        st.markdown(
            '**Observação**: é importante ressaltar que os valores negativos no eixo y ("% do total de discentes"), quando estamos observando o percentual de discentes do sexo feminino, não indica um valor negativo em si - esse formato foi utilizado por limitações da ferramenta.'
        )

        dfs = []
        df = df[df['nome_unidade_gestora'].notna()]
        df = df[df['nome_unidade_gestora'].str.contains('CENTRO')]

        for campus in df.nome_unidade_gestora.unique():
            df_campus = self._calcular_percentuais_by_campus(df, campus)
            df_campus['nome_unidade_gestora'] = campus
            dfs.append(df_campus)

        df_chart = pd.concat(dfs)
        filter_f = df_chart['sexo'] == 'F'
        df_chart.loc[filter_f,
                     'percentual'] = df_chart[filter_f]['percentual'] * -1
        df_chart['sexo'] = df_chart['sexo'].replace({
            'F': 'Feminino',
            'M': 'Masculino',
        })
        df_chart['sort'] = abs(df_chart['percentual'])
        df_chart['nome_unidade_gestora'] = df_chart[
            'nome_unidade_gestora'].str.title()
        df_chart = df_chart.sort_values(['sort'], ascending=False)
        df_chart = df_chart.reset_index(drop=True)

        for name, group in df_chart.groupby(
                by=['nome_unidade_gestora', 'sexo']):
            indexes = list(group.index)
            df_chart.at[indexes[0], 'size'] = 100
            df_chart.at[indexes[1], 'size'] = 50
            df_chart.at[indexes[2], 'size'] = 50

        chart_params = {
            'x':
            alt.X('nome_unidade_gestora:N',
                  title=None,
                  axis=alt.Axis(zindex=10)),
            'y':
            alt.Y('sum(percentual):Q',
                  stack=False,
                  title='% do total de discentes'),
            'color':
            alt.Color('tipo:N',
                      title='Status',
                      scale=alt.Scale(domain=['Evasão', 'Conclusão', 'Total'],
                                      range=['#fd8060', '#b0d8a4',
                                             '#fee191'])),
            'size':
            alt.Size('size:Q', legend=None, scale=alt.Scale(domain=[0, 40])),
            'order':
            alt.Order('sort', sort='descending'),
            'tooltip': [
                alt.Tooltip('sexo:N', title='Gênero'),
                alt.Tooltip('sum(percentual):Q',
                            title='% referente ao total',
                            format='.2f'),
                alt.Tooltip('tipo:N', title='Status'),
                alt.Tooltip('total:Q', title='Quantidade'),
            ]
        }

        alt_chart = alt.Chart(df_chart[df_chart['tipo'] == 'Total']).mark_bar()\
            .encode(**chart_params)\
            .properties(height=600)
        chart_params['y'] = alt.Y('sum(percentual):Q',
                                  title='% do total de discentes')
        alt_chart_stacked = alt.Chart(
            df_chart[df_chart['tipo'] != 'Total']).mark_bar().encode(
                **chart_params)
        line = alt.Chart(pd.DataFrame({'y': [0]})).mark_rule().encode(y='y')

        st.altair_chart(alt_chart + alt_chart_stacked + line,
                        use_container_width=True)
Beispiel #8
0
    review_df = review_df[review_df.channel_name.str.contains('assignment')]
    review_df = review_df[review_df.DataCracy_role.str.contains('Learner')]
    dis_cols2 = [
        'channel_name', 'created_at', 'msg_date', 'msg_time',
        'reply_user_count', 'submit_name'
    ]

    ## Discussion
    discuss_df = p_msg_df[p_msg_df.channel_name.str.contains('discuss')]
    discuss_df = discuss_df.sort_values(['msg_date', 'msg_time'])
    dis_cols3 = [
        'channel_name', 'msg_date', 'msg_time', 'wordcount',
        'reply_user_count', 'reply1_name'
    ]

    st.markdown('Hello **{}**!'.format(list(filter_user_df['real_name'])[0]))
    st.write(filter_user_df)
    st.markdown('## Lịch sử Nộp Assignment')
    st.write(submit_df[dis_cols1])
    st.markdown('## Lịch sử Review Assignment')
    st.write(review_df[dis_cols2])
    st.markdown('## Lịch sử Discussion')
    st.write(discuss_df[dis_cols3])

    # Number cards on Sidebar
    st.sidebar.markdown(
        f'''<div class="card text-info bg-info mb-3" style="width: 18rem">
    <div class="card-body">
    <h5 class="card-title">ĐÃ NỘP</h5>
    <p class="card-text">{len(submit_df):02d}</p>
    </div>
Beispiel #9
0
import base64

st.set_page_config(
    page_title="electricity price prediction",
    page_icon=":zap:",
    layout="centered",  # wide
    initial_sidebar_state="expanded")  # collapsed

### New changes from Ismael

st.markdown(
    """
<style>
.sidebar .sidebar-content {
    background-image: linear-gradient(#2e7bcf,#2e7bcf);
    color: white;
}
</style>
""",
    unsafe_allow_html=True,
)

st.sidebar.markdown("""
    <style>
        #title {color: black;
        font-size: 55px;
        text-align: right;}
    </style>
<b id="title"> :zap::zap::zap::zap: <br>
RAIDEN ENERGY <br>
:zap::zap::zap::zap: </b>
Beispiel #10
0
def main():
    #todo
    st.title("Binary Classification Web App")
    st.sidebar.title("Diabates or Not")
    st.markdown("Are you a diabates patient?")
    st.sidebar.markdown("Are you a diabates patient?")

    @st.cache(persist=True)
    def load_data():
        data = pd.read_csv("diabetes.csv")
        return data

    @st.cache(persist=True)
    def split(df):
        X = np.array(df.iloc[:, 0:8])
        Y = np.array(df.iloc[:, 8])
        xtrain, xtest, ytrain, ytest = train_test_split(X,
                                                        Y,
                                                        test_size=0.2,
                                                        random_state=0)
        return xtrain, xtest, ytrain, ytest

    def plot_metrics(metrics_list):
        if "Confusion_matrix" in metrics_list:
            st.subheader("Confusion Matrix")
            plot_confusion_matrix(model,
                                  xtest,
                                  ytest,
                                  display_labels=class_name)
            st.pyplot()
        if "ROC" in metrics_list:
            st.subheader("ROC")
            plot_roc_curve(model, xtest, ytest)
            st.pyplot()
        if "Precision Recall Curve" in metrics_list:
            st.subheader("Precision Recall Curve")
            plot_precision_recall_curve(model, xtest, ytest)
            st.pyplot()

    data = load_data()
    xtrain, xtest, ytrain, ytest = split(data)
    class_name = ["Diabetic", "NonDiabetic"]
    ch = st.sidebar.checkbox("Show Dataset")
    if (ch):
        st.subheader("Diabetes Data Set from Kaggles")
        st.write(data)
    classifier = st.sidebar.selectbox(
        "Classifier",
        ("Logistic Regression", "Decision Tree", "Neural Network"))

    if classifier == "Logistic Regression":
        st.sidebar.subheader("Parameters: ")
        iterations = st.sidebar.number_input("Iterations",
                                             100,
                                             1000,
                                             step=5,
                                             key='iterations')
        C = st.sidebar.number_input("Regularization Factor",
                                    0.01,
                                    1.0,
                                    step=0.01,
                                    key='C')
        solver = st.sidebar.radio(
            "Solver", ("newton-cg", "lbfgs", "liblinear", "sag", "saga"),
            key='solver')
        metrics = st.sidebar.multiselect(
            "What metrics to plot?",
            ("Confusion_matrix", "ROC", "Precision Recall Curve"))
        if st.sidebar.button("Classify"):
            model = LogisticRegression(max_iter=iterations, solver=solver, C=C)
            model.fit(xtrain, ytrain)
            ypred = model.predict(xtest)
            st.write("Model Accuracy: ", model.score(xtest, ytest))
            st.write("Model Precision: ",
                     precision_score(ytest, ypred, labels=class_name))
            plot_metrics(metrics)

    if classifier == "Decision Tree":
        st.sidebar.subheader("Parameters: ")
        max_leaf_nodes = st.sidebar.number_input("Max Leaf Nodes",
                                                 50,
                                                 200,
                                                 step=1,
                                                 key='max_leaf_nodes')
        criterion = st.sidebar.radio("Criterion", ("gini", "entropy"),
                                     key='criterion')
        max_features = st.sidebar.radio("Features", ("auto", "sqrt", "log2"),
                                        key='max_features')
        metrics = st.sidebar.multiselect(
            "What metrics to plot?",
            ("Confusion_matrix", "ROC", "Precision Recall Curve"))
        if st.sidebar.button("Classify"):
            model = DecisionTreeClassifier(max_leaf_nodes=max_leaf_nodes,
                                           criterion=criterion,
                                           max_features=max_features)
            model.fit(xtrain, ytrain)
            ypred = model.predict(xtest)
            st.write("Model Accuracy: ", model.score(xtest, ytest))
            st.write("Model Precision: ",
                     precision_score(ytest, ypred, labels=class_name))
            plot_metrics(metrics)

    if classifier == "Neural Network":
        st.sidebar.subheader("Parameters: ")
        activation = st.sidebar.radio("Activation",
                                      ("identity", "logistic", "tanh", "relu"),
                                      key='activation')
        solver = st.sidebar.radio("Solver", ("lbfgs", "sgd", "adam"),
                                  key='solver')
        alpha = st.sidebar.number_input("Regularization Factor",
                                        0.0001,
                                        0.1,
                                        step=0.0001,
                                        key='alpha')
        learning_rate = st.sidebar.radio(
            "Learning Rate", ("constant", "invscaling", "adaptive"),
            key='learning_rate')
        max_iter = st.sidebar.number_input("Iterations",
                                           200,
                                           1000,
                                           step=5,
                                           key='max_iter')
        metrics = st.sidebar.multiselect(
            "What metrics to plot?",
            ("Confusion_matrix", "ROC", "Precision Recall Curve"))
        if st.sidebar.button("Classify"):
            model = MLPClassifier(activation=activation,
                                  solver=solver,
                                  alpha=alpha,
                                  learning_rate=learning_rate,
                                  max_iter=max_iter,
                                  hidden_layer_sizes=(8, 8, 8))
            model.fit(xtrain, ytrain)
            ypred = model.predict(xtest)
            st.write("Model Accuracy: ", model.score(xtest, ytest))
            st.write("Model Precision: ",
                     precision_score(ytest, ypred, labels=class_name))
            plot_metrics(metrics)
Beispiel #11
0
def main():
    st.text(
        'Este aplicativo utiliza as informações atualizadas contidas no site Covid19Brazil'
    )
    st.write('https://covid19-brazil-api.now.sh/')
    st.title('Covid pelo Brasil')

    data = st.selectbox('Escolha a data que deseja visualizar', datas)
    data_aux = data.split('/')
    data = ''.join(data_aux[::-1])
    dados_brasil = get_dados_brasil_por_data(data)

    df = pd.DataFrame(dados_brasil['data'])
    if len(df) == 0:
        st.text('Não há dados para essa data no Brasil')
    else:
        df.merge(coordenadas_df.T)

        bar = alt.Chart(df).mark_bar().encode(
            alt.X('state:O', title='Estados'),
            alt.Y('deaths:Q'),
            color=alt.condition(
                alt.datum.deaths > 2072, alt.value('red'),
                alt.value('black'))).properties(
                    title='Mortes por Estado e linha de média de morte')

        rule = alt.Chart(df).mark_rule(color='red').encode(
            alt.Y('mean(deaths):Q', title='Quantidade de Mortes'))

        text = bar.mark_text(
            align='center',
            color='black',
            baseline='bottom',
            dx=3  # Nudges text to right so it doesn't appear on top of the bar
        ).encode(text='deaths:Q')

        st.write((bar + rule + text).properties(width=600, height=400))

        st.subheader('Números do Brasil')
        total_casos = df['cases'].sum()
        total_suspeitas = df['suspects'].sum()
        total_mortes = df['deaths'].sum()

        html_temp = """
         <div style="
            display:flex;
            margin-bottom:20px">
            <div style="
                background-color:#025951;
                display:flex;
                justify-content:center;
                align-items:center;
                color:white;
                border-radius:5px;
                width:150px;
                height:150px;
                padding:10px;
                font-size:15px;
                margin-right:10px;"
            >
                Total de Casos Confirmados
                <br>
                %d
            </div>
            <div style="
                background-color:#048ABF;
                display:flex;
                justify-content:center;
                align-items:center;
                color:white;
                border-radius:5px;
                width:150px;
                height:150px;
                padding:10px;
                font-size:15px;
                margin-right:10px;";
            >
                Total de Suspeitas    
                %d
            </div>
            <div style="
                background-color:#F25116;
                display:flex;
                justify-content:center;
                align-items:center;
                color:white;
                border-radius:5px;
                width:150px;
                height:150px;
                padding:10px;
                font-size:15px;
                margin-right:10px;";
            >
                Total de Mortes
                %d
            </div>
         </div>
        """ % (total_casos, total_suspeitas, total_mortes)
        st.write(html_temp, unsafe_allow_html=True)

        st.subheader('Números dos Estados do Brasil')
        estados = list(df['state'])
        estado = st.selectbox('Escolha o estado que deseja visualizar',
                              estados)
        estado_casos = df[df['state'] == estado]['cases'].sum()
        estado_suspeita = df[df['state'] == estado]['suspects'].sum()
        estado_morte = df[df['state'] == estado]['deaths'].sum()

        html_temp = """
         <div style="
            display:flex;
            margin-bottom:20px">
            <div style="
                background-color:#025951;
                display:flex;
                justify-content:center;
                align-items:center;
                color:white;
                border-radius:5px;
                width:150px;
                height:150px;
                padding:10px;
                font-size:15px;
                margin-right:10px;"
            >
                Total de Casos Confirmados
                <br>
                %d
            </div>
            <div style="
                background-color:#048ABF;
                display:flex;
                justify-content:center;
                align-items:center;
                color:white;
                border-radius:5px;
                width:150px;
                height:150px;
                padding:10px;
                font-size:15px;
                margin-right:10px;";
            >
                Total de Suspeitas    
                %d
            </div>
            <div style="
                background-color:#F25116;
                display:flex;
                justify-content:center;
                align-items:center;
                color:white;
                border-radius:5px;
                width:150px;
                height:150px;
                padding:10px;
                font-size:15px;
                margin-right:10px;";
            >
                Total de Mortes
                %d
           </div>
        """ % (estado_casos, estado_suspeita, estado_morte)
        st.write(html_temp, unsafe_allow_html=True)

    #sidebar
    dados_paises = get_dados_paises()
    dados_paises_df = pd.DataFrame(dados_paises['data'])
    paises = list(dados_paises_df['country'])

    st.sidebar.title('Números do Mundo')
    st.sidebar.text('Total de Casos Confirmados')
    st.sidebar.text(dados_paises_df['confirmed'].sum())
    st.sidebar.text('Total de Mortes')
    st.sidebar.text(dados_paises_df['deaths'].sum())
    st.sidebar.text('Total de Recuperações')
    st.sidebar.text(dados_paises_df['recovered'].sum())

    st.sidebar.title('Covid pelos Países')
    pais = st.sidebar.selectbox('Escolha o País', paises)

    st.sidebar.text('Total de Casos Confirmados')
    st.sidebar.text(
        dados_paises_df[dados_paises_df['country'] == pais]['confirmed'].sum())

    st.sidebar.text('Total de Mortes')
    st.sidebar.text(
        dados_paises_df[dados_paises_df['country'] == pais]['deaths'].sum())
    st.sidebar.text('Total de Recuperações')
    st.sidebar.text(
        dados_paises_df[dados_paises_df['country'] == pais]['recovered'].sum())

    html = """
    <style>
        .reportview-container {
        flex-direction: row-reverse;
       
        }
        header > .toolbar {
            flex-direction: row-reverse;
            left: 1rem;
            right: auto;
           
        }
        .sidebar .sidebar-collapse-control,
        .sidebar.--collapsed .sidebar-collapse-control {
            left: auto;
            right: 0.5rem;
            
        }

        .sidebar .sidebar-content {
            transition: margin-right .3s, box-shadow .3s;
            
        }

        .sidebar.--collapsed .sidebar-content {
            margin-left: auto;
            margin-right: -21rem;
            
        }

        @media (max-width: 991.98px) {
        .sidebar .sidebar-content {
            margin-left: auto;
        }
        }
    </style>
    """
    st.markdown(html, unsafe_allow_html=True)
Beispiel #12
0
        client.put_object(ACL=acl,
                          Body=newfile.getvalue(),
                          Bucket=bucket,
                          Key=key)
        path = f"s3://{bucket}/{key}"
        st.success(f"successfully uploaded to {path}")
        return path
    else:
        st.warning("awaiting your file ...")
        return ""


# MAIN
st.markdown(
    """
    <h1 style="font-size:3rem;">🍔 Data Recipes</h1>
    """,
    unsafe_allow_html=True,
)
st.sidebar.markdown(
    """
    <div stule="margin-left: auto; margin-right: auto;">
    <img style='width:40%; margin: 0 auto 2rem auto;display:block;'
        src="https://raw.githubusercontent.com/NYCPlanning/logo/master/dcp_logo_772.png">
    </div>
    """,
    unsafe_allow_html=True,
)

schemas = get_schema()
new = st.checkbox("new table?")
if new:
Beispiel #13
0
# -------------------------
option = st.sidebar.selectbox('Task type', ('Compare weights', 'Most similar'),
                              index=1)

if option == 'Most similar':

    st.title('Most similar')

    word = st.text_input('Type your word', value='dog')
    title = 'Most similar to %s' % word.upper()
    # run gensim
    try:
        ret = model.wv.most_similar(positive=word, topn=10)
    except Exception as e:
        ret = None
        st.markdown('Ups! The word **%s** is not in dictionary.' % word)

    if ret is not None:
        # convert to pandas
        data = pd.DataFrame(ret, columns=['word', 'distance'])

        chart = render_most_similar(data, title)
        st.altair_chart(chart)

elif option == 'Compare weights':

    st.title('Compare weights')

    word1 = st.text_input('First word', 'dog')
    word2 = st.text_input('Second word', 'cat')
    try:
def main():
    html_temp = """
    <div style="background-color:#f63366 ;padding:10px;margin-bottom:10px;">
    <h1 style="color:white;text-align:center;">Hand Gesture Recognition Web App</h1>
    </div>
    """
    st.markdown(html_temp, unsafe_allow_html=True)

    st.sidebar.title("Pages")
    # Add a selectbox to the sidebar:
    pages=['About Web App','Project Demo', 'Hand Gesture Detection', 'Gesture Control Page']
    add_pages = st.sidebar.selectbox('', pages)

    st.sidebar.title("Made By:")
    html_temp6 = """
<ul style="font-weight:bold;">
<li>Kaviya V</li>
<li>Shruthi S</li>
<li>Shifa Sultana M A</li>
</ul>
    """
    st.sidebar.markdown(html_temp6, unsafe_allow_html=True)

    if add_pages=='About Web App':
        html_temp2 = """
    <body style="background-color:white;padding:10px;">
    <h3 style="color:#f63366 ;text-align:center;">About Web App</h3>
    The Main aim of this application is to use the most natural form i.e., Hand gestures to interact with the
computer system. These gestures are implemented in such a way that they are easy to perform, fast,
efficient and ensuring an immediate response.
The application uses your device's camera to give you touch-free and remote-free control over your media player application
(without any special hardware).It increases productivity and makes life easier and comfortable by
letting you control your device from a distance.
    </body>
<div style="background-color:black;padding:10px;margin-bottom:10px;">
<h4 style="color:white;">Prepared using:</h4>
<ul style="color:white;">
<li>Opencv </li>
<li>Keras </li>
<li>Streamlit </li>
<li>PyAutoGui </li>
</ul>
</div>
"""
        st.markdown(html_temp2, unsafe_allow_html=True)

    elif add_pages =='Project Demo':
        html_temp3 = """
    <body style="background-color:white;padding:5px;">
    <h3 style="color:#f63366 ;text-align:center;">Demo of using Hand gestures to control Media player</h3>
    """
        st.markdown(html_temp3, unsafe_allow_html=True)
        st.video("D:\\Minor Project\\media\\demo.mp4")

    elif add_pages =='Hand Gesture Detection':
        html_temp4 = """
    <body style="background-color:white;padding:5px;">
    <h3 style="color:#f63366 ;text-align:center;">Hand Gesture Detection</h3>
    <ul>Gestures Supported:
    <li>✋ or 🤚 : Palm</li>
    <li>✊ : fist </li>
    <li>👍: Thumbs Up </li>
    <li>👎: Thumbs Down </li>
    <li>👉: Index Right </li>
    <li>👈: Index Left </li>
    <li>No Hand : No gesture  </li>
    </ul>
    """
        st.markdown(html_temp4, unsafe_allow_html=True)
        run = st.button('Start Web Camera')
        FRAME_WINDOW1 = st.image([])
        FRAME_WINDOW2 = st.image([])
        camera = cv2.VideoCapture(0)
        camera.set(cv2.CAP_PROP_FRAME_WIDTH, 400)
        camera.set(cv2.CAP_PROP_FRAME_HEIGHT, 400)
        #st.write("Test image")
        while run:
            _, frame = camera.read()
            # Simulating mirror image
            frame = cv2.flip(frame, 1)
            # Got this from collect-data.py
            # Coordinates of the ROI
            x1 = int(0.5*frame.shape[1])
            y1 = 10
            x2 = frame.shape[1]-10
            y2 = int(0.5*frame.shape[1])
            # Drawing the ROI
            # The increment/decrement by 1 is to compensate for the bounding box
            cv2.rectangle(frame, (x1-1, y1-1), (x2+1, y2+1), (255,0,0),3)
            # Extracting the ROI
            roi = frame[y1:y2, x1:x2]

            # Resizing the ROI so it can be fed to the model for prediction
            roi = cv2.resize(roi, (120, 120))
            roi = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)
            _, test_image = cv2.threshold(roi, 150, 255, cv2.THRESH_BINARY)
            frame = cv2.cvtColor(frame,cv2.COLOR_BGR2RGB)
            FRAME_WINDOW1.image(test_image)
            result = loaded_model.predict(test_image.reshape(1, 120, 120, 1))
            prediction = {'palm': result[0][0],
                              'fist': result[0][1],
                              'thumbs-up': result[0][2],
                              'thumbs-down': result[0][3],
                              'index-right': result[0][4],
                              'index-left': result[0][5],
                              'no-gesture':result[0][6]}
                # Sorting based on top prediction
            prediction = sorted(prediction.items(), key=operator.itemgetter(1), reverse=True)
            # Displaying the predictions
            cv2.putText(frame, prediction[0][0], (10, 120), cv2.FONT_HERSHEY_COMPLEX, 1, (255,0,0), 1)
            frame=cv2.cvtColor(cv2.Canny(frame, 100, 200), cv2.COLOR_GRAY2BGR)
            FRAME_WINDOW2.image(frame)
        camera.release()
        cv2.destroyAllWindows()

    elif add_pages =='Gesture Control Page':
        html_temp5 = """
    <body style="background-color:white;padding:5px;">
    <h3 style="color:#f63366 ;text-align:center;">Control Media player using Hand Gestures </h3>
        <ul> Gestures and their Function
        <li>✋ or 🤚 : Palm : Play / Pause</li>
        <li>✊ : fist : Mute</li>
        <li>👍: Thumbs Up : Volume up</li>
        <li>👎: Thumbs Down: Volume Down </li>
        <li>👉: Index Right: Forward </li>
        <li>👈: Index Left: Rewind </li>
        <li>No Hand : No gesture: No action  </li>
        </ul>
    """
        st.markdown(html_temp5, unsafe_allow_html=True)
        run = st.button('Start Web Camera')
        FRAME_WINDOW1 = st.image([])
        FRAME_WINDOW2 = st.image([])
        camera = cv2.VideoCapture(0)
        camera.set(cv2.CAP_PROP_FRAME_WIDTH, 400)
        camera.set(cv2.CAP_PROP_FRAME_HEIGHT, 400)
        #st.write("Test image")
        while run:
            _, frame = camera.read()
            # Simulating mirror image
            frame = cv2.flip(frame, 1)
            # Got this from collect-data.py
            # Coordinates of the ROI
            x1 = int(0.5*frame.shape[1])
            y1 = 10
            x2 = frame.shape[1]-10
            y2 = int(0.5*frame.shape[1])
            # Drawing the ROI
            # The increment/decrement by 1 is to compensate for the bounding box
            cv2.rectangle(frame, (x1-1, y1-1), (x2+1, y2+1), (255,0,0),3)
            # Extracting the ROI
            roi = frame[y1:y2, x1:x2]

            # Resizing the ROI so it can be fed to the model for prediction
            roi = cv2.resize(roi, (120, 120))
            roi = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)
            _, test_image = cv2.threshold(roi, 150, 255, cv2.THRESH_BINARY)
            frame = cv2.cvtColor(frame,cv2.COLOR_BGR2RGB)
            FRAME_WINDOW1.image(test_image)
            result = loaded_model.predict(test_image.reshape(1, 120, 120, 1))
            prediction = {'palm': result[0][0],
                              'fist': result[0][1],
                              'thumbs-up': result[0][2],
                              'thumbs-down': result[0][3],
                              'index-right': result[0][4],
                              'index-left': result[0][5],
                              'no-gesture':result[0][6]}
                # Sorting based on top prediction
            prediction = sorted(prediction.items(), key=operator.itemgetter(1), reverse=True)
            if(prediction[0][0] == 'palm'):
                final_label = 'palm'
                action = "PLAY/PAUSE"
                pyautogui.press('playpause', presses=1)
                time.sleep(0.5)
            elif (prediction[0][0] == 'fist'):
                final_label = 'fist'
                action = "MUTE"
                pyautogui.press('volumemute', presses=1)
                time.sleep(0.5)
            elif (prediction[0][0] == 'thumbs-up'):
                final_label = "thumbs-up"
                action = "VOLUME UP"
                pyautogui.press('volumeup', presses=1)
            elif (prediction[0][0] == "thumbs-down"):
                final_label = "thumbs-down"
                action = "VOLUME DOWN"
                pyautogui.press('volumedown', presses=1)
            elif (prediction[0][0] == "index-right"):
                final_label = "index-right"
                action = "FORWARD"
                pyautogui.press('nexttrack', presses=1)
            elif (prediction[0][0] == "index-left"):
                final_label = "index-left"
                action = "REWIND"
                pyautogui.press('prevtrack', presses=1)
            elif (prediction[0][0] == "no-gesture"):
                final_label = "no-gesture"
                action = "NO-ACTION"
            text1= "Gesture: {}".format(final_label)
            text2= "Action:{}".format(action)
                # Displaying the predictions
            cv2.putText(frame, text1 , (10, 120), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (255,0,0), 1)
            cv2.putText(frame, text2 , (10, 220), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (255,0,0), 1)
            FRAME_WINDOW2.image(frame)
        camera.release()
        cv2.destroyAllWindows()
Beispiel #15
0
import src.pages.detail
import src.pages.home
import plotly.graph_objects as go
import pandas as pd
import altair as alt
from altair import Chart, X, Y, Axis, SortField, OpacityValue
import numpy as np

st.set_page_config(layout="wide", page_title='VISUASYL', page_icon="🌍")
ast.core.services.other.set_logging_format()

# Markdown to hide MainMenu (which contains things like rerun or links to github)
st.markdown('''
        <style>
            #MainMenu{
            display:none;
            }
        </style>
        ''',
            unsafe_allow_html=True)

ast.core.services.other.set_logging_format()

PAGES = {
    "Welcome": src.pages.welcome,
    "Map": src.pages.home,
    "Detail": src.pages.detail,
}


def main():
    """Main function of the App"""
}
data_regressao = {
    'tipo_acidente': tipo_acidente[tipoacidente],
    'fase_dia': fase_dia[fasedia],
    'sentido_via': sentido_via[sentidovia],
    'condicao_metereologica': condicao_metereologica[metereologica],
    'tipo_pista': tipo_pista[tipopista],
    'tracado_via': tracado_via[tracado],
    'uso_solo': uso_solo[solo],
    'veiculos': quant_veiculos,
}

features_classificacao = pd.DataFrame(data_classificacao, index=[0])
features_regressao = pd.DataFrame(data_regressao, index=[0])

st.markdown('# Classificador')
st.markdown('### Caracteristicas usadas para predição:')
st.warning(
    '> Causa do Acidente, Tipo do Acidente, Fase do dia, Sentido da Via, Condição Metereológica, Tipo da Pista,	Traçado da Via, Área, Pessoas, Quantidade de Veiculos,	Tipos de Veiculos.'
)

prediction = clf.predict(features_classificacao)
prediction_proba = clf.predict_proba(features_classificacao)
print(prediction)
print(prediction_proba)
st.subheader("Previsão")
st.write(pd.DataFrame({'Conclusao': prediction}))
st.subheader("Previsão probabilística")
st.write(
    pd.DataFrame(
        {
Beispiel #17
0
if df is not None:
    future = m.make_future_dataframe(periods=periods_input)

    forecast = m.predict(future)
    fcst = forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']]

    fcst_filtered = fcst[fcst['ds'] > max_date]
    st.write(fcst_filtered)
    """
    The next visual shows the actual (black dots) and predicted (blue line) values over time.
    """
    fig1 = m.plot(forecast)
    st.write(fig1)
    """
    The next few visuals show a high level trend of predicted values, day of week trends, and yearly trends (if dataset covers multiple years). The blue shaded area represents upper and lower confidence intervals.
    """
    fig2 = m.plot_components(forecast)
    st.write(fig2)
"""
### Step 4: Download the Forecast Data

The below link allows you to download the newly created forecast to your computer for further analysis and use.
"""
if df is not None:
    csv_exp = fcst_filtered.to_csv(index=False)
    # When no file name is given, pandas returns the CSV as a string, nice.
    b64 = base64.b64encode(csv_exp.encode()).decode(
    )  # some strings <-> bytes conversions necessary here
    href = f'<a href="data:file/csv;base64,{b64}">Download CSV File</a> (right-click and save as ** &lt;forecast_name&gt;.csv**)'
    st.markdown(href, unsafe_allow_html=True)
Beispiel #18
0
def app_video_filters():
    """ Video transforms with OpenCV """
    class OpenCVVideoTransformer(VideoTransformerBase):
        type: Literal["noop", "cartoon", "edges", "rotate"]

        def __init__(self) -> None:
            self.type = "noop"

        def transform(self, frame: av.VideoFrame) -> av.VideoFrame:
            img = frame.to_ndarray(format="bgr24")

            if self.type == "noop":
                pass
            elif self.type == "cartoon":
                # prepare color
                img_color = cv2.pyrDown(cv2.pyrDown(img))
                for _ in range(6):
                    img_color = cv2.bilateralFilter(img_color, 9, 9, 7)
                img_color = cv2.pyrUp(cv2.pyrUp(img_color))

                # prepare edges
                img_edges = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
                img_edges = cv2.adaptiveThreshold(
                    cv2.medianBlur(img_edges, 7),
                    255,
                    cv2.ADAPTIVE_THRESH_MEAN_C,
                    cv2.THRESH_BINARY,
                    9,
                    2,
                )
                img_edges = cv2.cvtColor(img_edges, cv2.COLOR_GRAY2RGB)

                # combine color and edges
                img = cv2.bitwise_and(img_color, img_edges)
            elif self.type == "edges":
                # perform edge detection
                img = cv2.cvtColor(cv2.Canny(img, 100, 200),
                                   cv2.COLOR_GRAY2BGR)
            elif self.type == "rotate":
                # rotate image
                rows, cols, _ = img.shape
                M = cv2.getRotationMatrix2D((cols / 2, rows / 2),
                                            frame.time * 45, 1)
                img = cv2.warpAffine(img, M, (cols, rows))

            return img

    webrtc_ctx = webrtc_streamer(
        key="opencv-filter",
        mode=WebRtcMode.SENDRECV,
        client_settings=WEBRTC_CLIENT_SETTINGS,
        video_transformer_factory=OpenCVVideoTransformer,
        async_transform=True,
    )

    transform_type = st.radio("Select transform type",
                              ("noop", "cartoon", "edges", "rotate"))
    if webrtc_ctx.video_transformer:
        webrtc_ctx.video_transformer.type = transform_type

    st.markdown(
        "This demo is based on "
        "https://github.com/aiortc/aiortc/blob/2362e6d1f0c730a0f8c387bbea76546775ad2fe8/examples/server/server.py#L34. "  # noqa: E501
        "Many thanks to the project.")
Beispiel #19
0
import streamlit as st

st.title("Portfolio -MHbN")

left , right = st.beta_columns(2)

#Image Insertion
with left:
    from PIL import Image
    image = Image.open('images/dp.jpg')
    st.image(image , caption="Hi. I'm Mohammed Haaris bin Naveed")
with right:
    st.markdown("Socials")
    st.markdown("LinkedIn:[_Mohammed Haaris_](https://www.linkedin.com/in/mohammed-haaris-376a29158/)")
    st.markdown("GitHub:[_MHbN98_](https://github.com/MHbN98/)")
    st.markdown("Discord:[_MHbN_](https://discord.com/)")
    st.markdown("Instagram:[_ haaris _](https://www.instagram.com/l_haaris_l/)")
st.header("Skills")

l1,l2,l3,l4,l5 = st.beta_columns(5)

with l1:
    from PIL import Image
    image = Image.open('images/py.jpg')
    st.image(image,width=70)
    click = st.button('Python')
    if(click == True):
        st.balloons()


with l2:
Beispiel #20
0
def app_object_detection():
    """Object detection demo with MobileNet SSD.
    This model and code are based on
    https://github.com/robmarkcole/object-detection-app
    """
    MODEL_URL = "https://github.com/robmarkcole/object-detection-app/raw/master/model/MobileNetSSD_deploy.caffemodel"  # noqa: E501
    MODEL_LOCAL_PATH = HERE / "./models/MobileNetSSD_deploy.caffemodel"
    PROTOTXT_URL = "https://github.com/robmarkcole/object-detection-app/raw/master/model/MobileNetSSD_deploy.prototxt.txt"  # noqa: E501
    PROTOTXT_LOCAL_PATH = HERE / "./models/MobileNetSSD_deploy.prototxt.txt"

    CLASSES = [
        "background",
        "aeroplane",
        "bicycle",
        "bird",
        "boat",
        "bottle",
        "bus",
        "car",
        "cat",
        "chair",
        "cow",
        "diningtable",
        "dog",
        "horse",
        "motorbike",
        "person",
        "pottedplant",
        "sheep",
        "sofa",
        "train",
        "tvmonitor",
    ]
    COLORS = np.random.uniform(0, 255, size=(len(CLASSES), 3))

    download_file(MODEL_URL, MODEL_LOCAL_PATH, expected_size=23147564)
    download_file(PROTOTXT_URL, PROTOTXT_LOCAL_PATH, expected_size=29353)

    DEFAULT_CONFIDENCE_THRESHOLD = 0.5

    class Detection(NamedTuple):
        name: str
        prob: float

    class MobileNetSSDVideoTransformer(VideoTransformerBase):
        confidence_threshold: float
        result_queue: "queue.Queue[List[Detection]]"

        def __init__(self) -> None:
            self._net = cv2.dnn.readNetFromCaffe(str(PROTOTXT_LOCAL_PATH),
                                                 str(MODEL_LOCAL_PATH))
            self.confidence_threshold = DEFAULT_CONFIDENCE_THRESHOLD
            self.result_queue = queue.Queue()

        def _annotate_image(self, image, detections):
            # loop over the detections
            (h, w) = image.shape[:2]
            result: List[Detection] = []
            for i in np.arange(0, detections.shape[2]):
                confidence = detections[0, 0, i, 2]

                if confidence > self.confidence_threshold:
                    # extract the index of the class label from the `detections`,
                    # then compute the (x, y)-coordinates of the bounding box for
                    # the object
                    idx = int(detections[0, 0, i, 1])
                    box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
                    (startX, startY, endX, endY) = box.astype("int")

                    name = CLASSES[idx]
                    result.append(Detection(name=name, prob=float(confidence)))

                    # display the prediction
                    label = f"{name}: {round(confidence * 100, 2)}%"
                    cv2.rectangle(image, (startX, startY), (endX, endY),
                                  COLORS[idx], 2)
                    y = startY - 15 if startY - 15 > 15 else startY + 15
                    cv2.putText(
                        image,
                        label,
                        (startX, y),
                        cv2.FONT_HERSHEY_SIMPLEX,
                        0.5,
                        COLORS[idx],
                        2,
                    )
            return image, result

        def transform(self, frame: av.VideoFrame) -> np.ndarray:
            image = frame.to_ndarray(format="bgr24")
            blob = cv2.dnn.blobFromImage(cv2.resize(image, (300, 300)),
                                         0.007843, (300, 300), 127.5)
            self._net.setInput(blob)
            detections = self._net.forward()
            annotated_image, result = self._annotate_image(image, detections)

            # NOTE: This `transform` method is called in another thread,
            # so it must be thread-safe.
            self.result_queue.put(result)

            return annotated_image

    webrtc_ctx = webrtc_streamer(
        key="object-detection",
        mode=WebRtcMode.SENDRECV,
        client_settings=WEBRTC_CLIENT_SETTINGS,
        video_transformer_factory=MobileNetSSDVideoTransformer,
        async_transform=True,
    )

    confidence_threshold = st.slider("Confidence threshold", 0.0, 1.0,
                                     DEFAULT_CONFIDENCE_THRESHOLD, 0.05)
    if webrtc_ctx.video_transformer:
        webrtc_ctx.video_transformer.confidence_threshold = confidence_threshold

    if st.checkbox("Show the detected labels", value=True):
        if webrtc_ctx.state.playing:
            labels_placeholder = st.empty()
            # NOTE: The video transformation with object detection and
            # this loop displaying the result labels are running
            # in different threads asynchronously.
            # Then the rendered video frames and the labels displayed here
            # are not strictly synchronized.
            if webrtc_ctx.video_transformer:
                while True:
                    result = webrtc_ctx.video_transformer.result_queue.get()
                    labels_placeholder.table(result)

    st.markdown("This demo uses a model and code from "
                "https://github.com/robmarkcole/object-detection-app. "
                "Many thanks to the project.")
Beispiel #21
0
import streamlit as st
st.title("SMATCH : Network of Shopify Merchants")
st.sidebar.title("Choose one")
template = """
    <div style = "background-color : black; padding : 2px;">
    <h1 style = "color:white;text-align:center;">Smart Inventory Management</h1>
    </div>
    """
st.markdown(template, unsafe_allow_html=True)
import pandas as pd
df = pd.read_csv("product.csv")
df1 = df.drop(
    ["Wholesale price", "Minimum Quantity", "Maximum Quantity", "Min SKU"],
    axis=1)
st.table(df1)
if st.sidebar.checkbox("Check stock"):
    st.success("Stock Out Products")
    list1 = list(df.Stock)
    list2 = list(df.Threshold)
    list3 = []
    for i in range(len(list1)):
        if list1[i] < list2[i]:
            list3.append("Reorder")
        else:
            list3.append("Enough stock")
    x = list3.index("Reorder")
    df1["Stock Status"] = list3
    st.dataframe(df1.iloc[x, ])
    st.write("Shoe Puma is out of stock")
    st.write("Find the merchants near by for quick delivery")
    st.success("Redirecting........")
Beispiel #22
0
input_df = df_clean[[
    'Perfil', 'AIS', 'Categoria', 'T_instalacoes', 'weekday', 'Conversao'
]]

# Carregando modelo
model = load_model('organic_model_09032021')

# Predict Organic
st.write('Clique em Predict para fazer a estimativa dos downloads orgânicos')
if st.button('Predict'):
    output = predict_model(model, data=input_df)

    preds = output['Label']

    # Criando df para exportar
    df_final = df_clean[['Data', 'T_instalacoes', 'Visitas', 'Conversao']]
    df_final['Instalações Orgânicas (Estimado)'] = round(preds, 0)

    df_final['Instalações Não-Orgânicas (Estimado)'] = df_final[
        'T_instalacoes'] - df_final['Instalações Orgânicas (Estimado)']
    df_final['Data'] = df_final['Data'].dt.strftime('%d/%m/%Y')
    df_final.rename(columns={
        'T_instalacoes': 'Total de Instalações',
        'Conversao': 'Conversão(%)'
    },
                    inplace=True)

    st.write(df_final)
    st.write('Clique em Download para baixar o arquivo')
    st.markdown(get_table_download_link(df_final), unsafe_allow_html=True)
Beispiel #23
0
import matplotlib
import math
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from IPython.display import HTML
import matplotlib.ticker as ticker
import geopandas as gp
import calmap
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures

st.title("Covid-19 Basic Visualization and Prediction")
st.markdown(
"""
Collect data about COVID-19 and any related data. Here I just give several data sources like [COVID-19 Open Datasets](https://www.aminer.cn/data-covid19/?from=singlemessage),[COVID-19 Epidemic Situation and Economic Research](http://cn.gtadata.com/#/datacenter/singletable/search?serId=16&databaseId=190). We get the data from [Github](https://github.com/CSSEGISandData/COVID-19/tree/master/csse_covid_19_data).
- We devolop a small demo to do some basic visualization and prediction.
- If you think it is necessary to preprocess data before jump into specific research question, you can do some data precessing in this section.
- If you think it is better to conduct data clean in the subsequent sections, please do it later.
""")

#get data
confirm_US_url = 'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_US.csv'
confirm_url = 'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv'
death_url = 'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_deaths_global.csv'
death_US_url = 'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_deaths_US.csv'
recover_url = 'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_recovered_global.csv'
group = pd.read_excel('group.xlsx')
confirm = pd.read_csv(confirm_url)
confirm_US = pd.read_csv(confirm_US_url)
death = pd.read_csv(death_url)
death_US = pd.read_csv(death_US_url)
def main():
    """News Classifier"""

    st.title("""News Classifier""")

    # st.subheader("ML App with Streamlit")

    html_temp = \
        """
	<div style="background-color:blue;padding:10px">
	<h1 style="color:white;text-align:center;">News Classification WebApp </h1>
	</div>
	"""
    st.markdown(html_temp, unsafe_allow_html=True)

    activity = ['Prediction', 'NLP']
    choice = st.sidebar.selectbox('Select Activity', activity)

    if choice == 'Prediction':
        st.info('Prediction with ML')

        news_text_ = st.text_area('Enter News URL Here', 'Paste URL Here.')
        all_ml_models = ['LR', 'RFOREST', 'NB', 'DECISION_TREE']
        model_choice = st.selectbox('Select Model', all_ml_models)

        prediction_labels = {
            'business': 0,
            'tech': 1,
            'sport': 2,
            'health': 3,
            'politics': 4,
            'entertainment': 5,
        }
        if st.button('Classify'):
            news_text = get_article_details(news_text_)
            st.text('Original Text::\n{}'.format(news_text))
            vect_text = news_cv.transform([news_text]).toarray()
            if model_choice == 'LR':
                predictor = \
                    load_prediction_models('models/newsclassifier_Logit_model.pkl'
                        )
                prediction = predictor.predict(vect_text)
            elif model_choice == 'RFOREST':

                # st.write(prediction)

                predictor = \
                    load_prediction_models('models/newsclassifier_RFOREST_model.pkl'
                        )
                prediction = predictor.predict(vect_text)
            elif model_choice == 'NB':

                # st.write(prediction)

                predictor = \
                    load_prediction_models('models/newsclassifier_NB_model.pkl'
                        )
                prediction = predictor.predict(vect_text)
            elif model_choice == 'DECISION_TREE':

                # st.write(prediction)

                predictor = \
                    load_prediction_models('models/newsclassifier_CART_model.pkl'
                        )
                prediction = predictor.predict(vect_text)

                # st.write(prediction)

            final_result = get_key(prediction, prediction_labels)
            st.success('News Categorized as:: {}'.format(final_result))

    if choice == 'NLP':
        st.info('Natural Language Processing of Text')
        raw_text_ = st.text_area('Enter News URL Here', 'Paste URL Here')
        nlp_task = ['Tokenization', 'Lemmatization', 'NER', 'POS Tags']
        task_choice = st.selectbox('Choose NLP Task', nlp_task)
        if st.button('Analyze'):
            raw_text = get_article_details(raw_text_)
            st.info('Original Text::\n{}'.format(raw_text))

            docx = nlp(raw_text)
            if task_choice == 'Tokenization':
                result = [token.text for token in docx]
            elif task_choice == 'Lemmatization':
                result = [
                    "'Token':{},'Lemma':{}".format(token.text, token.lemma_)
                    for token in docx
                ]
            elif task_choice == 'NER':
                result = [(entity.text, entity.label_) for entity in docx.ents]
            elif task_choice == 'POS Tags':
                result = \
                    ["'Token':{},'POS':{},'Dependency':{}".format(word.text,
                     word.tag_, word.dep_) for word in docx]

            st.json(result)

        if st.button('Tabulize'):
            raw_text = get_article_details(raw_text_)
            docx = nlp(raw_text)
            c_tokens = [token.text for token in docx]
            c_lemma = [token.lemma_ for token in docx]
            c_pos = [token.pos_ for token in docx]

            new_df = pd.DataFrame(zip(c_tokens, c_lemma, c_pos),
                                  columns=['Tokens', 'Lemma', 'POS'])
            st.dataframe(new_df)

        if st.checkbox('WordCloud'):
            raw_text = get_article_details(raw_text_)
            c_text = raw_text
            wordcloud = WordCloud().generate(c_text)
            plt.imshow(wordcloud, interpolation='bilinear')
            plt.axis('off')
            st.pyplot()

    st.sidebar.subheader('About')
Beispiel #25
0
import streamlit as st
import pandas as pd
import numpy as np
import pydeck as pdk
import plotly.express as px

DATA_URL = "crashes.csv"

st.title("Motor Vehicle Collisions in New York City")
st.markdown(
    "This application is a Streamlit dashboard that can be used to analyze motor vehicle collision in NYC 🚗"
)


@st.cache(persist=True)
def load_raw_data(nrows):
    df = pd.read_csv(DATA_URL, nrows=nrows)
    return df


raw_data = load_raw_data(1000)

if st.sidebar.checkbox("Show Summary", False):
    st.write("Showing summary", raw_data.describe())

if st.sidebar.checkbox("Show Raw Data", False):
    st.subheader("Raw Data")
    st.write(raw_data)
    st.write("Shape: ", raw_data.shape)
    if st.checkbox("Raw Data Columns: ", False):
        st.write("Columns: ", raw_data.columns)
Beispiel #26
0
                'Comparison of Total Deaths of 10 Most Affected Countries',
                xaxis_title='Country',
                yaxis_title='Total Deaths',
                template="plotly_dark")
            st.plotly_chart(fig)

    st.sidebar.subheader('Analysis through 3D Plot')

    if not st.sidebar.checkbox("Hide 3D plot", True):

        fig = px.scatter_3d(dfc.head(10),
                            x='TotalConfirmed',
                            y='TotalDeaths',
                            z='TotalRecovered',
                            color='Country')
        fig.update_layout(
            title=
            '3D Plot of Total Cases, Total Deaths and Total Recovered of Top 20 Affected Countries'
        )
        st.plotly_chart(fig)

    if st.sidebar.checkbox("Show Raw Data", False):
        st.subheader("Covid 19 Data")
        st.write(covid1)


if __name__ == '__main__':
    main()

    st.markdown("For issues Contact - [email protected]")
Beispiel #27
0
    ], ['Breeam spaces', existing_car_spaces, breeam_max],
    [
        'Breeam area m2 (estimate)',
        float(existing_carpark_area), bre_hardstanding
    ]
]

output_table_df = pd.DataFrame(output_table_data,
                               columns=['Variable', 'Existing', 'Proposed'])
output_table_df['Variance'] = output_table_df['Existing'] - \
    output_table_df['Proposed']
output_table_df = output_table_df[[
    'Variable', 'Existing', 'Proposed', 'Variance'
]]

st.markdown("# Car parking and hardstanding requirements")
st.markdown("Breeam is subject to their public transport index, sufficient \
        public transport to replace car parking need")

# %% Table

fig = go.Figure(data=[
    go.Table(
        columnwidth=[20, 10, 10, 10],
        header=dict(
            values=['Output', 'Existing', 'Proposed', 'Variance'],
            line_color="darkslategray",
            fill_color="darkblue",
            align="left",
            font=dict(color="white", size=11),
        ),
Beispiel #28
0
def main():

    st.markdown(
        "<h1 style='text-align: center; color: #ff634d;'><strong><u>Covid-19 Dashboard</u></strong></h1>",
        unsafe_allow_html=True)
    st.sidebar.markdown(
        "<h1 style='text-align: center; color: #aaccee;'><strong><u>Covid-19 Dashboard</u></strong></h1>",
        unsafe_allow_html=True)

    st.markdown(
        "This Web App is a live Covid-19 Dashboard which access Data sourced from Johns Hopkins CSSE",
        unsafe_allow_html=True)

    conn = http.client.HTTPSConnection("api.covid19api.com")
    payload = ''
    headers = {}
    conn.request("GET", "/summary", payload, headers)
    res = conn.getresponse()
    data = res.read().decode('UTF-8')
    covid = json.loads(data)

    df = pd.DataFrame(covid['Countries'])

    covid1 = df.drop(columns=['CountryCode', 'Slug', 'Date', 'Premium'],
                     axis=1)
    covid1['ActiveCases'] = covid1['TotalConfirmed'] - covid1['TotalRecovered']
    covid1['ActiveCases'] = covid1['ActiveCases'] - covid1['TotalDeaths']

    dfn = covid1.drop(['NewConfirmed', 'NewDeaths', 'NewRecovered'], axis=1)
    dfn = dfn.groupby('Country')['TotalConfirmed', 'TotalDeaths',
                                 'TotalRecovered',
                                 'ActiveCases'].sum().sort_values(
                                     by='TotalConfirmed', ascending=False)
    dfn.style.background_gradient(cmap='Oranges')

    dfc = covid1.groupby('Country')['TotalConfirmed', 'TotalDeaths',
                                    'TotalRecovered',
                                    'ActiveCases'].max().sort_values(
                                        by='TotalConfirmed',
                                        ascending=False).reset_index()

    m = folium.Map(tiles='Stamen Terrain', min_zoom=1.5)
    url = 'https://raw.githubusercontent.com/python-visualization/folium/master/examples/data'
    country_shapes = f'{url}/world-countries.json'
    folium.Choropleth(
        geo_data=country_shapes,
        min_zoom=2,
        name='Covid-19',
        data=covid1,
        columns=['Country', 'TotalConfirmed'],
        key_on='feature.properties.name',
        fill_color='YlOrRd',
        nan_fill_color='black',
        legend_name='Total Confirmed Cases',
    ).add_to(m)

    m1 = folium.Map(tiles='Stamen Terrain', min_zoom=1.5)
    url = 'https://raw.githubusercontent.com/python-visualization/folium/master/examples/data'
    country_shapes = f'{url}/world-countries.json'
    folium.Choropleth(
        geo_data=country_shapes,
        min_zoom=2,
        name='Covid-19',
        data=covid1,
        columns=['Country', 'TotalRecovered'],
        key_on='feature.properties.name',
        fill_color='YlOrRd',
        nan_fill_color='black',
        legend_name='Total Recovered Cases',
    ).add_to(m1)

    m4 = folium.Map(tiles='Stamen Terrain', min_zoom=1.5)
    url = 'https://raw.githubusercontent.com/python-visualization/folium/master/examples/data'
    country_shapes = f'{url}/world-countries.json'
    folium.Choropleth(
        geo_data=country_shapes,
        min_zoom=2,
        name='Covid-19',
        data=covid1,
        columns=['Country', 'ActiveCases'],
        key_on='feature.properties.name',
        fill_color='YlOrRd',
        nan_fill_color='black',
        legend_name='Active Cases',
    ).add_to(m4)

    coordinates = pd.read_csv(
        'https://raw.githubusercontent.com/VinitaSilaparasetty/covid-map/master/country-coordinates-world.csv'
    )
    covid_final = pd.merge(covid1, coordinates, on='Country')

    dfn
    confirmed_tot = int(dfc['TotalConfirmed'].sum())
    deaths_tot = int(dfc['TotalDeaths'].sum())
    recovered_tot = int(dfc['TotalRecovered'].sum())
    active_tot = int(dfc['ActiveCases'].sum())

    st.write('TOTAL CONFIRMED CASES FROM ALL OVER THE WORLD - ', confirmed_tot)
    st.write('TOTAL DEATH CASES FROM ALL OVER THE WORLD - ', deaths_tot)
    st.write('TOTAL RECOVERED CASES FROM ALL OVER THE WORLD - ', recovered_tot)
    st.write('TOTAL ACTIVE CASES FROM ALL OVER THE WORLD - ', active_tot)

    st.sidebar.subheader('Analysis through Map - Folium')

    select = st.sidebar.selectbox(
        'Choose Map Type',
        ['Confirmed Cases', 'Recovered Cases', 'Active Cases', 'Deaths'],
        key='1')

    if not st.sidebar.checkbox("Hide Map", True):

        if select == "Confirmed Cases":
            folium_static(m)

        elif select == "Recovered Cases":

            folium_static(m1)

        elif select == "Active Cases":

            folium_static(m4)

        else:
            m2 = folium.Map(tiles='StamenToner', min_zoom=1.5)
            deaths = covid_final['TotalDeaths'].astype(float)
            lat = covid_final['latitude'].astype(float)
            long = covid_final['longitude'].astype(float)

            m2.add_child(HeatMap(zip(lat, long, deaths), radius=0))
            folium_static(m2)

    st.sidebar.subheader('Analysis through Bar Chart')

    select = st.sidebar.selectbox(
        'Choose Bar Chart',
        ['Confirmed Cases', 'Recovered Cases', 'Active Cases', 'Deaths'],
        key='2')

    if not st.sidebar.checkbox("Hide Bar Chart", True):

        if select == "Confirmed Cases":
            fig = px.bar(dfc.head(10),
                         y='TotalConfirmed',
                         x='Country',
                         color='Country',
                         height=400)
            fig.update_layout(
                title=
                'Comparison of Total Confirmed Cases of 10 Most Affected Countries',
                xaxis_title='Country',
                yaxis_title='Total Confirmed Case',
                template="plotly_dark")
            st.plotly_chart(fig)

        elif select == "Recovered Cases":

            fig = px.bar(dfc.head(10),
                         y='TotalRecovered',
                         x='Country',
                         color='Country',
                         height=400)
            fig.update_layout(
                title=
                'Comparison of Total Recovered of 10 Most Affected Countries',
                xaxis_title='Country',
                yaxis_title='Total Recovered',
                template="plotly_dark")
            st.plotly_chart(fig)

        elif select == "Active Cases":

            fig = px.bar(dfc.head(10),
                         y='ActiveCases',
                         x='Country',
                         color='Country',
                         height=400)
            fig.update_layout(
                title=
                'Comparison of Active Cases of 10 Most Affected Countries',
                xaxis_title='Country',
                yaxis_title='Total Recovered',
                template="plotly_dark")
            st.plotly_chart(fig)

        else:
            fig = px.bar(dfc.head(10),
                         y='TotalDeaths',
                         x='Country',
                         color='Country',
                         height=400)
            fig.update_layout(
                title=
                'Comparison of Total Deaths of 10 Most Affected Countries',
                xaxis_title='Country',
                yaxis_title='Total Deaths',
                template="plotly_dark")
            st.plotly_chart(fig)

    st.sidebar.subheader('Analysis through 3D Plot')

    if not st.sidebar.checkbox("Hide 3D plot", True):

        fig = px.scatter_3d(dfc.head(10),
                            x='TotalConfirmed',
                            y='TotalDeaths',
                            z='TotalRecovered',
                            color='Country')
        fig.update_layout(
            title=
            '3D Plot of Total Cases, Total Deaths and Total Recovered of Top 20 Affected Countries'
        )
        st.plotly_chart(fig)

    if st.sidebar.checkbox("Show Raw Data", False):
        st.subheader("Covid 19 Data")
        st.write(covid1)
Beispiel #29
0

with st.sidebar:
    inputs = show()
"""
# Code Generator for Slurm on Bowser
"""
html_icons = """
<center>
<a href="https://github.com/devanshkv/bowser_slurm_tutorial/issues"><img alt="GitHub issues" src="https://img.shields.io/github/issues/devanshkv/bowser_slurm_tutorial?style=social"></a>
<a href="https://github.com/devanshkv/bowser_slurm_tutorial/network"><img alt="GitHub forks" src="https://img.shields.io/github/forks/devanshkv/bowser_slurm_tutorial?style=social"></a>
<a href="https://github.com/devanshkv/bowser_slurm_tutorial/stargazers"><img alt="GitHub stars" src="https://img.shields.io/github/stars/devanshkv/bowser_slurm_tutorial?style=social"></a>
<a href="https://www.twitter.com/devanshkv"><img alt="Follow" src="https://img.shields.io/twitter/follow/devanshkv?style=social"></a>
</center>
"""
st.markdown(html_icons, unsafe_allow_html=True)
st.markdown("<br>", unsafe_allow_html=True)
"""
Jumpstart your research:

1. Specify details in the sidebar *(click on **>** if closed)*

2. Code will be generated below

3. Download and do magic! :sparkles:
---
"""
env = Environment(
    loader=FileSystemLoader("templates"),
    trim_blocks=True,
    lstrip_blocks=True,
Beispiel #30
0
import pandas as pd
import streamlit as st
import numpy as np
import matplotlib.pyplot as plt

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

delaware = 564696
chester = 519293
montgomery = 826075
bucks = 628341
philly = 1581000
S_default = delaware + chester + montgomery + bucks + philly
known_infections = 31

# Widgets
initial_infections = st.sidebar.number_input(
    "Currently Known Regional Infections",
    value=known_infections,
    step=10,
    format="%i")
current_hosp = st.sidebar.number_input(
    "Currently Hospitalized COVID-19 Patients", value=2, step=1, format="%i")
doubling_time = st.sidebar.number_input("Doubling Time (days)",
                                        value=6,
                                        step=1,