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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
|
| 3 |
+
import gradio as gr
|
| 4 |
+
import pandas as pd
|
| 5 |
+
import geopandas as gpd
|
| 6 |
+
from shapely.geometry import Point # Importar Point para a conversão
|
| 7 |
+
import folium
|
| 8 |
+
from folium.plugins import MeasureControl
|
| 9 |
+
import html
|
| 10 |
+
from rapidfuzz import process
|
| 11 |
+
|
| 12 |
+
# --- CARREGAMENTO E PRÉ-PROCESSAMENTO DE DADOS ---
|
| 13 |
+
|
| 14 |
+
try:
|
| 15 |
+
# Carrega os eixos (ruas) e projeta para o sistema de coordenadas padrão (WGS84)
|
| 16 |
+
gdf_eixos = gpd.read_file("Eixos.shp", engine="fiona")
|
| 17 |
+
gdf_eixos_proj = gdf_eixos.to_crs("EPSG:4326")
|
| 18 |
+
print("Shapefile de Eixos carregado com sucesso.")
|
| 19 |
+
|
| 20 |
+
# 1. Criar o dicionário de mapeamento unificado: NOME -> CDLOG
|
| 21 |
+
mapa_nome_para_cdlog = {}
|
| 22 |
+
df_mapeamento = gdf_eixos_proj[['NMIDELOG', 'NMIDEABR', 'CDLOG']].dropna(subset=['CDLOG'])
|
| 23 |
+
|
| 24 |
+
for _, row in df_mapeamento.iterrows():
|
| 25 |
+
cdlog = row['CDLOG']
|
| 26 |
+
if pd.notna(row['NMIDELOG']):
|
| 27 |
+
mapa_nome_para_cdlog[row['NMIDELOG']] = cdlog
|
| 28 |
+
if pd.notna(row['NMIDEABR']):
|
| 29 |
+
mapa_nome_para_cdlog[row['NMIDEABR']] = cdlog
|
| 30 |
+
|
| 31 |
+
# 2. Criar a lista de busca unificada com todos os nomes únicos
|
| 32 |
+
lista_nomes_ruas_oficiais = list(mapa_nome_para_cdlog.keys())
|
| 33 |
+
|
| 34 |
+
print(f"{len(lista_nomes_ruas_oficiais)} nomes de ruas únicos (de NMIDELOG e NMIDEABR) pré-processados para busca.")
|
| 35 |
+
|
| 36 |
+
except Exception as e:
|
| 37 |
+
print(f"ERRO CRÍTICO: Não foi possível carregar ou processar o Shapefile 'Eixos.shp'.")
|
| 38 |
+
print(f"Verifique se o caminho de rede está correto e acessível.")
|
| 39 |
+
print(f"Erro original: {e}")
|
| 40 |
+
exit()
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
# --- FUNÇÕES DE PROCESSAMENTO (BACK-END) ---
|
| 44 |
+
|
| 45 |
+
def encontrar_melhor_correspondencia(nome_rua_usuario, score_minimo=85):
|
| 46 |
+
"""
|
| 47 |
+
Encontra a melhor correspondência para um nome de rua na lista oficial.
|
| 48 |
+
A comparação é feita em CAIXA ALTA para ser insensível ao caso.
|
| 49 |
+
"""
|
| 50 |
+
if not nome_rua_usuario or pd.isna(nome_rua_usuario):
|
| 51 |
+
return None, None, 0
|
| 52 |
+
|
| 53 |
+
nome_rua_upper = str(nome_rua_usuario).upper()
|
| 54 |
+
melhor_match = process.extractOne(nome_rua_upper, lista_nomes_ruas_oficiais)
|
| 55 |
+
|
| 56 |
+
if melhor_match and melhor_match[1] >= score_minimo:
|
| 57 |
+
nome_encontrado = melhor_match[0]
|
| 58 |
+
score = melhor_match[1]
|
| 59 |
+
cdlog_encontrado = mapa_nome_para_cdlog[nome_encontrado]
|
| 60 |
+
return int(cdlog_encontrado), nome_encontrado, score
|
| 61 |
+
|
| 62 |
+
return None, None, melhor_match[1] if melhor_match else 0
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def geocodificar_lote_por_nome(df, coluna_nome_rua, coluna_num):
|
| 66 |
+
"""
|
| 67 |
+
Função principal que processa o DataFrame inteiro.
|
| 68 |
+
"""
|
| 69 |
+
if df is None:
|
| 70 |
+
return None, None, None
|
| 71 |
+
|
| 72 |
+
resultados_finais = []
|
| 73 |
+
falhas_geocodificacao = []
|
| 74 |
+
|
| 75 |
+
for index, row in df.iterrows():
|
| 76 |
+
nome_rua_original = row[coluna_nome_rua]
|
| 77 |
+
numero = pd.to_numeric(row[coluna_num], errors='coerce')
|
| 78 |
+
|
| 79 |
+
dados_linha = row.to_dict()
|
| 80 |
+
cdlog, nome_correspondido, score = encontrar_melhor_correspondencia(nome_rua_original)
|
| 81 |
+
|
| 82 |
+
dados_linha['CDLOG_ENCONTRADO'] = cdlog
|
| 83 |
+
dados_linha['NM_CORRESPONDIDO'] = nome_correspondido
|
| 84 |
+
dados_linha['SCORE_SIMILARIDADE'] = score
|
| 85 |
+
|
| 86 |
+
if not cdlog:
|
| 87 |
+
falhas_geocodificacao.append({**dados_linha, 'MOTIVO_FALHA': 'Nome da rua não encontrado com similaridade aceitável'})
|
| 88 |
+
resultados_finais.append({**dados_linha, 'x': None, 'y': None})
|
| 89 |
+
continue
|
| 90 |
+
|
| 91 |
+
if pd.isna(numero):
|
| 92 |
+
falhas_geocodificacao.append({**dados_linha, 'MOTIVO_FALHA': 'Número do imóvel inválido ou vazio'})
|
| 93 |
+
resultados_finais.append({**dados_linha, 'x': None, 'y': None})
|
| 94 |
+
continue
|
| 95 |
+
|
| 96 |
+
numero = int(numero)
|
| 97 |
+
segmentos = gdf_eixos_proj[gdf_eixos_proj['CDLOG'] == cdlog]
|
| 98 |
+
cond = (segmentos['NRPARINI'] <= numero) & (segmentos['NRPARFIN'] >= numero) if numero % 2 == 0 else (segmentos['NRIMPINI'] <= numero) & (segmentos['NRIMPFIN'] >= numero)
|
| 99 |
+
segmento_valido = segmentos[cond]
|
| 100 |
+
|
| 101 |
+
if segmento_valido.empty:
|
| 102 |
+
falhas_geocodificacao.append({**dados_linha, 'MOTIVO_FALHA': 'Número do imóvel fora do intervalo da rua encontrada'})
|
| 103 |
+
resultados_finais.append({**dados_linha, 'x': None, 'y': None})
|
| 104 |
+
continue
|
| 105 |
+
|
| 106 |
+
linha_eixo = segmento_valido.iloc[0]
|
| 107 |
+
geom = linha_eixo.geometry
|
| 108 |
+
ini, fim = (linha_eixo['NRPARINI'], linha_eixo['NRPARFIN']) if numero % 2 == 0 else (linha_eixo['NRIMPINI'], linha_eixo['NRIMPFIN'])
|
| 109 |
+
|
| 110 |
+
if pd.isna(ini) or pd.isna(fim) or fim == ini: frac = 0.5
|
| 111 |
+
else: frac = (numero - ini) / (fim - ini)
|
| 112 |
+
|
| 113 |
+
frac = max(0, min(1, frac))
|
| 114 |
+
ponto = geom.interpolate(geom.length * frac)
|
| 115 |
+
|
| 116 |
+
dados_linha['x'] = ponto.x
|
| 117 |
+
dados_linha['y'] = ponto.y
|
| 118 |
+
resultados_finais.append(dados_linha)
|
| 119 |
+
|
| 120 |
+
df_resultado = pd.DataFrame(resultados_finais)
|
| 121 |
+
df_falhas = pd.DataFrame(falhas_geocodificacao)
|
| 122 |
+
output_path = "dados_geocodificados.xlsx"
|
| 123 |
+
df_resultado.to_excel(output_path, index=False)
|
| 124 |
+
|
| 125 |
+
return df_resultado, df_falhas, output_path
|
| 126 |
+
|
| 127 |
+
# --- FUNÇÃO DO MAPA CORRIGIDA ---
|
| 128 |
+
def gerar_mapa_interpolado(df_interpolado):
|
| 129 |
+
"""Gera o mapa HTML a partir do DataFrame com coordenadas."""
|
| 130 |
+
if df_interpolado is None:
|
| 131 |
+
return "<div>Mapa não gerado. Processe os dados primeiro.</div>"
|
| 132 |
+
|
| 133 |
+
df_valido = df_interpolado.dropna(subset=['x', 'y']).copy()
|
| 134 |
+
if df_valido.empty:
|
| 135 |
+
return "<div>Nenhum ponto válido para exibir no mapa.</div>"
|
| 136 |
+
|
| 137 |
+
# --- INÍCIO DA CORREÇÃO ---
|
| 138 |
+
# 1. Converter o DataFrame do pandas para um GeoDataFrame do geopandas
|
| 139 |
+
gdf_valido = gpd.GeoDataFrame(
|
| 140 |
+
df_valido,
|
| 141 |
+
geometry=gpd.points_from_xy(df_valido.x, df_valido.y),
|
| 142 |
+
crs="EPSG:4326" # Definir o sistema de coordenadas (importante!)
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
# 2. Calcular o centro do mapa de forma eficiente
|
| 146 |
+
# Pega os limites geográficos de todos os pontos (min_x, min_y, max_x, max_y)
|
| 147 |
+
bounds = gdf_valido.total_bounds
|
| 148 |
+
center_y = (bounds[1] + bounds[3]) / 2
|
| 149 |
+
center_x = (bounds[0] + bounds[2]) / 2
|
| 150 |
+
|
| 151 |
+
m = folium.Map(location=[center_y, center_x], zoom_start=13, tiles='CartoDB positron')
|
| 152 |
+
# --- FIM DA CORREÇÃO ---
|
| 153 |
+
|
| 154 |
+
MeasureControl(primary_length_unit='meters', secondary_length_unit='kilometers').add_to(m)
|
| 155 |
+
|
| 156 |
+
# O resto da função permanece igual
|
| 157 |
+
for _, row in gdf_valido.iterrows():
|
| 158 |
+
conteudo_popup = "<br>".join([f"<b>{col}</b>: {row[col]}" for col in gdf_valido.columns if col != 'geometry'])
|
| 159 |
+
folium.CircleMarker(
|
| 160 |
+
location=[row['y'], row['x']],
|
| 161 |
+
radius=5, color='#007BFF', fill=True, fill_color='#007BFF',
|
| 162 |
+
fill_opacity=0.8, popup=folium.Popup(conteudo_popup, max_width=350)
|
| 163 |
+
).add_to(m)
|
| 164 |
+
|
| 165 |
+
mapa_html = m.get_root().render()
|
| 166 |
+
mapa_html_escapado = html.escape(mapa_html)
|
| 167 |
+
return f"<iframe srcdoc=\"{mapa_html_escapado}\" width='100%' height='1000px' style='border:none;'></iframe>"
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
# --- Funções de Interface (Gradio) ---
|
| 171 |
+
def carregar_abas(arquivo_excel):
|
| 172 |
+
if arquivo_excel is None: return gr.update(choices=[]), None
|
| 173 |
+
xls = pd.ExcelFile(arquivo_excel.name)
|
| 174 |
+
abas = xls.sheet_names
|
| 175 |
+
return gr.update(choices=abas, value=abas[0] if abas else None), abas[0] if abas else None
|
| 176 |
+
|
| 177 |
+
def listar_colunas(arquivo_excel, aba_selecionada):
|
| 178 |
+
if arquivo_excel is None or aba_selecionada is None:
|
| 179 |
+
return gr.update(choices=[]), gr.update(choices=[]), None, "", None
|
| 180 |
+
df = pd.read_excel(arquivo_excel.name, sheet_name=aba_selecionada)
|
| 181 |
+
colunas = df.columns.tolist()
|
| 182 |
+
return (gr.update(choices=colunas), gr.update(choices=colunas), df,
|
| 183 |
+
f"O DataFrame possui {df.shape[0]} linhas e {df.shape[1]} colunas.", df)
|
| 184 |
+
|
| 185 |
+
def reset_app():
|
| 186 |
+
return None, gr.update(choices=[], value=None), "", None, None, None, None, None, None, None
|
| 187 |
+
|
| 188 |
+
# --- INTERFACE GRÁFICA (GRADIO) ---
|
| 189 |
+
with gr.Blocks(theme=gr.themes.Soft(), title="Geocodificador Simplificado") as demo:
|
| 190 |
+
estado_df = gr.State()
|
| 191 |
+
|
| 192 |
+
gr.Markdown("# Geocodificador de Endereços")
|
| 193 |
+
gr.Markdown("Faça o upload de uma planilha Excel, selecione as colunas com **NOME da rua** e **NÚMERO**, e o aplicativo encontrará as coordenadas.")
|
| 194 |
+
|
| 195 |
+
with gr.Tabs():
|
| 196 |
+
with gr.TabItem("Processo de Geocodificação"):
|
| 197 |
+
with gr.Row():
|
| 198 |
+
with gr.Column(scale=1):
|
| 199 |
+
arquivo = gr.File(label="1. Selecione um arquivo Excel", file_types=[".xlsx"])
|
| 200 |
+
dropdown_abas = gr.Dropdown(label="2. Selecione uma aba da planilha", interactive=True)
|
| 201 |
+
dropdown_nome_rua = gr.Dropdown(label="3. Selecione a coluna com o NOME da rua", interactive=True)
|
| 202 |
+
dropdown_num = gr.Dropdown(label="4. Selecione a coluna com o NÚMERO do imóvel", interactive=True)
|
| 203 |
+
btn_processar = gr.Button("5. Geocodificar Endereços", variant="primary")
|
| 204 |
+
|
| 205 |
+
with gr.Column(scale=3):
|
| 206 |
+
linhas_colunas_output = gr.Textbox(label="Dimensões da Tabela", interactive=False)
|
| 207 |
+
tabela_output = gr.Dataframe(label="Pré-visualização dos Dados", height=400)
|
| 208 |
+
|
| 209 |
+
gr.Markdown("---")
|
| 210 |
+
gr.Markdown("### Resultados")
|
| 211 |
+
|
| 212 |
+
with gr.Row():
|
| 213 |
+
tabela_interpolada = gr.Dataframe(label="Dados com Coordenadas e Verificação de Endereço", interactive=False, height=350)
|
| 214 |
+
falhas_output = gr.Dataframe(label="Relatório de Endereços Não Encontrados", interactive=False, height=350)
|
| 215 |
+
|
| 216 |
+
arquivo_excel_output = gr.File(label="Baixar resultado completo como Excel", interactive=False)
|
| 217 |
+
|
| 218 |
+
with gr.TabItem("Mapa de Resultados"):
|
| 219 |
+
mapa_html = gr.HTML(label="Visualização Geográfica dos Dados")
|
| 220 |
+
|
| 221 |
+
btn_clear = gr.Button("Limpar Tudo e Recomeçar", variant="stop")
|
| 222 |
+
|
| 223 |
+
# --- LÓGICA DE EVENTOS DA INTERFACE ---
|
| 224 |
+
arquivo.change(fn=carregar_abas, inputs=arquivo, outputs=[dropdown_abas, dropdown_abas])
|
| 225 |
+
|
| 226 |
+
dropdown_abas.change(
|
| 227 |
+
fn=listar_colunas,
|
| 228 |
+
inputs=[arquivo, dropdown_abas],
|
| 229 |
+
outputs=[dropdown_nome_rua, dropdown_num, estado_df, linhas_colunas_output, tabela_output]
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
btn_processar.click(
|
| 233 |
+
fn=geocodificar_lote_por_nome,
|
| 234 |
+
inputs=[estado_df, dropdown_nome_rua, dropdown_num],
|
| 235 |
+
outputs=[tabela_interpolada, falhas_output, arquivo_excel_output]
|
| 236 |
+
).then(
|
| 237 |
+
fn=gerar_mapa_interpolado,
|
| 238 |
+
inputs=tabela_interpolada,
|
| 239 |
+
outputs=mapa_html
|
| 240 |
+
)
|
| 241 |
+
|
| 242 |
+
btn_clear.click(fn=reset_app, inputs=None, outputs=[
|
| 243 |
+
arquivo, dropdown_abas, linhas_colunas_output, dropdown_nome_rua, dropdown_num,
|
| 244 |
+
tabela_output, tabela_interpolada, falhas_output, arquivo_excel_output, mapa_html
|
| 245 |
+
])
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
# --- INICIAR A APLICAÇÃO ---
|
| 249 |
+
if __name__ == "__main__":
|
| 250 |
+
demo.launch(debug=True)
|