Spaces:
Running
Running
File size: 11,521 Bytes
6546fcc 663f4dc 063f62f 42bcde6 6546fcc b46a94b 727ab43 42bcde6 8f7f056 cdea60a 6546fcc 333044f 3743999 817fac1 f372543 5df022a 6546fcc aecdb18 063f62f 663f4dc 727ab43 b46a94b 727ab43 663f4dc b206342 8ab68f6 b206342 663f4dc 6546fcc 663f4dc 70ff6a7 8ab68f6 70ff6a7 8ab68f6 663f4dc 8ab68f6 663f4dc 99bdfc3 42bcde6 c2a03fa f372543 6546fcc 663f4dc 6546fcc 663f4dc 6546fcc aecdb18 b46a94b b206342 781e030 b46a94b 83ebe75 6546fcc 663f4dc 6546fcc 663f4dc 6546fcc 99bdfc3 6546fcc 99bdfc3 08126da b46a94b 99bdfc3 8ab68f6 99bdfc3 83ebe75 aecdb18 8ab68f6 83ebe75 8ab68f6 99bdfc3 8ab68f6 6546fcc 13aaa12 6546fcc 663f4dc 6546fcc 663f4dc 6546fcc 663f4dc f5b2cdd 6546fcc 663f4dc 6546fcc 663f4dc 6546fcc f5b2cdd 663f4dc 6546fcc 13aaa12 6546fcc b46a94b 99bdfc3 7917b25 727ab43 7917b25 b206342 83ebe75 42bcde6 333044f 663f4dc 8816b15 663f4dc 333044f 8b31d63 663f4dc 8816b15 6d06a5a 42bcde6 13aaa12 57c8ad1 b25651f 5df022a 9863f7d 70ff6a7 5df022a 8816b15 5df022a 8816b15 5df022a | 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 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 | import streamlit as st
import warnings
warnings.filterwarnings("ignore")
st.set_page_config(layout="wide")
import folium
from streamlit_folium import st_folium
import pandas as pd
#import pymongo
from pymongo.errors import PyMongoError
import uuid
import datetime
import numpy as np
from st_aggrid import GridOptionsBuilder, AgGrid, GridUpdateMode, ColumnsAutoSizeMode
from FSM import view
from utils import construct_filters, construct_filters_geo,store_data, save_report
# from utils import display_sidebar
from modal import show_modal
import json
from preload import (
mongo_client,
mappatura_data,
color_data_regioni,
color_data_province,
color_data_comuni,
presence_regioni,
all_regions,
all_provinces,
all_munis,
presence_province,
presence_comuni,
)
from const import (
COLUMNS_SHOW,
HELP,
OPTIONS_DEPRIVATION,
OPTIONS_OBJECTIVE,
OPTIONS_ACTIVITIES,
OPTIONS_TARGET,
OPTIONS_AGE,
CRPL_SETTINGS,
available_years
)
#### INITIALIZATION
# Gets run only once when each user opens the app
if "init" not in st.session_state:
st.session_state["init"] = True
st.session_state["view"] = view()
st.session_state["id"] = uuid.uuid4()
st.session_state["last_row"] = None
if "logging_level" in st.secrets:
st.session_state["logging_level"] = st.secrets["logging_level"]
else:
st.session_state["logging_level"] = "basic"
store_data(
{
"UniqueID": st.session_state["id"],
"Timestamp": str(datetime.datetime.now()),
"Start": True,
},
mongo_client=mongo_client,
)
## Show the sidebar
#display_sidebar()
#### BUTTONS
# These functions deal with button clicks, in this case we really only need one I think...
def clicked_go_up():
st.session_state["view"].go_up()
@st.dialog("Come usare questa app?")
def info():
# st.write("**Come usare questa app?**")
for item in HELP:
st.write(item)
#### LAYOUT of the main page is in two columns, feel free to change this...
col1, col2 = st.columns([2, 1])
#### The second column are the filters
with col2:
st.button(
":grey_question: Come usare questa app",
key="info",
type="primary",
on_click=info,
)
with st.container(border=True):
st.write("**Filtri**")
st.multiselect(
label="Apprendimento/privazione educativa *",
options=OPTIONS_DEPRIVATION,
key="filter_deprivation",
)
st.multiselect(
label="Obiettivo dell'iniziativa",
options=OPTIONS_OBJECTIVE,
key="filter_objective",
)
st.multiselect(
label="Attività realizzate",
options=OPTIONS_ACTIVITIES,
key="filter_activities",
)
st.multiselect(
label="Target",
options=OPTIONS_TARGET,
key="filter_target",
)
st.multiselect(
label="Età",
options=OPTIONS_AGE,
key="filter_age",
)
st.multiselect(
label="Anno",
options=available_years,
key="filter_year",
)
# NUOVO FILTRO
st.text_input(
label="Capofila progetto",
placeholder="Inserisci il nome del capofila...",
key="filter_capofila",
)
# st.multiselect(label="ambito territoriale",options=["Internazionale","Multi-regionale","Regionale","Locale"], key="filter_level")
for k in range(1):
st.write("")
st.caption(
"*Per la definizione delle categorie riportate è stata utilizzata la classificazione messa a punto da Save the Children"
)
#### dynamic color
#### DATA
color_masks = construct_filters(st.session_state, mappatura_data)
df_color = mappatura_data[color_masks]
chosen_ids = list(df_color["_id"])
color_reg_dyn = np.zeros(len(all_regions))
color_pro_dyn = np.zeros(len(all_provinces))
color_mun_dyn = np.zeros(len(all_munis))
for id in chosen_ids:
color_reg_dyn += np.array(presence_regioni[id])
color_pro_dyn += np.array(presence_province[id])
color_mun_dyn += np.array(presence_comuni[id])
color_data_regioni2 = pd.DataFrame({"reg_name": all_regions, "color": color_reg_dyn})
color_data_province2 = pd.DataFrame({"prov_name": all_provinces, "color": color_pro_dyn})
color_data_comuni2 = pd.DataFrame({"name": all_munis, "color": color_mun_dyn})
# PARTE DI CODICE DI CONTROLLO PER DEBUGGING ACCENTI
#print(color_data_comuni.head(20))
#print(color_data_comuni2.head(20))
#print(color_data_comuni2[
# color_data_comuni2["name"].str.contains(
# "è|é|à|ò|ù|ì",
# regex=True,
# na=False
# )
#].head(50))
# FINE CODICE DI CONTROLLO
#### MAP
# This part of the code deals with the map
# Use the Finite State Machine class to figure out what to show.
map_name, cur_center, cur_zoom = st.session_state["view"].render()
base_map = folium.Map(location=cur_center, zoom_start=cur_zoom, scrollWheelZoom=False)
# This is the tooltip section, depending on the level we show different tooltips
# it could be made fancier, but this is just an example
CRPL_SETTINGS[0]["data"] = color_data_regioni2
CRPL_SETTINGS[1]["data"] = color_data_province2
CRPL_SETTINGS[2]["data"] = color_data_comuni2
cp_level = st.session_state["view"].level
#<<<<<<< HEAD
#with open(map_name, encoding="utf-8") as f: # aggiunta per codifica UTF8 su WIN
# geo_data = json.load(f) # aggiunta per codifica UTF8 su WIN
#
#choropleth = folium.Choropleth(
# geo_data=geo_data, # ← ora è un dict Python, non un path (geo_data al posto di map_name)
#=======
# Leggi il geojson pulito tramite geopandas (già caricato in st.session_state["view"].gp_frame o ricaricandolo)
#gdf = st.session_state["view"].gp_frame
# Converti il GeoDataFrame in una stringa/dizionario JSON pulito in UTF-8
#geo_json_data = gdf.__geo_interface__ # oppure json.loads(gdf.to_json())
#choropleth = folium.Choropleth(
# geo_data=geo_json_data, # <-- Passiamo direttamente l'oggetto python/json e non il path del file
#>>>>>>> e4b4165 (Corretto bug e problemi di visualizzazione)
# Leggi il geojson dal GeoDataFrame già caricato
gdf = st.session_state["view"].gp_frame
# Conversione in GeoJSON Python
geo_json_data = gdf.__geo_interface__
choropleth = folium.Choropleth(
geo_data=geo_json_data, # <-- Passiamo direttamente l'oggetto python/json e non il path del file
key_on=CRPL_SETTINGS[cp_level]["key_on"],
data=CRPL_SETTINGS[cp_level]["data"],
columns=CRPL_SETTINGS[cp_level]["columns"],
line_opacity=0.75,
highlight=True,
bins=CRPL_SETTINGS[cp_level]["bins"],
)
tooltip = folium.GeoJsonTooltip(CRPL_SETTINGS[cp_level]["tooltip"], aliases=[""])
tooltip.add_to(choropleth.geojson)
choropleth.geojson.add_to(base_map)
#placeholder2 = st.empty()
#### The first column is the map
with col1:
### This button is for going up: when clicked it calls the "go_up function"
# st.button(label=":arrow_up: Vai al livello territoriale superiore",type='primary', on_click=clicked_go_up)
### This is the map, here we call it, which means it will be displayed here.
st.button(
label=":arrow_up: Vai al livello territoriale superiore",
type="primary",
on_click=clicked_go_up,
)
st_data = st_folium(base_map, height=600, width=600)
if st_data is not None:
## When the map is clicked the 'last_active_drawing' variable is filled with the properties of the clicked object
## I check that it exists and it is not empty, that means the map was clicked.
if (
"last_active_drawing" in st_data
and st_data["last_active_drawing"] is not None
):
last_level = st.session_state["view"].level
## Update the Finite State Machine
st.session_state["view"].go_down(
st_data["last_active_drawing"]["properties"]
)
## I use the "last_level" to see if I just transitioned from province to comune level, in that case I rerun the script.
if last_level < 2:
## This means we are drilling down so we need to rerun the script.
st.rerun()
else:
## This means we are already at the comune level, so we just changed the comune view...
pass
# st.write(st_data["last_active_drawing"]['properties']['name'])
else:
pass
if st_data is None:
st.write("None")
#### DATA
full_masks = construct_filters_geo(st.session_state, mappatura_data, st_data)
df_display = mappatura_data[full_masks]
# This part of the code deals with the data table
# st.write(df_display.columns.tolist()) per verificare i nomi delle colonne del dataframe
df_display.columns = df_display.columns.str.strip() # questo comando serve a eliminare gli spazi prima e dopo i nomi delle colonne//proprietà
gb = GridOptionsBuilder.from_dataframe(df_display[COLUMNS_SHOW])
col_width = 600
gb.configure_column(
"Titolo",
header_name="Titolo",
editable=False,
width=col_width,
initialWidth=col_width,
maxWidth=col_width,
minWidth=col_width,
suppressSizeToFit=True,
)
gb.configure_column(
"Apprendimento/privazione educativa",
header_name="Apprendimento",
editable=False,
width=col_width,
initialWidth=col_width,
maxWidth=col_width,
minWidth=col_width,
suppressSizeToFit=True,
)
gb.configure_column(
"Obiettivo sintetico",
header_name="Obiettivo",
editable=False,
width=col_width,
initialWidth=col_width,
maxWidth=col_width,
minWidth=col_width,
suppressSizeToFit=True,
)
gb.configure_column(
"Attività sintetico",
header_name="Attività",
editable=False,
width=col_width,
initialWidth=col_width,
maxWidth=col_width,
minWidth=col_width,
suppressSizeToFit=True,
)
gb.configure_column(
"Target",
header_name="Target",
editable=False,
width=col_width,
initialWidth=col_width,
maxWidth=col_width,
minWidth=col_width,
suppressSizeToFit=True,
)
gb.configure_column(
"Link",
header_name="Link",
editable=False,
width=col_width,
initialWidth=col_width,
maxWidth=col_width,
minWidth=col_width,
suppressSizeToFit=True,
)
gb.configure_selection(selection_mode="single")
gb.configure_side_bar()
gridOptions = gb.build()
# cols = gridOptions['columnDefs']
# for col in cols:
# if col['field'] == 'Titolo':
# col["suppressSizeToFit"] = True
#with placeholder2:
data = AgGrid(
df_display,
gridOptions=gridOptions,
enable_enterprise_modules=False,
allow_unsafe_jscode=True,
update_mode=GridUpdateMode.SELECTION_CHANGED,
columns_auto_size_mode=ColumnsAutoSizeMode.FIT_ALL_COLUMNS_TO_VIEW,
)
save_report(st.session_state, modal=None, error=None)
if "selected_rows" in data and data["selected_rows"] is not None:
selected_row = data["selected_rows"].iloc[0].to_dict()
if "last_displayed_popup" in st.session_state:
if st.session_state["last_displayed_popup"] != selected_row["Titolo"]:
st.session_state["last_displayed_popup"] = selected_row["Titolo"]
show_modal(selected_row)
else:
st.session_state["last_displayed_popup"] = selected_row["Titolo"]
show_modal(selected_row)
|