albertoakel commited on
Commit
75c6e74
·
0 Parent(s):

Initial clean deploy (no binary files)

Browse files
Files changed (12) hide show
  1. .gitattributes +35 -0
  2. .gitignore +10 -0
  3. Dockerfile +30 -0
  4. README.md +10 -0
  5. app_04.py +46 -0
  6. assets/style.css +38 -0
  7. callbacks.py +74 -0
  8. download_data.py +25 -0
  9. fig_plots.py +485 -0
  10. layout_01.py +183 -0
  11. load_process.py +90 -0
  12. requirements.txt +14 -0
.gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ # Dados grandes / binários
2
+ *.gpkg
3
+ *.shp
4
+ *.dbf
5
+ *.shx
6
+ *.geojson
7
+ data/process/*.gpkg
8
+ *.gpkg
9
+ data/
10
+ maps/
Dockerfile ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.10-slim
2
+
3
+ # Evita prompts
4
+ ENV DEBIAN_FRONTEND=noninteractive
5
+
6
+ # Dependências do sistema (GEOPANDAS + FOLIUM)
7
+ RUN apt-get update && apt-get install -y \
8
+ gdal-bin \
9
+ libgdal-dev \
10
+ libproj-dev \
11
+ proj-data \
12
+ proj-bin \
13
+ build-essential \
14
+ && rm -rf /var/lib/apt/lists/*
15
+
16
+ # Diretório de trabalho
17
+ WORKDIR /app
18
+
19
+ # Copiar arquivos
20
+ COPY . /app
21
+
22
+ # Instalar dependências Python
23
+ RUN pip install --upgrade pip
24
+ RUN pip install -r requirements.txt
25
+
26
+ # Porta padrão do Spaces
27
+ EXPOSE 7860
28
+
29
+ # Comando de inicialização
30
+ CMD ["gunicorn", "app_04:server", "--bind", "0.0.0.0:7860", "--workers", "1"]
README.md ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Dash Apps Docker Vs
3
+ emoji: 👁
4
+ colorFrom: pink
5
+ colorTo: blue
6
+ sdk: docker
7
+ pinned: false
8
+ ---
9
+
10
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app_04.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # app_04.py
3
+ import os
4
+ import dash
5
+ from load_process import load_files
6
+ from layout_01 import criar_layout
7
+ from callbacks import registrar_callbacks
8
+ from flask_caching import Cache
9
+
10
+
11
+
12
+ # Leitura dos dados
13
+ #gdf_m,df_plot,list_feature,feat_options=load_files() #original
14
+ gdf_m,df_plot,list_feature,feat_options,gdf_p =load_files(ponto_descarte=True)
15
+
16
+ descriptions_map = {
17
+ opt['value']: opt['description']
18
+ for opt in feat_options
19
+ if opt.get('description') is not None
20
+ }
21
+
22
+ # APP
23
+ app = dash.Dash(__name__)
24
+ server = app.server #to render deploy
25
+
26
+ # Inicialização do CACHE
27
+ cache = Cache(server, config={
28
+ 'CACHE_TYPE': 'SimpleCache',
29
+ 'CACHE_DEFAULT_TIMEOUT': 300 # segundos
30
+ })
31
+
32
+ # Configurar layout
33
+ app.layout = criar_layout(feat_options)
34
+
35
+ # Registrar callbacks
36
+ registrar_callbacks(app, df_plot, gdf_m,descriptions_map,gdf_p,cache)
37
+
38
+ # if __name__ == '__main__':
39
+ # app.run(debug=True, host='0.0.0.0', port=8050)
40
+
41
+
42
+
43
+ # Execução local (ignorado por Gunicorn)
44
+ if __name__ == '__main__':
45
+ port = int(os.environ.get("PORT", 8050))
46
+ app.run(debug=False, host='0.0.0.0', port=port)
assets/style.css ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* style.css */
2
+ .dropdown-alto .Select-control {
3
+ height: 52px;
4
+ display: flex;
5
+ align-items: center;
6
+ font-size: 24px;
7
+ }
8
+
9
+ .dropdown-alto .Select-value {
10
+ position: absolute;
11
+ left: 0;
12
+ right: 0;
13
+ top: 50%;
14
+ transform: translateY(+20%);
15
+ text-align: center;
16
+ pointer-events: none;
17
+ }
18
+
19
+ .dropdown-alto .Select-value-label {
20
+ width: 100%;
21
+ text-align: center;
22
+ }
23
+
24
+ .dropdown-alto .Select-placeholder {
25
+ position: absolute;
26
+ left: 0;
27
+ right: 0;
28
+ top: 50%;
29
+ transform: translateY(+20%);
30
+ text-align: center;
31
+ }
32
+
33
+ .dropdown-alto .Select-arrow-zone {
34
+ margin-left: auto;
35
+ padding-right: 10px;
36
+ display: flex;
37
+ align-items: center;
38
+ }
callbacks.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # callbacks.py
3
+ from dash import Input, Output
4
+ from fig_plots import *
5
+
6
+ def registrar_callbacks(app, df_plot, gdf_m,descriptions_map,gdf_p=None,cache=None ):
7
+ """
8
+ df_plot : DataFrame analítico sem geometria
9
+ Usado para gráficos estatísticos
10
+ gdf_m : GeoDataFrame com geometria
11
+ Usado exclusivamente para mapas
12
+ gdp_p : GeoDataFrama com pontos de descartes(opcional)
13
+ cache : Flask-Caching (opcional)
14
+ """
15
+
16
+
17
+ if cache is not None:
18
+ decorator = cache.memoize()
19
+ #print("Cache ATIVADO nos callbacks")
20
+ else:
21
+ decorator = lambda f: f
22
+ #print("Cache DESATIVADO nos callbacks")
23
+
24
+ if gdf_p is not None:
25
+ pass
26
+
27
+ @app.callback(
28
+ [Output('kpis', 'children'),
29
+ Output('descricao-variavel', 'children'), # <<< 2º OUTPUT ADICIONADO
30
+ Output('mapa', 'srcDoc'),
31
+ Output('fig_rank', 'figure'),
32
+ Output('fig_hist', 'figure'),
33
+ Output('fig_box', 'figure'),
34
+ Output('fig_scatter', 'figure')],
35
+ Input('variavel', 'value')
36
+ )
37
+ @decorator
38
+ def atualizar(var):
39
+
40
+ # métrica KPIS
41
+ kpis =kpis_out(df=df_plot,x=var)
42
+
43
+ # Descrição da variavel Dropdown
44
+ description_text = descriptions_map.get(var,"Descrição não disponível para a variável: " + str(var))
45
+ descricao_componente = html.P([description_text], style={'margin': '0'})
46
+
47
+ # Mapa
48
+ #mapa=mapa_folium(gdf=gdf_m, x=var)
49
+ mapa=mapa_folium(gdf=gdf_m, x=var,gdf_d=gdf_p)
50
+
51
+
52
+ #Rank
53
+ fig_rank=toptop_bairro(df=df_plot,x=var)
54
+
55
+ #Histograma
56
+ fig_hist=histplot_bairro_px(df=df_plot,x=var)
57
+
58
+ #Boxplot
59
+ fig_box=boxplot_bairro_px(df=df_plot,x=var)
60
+
61
+ #dispersão
62
+ fig_scatter = scatterplot_bairro_px(df=df_plot, x=var,hue_var='Risco')
63
+
64
+ # FUNDO TRANSPARENTE PARA TODOS
65
+ for fig in [fig_hist, fig_box, fig_rank, fig_scatter]:
66
+ fig.update_layout(
67
+ paper_bgcolor='rgba(0.0,0,0,0)',
68
+ plot_bgcolor='rgba(0.0,0,0,0)',
69
+ font=dict(size=12)
70
+ )
71
+
72
+ return kpis,descricao_componente,mapa._repr_html_(), fig_rank,fig_hist, fig_box, fig_scatter
73
+
74
+ return atualizar
download_data.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from huggingface_hub import hf_hub_download
3
+
4
+ REPO_ID = "albertoakel/dados_belem"
5
+ SUBDIR = "data/process"
6
+
7
+ FILES = [
8
+ "shape_bairros.gpkg",
9
+ "shape_coleta.gpkg",
10
+ "Pontos_descartes_ML.gpkg",
11
+ "tabela_total_com_DIEs.csv",
12
+ "Bairros_Ncoleta.csv",
13
+ ]
14
+
15
+ def ensure_data():
16
+ paths = {}
17
+ for f in FILES:
18
+ path = hf_hub_download(
19
+ repo_id=REPO_ID,
20
+ filename=f"{SUBDIR}/{f}",
21
+ repo_type="dataset"
22
+ )
23
+ paths[f] = path
24
+ return paths
25
+
fig_plots.py ADDED
@@ -0,0 +1,485 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # fig_plots
3
+ import folium
4
+ import numpy as np
5
+ import pandas as pd
6
+ import plotly.colors
7
+ import plotly.graph_objects as go
8
+ from dash import html
9
+ from scipy.stats import pearsonr
10
+ from scipy.stats import t
11
+
12
+
13
+ def get_paleta(x,cor_unica=None):
14
+ paletas = {
15
+ 'area_km2': 'Blues',
16
+ 'Hab': 'YlOrRd',
17
+ 'Mor': 'YlOrRd',
18
+ 'Mor/Hab': 'YlOrRd',
19
+ 'N_ren': 'Reds',
20
+ 'NS': 'Reds',
21
+ 'ren_avg': 'RdYlGn',
22
+ 'ren_mdn': 'RdYlGn',
23
+ 'T.A.': 'RdBu',
24
+ 'IDH-R': 'RdBu',
25
+ 'IDH-L': 'RdBu',
26
+ 'IDH-E': 'RdBu',
27
+ 'IDH': 'RdBu',
28
+ 'QTI': 'RdYlGn',
29
+ 'CRA': 'Blues',
30
+ 'PPR': 'Reds',
31
+ 'nd_med': 'RdYlGn',
32
+ 'DIEs': 'RdYlGn_r',
33
+ 'N_setores': 'Blues'}
34
+
35
+ # Obtém a paleta ou usa padrão
36
+ paleta_name = paletas.get(x, 'Greys')
37
+ if cor_unica is not None:
38
+ scale_cor={'area_km2':0.50,
39
+ 'Hab':0.4,
40
+ 'ren_avg':0.2,
41
+ 'ren_mdn':0.15,
42
+ 'Mor/Hab':0.75,
43
+ 'T.A.':0.80,
44
+ 'IDH-R': 0.75,
45
+ 'IDH-L':0.75,
46
+ 'IDH':0.75,
47
+ 'CRA': 0.50,
48
+ 'IDH-E':0.75,
49
+ 'nd_med':0.80,
50
+ 'N_setores':0.5}
51
+ idx=scale_cor.get(x,0.25)
52
+ paleta_name = plotly.colors.sample_colorscale(paleta_name, [idx])[0]
53
+ return paleta_name
54
+
55
+ def kpis_out(df,x):
56
+ serie = df[x].dropna()
57
+
58
+ # Estilo compacto
59
+ card_style = {
60
+ 'background': 'white',
61
+ 'padding': '8px 5px', # Menor padding
62
+ 'borderRadius': '6px',
63
+ 'textAlign': 'center',
64
+ 'minHeight': '80px', # Altura controlada
65
+ }
66
+
67
+ kpis = [
68
+ html.Div([
69
+ html.H4(f'{serie.mean():.2f}', style={'margin': '5px 0', 'fontSize': '26px'}),
70
+ html.P('Média', style={'margin': '0', 'fontSize': '18px'})
71
+ ], style=card_style),
72
+
73
+ html.Div([
74
+ html.H4(f'{serie.median():.2f}', style={'margin': '5px 0', 'fontSize': '26px'}),
75
+ html.P('Mediana', style={'margin': '0', 'fontSize': '18px'})
76
+ ], style=card_style),
77
+
78
+ html.Div([
79
+ html.H4(f'{serie.max():.2f}', style={'margin': '5px 0', 'fontSize': '26px'}),
80
+ html.P('Máximo', style={'margin': '0', 'fontSize': '18px'})
81
+ ], style=card_style),
82
+
83
+ html.Div([
84
+ html.H4(f'{serie.min():.2f}', style={'margin': '5px 0', 'fontSize': '26px'}),
85
+ html.P('Mínimo', style={'margin': '0', 'fontSize': '18px'})
86
+ ], style=card_style)
87
+ ]
88
+ return kpis
89
+
90
+ def add_pontos_descartes(map,gdf_d):
91
+
92
+ ponto_colors = {
93
+ "Estimados": "gray",
94
+ "Dados": "back"}
95
+
96
+ layer_pontos = folium.FeatureGroup(name="Pontos (⚪Estimados/⚫ coletados)", show=False)
97
+
98
+ if gdf_d is not None and gdf_d.empty:
99
+ print("AVISO: GeoDataFrame de pontos está vazio!")
100
+
101
+ for _, row in gdf_d.iterrows():
102
+ try:
103
+ bairro = row["Bairro"]
104
+ lat = row["lat"]
105
+ lon = row["lon"]
106
+ cor = row["Cor"]
107
+
108
+ # Verificar coordenadas válidas
109
+ if pd.isna(lat) or pd.isna(lon):
110
+ print(f"AVISO: Coordenadas inválidas para bairro {bairro}")
111
+ continue
112
+
113
+ marker_color = ponto_colors.get(cor, "black")
114
+ popup_html = f"""
115
+ <b>Bairro:</b> {bairro}<br>
116
+ <b>Tipo:</b> {cor}<br>
117
+ <b>Lat:</b> {lat:.5f}<br>
118
+ <b>Lon:</b> {lon:.5f}
119
+ """
120
+
121
+ # Adicionar ao layer_pontos
122
+ folium.CircleMarker(
123
+ location=[lat, lon],
124
+ radius=3,
125
+ color=marker_color,
126
+ fill=True,
127
+ fill_color=marker_color,
128
+ fill_opacity=1,
129
+ popup=popup_html,
130
+ tooltip=f"{bairro} — {cor}"
131
+ ).add_to(layer_pontos)
132
+
133
+ except Exception as e:
134
+ print(f"Erro ao processar ponto: {e}")
135
+ continue
136
+
137
+ layer_pontos.add_to(map) # Adicionar layer_pontos ao mapa
138
+ folium.LayerControl().add_to(map) # Adicionar controle de camadas
139
+
140
+ return map
141
+
142
+ MAP_CACHE = {} # cache LOCAL do módulo
143
+ def mapa_folium(gdf, x,gdf_d=None):
144
+ if x in MAP_CACHE:
145
+
146
+ return MAP_CACHE[x]
147
+
148
+ paleta_name = get_paleta(x)
149
+
150
+ # Criar mapa
151
+ map = folium.Map(location=[-1.43, -48.42], zoom_start=12, tiles='CartoDB Positron')
152
+
153
+ # Choropleth
154
+ choropleth = folium.Choropleth(
155
+ geo_data=gdf,
156
+ data=gdf,
157
+ columns=['Bairro', x],
158
+ key_on='feature.properties.Bairro',
159
+ fill_color=paleta_name,
160
+ fill_opacity=0.7,
161
+ line_opacity=0.2,
162
+ legend_name=x
163
+ ).add_to(map)
164
+
165
+ # Tooltip
166
+ tooltip = folium.features.GeoJsonTooltip(
167
+ fields=['Bairro', x],
168
+ aliases=['Bairro', x],
169
+ style="font-size: 12px;"
170
+ )
171
+ choropleth.geojson.add_child(tooltip)
172
+
173
+ if gdf_d is not None:
174
+ map=add_pontos_descartes(map,gdf_d)
175
+ MAP_CACHE[x] = map
176
+
177
+ return map
178
+ else:
179
+ MAP_CACHE[x] = map
180
+
181
+ return map
182
+
183
+ def toptop_bairro(df,x):
184
+ paleta_name=get_paleta(x)
185
+
186
+ rank=15
187
+ top = df.nlargest(rank, x).sort_values(x, ascending=True)
188
+
189
+ # Define limites da escala de cores
190
+ cmin_val = df[x].min() # ou df[x].min() para escala global
191
+ cmax_val = df[x].max() # ou df[x].max() para escala global
192
+
193
+ fig = go.Figure()
194
+ fig.add_trace(
195
+ go.Bar(
196
+ y=top['Bairro'],
197
+ x=top[x],
198
+ orientation='h',
199
+ texttemplate='%{x:.2f}',
200
+ marker=dict(
201
+ color=top[x], # Valores para o gradiente
202
+ colorscale=paleta_name,
203
+ cmin=cmin_val,
204
+ cmax=cmax_val,
205
+ opacity=0.7,
206
+ line=dict(width=1, color='white')),
207
+ hovertemplate=f'<b>%{{y}}</b><br>{x}: %{{x}}<extra></extra>',
208
+ name=x
209
+ )
210
+ )
211
+ fig.update_layout(title='Bairros com maiores valores')
212
+ return fig
213
+
214
+
215
+ def histplot_bairro_px(df,x):
216
+
217
+ cor_hist=get_paleta(x,cor_unica=1)
218
+
219
+ nb=10
220
+ fig = go.Figure()
221
+ fig.add_trace(
222
+ go.Histogram(
223
+ x=df[x],
224
+ nbinsx=nb,
225
+ histnorm='percent',
226
+ texttemplate='%{y:.1f}%',
227
+ textposition='inside',
228
+ marker=dict(color=cor_hist,
229
+ line=dict(width=1, color='white')) ),
230
+ )
231
+ fig.update_layout(xaxis_title=x,yaxis_title='percentual(%)')
232
+
233
+ return fig
234
+
235
+ def boxplot_bairro_px(df,x):
236
+ cor_box=get_paleta(x,cor_unica=1)
237
+
238
+ fig = go.Figure()
239
+
240
+ fig.add_trace(
241
+ go.Box(
242
+ y=df[x],
243
+ boxpoints='all',
244
+ name=x,
245
+ opacity=1,
246
+ marker=dict(color=cor_box,
247
+ line=dict(width=1, color='white'),
248
+ opacity=0.99)) )
249
+
250
+ return fig
251
+
252
+
253
+ def scatterplot_bairro_px(df, x, hue_var=None, teste=None):
254
+ palette = {
255
+ "Ideal": "#02a84f",
256
+ "Baixo": "#f7e305",
257
+ "Alto": "#f7870f",
258
+ "Critico": "#f01707"}
259
+ cor_fill = get_paleta(x, cor_unica=1)
260
+
261
+ # =========================
262
+ # Colunas necessárias
263
+ # =========================
264
+ y = 'QTI'
265
+ cols = [x, y]
266
+
267
+ if hue_var:
268
+ cols.append(hue_var)
269
+
270
+ if "Bairro" in df.columns:
271
+ cols.append("Bairro")
272
+
273
+ dados = df[cols].dropna()
274
+
275
+ if x == hue_var:
276
+ dados.columns.values[0] = 'Risco'
277
+ x = 'Risco'
278
+ dados = dados.loc[:, ~dados.columns.duplicated()] # remover colunas duplicadas
279
+
280
+ if 'Risco' in dados.columns:
281
+ mapeamento = {
282
+ 1: 'Ideal',
283
+ 2: 'Baixo',
284
+ 3: 'Alto',
285
+ 4: 'Critico'}
286
+ dados['Risco'] = dados['Risco'].map(mapeamento)
287
+
288
+ if len(dados) < 2:
289
+ print('dados insuficientes')
290
+ return None
291
+ else:
292
+ x_vals = dados[x].values
293
+ y_vals = dados[y].values
294
+ correlacao, p_valor = pearsonr(x_vals, y_vals)
295
+
296
+ coef_angular, intercepto = np.polyfit(x_vals, y_vals, 1)
297
+
298
+ stats = {
299
+ "variavel_x": x,
300
+ "variavel_y": y,
301
+ "correlacao": correlacao,
302
+ "p_valor": p_valor,
303
+ "r_quadrado": correlacao ** 2,
304
+ "coef_angular": coef_angular,
305
+ "intercepto": intercepto,
306
+ "equacao": f"y = {coef_angular:.4f}x + {intercepto:.4f}",
307
+ "n": len(dados)}
308
+
309
+ # 1. Primeiro: CRIAR FIGURA VAZIA
310
+ fig = go.Figure()
311
+
312
+ # 2. SEGUNDO: Banda de confiança (camada mais baixa)
313
+ # Preparar dados da banda
314
+ x_range = np.linspace(x_vals.min(), x_vals.max(), 100)
315
+ y_pred = coef_angular * x_range + intercepto
316
+
317
+ n = len(x_vals)
318
+ x_mean = np.mean(x_vals)
319
+
320
+ # Resíduos e erro padrão
321
+ y_hat = coef_angular * x_vals + intercepto
322
+ residuos = y_vals - y_hat
323
+ s_err = np.sqrt(np.sum(residuos ** 2) / (n - 2))
324
+
325
+ # Inicializar variáveis
326
+ y_upper = None
327
+ y_lower = None
328
+ p_perm = None
329
+
330
+ if teste is None:
331
+ # Intervalo de confiança clássico
332
+ t_val = t.ppf(0.975, df=n - 2)
333
+ Sxx = np.sum((x_vals - x_mean) ** 2)
334
+ conf = t_val * s_err * np.sqrt(1 / n + (x_range - x_mean) ** 2 / Sxx)
335
+ y_upper = y_pred + conf
336
+ y_lower = y_pred - conf
337
+
338
+ elif teste == "bootstrap":
339
+ # Intervalo de confiança via bootstrap
340
+ B = 5000
341
+ y_boot = np.zeros((B, len(x_range)))
342
+ r_perm = np.zeros(B)
343
+
344
+ r_obs, _ = pearsonr(x_vals, y_vals)
345
+
346
+ for b in range(B):
347
+ idx = np.random.randint(0, n, n)
348
+ xb = x_vals[idx]
349
+ yb = y_vals[idx]
350
+ m_b, c_b = np.polyfit(xb, yb, 1)
351
+ y_boot[b, :] = m_b * x_range + c_b
352
+
353
+ y_perm = np.random.permutation(y_vals)
354
+ r_perm[b], _ = pearsonr(x_vals, y_perm)
355
+
356
+ p_perm = np.mean(np.abs(r_perm) >= abs(r_obs))
357
+ y_lower = np.percentile(y_boot, 2.5, axis=0)
358
+ y_upper = np.percentile(y_boot, 97.5, axis=0)
359
+
360
+ # Adicionar banda de confiança (PRIMEIRA camada)
361
+ if y_upper is not None and y_lower is not None:
362
+ fig.add_trace(
363
+ go.Scatter(
364
+ x=np.concatenate([x_range, x_range[::-1]]),
365
+ y=np.concatenate([y_upper, y_lower[::-1]]),
366
+ fill='toself',
367
+ fillcolor=cor_fill,
368
+ opacity=0.5,
369
+ line=dict(color='rgba(255,255,255,0)'),
370
+ hoverinfo="skip",
371
+ showlegend=False,
372
+ name='IC 95%'))
373
+
374
+ # 3. TERCEIRO: Linha de regressão (camada intermediária)
375
+ fig.add_trace(
376
+ go.Scatter(
377
+ x=x_range,
378
+ y=y_pred,
379
+ mode='lines',
380
+ line=dict(color='black', width=2, dash='solid'),
381
+ name='Linha de regressão',
382
+ showlegend=True,
383
+ legendgroup="regressao"
384
+ )
385
+ )
386
+
387
+ # 4. QUARTA: Pontos do scatterplot (camada mais ALTA/sobreposta)
388
+ if hue_var and hue_var in dados.columns:
389
+ categorias = dados[hue_var].unique()
390
+ for categoria in categorias:
391
+ dados_cat = dados[dados[hue_var] == categoria]
392
+
393
+ fig.add_trace(
394
+ go.Scatter(
395
+ x=dados_cat[x],
396
+ y=dados_cat[y],
397
+ mode='markers',
398
+ marker=dict(
399
+ size=12,
400
+ color=palette.get(categoria, '#888888'),
401
+ opacity=1
402
+ ),
403
+ name=str(categoria),
404
+ text=dados_cat['Bairro'] if 'Bairro' in dados_cat.columns else None,
405
+ hoverinfo='text+x+y',
406
+ showlegend=True
407
+ )
408
+ )
409
+ else:
410
+ # Sem categoria
411
+ fig.add_trace(
412
+ go.Scatter(
413
+ x=dados[x],
414
+ y=dados[y],
415
+ mode='markers',
416
+ marker=dict(
417
+ size=12,
418
+ color='blue',
419
+ opacity=0.9,
420
+ line=dict(width=1, color='black')
421
+ ),
422
+ name='Dados',
423
+ text=dados['Bairro'] if 'Bairro' in dados.columns else None,
424
+ hoverinfo='text+x+y',
425
+ showlegend=True
426
+ )
427
+ )
428
+
429
+ # =========================
430
+ # Layout e formatação
431
+ # =========================
432
+ texto_stats = (
433
+ f"<b>Estatísticas</b><br>"
434
+ f"r = {stats['correlacao']:.4f}<br>"
435
+ f"r² = {stats['r_quadrado']:.4f}<br>"
436
+ f"n = {stats['n']}<br>"
437
+ f"{stats['equacao']}")
438
+
439
+ if p_perm is not None:
440
+ texto_stats += f"<br>p-perm = {p_perm:.4f}"
441
+
442
+ fig.add_annotation(
443
+ x=0.01,
444
+ y=0.99,
445
+ xref="paper",
446
+ yref="paper",
447
+ showarrow=False,
448
+ align="left",
449
+ text=texto_stats,
450
+ bgcolor="#eef2f7",
451
+ opacity=0.85
452
+ )
453
+
454
+ fig.update_layout(
455
+ title_x=0.5,
456
+ xaxis_title=x,
457
+ yaxis_title=y,
458
+ legend_title=hue_var)
459
+
460
+ fig.update_traces(marker_size=12, marker_opacity=0.8)
461
+
462
+ # Interpretação da correlação
463
+ r_abs = abs(correlacao)
464
+ if r_abs >= 0.8:
465
+ força = "MUITO FORTE"
466
+ elif r_abs >= 0.6:
467
+ força = "FORTE"
468
+ elif r_abs >= 0.4:
469
+ força = "MODERADA"
470
+ elif r_abs >= 0.2:
471
+ força = "FRACA"
472
+ else:
473
+ força = "MUITO FRACA"
474
+
475
+ direcao = "POSITIVA" if correlacao > 0 else "NEGATIVA"
476
+ alpha = 0.05
477
+
478
+ if p_perm is not None:
479
+ significancia = f"ESTATISTICAMENTE SIGNIFICATIVA Valor-perm: {p_perm:.4f}" if p_perm < alpha else f"NÃO SIGNIFICATIVA Valor-perm: {p_perm:.4f}"
480
+ else:
481
+ significancia = f"ESTATISTICAMENTE SIGNIFICATIVA Valor-p: {p_valor:.4f}" if (isinstance(p_valor, (int,
482
+ float)) and p_valor < 0.05) else f"NÃO SIGNIFICATIVA Valor-p: {p_valor:.4f}"
483
+ #print(f"Interpretação: {força} correlação {direcao} ({significancia})")
484
+
485
+ return fig
layout_01.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # layout_01.py
3
+ from dash import dcc, html
4
+ def criar_layout(feat_options):
5
+ """
6
+ Cria o layout do aplicativo Dash
7
+ """
8
+ return html.Div(
9
+
10
+ # ===== CONTAINER GERAL =====
11
+ style={
12
+ 'background': '#eef2f7',
13
+ 'padding': '20px 30px',
14
+ 'fontFamily': 'Roboto'
15
+ },
16
+
17
+ children=[
18
+
19
+ # ======================================================
20
+ # HEADER (TÍTULO + DROPDOWN)
21
+ # ======================================================
22
+ html.Div(
23
+ style={
24
+ 'display': 'grid',
25
+ 'gridTemplateColumns': '1fr 300px',
26
+ 'alignItems': 'center',
27
+ 'marginBottom': '20px' },
28
+ children=[
29
+
30
+ # TÍTULO
31
+ html.Div(
32
+ style={
33
+ 'background': '#1f2933',
34
+ 'padding': '25px 20px',
35
+ 'borderRadius': '6px'
36
+ },
37
+ children=[
38
+ html.H2(
39
+ 'Painel de Diagnóstico Ambiental Urbano',
40
+ style={'margin': '0', 'color': 'white'}
41
+ ),
42
+ html.P(
43
+ 'Distribuição, ranking, dispersão e análise espacial por bairro',
44
+ style={'margin': '0', 'color': '#9ca3af', 'fontSize': '13px'}
45
+ )
46
+ ]
47
+ ),
48
+ html.Div(
49
+ style={
50
+ 'justifySelf': 'end',
51
+ 'paddingRight': '20px',
52
+ 'width': '260px', },
53
+ children=[
54
+ dcc.Dropdown(
55
+ id='variavel',
56
+ options=[{'label': opt['label'], 'value': opt['value']} for opt in feat_options],
57
+ value=feat_options[0]['value'],
58
+ clearable=False,
59
+ className='dropdown-alto'
60
+ ),
61
+ html.Div(
62
+ id='descricao-variavel',
63
+ style={
64
+ 'marginTop': '10px',
65
+ 'padding': '10px',
66
+ 'borderLeft': '3px solid #007bff',
67
+ 'backgroundColor': '#f8f9fa',
68
+ 'fontSize': '10px' # Opcional: ajustar tamanho da fonte
69
+ }
70
+ )
71
+ ]
72
+ )
73
+
74
+ ]
75
+ ),
76
+
77
+ html.Div(
78
+ id='kpis',
79
+ style={
80
+ 'display': 'grid',
81
+ 'gridTemplateColumns': 'repeat(4, 1fr)',
82
+ 'gap': '15px', # Mínimo
83
+ 'marginBottom': '10px',
84
+ 'padding': '0px', # Remove padding interno
85
+ }
86
+ ),
87
+
88
+ # ======================================================
89
+ # MAPA + RANKING
90
+ # ======================================================
91
+ html.Div(
92
+ style={
93
+ 'display': 'grid',
94
+ 'gridTemplateColumns': '3fr 1.2fr',
95
+ 'gap': '20px',
96
+ 'marginBottom': '25px'
97
+ },
98
+ children=[
99
+
100
+ # MAPA
101
+ html.Div(
102
+ style={
103
+ 'background': 'white',
104
+ 'padding': '10px',
105
+ 'borderRadius': '8px'
106
+ },
107
+ children=[
108
+ html.Iframe(
109
+ id='mapa',
110
+ style={
111
+ 'width': '100%',
112
+ 'height': '520px',
113
+ 'border': 'none'
114
+ }
115
+ )
116
+ ]
117
+ ),
118
+
119
+ # RANKING TOP 10
120
+ html.Div(
121
+ style={
122
+ 'background': 'None',
123
+ 'padding': '10px',
124
+ 'borderRadius': '8px'
125
+ },
126
+ children=[
127
+ dcc.Graph(
128
+ id='fig_rank',
129
+ style={'height': '520px'}
130
+ )
131
+ ]
132
+ )
133
+ ]
134
+ ),
135
+
136
+ # ======================================================
137
+ # GRÁFICOS ANALÍTICOS (3 COLUNAS)
138
+ # ======================================================
139
+ html.Div(
140
+ style={
141
+ 'display': 'grid',
142
+ 'gridTemplateColumns': 'repeat(3, 1fr)',
143
+ 'gap': '20px',
144
+ 'marginBottom': '25px'
145
+ },
146
+ children=[
147
+
148
+ html.Div(
149
+ style={'background': 'None', 'padding': '10px', 'borderRadius': '8px'},
150
+ children=[dcc.Graph(id='fig_hist')]
151
+ ),
152
+
153
+ html.Div(
154
+ style={'background': 'None', 'padding': '10px', 'borderRadius': '8px'},
155
+ children=[dcc.Graph(id='fig_box')]
156
+ ),
157
+
158
+ html.Div(
159
+ style={'background': 'None', 'padding': '10px', 'borderRadius': '8px'},
160
+ children=[dcc.Graph(id='fig_scatter')]
161
+ )
162
+ ]
163
+ ),
164
+
165
+ # ======================================================
166
+ # RODAPÉ ANALÍTICO
167
+ # ======================================================
168
+ html.Div(
169
+ style={
170
+ 'background': 'white',
171
+ 'padding': '15px',
172
+ 'borderRadius': '8px'
173
+ },
174
+ children=[
175
+ html.P(
176
+ 'Estatísticas complementares, observações analíticas e notas metodológicas.',
177
+ style={'margin': '0', 'fontSize': '13px', 'color': '#374151'}
178
+ )
179
+ ]
180
+ )
181
+
182
+ ]
183
+ )
load_process.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # load_process.py
3
+ import pandas as pd
4
+ import geopandas as gpd
5
+ import os
6
+
7
+ from download_data import ensure_data
8
+
9
+
10
+ def load_files(ponto_descarte=None):
11
+ # Leitura dos DADOS & organização
12
+
13
+ paths = ensure_data()
14
+
15
+ gdf = gpd.read_file(paths["shape_bairros.gpkg"]).rename(columns={'NM_BAIRRO': 'Bairro'})
16
+ df1 = pd.read_csv(paths["tabela_total_com_DIEs.csv"])
17
+ df2 = pd.read_csv(paths["Bairros_Ncoleta.csv"])
18
+
19
+ # BASE_DIR = os.path.dirname(os.path.abspath(__file__))
20
+ # DATA_DIR = os.path.join(BASE_DIR, "data", "process")
21
+
22
+ # gdf = gpd.read_file(os.path.join(DATA_DIR, "shape_bairros.gpkg")).rename(columns={'NM_BAIRRO': 'Bairro'})
23
+ # df1 = pd.read_csv(os.path.join(DATA_DIR, "tabela_total_com_DIEs.csv"))
24
+ # df2 = pd.read_csv(os.path.join(DATA_DIR, "Bairros_Ncoleta.csv"))
25
+
26
+
27
+ #gdf = gpd.read_file(path + 'shape_bairros.gpkg').rename(columns={'NM_BAIRRO': 'Bairro'})
28
+ #df1 = pd.read_csv(path + 'tabela_total_com_DIEs.csv')
29
+ #df2 = pd.read_csv(path + 'Bairros_Ncoleta.csv')
30
+
31
+ df = df1.merge(df2, on='Bairro', how='left')
32
+ gdf_m = gdf.merge(df, on='Bairro', how='left')
33
+
34
+ #add % de Moradores sem renda
35
+ gdf_m['NS']=(gdf_m['Mor']-gdf_m['N_ren'])/gdf_m['Mor']
36
+ colunas = list(gdf_m.columns)
37
+ colunas.remove('NS')
38
+ colunas.insert(7, 'NS')
39
+ gdf_m = gdf_m[colunas]
40
+ # Função de categorização
41
+
42
+ def categorizar_dies(dies):
43
+ if dies == 0:
44
+ return 1
45
+ elif 1 <= dies <= 3:
46
+ return 2
47
+ elif 4 <= dies <= 6:
48
+ return 3
49
+ else:
50
+ return 4
51
+
52
+ gdf_m['Risco'] = gdf_m['DIEs'].apply(categorizar_dies)
53
+
54
+ df_plot = gdf_m.drop(columns=['geometry','V_setores_val'])
55
+
56
+ list_feature = df_plot.drop(columns='Risco').select_dtypes(include=['number']).columns
57
+
58
+ feat_options = []
59
+ for feature in list_feature:
60
+ feat_options.append({'label': feature, 'value': feature, 'description': None})
61
+
62
+ feat_options[0]['description'] = 'Área do Bairro (km²)'
63
+ feat_options[1]['description'] = 'Número Total de Habitações'
64
+ feat_options[2]['description'] = 'Número Total de Moradores'
65
+ feat_options[3]['description'] = 'relação Moradores/Habitação'
66
+ feat_options[4]['description'] = 'Números totais de Moradores com Renda'
67
+ feat_options[5]['description'] = '% de moradores sem renda'
68
+ feat_options[6]['description'] = 'Renda média do Morador'
69
+ feat_options[7]['description'] = 'Mediana da renda do Morador'
70
+ feat_options[8]['description'] = 'Taxa de alfabetização'
71
+ feat_options[9]['description'] = 'IDH Renda'
72
+ feat_options[10]['description'] = 'IDH Longevidade'
73
+ feat_options[11]['description'] = 'IDH Educação'
74
+ feat_options[12]['description'] = 'Indice de desenvolvimento Humano'
75
+ feat_options[13]['description'] = 'Quantidade de Deposito Irregulares '
76
+ feat_options[14]['description'] = 'Concentração Riqueza por area( Ren_avg x (Mor/Hab)/Area_km)'
77
+ feat_options[15]['description'] = 'Percentual da populção com rendimento'
78
+ feat_options[16]['description'] = 'Quantidade de Depósitos Irregulares estimado'
79
+ feat_options[17]['description'] = 'Média de dias de coleta de lixo'
80
+ feat_options[18]['description'] = 'Quantidade de setores/rotas de coleta'
81
+
82
+ if ponto_descarte is not None:
83
+ #gdf_p = gpd.read_file(os.path.join(DATA_DIR, "Pontos_descartes_ML.gpkg"))
84
+ gdf_p = gpd.read_file(paths["Pontos_descartes_ML.gpkg"])
85
+
86
+ #gdf_p = gpd.read_file(path + 'Pontos_descartes_ML.gpkg')
87
+ return gdf_m,df_plot,list_feature, feat_options, gdf_p
88
+ else:
89
+ print('debub: sem arquivo descartes')
90
+ return gdf_m,df_plot,list_feature, feat_options
requirements.txt ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ dash
2
+ flask
3
+ flask-caching
4
+ pandas
5
+ geopandas
6
+ numpy
7
+ plotly
8
+ folium
9
+ scipy
10
+ shapely
11
+ pyproj
12
+ gunicorn
13
+ huggingface-hub
14
+