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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Importing the required libraries
|
2 |
+
import streamlit as st
|
3 |
+
import pandas as pd
|
4 |
+
import numpy as np
|
5 |
+
import snowflake.connector
|
6 |
+
import folium
|
7 |
+
from streamlit_folium import st_folium
|
8 |
+
import pycountry_convert as pc
|
9 |
+
|
10 |
+
# Setup web page - App Title, Page Title and Page Layout
|
11 |
+
APP_TITLE = 'Plotting F1 Circuit Locations into a map on Streamlit on Hugging Face using Folium'
|
12 |
+
st.set_page_config(
|
13 |
+
page_title='F1 Circuits',
|
14 |
+
layout='wide',
|
15 |
+
menu_items={'Get Help': 'https://www.linkedin.com/in/daanbakboord',
|
16 |
+
'About': "This app is powered by Snowflake, Streamlit, Hugging Face and Folium | Developed by DaAnalytics (Daan Bakboord)"
|
17 |
+
}
|
18 |
+
)
|
19 |
+
|
20 |
+
# Initialize connection.
|
21 |
+
# Uses st.experimental_singleton to only run once.
|
22 |
+
@st.experimental_singleton
|
23 |
+
def init_connection():
|
24 |
+
#return snowflake.connector.connect(**st.secrets["snowflake"])
|
25 |
+
return snowflake.connector.connect(
|
26 |
+
user = st.secrets["user"],
|
27 |
+
password = st.secrets["password"],
|
28 |
+
account = st.secrets["account"],
|
29 |
+
role = st.secrets["role"]
|
30 |
+
)
|
31 |
+
|
32 |
+
# Create context
|
33 |
+
def create_sf_session_object():
|
34 |
+
|
35 |
+
if "snowflake_context" not in st.session_state:
|
36 |
+
|
37 |
+
ctx = init_connection()
|
38 |
+
|
39 |
+
st.session_state['snowflake_context'] = ctx
|
40 |
+
|
41 |
+
else:
|
42 |
+
|
43 |
+
ctx = st.session_state['snowflake_context']
|
44 |
+
|
45 |
+
return ctx
|
46 |
+
|
47 |
+
# Get Continent based on Country
|
48 |
+
def country_convert(country_name):
|
49 |
+
|
50 |
+
try:
|
51 |
+
|
52 |
+
country_code = pc.country_name_to_country_alpha2(country_name, cn_name_format='default')
|
53 |
+
|
54 |
+
continent_name = pc.country_alpha2_to_continent_code(country_code)
|
55 |
+
|
56 |
+
return pc.convert_continent_code_to_continent_name(continent_name)
|
57 |
+
|
58 |
+
except (KeyError, TypeError):
|
59 |
+
|
60 |
+
return (country_name)
|
61 |
+
|
62 |
+
# Base color on Continent
|
63 |
+
# 'darkblue', 'white', 'lightblue', 'pink', 'gray', 'green', 'orange', 'darkred', 'black', 'blue', 'cadetblue'
|
64 |
+
#, 'lightgreen', 'purple', 'darkgreen', 'red', 'beige', 'lightred', 'darkpurple', 'lightgray'
|
65 |
+
|
66 |
+
## 'Oceania', 'Asia', 'Europe', 'North America', 'UK', 'South America', 'UAE',
|
67 |
+
## 'Africa', 'Korea'
|
68 |
+
|
69 |
+
def marker_color(continent_name):
|
70 |
+
if continent_name == 'Asia':
|
71 |
+
color = 'pink'
|
72 |
+
elif continent_name == 'Africa':
|
73 |
+
color = 'green'
|
74 |
+
elif continent_name == 'Europe':
|
75 |
+
color = 'blue'
|
76 |
+
elif continent_name == 'North America':
|
77 |
+
color = 'red'
|
78 |
+
elif continent_name == 'South America':
|
79 |
+
color = 'orange'
|
80 |
+
elif continent_name == 'Oceania':
|
81 |
+
color = 'purple'
|
82 |
+
elif continent_name == 'UK':
|
83 |
+
color = 'beige'
|
84 |
+
elif continent_name == 'UAE':
|
85 |
+
color = 'lightgreen'
|
86 |
+
elif continent_name == 'Korea':
|
87 |
+
color = 'cadetblue'
|
88 |
+
else:
|
89 |
+
color = 'grey'
|
90 |
+
return color
|
91 |
+
|
92 |
+
def load_data(cur, map_type):
|
93 |
+
|
94 |
+
global df_f1_con_circuits
|
95 |
+
|
96 |
+
global df_f1_cou_circuits
|
97 |
+
|
98 |
+
global df_qo_f1_circuits
|
99 |
+
|
100 |
+
# Connect to DEMO_DB database
|
101 |
+
cur.execute("USE DATABASE DEMO_DB")
|
102 |
+
|
103 |
+
# Connect to PRE_F1PY schema
|
104 |
+
f1_pre_schema = 'PRE_F1PY'
|
105 |
+
|
106 |
+
cur.execute("USE SCHEMA " + f1_pre_schema)
|
107 |
+
|
108 |
+
# Select Query F1 Circuits
|
109 |
+
|
110 |
+
sql_f1_circuits = """select replace(name, '"','') as name
|
111 |
+
, lat
|
112 |
+
, lng
|
113 |
+
, replace(country, '"','') as country
|
114 |
+
, replace(url, '"','') as url
|
115 |
+
from demo_db.pre_f1py.pre_f1py_circuits
|
116 |
+
"""
|
117 |
+
|
118 |
+
# Query F1 Circuits
|
119 |
+
cur.execute(sql_f1_circuits)
|
120 |
+
|
121 |
+
# Convert Query output to a DataFrame
|
122 |
+
df_qo_f1_circuits = cur.fetch_pandas_all()
|
123 |
+
|
124 |
+
# Add Continent to df_f1_circuits DataFrame
|
125 |
+
df_qo_f1_circuits['CONTINENT'] = df_qo_f1_circuits['COUNTRY'].apply(country_convert)
|
126 |
+
|
127 |
+
# Create Continents DataFrame
|
128 |
+
df_f1_con_circuits = df_qo_f1_circuits['CONTINENT'].unique()
|
129 |
+
|
130 |
+
# Create Country DataFrame
|
131 |
+
df_f1_cou_circuits = df_qo_f1_circuits['COUNTRY'].unique()
|
132 |
+
|
133 |
+
def filter_data(map_type, detail):
|
134 |
+
|
135 |
+
global df_f1_circuits
|
136 |
+
|
137 |
+
if map_type == 'World':
|
138 |
+
|
139 |
+
df_f1_circuits = df_qo_f1_circuits
|
140 |
+
|
141 |
+
elif map_type == 'Continent':
|
142 |
+
|
143 |
+
# Filter df_f1_circuits DataFrame on 'Europe' Continent
|
144 |
+
df_f1_circuits = df_qo_f1_circuits.loc[df_qo_f1_circuits['CONTINENT'] == detail]
|
145 |
+
|
146 |
+
elif map_type == 'Country':
|
147 |
+
|
148 |
+
# Filter df_f1_circuits DataFrame on Country
|
149 |
+
df_f1_circuits = df_qo_f1_circuits.loc[df_qo_f1_circuits['COUNTRY'] == detail]
|
150 |
+
|
151 |
+
# Draw the Folium Map
|
152 |
+
draw_folium_map(map_type)
|
153 |
+
|
154 |
+
def draw_folium_map(map_type):
|
155 |
+
|
156 |
+
global CircuitsMap
|
157 |
+
|
158 |
+
# Creating the Folium Map
|
159 |
+
CircuitsMap = folium.Map(location=[df_f1_circuits.LAT.mean()
|
160 |
+
, df_f1_circuits.LNG.mean()]
|
161 |
+
, zoom_start=5
|
162 |
+
, control_scale=True
|
163 |
+
, tiles='openstreetmap')
|
164 |
+
|
165 |
+
# Adding Tile Layers
|
166 |
+
folium.TileLayer('openstreetmap').add_to(CircuitsMap)
|
167 |
+
folium.TileLayer('cartodb positron').add_to(CircuitsMap)
|
168 |
+
folium.TileLayer('stamenterrain').add_to(CircuitsMap)
|
169 |
+
folium.TileLayer('stamentoner').add_to(CircuitsMap)
|
170 |
+
folium.TileLayer('stamenwatercolor').add_to(CircuitsMap)
|
171 |
+
folium.TileLayer('cartodbdark_matter').add_to(CircuitsMap)
|
172 |
+
|
173 |
+
# Other mapping code (e.g. lines, markers etc.)
|
174 |
+
folium.LayerControl().add_to(CircuitsMap)
|
175 |
+
|
176 |
+
# Add Markers to the map
|
177 |
+
if map_type == 'World':
|
178 |
+
|
179 |
+
for index, location_info in df_f1_circuits.iterrows():
|
180 |
+
folium.Marker([location_info["LAT"], location_info["LNG"]], popup='<a href=' + location_info["URL"] + ' target="_blank">' + location_info["NAME"] + '</a>', icon=folium.Icon(icon_color='white', icon="car", prefix='fa', color=marker_color(location_info["CONTINENT"]))).add_to(CircuitsMap)
|
181 |
+
|
182 |
+
elif map_type == 'Continent':
|
183 |
+
|
184 |
+
for index, location_info in df_f1_circuits.iterrows():
|
185 |
+
folium.Marker([location_info["LAT"], location_info["LNG"]], popup='<a href=' + location_info["URL"] + ' target="_blank">' + location_info["NAME"] + '</a>', icon=folium.Icon(icon_color='white', icon="car", prefix='fa', color=marker_color(location_info["CONTINENT"]))).add_to(CircuitsMap)
|
186 |
+
|
187 |
+
elif map_type == 'Country':
|
188 |
+
|
189 |
+
for index, location_info in df_f1_circuits.iterrows():
|
190 |
+
folium.Marker([location_info["LAT"], location_info["LNG"]], popup='<a href=' + location_info["URL"] + ' target="_blank">' + location_info["NAME"] + '</a>', icon=folium.Icon(icon_color='white', icon="car", prefix='fa', color='darkgreen')).add_to(CircuitsMap)
|
191 |
+
|
192 |
+
# Zoom to LAT, LONG bounds
|
193 |
+
lft_dwn = df_f1_circuits[['LAT', 'LNG']].min().values.tolist() # Left Down
|
194 |
+
top_rgt = df_f1_circuits[['LAT', 'LNG']].max().values.tolist() # Top Right
|
195 |
+
|
196 |
+
CircuitsMap.fit_bounds([lft_dwn, top_rgt])
|
197 |
+
|
198 |
+
# Main code
|
199 |
+
if __name__ == "__main__":
|
200 |
+
|
201 |
+
#v_user = st.secrets["user"]
|
202 |
+
#st.sidebar.title(v_user)
|
203 |
+
|
204 |
+
# Connect to Snowflake
|
205 |
+
ctx = create_sf_session_object()
|
206 |
+
cur = ctx.cursor()
|
207 |
+
|
208 |
+
# Select Map type to show
|
209 |
+
st.sidebar.title("Select Map Type")
|
210 |
+
|
211 |
+
map_type = st.sidebar.radio(
|
212 |
+
"Which map would you like to show?",
|
213 |
+
('World', 'Continent', 'Country'))
|
214 |
+
|
215 |
+
# Load Data into a DataFrame
|
216 |
+
load_data(cur, map_type)
|
217 |
+
|
218 |
+
if map_type == 'World':
|
219 |
+
|
220 |
+
detail = map_type
|
221 |
+
|
222 |
+
st.sidebar.write('You selected:', detail)
|
223 |
+
|
224 |
+
elif map_type == 'Continent':
|
225 |
+
|
226 |
+
idx = int(np.where(df_f1_con_circuits == "Europe")[0][0])
|
227 |
+
|
228 |
+
continent = st.sidebar.selectbox(
|
229 |
+
'Which continent would you like to see?',
|
230 |
+
(df_f1_con_circuits)
|
231 |
+
, index = idx)
|
232 |
+
|
233 |
+
detail = continent
|
234 |
+
|
235 |
+
st.sidebar.write('You selected:', detail)
|
236 |
+
|
237 |
+
elif map_type == 'Country':
|
238 |
+
|
239 |
+
idx = int(np.where(df_f1_cou_circuits == "France")[0][0])
|
240 |
+
|
241 |
+
country = st.sidebar.selectbox(
|
242 |
+
'Which country would you like to see?',
|
243 |
+
(df_f1_cou_circuits)
|
244 |
+
, index = idx)
|
245 |
+
|
246 |
+
detail = country
|
247 |
+
|
248 |
+
st.sidebar.write('You selected:', detail)
|
249 |
+
|
250 |
+
# Filter Data based on Map Type
|
251 |
+
filter_data(map_type, detail)
|
252 |
+
|
253 |
+
# Draw the 'World' folium Map
|
254 |
+
# draw_folium_map(map_type)
|
255 |
+
|
256 |
+
st.title('Plotting F1 Circuit Locations into a map on Streamlit on Hugging Face using Folium')
|
257 |
+
|
258 |
+
if map_type == 'World':
|
259 |
+
|
260 |
+
st.subheader('Map of the ' + map_type )
|
261 |
+
|
262 |
+
else:
|
263 |
+
|
264 |
+
st.subheader('Map of ' + map_type + ' ' + detail)
|
265 |
+
|
266 |
+
|
267 |
+
# Render Folium Map in Streamlit
|
268 |
+
st_data = st_folium(CircuitsMap, width = 1250)
|