import os
import pycountry
import numpy as np
import pandas as pd
import gradio as gr
from datetime import datetime
import plotly.graph_objects as go
from Request_OECD_Data import oecd_data
master_file = 'OECD_DF_CITIES_coord.csv'
def reload_data(master_file):
if os.path.isfile(master_file):
now = datetime.now()
fdate = datetime.fromtimestamp(os.path.getmtime(master_file))
delta = (now - fdate).days
if delta > 30:
df = oecd_data()
else:
df = pd.read_csv(master_file)
else:
df = oecd_data()
return df
def feat_list():
global feats
global feat_simp
global feat_dict
df = reload_data(master_file)
non_feat = ['METRO_ID', 'Metropolitan areas', 'coordinates']
feats = [f for f in df.columns.tolist() if f not in non_feat]
feat_simp = [f.split(' (')[0] for f in feats]
feat_dict = dict(zip(feat_simp, feats))
return feat_simp
feat_list()
def feat_chooser(feat):
feat_simp = feat_list()
index = feat_simp.index(feat)
choosen_feat = '
' + feat_dict[feat] + '
'
features = gr.Dropdown(choices=feat_simp, label='Select the economic descriptor', value=feat_simp[index], interactive=True)
fig = plot_feat(feat)
return choosen_feat, features, fig
def plot_feat(feat):
feat = feat_dict[feat]
print(feat)
df = reload_data(master_file)
df = df.dropna(subset=[feat])
df = df.sort_values(by=feat, ascending=False)
df = df.reset_index(drop=True).reset_index().rename(columns={'index': 'Rank'})
df['Rank'] = df['Rank'] + 1
df['digit'] = df['Rank'].astype(str).str.len().astype(int) + 2
df['pad'] = ' '
df['pad']= df['pad'].str.repeat(df['digit'])
df['Latitude'] = df['coordinates'].str.split(',').str[1].str.replace(r'\)', '', regex=True)
df['Longitude'] = df['coordinates'].str.split(',').str[0].str.replace(r'\(', '', regex=True)
df['ISO2'] = df['METRO_ID'].apply(lambda s: ''.join(c for c in s if c.isalpha()))
def iso_to_iso(row):
if len(row) > 2:
row = pycountry.countries.get(alpha_3=row).alpha_2
else:
if row == 'EL':
row = 'GR'
elif row == 'UK':
row = 'GB'
else:
row = row
return row
df['Country Code'] = df['ISO2'].apply(lambda x: iso_to_iso(x))
df['Flag'] = df['Country Code'].apply(lambda x: pycountry.countries.get(alpha_2=x).flag)
fig = go.Figure()
fig.add_trace(go.Choropleth())
fig.add_trace(go.Scattergeo(
lon = df['Longitude'],
lat = df['Latitude'],
text = df['Rank'].astype(str) + '. ' + '' + df['Metropolitan areas'] + '' + ' ' + df['Flag'] + '
' + df['pad'] + '' + '$' + df[feat].astype(str) + 'K' + '',
hoverinfo='text',
name = '',
mode = 'markers',
marker = dict(
size = df[feat],
#sizemin=4,
sizeref=2.*max(df[feat])/(40.**2),
sizemode = 'area',
color = df[feat],
colorscale='Portland',
showscale=True,
),
))
fig.update_geos(projection_type='orthographic', projection_rotation = {'lat': 49.6112768, 'lon': 6.129799, 'roll': 0}, projection_scale = 1)
fig.update_layout(height=1080, hoverlabel=dict(font_size=14,font_family='Courier New, monospace'))
return fig
### Gradio app ###
with gr.Blocks() as demo:
gr.HTML('OECD Functional Urban Areas
')
features = gr.Dropdown(choices=feat_simp, label='Select the economic descriptor', value=feat_simp[0], interactive=True)
choosen_feat = gr.HTML(feat_dict[feat_simp[0]])
world_map = gr.Plot()
features.input(fn=feat_chooser, inputs=features, outputs=[choosen_feat, features, world_map])
demo.load(plot_feat, [features], world_map)
port = int(os.environ.get('PORT', 7860))
demo.launch(server_name="0.0.0.0", server_port=port)