Fabiobert commited on
Commit
99bdfc3
·
1 Parent(s): 8f7f056

Update app.py

Browse files

With contens from app_fab.py

Files changed (1) hide show
  1. app.py +153 -41
app.py CHANGED
@@ -6,12 +6,12 @@ from FSM import view
6
  import pymongo
7
  import uuid
8
  import datetime
 
9
 
10
  st.set_page_config(layout="wide")
11
 
12
  #### Handling the db
13
-
14
- #With this piece I connect to the
15
  @st.cache_resource()
16
  def get_database_client():
17
  client = pymongo.MongoClient(st.secrets["mongodb_string"])
@@ -48,7 +48,6 @@ with st.sidebar:
48
  st.write("Versione di prova")
49
 
50
 
51
-
52
  #### DATA
53
  # This part of the code deals with the data
54
  # In the future we will precompute this a load it once not every time the app reruns
@@ -56,21 +55,54 @@ with st.sidebar:
56
  # This is a stand-in for the data that tell us the colors on the map,
57
  # I would suggest we precompute these and make the number proportional to the amount of money or projects in the given entity
58
  # We can load it from a csv file (for example)
59
- color_data = pd.DataFrame({"reg_istat_code_num":[1,2,7],"color":[1,2,3]})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
 
61
  # This is a stand-in for the real data of your mappatura
62
  # We can load it from a csv file (for example)
63
- mappatura_data = pd.DataFrame(
64
- {
65
- "Progetto":["NGO1","NGO2"],
66
- "Ente Finanziatore":["Fondazione Ulaop CRT","Con i Bambini"],
67
- "Linea di finanziamento":["Attivià ordinarie","Un passo avanti"],
68
- "Target":["Bambini","Famiglie"],
69
- "Ambito territoriale":["Locale","Nazionale"],
70
- "Comuni":["Torino","Asti, Firenze, Milano, Napoli"],
71
- "Conteggio":[1,2]
72
- }
73
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
 
75
  #### BUTTONS
76
  # These functions deal with button clicks, in this case we really only need one I think...
@@ -85,26 +117,59 @@ def clicked_go_up():
85
  # Use the Finite State Machine class to figure out what to show.
86
  map_name, cur_center, cur_zoom = st.session_state['view'].render()
87
 
88
- base_map = folium.Map(location=cur_center, zoom_start=cur_zoom)
89
 
90
  # This is the overlaid data, we can get more fancy here
91
- choropleth = folium.Choropleth(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92
  geo_data=map_name,
93
- key_on='feature.properties.reg_istat_code_num',
94
- data=color_data,
95
- columns=["reg_istat_code_num","color"],
96
  line_opacity=0.75,
97
  highlight=True
98
  )
99
 
100
 
101
- # This is the tooltip section, depending on the level we show different tooltips
102
- # it could be made fancier, but this is just an example
103
- if st.session_state['view'].level == 0:
104
  tooltip = folium.GeoJsonTooltip(['reg_name'],aliases=[''])
 
 
105
  if st.session_state['view'].level == 1:
 
 
 
 
 
 
 
 
 
 
106
  tooltip = folium.GeoJsonTooltip(['prov_name'],aliases=[''])
107
  if st.session_state['view'].level == 2:
 
 
 
 
 
 
 
 
 
 
108
  tooltip = folium.GeoJsonTooltip(['name'],aliases=[''])
109
 
110
  tooltip.add_to(choropleth.geojson)
@@ -117,7 +182,7 @@ col1, col2 = st.columns([2,1])
117
  #### The first column is the map
118
  with col1:
119
  ### This button is for going up: when clicked it calls the "go_up function"
120
- st.button(label=":arrow_up: Vai su",type='primary', on_click=clicked_go_up)
121
 
122
  ### This is the map, here we call it, which means it will be displayed here.
123
  st_data = st_folium(base_map,height=600,width=600)
@@ -128,7 +193,6 @@ with col1:
128
 
129
  if "last_active_drawing" in st_data and st_data["last_active_drawing"] is not None:
130
 
131
- #st.write(st_data["last_active_drawing"])
132
  last_level = st.session_state['view'].level
133
 
134
  ## Update the Finite State Machine
@@ -148,32 +212,80 @@ with col1:
148
  #### The second column are the filters
149
 
150
  with col2:
151
- st.multiselect(label="Filtra per Target",options=["Bambini","Famiglie","Altro"], key="filter_focus")
152
- st.multiselect(label="Filtra per ambito territoriale",options=["Nazionale","Regionale","Locale"], key="filter_level")
 
 
153
 
154
 
155
  #### DATA
156
  # This part of the code deals with the data table
157
 
158
- query_focus = " | ".join([f'Target == "{item}"' for item in st.session_state["filter_focus"]])
159
- query_level = " | ".join([f'"Ambito territoriale" == "{item}"' for item in st.session_state["filter_level"]])
160
 
 
 
 
 
161
 
162
- if st.session_state['view'].level == 2:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
163
  if "last_active_drawing" in st_data and st_data["last_active_drawing"] is not None:
164
- query_locations = 'Comuni == "'+st_data['last_active_drawing']['properties']['name']+'"'
 
 
165
  else:
166
- query_locations = ""
167
- else:
168
- query_locations = ""
 
 
 
 
 
 
 
 
169
 
170
- queries = [query_focus,query_level, query_locations]
 
171
 
172
- bracketed = ["("+query+")" for query in queries if (query != "")]
173
- query = " & ".join(bracketed)
174
 
 
175
 
176
- if query == '':
177
- st.dataframe(data=mappatura_data)
178
- else:
179
- st.dataframe(data=mappatura_data.query("("+query+")"))
 
6
  import pymongo
7
  import uuid
8
  import datetime
9
+ import pickle
10
 
11
  st.set_page_config(layout="wide")
12
 
13
  #### Handling the db
14
+
 
15
  @st.cache_resource()
16
  def get_database_client():
17
  client = pymongo.MongoClient(st.secrets["mongodb_string"])
 
48
  st.write("Versione di prova")
49
 
50
 
 
51
  #### DATA
52
  # This part of the code deals with the data
53
  # In the future we will precompute this a load it once not every time the app reruns
 
55
  # This is a stand-in for the data that tell us the colors on the map,
56
  # I would suggest we precompute these and make the number proportional to the amount of money or projects in the given entity
57
  # We can load it from a csv file (for example)
58
+
59
+ regioni_counts = pickle.load(open("regioni.pkl",'rb'))
60
+ reg_names = [key for key in regioni_counts.keys()]
61
+ reg_counts = [value for value in regioni_counts.values()]
62
+
63
+ color_data_regioni = pd.DataFrame({"reg_name":reg_names,"color":reg_counts})
64
+
65
+ province_counts = pickle.load(open("province.pkl",'rb'))
66
+ prov_names = [key for key in province_counts.keys()]
67
+ prov_counts = [value for value in province_counts.values()]
68
+
69
+ color_data_province = pd.DataFrame({"prov_name":prov_names,"color":prov_counts})
70
+
71
+ comuni_counts = pickle.load(open("comuni.pkl",'rb'))
72
+ com_names = [key for key in comuni_counts.keys()]
73
+ com_counts = [value for value in comuni_counts.values()]
74
+
75
+ color_data_comuni = pd.DataFrame({"name":com_names,"color":com_counts})
76
+
77
 
78
  # This is a stand-in for the real data of your mappatura
79
  # We can load it from a csv file (for example)
80
+ # mappatura_data = pd.DataFrame(
81
+ # {
82
+ # "Progetto":["NGO1","NGO2"],
83
+ # "Ente Finanziatore":["Fondazione Ulaop CRT","Con i Bambini"],
84
+ # "Linea di finanziamento":["Attivià ordinarie","Un passo avanti"],
85
+ # "Target":["Bambini","Famiglie"],
86
+ # "Ambito territoriale":["Locale","Nazionale"],
87
+ # "Comuni":["Torino","Asti, Firenze, Milano, Napoli"],
88
+ # "Conteggio":[1,2]
89
+ # }
90
+ # )
91
+
92
+ #Load data method 1: load data from CSV:
93
+ #df = pd.read_csv('data/Database_poverta_educativa_beta_exp.csv', sep='|', encoding="latin-1")
94
+
95
+ #Load data method 2: import a MongoDB collection:
96
+ client = pymongo.MongoClient("mongodb+srv://mappatura_poved:U2Wx9TV46RcZT9Yl@cluster0.4w0zgb1.mongodb.net/?uuidRepresentation=standard")
97
+ col = client['poverta_educativa']['database_mappatura']
98
+
99
+ #select columns from the dataframe
100
+ #cursor = col.find({}, {"livello_analisi": 1, "titolo": 1, "ente_finanziatore": 1, "linea_finanz_bando": 1, "tipo_finanziatore": 1, "ambito_territoriale": 1, "apprendimento_privaz_edu": 1, "obiettivo_sintetico": 1, "attivita_sintetico": 1, "Target": 1, "Capofila": 1, "Partner": 1,"Data_inizio": 1, "Data_fine": 1, "Comuni_intervento": 1, "Province_intervento": 1, "Regioni_intervento": 1})
101
+
102
+ mappatura_tot = pd.DataFrame(list(col.find()))
103
+ mappatura_data = mappatura_tot.drop(['_id','Budget','Budget completo di cofinanziamento (*se noto)'], axis=1)
104
+ mappatura_data['Data inizio'] = mappatura_data["Data inizio"].astype(str)
105
+ mappatura_data['Data fine (prevista o effettiva)'] = mappatura_data["Data fine (prevista o effettiva)"].astype(str)
106
 
107
  #### BUTTONS
108
  # These functions deal with button clicks, in this case we really only need one I think...
 
117
  # Use the Finite State Machine class to figure out what to show.
118
  map_name, cur_center, cur_zoom = st.session_state['view'].render()
119
 
120
+ base_map = folium.Map(location=cur_center, zoom_start=cur_zoom, scrollWheelZoom=False)
121
 
122
  # This is the overlaid data, we can get more fancy here
123
+ # choropleth = folium.Choropleth(
124
+ # geo_data=map_name,
125
+ # key_on='feature.properties.reg_istat_code_num',
126
+ # data=color_data,
127
+ # columns=["reg_istat_code_num","color"],
128
+ # line_opacity=0.75,
129
+ # highlight=True
130
+ # )
131
+
132
+
133
+ # This is the tooltip section, depending on the level we show different tooltips
134
+ # it could be made fancier, but this is just an example
135
+ if st.session_state['view'].level == 0:
136
+
137
+ choropleth = folium.Choropleth(
138
  geo_data=map_name,
139
+ key_on='feature.properties.reg_name',
140
+ data=color_data_regioni,
141
+ columns=["reg_name","color"],
142
  line_opacity=0.75,
143
  highlight=True
144
  )
145
 
146
 
 
 
 
147
  tooltip = folium.GeoJsonTooltip(['reg_name'],aliases=[''])
148
+
149
+
150
  if st.session_state['view'].level == 1:
151
+
152
+ choropleth = folium.Choropleth(
153
+ geo_data=map_name,
154
+ key_on='feature.properties.prov_name',
155
+ data=color_data_province,
156
+ columns=["prov_name","color"],
157
+ line_opacity=0.75,
158
+ highlight=True
159
+ )
160
+
161
  tooltip = folium.GeoJsonTooltip(['prov_name'],aliases=[''])
162
  if st.session_state['view'].level == 2:
163
+
164
+ choropleth = folium.Choropleth(
165
+ geo_data=map_name,
166
+ key_on='feature.properties.name',
167
+ data=color_data_comuni,
168
+ columns=["name","color"],
169
+ line_opacity=0.75,
170
+ highlight=True
171
+ )
172
+
173
  tooltip = folium.GeoJsonTooltip(['name'],aliases=[''])
174
 
175
  tooltip.add_to(choropleth.geojson)
 
182
  #### The first column is the map
183
  with col1:
184
  ### This button is for going up: when clicked it calls the "go_up function"
185
+ st.button(label=":arrow_up: Vai al livello superiore",type='primary', on_click=clicked_go_up)
186
 
187
  ### This is the map, here we call it, which means it will be displayed here.
188
  st_data = st_folium(base_map,height=600,width=600)
 
193
 
194
  if "last_active_drawing" in st_data and st_data["last_active_drawing"] is not None:
195
 
 
196
  last_level = st.session_state['view'].level
197
 
198
  ## Update the Finite State Machine
 
212
  #### The second column are the filters
213
 
214
  with col2:
215
+ st.multiselect(label="Filtra per Target",options=["Minori 0-6 anni","Minori 6-11 anni","Minori 11-14 anni","Minori 14-16 anni","Minori - residuale","BES - Disabilità","BES - Disturbi evolutivi specifici","BES – Svantaggio socio-economico, linguistico, culturale","Famiglie","Comunità","Minori Complessovo"], key="filter_target")
216
+ st.multiselect(label="Filtra per ambito territoriale",options=["Internazionale","Multi-regionale","Regionale","Locale"], key="filter_level")
217
+ st.multiselect(label="Filtra per obiettivo dell'iniziativa",options=["Contrasto alla dispersione scolastica","Elaborazione modelli e disseminazione di buone pratiche","Inclusione","Percorsi post-traumatici","Riduzione delle diseguaglianze territoriali","Sostegno alla genitorialità","Sviluppo comunità educante","Sviluppo delle competenze soft","Sviluppo delle competenze hard","Benessere psicologico"], key="filter_objective")
218
+ st.multiselect(label="Filtra per attività realizzate",options=["Accompagnamento psicologico e terapeutico","Attività sportive","Attività culturali e di valorizzazione del patrimonio (storico, artistico, naturalistico, paesaggistico)","Co-progettazione con minori e famiglie e protagonismo minorile","Formazione","Incentivo economico"," Rafforzamento dei servizi e delle reti territoriali","Interventi sugli spazi","Laboratori","Attività di ricerca e attività di raccolta dei bisogni","Socializzazione","Sostegno didattico e orientamento","out reaching-aggancio","Informazione, comunicazione territoriale e sensibilizzazione","attività e percorsi di giustizizia riparativa","altro"], key="filter_activities")
219
 
220
 
221
  #### DATA
222
  # This part of the code deals with the data table
223
 
224
+ trues = [True for i in range(len(mappatura_data))]
225
+ df_true = pd.DataFrame({'true':trues})
226
 
227
+ if len(st.session_state["filter_target"]) > 0:
228
+ target_masks = sum([mappatura_data['Target'].str.contains(item) for item in st.session_state["filter_target"]])
229
+ else:
230
+ target_masks = df_true['true']
231
 
232
+ if len(st.session_state["filter_level"]) > 0:
233
+ level_masks = sum([mappatura_data['Ambito territoriale'].str.contains(item) for item in st.session_state["filter_level"]])
234
+ else:
235
+ level_masks = df_true['true']
236
+
237
+ if len(st.session_state["filter_objective"]) > 0:
238
+ objective_masks = sum([mappatura_data['Obiettivo sintetico'].str.contains(item) for item in st.session_state["filter_objective"]])
239
+ else:
240
+ objective_masks = df_true['true']
241
+
242
+ if len(st.session_state["filter_activities"]) > 0:
243
+ # FIXME: `Attività sitentico`
244
+ activities_masks = sum([mappatura_data['Attività sintentico'].str.contains(item) for item in st.session_state["filter_activities"]])
245
+ else:
246
+ activities_masks = df_true['true']
247
+
248
+ #query_target = " | ".join([f'Target == "{item}"' for item in st.session_state["filter_target"]])
249
+ #query_level = " | ".join([f'`Ambito territoriale` == "{item}"' for item in st.session_state["filter_level"]])
250
+ #query_objective = " | ".join([f'`Obiettivo sintetico` == "{item}"' for item in st.session_state["filter_objective"]])
251
+ #query_activities = " | ".join([f'`Attività sintetico` == "{item}"' for item in st.session_state["filter_activities"]])
252
+
253
+
254
+ last_level=st.session_state['view'].level
255
+
256
+ geo_masks = df_true['true']
257
+
258
+ if last_level == 1:
259
+ #query_regione = '`Regioni di intervento` == "'+st.session_state['view'].hierarchy_names[-1]+'"'
260
+ geo_masks = mappatura_data['Regioni di intervento'].str.contains(st.session_state['view'].hierarchy_names[-1])
261
+
262
+
263
+ if last_level == 2:
264
  if "last_active_drawing" in st_data and st_data["last_active_drawing"] is not None:
265
+ #query_comune = '`Comuni di intervento` == "'+st_data['last_active_drawing']['properties']['name']+'"'
266
+ geo_masks = mappatura_data['Comuni di intervento'].str.contains(st_data['last_active_drawing']['properties']['name'])
267
+
268
  else:
269
+ #query_provincia = '`Province di intervento` == "'+st.session_state['view'].hierarchy_names[-1]+'"'
270
+ geo_masks = mappatura_data['Province di intervento'].str.contains(st.session_state['view'].hierarchy_names[-1])
271
+
272
+
273
+ full_masks = target_masks & level_masks & objective_masks & activities_masks & geo_masks
274
+
275
+ df_display = mappatura_data[full_masks]
276
+
277
+ #queries = [query_target, query_level, query_objective, query_activities, query_comune, query_provincia, query_regione]
278
+
279
+ #st.write(queries)
280
 
281
+ #bracketed = ["("+query+")" for query in queries if (query != "")]
282
+ #query = " & ".join(bracketed)
283
 
284
+ #st.write(f"Query is: {query}")
 
285
 
286
+ st.dataframe(data=df_display)
287
 
288
+ #if query == '':
289
+ # st.dataframe(data=mappatura_data)
290
+ #else:
291
+ # st.dataframe(data=mappatura_data.query("("+query+")"))