def app():
    st.markdown('<style> body {font-weight:bold;background-image: url("https://images.unsplash.com/photo-1528459801416-a9e53bbf4e17?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=655&q=80"); background-size:cover;}</style>',unsafe_allow_html=True)

    html_temp = """
        <div style = "background-color: #a3a8b8; padding: 10px;">
            <center><h1 style="font-size:280%;font-family:Georgia;">SPOTIFY HIT PREDICTOR </h1></center>
        </div><br>
    """
    st.markdown(html_temp, unsafe_allow_html=True)

    danceability = st.number_input('Enter the DANCEABILITY score. Range:(0-1)')
    energy = st.number_input('Enter the ENERGY score. Range:(0 - 1)')
    key = st.number_input('Enter the KEY score. Range:(0 - 1)')
    loudness = st.number_input('Enter the LOUDNESS score. Range:(-50 - 0)')
    mode = st.number_input('Enter the MODE score. Range:(0 - 1)')
    speechiness = st.number_input('Enter the SPEECHINESS score. Range:(0 - 1)')
    acousticness = st.number_input('Enter the ACOUSTICNESS score. Range:(0 - 1)')
    instrumentalness = st.number_input('Enter the INSTRUMENTALNESS score. Range:(0 - 1)')
    liveness = st.number_input('Enter the LIVENESS score. Range:(0 - 1)')
    valence = st.number_input('Enter the VALENCE score. Range:(0 - 1)')
    tempo = st.number_input('Enter the TEMPO score. Range:(0 - 300)')
    duration_ms = st.number_input('Enter the DURATION_MS score. Range:(10000 - 10000000)')
    time_signature = st.number_input('Enter the TIME SIGNATURE score. Range:(0 - 5)')
    chorus_hit = st.number_input('Enter the CHORUS HIT score. Range:(0 - 300)')
    sections = st.number_input('Enter the SECTIONS score. Range:(1 - 200)')
    
    sample_data = [danceability, energy, key, loudness,
       mode, speechiness, acousticness, instrumentalness, liveness,
       valence, tempo, duration_ms, time_signature, chorus_hit,    
       sections]

    prep_data = np.array(sample_data).reshape(1, -1)

    decade = st.selectbox('Choose the decade for which you want to check the trend.',['1960s', '1970s', '1980s', '1990s', '2000s', '2010s'] )

    if st.button('PREDICT'):
        if decade == '1960s':
            predictor_60 = load_model('Trained_model_60')
            prediction_60 = predictor_60.predict(prep_data)
            result_60 = np.argmax(prediction_60)
            
            if result_60 == 0:
                st.error('THE SONG WITH ABOVE RATINGS WOULD BE A FLOP SONG.')

            elif result_60 == 1:
                st.success('THE SONG WITH ABOVE RATINGS WOULD BE A HIT SONG.')

        elif decade == '1970s':
            predictor_70 = load_model('Trained_model_70')
            prediction_70 = predictor_70.predict(prep_data)
            result_70 = np.argmax(prediction_70)
            
            if result_70 == 0:
                st.error('THE SONG WITH ABOVE RATINGS WOULD BE A FLOP SONG.')

            elif result_70 == 1:
                st.success('THE SONG WITH ABOVE RATINGS WOULD BE A HIT SONG.')

        elif decade == '1980s':
            predictor_80 = load_model('Trained_model_80')
            prediction_80 = predictor_80.predict(prep_data)
            result_80 = np.argmax(prediction_80)
            
            if result_80 == 0:
                st.error('THE SONG WITH ABOVE RATINGS WOULD BE A FLOP SONG.')

            elif result_80 == 1:
                st.success('THE SONG WITH ABOVE RATINGS WOULD BE A HIT SONG.')
            
        elif decade == '1990s':
            predictor_90 = load_model('Trained_model_90')
            prediction_90 = predictor_90.predict(prep_data)
            result_90 = np.argmax(prediction_90)
            
            if result_90 == 0:
                st.error('THE SONG WITH ABOVE RATINGS WOULD BE A FLOP SONG.')

            elif result_90 == 1:
                st.success('THE SONG WITH ABOVE RATINGS WOULD BE A HIT SONG.')
            
        elif decade == '2000s':
            predictor_00 = load_model('Trained_model_00')
            prediction_00 = predictor_00.predict(prep_data)
            result_00 = np.argmax(prediction_00)
            
            if result_00 == 0:
                st.error('THE SONG WITH ABOVE RATINGS WOULD BE A FLOP SONG.')

            elif result_00 == 1:
                st.success('THE SONG WITH ABOVE RATINGS WOULD BE A HIT SONG.')
            
        elif decade == '2010s':
            predictor_10 = load_model('Trained_model_10')
            prediction_10 = predictor_10.predict(prep_data)
            result_10 = np.argmax(prediction_10)
            
            if result_10 == 0:
                st.error('THE SONG WITH ABOVE RATINGS WOULD BE A FLOP SONG.')

            elif result_10 == 1:
                st.success('THE SONG WITH ABOVE RATINGS WOULD BE A HIT SONG.')
def main():

    # DO NOT REMOVE the 'Recommender System' option below, however,
    # you are welcome to add more options to enrich your app.
    page_options = [
        "Recommender System", "Pandas profiling", "Sweetviz", "EDA",
        "Solution Overview", "Slides"
    ]

    # -------------------------------------------------------------------
    # ----------- !! THIS CODE MUST NOT BE ALTERED !! -------------------
    # -------------------------------------------------------------------
    page_selection = st.sidebar.selectbox("Choose Option", page_options)
    if page_selection == "Recommender System":
        # Header contents
        st.markdown(rec_header, unsafe_allow_html=True)
        st.image('resources/imgs/Image_header.png', use_column_width=True)
        # Recommender System algorithm selection
        sys = st.radio(
            "Select an algorithm",
            ('Content Based Filtering', 'Collaborative Based Filtering'))

        # User-based preferences
        st.write('### Enter Your Three Favorite Movies')
        movie_1 = st.selectbox('Fisrt Option', title_list[14930:15200])
        movie_2 = st.selectbox('Second Option', title_list[25055:25255])
        movie_3 = st.selectbox('Third Option', title_list[21100:21200])
        fav_movies = [movie_1, movie_2, movie_3]

        # Perform top-10 movie recommendation generation
        if sys == 'Content Based Filtering':
            if st.button("Recommend"):
                try:
                    with st.spinner('Crunching the numbers...'):
                        top_recommendations = content_model(
                            movie_list=fav_movies, top_n=10)
                    st.title("We think you'll like:")
                    for i, j in enumerate(top_recommendations):
                        st.subheader(str(i + 1) + '. ' + j)
                except:
                    st.error("Oops! Looks like this algorithm does't work.\
                              We'll need to fix it!")

        if sys == 'Collaborative Based Filtering':
            if st.button("Recommend"):
                try:
                    with st.spinner('Crunching the numbers...'):
                        top_recommendations = collab_model(
                            movie_list=fav_movies, top_n=10)
                    st.title("We think you'll like:")
                    for i, j in enumerate(top_recommendations):
                        st.subheader(str(i + 1) + '. ' + j)
                except:
                    st.error("Oops! Looks like this algorithm does't work.\
                              We'll need to fix it!")

    # -----------------------------------------------------------------------#
    #                       SAFE FOR ALTERING/EXTENSION                      #
    #------------------------------------------------------------------------#
    #                           pandas profiling                             #
    #------------------------------------------------------------------------#
    if page_selection == "Pandas profiling":
        st.markdown(prof, unsafe_allow_html=True)
        ds = st.radio("choose the data sorce", ("movies data", "ratings data"))
        if ds == "movies data":
            data_file = 'resources/data/movies.csv'
        else:
            data_file = 'resources/data/ratings.csv'
        if data_file is not None:
            df = pd.read_csv(data_file)
            st.dataframe(df.head())
            profile = ProfileReport(df)
            st_profile_report(profile)
        pass

    #------------------------------------------------------------------------#
    #                           Sweetviz report                              #
    #------------------------------------------------------------------------#
    if page_selection == "Sweetviz":
        st.markdown(sweet, unsafe_allow_html=True)
        ds = st.radio("choose the data sorce", ("movies data", "ratings data"))
        if ds == "movies data":
            data_file = 'resources/data/movies.csv'
        else:
            data_file = 'resources/data/ratings.csv'
        if data_file is not None:
            df1 = pd.read_csv(data_file)
            st.dataframe(df1.head())
            if st.button("Genwrate Sweetviz Report"):
                report = sv.analyze(df1)
                report.show_html()
                st_display_sweetviz("SWEETVIZ_REPORT.html")
        pass

    #------------------------------------------------------------------------#
    #                           Custom EDA                                   #
    #------------------------------------------------------------------------#
    if page_selection == "EDA":
        #Ratings by year
        st.markdown(eda_header, unsafe_allow_html=True)

        if st.checkbox("Ratings by year"):
            st.image("resources/imgs/ratings_by_year.PNG", format='PNG')
            st.write(
                "The ratings for the movies span a period of 25 years, from 1995 all the way to 2019, with the last 5 years accumalatively having had the most ratings in comparison to any othe other 5 year interval. From 2006 to 2014 there is decline in user engagement when it comes to rating movies. Prior to 2006 there are 3 good years with ratings above 500000 ratings for the year, 3 more years at 400000 ratings and 3 below 300000 ratings for the year. it would be of interest to the spending behaviour of users for each of these years, as that would tell the complete story."
            )
            #components.html()

        #Movies Realese before and after 1995
        if st.checkbox(
                "Now for a look at the release year of each of the movies"):
            st.image("resources/imgs/Movie_release_over_T.PNG", format='PNG')
            st.write(
                "29906 movies have been released in total since 1995 up to 2019, in comparison to the 17937 that have released up to 1994 going all the way back to 1874 (this is not including movies that had no release date specified, which amount to 370 movies). The number of released movies per year is increases slowly at the beginning, then increasing faster leading up to 1995, where the is a substantial rise in the number of movies released. So much so that roughly on average a 153 movies have been released a year from 1874 to 1994, while that number increases substantially for the years between 1995 to 2019, averaging roughly 1246 movies per year. This has given users an overwheliming amount of options to choose from, with regards to the movies they can watch, catering to the needs of everyone, which makes the case for a recommendation system compelling."
            )

            #components.html()

        #Distributins of user ratings for movies in the past 25 years
        if st.checkbox(
                "Distributins of user ratings for movies in the past 25 years"
        ):
            st.image("resources/imgs/dst.PNG", format='PNG')
            st.image("resources/imgs/dst1.PNG", format='PNG')
            st.image("resources/imgs/dst2.png", format='PNG')
            st.write(
                "For the entire 25 year period, a rating of 4.0 is the most abundant rating given by users to movies,\
              followed by a rating of 3.0. Ratings of 5.0, 3.5 and 4.5 are next most numerous ratings users give to movies.\
              When the the 25 years are divided into 5, 5 year periods, the first 5 year period between 1995 and 1999,\
              there is an anomaly in the ratings, quite different from th other periods,\
              but still with ratings of 4.0 and 3.0 being the most abundant, followed by a 5.0 rating.\
              The last 3 intervals there is a contant pattern that has emerged with the distributions of the ratings"
            )
            #components.html()

        #Ratings distributions across movie genres
        if st.checkbox("Ratings distributions across movie genres"):
            st.image("resources/imgs/ratings_by_year.png", format='PNG')
            st.write(
                "Movies with between 1 to 4 genres have the most number of ratings for the 25 years, with an average rating for these of roughly bewteen 3.5 to 3.6. Movies with 2 and 3 genres movies get the lions share of the ratings."
            )
            #components.html()

        #Decade movies were released
        if st.checkbox("Decade movies were released"):
            st.image("resources/imgs/dc.png", format='PNG')
            st.write(
                "This is an interesting insight in the data with potentially huge implications, that will be eloborated upon later, in the conclusion when recommendations are put forward. For now however what emerges is the following; movies from before the 1970s have little to no ratings associated with them. Movies released from 1980s have the most ratings. The average rating for movies released for each decade from 1910 onwards is between 3.5 and 4.0., with that average for movies released in later decades carries more weight, since they have more ratings. With movies released in earlier decades having a lower average, perhaps to do with the quality of the movies."
            )
            #components.html()
        # Merging the train and movies data on the movieId column
        pass

    #------------------------------------------------------------------------#
    #                           Home                                         #
    #------------------------------------------------------------------------#
    #if page_selection == "Home":
    #    st.markdown(home,unsafe_allow_html=True)
    #
    #------------------------------------------------------------------------#
    #                        Slides                               #
    #------------------------------------------------------------------------#
    if page_selection == "Slides":
        st.markdown(slides, unsafe_allow_html=True)

        #load_css('utils/icon.css')

    #------------------------------------------------------------------------#
    #                        Solution Overview                               #
    #------------------------------------------------------------------------#
    if page_selection == "Solution Overview":
        st.markdown(html_temp, unsafe_allow_html=True)
        st.markdown(html_overview, unsafe_allow_html=True)
Пример #3
0
    <li class="nav-item">
        <a class="nav-link{' active' if t==active_tab else ''}" href="/?tab={t}">{t}</a>
    </li>
    """
    for t in tabs
)
tabs_html = f"""
    <ul class="nav nav-tabs">
    {li_items}
    </ul>
"""

st.markdown(tabs_html, unsafe_allow_html=True)
st.markdown("<br>", unsafe_allow_html=True)

if active_tab == "Principal":
    st.write("Welcome to my lovely page!")
    st.write("Feel free to play with this ephemeral slider!")
    st.slider(
        "Does this get preserved? You bet it doesn't!",
        min_value=0,
        max_value=100,
        value=50,
    )
elif active_tab == "About":
    st.write("This page was created as a hacky demo of tabs")
elif active_tab == "Contact":
    st.write("If you'd like to contact me, then please don't.")
else:
    st.error("Ocorreu um erro. Tente em alguns minutos.")
Пример #4
0
st.sidebar.markdown('---')

# TESTS
result = None

st.markdown('---')
if st.sidebar.checkbox('PyDeck test'):
    st.title('PyDeck test')
    suite = unittest.TestLoader().loadTestsFromTestCase(Tests_PyDeckMap)
    result = unittest.TextTestRunner(verbosity=2).run(suite)
    if result != None and result.wasSuccessful():
        st.info(f'Test PASSED :-)')
        # st.balloons()
    elif result != None:
        st.error(f'Test FAILED :-(')

if st.sidebar.checkbox('CAGR tests'):
    st.title('CAGR test')
    suite = unittest.TestLoader().loadTestsFromTestCase(Tests_CAGR)
    result = unittest.TextTestRunner(verbosity=2).run(suite)
    if result != None and result.wasSuccessful():
        st.info(f'Test PASSED :-)')
        # st.balloons()
    elif result != None:
        st.error(f'Test FAILED :-(')

if st.sidebar.checkbox('AVG tests'):
    st.title('AVG test')
    suite = unittest.TestLoader().loadTestsFromTestCase(Tests_AVG)
    result = unittest.TextTestRunner(verbosity=2).run(suite)
Пример #5
0
st.title("AIC-Bot")
st.subheader("*I can Tell you whats going on in an Image* :sunglasses: ")

################ SLIDE BAR ####################################

st.sidebar.header('Hello, World!')
st.sidebar.write("""
				I am Vivek and this is my Machine Learning Enginnering Nanodegree Cpstone Project.
				""")

file_image = st.file_uploader("Upload your photoes here", type=['jpg'])

if st.button("check"):
    if file_image:

        input_img = Image.open(file_image)

        st.write("**Input Photo**")
        st.image(input_img, use_column_width=False)

        caption = gen_cap(input_img)

        st.write("**Generated Caption **")
        st.success(caption)

    else:
        st.error("""Bad input ........:( ! 
			Please make sure the file upload is sucessful 
			""")
Пример #6
0
def write(analysis):
    """Writes the Relations Page"""
    
    # get data
    my_data = analysis['my_data']
    
    st.write("""
    # Relations
    *Visualizing Twitter-based communication networks within the Bundestag*
    
    How often do delegates interact and respond to each other on Twitter?
    
    Select a time frame and generate a visualization showing the connections
    which are formed by response tweets between members of the Bundestag. 
    The lines are coloured by the author of the tweets.
    """)
    
    # set default start and end times
    start_datetime = datetime.datetime.strptime('2018/05/01', '%Y/%M/%d')
    end_datetime = datetime.datetime.today()
    
    # select date range widget
    st.write("""
    ### Choose time frame:
    """)
    start_date = st.date_input('Start date', start_datetime)
    end_date = st.date_input('End date', end_datetime)
    
    # convert back to datetime
    start_datetime = datetime.datetime(year=start_date.year, month=start_date.month, day=start_date.day)
    end_datetime = datetime.datetime(year=end_date.year, month=end_date.month, day=end_date.day)

    # subset on selected time span
    mask = ((my_data.date >= start_datetime) & (my_data.date <= end_datetime))
    data_subset = my_data.loc[mask, :]
    
    # Drop down menu for threhold value
    thr_count = st.selectbox('Display only connections with more replies than ...', 
                          (3, 5, 10, 15), index=2)

    ## Get response tweets
    responses_count = vis_helpers.get_responses_count(data_subset)
    
    # show number of tweets selected
    if start_date < end_date:
        st.success(f'{len(responses_count)} tweets selected.')
    else:
        st.error('Error: End date must fall after start date.')
        
    ## Chord diagram
    chord_diagram = vis_helpers.generate_chord_diagram(responses_count, thr_count=int(thr_count))

    st.write(render(chord_diagram, backend='bokeh'))

    st.write("""
    ### How often do members of one party interact with members of other parties?
    """)
    ## Party-wise statistics
    for party in vis_helpers.party_cmap.keys():
        st.write(f"""### {party}""")
        chart = vis_helpers.generate_barplot_responding_to(responses_count, party=party)
        st.write(chart)
Пример #7
0
cnt['rolling_mean14days'] = cnt['Issues'].rolling(window=14).mean()
st.line_chart(cnt)

#perhaps create a list from length of dates and filter that way
st.subheader('Select the date range for the chart below')
from datetime import date

today = pd.Timestamp(date.today())
before = today + datetime.timedelta(days=-90)

start_date = st.date_input('Start date', before)
end_date = st.date_input('End date ', today)
if start_date < end_date:
    st.success('Start date: `%s`\n\nEnd date:`%s`' % (start_date, end_date))
else:
    st.error('Error: End date must fall after start date.')

st.write(start_date)
st.write(type(start_date))
data['created_at'] = pd.to_datetime(data['created_at'])
#st.write(data['created_at'])
#st.write(type(data['created_at']))

#filter_mask = data[DATE_COLUMN] > start_date
#filter_mask2 = data[DATE_COLUMN] < end_date
filtered_df = data[(data['created_at'] > start_date)
                   & (data['created_at'] < end_date)]
#st.dataframe(filtered_df.head())

cnt = pd.DataFrame(filtered_df.groupby('created_at').size().rename('Issues'))
cnt['rolling_mean7days'] = cnt['Issues'].rolling(window=7).mean()
Пример #8
0
def main():

    # DO NOT REMOVE the 'Recommender System' option below, however,
    # you are welcome to add more options to enrich your app.
    page_options = [
        "Solution Overview", "Insights", "Recommender System",
        "Why Choose Us?", "About Us", "Contact Us"
    ]
    st.markdown(
        """
		<style>
		.sidebar .sidebar-content{
		background-image: linear-gradient(white, red);
		font-color: white;
		}
		</style>
		""",
        unsafe_allow_html=True,
    )

    # -------------------------------------------------------------------
    # ----------- !! THIS CODE MUST NOT BE ALTERED !! -------------------
    # -------------------------------------------------------------------
    page_selection = st.sidebar.selectbox("Choose Option", page_options)
    if page_selection == "Recommender System":
        # Header contents
        st.write('# Movie Recommender Engine')
        st.write('### EXPLORE Data Science Academy Unsupervised Predict')
        st.image('resources/imgs/Image_header.png', use_column_width=True)
        # Recommender System algorithm selection
        sys = st.radio(
            "Select an algorithm",
            ('Content Based Filtering', 'Collaborative Based Filtering'))

        # User-based preferences
        st.write('### Enter Your Three Favorite Movies')
        movie_1 = st.selectbox('Fisrt Option', title_list[14930:15200])
        movie_2 = st.selectbox('Second Option', title_list[25055:25255])
        movie_3 = st.selectbox('Third Option', title_list[21100:21200])
        fav_movies = [movie_1, movie_2, movie_3]

        # Perform top-10 movie recommendation generation
        if sys == 'Content Based Filtering':
            if st.button("Recommend"):
                try:
                    with st.spinner('Crunching the numbers...'):
                        top_recommendations = content_model(
                            movie_list=fav_movies, top_n=10)
                    st.title("We think you'll like:")
                    for i, j in enumerate(top_recommendations):
                        st.subheader(str(i + 1) + '. ' + j)
                except:
                    st.error("Oops! Looks like this algorithm does't work.\
							  We'll need to fix it!")

        if sys == 'Collaborative Based Filtering':
            if st.button("Recommend"):
                try:
                    with st.spinner('Crunching the numbers...'):
                        top_recommendations = collab_model(
                            movie_list=fav_movies, top_n=10)
                    st.title("We think you'll like:")
                    for i, j in enumerate(top_recommendations):
                        st.subheader(str(i + 1) + '. ' + j)
                except:
                    st.error("Oops! Looks like this algorithm does't work.\
							  We'll need to fix it!")

    # -------------------------------------------------------------------

    # ------------- SAFE FOR ALTERING/EXTENSION -------------------
    #Home Page
    #if page_selection == "Home":

    #Solution Overview Page
    if page_selection == "Solution Overview":
        overview_options = ["Problem Statement", "Introduction", "Conclusion"]
        overview_selection = st.selectbox(
            "Please select an option to get an overview of the project",
            overview_options)

        if overview_selection == "Problem Statement":
            st.title('Problem Statement')
            break_h = """
				<br>
				<br>
				"""
            st.markdown(break_h, unsafe_allow_html=True)

            st.write(
                'Accurately predict unseen movie ratings gathered from thousands of users based on their historic preferences. The objective of this App is to construct a recommendation algorithm based on content and collaborative filtering, capable of accurately predicting how a user will rate a movie they have not watched yet based on their historical preference.'
            )

            break_h = """
				<br>
				<br>
				<br>
				"""

            st.markdown(break_h, unsafe_allow_html=True)

            st.image("resources/imgs/researcjh.png")

        if overview_selection == "Introduction":
            st.title('Introduction')
            break_h = """
				<br>
				<br>
				"""
            st.markdown(break_h, unsafe_allow_html=True)

            st.write(
                'Recommender systems are systems that are designed to recommend things to the user based on many different factors. These systems predict the most likely product that the user is most likely to purchase and are of interest. Companies like Netflix and Amazon use recommender systems to help their users to identify the correct product or movies for them. Recommender systems are an important class of machine learning algorithms that offer relevant suggestions to users. The suggested items are as relevant to the user as possible so that the user can engage with those items: YouTube videos, news articles, online products, movie and series recommendation. Items are ranked according to their relevancy, and the most relevant ones are shown to the user. The relevance is determined by the recommender system, mainly based on historical data. For example, If you have recently watched YouTube videos about elephants, then YouTube is going to start showing you many elephant videos with similar titles and themes. Recommender systems are generally divided into two main categories: collaborative filtering and content-based systems. Both users and service providers have benefited from these kinds of systems. Intelligent algorithms can help viewers find great titles from tens of thousands of options. This notebook will construct a recommendation algorithm based on content and collaborative filtering, capable of accurately predicting how a user will rate a movie they have not yet viewed based on their historic preferences. Providing an accurate and robust solution will have immense economic potential, with users of the system being exposed to content they would like to view or purchase - generating revenue and platform affinity.'
            )

            break_h = """
				<br>
				<br>
				<br>
				"""

            st.markdown(break_h, unsafe_allow_html=True)

            st.image("resources/imgs/data.png")

        if overview_selection == "Conclusion":
            st.title('Conclusion')
            break_h = """
				<br>
				<br>
				"""
            st.markdown(break_h, unsafe_allow_html=True)

            st.write(
                "Facebook, YouTube, LinkedIn are among the most used websites on the internet today that use recommender systems. Facebook suggests us to make more friends using the 'People You May Know' section. Similarly, LinkedIn recommends you connect with people you may know, and YouTube suggests relevant videos based on your previous browsing history. All of these are recommender systems in action. While most of the people are aware of these features, only a few know that the algorithms used behind these features are known as 'Recommender Systems'. They 'recommend' personalised content based on user's past / current preference to improve the user experience. We were tasked with accurately predicting unseen movie ratings gathered from thousands of users based on their historic preferences. Broadly, there are two types of recommendation systems: Content-Based and Collaborative filtering based as mention. In the notebook, we observation algorithms of both content-based and collaborative filtering. When we used the linear regression model (content-based) on the test data, it produced an RMSE score of 0.82565. However, the Singular Value Decomposition (collaborative-filtering) performed better on the test data with an RMSE score of 0.80773, which is our final score on the Kaggle leaderboard."
            )
            break_h = """
				<br>
				<br>
				<br>
				"""

            st.markdown(break_h, unsafe_allow_html=True)

            st.image("resources/imgs/dota.png")

    #About Us page
    if page_selection == "About Us":
        title = """
				<h2 style="color:black;text-align:center;">TEAM Four is a group of data scientists from EDSA</h2>
				"""
        st.markdown(title, unsafe_allow_html=True)

        st.image("resources/imgs/team.png", use_column_width=True)

    if page_selection == "Insights":
        #title_tag("Insights extracted from the data")
        visual_options = [
            "The top 15 movies", "Genres with the most number movies",
            "A count of films by directors", "Top 10 ratings",
            "Genre distribution", "Wordcloud", "Wordcloud analysis",
            "Model accuracy"
        ]
        visual_selection = st.selectbox(
            "Choose Exploratory Data Analaysis Visuas Option", visual_options)

        if visual_selection == "The top 15 movies":
            subheading('Top 15 movies by number of Ratings')
            st.image('resources/imgs/top_15_titles.png', use_column_width=True)
        elif visual_selection == "Genres with the most number movies":
            subheading('Genres with the most number movies')
            st.image('resources/imgs/Genres.png', use_column_width=True)
        elif visual_selection == "A count of films by directors":
            subheading('A count of films by directors')
            st.image('resources/imgs/director.png', use_column_width=True)
        elif visual_selection == "Wordcloud":
            subheading('Most Popular Movie Keywords')
            st.image('resources/imgs/wordcloud.png', use_column_width=True)
        elif visual_selection == "Top 10 ratings":
            subheading('Top 10 Movie Ratings')
            st.image('resources/imgs/top_10_ratings.png',
                     use_column_width=True)
        elif visual_selection == "Genre distribution":
            subheading('Number of times a genre appears')
            st.image('resources/imgs/Genres_2.png', use_column_width=True)
        elif visual_selection == "Wordcloud analysis":
            subheading('Most Popular Movie Keywords analysis')
            st.image('resources/imgs/wordcloud_2.png', use_column_width=True)
        elif visual_selection == "Model accuracy":
            subheading('Model accuracy by means of RMSE score')
            st.image('resources/imgs/model_accuracy.png',
                     use_column_width=True)

#Building out the business pitch
    if page_selection == "Why Choose Us?":
        st.title("Why Choose Us?")

        break_h = """
				<br>
				<br>
				"""

        st.markdown(break_h, unsafe_allow_html=True)

        st.write(
            "Our team can help your organisation find interesting patterns and inisghts from available data. One such data science project we proud on working on is a recommender system. Recommender systems can mean big business for your organisation. Research shows that recommender systems can increase an organisation's turnover by up to 30%"
        )

        break_h = """
				<br>
				"""

        st.markdown(break_h, unsafe_allow_html=True)

        st.image('resources/imgs/data-science.png')

    #Building out the Contact Page
    if page_selection == "Contact Us":
        title = """
		<div style="background-color:#464e5f00;padding:5px;border-radius:10px;margin:10px;">
		<h3 style="color:black;text-align:center;">Lets get in touch for all your Machine Learning needs!</h3>
  		"""

        st.markdown(title, unsafe_allow_html=True)
        firstname = st.text_input("Enter your Name", "Type Here Please...")
        lastname = st.text_input("Enter your last Name", "Type Here Please..")
        contactdetails = st.text_input("Enter your contact details here",
                                       "Type Here Please...")
        message = st.text_area(
            "What is company trying to achieve through data",
            "Type here Please..")

        if st.button("Submit"):
            result = message.title()
            st.success(result)
Пример #9
0
def main():

    # DO NOT REMOVE the 'Recommender System' option below, however,
    # you are welcome to add more options to enrich your app.
    page_options = ["Welcome","About The App","EDA","Recommender System","Search for a movie","Solution Overview","Contact Us","About Us"]

    # -------------------------------------------------------------------
    # ----------- !! THIS CODE MUST NOT BE ALTERED !! -------------------
    # -------------------------------------------------------------------
    page_selection = st.sidebar.selectbox("Choose Option", page_options)
    if page_selection == "Recommender System":
        # Header contents
        st.write('# Movie Recommender Engine')
        st.write('### EXPLORE Data Science Academy Unsupervised Predict')
        st.image('resources/imgs/Image_header.png',use_column_width=True)
        # Recommender System algorithm selection
        sys = st.radio("Select an algorithm",
                       ('Content Based Filtering',
                        'Collaborative Based Filtering'))

        # User-based preferences
        st.write('### Enter Your Three Favorite Movies')
        movie_1 = st.selectbox('Fisrt Option',title_list[14930:15200])
        movie_2 = st.selectbox('Second Option',title_list[25055:25255])
        movie_3 = st.selectbox('Third Option',title_list[21100:21200])
        fav_movies = [movie_1,movie_2,movie_3]

        # Perform top-10 movie recommendation generation
        if sys == 'Content Based Filtering':
            if st.button("Recommend"):
                try:
                    with st.spinner('Crunching the numbers...'):
                        top_recommendations = content_model(movie_list=fav_movies,
                                                            top_n=10)
                    st.title("We think you'll like:")
                    for i,j in enumerate(top_recommendations):
                        st.subheader(str(i+1)+'. '+j)
                except:
                    st.error("Oops! Looks like this algorithm does't work.\
                              We'll need to fix it!")


        if sys == 'Collaborative Based Filtering':
            if st.button("Recommend"):
                try:
                    with st.spinner('Crunching the numbers...'):
                        top_recommendations = collab_model(movie_list=fav_movies,
                                                           top_n=10)
                    st.title("We think you'll like:")
                    for i,j in enumerate(top_recommendations):
                        st.subheader(str(i+1)+'. '+j)
                except:
                    st.error("Oops! Looks like this algorithm does't work.\
                              We'll need to fix it!")


    # -------------------------------------------------------------------

    # ------------- SAFE FOR ALTERING/EXTENSION -------------------
    if page_selection == "Solution Overview":
        st.title("Solution Overview")
        st.markdown("<h1 style='text-align: left; color: black;'>Content-based filtering: uses item features to recommend other items similar to what the user likes, based on their previous actions or explicit feedback</h1>", unsafe_allow_html=True)
        st.image(('resources/imgs/content-based.png'), use_column_width=True)
        st.markdown("<h1 style='text-align: left; color: black;'>Collaborative filtering: builds a model from your past behavior (i.e. movies watched or selected by the you) as well as similar decisions made by other users</h1>", unsafe_allow_html=True)
        st.image(('resources/imgs/collaborative filtering.png'), use_column_width=True)
        st.write("Describe your winning approach on this page")

    if page_selection == "Search for a movie":
        st.title("Search for Movies")
        st.image(('resources/imgs/franchises.jpg'), use_column_width=True)
        st.markdown('Please Refer to the About Machine Learning Page to learn more about the techniques used to recommend movies. If you decide not to use the recommender systems you can use this page to filter movies based on the rating of the movie , the year in which the movie was released and the genre of the movies. After you change the filter you will be left with movies that are specific to that filter used. Then when you scroll down you will see the movie name and the link to a youtube trailer of that movie. When you click the link ,you will see a page on youtube for that specific movie and you can watch the trailer and see if you like it. This is an alternative method to you if you are not satisfied with the recommender engine . Enjoy! ', unsafe_allow_html=True)
        # Movies
        df = pd.read_csv('resources/data/movies.csv')

        
        def explode(df, lst_cols, fill_value='', preserve_index=False):
            import numpy as np
             # make sure `lst_cols` is list-alike
            if (lst_cols is not None
                    and len(lst_cols) > 0
                    and not isinstance(lst_cols, (list, tuple, np.ndarray, pd.Series))):
                lst_cols = [lst_cols]
            # all columns except `lst_cols`
            idx_cols = df.columns.difference(lst_cols)
            # calculate lengths of lists
            lens = df[lst_cols[0]].str.len()
            # preserve original index values    
            idx = np.repeat(df.index.values, lens)
            # create "exploded" DF
            res = (pd.DataFrame({
                        col:np.repeat(df[col].values, lens)
                        for col in idx_cols},
                        index=idx)
                    .assign(**{col:np.concatenate(df.loc[lens>0, col].values)
                            for col in lst_cols}))
            # append those rows that have empty lists
            if (lens == 0).any():
                # at least one list in cells is empty
                res = (res.append(df.loc[lens==0, idx_cols], sort=False)
                            .fillna(fill_value))
            # revert the original index order
            res = res.sort_index()   
            # reset index if requested
            if not preserve_index:        
                res = res.reset_index(drop=True)
            return res 
        movie_data = pd.merge(rating_m, df, on='movieId')
        movie_data['year'] = movie_data.title.str.extract('(\(\d\d\d\d\))',expand=False)
        #Removing the parentheses
        movie_data['year'] = movie_data.year.str.extract('(\d\d\d\d)',expand=False)

        movie_data.genres = movie_data.genres.str.split('|')
        movie_rating = st.sidebar.number_input("Pick a rating ",0.5,5.0, step=0.5)

        movie_data = explode(movie_data, ['genres'])
        movie_title = movie_data['genres'].unique()
        title = st.selectbox('Genre', movie_title)
        movie_data['year'].dropna(inplace = True)
        movie_data = movie_data.drop(['movieId','timestamp','userId'], axis = 1)
        year_of_movie_release = movie_data['year'].sort_values(ascending=False).unique()
        release_year = st.selectbox('Year', year_of_movie_release)

        movie = movie_data[(movie_data.rating == movie_rating)&(movie_data.genres == title)&(movie_data.year == release_year)]
        df = movie.drop_duplicates(subset = ["title"])
        if len(df) !=0:
            st.write(df)
        if len(df) ==0:
            st.write('We have no movies for that rating!')        
        def youtube_link(title):
    
            """This function takes in the title of a movie and returns a Search query link to youtube
    
            INPUT: ('Avengers age of ultron')
            -----------
    
            OUTPUT: https://www.youtube.com/results?search_query=The+little+Mermaid&page=1
            ----------
            """
            title = title.replace(' ','+')
            base = "https://www.youtube.com/results?search_query="
            q = title
            page = "&page=1"
            URL = base + q + page
            return URL            
        if len(df) !=0:           
            for _, row in df.iterrows():
                st.write(row['title'])
                st.write(youtube_link(title = row['title']))



    # You may want to add more sections here for aspects such as an EDA,
    # or to provide your business pitch.
    if page_selection == "Welcome":
        st.subheader("==========================================================")
        st.markdown('''<span style="color:black"> **Welcome To Our Movie Review App.** </span>''', unsafe_allow_html=True)
        st.subheader("==========================================================")
        st.image('resources/imgs/giphy.gif', use_column_width=True)
        st.image('resources/imgs/Movie-Show-GIF-960.gif', use_column_width=True)

    if page_selection == "About The App":
        st.title("About the App")
        st.markdown("Are you a movie lover? Are you tired of wasting your time watching tons of trailers and ending up not watching their movies? Are you tired of finishing your popcorns before you find the right movie? That has come to an end!!")
        st.image(["resources/imgs/Tired 1.1.gif", "resources/imgs/Tired 1.2.jpg"],use_column_width=True)
        st.markdown("Then we have got the right App for you.")
        st.subheader("How The App Works")
        st.markdown("The Movie Recommender App filters or predicts your preferences based on your favourite or watched movie selections. With just a few clicks, you will select three of your most favourite movies from thousands of movies on the app and you will get top 10 movies you are most likely to enjoy. You have an option to view some data visualizations including word clouds that show the most popular words that appear in movie titles and plots on the most popular genres. The app also contains a contact page, where users of the app can rate our app and give feedback and suggestions. Links to movie sites are also included, so the user has quick and easy to access the recommended movies.")
        st.subheader("Data Description")
        st.markdown("The dataset used for the movie recommender app consists of several million 5-star ratings obtained from users of the online MovieLens movie recommendation service. The data for the MovieLens dataset is maintained by the GroupLens research group in the Department of Computer Science and Engineering at the University of Minnesota. Additional movie content data was legally scraped from IMDB.")

    if page_selection == "EDA":
        st.title("Exploratory Data Analysis")
        st.subheader("All Time Popular Movies By Ratings Insights")
        st.markdown("The graph shows all the movies that have been rated the most for all movies in the dataset. The most popular can be seen as a 1994 movie Shawshank Redemption with a rating count of more than 30 thousand.,")
        st.image(('resources/imgs/all time popular movies by ratings.png'), use_column_width=True)
        st.subheader("Released Movies Per Year Insights")
        st.markdown("The graph shows the number of movies that have been released each year from 1971 to 2017. It is safe to note that there has been an exponential increase in the number of movies released each year. we can go as far as to say that movies released in the 2010s are about 4 times the number of those that were released in the 1070s.")
        st.image(('resources/imgs/total movies released per year.png'), use_column_width=True)
        st.subheader("Popular Genres By Rating Insights")
        st.markdown("The treemap depicts the genres that are most popular to the least popular in terms of ratings. From the treemap it can be seen that the most rated genre happens to be Drama, followed by Comedy with IMAX the least rated.")
        st.image(('resources/imgs/popular genres.png'), use_column_width=True)
        st.subheader("Percentage Of Users Per Ratings Insights")
        st.markdown("The graphs shows the total number of user percentage based on their ratings. Most users rated movies with a rating of 4.0(26.53%)")
        st.image(('resources/imgs/percentage of users per rating.png'), use_column_width=True)
        st.subheader("Popular Actors/Actresses Insights")
        st.markdown("The graph shows who the most popular actors/actresses appearing in the movies are and the number of movies they appear in. The actor Samuel L Jackson is the most popular, appearing in more than 80 movies. Actress Julianne Moore is the most popular amoung the actresses.")
        st.image(('resources/imgs/popular actors.png'), use_column_width=True)
        st.subheader("Rating Distribution")
        st.markdown("This graph shows how ratings are distributed. Just like in, Percentage of Users Per Ratings Insights, most movies have a rating of 4.0")
        st.image(('resources/imgs/rating distribution.png'), use_column_width=True)
        st.subheader("Movie Runtime Ditribution")
        st.markdown("Below we can a see a distribution of movie runtime. Majority of the movies have a 100 minutes runtime.")
        st.image(('resources/imgs/runtime distribution.png'), use_column_width=True)
        st.subheader("Popular Movies Wordcloud")
        st.markdown("The wordcloud below shows the letters appearing the most in the movie titles. Love, Girl, Man and Night are words that appear the biggest. This means that more movies have such words in their title. It makes sense that these words appear the most as we have more movies in the drama, comedy and romance genre.")
        st.image(('resources/imgs/most popular movies wordcloud.png'), use_column_width=True)
        st.subheader("Popular Movie Directors")
        st.markdown("The graph below shows the most popular movie directors. It makes sense for Woody Allen to be the most popular director as the first movie he directed was in 1965 and since then he has directed about 50 movies with the latest released in 2020. Woody has also been acting since 1965 to date, he has directed 3 short films and directed about 12 tv shows.")
        st.image(('resources/imgs/popular movie directors.png'), use_column_width=True)
        st.subheader("Average Budget Per Genre")
        st.markdown("The graph below shows the average budget used for movies in each genre. The War genre seems to have the highest average budget, with the Documentary genre having the least budget.")
        st.image(('resources/imgs/average budget per genre.png'), use_column_width=True)
        st.subheader("Average Runtime Per Genre")
        st.markdown("Western genre has the highest average movie runtime at about 120 minutes. Animation genre has the least average runtime at about 76-77 minutes.")
        st.image(('resources/imgs/average runtime per genre.png'), use_column_width=True)
        st.subheader("Top 20 Popular Movies From 2010")
        st.markdown("The 2014 movie Intersteller had the highest ratings. The movie only had a budget of $165 million but went to make $696.3 million from the box office. The movie also bagged 6 awards including an Academy award for best visual effects.")
        st.image(('resources/imgs/top 20 popular movies by ratings from 2010.png'), use_column_width=True)
        

    if page_selection == "Contact Us":
        st.title("Get in touch with us")
        st.markdown('''<span style="color:blue"> **Help us improve this app by rating it. Tell us how to give you a better user experience.** </span>''', unsafe_allow_html=True)
        @st.cache(allow_output_mutation=True)
        def get_data():
            return []
        name = st.text_input("User name")
        inputs = st.text_input("Let us improve your user experience!!!")
        rate = st.slider("Rate us", 0, 5)
        if st.button("Submit"):
            get_data().append({"User name": name, "Suggestion": inputs,"rating":rate})
        st.markdown('''<span style="color:blue"> **What other users said:** </span>''', unsafe_allow_html=True)
        st.write(pd.DataFrame(get_data()))
        st.markdown('''<span style="color:blue"> **For any questions contact us here:** </span>''', unsafe_allow_html=True)
        st.image(('resources/imgs/our contact2.PNG'), use_column_width=True)
            #pass
       
    if page_selection == "About Us":
        st.markdown("<h1 style='text-align: center; color: blue;'>About Us</h1>", unsafe_allow_html=True)
        st.markdown("")
        st.info("1. Palesa Hlungwani")
        st.image(('resources/imgs/Palesa.jpg'), use_column_width=True)
        st.markdown("* Github account:PTStace")
        st.markdown("* Kaggle account:palesa_hlungwani")
        st.markdown("* email:[email protected]")
        st.markdown("")

        st.info("2. Orline Sorelle Ketcha")
        st.image(('resources/imgs/Orline.jpg'), use_column_width=True)
        st.markdown("* Github account:OrlineSorel")
        st.markdown("* Kaggle account:Sorelle94")
        st.markdown("* email:[email protected]")
        st.markdown("")

        st.info("3. Thiyasizwe Kubeka")
        st.image(('resources/imgs/Thiya.jpg'), use_column_width=True)
        st.markdown("* Github account:thiyasizwe_kubeka")
        st.markdown("* Kaggle account:Thiyasizwa_kubeka")
        st.markdown("* email:[email protected]")
        st.markdown("")

        st.info("4. Katleho Mokhele")
        st.image(('resources/imgs/Katleho.jpg'), use_column_width=True)
        st.markdown("* Github account:Katness AI")
        st.markdown("* Kaggle account:Katleho Mokhele")
        st.markdown("* email:[email protected]")
        st.markdown("")

        st.info("5. Mfumo Baloyi")
        st.image(('resources/imgs/Mfumo.jpg'), use_column_width=True)
        st.markdown("* Github account:MfumoB")
        st.markdown("* Kaggle account:Mfumoe")
        st.markdown("* email:[email protected]")
Пример #10
0
def _(arg, prop, verbose=False):
    st.write(".. argument is of type ", type(arg))
    if prop=='price':
        product_price(arg)
    else:
        st.error(f'No such prop {prop}')
Пример #11
0
                        })
                        fps = mfram.fram_imwrite(int(se_frame[i][0]),
                                                 int(se_frame[i][1]))
                        bar.progress(round((i + 1) / (len(txt)) * 100))
                        smrng[i] = fps
                        area.table({
                            '开始帧': sframe,
                            '结束帧': eframe,
                            '流畅度': smrng,
                            ' ': mark,
                            '  ': mark
                        })
                    xndery.success("流畅度计算完成!")
                    st.balloons()
else:
    st.error("请输入正确的视频文件路径")


def get_user_name():
    return 'John'


# ------------------------------------------------
# with st.echo():
#     # Everything inside this block will be both printed to the screen
#     # and executed.
#     st.header('请在左侧选择功能后,点击运行')
#     st.warning('请在左侧选择功能后,点击运行')
#     st.info("获取一下fps")

#     def get_punctuation():
Пример #12
0
            BUY.append(i)
        elif not (np.isnan(sell)):
            SELL.append(i)
    col1.write(BUY)
    col2.write(SELL)
    for num, i in enumerate(list(df_selected_sector.Symbol)[:-1]):
        text = str(num + 1) + "." + i
        df_MACD = MACD(i)
        buy = df_MACD["Buy_Signal_Price"][-1]
        sell = df_MACD["Sell_Signal_Price"][-1]
        expanded = False
        if not (np.isnan(buy)):
            expanded = True
        elif not (np.isnan(sell)):
            expanded = True

        company_expander = st.beta_expander(text, expanded=expanded)
        with company_expander:
            if not (np.isnan(buy)):
                st.success("BUY")
            elif not (np.isnan(sell)):
                st.error("SELL")
            MACD_plot(df_MACD)

elif algo_trad_strat_radio == "RSI":
    # st.info("RSI of closing price")
    st.write("Coming soon..")
elif algo_trad_strat_radio == "Moving Average":
    # st.info("Moving Average of closing price")
    st.write("Coming soon..")
Пример #13
0
    st.title("High level metrics")
    st.write("This will take a minute to collect.")
    st.write(
        "If you want to contribute, please refer to the instructions in " +
        "[Contributing](https://github.com/bigscience-workshop/promptsource/blob/main/CONTRIBUTING.md)."
    )

    #
    # Loads template data
    #
    try:
        template_collection = TemplateCollection()
    except FileNotFoundError:
        st.error(
            "Unable to find the prompt folder!\n\n"
            "We expect the folder to be in the working directory. "
            "You might need to restart the app in the root directory of the repo."
        )
        st.stop()

    #
    # Global metrics
    #
    counts = template_collection.get_templates_count()
    nb_prompted_datasets = len(counts)
    st.write(f"## Number of *prompted datasets*: `{nb_prompted_datasets}`")
    nb_prompts = sum(counts.values())
    st.write(f"## Number of *prompts*: `{nb_prompts}`")

    #
    # Metrics per dataset/subset
    "number_project": Projects,
    "average_montly_hours": Hours,
    "time_spend_company": Years,
    "Work_accident": Accident,
    "promotion_last_5years": Promotion,
    "Departments ": Departments,
    "salary": Salary
}

df = pd.DataFrame.from_dict([my_dict])

if modell == "Gradient Boosting Classifier":
    prediction = gb_model.predict(df)
elif modell == "KNN Classifier":
    prediction = knn_model.predict(df)
else:
    prediction = rf_model.predict(df)

st.markdown("## The information about the employee is below")
st.write(df)

st.subheader("""Press 'Predict' if configuration is right""")

if st.button('Predict'):
    if prediction == 0:
        st.success("The employee seems NOT TO CHURN.")
        st.balloons()
    else:
        st.warning("The employee seems to CHURN.")
        st.error("You should take some precautions.")
Пример #15
0
age = st.number_input('enter house area in sqft',
                      max_value=50,
                      min_value=0,
                      value=1)

location = st.text_area('enter location address')

submit = st.button('make predictions')

if submit and location:
    #st.write('we got input')
    try:
        entry = UserInput(house_area=area,
                          no_of_rooms=rooms,
                          age=age,
                          location=location)

        sess.add(entry)
        sess.commit()
        st.success('data added to database')

    except Exception as e:
        st.error('something is wrong : {e}')

if st.checkbox('view data'):
    results = sess.query(UserInput).all()
    for item in results:
        st.write(item.location)
        st.write(item.house_area)
        st.write(item.age)
        st.write(item.no_of_rooms)
Пример #16
0
    )
    st.plotly_chart(fig)

######################## Countries with zero cases #######################
breakline()
st.markdown(
    "<h2 style='text-align: center; color: black; background-color:crimson'>Countries with zero cases</h2>",
    unsafe_allow_html=True)
case_type = st.selectbox("Select case type : ",
                         ['Confirmed', 'Active', 'Deaths', 'Recovered'],
                         1,
                         key='zero_cases')
temp_df = country_df[country_df[case_type] == 0]
st.write('### Countries with zero ' + case_type.lower() + ' cases :')
if len(temp_df) == 0:
    st.error('Sorry. There are no records present where ' + case_type.lower() +
             ' cases are zero!')
else:
    temp_df = temp_df[[
        'Country_Region', 'Confirmed', 'Deaths', 'Recovered', 'Active'
    ]]
    st.write(temp_df)
##########################################################################

# Data Resource Credits
st.subheader('Resource Credits')
data_source = 'Johns Hopkins University CSSE'
if sel_region == 'KOR':
    data_source = 'KCDC'
elif not sel_region:
    data_source += ', KCDC'
st.write('Data source: ' + data_source)
Пример #17
0
# csv
import csv

# Ttitle
st.title("Find your music type")

# Subtitle
st.subheader("Upload your music")

#def music_choice():
link = st.text_input('Enter a youtube url:')
try:
    st.video(link)
except FileNotFoundError:
    st.error('File not found.')

# convert youtube link to mp3 audio
audio = youtube_to_mp3(link)
print(f"youtube is : {audio}")
print("audio telecharge")

# time wait
time.sleep(1)

# convert mp3 audio to wav audio
audio_conversion(audio)
print(f"wav is: {audio}")
print('audio convertie')

# create an empty csv file
            ]

        #need it to be decreasing not increases
        setwinners = [t[0] for t in sorted(final_index, key=lambda x: x[1])]

        #add on some just really good episodes if their match didnt return enough
        counts = 0
        final_index = []
        while len(setwinners) + len(final_index) < 5:
            if counts not in setwinners:
                final_index.append(counts)
            counts = counts + 1

        setwinners = setwinners[0:min(len(setwinners), 5)]

        st.write(dataset.iloc[setwinners][['season', 'episode', 'title']])

        if len(final_index) > 0:
            st.write(
                'It looks like we didn\'t find enough matches to what you were looking for so please also enjoy these really good episodes'
            )
            st.write(dataset.iloc[final_index][['season', 'episode', 'title']])
        final_index = setwinners + final_index
        if not spoil:
            for i in final_index:
                st.write(dataset.iloc[i].title + ':')
                st.write(dataset.iloc[i].summary)

elif submit and not ready:
    st.error('Please fix the warnings and then resubmit')
Пример #19
0
def main():
	"""Tweet Classifier App with Streamlit """

	html_temp = """
    <div style="background:#025246 ;padding:5px">
    <h2 style="color:white;text-align:center;">TEAM 7 Tweet classification ML App </h2>
    </div>
    """
	st.markdown(html_temp, unsafe_allow_html = True)
	st.markdown('<style>body{background-color: #D8D8D8;}</style>',unsafe_allow_html=True)

	#image
	
	image = Image.open('resources/imgs/Quiver1.jpg')

	st.image(image,use_column_width=True)
	
	# Creating sidebar with selection box -
	# you can create multiple pages this way
	options = ["Background", "Insights", "Prediction", "About Team 7", "Contact Us"]
	selection = st.sidebar.selectbox("Please select an option", options)
	st.markdown(
	"""
	<style>
	.sidebar .sidebar-content{
	background-image: linear-gradient(#025246, #025246);
	font color: white;
	}
	</style>
	""",
	unsafe_allow_html=True,
	)



		#Building out the About Page
	if selection == "About Team 7":
		st.subheader("TEAM 7 is a group of four members from EDSA comprising of Thiyasize Kubeka, Warren Mnisi, Samuel Aina, and Tumelo Malebo")
		st.subheader("Visit our Contact Page and lets get in touch!")
  
	#Building out the "Insights" page   
	if selection == "Insights":
      	#st.warning("Please view the visualations and see how insightful the raw dataset became!")
       #Word cloud for anti and neutral tweets
       
		if st.checkbox("Word cloud for pro and news"):
			st.subheader("Word cloud analysis for pro and factual sentiments")
			st.image('resources/imgs/Word_Cloud_First_line.PNG')
   
		#Word cloud for anti and neutral tweets
		if st.checkbox("Word cloud for anti and neutral"):
			st.subheader("Word cloud analysis for anti and neutral sentiments")
			st.image('resources/imgs/Word_Cloud_Second_line.PNG')
   
		#Tweet distribution by sentiment
		if st.checkbox("Tweet distribution by sentiment"):
			st.subheader("count of words per each sentiment with clean data")
			st.image('resources/imgs/Distribution_of_Tweets_per_Sentiment_Group.PNG', channels="BGR")

		#Emoji analyis
		if st.checkbox("Emoji analysis"):
			st.subheader("A detailed analysis of the emoji's within the dataset")
			st.image('resources/imgs/Emoji_Analysis.PNG', channels="BGR")

		#Overall hashtag analysis
		if st.checkbox("Overall hashtag analysis"):
			st.subheader("This is an overall view of the hashtags encompasses the Pro, News, Neutral and Anti classes")
			st.image('resources/imgs/Hashtag_Analysis_Overall.PNG', channels="BGR")
			
			#Retweet distribution by hashtag
		if st.checkbox("Retweet distribution by sentiment"):
			st.subheader('frequent retweets are distributed to showcase which ones are the most common')
			st.image('resources/imgs/Tweet - Retweet Distributions by Sentiment Class.PNG', channels="BGR")
      
		if st.checkbox('Show raw data'): # data is hidden if box is unchecked
			st.subheader('Raw Twitter data and label')
			st.write(raw[['sentiment', 'message']]) # will write the df to the page
    
    
  
	if selection == "Background":
		
		st.success("We built a robust machine learning classification model to help tweets to be better classified wether they believe climate change is a man-made phenomena. In turn, this will help the market research divisions in offering more sustainable products and services.")

		st.write('Introduction')
		st.success("Climate change always been acknowledged by the scientific community as one of the critical issues facing mankind. Many companies are built around the idea of preserving an environmental friendly culture, be it on the products and services they offer or the actual raw material used to extend the structure of their company. One thing that has not been of certain yet is what perception other people have on environmental awareness.It is of importance to understand public perception of climate change through the use of twitter data. This will allow companies access to a broad base of consumer sentiment thereby increasing their insights for future marketing strategies.")
		
		st.write("Problem Statement")
		st.success("There is an excess of information about climate change on social media platforms like Twitter. As such it is difficult for companies to discern the beliefs of people relating to climate change. Having a robust machine learning model that is able to classify a person's belief in climate change from historical tweet data, as part of companies research toolset will enable them to better gauge their perception of customers relating to sustainability their products and services.")

		st.write("Conclusion")
		st.success("In conclusion we found that most tweets were from users who believed that climate change is a man-made phenomena. As such, for company's to stay relevant with most users is required to adapt their business models to more sustainable products and services as well being mindful of the externalities they bring along.")


	#Building out the Contact Page
	if selection == "Contact Us":
		st.info("Lets get in touch for all your ML needs")
		firstname = st.text_input("Enter your Name", "Type Here Please...")
		lastname = st.text_input("Enter your last Name", "Type Here Please..")
		contactdetails = st.text_input("Enter your contact details here", "Type Here Please...")
		message = st.text_area("Tell us about your compaby's Data Science needs", "Type here Please..")
  
		if st.button("Submit"):
			result = message.title()
			st.success(result)


	#Building out the Prediction Page
	if selection == "Prediction":
	# Creating a text box for user input
		options = st.selectbox(
			'Which model would you like to use?',
			('KNN Model', 'Linear SVC Model', 'Complement Naive Bayes Model'))

		st.write('You selected the :', options)
		#Selecting the KNN model
		if options == 'KNN Model':
			st.success("KNN or K-nearest Neighbors Classifiers algorithm assumes that similar things exist in close proximity. In other words, similar things are near to each other")
			# Creating a text box for user input
		user_text = st.text_area("Enter Text","Type Here", key=1)

		if st.button("Classify", key=1):
			# Transforming user input with vectorizer
			#vect_text = tweet_cv.fit_transform([tweet_text]).toarray()
			KNN= joblib.load(open(os.path.join("resources/team7_KNN.pkl"),"rb"))
			prediction = KNN.predict([user_text])
			st.success("Text Categorized as : {}".format(prediction))
			#Climate change Class result
			if prediction[0] == 2:
				st.info('This tweet links to factual news about climate change')
			if prediction[0] == 1:
				st.success('Tweet support the believe of man-made climate change')
			if prediction[0] == 0:
				st.warning('Tweet neither supports nor refutes the believe of man-made climate change')
			if prediction[0] == -1:
				st.error('Tweet does not believe in man-made climate change')
      
			#Selecting the Linear SVC Model
			if options == 'Linear SVC Model':
				st.success("A linear SVM model is a representation of the examples as points in space, mapped so that the examples of the separate categories are divided by a clear gap that is as wide as possible. New examples are then mapped into that same space and predicted to belong to a category based on the side of the gap on which they fall.")
				# Creating a text box for user input
			user_text = st.text_area("Enter Text","Type Here", key=2)
				

			if st.button("Classify", key=2):
				# Transforming user input with vectorizer
				#vect_text = tweet_cv.fit_transform([tweet_text]).toarray()
				Linear_SVC = joblib.load(open(os.path.join("resources/team7_linear_svc.pkl"),"rb"))
				prediction = Linear_SVC.predict([user_text])
				st.success("Text Categorized as : {}".format(prediction))
				#Climate change Class result
				if prediction[0] == 2:
					st.info('Tweet links factual news about climate change')
				if prediction[0] == 1:
					st.success('Tweet support the believe of man-made climate change')
				if prediction[0] == 0:
					st.warning('Tweet neither supports nor refutes the believe of man-made climate change')
				if prediction[0] == -1:
					st.error('Tweet does not believe in man-made climate change')
      

			#Selecting the Complement Naive Bayes Model
			if options == 'Complement Naive Bayes Model':
				st.success("Complement Naive Bayes is particularly suited to work with imbalanced datasets. In complement Naive Bayes, instead of calculating the probability of an item belonging to a certain class, we calculate the probability of the item belonging to all the classes.")
					# Creating a text box for user input
			user_text = st.text_area("Enter Text","Type Here", key=3)
				
			if st.button("Classify", key=3):
			# Transforming user input with vectorizer
			#vect_text = tweet_cv.fit_transform([tweet_text]).toarray()
				LR = joblib.load(open(os.path.join("resources/team7_complement_naive_bayes_model.pkl"),"rb"))
				prediction = LR.predict([user_text])
				st.success("Text Categorized as : {}".format(prediction))
				#Climate change Class result
				if prediction[0] == 2:
					st.info('This tweet links to factual news about climate change')
				if prediction[0] == 1:
					st.success('This tweet supports the belief of man-made climate climate')
				if prediction[0] == 0:
					st.warning('This tweet neither refutes or supports man-made climate change')
				if prediction[0] == -1:
					st.error(' This tweet does not believe in man-made climate change')
Пример #20
0
    drop_lat = st.number_input('Select dropoff latitude')
    st.write('Dropoff Latitude: ', drop_lat)

url = 'https://docker-image-tst-hroqn6xmnq-ew.a.run.app/predict_fare/'

if url == 'http://taxifare.lewagon.ai/predict_fare/':

    st.markdown(
        'Maybe you want to use your own API for the prediction, not the one provided by Le Wagon...'
    )

if st.button('Predict'):
    # print is visible in server output, not in the page

    if pick_long == 0 or pick_lat == 0 or drop_long == 0 or drop_lat == 0 or pass_cnt == 0:
        st.error('Please fill all the fields !')
    else:
        date = f'{d} 00:00:00 UTC'
        params = {"key":date, "pickup_datetime":date, "pickup_latitude":pick_lat,\
                    "pickup_longitude":pick_long, "dropoff_latitude":drop_lat, \
                        "dropoff_longitude":drop_long, "passenger_count":pass_cnt }

        # params = {
        #                 "dropoff_latitude":40.74383544921875,
        #                 "dropoff_longitude":-73.98143005371094,
        #                 "key":"2015-01-27 13:08:24.0000002",
        #                 "passenger_count":1,
        #                 "pickup_datetime":"2015-01-27 13:08:24 UTC",
        #                 "pickup_latitude":40.7638053894043,
        #                 "pickup_longitude":-73.97332000732422}
Пример #21
0
def diagnostico():
    st.info(
        "**ℹ    Esta aplicación bajo ningún punto de vista reemplaza la consulta con un profesional. Ante cualquier duda, no deje de consultar con su médico.**"
    )

    marcar = """<div class="container-fluid mb-3">
    <h2 style='font-family: Helvetica, Verdana, sans serif;font-size: 20px; border: 1px outset;border-radius: 10px 10px 10px 10px; text-align: center; color: white; background-color: black;'>Seleccione en caso que corresponda ✅</h2></div>
    """
    st.markdown(marcar, unsafe_allow_html=True)

    # Contacto estrecho
    if st.checkbox(
            "Contacto estrecho con caso confirmado de COVID-19 (dentro de los 14 días posteriores al contacto)",
            value=False):
        chk_contacto = 1
    else:
        chk_contacto = 0

    # Area de riesgo
    if st.checkbox(
            "Resida en Areas de riesgo determinadas por el gobierno(ej :AMBA, barrios populares o pueblos originarios)",
            value=False):
        chk_area = 1
    else:
        chk_area = 0

    # Personal de salud
    if st.checkbox("Personal de salud", value=False):
        chk_personal = 1
    else:
        chk_personal = 0
    sintomas = """<div class="container-fluid mb-3 justify-content-center">
    <h2 style='font-family: Helvetica, Verdana, sans serif;font-size: 20px; border: 1px outset;border-radius: 10px 10px 10px 10px; text-align: center; color: white; background-color: black;'>Seleccione sus síntomas 🌡</h2></div>
    """
    st.markdown("")
    st.markdown(sintomas, unsafe_allow_html=True)

    # Fiebre
    if st.checkbox("Fiebre (37.5° o más)", value=False):
        chk_fiebre = 1
    else:
        chk_fiebre = 0

    # Tos
    if st.checkbox("Tos", value=False):
        chk_tos = 1
    else:
        chk_tos = 0

    # Dolor de cabeza
    if st.checkbox("Dolor de cabeza", value=False):
        chk_dolor_cabeza = 1
    else:
        chk_dolor_cabeza = 0

    # Anosmia
    if st.checkbox("Pérdida del sentido del olfato o del gusto", value=False):
        chk_anosmia = 1
    else:
        chk_anosmia = 0

    # Odinofagia
    if st.checkbox("Odinofagia (Dolor de garganta)", value=False):
        chk_odinofagia = 1
    else:
        chk_odinofagia = 0

    # Dificultad Respiratoria
    if st.checkbox("Dificultad Respiratoria", value=False):
        chk_resp = 1
    else:
        chk_resp = 0

    # Diarrea
    if st.checkbox("Diarrea", value=False):
        chk_diarrea = 1
    else:
        chk_diarrea = 0

    # Vomitos
    if st.checkbox("Vomitos", value=False):
        chk_vomitos = 1
    else:
        chk_vomitos = 0

    #   Criterios

    if chk_anosmia + chk_area + chk_contacto + chk_dolor_cabeza + chk_fiebre + chk_odinofagia + chk_personal + chk_resp + chk_tos + chk_vomitos + chk_diarrea >= 2 and chk_anosmia + chk_area + chk_contacto + chk_dolor_cabeza + chk_fiebre + chk_odinofagia + chk_personal + chk_resp + chk_tos + chk_vomitos + chk_diarrea < 12:
        time.sleep(1)
        st.error(
            "☣ Usted presenta síntomas compatibles con la enfermedad COVID-19. Por favor consulte con su médico de inmediato."
        )

    if chk_anosmia + chk_area + chk_contacto + chk_dolor_cabeza + chk_fiebre + chk_odinofagia + chk_personal + chk_resp + chk_tos + chk_vomitos + chk_diarrea == 1:
        time.sleep(1)
        st.success(
            "😄 Usted no presenta síntomas compatibles compatibles con la enfermedad COVID-19."
        )
Пример #22
0
# Header/Subheader
st.header("This is a header")
st.subheader("This is a subheader")

# text
st.text("Hello Streamlit")

# Markdown
st.markdown("### This is markdown")

# Error/ Colorful text
st.success("Successful")
st.info("Information")
st.warning("This is a warning!")
st.error("This is an error!")
#st.exepiton("NameError('name three not defined')")
st.help(range)

st.write("Text with write")
st.write(range(10))

#images
from PIL import Image
img = Image.open("mlpic.jpg")
st.image(img, width=300, caption="Simple Image")

#videos.
vid_file = open("examplevid.mp4", "rb").read()
#vid_bytes = vid_file.read()
st.video(vid_file)
Пример #23
0
st.map(map_data)

st.write("Congratulations")
selection = st.checkbox("Cong")
if selection:
    st.success("Congrats!")

st.write("Warning")
selection = st.checkbox("Warn")
if selection:
    st.warning("Uh oh!")

st.write("Error")
selection = st.checkbox("Err")
if selection:
    st.error("No! Try again!")

options = st.selectbox("What is your major?", ["IT", "CS", "Cyber Security"])

st.write("You selected {}.".format(options))

options2 = st.sidebar.selectbox("What year are you in the program?",
                                ["", "1st", "2nd", "3rd", "4th", "5th", "6th"])

#latest_iteration = st.empty()

#bar = st.progress(0)

#for i in range(100):
#    latest_iteration.text(f'Iteration {i+1}')
#    bar.progress(i+1)
Пример #24
0
def main():
    grim = []
    grim_path = "grim_st.json"
    try:
        with open(grim_path) as json_file:
            grim = json.load(json_file)
    except:
        st.error("No grim_st.json file")
        return

    print(grim["name"])
    st.title("Grimoire: " + grim["name"])
    st.markdown("## " + grim["value"])
    spell_tomb = {}

    if "isTest" in grim:
        hide_streamlit_style = """
            <style>
            #MainMenu {visibility: hidden;}
            footer {visibility: hidden;}
            </style>
            """
        st.markdown(hide_streamlit_style, unsafe_allow_html=True)
        st.markdown("### Using Sample Data")
        data = "sample_data/iris.csv"
        mana = pd.read_csv(data)
        #st.write(mana)
    else:
        mana_choices = [
            "CSV",
            "JSON",
            "Free text",
            "Image",
            "Database",
            "Data Files",
            "None",
        ]

        mana_choice = st.selectbox("Select data format", mana_choices)
        try:
            mana = set_mana(mana_choice)
        except Exception as e:
            show_error = st.checkbox("Show Error details?")

            if show_error:
                st.write(e)
            st.error("Invalid input")
            return

        # st.markdown('### Before you can cast your spells, upload your data')
        # data = st.file_uploader("Choose a CSV file", type="csv")
    spell_count = 1

    st.sidebar.title("Grimoire: " + grim["name"])
    image = Image.open("assets/spellbook.png")
    st.sidebar.image(image, use_column_width=True, format="png")
    if mana is not None:

        st.write(mana)

        # mana = pd.read_csv(data)
        if st.sidebar.checkbox("Add markdown at start?",
                               key="add_markdown-start-" + str(spell_count)):
            markdown_text = st.sidebar.text_area("Enter Markdown Text",
                                                 key="markdown-start-text-" +
                                                 str(spell_count))
            st.markdown(markdown_text)

        for spell in grim["spells"]:
            spell_name = spell["spell_name"]
            spell_type = spell["spell_type"]
            spell_info = spell["spell_info"]
            spell_inputs = spell["spell_inputs"]
            spell_output = spell["spell_output"]
            takes_mana = spell["takes_mana"]
            for spell_input in spell_inputs.keys():
                # only add input if not in tomb
                if spell_input not in spell_tomb:
                    spell_tomb[spell_input] = spell_inputs[spell_input]
                else:
                    # spell input is in tomb, replace value
                    spell_inputs[spell_input] = spell_tomb[spell_input]

            st.markdown("## Casting spell: " + spell_type + " " + spell_name)
            st.markdown("### " + spell_info)

            # first spell must take mana as input
            try:
                if takes_mana:
                    # would have to do a check here? or pass in mana
                    spell_tomb[spell_output], mana = REGISTERED_SPELLS[
                        spell_name](mana)
                else:
                    spell_tomb[spell_output], mana = REGISTERED_SPELLS[
                        spell_name](spell_inputs)

                if st.sidebar.checkbox(
                        "Add markdown after spell " + spell_name + "?",
                        key="add_markdown-end-" + str(spell_count),
                ):
                    markdown_text = st.sidebar.text_area(
                        "Enter Markdown Text",
                        key="markdown-end-text-" + str(spell_count),
                    )
                    st.markdown(markdown_text)
            except Exception as e:
                show_error = st.checkbox("Show Error details?",
                                         key="spell_cast_errors")
                if show_error:
                    st.write(e)
                st.error("Invalid input")
                return
            spell_count += 1
Пример #25
0
def counterexamples_page(state):
    logger.info({"message": "Loading counterexamples page."})
    st.title("Counterexamples")

    st.markdown("""
    Counterexamples in Watson Assistant are used when we want to avoid answer incorrectly for some user inputs.

    In IBM Cloud it isn't possible to manage counterexamples, you can only add new counerexamples in "Try out".

    We have created this page for you see and delete counterexamples as needed.
    """)
    from src.connectors.watson_assistant import WatsonAssistant
    wa = WatsonAssistant(apikey=state.watson_args["apikey"],
                         service_endpoint=state.watson_args["endpoint"],
                         default_skill_id=state.watson_args["skill_id"])

    # Add new counter example
    counter_example = st.text_input("Add counterexample")

    if st.button("Insert"):
        response = wa.add_counterexamples(counter_example)
        if response["success"]:
            st.success("Counterexample added.")
            time.sleep(state.alert_timeout)
        else:
            logger.error({"message": "Failed to add the counterexample."})
            st.error("Failed to add the counterexample.")
            time.sleep(state.alert_timeout)

    # Getting counter examples
    counter_examples = wa.get_counterexamples()
    counter_examples = counter_examples["counterexamples"]

    if len(counter_examples) > 0:
        col1, col2 = st.columns(2)
        col1.header("Counterexamples")
        col2.header("Actions")

        for i in range(len(counter_examples)):
            ckey = "counter_examples_{}".format(i)
            col1.write(counter_examples[i])
            cbutton = col2.button("Delete", key=ckey)
            if cbutton:
                pos = int(ckey.split("_")[-1])
                response = wa.delete_counterexamples(counter_examples[pos])
                if response["success"]:
                    st.success("Counterexample deleted.")
                    time.sleep(state.alert_timeout)
                else:
                    logger.error(
                        {"message": "Failed to delete counterexample."})
                    st.error("Failed to delete counterexample.")
                    time.sleep(state.alert_timeout)

                raise st.script_runner.RerunException(
                    st.script_request_queue.RerunData(None))
    else:
        st.markdown(
            "We have no counterexamples in this Watson Assistant skill.")

    state.sync()
Пример #26
0
def set_mana(mana_choice):

    if mana_choice == "CSV":
        st.write("### Select how you will load the CSV")
        csv_choices = ["Upload", "URL", "Free text"]
        csv_choice = st.selectbox("Select csv loading type", csv_choices)
        if csv_choice == "Upload":
            data = st.file_uploader("Choose a CSV file", type="csv")
        if csv_choice == "URL":
            data = st.text_input("URL:", "")
        if csv_choice == "Free text":
            raw_data = st.text_area("Enter Data", "")
            data = None
            if raw_data is not "":
                data = StringIO(raw_data)

        if data is not None:
            if data is not "":
                mana = load_mana("csv", data)
                return mana

    elif mana_choice == "JSON":
        st.write("### Select how you will load the JSON")
        json_choices = ["Upload", "URL", "Free text"]
        json_choice = st.selectbox("Select json loading type", json_choices)
        if json_choice == "Upload":
            data = st.file_uploader("Choose a JSON file", type="json")
        if json_choice == "URL":
            data = st.text_input("URL:", "")
        if json_choice == "Free text":
            raw_data = st.text_area("Enter Data")
            data = None
            if raw_data is not "":
                data = StringIO(raw_data)

        if data is not None:
            if data is not "":
                mana = load_mana("json", data)
                return mana
    elif mana_choice == "Image":
        st.write("### Select how you will load the Image")
        image_choices = ["Upload", "URL"]
        image_choice = st.selectbox("Select json loading type", image_choices)
        if image_choice == "Upload":
            data = st.file_uploader("Choose an Image file", type="png,jpg")
        if image_choice == "URL":
            url = st.text_input("URL:", "")
            data = None
            if url is not "":
                response = requests.get(url)
                data = BytesIO(response.content)
        if data is not None:
            if data is not "":
                mana = load_image(data)
                st.image(mana, use_column_width=True)
                return mana
    elif mana_choice == "Free text":
        st.write("Free text")
        mana = st.text_area("Enter Data")
        return mana
    elif mana_choice == "Database":
        st.write("Database")
        st.error("todo")
    elif mana_choice == "Data Files":
        return "Data Files"
    elif mana_choice == "None":
        return "None"
    else:
        st.balloons()
        st.error("Congrats you broke the system")

    return
Пример #27
0
    def show_remove(self):
        tables_for_remove = self.tables.copy()
        try:
            tables_for_remove.remove("Imports")
            tables_for_remove.remove("Transactions")
        except ValueError:
            pass

        with st.beta_container():
            self.current_option = st.selectbox("Select table to remove: ", tables_for_remove)

            if self.current_option == "Customer":
                st.info("""
                    Input id or name to search for customer to remove from the database.
                    If there is no input, all entries be shown.
                """)
                choice = st.radio("Search by id/name: ", options=['id', 'name'])

                if choice == "id":
                    customer_id = st.number_input("Input customer id: ", step=1, value=0, min_value=0,
                                                  max_value=customer.max_id(self.connection) or 0)
                    data = customer.search_by_id(self.connection, customer_id)
                elif choice == "name":
                    customer_name = st.text_input("Input customer name: ", value="")
                    data = customer.search_by_name(self.connection, customer_name)

                df = pd.DataFrame.from_records(data, columns=self.customer_columns)[:1000]

                with st.beta_expander("Show all customers"):
                    st.dataframe(df)

                with st.beta_expander("Remove customer(s)", expanded=True):
                    if choice == "id":
                        data = customer.search_by_id(self.connection, customer_id)
                    elif choice == "name":
                        selected_ids = st.multiselect("Select customer id(s): ", df["customerID"])
                        data = customer.search_by_name(self.connection, customer_name)

                    if len(df["customerID"]) == 1:
                        selected_ids = df["customerID"].values

                    try:
                        df = pd.concat([pd.DataFrame.from_records(data, columns=self.customer_columns).loc[
                                            df["customerID"] == i] for i in selected_ids], ignore_index=True)
                    except ValueError:
                        pass
                    st.dataframe(df)

                    if st.button("Remove customer"):
                        for Cid in selected_ids:
                            if transactions.search_by_customer_id(self.connection, int(Cid)):
                                st.error(f"""
                                    Customer {Cid} can't be removed. They have already made a transaction.
                                """)
                            else:
                                removed = customer.delete_by_id(self.connection, int(Cid))
                                st.experimental_rerun()

            elif self.current_option == "ItemCategory":
                st.info("""
                    Input id or name to search for item category to remove from the database.
                    If there is no input, all entries be shown.
                """)
                choice = st.radio("Search by id/name: ", options=['id', 'name'])

                if choice == "id":
                    category_id = st.number_input("Input category id: ", step=1, value=0, min_value=0,
                                                  max_value=item_category.max_id(self.connection) or 0)
                    data = item_category.search_by_id(self.connection, category_id)
                elif choice == "name":
                    category_name = st.text_input("Input category name: ", value="")
                    data = item_category.search_by_name(self.connection, category_name)

                df = pd.DataFrame.from_records(data, columns=self.category_columns)[:1000]

                with st.beta_expander("Show all item categories"):
                    st.dataframe(df)

                with st.beta_expander("Remove item category(s)", expanded=True):
                    if choice == "id":
                        data = item_category.search_by_id(self.connection, category_id)
                    elif choice == "name":
                        selected_ids = st.multiselect("Select category id(s): ", df["categoryID"])
                        data = item_category.search_by_name(self.connection, category_name)

                    if len(df["categoryID"]) == 1:
                        selected_ids = df["categoryID"].values

                    try:
                        df = pd.concat([pd.DataFrame.from_records(data, columns=self.category_columns).loc[
                                            df["categoryID"] == i] for i in selected_ids], ignore_index=True)
                    except ValueError:
                        pass
                    st.dataframe(df)

                    if st.button("Remove item category"):
                        for ICid in selected_ids:
                            if item.search_by_category_id(self.connection, int(ICid)):
                                st.error(f"""
                                    Item category {ICid} can't be removed. There is at least an item assigned to it.
                                """)
                            else:
                                removed = item_category.delete_by_id(self.connection, int(ICid))
                                st.experimental_rerun()

            elif self.current_option == "Buyer":
                pass

            elif self.current_option == "Shop":
                st.info("""
                    Input id or name to search for shop to remove from the database.
                    If there is no input, all entries be shown.
                """)
                choice = st.radio("Search by id/name: ", options=['id', 'name'])

                if choice == "id":
                    shop_id = st.number_input("Input shop id: ", step=1, value=0, min_value=0,
                                              max_value=shop.max_id(self.connection) or 0)
                    data = shop.search_by_id(self.connection, shop_id)
                elif choice == "name":
                    shop_name = st.text_input("Input shop name: ", value="")
                    data = shop.search_by_name(self.connection, shop_name)

                df = pd.DataFrame.from_records(data, columns=self.shop_columns)[:1000]

                with st.beta_expander("Show all shops"):
                    st.dataframe(df)

                with st.beta_expander("Remove shop(s)"):
                    if choice == "id":
                        data = shop.search_by_id(self.connection, shop_id)
                    elif choice == "name":
                        selected_ids = st.multiselect("Select shop id(s): ", df["shopID"])
                        data = shop.search_by_name(self.connection, shop_name)

                    if len(df["shopID"]) == 1:
                        selected_ids = df["shopID"].values

                    try:
                        df = pd.concat([pd.DataFrame.from_records(data, columns=self.shop_columns).loc[
                                            df["shopID"] == i] for i in selected_ids], ignore_index=True)
                    except ValueError:
                        pass
                    st.dataframe(df)

                    if st.button("Remove shop"):
                        for Sid in selected_ids:
                            if item.search_by_shop_id(self.connection, int(Sid)):
                                st.error(f"""
                                    Shop {Sid} can't be removed. There is at least an item assigned to it.
                            """)
                            else:
                                removed = shop.delete_by_id(self.connection, int(Sid))
                                st.experimental_rerun()

            elif self.current_option == "Item":
                st.info("""
                    Input id or name to search for item to remove from the database.
                    If there is no input, all entries be shown.
                """)
                choice = st.radio("Search by id/name/category/shop: ", options=['id', 'name', 'category', 'shop'])

                if choice == "id":
                    item_id = st.number_input("Input item id: ", step=1, value=0, min_value=0,
                                              max_value=item.max_id(self.connection) or 0)
                    data = item.search_by_id(self.connection, item_id)
                elif choice == "name":
                    item_name = st.text_input("Input item name (* to search all): ", value="")
                    data = item.search_by_name(self.connection, item_name)
                elif choice == "category":
                    category_id = st.number_input("Input category id: ", step=1, value=0, min_value=0,
                                                  max_value=item_category.max_id(self.connection) or 0)
                    data = item.search_by_category_id(self.connection, category_id)
                elif choice == "shop":
                    shop_id = st.number_input("Input shop id: ", step=1, value=0, min_value=0,
                                              max_value=shop.max_id(self.connection) or 0)
                    data = item.search_by_shop_id(self.connection, shop_id)

                df = pd.DataFrame.from_records(data, columns=self.customer_columns)[:1000]

                with st.beta_expander("Show all items"):
                    st.dataframe(df)

                with st.beta_expander("Remove item(s)", expanded=True):
                    if choice == "id":
                        data = item.search_by_id(self.connection, item_id)
                    elif choice == "name":
                        selected_ids = st.multiselect("Select item id(s): ", df["itemID"])
                        data = item.search_by_name(self.connection, item_name)

                    if len(df["itemID"]) == 1:
                        selected_ids = df["itemID"].values

                    try:
                        df = pd.concat([pd.DataFrame.from_records(data, columns=self.customer_columns).loc[
                                            df["itemID"] == i] for i in selected_ids], ignore_index=True)
                    except ValueError:
                        pass
                    st.dataframe(df)

                    if st.button("Remove item"):
                        for Iid in selected_ids:
                            removed = item.delete_by_id(self.connection, int(Iid))
                            st.experimental_rerun()
Пример #28
0
def validation():
    banner = "<img src='data:image/png;base64,{}' class='img-fluid'>".format(
        img_to_bytes("./static/banner-validation.png"))
    st.markdown(banner, unsafe_allow_html=True)
    st.markdown('')
    st.markdown('')
    st.markdown('Implementation of Sequential Probability Ratio Test (SPRT)')

    st.markdown('''To validate with a statistical framework, the hypothesis of
                whether the MTBF of the asset is as specified. It is a
                modification of the use case as known in reliability
                engineering literature called Reliability Demonstration Test,
                covered in IEC 61124 standard.''')
    st.markdown('''The test can have a second interpretation, where we may test
                one MTBF value against another. Please input `Specified MTBF`
                as the larger MTBF, and the `Discrimination Ratio` as the ratio
                of the larger MTBF to the smaller MTBF. The interpretation of
                `alpha` and `beta` thus changes to the risk of wrongly
                accepting the lower MTBF and the higher MTBF, respectively.''')

    # Sidebar section
    st.sidebar.header('Parameters')
    m0 = st.sidebar.number_input('Specified MTBF', 1000, 100000, 20000)
    d = st.sidebar.number_input('Discrimination Ratio', 1.01, 5.0, 1.5, 0.01)
    alpha = st.sidebar.slider("Producer's Risk (alpha)", 0.01, 0.3, 0.05, 0.01)
    beta = st.sidebar.slider("Consumer's Risk (beta)", 0.01, 0.3, 0.05, 0.01)
    st.sidebar.header('System')
    noc = st.sidebar.number_input('Number of Components Tested', 1, 100, 10)
    oh = st.sidebar.number_input('Operational Hours (Yearly)', 1, 24 * 366,
                                 5000)

    # Main page
    st.header('Create Test Plan')
    st.markdown('''Change the test plan parameters on the sidebar.
                Click on the `Create` button if you want to create a test
                plan with the current parameters''')
    text = st.text_input('Test Plan ID', 'TestA')
    params = {
        'ID': text,
        'Alpha': alpha,
        'Beta': beta,
        'Disc. Ratio': d,
        'Specified MTBF': m0
    }
    pdf = pd.DataFrame(params, index=['Value'])
    st.write(
        '''*The test preview below will be updated whenever the parameter
             is changed*''', pdf)

    # Manage input states
    @st.cache(allow_output_mutation=True)
    def get_state():
        return []

    state = get_state()

    create = st.button('Create')
    if create:
        if test_inputs(state, params) == 'iderror':
            st.error('ID exists. Please choose another ID')
        elif test_inputs(state, params) == 'paramerror':
            st.error('Test plan with these parameters already exists')
        else:
            state.append(list(params.values()))
            st.info('Create successful')

    st.subheader('Current Test Plans')
    st.write(pd.DataFrame(state, columns=params.keys()))

    st.header('Test')
    st.markdown('Select one of the test IDs')
    tid = st.selectbox('Test ID', [x[0] for x in state])
    if tid:
        st.subheader('Test Properties')
        plot_properties(state, tid, noc, oh)

    st.subheader('Upload')
    st.markdown('''Upload test data with format as specified in the Fitter
                page. In the page, you can also generate and download the toy
                data. You can upload the toy data here.''')
    file_csv = st.file_uploader('''Upload Test Data in CSV format''',
                                type=['csv'])

    # Once uploaded and test plan chosen
    sel = st.selectbox('Use Test Plan?', ['No'] + [x[0] for x in state])
    st.subheader('Results')
    if file_csv:
        encoded = file_csv.read().encode('utf8')
        df = pd.read_csv(io.BytesIO(encoded))
        if sel != 'No':
            alpha, beta, d, m0 = [x[1:] for x in state if x[0] == sel][0]
        correction_factor = (d + 1) / (2 * d)
        ub = (1 - beta) / alpha * correction_factor
        lb = beta / (1 - alpha)
        plot_sequential_test(df, (lb, ub, d, m0, oh, noc))
Пример #29
0
left_column_1, right_column_1 = st.beta_columns(2)
with left_column_1:
    numdays = st.slider(
        'Select next how many days you want to search for slots!', 1, 30, 5)

with right_column_1:
    pincode = int(st.number_input('Enter your PinCode', value=110001))

base = datetime.datetime.today()
date_list = [base + datetime.timedelta(days=x) for x in range(numdays)]
date_str = [x.strftime("%d-%m-%Y") for x in date_list]

st.header("Results")
if len(str(pincode)) < 6 or len(str(pincode)) > 6:
    st.error("Please enter a valid 6 digit Pincode.")
else:
    ua = UserAgent()
    header = {'User-Agent': str(ua.chrome)}
    for INP_DATE in date_str:
        URL = "https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/calendarByPin?pincode={}&date={}".format(
            pincode, INP_DATE)
        response = requests.get(URL, headers=header)
        if response.ok:
            resp_json = response.json()
            st.subheader("Date: {}".format(INP_DATE))
            if resp_json["centers"]:
                count = 0
                itr = 0
                for center in resp_json["centers"]:
                    for session in center["sessions"]:
Пример #30
0
        z3 = st.sidebar.number_input(header[3],  0, 10000, 316)
        z4 = st.sidebar.number_input(header[4],  0, 10000, 124)
        z5 = st.sidebar.number_input(header[5],  0, 10000, 105)
        z6 = st.sidebar.number_input(header[6],  0, 10000, 36)
        z7 = st.sidebar.number_input(header[7],  0, 10000, 8)
        z8 = st.sidebar.number_input(header[8],  0, 10000, 9)
        totaal_ziek = z0 +z1 +z2 +z3 +z4 +z5 +z6 +z7 +z8
        st.sidebar.write(f"Totaal {totaal_ziek}")
        ziek = [z0,z1,z2,z3,z4,z5,z6,z7,z8]
        totaal = 100

        if totaal == 100:
            calculate_aantallen(ziek, header, h_, ic_opn,ifr_, long_covid)

        else:
            st.error(f"Zorg ervoor dat de fracties in totaal 100 zijn in plaats van {totaal}")

    st.subheader ("Kansenmatrix")
    kansenmatrix = pd.DataFrame(
    {'age': header,
     'ziekenhuisopn yorick': h_yorick,
     'ziekenhuisopn rene': h_rene,
     'ziekenhuisopn rivm': h_rivm,
     'IC opname': ic_opn,
     'IFR':ifr_
    })

    st.write ("Ziekenhuisopname kans is berekend door Yorick Bleijenberg adhv Sanquin, mijzelf (zie broncode) en RIVM data.")
    st.write(" De categorieen 0-9 en 10-19 zijn gelijk getrokken 80-89 en 90+ zijn gemiddeld")

    st.write (kansenmatrix)