Spaces:
Sleeping
Sleeping
File size: 3,969 Bytes
e5210b5 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 |
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 = '<h2>' + feat_dict[feat] + '</h2>'
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) + '. ' + '<b>' + df['Metropolitan areas'] + '</b>' + ' ' + df['Flag'] + '<br>' + df['pad'] + '<b>' + '$' + df[feat].astype(str) + 'K' + '</b>',
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('<h1>OECD Functional Urban Areas</h1>')
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)
|