<filename>demo_app.py
import pandas as pd
import numpy as np
import streamlit as st
import requests
from bs4 import BeautifulSoup
from streamlit_folium import folium_static
import folium
import plotly.graph_objects as go
import matplotlib.pyplot as plt
import plotly.express as px
from zipfile import ZipFile
with st.echo(code_location='below'):
    page = st.sidebar.selectbox('Select App:',('Application One','Application Two'))
    df = pd.read_csv("costs.csv")
    zip_file = ZipFile('AB_US_2020.csv.zip')
    csv_file = zip_file.extractall()
    strb = pd.read_csv("Starbucks.csv")
    str_us = strb[strb['Country'] == 'US']
    airbnb = pd.read_csv('AB_US_2020.csv')
    airports = pd.read_csv('https://ourairports.com/data/airports.csv')
    visas = pd.read_csv('VisaFree.csv')
    covid = pd.read_csv('https://raw.githubusercontent.com/nytimes/covid-19-data/master/us-counties-recent.csv')
    money = pd.read_csv('CPI.csv')
    df_2 = pd.read_csv("iso_2.csv", )
    def iso_2(country):
        return df_2['Alpha-3 code'][df_2.loc[df_2['Country'] == country].index.values[0]]
    def country_names(counts):
        countries = []
        for count in counts:
            countries.append(count)
        return countries
    def iso(country):
        df_iso = pd.read_csv("Tags.csv", )
        return df_iso['Code'][df_iso.loc[df_iso['Name'] == country].index.values[0]]
    def get_airports(country):
        r = requests.get(("https://www.flightconnections.com/airports-in-" + country.lower() + "-" + iso(country).lower()))
        soup = BeautifulSoup(r.text)
        list_of_tags = []
        for i in soup.find_all('span', {'class', 'airport-code'}):
            list_of_tags.append(i.text)
        for i in range(len(list_of_tags)):
            list_of_tags[i] = (soup.find_all('span', {'class', 'airport-name'})[i].text, list_of_tags[i])
        return dict(list_of_tags)
    def get_coord(place):
        entrypoint = "https://nominatim.openstreetmap.org/search"
        query_1 = {'q': place, 'format' : 'json'}
        r_1 = requests.get(entrypoint, params = query_1)
        return [r_1.json()[0]['lat'], r_1.json()[0]['lon']]
    def get_info(air_1, air_2):
        r = requests.get("https://www.flightconnections.com/flights-from-" + air_1 + "-to-" + air_2)
        soup = BeautifulSoup(r.text)
        list_of_tags = []
        for i in soup.find_all('div', {'class', 'route-page-info-text'}):
            list_of_tags.append(i.text)
        return list_of_tags
    def get_prices(Choice, An_choice, air_1, air_2):
        r = requests.get("https://www.trip.com/flights/airport-" + air_1 + "-" + air_2 + "/" +
                         Choice.lower().replace(" ", "-") + "-to-" + An_choice.lower().replace(" ", "-") + "/")
        soup = BeautifulSoup(r.text)
        return soup.find('p', {'class', 'price-txt blod-txt single-row-txt'}).text
    def get_color(colors_list, room_type, types):
        index = types.index(room_type)
        color = colors[index % len(colors_list)]
        return color
    def get_air_coor(airport):
        air = airports[airports['iata_code'] == airport]
        coord_list = [float(air['latitude_deg']), float(air['longitude_deg'])]
        return coord_list
    visas['code'] = None
    for x in range(len(visas)):
        if visas['country'][x] in df_2['Country'].unique():
            visas['code'][x] = iso_2(visas['country'][x])[2:5]
        else:
            visas.drop(x)
    countries = country_names(df['Country'])
    if page == 'Application One':
        st.write("###### When creating the application, various datasets were used, the information in "
                 "which is contained in different formats. Because of this, you may have problems at some "
                 "of the stages of working with the application. In such cases, a corresponding message will appear. ")
        st.write("###### In case of unsuccessful filling of the cells, I offer you my version of the variables, "
                 "which is guaranteed to allow you to see all the graphs:")
        st.write("###### Russia - Spain")
        st.write("###### Domodedovo international Airport - Barcelona Airport")
        st.write("#")
        st.title('This app is useful when planning trips abroad')
        Dprt_country = st.text_input("Enter a country of departure:", )
        Choice_1 = st.text_input("Enter a country of arrival:", )
        if len(Dprt_country) >= 1 and len(Choice_1) >= 1:
            if Choice_1 not in countries:
                st.write("Sorry, I couldn't find information about these countries")
                st.write("Please, try other countries.")
            elif Dprt_country not in countries:
                st.write("Sorry, I couldn't find information about these countries")
                st.write("Please, try other countries.")
            else:
                if Dprt_country != Choice_1:
                    ind_1 = df.loc[df['Country'] == Choice_1].index.values[0]
                    ind_2 = df.loc[df['Country'] == Dprt_country].index.values[0]
                    categories = ['Cost of Living Index','Rent Index','Groceries Index',
                              'Restaurant Price Index', 'Local Purchasing Power Index']
                    r_1 = [df[categories[0]][ind_1], df[categories[1]][ind_1], df[categories[2]][ind_1],
                       df[categories[3]][ind_1], df[categories[4]][ind_1]]
                    r_2 = [df[categories[0]][ind_2], df[categories[1]][ind_2], df[categories[2]][ind_2],
                       df[categories[3]][ind_2], df[categories[4]][ind_2]]
                    fig = go.Figure()
                    fig.add_trace(go.Scatterpolar(r = r_1, theta = categories, fill = 'toself', name = Dprt_country))
                    fig.add_trace(go.Scatterpolar(r = r_2, theta = categories, fill = 'toself', name = Choice_1))
                    fig.update_layout(polar = dict(radialaxis = dict(visible = True, range = [0, 5 + max(max(r_1), max(r_2))])),
                    showlegend=False)
                    st.write("This information about costs of living in the chosen countries may"
                         " help you planning your budget. ")
                    st.write(fig)
                    st.write("###### *These indices are relative to New York City (NYC)*")
                    st.write("##")
                    st.write("This animation will make you understand the dynamics in CPI values in these countries "
                             "over time. ")
                    money_1 = money[money['Economy'] == Dprt_country].dropna()
                    money_2 = money[money['Economy'] == Choice_1].dropna()
                    money_1 = money_1.groupby('Year').mean()
                    money_1 = money_1.reset_index()
                    money_1['Country'] = Dprt_country
                    minimum_1 = min(money_1['Year'])
                    money_2 = money_2.groupby('Year').mean()
                    money_2 = money_2.reset_index()
                    money_2['Country'] = Choice_1
                    minimum_2 = min(money_2['Year'])
                    minimum = max(minimum_1, minimum_2)
                    money_1 = money_1[money_1['Year'] >= minimum]
                    money_2 = money_2[money_2['Year'] >= minimum]
                    cpi_data = money_1.append(money_2)
                    cpi_data = cpi_data[['Year', 'CPI', 'Country']]
                    fig, ax = plt.subplots()
                    fig = px.bar(cpi_data, x = 'Country', y = "CPI", color = 'Country', animation_frame = "Year",
                                 animation_group = cpi_data['Country'], range_y = [0, 1.25 * max(cpi_data['CPI'])])
                    st.write(fig)
                    st.write("##")
                    st.write('Since you want to travel abroad, pick international airports')
                    Choice_2 = st.selectbox('Select an airport in ' + Dprt_country, list(get_airports(Dprt_country).keys()))
                    Choice_3 = st.selectbox('Select an airport in ' + Choice_1, list(get_airports(Choice_1).keys()))
                    tag_1 = get_airports(Dprt_country)[Choice_2].lower()
                    tag_2 = get_airports(Choice_1)[Choice_3].lower()
                    air_1 = get_air_coor(tag_1.upper())
                    air_2 = get_air_coor(tag_2.upper())
                    if get_info(tag_1, tag_2)[1].split()[0] == "0":
                        st.write("Unfortunately, there are no direct flights available at the moment.")
                        st.write("###### *If you are seeing this message, please, try inputting other data*")
                    else:
                        st.write("Your flight from " + Dprt_country + " to " + Choice_1 + " will take approximately " +
                         get_info(tag_1, tag_2)[2])
                        st.write("The estimated price for your flight is " + get_prices(Choice_2, Choice_3, tag_1, tag_2))
                        st.write("##")
                        st.write("The map below displays your flight:")
                        fig = go.Figure(go.Scattermapbox(mode = "markers", text = [Choice_2, Choice_3], showlegend = False,
                        lon = [air_1[1], air_2[1]], lat = [air_1[0], air_2[0]],marker = {'size': 6}))
                        fig.add_trace(go.Scattermapbox(text = Choice_2 + " to " + Choice_3, lon = [air_1[1], air_2[1]],
                        lat = [air_1[0], air_2[0]], mode = 'lines', line = dict(width = 1, color = 'blue'),
                        opacity = 0.95, showlegend = False,))
                        fig.update_layout(margin ={'l':0,'t':0,'b':0,'r':0}, mapbox = {'center': {'lon': (air_1[1] + air_2[1]) / 2,
                                   'lat': (air_1[0] + air_2[0]) / 2}, 'style': "stamen-terrain", 'zoom': 1})
                        st.write(fig)
                else:
                    st.write("### Please, try entering different countries.")
                st.write("#")
                st.write("#")
                st.write("The map below is a thematic map that displays the number of"
                         " passports worldwide that have visa-free access to a country. It may be useful"
                         " when planning your future trips.")
                st.write("###### *Expand it for a better look*.")
                ### (partly) FROM: (https://plotly.com/python/choropleth-maps/)
                fig = go.Figure(data = go.Choropleth(locations = visas['code'], z = visas['visawelc'], text = visas['country'],
                                colorscale = 'Blues', reversescale=True, marker_line_color='darkgray', marker_line_width=0.5,
                                colorbar_title = 'Number of passports accepted for travel'))
                fig.update_layout(title_text = 'Welcoming Rank', geo = dict(showframe = False, showcoastlines = False, showlakes = False,
                                  projection_type = 'kavrayskiy7'), annotations = [dict(x = 0.55, y = 0.1, xref = 'paper', yref = 'paper',
                                  text='Source: <a href="https://www.passportindex.org">Passport Index</a>', showarrow = False)])
                ### END FROM
                st.write(fig)
                st.write("###### The data is not up-to-date (2016 dataset was used). Changes may have occurred after the date of appeal")
    else:
        st.write("###### When creating the application, various datasets were used, the information in "
                 "which is contained in different formats. Because of this, you may have problems at some "
                 "of the stages of working with the application. In such cases, a corresponding message will appear. ")
        st.write("###### In case of unsuccessful filling of the cells, I recommend you choosing Los Angeles as the destination.")
        st.write("#")
        st.title("Imagine, you're travelling to US")
        st.subheader("Here's a small app that may help you")
        City_choice = st.selectbox('Choose a city you want to visit:', airbnb['city'].unique())
        if len(City_choice) >= 1:
            st.write("When planning a trip, the first thing you should think about is the accommodation.")
            st.write("You can find places to stay here:")
            citybnb = airbnb[airbnb['city'] == City_choice]
            Max_price = st.number_input('Enter the maximum price you are ready to pay for a night:',
                                        min_value= 0.0)
            # The line above is used for convenience while using the slider below
            if (Max_price) > 0.0:
                Price = st.slider("Please, specify the price range:", 0.0, Max_price, (Max_price/8, Max_price/2), 0.5)
                bnb = citybnb[citybnb['price'] <= Price[1]]
                bnb = bnb[bnb['price'] >= Price[0]]
                Days = st.slider('For how long are you going to stay in ' + City_choice + '?',
                                 0, 60, (0, 7), 1)
                Stay = []
                Stay.append(Days[0])
                Stay.append(Days[1])
                Stay[0] = max([Stay[0], 1])
                Check = st.checkbox('Show options for 60+ days stay')
                if Check:
                    Stay[1] = bnb['minimum_nights'].max()
                if Stay[0] > 0:
                    bnb = bnb[bnb['minimum_nights'] >= Stay[0]]
                    bnb = bnb[bnb['minimum_nights'] <= Stay[1]]
                    st.write("This is a map of places in " + City_choice + " that satisfy your requirements")
                    map_bnb = folium.Map(location = [get_coord(City_choice)[0], get_coord(City_choice)[1]],
                                         tiles = "OpenStreetMap", zoom_start = 10)
                    colors = ['red', 'blue', 'green', 'purple', 'orange', 'darkred', 'lightred', 'beige', 'lightblue']
                    room_types = list(airbnb['room_type'].unique())
                    for i in range(0,len(bnb)):
                        folium.Circle(location=[bnb.iloc[i]['latitude'], bnb.iloc[i]['longitude']], popup = bnb.iloc[i]['room_type'] + ", $" + str(bnb.iloc[i]['price']) + ' per night',radius = 0.5,
                                      color = get_color(colors, bnb.iloc[i]['room_type'], room_types), fill = True,
                                      fill_color = get_color(colors, bnb.iloc[i]['room_type'], room_types)).add_to(map_bnb)
                    folium_static(map_bnb)
                    st.write("#")
                    st.write("I advise you visit Starbucks during your trip.")
                    st.write("In a map below, you can see all Starbucks coffee shops located in " + City_choice + ".")
                    str_city = str_us[str_us['City'] == City_choice]
                    m_2 = folium.Map(location = [get_coord(City_choice)[0], get_coord(City_choice)[1]], tiles = "OpenStreetMap", zoom_start = 10)
                    for i in range(0,len(str_city)):
                        folium.Marker(location=[str_city.iloc[i]['Latitude'], str_city.iloc[i]['Longitude']],
                                      popup=str_city.iloc[i]['Street Address'],).add_to(m_2)
                    folium_static(m_2)
                    st.write("#")
                    cov = covid[covid['county'] == City_choice]
                    if len(cov) == 0:
                        st.write('Unfortunately, there is no actual information about COVID-19 in this city')
                        st.write('Please, try entering another destination')
                    else:
                        st.write("COVID-19 Dynamics in " + City_choice + " for the last month:")
                        cov.reset_index(drop=True, inplace=True)
                        cov['deaths_dyn'] = 0
                        cov['cases_dyn'] = 0
                        for i in range(1, len(cov)):
                            cov['deaths_dyn'][i] = cov['deaths'][i] - cov['deaths'][i - 1]
                            cov['cases_dyn'][i] = cov['cases'][i] - cov['cases'][i - 1]
                        xticks = []
                        for i in range(len(cov['date'])):
                            if i % 4 == 0:
                                xticks.append(cov['date'][i])
                        plt.stackplot(cov['date'], cov['cases_dyn'], cov['deaths_dyn'], labels=['Dynamics in cases','Dynamics in deaths'], colors = ["#d13221",  "#0e1659"], alpha = 0.75)
                        plt.legend(loc = 'upper right')
                        plt.xticks(xticks, rotation=45)
                        st.set_option('deprecation.showPyplotGlobalUse', False)
                        st.pyplot(plt.show())















<filename>demo_app.py
import pandas as pd
import numpy as np
import streamlit as st
import requests
from bs4 import BeautifulSoup
from streamlit_folium import folium_static
import folium
import plotly.graph_objects as go
import matplotlib.pyplot as plt
import plotly.express as px
from zipfile import ZipFile
with st.echo(code_location='below'):
    page = st.sidebar.selectbox('Select App:',('Application One','Application Two'))
    df = pd.read_csv("costs.csv")
    zip_file = ZipFile('AB_US_2020.csv.zip')
    csv_file = zip_file.extractall()
    strb = pd.read_csv("Starbucks.csv")
    str_us = strb[strb['Country'] == 'US']
    airbnb = pd.read_csv('AB_US_2020.csv')
    airports = pd.read_csv('https://ourairports.com/data/airports.csv')
    visas = pd.read_csv('VisaFree.csv')
    covid = pd.read_csv('https://raw.githubusercontent.com/nytimes/covid-19-data/master/us-counties-recent.csv')
    money = pd.read_csv('CPI.csv')
    df_2 = pd.read_csv("iso_2.csv", )
    def iso_2(country):
        return df_2['Alpha-3 code'][df_2.loc[df_2['Country'] == country].index.values[0]]
    def country_names(counts):
        countries = []
        for count in counts:
            countries.append(count)
        return countries
    def iso(country):
        df_iso = pd.read_csv("Tags.csv", )
        return df_iso['Code'][df_iso.loc[df_iso['Name'] == country].index.values[0]]
    def get_airports(country):
        r = requests.get(("https://www.flightconnections.com/airports-in-" + country.lower() + "-" + iso(country).lower()))
        soup = BeautifulSoup(r.text)
        list_of_tags = []
        for i in soup.find_all('span', {'class', 'airport-code'}):
            list_of_tags.append(i.text)
        for i in range(len(list_of_tags)):
            list_of_tags[i] = (soup.find_all('span', {'class', 'airport-name'})[i].text, list_of_tags[i])
        return dict(list_of_tags)
    def get_coord(place):
        entrypoint = "https://nominatim.openstreetmap.org/search"
        query_1 = {'q': place, 'format' : 'json'}
        r_1 = requests.get(entrypoint, params = query_1)
        return [r_1.json()[0]['lat'], r_1.json()[0]['lon']]
    def get_info(air_1, air_2):
        r = requests.get("https://www.flightconnections.com/flights-from-" + air_1 + "-to-" + air_2)
        soup = BeautifulSoup(r.text)
        list_of_tags = []
        for i in soup.find_all('div', {'class', 'route-page-info-text'}):
            list_of_tags.append(i.text)
        return list_of_tags
    def get_prices(Choice, An_choice, air_1, air_2):
        r = requests.get("https://www.trip.com/flights/airport-" + air_1 + "-" + air_2 + "/" +
                         Choice.lower().replace(" ", "-") + "-to-" + An_choice.lower().replace(" ", "-") + "/")
        soup = BeautifulSoup(r.text)
        return soup.find('p', {'class', 'price-txt blod-txt single-row-txt'}).text
    def get_color(colors_list, room_type, types):
        index = types.index(room_type)
        color = colors[index % len(colors_list)]
        return color
    def get_air_coor(airport):
        air = airports[airports['iata_code'] == airport]
        coord_list = [float(air['latitude_deg']), float(air['longitude_deg'])]
        return coord_list
    visas['code'] = None
    for x in range(len(visas)):
        if visas['country'][x] in df_2['Country'].unique():
            visas['code'][x] = iso_2(visas['country'][x])[2:5]
        else:
            visas.drop(x)
    countries = country_names(df['Country'])
    if page == 'Application One':
        st.write("###### When creating the application, various datasets were used, the information in "
                 "which is contained in different formats. Because of this, you may have problems at some "
                 "of the stages of working with the application. In such cases, a corresponding message will appear. ")
        st.write("###### In case of unsuccessful filling of the cells, I offer you my version of the variables, "
                 "which is guaranteed to allow you to see all the graphs:")
        st.write("###### Russia - Spain")
        st.write("###### Domodedovo international Airport - Barcelona Airport")
        st.write("#")
        st.title('This app is useful when planning trips abroad')
        Dprt_country = st.text_input("Enter a country of departure:", )
        Choice_1 = st.text_input("Enter a country of arrival:", )
        if len(Dprt_country) >= 1 and len(Choice_1) >= 1:
            if Choice_1 not in countries:
                st.write("Sorry, I couldn't find information about these countries")
                st.write("Please, try other countries.")
            elif Dprt_country not in countries:
                st.write("Sorry, I couldn't find information about these countries")
                st.write("Please, try other countries.")
            else:
                if Dprt_country != Choice_1:
                    ind_1 = df.loc[df['Country'] == Choice_1].index.values[0]
                    ind_2 = df.loc[df['Country'] == Dprt_country].index.values[0]
                    categories = ['Cost of Living Index','Rent Index','Groceries Index',
                              'Restaurant Price Index', 'Local Purchasing Power Index']
                    r_1 = [df[categories[0]][ind_1], df[categories[1]][ind_1], df[categories[2]][ind_1],
                       df[categories[3]][ind_1], df[categories[4]][ind_1]]
                    r_2 = [df[categories[0]][ind_2], df[categories[1]][ind_2], df[categories[2]][ind_2],
                       df[categories[3]][ind_2], df[categories[4]][ind_2]]
                    fig = go.Figure()
                    fig.add_trace(go.Scatterpolar(r = r_1, theta = categories, fill = 'toself', name = Dprt_country))
                    fig.add_trace(go.Scatterpolar(r = r_2, theta = categories, fill = 'toself', name = Choice_1))
                    fig.update_layout(polar = dict(radialaxis = dict(visible = True, range = [0, 5 + max(max(r_1), max(r_2))])),
                    showlegend=False)
                    st.write("This information about costs of living in the chosen countries may"
                         " help you planning your budget. ")
                    st.write(fig)
                    st.write("###### *These indices are relative to New York City (NYC)*")
                    st.write("##")
                    st.write("This animation will make you understand the dynamics in CPI values in these countries "
                             "over time. ")
                    money_1 = money[money['Economy'] == Dprt_country].dropna()
                    money_2 = money[money['Economy'] == Choice_1].dropna()
                    money_1 = money_1.groupby('Year').mean()
                    money_1 = money_1.reset_index()
                    money_1['Country'] = Dprt_country
                    minimum_1 = min(money_1['Year'])
                    money_2 = money_2.groupby('Year').mean()
                    money_2 = money_2.reset_index()
                    money_2['Country'] = Choice_1
                    minimum_2 = min(money_2['Year'])
                    minimum = max(minimum_1, minimum_2)
                    money_1 = money_1[money_1['Year'] >= minimum]
                    money_2 = money_2[money_2['Year'] >= minimum]
                    cpi_data = money_1.append(money_2)
                    cpi_data = cpi_data[['Year', 'CPI', 'Country']]
                    fig, ax = plt.subplots()
                    fig = px.bar(cpi_data, x = 'Country', y = "CPI", color = 'Country', animation_frame = "Year",
                                 animation_group = cpi_data['Country'], range_y = [0, 1.25 * max(cpi_data['CPI'])])
                    st.write(fig)
                    st.write("##")
                    st.write('Since you want to travel abroad, pick international airports')
                    Choice_2 = st.selectbox('Select an airport in ' + Dprt_country, list(get_airports(Dprt_country).keys()))
                    Choice_3 = st.selectbox('Select an airport in ' + Choice_1, list(get_airports(Choice_1).keys()))
                    tag_1 = get_airports(Dprt_country)[Choice_2].lower()
                    tag_2 = get_airports(Choice_1)[Choice_3].lower()
                    air_1 = get_air_coor(tag_1.upper())
                    air_2 = get_air_coor(tag_2.upper())
                    if get_info(tag_1, tag_2)[1].split()[0] == "0":
                        st.write("Unfortunately, there are no direct flights available at the moment.")
                        st.write("###### *If you are seeing this message, please, try inputting other data*")
                    else:
                        st.write("Your flight from " + Dprt_country + " to " + Choice_1 + " will take approximately " +
                         get_info(tag_1, tag_2)[2])
                        st.write("The estimated price for your flight is " + get_prices(Choice_2, Choice_3, tag_1, tag_2))
                        st.write("##")
                        st.write("The map below displays your flight:")
                        fig = go.Figure(go.Scattermapbox(mode = "markers", text = [Choice_2, Choice_3], showlegend = False,
                        lon = [air_1[1], air_2[1]], lat = [air_1[0], air_2[0]],marker = {'size': 6}))
                        fig.add_trace(go.Scattermapbox(text = Choice_2 + " to " + Choice_3, lon = [air_1[1], air_2[1]],
                        lat = [air_1[0], air_2[0]], mode = 'lines', line = dict(width = 1, color = 'blue'),
                        opacity = 0.95, showlegend = False,))
                        fig.update_layout(margin ={'l':0,'t':0,'b':0,'r':0}, mapbox = {'center': {'lon': (air_1[1] + air_2[1]) / 2,
                                   'lat': (air_1[0] + air_2[0]) / 2}, 'style': "stamen-terrain", 'zoom': 1})
                        st.write(fig)
                else:
                    st.write("### Please, try entering different countries.")
                st.write("#")
                st.write("#")
                st.write("The map below is a thematic map that displays the number of"
                         " passports worldwide that have visa-free access to a country. It may be useful"
                         " when planning your future trips.")
                st.write("###### *Expand it for a better look*.")
                ### (partly) FROM: (https://plotly.com/python/choropleth-maps/)
                fig = go.Figure(data = go.Choropleth(locations = visas['code'], z = visas['visawelc'], text = visas['country'],
                                colorscale = 'Blues', reversescale=True, marker_line_color='darkgray', marker_line_width=0.5,
                                colorbar_title = 'Number of passports accepted for travel'))
                fig.update_layout(title_text = 'Welcoming Rank', geo = dict(showframe = False, showcoastlines = False, showlakes = False,
                                  projection_type = 'kavrayskiy7'), annotations = [dict(x = 0.55, y = 0.1, xref = 'paper', yref = 'paper',
                                  text='Source: <a href="https://www.passportindex.org">Passport Index</a>', showarrow = False)])
                ### END FROM
                st.write(fig)
                st.write("###### The data is not up-to-date (2016 dataset was used). Changes may have occurred after the date of appeal")
    else:
        st.write("###### When creating the application, various datasets were used, the information in "
                 "which is contained in different formats. Because of this, you may have problems at some "
                 "of the stages of working with the application. In such cases, a corresponding message will appear. ")
        st.write("###### In case of unsuccessful filling of the cells, I recommend you choosing Los Angeles as the destination.")
        st.write("#")
        st.title("Imagine, you're travelling to US")
        st.subheader("Here's a small app that may help you")
        City_choice = st.selectbox('Choose a city you want to visit:', airbnb['city'].unique())
        if len(City_choice) >= 1:
            st.write("When planning a trip, the first thing you should think about is the accommodation.")
            st.write("You can find places to stay here:")
            citybnb = airbnb[airbnb['city'] == City_choice]
            Max_price = st.number_input('Enter the maximum price you are ready to pay for a night:',
                                        min_value= 0.0)
            # The line above is used for convenience while using the slider below
            if (Max_price) > 0.0:
                Price = st.slider("Please, specify the price range:", 0.0, Max_price, (Max_price/8, Max_price/2), 0.5)
                bnb = citybnb[citybnb['price'] <= Price[1]]
                bnb = bnb[bnb['price'] >= Price[0]]
                Days = st.slider('For how long are you going to stay in ' + City_choice + '?',
                                 0, 60, (0, 7), 1)
                Stay = []
                Stay.append(Days[0])
                Stay.append(Days[1])
                Stay[0] = max([Stay[0], 1])
                Check = st.checkbox('Show options for 60+ days stay')
                if Check:
                    Stay[1] = bnb['minimum_nights'].max()
                if Stay[0] > 0:
                    bnb = bnb[bnb['minimum_nights'] >= Stay[0]]
                    bnb = bnb[bnb['minimum_nights'] <= Stay[1]]
                    st.write("This is a map of places in " + City_choice + " that satisfy your requirements")
                    map_bnb = folium.Map(location = [get_coord(City_choice)[0], get_coord(City_choice)[1]],
                                         tiles = "OpenStreetMap", zoom_start = 10)
                    colors = ['red', 'blue', 'green', 'purple', 'orange', 'darkred', 'lightred', 'beige', 'lightblue']
                    room_types = list(airbnb['room_type'].unique())
                    for i in range(0,len(bnb)):
                        folium.Circle(location=[bnb.iloc[i]['latitude'], bnb.iloc[i]['longitude']], popup = bnb.iloc[i]['room_type'] + ", $" + str(bnb.iloc[i]['price']) + ' per night',radius = 0.5,
                                      color = get_color(colors, bnb.iloc[i]['room_type'], room_types), fill = True,
                                      fill_color = get_color(colors, bnb.iloc[i]['room_type'], room_types)).add_to(map_bnb)
                    folium_static(map_bnb)
                    st.write("#")
                    st.write("I advise you visit Starbucks during your trip.")
                    st.write("In a map below, you can see all Starbucks coffee shops located in " + City_choice + ".")
                    str_city = str_us[str_us['City'] == City_choice]
                    m_2 = folium.Map(location = [get_coord(City_choice)[0], get_coord(City_choice)[1]], tiles = "OpenStreetMap", zoom_start = 10)
                    for i in range(0,len(str_city)):
                        folium.Marker(location=[str_city.iloc[i]['Latitude'], str_city.iloc[i]['Longitude']],
                                      popup=str_city.iloc[i]['Street Address'],).add_to(m_2)
                    folium_static(m_2)
                    st.write("#")
                    cov = covid[covid['county'] == City_choice]
                    if len(cov) == 0:
                        st.write('Unfortunately, there is no actual information about COVID-19 in this city')
                        st.write('Please, try entering another destination')
                    else:
                        st.write("COVID-19 Dynamics in " + City_choice + " for the last month:")
                        cov.reset_index(drop=True, inplace=True)
                        cov['deaths_dyn'] = 0
                        cov['cases_dyn'] = 0
                        for i in range(1, len(cov)):
                            cov['deaths_dyn'][i] = cov['deaths'][i] - cov['deaths'][i - 1]
                            cov['cases_dyn'][i] = cov['cases'][i] - cov['cases'][i - 1]
                        xticks = []
                        for i in range(len(cov['date'])):
                            if i % 4 == 0:
                                xticks.append(cov['date'][i])
                        plt.stackplot(cov['date'], cov['cases_dyn'], cov['deaths_dyn'], labels=['Dynamics in cases','Dynamics in deaths'], colors = ["#d13221",  "#0e1659"], alpha = 0.75)
                        plt.legend(loc = 'upper right')
                        plt.xticks(xticks, rotation=45)
                        st.set_option('deprecation.showPyplotGlobalUse', False)
                        st.pyplot(plt.show())















##### When creating the application, various datasets were used, the information in " ##### In case of unsuccessful filling of the cells, I offer you my version of the variables, " ##### Russia - Spain") ##### Domodedovo international Airport - Barcelona Airport") ##### *These indices are relative to New York City (NYC)*") #") #") ##### *If you are seeing this message, please, try inputting other data*") #") ## Please, try entering different countries.") ##### *Expand it for a better look*.") ### (partly) FROM: (https://plotly.com/python/choropleth-maps/) ### END FROM ##### The data is not up-to-date (2016 dataset was used). Changes may have occurred after the date of appeal") ##### When creating the application, various datasets were used, the information in " ##### In case of unsuccessful filling of the cells, I recommend you choosing Los Angeles as the destination.") # The line above is used for convenience while using the slider below