Update app.py
Browse files
app.py
CHANGED
|
@@ -2,28 +2,18 @@ import gradio as gr
|
|
| 2 |
import pandas as pd
|
| 3 |
import geopandas as gpd
|
| 4 |
|
| 5 |
-
#
|
| 6 |
-
# Carregamento único dos eixos (feito uma vez)
|
| 7 |
-
# --------------------------------------------------
|
| 8 |
gdf_eixos = gpd.read_file("EixosLogradouros.shp", engine="fiona")
|
| 9 |
gdf_eixos = gdf_eixos.to_crs("EPSG:4326")
|
|
|
|
| 10 |
|
| 11 |
-
# Pré-agrupamento para evitar filtro a cada linha
|
| 12 |
-
eixos_por_cdlog = {
|
| 13 |
-
cdlog: grupo.copy()
|
| 14 |
-
for cdlog, grupo in gdf_eixos.groupby("CDLOG")
|
| 15 |
-
}
|
| 16 |
-
|
| 17 |
-
# --------------------------------------------------
|
| 18 |
# Funções auxiliares
|
| 19 |
-
# --------------------------------------------------
|
| 20 |
def formatar_float_visualizacao(df, casas=4):
|
| 21 |
df_visual = df.copy()
|
| 22 |
float_cols = df_visual.select_dtypes(include=["float"]).columns
|
| 23 |
df_visual[float_cols] = df_visual[float_cols].round(casas)
|
| 24 |
return df_visual
|
| 25 |
|
| 26 |
-
|
| 27 |
def carregar_abas(arquivo_excel):
|
| 28 |
if arquivo_excel is None:
|
| 29 |
return gr.update(choices=[]), None
|
|
@@ -31,437 +21,164 @@ def carregar_abas(arquivo_excel):
|
|
| 31 |
abas = xls.sheet_names
|
| 32 |
return gr.update(choices=abas, value=abas[0]), abas[0]
|
| 33 |
|
| 34 |
-
|
| 35 |
def listar_colunas(arquivo_excel, aba):
|
| 36 |
if arquivo_excel is None or aba is None:
|
| 37 |
return gr.update(choices=[]), gr.update(choices=[])
|
| 38 |
-
|
| 39 |
df = pd.read_excel(arquivo_excel.name, sheet_name=aba)
|
| 40 |
colunas = df.columns.tolist()
|
| 41 |
-
|
| 42 |
-
# Criar versão upper para comparação
|
| 43 |
colunas_upper = {col.upper(): col for col in colunas}
|
| 44 |
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
# -----------------------------------
|
| 48 |
-
coluna_cdlog_pre = None
|
| 49 |
-
|
| 50 |
-
if "CTM" in colunas_upper:
|
| 51 |
-
coluna_cdlog_pre = colunas_upper["CTM"]
|
| 52 |
-
elif "CDLOG" in colunas_upper:
|
| 53 |
-
coluna_cdlog_pre = colunas_upper["CDLOG"]
|
| 54 |
-
|
| 55 |
-
# -----------------------------------
|
| 56 |
-
# Pré-seleção Número
|
| 57 |
-
# -----------------------------------
|
| 58 |
-
coluna_num_pre = None
|
| 59 |
-
|
| 60 |
-
prioridades_num = ["Nº GEO", "NUM_GEO", "NUM"]
|
| 61 |
-
|
| 62 |
-
for nome in prioridades_num:
|
| 63 |
-
if nome.upper() in colunas_upper:
|
| 64 |
-
coluna_num_pre = colunas_upper[nome.upper()]
|
| 65 |
-
break
|
| 66 |
-
|
| 67 |
-
return (
|
| 68 |
-
gr.update(choices=colunas, value=coluna_cdlog_pre),
|
| 69 |
-
gr.update(choices=colunas, value=coluna_num_pre),
|
| 70 |
-
)
|
| 71 |
|
|
|
|
| 72 |
|
| 73 |
def exibir_tabela(arquivo_excel, aba, coluna_num):
|
| 74 |
if arquivo_excel is None or aba is None:
|
| 75 |
return None, ""
|
| 76 |
-
|
| 77 |
df = pd.read_excel(arquivo_excel.name, sheet_name=aba)
|
| 78 |
-
|
| 79 |
-
# Criar índice técnico estável
|
| 80 |
df["_idx"] = range(len(df))
|
| 81 |
-
|
| 82 |
if coluna_num in df.columns:
|
| 83 |
df[coluna_num] = pd.to_numeric(df[coluna_num], errors="coerce").fillna(0).astype(int)
|
| 84 |
-
|
| 85 |
texto = f"O DataFrame possui {df.shape[0]} linhas e {df.shape[1]} colunas."
|
| 86 |
return formatar_float_visualizacao(df), texto
|
| 87 |
|
| 88 |
-
def gerar_sugestoes(segmentos, numero):
|
| 89 |
-
|
| 90 |
-
if segmentos is None or segmentos.empty:
|
| 91 |
-
return ""
|
| 92 |
-
|
| 93 |
-
linha = segmentos.iloc[0]
|
| 94 |
-
|
| 95 |
-
if numero % 2 == 0:
|
| 96 |
-
ini = linha["NRPARINI"]
|
| 97 |
-
fim = linha["NRPARFIN"]
|
| 98 |
-
else:
|
| 99 |
-
ini = linha["NRIMPINI"]
|
| 100 |
-
fim = linha["NRIMPFIN"]
|
| 101 |
-
|
| 102 |
-
if pd.isna(ini) or pd.isna(fim):
|
| 103 |
-
return ""
|
| 104 |
-
|
| 105 |
-
numeros_validos = list(range(int(ini), int(fim) + 1, 2))
|
| 106 |
-
|
| 107 |
-
# limitar quantidade
|
| 108 |
-
sugestoes = numeros_validos[:20]
|
| 109 |
-
|
| 110 |
-
return ", ".join(map(str, sugestoes))
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
# --------------------------------------------------
|
| 114 |
-
# Motor de Interpolação
|
| 115 |
-
# --------------------------------------------------
|
| 116 |
def interpolar(df, coluna_cdlog, coluna_num):
|
| 117 |
-
|
| 118 |
df = df.copy()
|
| 119 |
df[coluna_num] = pd.to_numeric(df[coluna_num], errors="coerce").fillna(0).astype(int)
|
| 120 |
|
| 121 |
-
lons = []
|
| 122 |
-
lats = []
|
| 123 |
-
falhas = []
|
| 124 |
|
| 125 |
for _, row in df.iterrows():
|
| 126 |
-
|
| 127 |
-
idx = row["_idx"]
|
| 128 |
-
cdlog = row[coluna_cdlog]
|
| 129 |
-
numero = row[coluna_num]
|
| 130 |
-
|
| 131 |
segmentos = eixos_por_cdlog.get(cdlog)
|
| 132 |
|
| 133 |
-
# --------------------------------------------------
|
| 134 |
-
# CDLOG não encontrado
|
| 135 |
-
# --------------------------------------------------
|
| 136 |
if segmentos is None:
|
| 137 |
-
|
| 138 |
lons.append(None)
|
| 139 |
lats.append(None)
|
| 140 |
-
|
| 141 |
falhas.append({
|
| 142 |
"_idx": idx,
|
| 143 |
"CDLOG": cdlog,
|
| 144 |
"Numero Atual": numero,
|
| 145 |
"Motivo": "CDLOG não encontrado",
|
| 146 |
-
"
|
| 147 |
-
"
|
|
|
|
| 148 |
})
|
| 149 |
continue
|
| 150 |
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
if numero % 2 == 0:
|
| 155 |
-
cond = (segmentos["NRPARINI"] <= numero) & (segmentos["NRPARFIN"] >= numero)
|
| 156 |
-
ini_col = "NRPARINI"
|
| 157 |
-
fim_col = "NRPARFIN"
|
| 158 |
-
else:
|
| 159 |
-
cond = (segmentos["NRIMPINI"] <= numero) & (segmentos["NRIMPFIN"] >= numero)
|
| 160 |
-
ini_col = "NRIMPINI"
|
| 161 |
-
fim_col = "NRIMPFIN"
|
| 162 |
-
|
| 163 |
seg_validos = segmentos[cond]
|
| 164 |
|
| 165 |
-
# # --------------------------------------------------
|
| 166 |
-
# # Número fora do intervalo
|
| 167 |
-
# # --------------------------------------------------
|
| 168 |
-
# if seg_validos.empty:
|
| 169 |
-
|
| 170 |
-
# sugestao_formatada = ""
|
| 171 |
-
|
| 172 |
-
# if not segmentos.empty:
|
| 173 |
-
|
| 174 |
-
# if numero % 2 == 0:
|
| 175 |
-
# diffs = (segmentos["NRPARINI"] - numero).abs()
|
| 176 |
-
# ini_col = "NRPARINI"
|
| 177 |
-
# fim_col = "NRPARFIN"
|
| 178 |
-
# else:
|
| 179 |
-
# diffs = (segmentos["NRIMPINI"] - numero).abs()
|
| 180 |
-
# ini_col = "NRIMPINI"
|
| 181 |
-
# fim_col = "NRIMPFIN"
|
| 182 |
-
|
| 183 |
-
# if not diffs.empty:
|
| 184 |
-
# min_index = diffs.idxmin()
|
| 185 |
-
# linha_proxima = segmentos.loc[min_index]
|
| 186 |
-
|
| 187 |
-
# ini = linha_proxima[ini_col]
|
| 188 |
-
# fim = linha_proxima[fim_col]
|
| 189 |
-
|
| 190 |
-
# if pd.notna(ini) and pd.notna(fim):
|
| 191 |
-
# sugestao_formatada = f"Intervalo válido: {int(ini)} até {int(fim)}"
|
| 192 |
-
|
| 193 |
-
# lons.append(None)
|
| 194 |
-
# lats.append(None)
|
| 195 |
-
|
| 196 |
-
# falhas.append({
|
| 197 |
-
# "_idx": idx,
|
| 198 |
-
# "CDLOG": cdlog,
|
| 199 |
-
# "Numero Atual": numero,
|
| 200 |
-
# "Motivo": "Numeração fora do intervalo",
|
| 201 |
-
# "Sugestões": sugestao_formatada,
|
| 202 |
-
# "Novo Número": None
|
| 203 |
-
# })
|
| 204 |
-
|
| 205 |
-
# continue
|
| 206 |
-
|
| 207 |
-
# --------------------------------------------------
|
| 208 |
-
# Número fora do intervalo
|
| 209 |
-
# --------------------------------------------------
|
| 210 |
if seg_validos.empty:
|
| 211 |
-
|
| 212 |
-
sugestoes_lista = []
|
| 213 |
-
lado = "Par" if numero % 2 == 0 else "Ímpar"
|
| 214 |
-
intervalo_texto = ""
|
| 215 |
-
|
| 216 |
if not segmentos.empty:
|
| 217 |
-
|
| 218 |
-
if numero % 2 == 0:
|
| 219 |
-
diffs = (segmentos["NRPARINI"] - numero).abs()
|
| 220 |
-
ini_col = "NRPARINI"
|
| 221 |
-
fim_col = "NRPARFIN"
|
| 222 |
-
else:
|
| 223 |
-
diffs = (segmentos["NRIMPINI"] - numero).abs()
|
| 224 |
-
ini_col = "NRIMPINI"
|
| 225 |
-
fim_col = "NRIMPFIN"
|
| 226 |
-
|
| 227 |
if not diffs.empty:
|
| 228 |
min_index = diffs.idxmin()
|
| 229 |
linha_proxima = segmentos.loc[min_index]
|
| 230 |
-
|
| 231 |
-
ini = linha_proxima[ini_col]
|
| 232 |
-
fim = linha_proxima[fim_col]
|
| 233 |
-
|
| 234 |
if pd.notna(ini) and pd.notna(fim):
|
| 235 |
-
|
| 236 |
-
intervalo_texto = f"{int(ini)} até {int(fim)}"
|
| 237 |
-
|
| 238 |
numeros_validos = list(range(int(ini), int(fim) + 1, 2))
|
| 239 |
numeros_validos.sort(key=lambda x: abs(x - numero))
|
| 240 |
-
|
| 241 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 242 |
lons.append(None)
|
| 243 |
lats.append(None)
|
| 244 |
-
|
| 245 |
falhas.append({
|
| 246 |
"_idx": idx,
|
| 247 |
"CDLOG": cdlog,
|
| 248 |
"Numero Atual": numero,
|
| 249 |
"Motivo": "Numeração fora do intervalo",
|
| 250 |
"Lado": lado,
|
| 251 |
-
"Intervalo":
|
| 252 |
-
"Sugestões":
|
| 253 |
})
|
| 254 |
-
|
| 255 |
continue
|
| 256 |
|
| 257 |
-
# --------------------------------------------------
|
| 258 |
-
# Interpolação válida
|
| 259 |
-
# --------------------------------------------------
|
| 260 |
linha = seg_validos.iloc[0]
|
| 261 |
geom = linha.geometry
|
| 262 |
-
|
| 263 |
-
ini = linha[ini_col]
|
| 264 |
-
fim = linha[fim_col]
|
| 265 |
-
|
| 266 |
if fim == ini:
|
| 267 |
lons.append(None)
|
| 268 |
lats.append(None)
|
| 269 |
continue
|
| 270 |
-
|
| 271 |
frac = (numero - ini) / (fim - ini)
|
| 272 |
frac = max(0, min(1, frac))
|
| 273 |
ponto = geom.interpolate(geom.length * frac)
|
| 274 |
-
|
| 275 |
lons.append(ponto.x)
|
| 276 |
lats.append(ponto.y)
|
| 277 |
|
| 278 |
-
# --------------------------------------------------
|
| 279 |
-
# Atualizar dataframe principal
|
| 280 |
-
# --------------------------------------------------
|
| 281 |
df["lon"] = lons
|
| 282 |
df["lat"] = lats
|
| 283 |
-
|
| 284 |
output_path = "dados_interpolados.xlsx"
|
| 285 |
df.to_excel(output_path, index=False)
|
| 286 |
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
# --------------------------------------------------
|
| 290 |
-
# colunas_fixas = [
|
| 291 |
-
# "_idx",
|
| 292 |
-
# "CDLOG",
|
| 293 |
-
# "Numero Atual",
|
| 294 |
-
# "Motivo",
|
| 295 |
-
# "Sugestões",
|
| 296 |
-
# "Novo Número"
|
| 297 |
-
# ]
|
| 298 |
-
|
| 299 |
-
colunas_fixas = [
|
| 300 |
-
"_idx",
|
| 301 |
-
"CDLOG",
|
| 302 |
-
"Numero Atual",
|
| 303 |
-
"Motivo",
|
| 304 |
-
"Lado",
|
| 305 |
-
"Intervalo",
|
| 306 |
-
"Sugestões"
|
| 307 |
-
]
|
| 308 |
-
|
| 309 |
-
if len(falhas) == 0:
|
| 310 |
-
df_falhas = pd.DataFrame(columns=colunas_fixas)
|
| 311 |
-
else:
|
| 312 |
-
df_falhas = pd.DataFrame(falhas)
|
| 313 |
-
df_falhas = df_falhas[colunas_fixas]
|
| 314 |
|
| 315 |
return formatar_float_visualizacao(df), output_path, df_falhas
|
| 316 |
|
| 317 |
-
|
| 318 |
-
# Preparar sugestões
|
| 319 |
-
# --------------------------------------------------
|
| 320 |
-
|
| 321 |
-
def preparar_sugestoes(df_falhas, evt: gr.SelectData):
|
| 322 |
-
|
| 323 |
linha = df_falhas.iloc[evt.index[0]]
|
| 324 |
-
|
| 325 |
idx = linha["_idx"]
|
| 326 |
lado = linha.get("Lado", "")
|
| 327 |
intervalo = linha.get("Intervalo", "")
|
| 328 |
sugestoes = linha.get("Sugestões", [])
|
| 329 |
-
|
| 330 |
-
# 🔴 CORREÇÃO AQUI
|
| 331 |
if isinstance(sugestoes, str):
|
| 332 |
sugestoes = [int(x.strip()) for x in sugestoes.split(",") if x.strip().isdigit()]
|
|
|
|
| 333 |
|
| 334 |
-
if not isinstance(sugestoes, list):
|
| 335 |
-
sugestoes = []
|
| 336 |
-
|
| 337 |
-
return (
|
| 338 |
-
idx,
|
| 339 |
-
lado,
|
| 340 |
-
intervalo,
|
| 341 |
-
gr.update(choices=sugestoes, value=None)
|
| 342 |
-
)
|
| 343 |
-
|
| 344 |
-
# --------------------------------------------------
|
| 345 |
-
# Aplicar Sugestões
|
| 346 |
-
# --------------------------------------------------
|
| 347 |
def aplicar_sugestao(df_original, idx, numero_escolhido, coluna_num):
|
| 348 |
-
|
| 349 |
if numero_escolhido is None:
|
| 350 |
return df_original
|
| 351 |
-
|
| 352 |
df_original = df_original.copy()
|
| 353 |
-
|
| 354 |
df_original.loc[df_original["_idx"] == idx, coluna_num] = int(numero_escolhido)
|
| 355 |
-
|
| 356 |
return df_original
|
| 357 |
|
| 358 |
-
# --------------------------------------------------
|
| 359 |
-
# Aplicar Correções
|
| 360 |
-
# --------------------------------------------------
|
| 361 |
-
def aplicar_correcoes(df_original, df_falhas, coluna_num):
|
| 362 |
-
|
| 363 |
-
if df_falhas is None or df_falhas.empty:
|
| 364 |
-
return df_original
|
| 365 |
-
|
| 366 |
-
df_original = df_original.copy()
|
| 367 |
-
|
| 368 |
-
for _, row in df_falhas.iterrows():
|
| 369 |
-
if pd.notna(row["Novo Número"]):
|
| 370 |
-
idx = row["_idx"]
|
| 371 |
-
df_original.loc[df_original["_idx"] == idx, coluna_num] = int(row["Novo Número"])
|
| 372 |
-
|
| 373 |
-
return df_original
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
# --------------------------------------------------
|
| 378 |
# Interface
|
| 379 |
-
# --------------------------------------------------
|
| 380 |
with gr.Blocks() as app:
|
| 381 |
-
|
| 382 |
gr.Markdown("## DAI - Geolocalização com Correção Assistida")
|
| 383 |
-
|
| 384 |
estado_tabela = gr.State()
|
| 385 |
|
| 386 |
arquivo = gr.File(label="Arquivo Excel", file_types=[".xlsx"])
|
| 387 |
dropdown_abas = gr.Dropdown(label="Aba")
|
| 388 |
linhas_info = gr.Textbox(label="Linhas e Colunas", interactive=False)
|
| 389 |
-
|
| 390 |
dropdown_cdlog = gr.Dropdown(label="Coluna CDLOG")
|
| 391 |
dropdown_num = gr.Dropdown(label="Coluna Número")
|
| 392 |
-
|
| 393 |
tabela = gr.Dataframe(label="Tabela Original", interactive=False)
|
| 394 |
-
|
| 395 |
btn_interpolar = gr.Button("Interpolar")
|
| 396 |
-
|
| 397 |
tabela_resultado = gr.Dataframe(label="Com Coordenadas", interactive=False)
|
| 398 |
arquivo_saida = gr.File(label="Arquivo Gerado")
|
| 399 |
-
|
| 400 |
falhas = gr.Dataframe(label="Falhas (Editar Novo Número)", interactive=True)
|
| 401 |
-
|
| 402 |
gr.Markdown("### Correção Assistida")
|
| 403 |
idx_selecionado = gr.Number(visible=False)
|
| 404 |
info_lado = gr.Textbox(label="Lado", interactive=False)
|
| 405 |
info_intervalo = gr.Textbox(label="Intervalo Válido", interactive=False)
|
| 406 |
radio_sugestoes = gr.Radio(label="Escolha o Número Correto")
|
| 407 |
btn_aplicar_sugestao = gr.Button("Aplicar Sugestão")
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
# =============================
|
| 411 |
-
# EVENTOS
|
| 412 |
-
# =============================
|
| 413 |
-
|
| 414 |
-
arquivo.change(
|
| 415 |
-
fn=carregar_abas,
|
| 416 |
-
inputs=arquivo,
|
| 417 |
-
outputs=[dropdown_abas, dropdown_abas]
|
| 418 |
-
)
|
| 419 |
-
|
| 420 |
-
dropdown_abas.change(
|
| 421 |
-
fn=exibir_tabela,
|
| 422 |
-
inputs=[arquivo, dropdown_abas, dropdown_num],
|
| 423 |
-
outputs=[tabela, linhas_info]
|
| 424 |
-
).then(
|
| 425 |
-
fn=lambda df: df,
|
| 426 |
-
inputs=tabela,
|
| 427 |
-
outputs=estado_tabela
|
| 428 |
-
).then(
|
| 429 |
-
fn=listar_colunas,
|
| 430 |
-
inputs=[arquivo, dropdown_abas],
|
| 431 |
-
outputs=[dropdown_cdlog, dropdown_num]
|
| 432 |
-
)
|
| 433 |
-
|
| 434 |
-
btn_interpolar.click(
|
| 435 |
-
fn=interpolar,
|
| 436 |
-
inputs=[tabela, dropdown_cdlog, dropdown_num],
|
| 437 |
-
outputs=[tabela_resultado, arquivo_saida, falhas]
|
| 438 |
-
)
|
| 439 |
-
|
| 440 |
-
falhas.select(
|
| 441 |
-
fn=preparar_sugestoes,
|
| 442 |
-
inputs=falhas,
|
| 443 |
-
outputs=[
|
| 444 |
-
idx_selecionado,
|
| 445 |
-
info_lado,
|
| 446 |
-
info_intervalo,
|
| 447 |
-
radio_sugestoes
|
| 448 |
-
]
|
| 449 |
-
)
|
| 450 |
-
|
| 451 |
-
btn_aplicar_sugestao.click(
|
| 452 |
-
fn=aplicar_sugestao,
|
| 453 |
-
inputs=[estado_tabela, idx_selecionado, radio_sugestoes, dropdown_num],
|
| 454 |
-
outputs=estado_tabela
|
| 455 |
-
).then(
|
| 456 |
-
fn=lambda df: df,
|
| 457 |
-
inputs=estado_tabela,
|
| 458 |
-
outputs=tabela
|
| 459 |
-
).then(
|
| 460 |
-
fn=interpolar,
|
| 461 |
-
inputs=[estado_tabela, dropdown_cdlog, dropdown_num],
|
| 462 |
-
outputs=[tabela_resultado, arquivo_saida, falhas]
|
| 463 |
-
)
|
| 464 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 465 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 466 |
|
| 467 |
-
app.launch(server_name="0.0.0.0", server_port=7860)
|
|
|
|
| 2 |
import pandas as pd
|
| 3 |
import geopandas as gpd
|
| 4 |
|
| 5 |
+
# Carregamento único dos eixos
|
|
|
|
|
|
|
| 6 |
gdf_eixos = gpd.read_file("EixosLogradouros.shp", engine="fiona")
|
| 7 |
gdf_eixos = gdf_eixos.to_crs("EPSG:4326")
|
| 8 |
+
eixos_por_cdlog = {cdlog: grupo.copy() for cdlog, grupo in gdf_eixos.groupby("CDLOG")}
|
| 9 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
# Funções auxiliares
|
|
|
|
| 11 |
def formatar_float_visualizacao(df, casas=4):
|
| 12 |
df_visual = df.copy()
|
| 13 |
float_cols = df_visual.select_dtypes(include=["float"]).columns
|
| 14 |
df_visual[float_cols] = df_visual[float_cols].round(casas)
|
| 15 |
return df_visual
|
| 16 |
|
|
|
|
| 17 |
def carregar_abas(arquivo_excel):
|
| 18 |
if arquivo_excel is None:
|
| 19 |
return gr.update(choices=[]), None
|
|
|
|
| 21 |
abas = xls.sheet_names
|
| 22 |
return gr.update(choices=abas, value=abas[0]), abas[0]
|
| 23 |
|
|
|
|
| 24 |
def listar_colunas(arquivo_excel, aba):
|
| 25 |
if arquivo_excel is None or aba is None:
|
| 26 |
return gr.update(choices=[]), gr.update(choices=[])
|
|
|
|
| 27 |
df = pd.read_excel(arquivo_excel.name, sheet_name=aba)
|
| 28 |
colunas = df.columns.tolist()
|
|
|
|
|
|
|
| 29 |
colunas_upper = {col.upper(): col for col in colunas}
|
| 30 |
|
| 31 |
+
coluna_cdlog_pre = colunas_upper.get("CTM", colunas_upper.get("CDLOG", None))
|
| 32 |
+
coluna_num_pre = next((colunas_upper[nome.upper()] for nome in ["Nº GEO", "NUM_GEO", "NUM"] if nome.upper() in colunas_upper), None)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
|
| 34 |
+
return gr.update(choices=colunas, value=coluna_cdlog_pre), gr.update(choices=colunas, value=coluna_num_pre)
|
| 35 |
|
| 36 |
def exibir_tabela(arquivo_excel, aba, coluna_num):
|
| 37 |
if arquivo_excel is None or aba is None:
|
| 38 |
return None, ""
|
|
|
|
| 39 |
df = pd.read_excel(arquivo_excel.name, sheet_name=aba)
|
|
|
|
|
|
|
| 40 |
df["_idx"] = range(len(df))
|
|
|
|
| 41 |
if coluna_num in df.columns:
|
| 42 |
df[coluna_num] = pd.to_numeric(df[coluna_num], errors="coerce").fillna(0).astype(int)
|
|
|
|
| 43 |
texto = f"O DataFrame possui {df.shape[0]} linhas e {df.shape[1]} colunas."
|
| 44 |
return formatar_float_visualizacao(df), texto
|
| 45 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
def interpolar(df, coluna_cdlog, coluna_num):
|
|
|
|
| 47 |
df = df.copy()
|
| 48 |
df[coluna_num] = pd.to_numeric(df[coluna_num], errors="coerce").fillna(0).astype(int)
|
| 49 |
|
| 50 |
+
lons, lats, falhas = [], [], []
|
|
|
|
|
|
|
| 51 |
|
| 52 |
for _, row in df.iterrows():
|
| 53 |
+
idx, cdlog, numero = row["_idx"], row[coluna_cdlog], row[coluna_num]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
segmentos = eixos_por_cdlog.get(cdlog)
|
| 55 |
|
|
|
|
|
|
|
|
|
|
| 56 |
if segmentos is None:
|
|
|
|
| 57 |
lons.append(None)
|
| 58 |
lats.append(None)
|
|
|
|
| 59 |
falhas.append({
|
| 60 |
"_idx": idx,
|
| 61 |
"CDLOG": cdlog,
|
| 62 |
"Numero Atual": numero,
|
| 63 |
"Motivo": "CDLOG não encontrado",
|
| 64 |
+
"Lado": "",
|
| 65 |
+
"Intervalo": "",
|
| 66 |
+
"Sugestões": []
|
| 67 |
})
|
| 68 |
continue
|
| 69 |
|
| 70 |
+
lado = "Par" if numero % 2 == 0 else "Ímpar"
|
| 71 |
+
ini_col, fim_col = ("NRPARINI", "NRPARFIN") if lado == "Par" else ("NRIMPINI", "NRIMPFIN")
|
| 72 |
+
cond = (segmentos[ini_col] <= numero) & (segmentos[fim_col] >= numero)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
seg_validos = segmentos[cond]
|
| 74 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
if seg_validos.empty:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
if not segmentos.empty:
|
| 77 |
+
diffs = (segmentos[ini_col] - numero).abs()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
if not diffs.empty:
|
| 79 |
min_index = diffs.idxmin()
|
| 80 |
linha_proxima = segmentos.loc[min_index]
|
| 81 |
+
ini, fim = linha_proxima[ini_col], linha_proxima[fim_col]
|
|
|
|
|
|
|
|
|
|
| 82 |
if pd.notna(ini) and pd.notna(fim):
|
|
|
|
|
|
|
|
|
|
| 83 |
numeros_validos = list(range(int(ini), int(fim) + 1, 2))
|
| 84 |
numeros_validos.sort(key=lambda x: abs(x - numero))
|
| 85 |
+
falhas.append({
|
| 86 |
+
"_idx": idx,
|
| 87 |
+
"CDLOG": cdlog,
|
| 88 |
+
"Numero Atual": numero,
|
| 89 |
+
"Motivo": "Numeração fora do intervalo",
|
| 90 |
+
"Lado": lado,
|
| 91 |
+
"Intervalo": f"{int(ini)} até {int(fim)}",
|
| 92 |
+
"Sugestões": numeros_validos[:10]
|
| 93 |
+
})
|
| 94 |
+
lons.append(None)
|
| 95 |
+
lats.append(None)
|
| 96 |
+
continue
|
| 97 |
lons.append(None)
|
| 98 |
lats.append(None)
|
|
|
|
| 99 |
falhas.append({
|
| 100 |
"_idx": idx,
|
| 101 |
"CDLOG": cdlog,
|
| 102 |
"Numero Atual": numero,
|
| 103 |
"Motivo": "Numeração fora do intervalo",
|
| 104 |
"Lado": lado,
|
| 105 |
+
"Intervalo": "",
|
| 106 |
+
"Sugestões": []
|
| 107 |
})
|
|
|
|
| 108 |
continue
|
| 109 |
|
|
|
|
|
|
|
|
|
|
| 110 |
linha = seg_validos.iloc[0]
|
| 111 |
geom = linha.geometry
|
| 112 |
+
ini, fim = linha[ini_col], linha[fim_col]
|
|
|
|
|
|
|
|
|
|
| 113 |
if fim == ini:
|
| 114 |
lons.append(None)
|
| 115 |
lats.append(None)
|
| 116 |
continue
|
|
|
|
| 117 |
frac = (numero - ini) / (fim - ini)
|
| 118 |
frac = max(0, min(1, frac))
|
| 119 |
ponto = geom.interpolate(geom.length * frac)
|
|
|
|
| 120 |
lons.append(ponto.x)
|
| 121 |
lats.append(ponto.y)
|
| 122 |
|
|
|
|
|
|
|
|
|
|
| 123 |
df["lon"] = lons
|
| 124 |
df["lat"] = lats
|
|
|
|
| 125 |
output_path = "dados_interpolados.xlsx"
|
| 126 |
df.to_excel(output_path, index=False)
|
| 127 |
|
| 128 |
+
colunas_fixas = ["_idx", "CDLOG", "Numero Atual", "Motivo", "Lado", "Intervalo", "Sugestões"]
|
| 129 |
+
df_falhas = pd.DataFrame(falhas, columns=colunas_fixas) if falhas else pd.DataFrame(columns=colunas_fixas)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 130 |
|
| 131 |
return formatar_float_visualizacao(df), output_path, df_falhas
|
| 132 |
|
| 133 |
+
def preparar_sugestoes(df_falhas, evt):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
linha = df_falhas.iloc[evt.index[0]]
|
|
|
|
| 135 |
idx = linha["_idx"]
|
| 136 |
lado = linha.get("Lado", "")
|
| 137 |
intervalo = linha.get("Intervalo", "")
|
| 138 |
sugestoes = linha.get("Sugestões", [])
|
|
|
|
|
|
|
| 139 |
if isinstance(sugestoes, str):
|
| 140 |
sugestoes = [int(x.strip()) for x in sugestoes.split(",") if x.strip().isdigit()]
|
| 141 |
+
return idx, lado, intervalo, gr.update(choices=sugestoes, value=None)
|
| 142 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 143 |
def aplicar_sugestao(df_original, idx, numero_escolhido, coluna_num):
|
|
|
|
| 144 |
if numero_escolhido is None:
|
| 145 |
return df_original
|
|
|
|
| 146 |
df_original = df_original.copy()
|
|
|
|
| 147 |
df_original.loc[df_original["_idx"] == idx, coluna_num] = int(numero_escolhido)
|
|
|
|
| 148 |
return df_original
|
| 149 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 150 |
# Interface
|
|
|
|
| 151 |
with gr.Blocks() as app:
|
|
|
|
| 152 |
gr.Markdown("## DAI - Geolocalização com Correção Assistida")
|
|
|
|
| 153 |
estado_tabela = gr.State()
|
| 154 |
|
| 155 |
arquivo = gr.File(label="Arquivo Excel", file_types=[".xlsx"])
|
| 156 |
dropdown_abas = gr.Dropdown(label="Aba")
|
| 157 |
linhas_info = gr.Textbox(label="Linhas e Colunas", interactive=False)
|
|
|
|
| 158 |
dropdown_cdlog = gr.Dropdown(label="Coluna CDLOG")
|
| 159 |
dropdown_num = gr.Dropdown(label="Coluna Número")
|
|
|
|
| 160 |
tabela = gr.Dataframe(label="Tabela Original", interactive=False)
|
|
|
|
| 161 |
btn_interpolar = gr.Button("Interpolar")
|
|
|
|
| 162 |
tabela_resultado = gr.Dataframe(label="Com Coordenadas", interactive=False)
|
| 163 |
arquivo_saida = gr.File(label="Arquivo Gerado")
|
|
|
|
| 164 |
falhas = gr.Dataframe(label="Falhas (Editar Novo Número)", interactive=True)
|
|
|
|
| 165 |
gr.Markdown("### Correção Assistida")
|
| 166 |
idx_selecionado = gr.Number(visible=False)
|
| 167 |
info_lado = gr.Textbox(label="Lado", interactive=False)
|
| 168 |
info_intervalo = gr.Textbox(label="Intervalo Válido", interactive=False)
|
| 169 |
radio_sugestoes = gr.Radio(label="Escolha o Número Correto")
|
| 170 |
btn_aplicar_sugestao = gr.Button("Aplicar Sugestão")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 171 |
|
| 172 |
+
# Eventos
|
| 173 |
+
arquivo.change(fn=carregar_abas, inputs=arquivo, outputs=[dropdown_abas, dropdown_abas])
|
| 174 |
+
dropdown_abas.change(fn=exibir_tabela, inputs=[arquivo, dropdown_abas, dropdown_num], outputs=[tabela, linhas_info]).then(
|
| 175 |
+
fn=lambda df: df, inputs=tabela, outputs=estado_tabela
|
| 176 |
+
).then(fn=listar_colunas, inputs=[arquivo, dropdown_abas], outputs=[dropdown_cdlog, dropdown_num])
|
| 177 |
|
| 178 |
+
btn_interpolar.click(fn=interpolar, inputs=[tabela, dropdown_cdlog, dropdown_num], outputs=[tabela_resultado, arquivo_saida, falhas])
|
| 179 |
+
falhas.select(fn=preparar_sugestoes, inputs=falhas, outputs=[idx_selecionado, info_lado, info_intervalo, radio_sugestoes])
|
| 180 |
+
btn_aplicar_sugestao.click(fn=aplicar_sugestao, inputs=[estado_tabela, idx_selecionado, radio_sugestoes, dropdown_num], outputs=estado_tabela).then(
|
| 181 |
+
fn=lambda df: df, inputs=estado_tabela, outputs=tabela
|
| 182 |
+
).then(fn=interpolar, inputs=[estado_tabela, dropdown_cdlog, dropdown_num], outputs=[tabela_resultado, arquivo_saida, falhas])
|
| 183 |
|
| 184 |
+
app.launch(server_name="0.0.0.0", server_port=7860)
|