Beispiel #1
0
def write():

    st.header("The Rent in Santa Clara County")
    st.subheader("**Introduction**")
    #income1,immi1=st.beta_columns(2)
    st.markdown("Economy Part")
    income = """https://datausa.io/profile/geo/santa-clara-county-ca/economy/income?viz=true"""
    components.iframe(income, width=1000, height=500, scrolling=True)
    #income1 = components.iframe(income,width=300,height=120,scrolling=True)
    st.markdown(
        "Here we can see the foreign population has a huge percent in Santa Clara County compared to the other places in US"
    )
    immi = """https://datausa.io/profile/geo/santa-clara-county-ca/demographics/foreign_born?viz=true"""
    components.iframe(immi, width=1000, height=500, scrolling=True)
    #immi1 = components.iframe(immi,width=300,height=120,scrolling=True)
    #income1,immi1=st.beta_columns(2)
    propertyvalue = """https://datausa.io/profile/geo/santa-clara-county-ca/housing/property_value?viz=true"""
    components.iframe(propertyvalue, width=1000, height=2500, scrolling=True)
    pv = "https://datausa.io/profile/geo/santa-clara-county-ca/housing/household_income?viz=true"
    components.iframe(pv, 1000, 500, True)
    rentvsown = "https://datausa.io/profile/geo/santa-clara-county-ca/housing/rent_own?viz=true"
    components.iframe(rentvsown, width=1000, height=500, scrolling=True)

    #html_temp = """<div class='tableauPlaceholder' id='viz1620738274887' style='position: relative'><noscript><a href='https:&#47;&#47;www.linkedin.com&#47;in&#47;obyali&#47;'><img alt='Santa Clara County Home Market@Oby Ali Real Estate Services 415-608-1859 ' src='https:&#47;&#47;public.tableau.com&#47;static&#47;images&#47;Sa&#47;SantaClaraCountyMapPrices&#47;Sheet2&#47;1_rss.png' style='border: none' /></a></noscript><object class='tableauViz'  style='display:none;'><param name='host_url' value='https%3A%2F%2Fpublic.tableau.com%2F' /> <param name='embed_code_version' value='3' /> <param name='site_root' value='' /><param name='name' value='SantaClaraCountyMapPrices&#47;Sheet2' /><param name='tabs' value='no' /><param name='toolbar' value='yes' /><param name='static_image' value='https:&#47;&#47;public.tableau.com&#47;static&#47;images&#47;Sa&#47;SantaClaraCountyMapPrices&#47;Sheet2&#47;1.png' /> <param name='animate_transition' value='yes' /><param name='display_static_image' value='yes' /><param name='display_spinner' value='yes' /><param name='display_overlay' value='yes' /><param name='display_count' value='yes' /><param name='language' value='zh-Hans' /></object></div>                <script type='text/javascript'>                    var divElement = document.getElementById('viz1620738274887');                    var vizElement = divElement.getElementsByTagName('object')[0];                    vizElement.style.width='100%';vizElement.style.height=(divElement.offsetWidth*0.75)+'px';                    var scriptElement = document.createElement('script');                    scriptElement.src = 'https://public.tableau.com/javascripts/api/viz_v1.js';                    vizElement.parentNode.insertBefore(scriptElement, vizElement);                </script>"""
    #components.html(html_temp,1000,500,scrolling=True)
    temp2 = """<div class='tableauPlaceholder' id='viz1620738379905' style='position: relative'><noscript><a href='#'><img alt='Santa Clara County ' src='https:&#47;&#47;public.tableau.com&#47;static&#47;images&#47;BT&#47;BTM39PF2D&#47;1_rss.png' style='border: none' /></a></noscript><object class='tableauViz'  style='display:none;'><param name='host_url' value='https%3A%2F%2Fpublic.tableau.com%2F' /> <param name='embed_code_version' value='3' /> <param name='path' value='shared&#47;BTM39PF2D' /> <param name='toolbar' value='yes' /><param name='static_image' value='https:&#47;&#47;public.tableau.com&#47;static&#47;images&#47;BT&#47;BTM39PF2D&#47;1.png' /> <param name='animate_transition' value='yes' /><param name='display_static_image' value='yes' /><param name='display_spinner' value='yes' /><param name='display_overlay' value='yes' /><param name='display_count' value='yes' /><param name='language' value='zh-Hans' /></object></div>                <script type='text/javascript'>                    var divElement = document.getElementById('viz1620738379905');                    var vizElement = divElement.getElementsByTagName('object')[0];                    vizElement.style.width='1366px';vizElement.style.height='795px';                    var scriptElement = document.createElement('script');                    scriptElement.src = 'https://public.tableau.com/javascripts/api/viz_v1.js';                    vizElement.parentNode.insertBefore(scriptElement, vizElement);                </script>"""
    components.html(temp2, width=1000, height=500, scrolling=True)
    temp3 = "<div class='tableauPlaceholder' id='viz1620858690143' style='position: relative'><noscript><a href='https:&#47;&#47;www.linkedin.com&#47;in&#47;obyali&#47;'><img alt='Santa Clara County Home Market@Oby Ali Real Estate Services 415-608-1859 ' src='https:&#47;&#47;public.tableau.com&#47;static&#47;images&#47;Sa&#47;SantaClaraCountyMapPrices&#47;Sheet2&#47;1_rss.png' style='border: none' /></a></noscript><object class='tableauViz'  style='display:none;'><param name='host_url' value='https%3A%2F%2Fpublic.tableau.com%2F' /> <param name='embed_code_version' value='3' /> <param name='site_root' value='' /><param name='name' value='SantaClaraCountyMapPrices&#47;Sheet2' /><param name='tabs' value='no' /><param name='toolbar' value='yes' /><param name='static_image' value='https:&#47;&#47;public.tableau.com&#47;static&#47;images&#47;Sa&#47;SantaClaraCountyMapPrices&#47;Sheet2&#47;1.png' /> <param name='animate_transition' value='yes' /><param name='display_static_image' value='yes' /><param name='display_spinner' value='yes' /><param name='display_overlay' value='yes' /><param name='display_count' value='yes' /><param name='language' value='zh-Hans' /></object></div>                <script type='text/javascript'>                    var divElement = document.getElementById('viz1620858690143');                    var vizElement = divElement.getElementsByTagName('object')[0];                    vizElement.style.width='100%';vizElement.style.height=(divElement.offsetWidth*0.75)+'px';                    var scriptElement = document.createElement('script');                    scriptElement.src = 'https://public.tableau.com/javascripts/api/viz_v1.js';                    vizElement.parentNode.insertBefore(scriptElement, vizElement);                </script>"
    components.html(temp3, 1000, 500, True)
    temp4 = "<div class='tableauPlaceholder' id='viz1620858756097' style='position: relative'><noscript><a href='#'><img alt='Airbnb Listing Analysis 2008 -2018 Santa Clara County Dataset from Inside Airbnb ' src='https:&#47;&#47;public.tableau.com&#47;static&#47;images&#47;Z4&#47;Z43SFQNQ6&#47;1_rss.png' style='border: none' /></a></noscript><object class='tableauViz'  style='display:none;'><param name='host_url' value='https%3A%2F%2Fpublic.tableau.com%2F' /> <param name='embed_code_version' value='3' /> <param name='path' value='shared&#47;Z43SFQNQ6' /> <param name='toolbar' value='yes' /><param name='static_image' value='https:&#47;&#47;public.tableau.com&#47;static&#47;images&#47;Z4&#47;Z43SFQNQ6&#47;1.png' /> <param name='animate_transition' value='yes' /><param name='display_static_image' value='yes' /><param name='display_spinner' value='yes' /><param name='display_overlay' value='yes' /><param name='display_count' value='yes' /><param name='language' value='zh-Hans' /></object></div>                <script type='text/javascript'>                    var divElement = document.getElementById('viz1620858756097');                    var vizElement = divElement.getElementsByTagName('object')[0];                    if ( divElement.offsetWidth > 800 ) { vizElement.style.width='1000px';vizElement.style.height='827px';} else if ( divElement.offsetWidth > 500 ) { vizElement.style.width='1000px';vizElement.style.height='827px';} else { vizElement.style.width='100%';vizElement.style.height='1727px';}                     var scriptElement = document.createElement('script');                    scriptElement.src = 'https://public.tableau.com/javascripts/api/viz_v1.js';                    vizElement.parentNode.insertBefore(scriptElement, vizElement);                </script>"
    components.html(temp4, 1000, 500, True)
Beispiel #2
0
def app():
    st.write("## Maps and Data")

    st.write('''
        The data in these maps represents the factors affecting the severity of covid-19 in different counties in the united states.
        ''')

    # st.subheader('Overlay Of all Factors Considered (Severity Index)')
    # severity_index = open("severity_index.html", 'r', encoding='utf-8')
    # severity_index_code = severity_index.read()
    # components.html(severity_index_code, height=550)

    st.subheader('Number of Cases Per County')
    numCases = open("CovidCount.html", 'r', encoding='utf-8')
    numCases_code = numCases.read()
    components.html(numCases_code, height=550)

    st.subheader('Rate of Change of Cases Per County')
    firstDeriv = open("firstDerivative.html", 'r', encoding='utf-8')
    firstDeriv_code = firstDeriv.read()
    components.html(firstDeriv_code, height=550)

    # st.subheader('Rate of Change of Rate of Change of Cases Per County')
    # secondDeriv = open("secondDerivative.html", 'r', encoding='utf-8')
    # secondDeriv_code = secondDeriv.read()
    # components.html(secondDeriv_code, height=550)

    st.subheader('Elderly People Per County')
    elderlyCount = open("ElderlyCount.html", 'r', encoding='utf-8')
    elderlyCount_code = elderlyCount.read()
    components.html(elderlyCount_code, height=550)

    # ICU Beds
    components.iframe("https://datawrapper.dwcdn.net/OvQv5/1/", height=550)
Beispiel #3
0
def htmlcss():
    #Libs
    import streamlit as st
    import streamlit.components.v1 as components

    st.title('Inserir HTML/CSS')

    st.markdown("<h1 style='color:#F00;'>H1 com cor RED</h1>",
                unsafe_allow_html=True)
    st.markdown("<h2 style='color:#0F0;'>H2 com cor GREEN</h2>",
                unsafe_allow_html=True)
    st.markdown("<h3 style='color:#00F;'>H3 com cor BLUE</h1>",
                unsafe_allow_html=True)
    st.markdown(
        "<h1 style='color:#F00; font-family:arial'>H1 com cor RED e Arial</h1>",
        unsafe_allow_html=True)

    st.title('Inserir Iframe')
    components.iframe("https://tecnothink.com.br", height=600)

    st.title('HTML/CSS Puro')
    components.html(
        """
            <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
            <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
            <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
            <div id="accordion">
            <div class="card">
                <div class="card-header" id="headingOne">
                    <h5 class="mb-0">
                        <button class="btn btn-link" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
                        Item #1
                        </button>
                    </h5>
                </div>
                <div id="collapseOne" class="collapse show" aria-labelledby="headingOne" data-parent="#accordion">
                    <div class="card-body">
                        Item #1 Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
                    </div>
                </div>
            </div>
            <div class="card">
                <div class="card-header" id="headingTwo">
                    <h5 class="mb-0">
                        <button class="btn btn-link collapsed" data-toggle="collapse" data-target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo">
                        Item #2
                        </button>
                    </h5>
                </div>
                <div id="collapseTwo" class="collapse" aria-labelledby="headingTwo" data-parent="#accordion">
                    <div class="card-body">
                        Item #2 Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
                    </div>
                </div>
            </div>
            </div>
        """,
        height=400,
    )
Beispiel #4
0
def gca_page_2():
    st.title("GOOGLE CALENDARS ANALYTICS PAGE 2")
    st.write(f'## 2 GOOGLE CALENDAR SPECIFIC ANALYSIS (1 CALENDAR)')
    st.sidebar.write(f'#### 2 GOOGLE CALENDAR SPECIFIC ANALYSIS (1 CALENDAR)')

    input_calendar_name = st.sidebar.selectbox('2 SELECT CALENDAR:',
                                               mf.list_calendar_names)

    input_calendar_id = [
        x["id"] for x in mf.list_calendar
        if x["summary"] == input_calendar_name
    ][0]

    input_dates_analyze = st.sidebar.date_input(
        "2_b SELECT RANGE OF DATES TO ANALYZE",
        [datetime.date(2019, 1, 1),
         datetime.date.today()],
        key="spe_di")

    input_calendar_specific_type = st.sidebar.selectbox(
        '2_b SELECT EVENTS TYPE:', ["HOURS EVENTS", "DAYS EVENTS"],
        key="spe_sb")

    # Visualize events of selected calendar
    input_calendar_events = gl.retrieve_calendar_events_by_id(
        input_calendar_id)
    if len(input_calendar_events) == 0:
        st.write("No values in this calendar.")
    else:
        #TODO Filter before dataframe
        # df_events = filter_by_dates(input_calendar_events, input_dates_analyze, input_calendar_specific_type)
        df_events = pd.DataFrame(input_calendar_events)

        st.write(
            f'### **2_a_I** List of events in "{input_calendar_name}" calendar'
        )
        st.dataframe(df_events)

        st.write(
            f'### **2_a_II** "{input_calendar_name}" calendar visualization')
        input_calendar_id_number = urllib.parse.quote(input_calendar_id)
        components.iframe(
            f"https://calendar.google.com/calendar/embed?src={input_calendar_id_number}&ctz=Europe%2FMadrid",
            width=1200,
            height=800,
            scrolling=True)

        if input_calendar_specific_type == "HOURS EVENTS":
            mf.specific_analysis(df_events, input_calendar_events,
                                 input_calendar_name, "dateTime",
                                 "%Y-%m-%dT%H:%M:%S%z", "hours",
                                 input_dates_analyze)

        elif input_calendar_specific_type == "DAYS EVENTS":
            mf.specific_analysis(df_events, input_calendar_events,
                                 input_calendar_name, "date", "%Y-%m-%d",
                                 "days", input_dates_analyze)
    st.sidebar.write(f"---")
    st.write(f"---")
Beispiel #5
0
def main():
    menu = ['Pandas-Profiling', 'SweetViz', 'D-tale', 'About']
    option = st.selectbox("Select Tool for Viz", menu)

    if option == 'Pandas-Profiling':
        st.header("Pandas-Profiling")
        data_file = st.file_uploader("Upload_csv", type=['csv'])
        if data_file is not None:
            load_csv = pd.read_csv(data_file)
            st.write(load_csv.head())
            st.success("Successfully uploaded!")
            if st.button('Generate Report'):
                report = ProfileReport(load_csv,
                                       title="CSV Profiling Report",
                                       explorative=True)
                st.write('---')
                st.header('**Pandas Profiling Report**')
                st_profile_report(report)

    elif option == 'SweetViz':
        st.header("SweetViz")
        data_file = st.file_uploader("Upload_csv", type=['csv'])
        st.success("Successfully uploaded!")
        if data_file is not None:
            load_csv = pd.read_csv(data_file)
            st.write(load_csv)
            st.write('---')
            st.header('**SweetViz Profiling Report**')
            if st.button('Generate Report'):
                report = sv.analyze(load_csv)
                report.show_html()
                display_sweetviz("SWEETVIZ_REPORT.html")

    elif option == 'D-tale':
        st.header('D-tale')
        data_file = st.file_uploader("Upload_csv", type=['csv'])
        st.success("Successfully uploaded!")
        if data_file is not None:
            load_csv = pd.read_csv(data_file)
            st.write(load_csv)
            st.write('---')
            st.header('**D-Tale Profiling Report**')
            if st.button('Generate Report'):
                dtale.show(load_csv)
                components.iframe('http://dell-virlgti:40000/dtale/main/1',
                                  width=1500,
                                  height=800,
                                  scrolling=True)
                # st.markdown(html, unsafe_allow_html=True)

    elif menu == 'About':
        st.subheader(
            "Simple tool for better and quick visualization and EDA!!")
        st.write()
        st.write(
            "check out this [link](https://share.streamlit.io/mesmith027/streamlit_webapps/main/MC_pi/streamlit_app.py)"
        )
Beispiel #6
0
    def test_iframe(self):
        """Test components.iframe"""
        components.iframe("http://not.a.url", width=200, scrolling=True)

        el = self.get_delta_from_queue().new_element
        self.assertEqual(el.iframe.src, "http://not.a.url")
        self.assertEqual(el.iframe.srcdoc, "")
        self.assertEqual(el.iframe.width, 200)
        self.assertTrue(el.iframe.has_width)
        self.assertTrue(el.iframe.scrolling)
def main():
    is_authenticated = check_token(session_state.token)
    if not is_authenticated:
        messageboard.info('Thanks! Signed out.')
    else:
        run_login_component()
        components.iframe(src=f'{settings.API_BASE_URL}/api/logout', width=None, height=0, scrolling=False)
        session_state.token={'value': None, 'expiry': None}
        session_state.user=None
        session_state.email=None
Beispiel #8
0
def app():
    st.write("## Maps and Data on Per Capita Basis")

    st.write('''
        The data in these maps represents the factors affecting the severity of covid-19 in different counties in the united states on a per person basis.
        ''')

    # Proportion of Elderly People
    components.iframe("https://datawrapper.dwcdn.net/yarxi/2/", height=550)

    # Covid Cases Per Capita
    components.iframe("https://datawrapper.dwcdn.net/iWLyV/2/", height=550)
Beispiel #9
0
def main():
    is_authenticated = check_token(session_state.token)
    if is_authenticated:
        # token_value = auth_component.session_state.token['value']
        # token_expiry = datetime.fromtimestamp(int(auth_component.session_state.token['expiry']))
        # messageboard.info(f'You are already logged in.\n\nToken is {token_value[0:30]}... | Expires at {token_expiry}')
        messageboard.info(f'You\'re logged in and authorized to use the app.')
    else:
        run_login_component()
        components.iframe(src=f'{settings.API_BASE_URL}/api/login',
                          width=None,
                          height=600,
                          scrolling=True)
def main():
    st.title("Streamlit Weekly Roundups Explorer")
    st.sidebar.subheader("Configuration")
    section_to_urls = load_data("./data")

    selected_section = st.sidebar.selectbox("Select section: ",
                                            sorted(section_to_urls.keys()))
    urls_to_title = section_to_urls[selected_section]

    selected_url = st.selectbox(
        "Search for a link:",
        list(urls_to_title.keys()),
        format_func=lambda option: urls_to_title[option],
    )
    st.markdown(f"URL: {selected_url}")
    st.markdown(
        "Embedded page below. If it does not work, click on the URL above")
    components.iframe(selected_url, height=1200, scrolling=True)
Beispiel #11
0
def main():
    stc.html(LOGO_BANNER)

    menu = [
        "Home", "Set Analysis", "Digit Analysis", "Set History",
        "Run Scraping", "About"
    ]
    choice = st.sidebar.selectbox("Menu", menu)

    if choice == "Home":
        st.subheader("Home")
        stc.iframe(
            "https://www.singaporepools.com.sg/en/product/pages/4d_results.aspx",
            height=700,
            width=300,
            scrolling=True)
    elif choice == "Set Analysis":
        run_setAnalysis()
    elif choice == "Digit Analysis":
        run_digitAnalysis()
    elif choice == "Set History":
        run_setHistory()
    elif choice == "Run Scraping":
        run_scraping()
    else:
        st.info("__About__")
        st.write("A web application to analyze past 4D winning numbers.")
        st.info("__Techology Utilized__")
        st.write("Python, Streamlit, BeautifulSoup, Pandas, Requests")
        st.info("__Responsible Gambling__")
        st.write("__We are not responsible for any of your losses.__")
        st.write("Please leave the website if you are under 18 years old.")
        st.info("__Legal__")
        st.write("You are responsible for any abuse or misuse of this tool.")
        st.info("__Limitations__")
        st.write("We will not be hold accountable for any damages that will\
                 arise with the use of this 4D analysis tool.")
        st.info("__Terms__")
        st.write("By accessing this website, you are responsible for \
                 the agreement with any applicable local laws.")
        st.balloons()
Beispiel #12
0
def page():
    st.title('Analisi dei dati "Covid-19"')
    st.subheader('Studio della situazione in Italia - il progetto')
    st.markdown('''
        Questa web app è stata creata come progetto di gruppo del corso di Machine Learning di IFOA nel contesto del DataLab (https://www.bigdata-lab.it/).
        
        Le analisi si basano sui dati pubblici rilasciati dalla Protezione Civile italiana durante l'emergenza Covid del 2020-2021.

        Qui di seguito si può avere una visione d'insieme delle statistiche dei dati sino ad oggi raccolti.<br><br>
    ''', unsafe_allow_html=True)

    
    # st.markdown('''
    # <br><br>
    # <iframe src='https://flo.uri.sh/story/722265/embed' title='Interactive or visual content' frameborder='0' scrolling='no' style='width:100%;height:900px;' sandbox='allow-same-origin allow-forms allow-scripts allow-downloads allow-popups allow-popups-to-escape-sandbox allow-top-navigation-by-user-activation'></iframe>
    # <div style='width:100%!;margin-top:4px!important;text-align:right!important;'>
    #     <a class='flourish-credit' href='https://public.flourish.studio/story/722265/?utm_source=embed&utm_campaign=story/722265' target='_top' style='text-decoration:none!important'>
    #         <img alt='Made with Flourish' src='https://public.flourish.studio/resources/made_with_flourish.svg' style='width:105px!important;height:16px!important;border:none!important;margin:0!important;'>
    #     </a>
    # </div>
    # ''', unsafe_allow_html=True)
    st.subheader("Bar Chart Race totale positivi")
    components.iframe('https://flo.uri.sh/visualisation/5715327/embed', 800, 600)
Beispiel #13
0
def display_matched_result(audio_container_name, has_pex_result=False):
    st.title(f"Matched Result For:")
    st.markdown(f'https://www.youtube.com/watch?v={audio_container_name}')

    query_audio_path = list(
        glob(root_path +
             f"/assets/{audio_container_name}/query/*.{EXTENSION}"))[0]
    query_audio_name = os.path.basename(query_audio_path)
    asset_audio_container_paths = glob(
        root_path + f"/assets/{audio_container_name}/assets/*")

    # Show summary
    # dataframe = pd.DataFrame(
    #     np.array(get_result_dataframe(audio_container_name)),
    #     columns=['Video ID', 'Matching Segments On Clip', 'Matching Segment on Asset', 'Asset Filename'])
    # st.table(dataframe)

    # Show detail

    content_server_name = config.get('content_server_name', "")

    if has_pex_result:
        st.header('PEX Result:')
        components.iframe(f"{content_server_name}/index_origin", height=300)
        st.header('DeepHub Result:')

    # logging.info(query_audio_name)

    components.iframe(
        f"{content_server_name}/query_predict?query_audio_container_name={audio_container_name}&query_audio_name={query_audio_name}",
        height=250)

    st.header(f'Asset Segments ({len(asset_audio_container_paths)}):')
    match_duration = 0
    for asset_audio_container_path in asset_audio_container_paths:
        # get duration
        annot_path = os.path.join(asset_audio_container_path,
                                  'annotation.json')
        with open(annot_path, 'r') as annot_f:
            annot_data = json.load(annot_f)
            for data in annot_data:
                start = float(data['start'])
                end = float(data['end'])
                match_duration += end - start

        # show asset audio
        asset_audio_name = os.path.basename(asset_audio_container_path)
        components.iframe(
            f"{content_server_name}/asset_predict?query_audio_container_name={audio_container_name}&asset_audio_name={asset_audio_name}",
            height=250)

    display_summary(query_audio_path, len(asset_audio_container_paths),
                    match_duration)
Beispiel #14
0
import streamlit as st
import streamlit.components.v1 as components
from data import Epicurious
import random

TITLE = st.title("recipeo")

USER_INPUT = st.text_input("What are you looking for?")
    
e = Epicurious(USER_INPUT)
soup = e.get_soup()
links = e.get_links(soup)
srcs = e.filter_links(links)

if USER_INPUT:
    try:
        i = random.randint(0, len(srcs))
        components.iframe(srcs[i], height=800, scrolling=True)
    except IndexError:
        st.write("Search for something else.")
Beispiel #15
0
def write():
    """Used to write the page in the app.py file"""

    st.title("All about Work Learnings :speech_balloon: ")
    st.markdown(
        """
            Sharing what I have learned at work, which has immensely helped me to grow and interact with my Linkedin Family..!!""",
        unsafe_allow_html=True,
    )
    c1, c2 = st.beta_columns((3, 3))

    with c1:
        components.iframe(
            src=
            "https://www.linkedin.com/embed/feed/update/urn:li:share:6777589026737205248",
            height=400)
        components.iframe(
            src=
            "https://www.linkedin.com/embed/feed/update/urn:li:share:6770780292924928000",
            height=296)
        components.iframe(
            src=
            "https://www.linkedin.com/embed/feed/update/urn:li:share:6771043712911884288",
            height=500)
        components.iframe(
            src=
            "https://www.linkedin.com/embed/feed/update/urn:li:share:6729753913366515712",
            height=400)

    with c2:
        components.iframe(
            src=
            "https://www.linkedin.com/embed/feed/update/urn:li:share:6775398788417826816",
            height=500)
        components.iframe(
            src=
            "https://www.linkedin.com/embed/feed/update/urn:li:share:6767781819942285312",
            height=500)
        components.iframe(
            src=
            "https://www.linkedin.com/embed/feed/update/urn:li:ugcPost:6732275725614813186",
            height=400)
Beispiel #16
0
def write():
    
    st.header("The Rent in Austin")
    st.subheader("**Introduction**")
    ##income1,immi1=st.beta_columns(2)
    st.markdown("Economy Part")
    income ="""https://datausa.io/profile/geo/austin-tx/economy/income?viz=true"""
    components.iframe(income,width=1000,height=500,scrolling=True)
    em = "https://datausa.io/profile/geo/austin-tx/covid/covid-employment?viz=true"
    components.iframe(em,width=1000,height=500,scrolling=True)
    ##income1 = components.iframe(income,width=1000,height=500,scrolling=True)
    immi = """https://datausa.io/profile/geo/austin-tx/demographics/foreign_born?viz=true"""
    components.iframe(immi,width=1000,height=500,scrolling=True)
    ##immi1 = components.iframe(immi,width=1000,height=500,scrolling=True)
    cz = "https://datausa.io/profile/geo/austin-tx/demographics/citizenship?viz=true"
    components.iframe(cz,width=1000,height=500,scrolling=True)
    propertyvalue = """https://datausa.io/profile/geo/austin-tx/housing/property_value?viz=true"""
    components.iframe(propertyvalue,width=1000,height=500,scrolling=True)
    pv="https://datausa.io/profile/geo/austin-tx/housing/household_income?viz=true" 
    components.iframe(pv,1000,700,True)
    rentvsown = "https://datausa.io/profile/geo/austin-tx/housing/rent_own?viz=true"
    components.iframe(rentvsown,width=1000,height=500,scrolling=True)
    html1="<div class='tableauPlaceholder' id='viz1620859341142' style='position: relative'><noscript><a href='#'><img alt=' ' src='https:&#47;&#47;public.tableau.com&#47;static&#47;images&#47;Ai&#47;AirbnbAustinRegions&#47;GroupBookingStory&#47;1_rss.png' style='border: none' /></a></noscript><object class='tableauViz'  style='display:none;'><param name='host_url' value='https%3A%2F%2Fpublic.tableau.com%2F' /> <param name='embed_code_version' value='3' /> <param name='site_root' value='' /><param name='name' value='AirbnbAustinRegions&#47;GroupBookingStory' /><param name='tabs' value='yes' /><param name='toolbar' value='yes' /><param name='static_image' value='https:&#47;&#47;public.tableau.com&#47;static&#47;images&#47;Ai&#47;AirbnbAustinRegions&#47;GroupBookingStory&#47;1.png' /> <param name='animate_transition' value='yes' /><param name='display_static_image' value='yes' /><param name='display_spinner' value='yes' /><param name='display_overlay' value='yes' /><param name='display_count' value='yes' /><param name='language' value='zh-Hans' /></object></div>                <script type='text/javascript'>                    var divElement = document.getElementById('viz1620859341142');                    var vizElement = divElement.getElementsByTagName('object')[0];                    vizElement.style.width='800px';vizElement.style.height='850px';                    var scriptElement = document.createElement('script');                    scriptElement.src = 'https://public.tableau.com/javascripts/api/viz_v1.js';                    vizElement.parentNode.insertBefore(scriptElement, vizElement);                </script>"
    components.html(html1,1000,500,True)
    html_temp = "<div class='tableauPlaceholder' id='viz1620764157103' style='position: relative'><noscript><a href='#'><img alt='Most Popular Neighborhoods in Austin ' src='https:&#47;&#47;public.tableau.com&#47;static&#47;images&#47;mo&#47;mostpopularhoodsinaustin_0&#47;Map&#47;1_rss.png' style='border: none' /></a></noscript><object class='tableauViz'  style='display:none;'><param name='host_url' value='https%3A%2F%2Fpublic.tableau.com%2F' /> <param name='embed_code_version' value='3' /> <param name='site_root' value='' /><param name='name' value='mostpopularhoodsinaustin_0&#47;Map' /><param name='tabs' value='no' /><param name='toolbar' value='yes' /><param name='static_image' value='https:&#47;&#47;public.tableau.com&#47;static&#47;images&#47;mo&#47;mostpopularhoodsinaustin_0&#47;Map&#47;1.png' /> <param name='animate_transition' value='yes' /><param name='display_static_image' value='yes' /><param name='display_spinner' value='yes' /><param name='display_overlay' value='yes' /><param name='display_count' value='yes' /><param name='language' value='zh-Hans' /></object></div>                <script type='text/javascript'>                    var divElement = document.getElementById('viz1620764157103');                    var vizElement = divElement.getElementsByTagName('object')[0];                    vizElement.style.width='100%';vizElement.style.height=(divElement.offsetWidth*0.75)+'px';                    var scriptElement = document.createElement('script');                    scriptElement.src = 'https://public.tableau.com/javascripts/api/viz_v1.js';                    vizElement.parentNode.insertBefore(scriptElement, vizElement);                </script>"
    components.html(html_temp,1000,500,scrolling=True)
    temp2 = """<div class='tableauPlaceholder' id='viz1620764267668' style='position: relative'><noscript><a href='#'><img alt=' ' src='https:&#47;&#47;public.tableau.com&#47;static&#47;images&#47;Au&#47;Austin-HomeMarketAnalysis&#47;City&#47;1_rss.png' style='border: none' /></a></noscript><object class='tableauViz'  style='display:none;'><param name='host_url' value='https%3A%2F%2Fpublic.tableau.com%2F' /> <param name='embed_code_version' value='3' /> <param name='site_root' value='' /><param name='name' value='Austin-HomeMarketAnalysis&#47;City' /><param name='tabs' value='yes' /><param name='toolbar' value='yes' /><param name='static_image' value='https:&#47;&#47;public.tableau.com&#47;static&#47;images&#47;Au&#47;Austin-HomeMarketAnalysis&#47;City&#47;1.png' /> <param name='animate_transition' value='yes' /><param name='display_static_image' value='yes' /><param name='display_spinner' value='yes' /><param name='display_overlay' value='yes' /><param name='display_count' value='yes' /><param name='language' value='zh-Hans' /></object></div>                <script type='text/javascript'>                    var divElement = document.getElementById('viz1620764267668');                    var vizElement = divElement.getElementsByTagName('object')[0];                    vizElement.style.width='1055px';vizElement.style.height='642px';                    var scriptElement = document.createElement('script');                    scriptElement.src = 'https://public.tableau.com/javascripts/api/viz_v1.js';                    vizElement.parentNode.insertBefore(scriptElement, vizElement);                </script>"""
    components.html(temp2,width=1000,height=500,scrolling=True)
    temp3="<div class='tableauPlaceholder' id='viz1620859103300' style='position: relative'><noscript><a href='#'><img alt='What does the Airbnb business in Austin look like? ' src='https:&#47;&#47;public.tableau.com&#47;static&#47;images&#47;Au&#47;Austin_Airbnb_16118640907970&#47;AustinAirbnb&#47;1_rss.png' style='border: none' /></a></noscript><object class='tableauViz'  style='display:none;'><param name='host_url' value='https%3A%2F%2Fpublic.tableau.com%2F' /> <param name='embed_code_version' value='3' /> <param name='site_root' value='' /><param name='name' value='Austin_Airbnb_16118640907970&#47;AustinAirbnb' /><param name='tabs' value='no' /><param name='toolbar' value='yes' /><param name='static_image' value='https:&#47;&#47;public.tableau.com&#47;static&#47;images&#47;Au&#47;Austin_Airbnb_16118640907970&#47;AustinAirbnb&#47;1.png' /> <param name='animate_transition' value='yes' /><param name='display_static_image' value='yes' /><param name='display_spinner' value='yes' /><param name='display_overlay' value='yes' /><param name='display_count' value='yes' /><param name='language' value='zh-Hans' /></object></div>                <script type='text/javascript'>                    var divElement = document.getElementById('viz1620859103300');                    var vizElement = divElement.getElementsByTagName('object')[0];                    vizElement.style.width='1016px';vizElement.style.height='991px';                    var scriptElement = document.createElement('script');                    scriptElement.src = 'https://public.tableau.com/javascripts/api/viz_v1.js';                    vizElement.parentNode.insertBefore(scriptElement, vizElement);                </script>"
    components.html(temp3,width=1000,height=500,scrolling=True)
    temp4="<div class='tableauPlaceholder' id='viz1620859189007' style='position: relative'><noscript><a href='http:&#47;&#47;www.TexasNationalTitle.com'><img alt='Median Sales Price Appreciation by Zip CodeMarch 2020 to March 2021 ' src='https:&#47;&#47;public.tableau.com&#47;static&#47;images&#47;Me&#47;MedianSalesPriceAppreciationbyZipCodeMarch2021&#47;Mar2021&#47;1_rss.png' style='border: none' /></a></noscript><object class='tableauViz'  style='display:none;'><param name='host_url' value='https%3A%2F%2Fpublic.tableau.com%2F' /> <param name='embed_code_version' value='3' /> <param name='site_root' value='' /><param name='name' value='MedianSalesPriceAppreciationbyZipCodeMarch2021&#47;Mar2021' /><param name='tabs' value='no' /><param name='toolbar' value='yes' /><param name='static_image' value='https:&#47;&#47;public.tableau.com&#47;static&#47;images&#47;Me&#47;MedianSalesPriceAppreciationbyZipCodeMarch2021&#47;Mar2021&#47;1.png' /> <param name='animate_transition' value='yes' /><param name='display_static_image' value='yes' /><param name='display_spinner' value='yes' /><param name='display_overlay' value='yes' /><param name='display_count' value='yes' /><param name='language' value='zh-Hans' /></object></div>                <script type='text/javascript'>                    var divElement = document.getElementById('viz1620859189007');                    var vizElement = divElement.getElementsByTagName('object')[0];                    if ( divElement.offsetWidth > 800 ) { vizElement.style.minWidth='420px';vizElement.style.maxWidth='650px';vizElement.style.width='100%';vizElement.style.minHeight='587px';vizElement.style.maxHeight='887px';vizElement.style.height=(divElement.offsetWidth*0.75)+'px';} else if ( divElement.offsetWidth > 500 ) { vizElement.style.minWidth='420px';vizElement.style.maxWidth='650px';vizElement.style.width='100%';vizElement.style.minHeight='587px';vizElement.style.maxHeight='887px';vizElement.style.height=(divElement.offsetWidth*0.75)+'px';} else { vizElement.style.width='100%';vizElement.style.height='777px';}                     var scriptElement = document.createElement('script');                    scriptElement.src = 'https://public.tableau.com/javascripts/api/viz_v1.js';                    vizElement.parentNode.insertBefore(scriptElement, vizElement);                </script>"
    components.html(temp4,width=1000,height=500,scrolling=True)
    temp8="<div class='tableauPlaceholder' id='viz1620859490626' style='position: relative'><noscript><a href='#'><img alt='Reviews Per Month ' src='https:&#47;&#47;public.tableau.com&#47;static&#47;images&#47;Au&#47;AustinAirbnb_15643508724270&#47;ReviewsPerMonth&#47;1_rss.png' style='border: none' /></a></noscript><object class='tableauViz'  style='display:none;'><param name='host_url' value='https%3A%2F%2Fpublic.tableau.com%2F' /> <param name='embed_code_version' value='3' /> <param name='site_root' value='' /><param name='name' value='AustinAirbnb_15643508724270&#47;ReviewsPerMonth' /><param name='tabs' value='no' /><param name='toolbar' value='yes' /><param name='static_image' value='https:&#47;&#47;public.tableau.com&#47;static&#47;images&#47;Au&#47;AustinAirbnb_15643508724270&#47;ReviewsPerMonth&#47;1.png' /> <param name='animate_transition' value='yes' /><param name='display_static_image' value='yes' /><param name='display_spinner' value='yes' /><param name='display_overlay' value='yes' /><param name='display_count' value='yes' /><param name='language' value='zh-Hans' /></object></div>                <script type='text/javascript'>                    var divElement = document.getElementById('viz1620859490626');                    var vizElement = divElement.getElementsByTagName('object')[0];                    vizElement.style.width='100%';vizElement.style.height=(divElement.offsetWidth*0.75)+'px';                    var scriptElement = document.createElement('script');                    scriptElement.src = 'https://public.tableau.com/javascripts/api/viz_v1.js';                    vizElement.parentNode.insertBefore(scriptElement, vizElement);                </script>"
    components.html(temp8,width=1000,height=500,scrolling=True)
    temp9="<div class='tableauPlaceholder' id='viz1620859557078' style='position: relative'><noscript><a href='#'><img alt='map_final ' src='https:&#47;&#47;public.tableau.com&#47;static&#47;images&#47;au&#47;austin_neighborhood_rents&#47;map_final&#47;1_rss.png' style='border: none' /></a></noscript><object class='tableauViz'  style='display:none;'><param name='host_url' value='https%3A%2F%2Fpublic.tableau.com%2F' /> <param name='embed_code_version' value='3' /> <param name='site_root' value='' /><param name='name' value='austin_neighborhood_rents&#47;map_final' /><param name='tabs' value='no' /><param name='toolbar' value='yes' /><param name='static_image' value='https:&#47;&#47;public.tableau.com&#47;static&#47;images&#47;au&#47;austin_neighborhood_rents&#47;map_final&#47;1.png' /> <param name='animate_transition' value='yes' /><param name='display_static_image' value='yes' /><param name='display_spinner' value='yes' /><param name='display_overlay' value='yes' /><param name='display_count' value='yes' /><param name='language' value='zh-Hans' /></object></div>                <script type='text/javascript'>                    var divElement = document.getElementById('viz1620859557078');                    var vizElement = divElement.getElementsByTagName('object')[0];                    if ( divElement.offsetWidth > 800 ) { vizElement.style.width='754px';vizElement.style.height='827px';} else if ( divElement.offsetWidth > 500 ) { vizElement.style.width='754px';vizElement.style.height='827px';} else { vizElement.style.width='100%';vizElement.style.height='927px';}                     var scriptElement = document.createElement('script');                    scriptElement.src = 'https://public.tableau.com/javascripts/api/viz_v1.js';                    vizElement.parentNode.insertBefore(scriptElement, vizElement);                </script>"
    components.html(temp9,width=1000,height=500,scrolling=True)
    temp7="<div class='tableauPlaceholder' id='viz1620859423599' style='position: relative'><noscript><a href='#'><img alt=' ' src='https:&#47;&#47;public.tableau.com&#47;static&#47;images&#47;Au&#47;Austin-Analysis&#47;Rentv_HomeValues&#47;1_rss.png' style='border: none' /></a></noscript><object class='tableauViz'  style='display:none;'><param name='host_url' value='https%3A%2F%2Fpublic.tableau.com%2F' /> <param name='embed_code_version' value='3' /> <param name='site_root' value='' /><param name='name' value='Austin-Analysis&#47;Rentv_HomeValues' /><param name='tabs' value='yes' /><param name='toolbar' value='yes' /><param name='static_image' value='https:&#47;&#47;public.tableau.com&#47;static&#47;images&#47;Au&#47;Austin-Analysis&#47;Rentv_HomeValues&#47;1.png' /> <param name='animate_transition' value='yes' /><param name='display_static_image' value='yes' /><param name='display_spinner' value='yes' /><param name='display_overlay' value='yes' /><param name='display_count' value='yes' /><param name='language' value='zh-Hans' /></object></div>                <script type='text/javascript'>                    var divElement = document.getElementById('viz1620859423599');                    var vizElement = divElement.getElementsByTagName('object')[0];                    vizElement.style.width='100%';vizElement.style.height=(divElement.offsetWidth*0.75)+'px';                    var scriptElement = document.createElement('script');                    scriptElement.src = 'https://public.tableau.com/javascripts/api/viz_v1.js';                    vizElement.parentNode.insertBefore(scriptElement, vizElement);                </script>"
    components.html(temp7,width=1000,height=500,scrolling=True)
    
    
Beispiel #17
0
components.html("""
<html>
<body>

<h1>The datalist element</h1>

<form action="/action_page.php" method="get">
  <label for="browser">Choose your browser from the list:</label>
  <input list="browsers" name="browser" id="browser">
  <datalist id="browsers">
    <option value="Edge">
    <option value="Firefox">
    <option value="Chrome">
    <option value="Opera">
    <option value="Safari">
  </datalist>
  <input type="submit">
</form>

<p><strong>Note:</strong> The datalist tag is not supported in Safari 12.0 (or earlier).</p>

</body>
</html>
                <a class="twitter-timeline"
                href="https://twitter.com/streamlit?ref_src=twsrc%5Etfw">Tweets by streamlit</a>
                <script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>
                """)

# embed streamlit docs in a streamlit app
components.iframe("https://docs.streamlit.io/en/latest")
def write():
    """Used to write the page in the app.py file"""

    st.title("Thoughts :thought_balloon: ")
    st.markdown(
        """
            Sharing some postitvity and soft skills that help us everyday..!!""",
        unsafe_allow_html=True,
    )
    c1, c2 = st.beta_columns((3, 3))

    with c1:
        components.iframe(
            src=
            "https://www.linkedin.com/embed/feed/update/urn:li:share:6778895371167961088",
            height=300)
        components.iframe(
            src=
            "https://www.linkedin.com/embed/feed/update/urn:li:share:6778510384224636928",
            height=296)
        components.iframe(
            src=
            "https://www.linkedin.com/embed/feed/update/urn:li:share:6777228909109932032",
            height=500)
        components.iframe(
            src=
            "https://www.linkedin.com/embed/feed/update/urn:li:share:6772864413667004416",
            height=400)
        components.iframe(
            src=
            "https://www.linkedin.com/embed/feed/update/urn:li:share:6777787626494705664",
            height=250)
        components.iframe(
            src=
            "https://www.linkedin.com/embed/feed/update/urn:li:share:6729008253046439936",
            height=360)

    with c2:
        components.iframe(
            src=
            "https://www.linkedin.com/embed/feed/update/urn:li:share:6778654002344202240",
            height=300)
        components.iframe(
            src=
            "https://www.linkedin.com/embed/feed/update/urn:li:share:6772503725744410625",
            height=400)
        components.iframe(
            src=
            "https://www.linkedin.com/embed/feed/update/urn:li:share:6778179581686935552",
            height=250)
        components.iframe(
            src=
            "https://www.linkedin.com/embed/feed/update/urn:li:share:6778293153016401920",
            height=480)
        components.iframe(
            src=
            "https://www.linkedin.com/embed/feed/update/urn:li:share:6773968490819833856",
            height=500)
        components.iframe(
            src=
            "https://www.linkedin.com/embed/feed/update/urn:li:share:6731546780737028096",
            height=500)
Beispiel #19
0
                   paper_bgcolor='#D6D6D6',
                   plot_bgcolor='#D6D6D6',
                   hoverlabel={"bordercolor": '#EBEEEE'},
                   margin={"pad": 2},
                   width=700,
                   height=400,
                   font={'color': '#191616'})

st.plotly_chart(fig1, use_container_width=True)

st.text('     ')
st.text('     ')
st.text('     ')
st.markdown(
    "<h2 style='text-align: center; color: red;'>List of covid Health centres</h2>",
    unsafe_allow_html=True)
st.text('     ')
st.text('     ')
st.text('     ')
image = Image.open('hospitals_list.jpg')
st.image(image, use_column_width=True)
st.markdown("<h1 style='text-align: center;'>Poll</h1>",
            unsafe_allow_html=True)
st.markdown('   ')
components.iframe("https://www.opinionstage.com/api/v1/widgets/746208/iframe",
                  height=450,
                  width=450)
components.iframe("https://www.opinionstage.com/api/v1/widgets/746254/iframe",
                  height=420,
                  width=450)
Beispiel #20
0
# Copyright 2018-2021 Streamlit Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import streamlit.components.v1 as components

src = "http://not.a.real.url"
components.iframe(src, width=200, height=500, scrolling=True)
def main():		
	"""Diabetes Prediction App"""
	html_temp = """
		<div style="background-color:navy;padding:10px;border-radius:10px">
		<h1 style="color:white;text-align:center;">Echidna AI</h1>
		<h5 style="color:white;text-align:center;">Diabetes Prediction WEB APP</h5>
		</div>
		"""

	components.html(html_temp)
	image = Image.open('C:/Users/Adila/Documents/hep_app/LOGO.png')
	st.image(image, use_column_width=True)

	menu = ["Home", "Login", "SignUp", "Book An Appointment", "Profile Report", "About", "Privacy Policy"]
	submenu = ["Plot", "Prediction",]

	choice = st.sidebar.selectbox("Menu", menu)
	if choice == "Home":
		st.subheader("---------------WELCOME TO THE DIABETES PREDICTION APP-----------------")
		




		html_temp2 = """
		<div style="background-color:navy;padding:3px;border-radius:10px">
		<h1 style="color:white;text-align:center;">How to Login?</h1>
		<h5 style="color:white;text-align:center;">press the arrow on the top left corner and choose the LOGIN from menu to get started</h5>
		</div>
		"""
		components.html(html_temp2)

		html_temp3 = """
		<div style="background-color:navy;padding:3px;border-radius:10px">
		<h1 style="color:white;text-align:center;">How to Sign Up?</h1>
		<h5 style="color:white;text-align:center;">press the arrow on the top left corner and choose the SIGN UP from menu to get started</h5>
		</div>
		"""
		components.html(html_temp3)
		st.title("Brief explanation on Diabetes Mellitus")
		st.subheader("------Diabetes mellitus (DM), commonly known as diabetes, is a group of metabolic disorders characterized by a high blood sugar level over a prolonged period. Symptoms often include frequent urination, increased thirst, and increased appetite. If left untreated, diabetes can cause many complications. Acute complications can include diabetic ketoacidosis, hyperosmolar hyperglycemic state, or death. Serious long-term complications include cardiovascular disease, stroke, chronic kidney disease, foot ulcers, damage to the nerves, damage to the eyes and cognitive impairment.")
		st.subheader("------Diabetes is due to either the pancreas not producing enough insulin, or the cells of the body not responding properly to the insulin produced. There are three main types of diabetes mellitus:")
		st.subheader("------Type 1 diabetes results from the pancreas's failure to produce enough insulin due to loss of beta cells. This form was previously referred to as insulin-dependent diabetes mellitus (IDDM) or  juvenile diabetes . The loss of beta cells is caused by an autoimmune response. The cause of this autoimmune response is unknown.") 
		st.subheader("------Type 2 diabetes begins with insulin resistance, a condition in which cells fail to respond to insulin properly. As the disease progresses, a lack of insulin may also develop. This form was previously referred to as non-insulin-dependent diabetes mellitus  (NIDDM) or  adult-onset diabetes .  The most common cause is a combination of excessive body weight and insufficient exercise.") 
		st.subheader("------Gestational diabetes is the third main form and occurs when pregnant women without a previous history of diabetes develop high blood sugar levels.")
		st.subheader("------Type 1 diabetes must be managed with insulin injections. Prevention and treatment of type 2 diabetes involves maintaining a healthy diet, regular physical exercise, a normal body weight, and avoiding use of tobacco. Type 2 diabetes may be treated with medications such as insulin sensitizers with or without insulin. Control of blood pressure and maintaining proper foot and eye care are important for people with the disease. Insulin and some oral medications can cause low blood sugar.  Weight loss surgery in those with obesity is sometimes an effective measure in those with type 2 diabetes. Gestational diabetes usually resolves after the birth of the baby.")
		st.subheader("------As of 2019, an estimated 463 million people had diabetes worldwide (8.8% of the adult population), with type 2 diabetes making up about 90% of the cases.  Rates are similar in women and men. Trends suggest that rates will continue to rise. Diabetes at least doubles a person's risk of early death. In 2019, diabetes resulted in approximately 4.2 million deaths. It is the 7th leading cause of death globally. The global economic cost of diabetes related health expenditure in 2017 was estimated at US$727 billion. In the United States, diabetes cost nearly US$327 billion in 2017. Average medical expenditures among people with diabetes are about 2.3 times higher.")

	elif choice == "Login":
		username = st.sidebar.text_input("Username")
		password = st.sidebar.text_input("Password",type='password')
		if st.sidebar.checkbox("Login"):
			create_usertable()
			hashed_pswd = generate_hashes(password)
			result = login_user(username,verify_hashes(password, hashed_pswd))
			#if password == "12345":
			if result:
				st.success("Welcome {}".format(username))

				activity = st.selectbox("Activity", submenu)
				if activity == "Plot":
					st.subheader("Data Vis Plot")
					df = pd.read_csv("data/clean_hepatitis_dataset.csv")
					st.dataframe(df)

					df['class'].value_counts().plot(kind='bar')
					st.pyplot()

					#Freq Dist Plot
					freq_df = pd.read_csv("data/freq_df_hepatitis_dataset.csv")
					st.bar_chart(freq_df['count'])

					
					if st.checkbox("Area Chart"):
						all_columns = df.columns.to_list()
						feat_choices = st.multiselect("Choose a Feature",all_columns)
						new_df = df[feat_choices]
						st.area_chart(new_df)

				elif activity == "Prediction":
					st.subheader("Predictive Analytics")

					age = st.number_input("Age",7,80)
					sex = st.radio("Sex",tuple(gender_dict.keys()))
					steroid = st.radio("Do You Take Steroids?",tuple(feature_dict.keys()))
					antivirals = st.radio("Do You Take Antivirals?",tuple(feature_dict.keys()))
					fatigue = st.radio("Do You Have Fatigue",tuple(feature_dict.keys()))
					spiders = st.radio("Presence of Spider Naeve",tuple(feature_dict.keys()))
					ascites = st.selectbox("Ascities",tuple(feature_dict.keys()))
					varices = st.selectbox("Presence of Varices",tuple(feature_dict.keys()))
					bilirubin = st.number_input("bilirubin Content",0.0,8.0)
					alk_phosphate = st.number_input("Alkaline Phosphate Content",0.0,296.0)
					sgot = st.number_input("Sgot",0.0,648.0)
					albumin = st.number_input("Albumin",0.0,6.4)
					protime = st.number_input("Prothrombin Time",0.0,100.0)
					histology = st.selectbox("Histology",tuple(feature_dict.keys()))
					feature_list = [age,get_value(sex,gender_dict),get_fvalue(steroid),get_fvalue(antivirals),get_fvalue(fatigue),get_fvalue(spiders),get_fvalue(ascites),get_fvalue(varices),bilirubin,alk_phosphate,sgot,albumin,int(protime),get_fvalue(histology)]

					st.write(feature_list)
					pretty_result = {"age":age,"sex":sex,"steroid":steroid,"antivirals":antivirals,"fatigue":fatigue,"spiders":spiders,"ascites":ascites,"varices":varices,"bilirubin":bilirubin,"alk_phosphate":alk_phosphate,"sgot":sgot,"albumin":albumin,"protime":protime,"histolog":histology}
					st.json(pretty_result)
					single_sample = np.array(feature_list).reshape(1,-1)

					#ML
					model_choice = st.selectbox("Select Model", ["KNN", "DecisionTree", "LR"]) 
					if st.button("Predict"):
						if model_choice == "KNN":
							loaded_model = load_model("models/knn_hepB_model.pkl")
							prediction = loaded_model.predict(single_sample)
							pred_prob = loaded_model.predict_proba(single_sample)
						elif model_choice == "DecisionTree":
							loaded_model = load_model("models/decision_tree_clf_hepB_model.pkl")
							prediction = loaded_model.predict(single_sample)
							pred_prob = loaded_model.predict_proba(single_sample)
						else:
							loaded_model = load_model("models/logistic_regression_hepB_model.pkl")
							prediction = loaded_model.predict(single_sample)
							pred_prob = loaded_model.predict_proba(single_sample)

						#st.write(prediction)
						#prediction_label = {"You have a risk to have diabetes":1, "You don't have a risk to have diabetes":2}
						#final_result = get_key(prediction,prediction_label)
						#st.write(Ffinal_result)
						if prediction == 1:
							st.warning("Patient has a risk to have Diabetes")
							pred_probability_score = {"Dibetes":pred_prob[0][0]*100,"No Diabetes":pred_prob[0][1]*100}
							st.subheader("Prediction Probability Score using Neural network with {}".format(model_choice))
							st.json(pred_probability_score)
							st.subheader("Prescriptive Analytics")
							st.markdown(prescriptive_message_temp,unsafe_allow_html=True)
							
						else:
							st.success("Patient don't have a risk of having Diabetes")
							pred_probability_score = {"Has a risk":pred_prob[0][0]*100,"No Risk":pred_prob[0][1]*100}
							st.subheader("Prediction Probability Score using Neural network with {}".format(model_choice))
							st.json(pred_probability_score)



					if st.checkbox("Interpret"):
						if model_choice == "KNN":
							loaded_model = load_model("models/knn_hepB_model.pkl")
							
						elif model_choice == "DecisionTree":
							loaded_model = load_model("models/decision_tree_clf_hepB_model.pkl")
							
						else:
							loaded_model = load_model("models/logistic_regression_hepB_model.pkl")
							

						# loaded_model = load_model("models/logistic_regression_model.pkl")							
						# 1 Die and 2 Live
						df = pd.read_csv("data/clean_hepatitis_dataset.csv")
						x = df[['age', 'sex', 'steroid', 'antivirals','fatigue','spiders', 'ascites','varices', 'bilirubin', 'alk_phosphate', 'sgot', 'albumin', 'protime','histology']]
						feature_names = ['age', 'sex', 'steroid', 'antivirals','fatigue','spiders', 'ascites','varices', 'bilirubin', 'alk_phosphate', 'sgot', 'albumin', 'protime','histology']
						class_names = ['Die(1)','Live(2)']
						explainer = lime.lime_tabular.LimeTabularExplainer(x.values,feature_names=feature_names, class_names=class_names,discretize_continuous=True)
						# The Explainer Instance
						exp = explainer.explain_instance(np.array(feature_list), loaded_model.predict_proba,num_features=13, top_labels=13)
						exp.show_in_notebook(show_table=True, show_all=True)
						# exp.save_to_file('lime_oi.html')
						st.write(exp.as_list())
						new_exp = exp.as_list()
						label_limits = [i[0] for i in new_exp]
						# st.write(label_limits)
						label_scores = [i[1] for i in new_exp]
						plt.barh(label_limits,label_scores)
						st.pyplot()
						plt.figure(figsize=(20,10))
						fig = exp.as_pyplot_figure()
						st.pyplot()	
				


			else:		
				st.warning("Incorrect Username or Password")
	elif choice == "SignUp":
		new_username = st.text_input("User name")
		new_password = st.text_input("Password", type='password')

		confirm_password = st.text_input("Confirm Password",type='password')
		if new_password == confirm_password:
			st.success("Password Confirmed")
		else:
			st.warning("Passwords not the same")

		if st.button("Submit"):
			create_usertable()
			hashed_new_password = generate_hashes(new_password)
			add_userdata(new_username,hashed_new_password)
			st.success("You have created a new account")
			st.info("Login to get started")

	elif choice == "Profile Report":
		st.title("What is Profile Report?")
		st.subheader("------This technology can be used to upload datasets that you may have as analyst or if you are a doctor who wants to get a clear idea about percentage of patients who has this or that problem. And then the technology itself will analyze it.")
		st.title("How to start to analyze the data?")
		st.subheader("------To analyze the data you just simply need to upload a CSV file") 
		st.title("What kind of files this technology accepts?")
		st.subheader("------Basically a CSV files")
		st.title("How is it analyzing the data?")
		st.subheader("------Mainly, technology itself uses a neural networks to analyze the data, and then it will represent the data as a charts")
		


		data_file = st.file_uploader("UPLOAD CSV",type=['csv'])
		st.set_option('deprecation.showfileUploaderEncoding', False)
		if data_file is not None:
			df = pd.read_csv(data_file)
			st.dataframe(df.head())
			profile = ProfileReport(df)
			st_profile_report(profile)

			
	elif choice == "Book An Appointment":
		st.title("Book An Appointments")
		st.title("Integration with Nilai medical center website")
		st.subheader("------Developer integrated this WebApp with existed website to make sure that patients can book an appointment to a real medical") 
		components.iframe('https://nmc.encoremed.io/',width=700,height=2000)

	elif choice == "About":
		st.title("About App")
		st.title("F.A.Q.")
		st.title("What is Echidna AI?")
		st.subheader("------Basically, its an a WEB APP that can help people to predict Diabetes")
		st.title("What kind of functions do Echidna Have?")
		st.subheader("------The main purpose of the Echidna AI is to provide a solution for people to predict diabetes and to help analysts to analyze the data in a better way. And the data itself can be stored inside this WEB APP because it has a neural network that can store data inside nodes")
		st.title("Is it Open source Alghorithm?")
		st.subheader("------The Echidna AI® algorithm")
		st.subheader("------This web app was released as open source software under the GNU Affero General Public Licence, version 3. This ensures that academics and others interested in the core of the algorithms at least start with a working implementation. The terms of the licence ensure that implementations are transparent and open, and are, in turn, open for others to use and/or modify under the same licence.")
		st.title("Is Echidna AI can be recommended for clinical use?")
		st.subheader("------It can be recommended for clinical use, software developers can use this professionally supported software development kits.")
		st.title("Would Echidna AI be supported in future?")
		st.subheader("------Echidna AI®-2020 will be released to licencees of our Echidna AI® software development kit in the new year, for deployment from August. Which means that it will be suported")
		st.title("Do Echidna AI patented or is it has a copyright?")
		st.subheader("Yes, Echidna AI has  a copyright, but it is an open source software that can be modified")
		st.subheader("------Copyright ©Echidna 2020. ALL RIGHTS RESERVED.")
		st.subheader("------Materials on this web site are protected by copyright law. Access to the materials on this web site for the sole purpose of personal educational and research use only. Where appropriate a single print out of a reasonable proportion of these materials may be made for personal education, research and private study. Materials should not be further copied, photocopied or reproduced, or distributed in electronic form. Any unauthorised use or distribution for commercial purposes is expressly forbidden. Any other unauthorised use or distribution of the materials may constitute an infringement of ClinRisk's copyright and may lead to legal action.")
		st.subheader("------For avoidance of doubt, any use of this site as a web service to obtain a Echidna AI® for any purpose is expressly forbidden. Similarly, use of this website for developing or testing software of any sort is forbidden unless permission has been explicitly granted.")
		st.subheader("------BMI predictor algorithm © 2020 Echidna Inc.")
		st.subheader("------WebApp and risk engine built by Adilan Akhramovich WebApp design ©Echidna 2020.")
		#components.iframe('https://quickdraw.withgoogle.com',height=2000)
		components.html(footer_html,height=500)

	elif choice == "Privacy Policy":
		st.title("Privacy Policy of Echidna Inc.")
		st.subheader("------At ECHIDNA AI, one of our main priorities is the privacy of our visitors. This Privacy Policy document contains types of information that is collected and recorded by ECHIDNA AI and how we use it.")

		st.subheader("------If you have additional questions or require more information about our Privacy Policy, do not hesitate to contact us.")

		st.subheader("------This Privacy Policy applies only to our online activities and is valid for visitors to our webapp with regards to the information that they shared and/or collect in ECHIDNA AI. This policy is not applicable to any information collected offline or via channels other than this webapp.")

		st.title("Consent")
		st.subheader("------By using our webapp, you hereby consent to our Privacy Policy and agree to its terms.")

		st.title("Information we collect")
		st.subheader("------The personal information that you are asked to provide, and the reasons why you are asked to provide it, will be made clear to you at the point we ask you to provide your personal information.")

		st.subheader("------If you contact us directly, we may receive additional information about you such as your name, email address, phone number, the contents of the message and/or attachments you may send us, and any other information you may choose to provide.")

		st.title("How we use your information?")
		st.subheader("We use the information we collect in various ways, including to:")

		st.subheader("------Provide, operate, and maintain our webapp")
		st.subheader("------Improve, personalize, and expand our webapp")
		st.subheader("------Understand and analyze how you use our webapp")
		st.subheader("------Develop new products, services, features, and functionality")
		st.subheader("------Communicate with you, either directly or through one of our partners, including for customer service, to provide you with updates and other information relating to the webapp, and for marketing and promotional purposes")
		st.subheader("------Send you emails")
		st.subheader("------Find and prevent fraud")

		st.title("Log Files")
		st.subheader("------ECHIDNA AI follows a standard procedure of using log files. These files log visitors when they visit websites. All hosting companies do this and a part of hosting services' analytics. The information collected by log files include internet protocol (IP) addresses, browser type, Internet Service Provider (ISP), date and time stamp, referring/exit pages, and possibly the number of clicks. These are not linked to any information that is personally identifiable. The purpose of the information is for analyzing trends, administering the site, tracking users' movement on the website, and gathering demographic information.")

		st.title("Advertising Partners Privacy Policies")
		st.subheader("------You may consult this list to find the Privacy Policy for each of the advertising partners of ECHIDNA AI.")

		st.subheader("------Third-party ad servers or ad networks uses technologies like cookies, JavaScript, or Web Beacons that are used in their respective advertisements and links that appear on ECHIDNA AI, which are sent directly to users' browser. They automatically receive your IP address when this occurs. These technologies are used to measure the effectiveness of their advertising campaigns and/or to personalize the advertising content that you see on websites that you visit.")

		st.subheader("------Note that ECHIDNA AI has no access to or control over these cookies that are used by third-party advertisers.")

		st.title("Third Party Privacy Policies")
		st.subheader("------ECHIDNA AI's Privacy Policy does not apply to other advertisers or websites. Thus, we are advising you to consult the respective Privacy Policies of these third-party ad servers for more detailed information. It may include their practices and instructions about how to opt-out of certain options.")

		st.subheader("------You can choose to disable cookies through your individual browser options. To know more detailed information about cookie management with specific web browsers, it can be found at the browsers' respective websites.")

		st.title("MCPA Privacy Rights (Do Not Sell My Personal Information)")
		st.subheader("Under the MCPA, among other rights, consumers have the right to:")

		st.subheader("------Request that a business that collects a consumer's personal data disclose the categories and specific pieces of personal data that a business has collected about consumers.")

		st.subheader("------Request that a business delete any personal data about the consumer that a business has collected.")

		st.subheader("------Request that a business that sells a consumer's personal data, not sell the consumer's personal data.")

		st.subheader("------If you make a request, we have one month to respond to you. If you would like to exercise any of these rights, please contact us.")

		st.title("GDPR Data Protection Rights")
		st.subheader("We would like to make sure you are fully aware of all of your data protection rights. Every user is entitled to the following:")

		st.subheader("------The right to access – You have the right to request copies of your personal data. We may charge you a small fee for this service.")

		st.subheader("------The right to rectification – You have the right to request that we correct any information you believe is inaccurate. You also have the right to request that we complete the information you believe is incomplete.")

		st.subheader("------The right to erasure – You have the right to request that we erase your personal data, under certain conditions.")

		st.subheader("------The right to restrict processing – You have the right to request that we restrict the processing of your personal data, under certain conditions.")

		st.subheader("------The right to object to processing – You have the right to object to our processing of your personal data, under certain conditions.")

		st.subheader("------The right to data portability – You have the right to request that we transfer the data that we have collected to another organization, or directly to you, under certain conditions.")

		st.subheader("------If you make a request, we have one month to respond to you. If you would like to exercise any of these rights, please contact us.")

		st.title("Children's Information")
		st.subheader("------Another part of our priority is adding protection for children while using the internet. We encourage parents and guardians to observe, participate in, and/or monitor and guide their online activity.")

		st.subheader("------ECHIDNA AI does not knowingly collect any Personal Identifiable Information from children under the age of 13. If you think that your child provided this kind of information on our website, we strongly encourage you to contact us immediately and we will do our best efforts to promptly remove such information from our records.")
Beispiel #22
0
def main():
    side_img = Image.open("images/emotion3.jpg")
    with st.sidebar:
        st.image(side_img, width=300)
    st.sidebar.subheader("Menu")
    website_menu = st.sidebar.selectbox(
        "Menu", ("Emotion Recognition", "Project description", "Our team",
                 "Leave feedback", "Relax"))
    st.set_option('deprecation.showfileUploaderEncoding', False)

    if website_menu == "Emotion Recognition":
        st.sidebar.subheader("Model")
        model_type = st.sidebar.selectbox("How would you like to predict?",
                                          ("mfccs", "mel-specs"))
        em3 = em6 = em7 = gender = False
        st.sidebar.subheader("Settings")

        st.markdown("## Upload the file")
        with st.container():
            col1, col2 = st.columns(2)
            # audio_file = None
            # path = None
            with col1:
                audio_file = st.file_uploader("Upload audio file",
                                              type=['wav', 'mp3', 'ogg'])
                if audio_file is not None:
                    if not os.path.exists("audio"):
                        os.makedirs("audio")
                    path = os.path.join("audio", audio_file.name)
                    if_save_audio = save_audio(audio_file)
                    if if_save_audio == 1:
                        st.warning("File size is too large. Try another file.")
                    elif if_save_audio == 0:
                        # extract features
                        # display audio
                        st.audio(audio_file, format='audio/wav', start_time=0)
                        try:
                            wav, sr = librosa.load(path, sr=44100)
                            Xdb = get_melspec(path)[1]
                            mfccs = librosa.feature.mfcc(wav, sr=sr)
                            # # display audio
                            # st.audio(audio_file, format='audio/wav', start_time=0)
                        except Exception as e:
                            audio_file = None
                            st.error(
                                f"Error {e} - wrong format of the file. Try another .wav file."
                            )
                    else:
                        st.error("Unknown error")
                else:
                    if st.button("Try test file"):
                        wav, sr = librosa.load("test.wav", sr=44100)
                        Xdb = get_melspec("test.wav")[1]
                        mfccs = librosa.feature.mfcc(wav, sr=sr)
                        # display audio
                        st.audio("test.wav", format='audio/wav', start_time=0)
                        path = "test.wav"
                        audio_file = "test"
            with col2:
                if audio_file is not None:
                    fig = plt.figure(figsize=(10, 2))
                    fig.set_facecolor('#d1d1e0')
                    plt.title("Wave-form")
                    librosa.display.waveplot(wav, sr=44100)
                    plt.gca().axes.get_yaxis().set_visible(False)
                    plt.gca().axes.get_xaxis().set_visible(False)
                    plt.gca().axes.spines["right"].set_visible(False)
                    plt.gca().axes.spines["left"].set_visible(False)
                    plt.gca().axes.spines["top"].set_visible(False)
                    plt.gca().axes.spines["bottom"].set_visible(False)
                    plt.gca().axes.set_facecolor('#d1d1e0')
                    st.write(fig)
                else:
                    pass
            #     st.write("Record audio file")
            #     if st.button('Record'):
            #         with st.spinner(f'Recording for 5 seconds ....'):
            #             st.write("Recording...")
            #             time.sleep(3)
            #         st.success("Recording completed")
            #         st.write("Error while loading the file")

        if model_type == "mfccs":
            em3 = st.sidebar.checkbox("3 emotions", True)
            em6 = st.sidebar.checkbox("6 emotions", True)
            em7 = st.sidebar.checkbox("7 emotions")
            gender = st.sidebar.checkbox("gender")

        elif model_type == "mel-specs":
            st.sidebar.warning("This model is temporarily disabled")

        else:
            st.sidebar.warning("This model is temporarily disabled")

        # with st.sidebar.expander("Change colors"):
        #     st.sidebar.write("Use this options after you got the plots")
        #     col1, col2, col3, col4, col5, col6, col7 = st.columns(7)
        #
        #     with col1:
        #         a = st.color_picker("Angry", value="#FF0000")
        #     with col2:
        #         f = st.color_picker("Fear", value="#800080")
        #     with col3:
        #         d = st.color_picker("Disgust", value="#A52A2A")
        #     with col4:
        #         sd = st.color_picker("Sad", value="#ADD8E6")
        #     with col5:
        #         n = st.color_picker("Neutral", value="#808080")
        #     with col6:
        #         sp = st.color_picker("Surprise", value="#FFA500")
        #     with col7:
        #         h = st.color_picker("Happy", value="#008000")
        #     if st.button("Update colors"):
        #         global COLOR_DICT
        #         COLOR_DICT = {"neutral": n,
        #                       "positive": h,
        #                       "happy": h,
        #                       "surprise": sp,
        #                       "fear": f,
        #                       "negative": a,
        #                       "angry": a,
        #                       "sad": sd,
        #                       "disgust": d}
        #         st.success(COLOR_DICT)

        if audio_file is not None:
            st.markdown("## Analyzing...")
            if not audio_file == "test":
                st.sidebar.subheader("Audio file")
                file_details = {
                    "Filename": audio_file.name,
                    "FileSize": audio_file.size
                }
                st.sidebar.write(file_details)

            with st.container():
                col1, col2 = st.columns(2)
                with col1:
                    fig = plt.figure(figsize=(10, 2))
                    fig.set_facecolor('#d1d1e0')
                    plt.title("MFCCs")
                    librosa.display.specshow(mfccs, sr=sr, x_axis='time')
                    plt.gca().axes.get_yaxis().set_visible(False)
                    plt.gca().axes.spines["right"].set_visible(False)
                    plt.gca().axes.spines["left"].set_visible(False)
                    plt.gca().axes.spines["top"].set_visible(False)
                    st.write(fig)
                with col2:
                    fig2 = plt.figure(figsize=(10, 2))
                    fig2.set_facecolor('#d1d1e0')
                    plt.title("Mel-log-spectrogram")
                    librosa.display.specshow(Xdb,
                                             sr=sr,
                                             x_axis='time',
                                             y_axis='hz')
                    plt.gca().axes.get_yaxis().set_visible(False)
                    plt.gca().axes.spines["right"].set_visible(False)
                    plt.gca().axes.spines["left"].set_visible(False)
                    plt.gca().axes.spines["top"].set_visible(False)
                    st.write(fig2)

            if model_type == "mfccs":
                st.markdown("## Predictions")
                with st.container():
                    col1, col2, col3, col4 = st.columns(4)
                    mfccs = get_mfccs(path, model.input_shape[-1])
                    mfccs = mfccs.reshape(1, *mfccs.shape)
                    pred = model.predict(mfccs)[0]

                    with col1:
                        if em3:
                            pos = pred[3] + pred[5] * .5
                            neu = pred[2] + pred[5] * .5 + pred[4] * .5
                            neg = pred[0] + pred[1] + pred[4] * .5
                            data3 = np.array([pos, neu, neg])
                            txt = "MFCCs\n" + get_title(data3, CAT3)
                            fig = plt.figure(figsize=(5, 5))
                            COLORS = color_dict(COLOR_DICT)
                            plot_colored_polar(fig,
                                               predictions=data3,
                                               categories=CAT3,
                                               title=txt,
                                               colors=COLORS)
                            # plot_polar(fig, predictions=data3, categories=CAT3,
                            # title=txt, colors=COLORS)
                            st.write(fig)
                    with col2:
                        if em6:
                            txt = "MFCCs\n" + get_title(pred, CAT6)
                            fig2 = plt.figure(figsize=(5, 5))
                            COLORS = color_dict(COLOR_DICT)
                            plot_colored_polar(fig2,
                                               predictions=pred,
                                               categories=CAT6,
                                               title=txt,
                                               colors=COLORS)
                            # plot_polar(fig2, predictions=pred, categories=CAT6,
                            #            title=txt, colors=COLORS)
                            st.write(fig2)
                    with col3:
                        if em7:
                            model_ = load_model("model4.h5")
                            mfccs_ = get_mfccs(path, model_.input_shape[-2])
                            mfccs_ = mfccs_.T.reshape(1, *mfccs_.T.shape)
                            pred_ = model_.predict(mfccs_)[0]
                            txt = "MFCCs\n" + get_title(pred_, CAT7)
                            fig3 = plt.figure(figsize=(5, 5))
                            COLORS = color_dict(COLOR_DICT)
                            plot_colored_polar(fig3,
                                               predictions=pred_,
                                               categories=CAT7,
                                               title=txt,
                                               colors=COLORS)
                            # plot_polar(fig3, predictions=pred_, categories=CAT7,
                            #            title=txt, colors=COLORS)
                            st.write(fig3)
                    with col4:
                        if gender:
                            with st.spinner('Wait for it...'):
                                gmodel = load_model("model_mw.h5")
                                gmfccs = get_mfccs(path,
                                                   gmodel.input_shape[-1])
                                gmfccs = gmfccs.reshape(1, *gmfccs.shape)
                                gpred = gmodel.predict(gmfccs)[0]
                                gdict = [["female", "woman.png"],
                                         ["male", "man.png"]]
                                ind = gpred.argmax()
                                txt = "Predicted gender: " + gdict[ind][0]
                                img = Image.open("images/" + gdict[ind][1])

                                fig4 = plt.figure(figsize=(3, 3))
                                fig4.set_facecolor('#d1d1e0')
                                plt.title(txt)
                                plt.imshow(img)
                                plt.axis("off")
                                st.write(fig4)

            # if model_type == "mel-specs":
            # st.markdown("## Predictions")
            # st.warning("The model in test mode. It may not be working properly.")
            # if st.checkbox("I'm OK with it"):
            #     try:
            #         with st.spinner("Wait... It can take some time"):
            #             global tmodel
            #             tmodel = load_model_cache("tmodel_all.h5")
            #             fig, tpred = plot_melspec(path, tmodel)
            #         col1, col2, col3 = st.columns(3)
            #         with col1:
            #             st.markdown("### Emotional spectrum")
            #             dimg = Image.open("images/spectrum.png")
            #             st.image(dimg, use_column_width=True)
            #         with col2:
            #             fig_, tpred_ = plot_melspec(path=path,
            #                                         tmodel=tmodel,
            #                                         three=True)
            #             st.write(fig_, use_column_width=True)
            #         with col3:
            #             st.write(fig, use_column_width=True)
            #     except Exception as e:
            #         st.error(f"Error {e}, model is not loaded")

    elif website_menu == "Project description":
        import pandas as pd
        import plotly.express as px
        st.title("Project description")
        st.subheader("GitHub")
        link = '[GitHub repository of the web-application]' \
               '(https://github.com/CyberMaryVer/speech-emotion-webapp)'
        st.markdown(link, unsafe_allow_html=True)

        st.subheader("Theory")
        link = '[Theory behind - Medium article]' \
               '(https://talbaram3192.medium.com/classifying-emotions-using-audio-recordings-and-python-434e748a95eb)'
        st.markdown(link + ":clap::clap::clap: Tal!", unsafe_allow_html=True)
        with st.expander("See Wikipedia definition"):
            components.iframe(
                "https://en.wikipedia.org/wiki/Emotion_recognition",
                height=320,
                scrolling=True)

        st.subheader("Dataset")
        txt = """
            This web-application is a part of the final **Data Mining** project for **ITC Fellow Program 2020**. 

            Datasets used in this project
            * Crowd-sourced Emotional Mutimodal Actors Dataset (**Crema-D**)
            * Ryerson Audio-Visual Database of Emotional Speech and Song (**Ravdess**)
            * Surrey Audio-Visual Expressed Emotion (**Savee**)
            * Toronto emotional speech set (**Tess**)    
            """
        st.markdown(txt, unsafe_allow_html=True)

        df = pd.read_csv("df_audio.csv")
        fig = px.violin(df,
                        y="source",
                        x="emotion4",
                        color="actors",
                        box=True,
                        points="all",
                        hover_data=df.columns)
        st.plotly_chart(fig, use_container_width=True)

        st.subheader("FYI")
        st.write(
            "Since we are currently using a free tier instance of AWS, "
            "we disabled mel-spec and ensemble models.\n\n"
            "If you want to try them we recommend to clone our GitHub repo")
        st.code(
            "git clone https://github.com/CyberMaryVer/speech-emotion-webapp.git",
            language='bash')

        st.write(
            "After that, just uncomment the relevant sections in the app.py file "
            "to use these models:")

    elif website_menu == "Our team":
        st.subheader("Our team")
        st.balloons()
        col1, col2 = st.columns([3, 2])
        with col1:
            st.info("*****@*****.**")
            st.info("*****@*****.**")
            st.info("*****@*****.**")
        with col2:
            liimg = Image.open("images/LI-Logo.png")
            st.image(liimg)
            st.markdown(
                f""":speech_balloon: [Maria Startseva](https://www.linkedin.com/in/maria-startseva)""",
                unsafe_allow_html=True)
            st.markdown(
                f""":speech_balloon: [Tal Baram](https://www.linkedin.com/in/tal-baram-b00b66180)""",
                unsafe_allow_html=True)
            st.markdown(
                f""":speech_balloon: [Asher Holder](https://www.linkedin.com/in/asher-holder-526a05173)""",
                unsafe_allow_html=True)

    elif website_menu == "Leave feedback":
        st.subheader("Leave feedback")
        user_input = st.text_area("Your feedback is greatly appreciated")
        user_name = st.selectbox(
            "Choose your personality",
            ["checker1", "checker2", "checker3", "checker4"])

        if st.button("Submit"):
            st.success(f"Message\n\"\"\"{user_input}\"\"\"\nwas sent")

            if user_input == "log123456" and user_name == "checker4":
                with open("log0.txt", "r", encoding="utf8") as f:
                    st.text(f.read())
            elif user_input == "feedback123456" and user_name == "checker4":
                with open("log.txt", "r", encoding="utf8") as f:
                    st.text(f.read())
            else:
                log_file(user_name + " " + user_input)
                thankimg = Image.open("images/sticky.png")
                st.image(thankimg)

    else:
        import requests
        import json

        url = 'http://api.quotable.io/random'
        if st.button("get random mood"):
            with st.container():
                col1, col2 = st.columns(2)
                n = np.random.randint(1, 1000, 1)[0]
                with col1:
                    quotes = {
                        "Good job and almost done":
                        "checker1",
                        "Great start!!":
                        "checker2",
                        "Please make corrections base on the following observation":
                        "checker3",
                        "DO NOT train with test data":
                        "folk wisdom",
                        "good work, but no docstrings":
                        "checker4",
                        "Well done!":
                        "checker3",
                        "For the sake of reproducibility, I recommend setting the random seed":
                        "checker1"
                    }
                    if n % 5 == 0:
                        a = np.random.choice(list(quotes.keys()), 1)[0]
                        quote, author = a, quotes[a]
                    else:
                        try:
                            r = requests.get(url=url)
                            text = json.loads(r.text)
                            quote, author = text['content'], text['author']
                        except Exception as e:
                            a = np.random.choice(list(quotes.keys()), 1)[0]
                            quote, author = a, quotes[a]
                    st.markdown(f"## *{quote}*")
                    st.markdown(f"### ***{author}***")
                with col2:
                    st.image(image=f"https://picsum.photos/800/600?random={n}")
  axis=alt.Axis(title='Mes')),
  y=alt.Y('TOTALES', axis=alt.Axis(title='Total')),
  color=alt.Color('año:O', scale=alt.Scale(range=['#fcba03', '#fc3103'])),
  tooltip = ['TOTALES','año', 'mes']
)
tipoAve = aves[aves['NOMBRE COMUN']== select_aves].STATUS.unique()
if st.checkbox('Mostrar gráfico', True, key=1):
  st.markdown("### Monitoreo de %s " % (select_aves))
  st.markdown("Está clasificada como %s " % (tipoAve[0]))
  st.altair_chart(grafico, use_container_width=True)


"""
## Mapa de Aves por zonas"""
import streamlit.components.v1 as components
components.iframe("https://bitsviajeros.com/mapas/pantanos/",height=700)

# VISITANTES A PANTANOS DE VILLA 2019

# visitantes = pd.read_csv('Visitantes-2019.csv')

# visitantes.set_index('MES', inplace= True)

# visitantes_tipo = visitantes.T

# visitantes_tipo.loc['Visitantes_por_mes']= visitantes_tipo.sum()

# visitantes_tipo['Total_año'] = visitantes_tipo.sum(axis=1)

# visitantes_tipo.columns
Beispiel #24
0
with col2:
    st.image(
        'https://challengepost-s3-challengepost.netdna-ssl.com/photos/production/challenge_photos/001/380/923/datas/full_width.png'
    )

with col2:
    st.markdown(
        '## Dynamically Visualize South Korea COVID-19 data :mask: using TigerGraph , Graphistry  and Streamlit :tiger::chart::balloon:'
    )

with col3:
    st.write('Made with :heart: by')
    st.write('José Manuel Nápoles')
    st.write('[@napoles3d]((https://twitter.com/napoles3d))')

components.iframe(iframe_url, width=1200, height=600)

with st.beta_expander('Subgraph'):
    st.write('Subgraph for patient:', pat_id)
    pv_static(got_net)
    '''
    This subgraph is made with a component developed especially for this hackaton.
    The component its called **stvis** and can be installed by:
    '''
    st.code('pip install stvis')
    st.write('https://github.com/napoles-uach/stvis')

with st.beta_expander('Map for Contacts'):
    px_static(fig, width=1200)
    '''
    This subgraph is made with a component developed especially for this hackaton.
    return [df.min(), df.max()]

@st.cache
def data_overview():
    result = conn.runInstalledQuery('data_overview', timeout = 16000)
    data = pd.DataFrame(result[0]['@@edgeList'])
    g = graphistry.edges(data, 'from_id', 'to_id')
    graph = g.plot(render=False)
    return graph

if graph_option == 'Data overview':
    st.title('Take a look of the data')
    graph = data_overview()
    st.write("**You can see all airport vertices and edges in graphistry window below. Click to check out vertex and edge information.**")
    st.markdown('To explore shortest path or centrality of the airport, please select on dropdown box in sidebar.:sunglasses:')
    components.iframe(graph, width=1200, height=600)

# shortest path option
elif graph_option == "Shortest path":
    path = st.sidebar.radio('',['shortest path unweight', 'shortest path weighted'], index = 0)
    if path == 'shortest path weighted':
        st.title("Shortest path with weighted")
        weighted_path(conn, country)
    elif path == 'shortest path unweight':
        shortest_path_unweighted(conn)
    

# centrality measurement
elif graph_option == "Centrality":
    #sidebar
    country_opt = sidebar.selectbox('Choose a country', country)
Beispiel #26
0
def app():
    menu2 = ['Análisis 1', 'Análisis 2',
             'Análisis 3', 'Análisis 4', 'Análisis 5']
    st.subheader('Seleccione el análisis que desea visualizar: ')
    choice = st.selectbox(
        'Seleccione el analisis de la pregunta que desee del reto: ', menu2)
    if choice == "Análisis 1":

        st.header("¿De qué manera se ha visto afectado el consumo y la producción de frutas y hortalizas durante la pandemia con respecto a años anteriores?")
        st.markdown('###')
        st.subheader('Jupyter Notebooks: ')

        col1, col2, col3 = st.beta_columns(3)

        if col1.checkbox('Variación Consumo/Precio'):
            st.markdown(
                '*Desmarque la casilla para poder seleccionar otro notebook*')
            HtmlFile = open('./data/analisis/a1/analisis1.html',
                            'r', encoding='utf-8')
            source_code = HtmlFile.read()
            stc.html(source_code, width=1400, height=650, scrolling=True)
        elif col2.checkbox('Consumo vs Producción'):
            st.markdown(
                '*Desmarque la casilla para poder seleccionar otro notebook*')
            HtmlFile = open('./data/analisis/a1/analisis1_2.html',
                            'r', encoding='utf-8')
            source_code = HtmlFile.read()
            stc.html(source_code, width=1400, height=650, scrolling=True)

        elif col3.checkbox('Composición Atmosférica'):
            st.markdown(
                '*Desmarque la casilla para poder seleccionar otro notebook*')
            HtmlFile = open('./data/analisis/a1/analisis1_3.html',
                            'r', encoding='utf-8')
            source_code = HtmlFile.read()
            stc.html(source_code, width=1400, height=650, scrolling=True)
        else:
            pass

        st.markdown('##')

        st.markdown("""
        La pandemia ha impulsado la búsqueda de un estilo de vida más saludable que tiene como pilar fundamental una alimentación rica en frutas y verduras. Un síntoma de esta tendencia son campañas como la de la Federación Española de Asociaciones de Productores Exportadores de Frutas y Hortalizas (Fepex) llevó a cabo en abril de 2020 la campaña ‘Vive Saludablemente. Frutas y Verduras '' con el objetivo de “impulsar hábitos de consumo saludables y mostrar la riqueza y variedad de la producción hortofrutícola nacional” y buscando en estos alimentos un aliado contra la pandemia. La campaña sumaba en mayo 120 empresas adheridas.

        Con la finalidad de poder analizar cómo afectó la pandemia al mercado agrícola, más en concreto la variación del consumo y precio de frutas y hortalizas, se incluye a continuación un informe general que compara la variación de 2020 con 2019 y de 2019 con 2018 por cada comunidad autónoma y producto.

        """)

        st.markdown('##')

        stc.iframe("https://app.powerbi.com/view?r=eyJrIjoiMjc0ODAzMjgtOWEwNS00MjVkLWIzZTUtNTUwNjc1Mjc1YjAxIiwidCI6IjZhZmVhODVkLWMzMjMtNDI3MC1iNjlkLWE0ZmIzOTI3YzI1NCIsImMiOjl9", height=635, width=1200)

        st.markdown('##')
        
        st.markdown("""El consumo total de frutas y de hortalizas se disparó en el mes de abril alcanzando valores de crecimiento del 35.56 % y el 44.04% respectivamente, valores que disminuyeron con la desescalada hasta estabilizarse con la llegada de la “nueva normalidad”.  
        """)

        st.markdown('##')

        st.image('./img/img1.png', use_column_width='auto')

        st.markdown('##')

        st.markdown("""
        Las frutas que más se consumieron fueron aquellas con más vitamina C (como es el caso de las naranjas) al igual que limones, manzanas, plátanos y peras. Resulta muy interesante el caso de la nectarina que en el mes de marzo había sufrido una caída del 11% para pasar a un crecimiento del 165% en abril. Al igual que la nectarina, en la tabla de la izquierda (top 10 crecimientos del consumo), también aparecen otras frutas de hueso como el melocotón o el albaricoque.
        Sin embargo, tal y como se observa en la tabla de la derecha (top 10 caídas del consumo) , las fresas protagonizaron una dramática caída de la demanda tanto en el mercado interior como de exportación, coincidente además con el periodo de máxima producción.
        En cuanto a las hortalizas, las más consumidas fueron aquellas consideradas más saludables como las coles, el brócoli, las zanahorias, las berenjenas o los calabacines. Llama la atención el caso de Navarra y la Rioja por el cambio brusco en sus hábitos alimentarios (aumento masivo de coles en Navarra y de ciruelas en la Rioja).
        
        """)

        st.markdown('##')

        st.image('./img/img2.png',use_column_width='auto')

        st.markdown('##')

        st.markdown("""
        Al mismo tiempo la producción se vio afectada por la falta de jornaleros, mano de obra muy específica que provenía en gran parte de personal inmigrante. El cierre de fronteras dificultó que pudieran llevar a cabo su labor. Estas dificultades afectaron a la producción del año 2020, que se vio reducida con respecto a 2018 y 2019 como se observa en informe presentado a continuación. 
        
        """)
        st.markdown('##')

        stc.iframe("https://app.powerbi.com/view?r=eyJrIjoiZGVkNDBhMzUtYTU4YS00MWVkLWEwNjYtYzRlY2ZiMTVmODhhIiwidCI6IjZhZmVhODVkLWMzMjMtNDI3MC1iNjlkLWE0ZmIzOTI3YzI1NCIsImMiOjl9", height=635, width=1200)

        st.markdown('##')

        st.markdown("""
        Las estrictas normas de seguridad que tenían que seguir los agricultores doblaron los precios de logística y transporte en el campo, además de que tuvieron que asumir la compra de material sanitario de protección (mascarillas y otros productos). Esto provocó que en muchas zonas no se pudiese cubrir la demanda existente de ciertos productos como el melocotón o la nectarina y que se dispararan los precios (explicación en detalle en el análisis 2).
        También afectaron a la producción variables exógenas como la temperatura, la humedad o la contaminación. 
        En el mapa que incluimos a continuación se pueden ver las diferentes estaciones atmosféricas españolas que recogen datos de compuestos químicos, algunos claramente perjudiciales para la producción agrícola, como el dióxido de azufre (SO2) o el dióxido de nitrógeno (NO2) y otros de dudoso efecto como el ozono (O3).

        """)

        st.markdown('##')

        stc.iframe("https://app.powerbi.com/view?r=eyJrIjoiNzRjMzgyZmQtN2YzOC00NjliLWEzZDYtOWFiMmFhYTQ3YjUxIiwidCI6IjZhZmVhODVkLWMzMjMtNDI3MC1iNjlkLWE0ZmIzOTI3YzI1NCIsImMiOjl9", height=635, width=1200)
        
        st.markdown('##')

        st.markdown("""
        Durante los meses del estado de alarma, en el que la población española fue obligada a permanecer en su domicilio, se observa un descenso en las emisiones de compuestos contaminantes como el dióxido de nitrógeno o el dióxido de azufre. Una menor concentración de estos compuestos en la atmósfera favoreció la mejora en la producción agrícola, ya que el exceso de nitrógeno empeora la calidad del aire, del suelo y tiene importantes efectos sobre la salud humana. Es interesante comprobar que el descenso no es homogéneo en todo el país, seguramente como consecuencia de diferencias locales en las medidas de confinamientos adoptadas. Sin embargo, con la desescalada esos valores volvieron a la normalidad. Al igual que disminuyó la polución, se esperaba que también lo hiciese la concentración de ozono. Sin embargo, los datos mostraron el resultado contrario. Durante los meses del estado de alarma, pasó de haber un 7% de concentración a un 9%. La explicación de este fenómeno no es clara pero la posible influencia de otros factores atmosféricos como la temperatura, las precipitaciones, el viento, las horas de sol o las presiones mínimas y máximas en los niveles de polución podrían ser parte de la explicación.

        """)

        st.markdown('##')

        stc.iframe("https://app.powerbi.com/view?r=eyJrIjoiZTNhNTQ2ZGYtNjcxNy00OTA1LWFmMDItOWI5ZTlmMjk3YjhlIiwidCI6IjZhZmVhODVkLWMzMjMtNDI3MC1iNjlkLWE0ZmIzOTI3YzI1NCIsImMiOjl9&amp;pageName=ReportSectionb09c803e00d05d8a769d", height=635, width=1200)

        st.markdown('##')

        st.markdown("""
        Sí parece que existe una correlación entre los diferentes compuestos químicos que se encuentran en la atmósfera y la producción. Para corroborar si esto era así, se representó una matriz de correlación con los datos de la producción y de la composición atmosférica de los 3 últimos años. El resultado fue el siguiente.
        
        """)

        st.markdown('##')

        st.image('./img/img3.png', use_column_width='auto')

        st.markdown('##')

        st.markdown("""
        Si se observa la fila de la producción, existe una correlación negativa (inversamente proporcional) entre la producción y el NO2 y el SO2 (más fuerte en el caso del NO2). Sin embargo, la correlación con el O3 es positiva (directamente proporcional). Los estudios demuestran que la cantidad de O3 en la troposfera en pequeñas cantidades es beneficioso, siempre y cuando no supere unos niveles a partir de los cuales deja de proteger a los cultivos de las plagas. 
        Hacen falta más datos para llegar a una respuesta concluyente sobre el efecto del ozono, pero a priori sabemos que la composición de la atmósfera es una variable a tener en cuenta si se quiere realizar una buena predicción de la producción.
        """)

    elif choice == "Análisis 2":
        st.header(
            'Evolución de los precios en las principales plataformas de distribución de España.')

        st.markdown('##')

        if st.checkbox('Ver Jupyter Notebook'):
            HtmlFile = open('./data/analisis/a2/evol_precios.html',
                            'r', encoding='utf-8')
            source_code = HtmlFile.read()
            stc.html(source_code, width=1400, height=650, scrolling=True)
        else:
            pass

        st.markdown('##')

        st.markdown("""
        El estallido de la Covid-19 y la consecuente crisis sanitaria provocó una bajada inicial de precios. Sin embargo, como ya se vaticinaba en el análisis 1, el aumento de la demanda unido a las dificultades en la producción desembocó en un aumento de la volatilidad de los precios de ciertos alimentos, lo que provocó una inestabilidad del mercado que desembocó finalmente en un escenario alcista con una elevación significativa de los precios en frutas y hortalizas.
         
        """)

        st.markdown('##')

        stc.iframe("https://app.powerbi.com/view?r=eyJrIjoiNDZlZDcwODItMjZjNy00ZmZjLTllNDktOTk1ODU3MjM5YjE4IiwidCI6IjZhZmVhODVkLWMzMjMtNDI3MC1iNjlkLWE0ZmIzOTI3YzI1NCIsImMiOjl9&amp;pageName=ReportSection",height=635,width=1200)

        st.markdown('##')

        st.markdown("""
        La demanda de frutas como fuente de vitaminas incrementó los precios de los cítricos, los melocotones (289.37%), la sandía (58.40%), el melón (82.54%) o la uva (67.32%). El precio del aguacate, considerado por sus grandes propiedades nutricionales como un “superalimento” también creció un 76.41%. También el de ciertas hortalizas como la berenjena (125%) o el calabacín (101%). El temor de la población a la enfermedad también se tradujo en sus hábitos a la hora de realizar la compra, optando por productos envueltos en plástico antes que aquellos que están expuestos (como ocurre con la lechuga (45.59%)).
        
        """)

        st.markdown('##')

        stc.iframe("https://app.powerbi.com/view?r=eyJrIjoiN2JjOTMyMzAtZTM3NC00YzAyLWIzMzYtOGE2NzZjOWVlMzNiIiwidCI6IjZhZmVhODVkLWMzMjMtNDI3MC1iNjlkLWE0ZmIzOTI3YzI1NCIsImMiOjl9",height=635, width=1200)

        st.markdown('##')

        st.markdown("""
        Los precios que se alcanzaron en cada mercado dependieron de muchos factores, entre ellos la capacidad productiva de la comunidad autónoma a la que pertenece el mercado. En Cataluña se produjo una gran demanda de frutas de hueso como la nectarina, pero por la falta de capacidad productiva, los precios subieron. De hecho, si comparamos los precios de las nectarinas o de los melocotones entre mercaMadrid y mercaBarna se comprueba que el precio medio es mayor en el segundo. Este fenómeno justificó la decisión de utilizar fondos covid en el campo catalán para modernizar el regadío y digitalizar el sector.
        
        """)

        st.markdown("""
        En la otra cara de la moneda se encontraba Andalucía con el caso de las fresas de Huelva. Como se explicaba en el análisis 1, el inicio de la crisis sanitaria y la época de recolección coincidieron desencadenando graves problemas en la producción como consecuencia de la falta de mano de obra estacional y, por lo tanto, bajadas en los precios. Todo ello queda perfectamente reflejado en el informe que presentamos a continuación.
        
        """)

        st.markdown("##")

        stc.iframe("https://app.powerbi.com/view?r=eyJrIjoiZjYyNDYyYzctZWI3Yy00NDFiLWI3YmMtYjM2NTgxNTkwZTM0IiwidCI6IjZhZmVhODVkLWMzMjMtNDI3MC1iNjlkLWE0ZmIzOTI3YzI1NCIsImMiOjl9&amp;pageName=ReportSectionab929194a7fa9d1d65ba",height=635,width=1200)


    elif choice == "Análisis 3":
        st.header('¿Qué efecto ha tenido sobre las importaciones/exportaciones de F&H?¿Ha tenido algún efecto especial el periodo de excepción (Marzo, abril y mayo)?')
        
        st.markdown('##')

        if st.checkbox('Ver Jupyter Notebook'):
            HtmlFile = open('./data/analisis/a3/comercio_exterior.html',
                            'r', encoding='utf-8')
            source_code = HtmlFile.read()
            stc.html(source_code, width=1400, height=650, scrolling=True)
        else:
            pass
            
        
        st.markdown('##')

        st.markdown("""
        España fue el primer exportador hortofrutícula de toda la unión europea en el año 2020 y tercero mundial ya que sólo la superan EEUU y China. La mitad de la producción nacional se exporta fuera de nuestras fronteras y principalmente a la Unión Europea sobre todo las hortalizas de invierno además de los cítricos, como hemos podido observar en otro análisis del reto, han subido su demanda debido a la pandemia.
        
        """)

        st.markdown("""
Durante el periodo de enero-diciembre de 2020 y con una pandemia de por medio, el sector agroalimentario español no sólo no redujo sus exportaciones, sino que creció un 5,4% más con respecto al mismo periodo de 2019. En concreto las exportaciones de frutas y hortalizas crecieron en torno a un 7,7% en conjunto. Todo ello con el impacto inicial que causó la covid-19 en el saldo comercial durante los dos primeros meses de la pandemia y que causó el cierre de las fronteras de los países de la UE y su evolución como veremos mas adelante con el auge de España en las exportaciones. En el siguiente PowerBI podemos observas las importaciones/exportaciones de los distintos paises de la UE con respecto a España.
        
        """)

        st.markdown('##')

        stc.iframe("https://app.powerbi.com/view?r=eyJrIjoiZTE0YTU3NjctNzg1ZC00NTlhLTk4YmYtZDQ2NzZkZDczNzc2IiwidCI6IjZhZmVhODVkLWMzMjMtNDI3MC1iNjlkLWE0ZmIzOTI3YzI1NCIsImMiOjl9", height=635, width=1200)

        st.markdown('##')

        st.markdown("""
        Como podemos observar, los países que más frutas y hortalizas importaron de España durante el periodo de marzo a noviembre fueron: Alemania, Francia, Holanda, Italia y Portugal. Sin embargo, la mayor parte de las transacciones se produjeron a partir de mayo como hemos mencionado anteriormente tras empezar la desescalada generalizada por parte de todos los países de la unión. Por ejemplo, en Alemania el 67,8% de las importaciones provenientes de España durante el periodo mencionado anteriormente se produjeron a partir de dicho mes clave para la desescalada. Por otro lado, aquellos países que más frutas y hortalizas exportaron hacia España fueron Francia, Portugal, Países Bajos e Italia.
        """)

        st.subheader("¿Por qué ocurrió el boom exportador de España a la UE durante el final de la cuarentena?")

        st.markdown("""
        Durante los peores meses del confinamiento que fueron marzo y abril para el sector (dado que la cadena de suministro agroalimentaria está integrada y opera a través de las fronteras) el cierre fronterizo bloqueó el suministro y perturbó terriblemente la actividad durante estos meses tanto a nivel logístico como a nivel productivo. Al ser un sector donde los trabajadores suelen ser jornaleros de origen inmigrante y estar restringido el movimiento de personas entre países provocó una escasez de mano de obra. Estos obstáculos acabaron desencadenando en una rotura de stock en ciertas frutas y hortalizas en la Unión Europea sobre todo en los cítricos, fruta que España es la que más exporta a la UE y que aumentó su demanda exponencialmente durante el confinamiento. Por ello en mayo, cuando se empezaron a relajar las medidas y a abrir las fronteras entre países a través de corredores especiales para evitar desabastecimiento en la UE, España experimentó un crecimiento exponencial de su exportaciones de las frutas y hortalizas.
        
        """)

        st.markdown("""
        La necesidad de importar frutas y hortalizas por parte de los distintos países y el cambio de patrones de consumo provocó que el balance comercial en el sector agroalimentario de España cerrase 2020 en positivo con 14.025 millones de euros aproximadamente. Para concluir, la exportación de hortalizas en nuestro país durante 2020 creció un 4,6%. Por otro lado, la exportación de frutas en ese mismo periodo creció un 10% más que en 2019. El valor de los productos más exportados fue el de los cítricos debido a que durante la covid-19 ha aumentado el consumo de productos ricos en vitaminas debido al confinamiento domiciliario y una alimentación más saludable.
        
        
        """)

        st.markdown('##')

        stc.iframe("https://app.powerbi.com/view?r=eyJrIjoiZmIxNTM4N2EtZGQ3NS00ZmYyLWIxNTctYjEwMjRhNGE0ODEzIiwidCI6IjZhZmVhODVkLWMzMjMtNDI3MC1iNjlkLWE0ZmIzOTI3YzI1NCIsImMiOjl9", height=635, width=1200)


    elif choice == "Análisis 4":
        st.header(
            '¿Existe correlación entre los casos de COVID-19 y las importaciones/exportaciones a nivel de la Unión Europea?')

        st.markdown('##')

        if st.checkbox('Ver Jupyter Notebook'):
            HtmlFile = open('./data/analisis/a4/covid_19_comercioExt.html',
                            'r', encoding='utf-8')
            source_code = HtmlFile.read()
            stc.html(source_code, width=1400, height=650, scrolling=True)
        else:
            pass

        st.markdown('##')

        st.markdown("""
        Tras realizar un estudio de correlaciones entre los datos de la COVID-19 y el comercio exterior en la Unión Europea se ha llegado a la conclusión de que existe una correlación positiva entre el número de casos y las importaciones/exportaciones. Obteniendo resultados diferentes si comparamos los casos con el valor de la transacción o el número de kilos exportados/importados:
        
        """)

        st.markdown('##')

        st.image('./img/img4.png', use_column_width=True)

        st.markdown('##')

        st.markdown("""
        La correlación entre el número de kilos importados por parte de España desde los distintos países de la UE es de 0.28. Por otro lado, la correlación entre el número de kilos exportados por España a los diferentes países de la UE aumenta hasta 0.32 . Es decir, por cada 100 kg de frutas o verduras exportadas había en torno a 32 casos de Covid-19 en Europa. Además, comparando el valor en euros de las importaciones/exportaciones con el número de casos se ha obtenido prácticamente el mismo grado de correlación, por cada euro en comercio exterior se incrementa el número de casos en 0.26
        
        """)

        st.header("¿ A qué podría deberse estos resultados con respecto a la correlación y España?"
        
        )

        st.markdown("""
        Los diferentes ritmos de la recuperación de los distintos países de la Unión Europea durante el primer confinamiento domiciliario, sumado a las restricciones de movilidad, la escasa mano de obra, la dificultad logística y el gran problema de la rotura de stock además de la mayor demanda de consumo de F&H en toda la UE debido a una mejora de los hábitos alimenticios debido al mayor sedentarismo que suponía el confinamiento domiciliario, generó una fuerte dependencia hacia las importaciones por parte de los distintos países de la Unión Europea, sobre todo con respecto a España. Por ello la correlación aunque sea débilmente positiva, es suficiente para poder realizar hipótesis sobre ella. Los corredores especiales durante la desescalada, además de la conocida capacidad productiva de F&H en España supusieron una dependencia al comercio exterior por parte de los países europeos al no poder satisfacer la demanda nacional con su producción. 
        
        
        """)

        st.markdown('##')

        stc.iframe("https://app.powerbi.com/view?r=eyJrIjoiZmIxNTM4N2EtZGQ3NS00ZmYyLWIxNTctYjEwMjRhNGE0ODEzIiwidCI6IjZhZmVhODVkLWMzMjMtNDI3MC1iNjlkLWE0ZmIzOTI3YzI1NCIsImMiOjl9", height=635, width=1200)



    elif choice == "Análisis 5":
        st.header('El estado de alarma revoluciona los hábitos de consumo')
        
        st.markdown('##')

        st.subheader('Jupyter Notebooks: ')

        st.markdown

        col4,col5 = st.beta_columns(2)


        if col4.checkbox('Estudio patrones de consumo'):
            HtmlFile = open('./data/analisis/a5/patrones_consumo_1.html',
                            'r', encoding='utf-8')
            source_code = HtmlFile.read()
            stc.html(source_code, width=1400, height=650, scrolling=True)



        elif col5.checkbox('Modelo Machine Learning Consumo'):
            HtmlFile = open('./data/analisis/a5/patrones_consumo_extra.html',
                            'r', encoding='utf-8')
            source_code = HtmlFile.read()
            stc.html(source_code, width=1400, height=650, scrolling=True)

        else:
            pass


        st.markdown('##')

        st.markdown("""
        
        Los hábitos de consumo han ido cambiando en la última década con el boom del e-commerce. Sin embargo, hay una serie de productos cuya venta no había cuajado a través del canal online, como los pertenecientes al sector de la alimentación de productos frescos. En marzo de 2020, las grandes distribuidoras re-adaptaron sus cadenas de distribución para poder repartir este tipo de alimentos perecederos de forma rápida en los hogares españoles sometidos al confinamiento.

        """)

        st.markdown('##')

        stc.iframe("https://app.powerbi.com/view?r=eyJrIjoiMjIwOGEwNWItZWNhYy00NmYyLWFjODEtMzRlOTg2YjkyZTg3IiwidCI6IjZhZmVhODVkLWMzMjMtNDI3MC1iNjlkLWE0ZmIzOTI3YzI1NCIsImMiOjl9&amp;pageName=ReportSection62cbdfda817c90dec869",height=635, width=1200)

        st.markdown('##')

        st.markdown("""
        A continuación, se muestran los meses de mayor penetración por cada canal de venta (internet, supermercados e hipermercados) para el total de frutas, hortalizas y patatas.
        
        """)

        st.markdown('##')

        st.image('./img/img5.png', use_column_width='auto')

        st.markdown('##')

        st.markdown("""
        Se observa que la penetración (% de hogares/familias que compran ese producto) para los distintos tipos de producto fue variando a lo largo del primer confinamiento domiciliario en los distintos canales de venta. En cada uno de ellos la máxima penetración de frutas, hortalizas y patatas se da en el mismo mes. En el caso de internet y supermercados este mes es abril, mientras que de los hipermercados fue en marzo. 
        
        
        """)

        st.markdown("""
        Esto se debe a un fenómeno que todos hemos compartido. En marzo, con el mayor grado de incertidumbre respecto al virus, la gente temía ir a hacer la compra a espacios de tamaño reducido y además tampoco se podía hacer la compra online, ya que está quedó limitada para los grupos de mayor riesgo. Por ello, los consumidores acudían a los hipermercados y de ahí que el mes con mayor penetración fuera marzo. A lo largo de dicho mes la gente fue adaptándose a la situación y poco a poco mejoraron los sistemas de distribución que permitieron que abril fuese el mes en el que internet tuvo una mayor penetración de mercado.
        
        """)

        st.markdown('##')

        stc.iframe("https://app.powerbi.com/view?r=eyJrIjoiMDdhMjk5ZDUtOTBkMy00ZTQwLTg5YmUtYmQ1NTFjN2E1MGQwIiwidCI6IjZhZmVhODVkLWMzMjMtNDI3MC1iNjlkLWE0ZmIzOTI3YzI1NCIsImMiOjl9&amp;pageName=ReportSection205c65e8e1a505790279", height=635,width=1200)

        st.markdown('##')

        st.markdown("""
        Si se estudia la tendencia de productos agrícolas como la col, el brócoli o la zanahoria por internet y previamente al estado de alarma, se observa que es la misma todos los años. Esto ocurre de la misma manera en el gráfico de arriba para el canal físico. Sin embargo, llega el estado de alarma y se dispara la penetración de mercado por internet muy por encima de los valores normales correspondientes a esas fechas en años anteriores. Esto no ocurre en el caso del supermercado, donde la tendencia fue la misma.
        
        
        """)

        st.header("La Inteligencia Artificial como herramienta de apoyo en la toma de decisiones y en la digitalización del sector agrario")

        st.markdown('##')

        st.subheader("Aproximación 1: Modelo de Machine Learning para la predicción del consumo por producto y CCAA")

        st.markdown("""
        Para ello se llevó a cabo un modelo para la predicción del consumo (variable objetivo o target) en base al precio medio de cada producto y comunidad autónoma (características o features). 
        
        """)

        st.markdown("""
        Los datos para entrenar el modelo está comprendida por meses entre el 2018 y 2020. Previo a la introducción de los datos en el modelo, fue necesario llevar a cabo una serie de pasos:
        
        
        """)


        st.markdown("""
        - Convertir las variables de texto en variables categóricas: con la función OneHotEncoder que convierte las columnas ‘Producto’ y ‘Comunidad Autónoma’, creando una columna para cada valor distinto que exista en la característica que estamos codificando (por ejemplo, una columna por producto) y, para cada registro, marcar con un 1 la columna a la que pertenezca dicho registro y dejar las demás con 0. 
        - Eliminar la variable fecha y dejar las variables año y mes en columnas separadas (dos variables diferentes) y se ordena el dataset por fechas.
        - Dividir el dataset en train y test (80% y 20% respectivamente)
        - Inicializar 3 modelos diferentes de regresión para compararlos entre ellos: LGBMRegressor, XGBoostRegressor, CatBoostRegressor
        - Se construye un ‘pipeline’ que permite entrenar el modelo pasando por varias funciones. Esto es necesario ya que antes los valores deben estandarizarse antes de introducirse en el modelo.
        
        """)

        st.markdown("""
        Entonces se entrena el modelo y se obtienen las métricas tanto por separación train/test como por validación cruzada que evalúa los resultados del modelo entrenando con todos los datos en varias iteraciones (de forma que garantiza que el resultado es independiente de la partición entre datos de train y test). El score (que por defecto en los problemas de regresión es el r2 o coeficiente de determinación) fue el siguiente:
        
        """)

        st.image('./img/img6.png',use_column_width='auto')

        st.markdown("""
        El modelo con mayor score es el CatBoost por lo que se calcula el score para ese modelo por  validación cruzada (representación del score si se entrenase con todo el dataset). El score de validación cruzada es -0.171, es decir, el modelo predice por debajo de la media, es inservible.
        
        """)

        st.markdown("""
        Por esa razón, resulta necesario realizar una búsqueda de meta-parámetros, a través de GridSearchCV, donde se introduce un intervalo con varios parámetros y el modelo obtiene la combinación de ellos que maximiza el r2.
        
        """)

        st.image('./img/img7.png',use_column_width='auto')

        st.markdown("""
        El r2 score que se obtuvo era muy bajo (casi cercano a 0) por lo que el modelo no resultaba útil. Esto puede deberse a que se ha entrenado con todos los datos sin diferenciar el lugar de compra del cual proceden los productos. Por eso resulta fundamental realizar más modelos para los datos, pero segmentados por lugar de compra ya que cada uno sigue una tendencia diferente. 
        
        """)

        st.markdown("""
        Por eso, se realizó la segunda aproximación: la predicción del consumo por producto en un canal de compra específico (internet fue el escogido).
        
        
        """)

        st.subheader("Aproximación 2. Modelo de Machine Learning para la predicción de consumo en el canal de venta online (Internet)")


        st.markdown("""
        Para ello, se realizaron los mismos pasos que en el caso anterior, con la diferencia de que se aumentó la serie temporal (añadiendo datos desde 2013 a 2020). El resultado fue el siguiente:
        
        """)

        st.image('./img/img8.png',use_column_width='auto')

        st.markdown("Utilizando GridSearchCV para encontrar los meta-parámetros óptimos se obtuvo el siguiente score: ")

        st.image('./img/img9.png',use_column_width='auto')

        st.markdown("Con un modelo que tiene un r2 score de 0.707 se puede realizar una buena predicción del consumo. ")

        st.markdown("""
        La diferencia en el score de los dos modelos reside en un principio fundamental del Machine Learning: no se puede tener una buena predicción con datos que se diferencian mucho de la distribución que venía dándose años atrás. Por esa razón es muy importante tener un buen histórico de datos como ocurría en el segundo modelo que entrenaba con los datos (entre 2013 y 2020) obtenidos mediante el scraping del MAPA.
        
        """)

        st.markdown("""
        Estas predicciones resultan muy útiles para el mercado agrícola donde la volatilidad e impredictibilidad de los precios es en general contraproducente para la cadena alimentaria, y es especialmente crítica para los eslabones productores.
        
        """)

        st.markdown(""""
        Por eso resulta tan interesante incorporar también el AutoML donde se puede subir cualquier archivos csv y obtener predicciones de la variable que se desee, permitiendo así conocer las perspectivas de futuro del sector. Esta es la razón por la cual decidimos construir nuestra plataforma Datacrop Advanced Agro-Analytics Service (www.platform.datacrop.es) , con la finalidad de realizar toma de decisiones más efectiva y a destinar los recursos conforme a las predicciones obtenidas, de forma que se eviten situaciones como las que se dieron durante el estado de alarma, en las que no se pudo atender la demanda de ciertos productos. La plataforma no solo permite realizar predicciones recurriendo al AutoML, sino también tener una visualización completa de cómo las variables se relacionan entre sí.
        
        """)

        st.subheader("Conclusiones obtenidas en el análisis del reto")

        st.markdown("""
        Desde el comienzo del estado de alarma, los hábitos de compra cambiaron , el mercado interno no era capaz de absorber la producción debido al cierre del canal HORECA (Hoteles, Restaurantes y Cafeterías), el cierre de fronteras y las limitaciones de tránsito y transporte internacional limitaban considerablemente las exportaciones, y en este periodo de incertidumbre, otros países con medidas de prevención frente al coronavirus más laxas aprovechan para introducir sus productos en mercados que antes nos eran propios. Toda esta serie de hechos que se sucedieron en un escenario desconocido evidenciaron la necesidad de la digitalización del sector agrario, convirtiéndose esta en una herramienta transversal para la recuperación y modernización del sector agrario español tras la covid-19.
        
        """)




    else:
        st.info("Esperando a que seleccione alguna de las preguntas...")

    # Remover el footer de made with streamlit
    hide_footer_style = """
        <style>
        .reportview-container .main footer {visibility: hidden;}    
        """
    st.markdown(hide_footer_style, unsafe_allow_html=True)
def plot_county(county):
    import numpy as np
    FIPSs = confirmed.groupby(['Province_State', 'Admin2']).FIPS.unique().apply(pd.Series).reset_index()
    FIPSs.columns = ['State', 'County', 'FIPS']
    FIPSs['FIPS'].fillna(0, inplace = True)
    FIPSs['FIPS'] = FIPSs.FIPS.astype(int).astype(str).str.zfill(5)
    @st.cache(ttl=3*60*60, suppress_st_warning=True)
    def get_testing_data(County):
        apiKey = '9fe19182c5bf4d1bb105da08e593a578'
        if len(County) == 1:
            #print(len(County))
            f = FIPSs[FIPSs.County == County[0]].FIPS.values[0]
            #print(f)
            path1 = 'https://data.covidactnow.org/latest/us/counties/'+f+'.OBSERVED_INTERVENTION.timeseries.json?apiKey='+apiKey
            #print(path1)
            df = json.loads(requests.get(path1).text)
            #print(df.keys())
            data = pd.DataFrame.from_dict(df['actualsTimeseries'])
            data['Date'] = pd.to_datetime(data['date'])
            data = data.set_index('Date')
            #print(data.tail())
            try:
                data['new_negative_tests'] = data['cumulativeNegativeTests'].diff()
                data.loc[(data['new_negative_tests'] < 0)] = np.nan
            except: 
                data['new_negative_tests'] = np.nan
                st.text('Negative test data not avilable')
            data['new_negative_tests_rolling'] = data['new_negative_tests'].fillna(0).rolling(14).mean()
            
            
            try:
                data['new_positive_tests'] = data['cumulativePositiveTests'].diff()
                data.loc[(data['new_positive_tests'] < 0)] = np.nan
            except: 
                data['new_positive_tests'] = np.nan
                st.text('test data not avilable')
            data['new_positive_tests_rolling'] = data['new_positive_tests'].fillna(0).rolling(14).mean()
            data['new_tests'] = data['new_negative_tests']+data['new_positive_tests']
            data['new_tests_rolling'] = data['new_tests'].fillna(0).rolling(14).mean()
            data['testing_positivity_rolling'] = (data['new_positive_tests_rolling'] / data['new_tests_rolling'])*100
            #data['testing_positivity_rolling'].tail(14).plot()
            #plt.show()
            return data['new_tests_rolling'], data['testing_positivity_rolling'].iloc[-1:].values[0]
        elif (len(County) > 1) & (len(County) < 5):
            new_positive_tests = []
            new_negative_tests = []
            new_tests = []
            for c in County:
                f = FIPSs[FIPSs.County == c].FIPS.values[0]
                path1 = 'https://data.covidactnow.org/latest/us/counties/'+f+'.OBSERVED_INTERVENTION.timeseries.json?apiKey='+apiKey
                df = json.loads(requests.get(path1).text)
                data = pd.DataFrame.from_dict(df['actualsTimeseries'])
                data['Date'] = pd.to_datetime(data['date'])
                data = data.set_index('Date')
                try:
                    data['new_negative_tests'] = data['cumulativeNegativeTests'].diff()
                    data.loc[(data['new_negative_tests'] < 0)] = np.nan
                except: 
                    data['new_negative_tests'] = np.nan
                    #print('Negative test data not avilable')
                    
                try:
                    data['new_positive_tests'] = data['cumulativePositiveTests'].diff()
                    data.loc[(data['new_positive_tests'] < 0)] = np.nan
                except: 
                    data['new_positive_tests'] = np.nan
                    #print('Negative test data not avilable')
                data['new_tests'] = data['new_negative_tests']+data['new_positive_tests']
                
                new_positive_tests.append(data['new_positive_tests'])
                #new_negative_tests.append(data['new_tests'])
                new_tests.append(data['new_tests'])

            new_positive_tests_rolling = pd.concat(new_positive_tests, axis = 1).sum(axis = 1)
            new_positive_tests_rolling = new_positive_tests_rolling.fillna(0).rolling(14).mean()
        
            new_tests_rolling = pd.concat(new_tests, axis = 1).sum(axis = 1)
            new_tests_rolling = new_tests_rolling.fillna(0).rolling(14).mean()
            
            data_to_show = (new_positive_tests_rolling / new_tests_rolling)*100
            return new_tests_rolling, data_to_show.iloc[-1:].values[0]
        else:
            st.text('Getting testing data for California State')
            path1 = 'https://data.covidactnow.org/latest/us/states/CA.OBSERVED_INTERVENTION.timeseries.json?apiKey='+apiKey
            df = json.loads(requests.get(path1).text)
            data = pd.DataFrame.from_dict(df['actualsTimeseries'])
            data['Date'] = pd.to_datetime(data['date'])
            data = data.set_index('Date')
            
            try:
                data['new_negative_tests'] = data['cumulativeNegativeTests'].diff()
                data.loc[(data['new_negative_tests'] < 0)] = np.nan
            except: 
                data['new_negative_tests'] = np.nan
                print('Negative test data not avilable')
            data['new_negative_tests_rolling'] = data['new_negative_tests'].fillna(0).rolling(14).mean()
            
            
            try:
                data['new_positive_tests'] = data['cumulativePositiveTests'].diff()
                data.loc[(data['new_positive_tests'] < 0)] = np.nan
            except: 
                data['new_positive_tests'] = np.nan
                st.text('test data not avilable')
            data['new_positive_tests_rolling'] = data['new_positive_tests'].fillna(0).rolling(14).mean()
            data['new_tests'] = data['new_negative_tests']+data['new_positive_tests']
            data['new_tests_rolling'] = data['new_tests'].fillna(0).rolling(14).mean()
            data['testing_positivity_rolling'] = (data['new_positive_tests_rolling'] / data['new_tests_rolling'])*100
            return data['new_tests_rolling'], data['testing_positivity_rolling'].iloc[-1:].values[0]
            
    
    testing_df, testing_percent = get_testing_data(County=county)
    county_confirmed = confirmed[confirmed.Admin2.isin(county)]
    #county_confirmed = confirmed[confirmed.Admin2 == county]
    county_confirmed_time = county_confirmed.drop(county_confirmed.iloc[:, 0:12], axis=1).T #inplace=True, axis=1
    county_confirmed_time = county_confirmed_time.sum(axis= 1)
    county_confirmed_time = county_confirmed_time.reset_index()
    county_confirmed_time.columns = ['date', 'cases']
    county_confirmed_time['Datetime'] = pd.to_datetime(county_confirmed_time['date'])
    county_confirmed_time = county_confirmed_time.set_index('Datetime')
    del county_confirmed_time['date']
    #print(county_confirmed_time.head())
    incidence= pd.DataFrame(county_confirmed_time.cases.diff())
    incidence.columns = ['incidence']
    
    #temp_df_time = temp_df.drop(['date'], axis=0).T #inplace=True, axis=1
    county_deaths = deaths[deaths.Admin2.isin(county)]
    population = county_deaths.Population.values.sum()
    
    del county_deaths['Population']
    county_deaths_time = county_deaths.drop(county_deaths.iloc[:, 0:11], axis=1).T #inplace=True, axis=1
    county_deaths_time = county_deaths_time.sum(axis= 1)
    
    county_deaths_time = county_deaths_time.reset_index()
    county_deaths_time.columns = ['date', 'deaths']
    county_deaths_time['Datetime'] = pd.to_datetime(county_deaths_time['date'])
    county_deaths_time = county_deaths_time.set_index('Datetime')
    del county_deaths_time['date']
    
    cases_per100k  = ((county_confirmed_time)*100000/population)
    cases_per100k.columns = ['cases per 100K']
    cases_per100k['rolling average'] = cases_per100k['cases per 100K'].rolling(7).mean()
    
    deaths_per100k  = ((county_deaths_time)*100000/population)
    deaths_per100k.columns = ['deaths per 100K']
    deaths_per100k['rolling average'] = deaths_per100k['deaths per 100K'].rolling(7).mean()
    
    
    incidence['rolling_incidence'] = incidence.incidence.rolling(7).mean()
    metric = (incidence['rolling_incidence']*100000/population).iloc[[-1]]
    st.text('Number of new cases averaged over last seven days = %s' %'{:,.1f}'.format(metric.values[0]))
    st.text("Population under consideration = %s"% '{:,.0f}'.format(population))
    st.text("Total cases = %s"% '{:,.0f}'.format(county_confirmed_time.tail(1).values[0][0]))
    st.text("Total deaths = %s"% '{:,.0f}'.format(county_deaths_time.tail(1).values[0][0]))
    st.text("% test positivity (14 day average)*= "+"%.2f" % testing_percent)
    #print(county_deaths_time.tail(1).values[0])
    #print(cases_per100k.head())
    fig = Figure(figsize=(12,8))
    #fig, ((ax4, ax3),(ax1, ax2)) = plt.subplots(2,2, figsize=(6,4))
    ((ax4, ax3),(ax1, ax2)) = fig.subplots(2,2)
    
    county_confirmed_time.plot(ax = ax1,  lw=4, color = '#377eb8')
    county_deaths_time.plot(ax = ax1,  lw=4, color = '#e41a1c')
    ax1.set_xlabel('Time') 
    ax1.set_ylabel('Number of individuals')
    
    
    
    testing_df.plot(ax = ax2,  lw=4, color = '#377eb8')
    #cases_per100k['cases per 100K'].plot(ax = ax2,  lw=4, linestyle='--', color = '#377eb8')
    #cases_per100k['rolling average'].plot(ax = ax2, lw=4, color = '#377eb8')
    
    #deaths_per100k['deaths per 100K'].plot(ax = ax2,  lw=4, linestyle='--', color = '#e41a1c')
    #deaths_per100k['rolling average'].plot(ax = ax2, lw=4, color = '#e41a1c')
    
    ax2.set_xlabel('Time')
    ax2.set_ylabel('Number of new tests')
    
    incidence.incidence.plot(kind ='bar', ax = ax3, width=1)
    ax3.set_xticklabels(incidence.index.strftime('%b %d'))
    for index, label in enumerate(ax3.xaxis.get_ticklabels()):
        if index % 7 != 0:
            label.set_visible(False)
    for index, label in enumerate(ax3.xaxis.get_major_ticks()):
        if index % 7 != 0:
            label.set_visible(False)
    
    
    
    
    (incidence['rolling_incidence']*100000/population).plot(ax = ax4, lw = 4)
    ax4.axhline(y = 5,  linewidth=2, color='r', ls = '--', label="Threshold for Phase 2:\nInitial re-opening")
    ax4.axhline(y = 1,  linewidth=2, color='b', ls = '--', label="Threshold for Phase 3:\nEconomic recovery")
    ax4.legend(fontsize = 10)
    if (incidence['rolling_incidence']*100000/population).max()< 5.5:
        ax4.set_ylim(0,5.5)
    
    #print(metric)
    
    #incidence['rolling_incidence']
    #ax3.grid(which='both', alpha=1)
    ax1.set_title('(C) Cumulative cases and deaths')
    ax2.set_title('(D) Daily new tests')
    ax3.set_title('(B) Daily incidence (new cases)')
    ax4.set_title('(A) Weekly rolling mean of incidence per 100k')
    ax3.set_ylabel('Number of individuals')
    ax4.set_ylabel('per 100 thousand')

    with _lock:
        if len(county)<6:
            fig.suptitle('Current situation of COVID-19 cases in '+', '.join(map(str, county))+' county ('+ str(today)+')')
        else:
            fig.suptitle('Current situation of COVID-19 cases in California ('+ str(today)+')')
        fig.tight_layout(rect=[0, 0.03, 1, 0.95])
        st.pyplot(fig)
    
    import streamlit.components.v1 as components
    if len(county)<=3:
        for C in county:
            st.text(C)
            f = FIPSs[FIPSs.County == C].FIPS.values[0]
            components.iframe("https://covidactnow.org/embed/us/county/"+f, width=350, height=365, scrolling=False)
Beispiel #28
0
def write():
    """Used to write the page in the app.py file"""

    st.title("Pie and AI - Gujarat Meetups :slightly_smiling_face: ")
    st.markdown("""
            ### Pie and AI is a community in partnership with **deeplearning.ai**
            ### Here are some of the talks and discussions hosted by Pie and AI Gujarat. The sessions held are from various domains of Data Science..!!\n""",
                unsafe_allow_html=True)
    c1, c2, c3 = st.beta_columns((3, 3, 3))

    with c1:
        components.iframe(src="https://www.youtube.com/embed/CmjY1ATKNH0",
                          height=315)
        st.markdown(
            "** True/False Question Generation using NLP - Ramsri Goutham Golla**",
            unsafe_allow_html=True)

        components.iframe(src="https://www.youtube.com/embed/C2wEuFDdQpY",
                          height=315)
        st.markdown("**Grasp The Basics To Become an Expert - Danny Ma**",
                    unsafe_allow_html=True)

        components.iframe(src="https://www.youtube.com/embed/G2XJnfc3XJU",
                          height=315)
        st.markdown("**The Dangers of Dirty Data - Susan Walsh**",
                    unsafe_allow_html=True)

    with c2:
        components.iframe(src="https://www.youtube.com/embed/gIfN-N6OkLA",
                          height=315)
        st.markdown("**Brain vs AI - Giuseppe & Ghaith**",
                    unsafe_allow_html=True)

        components.iframe(src="https://www.youtube.com/embed/TVef8B8ekq4",
                          height=315)
        st.markdown(
            "**Data Visualisation is all about Data Storytelling - Vijay Pravin**",
            unsafe_allow_html=True)

        components.iframe(src="https://www.youtube.com/embed/8oJJNDtazkY",
                          height=315)
        st.markdown(
            "**Artificial Intelligence - 4th Industrial Revolution - Hari Kantipudi**",
            unsafe_allow_html=True)

    with c3:

        components.iframe(src="https://www.youtube.com/embed/rxkOeYwnvv4",
                          height=315)
        st.markdown("**Being a Data Scientist - Thom Ives & Abdul Najeeb**",
                    unsafe_allow_html=True)

        components.iframe(src="https://www.youtube.com/embed/0bC2hk2OB-U",
                          height=315)
        st.markdown(
            "**Algorithmic Decision Making: Why accuracy isn't enough ? - Ansgar **",
            unsafe_allow_html=True)
Beispiel #29
0
def write():
    """Used to write the page in the app.py file"""

    st.title("NLP & Data Science Learnings..!!")

    c1, c2 = st.beta_columns((3, 3))

    with c1:
        components.iframe(
            src=
            "https://www.linkedin.com/embed/feed/update/urn:li:share:6773646149204131841",
            height=520)
        components.iframe(
            src=
            "https://www.linkedin.com/embed/feed/update/urn:li:share:6769956489504333824",
            height=430)
        components.iframe(src="https://www.youtube.com/embed/YLj52vt-wQ4",
                          height=315)

    with c2:
        components.iframe(
            src=
            "https://www.linkedin.com/embed/feed/update/urn:li:ugcPost:6772128459939467264",
            height=450)
        components.iframe(
            src=
            "https://www.linkedin.com/embed/feed/update/urn:li:share:6730097521634418688",
            height=520)
        components.iframe(src="https://www.youtube.com/embed/f2m6Mon0VE8",
                          height=315)
Beispiel #30
0
def Annotation():
    #### NEWS DATA ####
    # Title
    st.subheader(data['title'])

    ####### SCREEN SHOT ########
    if st.button('Screenshot'):
        try:
            chrome_options = webdriver.ChromeOptions()
            chrome_options.binary_location = os.environ.get("GOOGLE_CHROME_BIN")
            chrome_options.add_argument("--headless")
            chrome_options.add_argument("--disable-dev-shm-usage")
            chrome_options.add_argument("--no-sandbox")
            driver = webdriver.Chrome(executable_path=os.environ.get("CHROMEDRIVER_PATH"), chrome_options=chrome_options)

            driver.get(data['url'])
            driver.save_screenshot('my_screenshot.png')
            driver.quit()
            st.image('my_screenshot.png',width=700)
        except:
            st.write('Sorry! Cannot Load the Screenshot.')

    # City
    st.markdown(data['city'])
    # url
    st.write(data['url'])
    components.iframe(data['url'],scrolling=True,height=300)
    # Summary
    st.subheader("Summary")
    st.write(data['summary'])
    # Percent prediction
    try:
        percent = ast.literal_eval(data['percent'])
        percent = pd.DataFrame.from_dict(percent, orient='index')
        percent.columns = ['percent']
        st.bar_chart(percent)
    except:
        st.write("No sentiment has been predicted!")

    # Keywords
    #st.markdown(f"Keywords: <span style='border:1px #f63366 solid;padding:2px;border-radius:3px;'>{data['keywords']}</span>",unsafe_allow_html=True)
    st.write(data['keywords'])

    st.markdown('---') # visual separation

    st.subheader("Text")

    tag_out={}
    obj_out={}
    space_out={}
    time_out={}
    Imp_out={}
    com_out={}
    sent_out={}
    text_sents = ast.literal_eval(data['sents'])
    for i, sent in enumerate(text_sents):
        st.markdown(text_ner(sent['sent']),unsafe_allow_html=True)
        pred = sent['pred']
        st.markdown(f'*<span style="color:grey">Current Model prediction: </span> <span style="color:#f63366;font-size:16px;">{clean_t(pred)}</span>*', unsafe_allow_html=True)
        st.markdown("*<span style='color:grey'>New Tags: </span>*",unsafe_allow_html=True)
        for aspct in ['tag','obj','space','time','Imp']:
            if sent[aspct] != []:
                st.markdown(f"{text_box(clean_t(sent[aspct]))}", unsafe_allow_html=True)
        st.markdown(f"*<span style='color:grey'>Comments: </span><span style='font-size:14px;'>{sent['comment']}</span>*", unsafe_allow_html=True)

        if st.checkbox('Edit',False,f'{x}{i}'):
            st.markdown('---')
            default = sent['tag']
            tag_out[f'{i}'] = st.multiselect('Sentiments',tags,key=i,default= default)
            obj_out[f'{i}'] = st.multiselect('Objectivity',['None','Perception','Fact','Policy'], key=f'{i}-obj',default=sent['obj'])
            space_out[f'{i}'] = st.multiselect('Scope | Space',['Local','City-wide'], key=f'{i}-spa',default=sent['space'])
            time_out[f'{i}'] = st.multiselect('Scope | time',['Occasional','General',],key=f'{i}-tim',default=sent['time'])
            Imp_out[f'{i}'] = st.multiselect('Importance',['Slightly important','Very Important','Extreamly important','Spam'],key=f'{i}-Imp',default=sent['Imp'])
            com_out[f'{i}'] = st.text_area('Comments',value=str(sent['comment']), key=i)
            if st.button('Update',i):
                sent['tag'] = tag_out[f'{i}']
                sent['comment']= com_out[f'{i}']
                sent['obj']= obj_out[f'{i}']
                sent['space']= space_out[f'{i}']
                sent['time']= time_out[f'{i}']
                sent['Imp']= Imp_out[f'{i}']
                update_data(x,str(text_sents))   
            st.markdown('---')
        if st.checkbox('NER',False,f'{x}{i}-ner'):
            sent_out[f'{i}']=st.text_area('ct: City, cz: Citizens, org: Organizations, st: State',value = sent['sent'],key= f"{i}-ner")
            if st.button('Update',f"{i}-ner"):
                if '%' in sent_out[f'{i}']:
                    split = sent_out[f'{i}'].split('%')
                    sent_out[f'{i}']=split[0]
                    text_sents.insert(i+1,{'sent': f'{split[1]}', 'pred': [], 'tag': [], 'comment': '', 'obj': [], 'space': [], 'time': [], 'Imp': []})
                sent['sent']=sent_out[f'{i}']
                update_data(x,str(text_sents))
        st.markdown('---')