init depot renew
This commit is contained in:
Executable
+613
@@ -0,0 +1,613 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: UTF-8 -*-
|
||||
#Nom : : foncier_insert_table.py
|
||||
#Description : Insertion des données cadastrales à la base <foncier>.
|
||||
#Copyright : 2021, CEN38
|
||||
#Auteur : Colas Geier
|
||||
#Version : 2.0
|
||||
|
||||
|
||||
from sqlalchemy import create_engine, text
|
||||
from geoalchemy2 import Geometry # need for pandas
|
||||
import datetime as dt
|
||||
import pandas as pd
|
||||
import sys
|
||||
|
||||
|
||||
# Parametrage geopandas
|
||||
import geopandas as gpd
|
||||
import warnings; warnings.filterwarnings('ignore', 'GeoSeries.isna', UserWarning)
|
||||
|
||||
|
||||
check_duplicates = True
|
||||
debug = True
|
||||
# Parametres bdd CADASTRE (in)
|
||||
# Données de sortie du plugin qgis "Cadastre"
|
||||
# Les schéma ont une nomenclarture numérique du type "dep_nom"
|
||||
user_cad = 'postgres' # utilisateur de connexion à la bdd
|
||||
pwd_cad = 'foncier_test1' # mot de passe de la bdd
|
||||
adr_cad = '172.17.0.2' # adresse ip de la bdd
|
||||
port_cad = '5432' # port de la bdd
|
||||
base_cad = 'postgres' # nom de la bdd
|
||||
schema_cad = '202007' # nom unique qui compose le nom des schémas cibles de l'année à récupérer
|
||||
list_dep = ['07', '26', '42', '38'] # liste des départements
|
||||
|
||||
|
||||
# Parametres bdd FONCIER (out)
|
||||
user_fon = 'colas_geier'
|
||||
pwd_fon = 'adm1n*fOncier'
|
||||
adr_fon = '91.134.194.221'
|
||||
# user_fon = 'postgres' # utilisateur de connexion à la bdd
|
||||
# pwd_fon = 'tutu' # mot de passe de la bdd
|
||||
# adr_fon = '192.168.60.9' # adresse ip de la bdd
|
||||
port_fon = '5432' # port de la bdd
|
||||
base_fon = 'bd_cen' # nom de la bdd
|
||||
schema_fon = 'cadastre' # nom du schéma cible dans la bdd
|
||||
sufx_nom_tab = '_38' # sufixe du nom des tables où insérer la données dans le schéma cadastre (ex: _dep)
|
||||
|
||||
|
||||
# Correspondance entre les tables
|
||||
epsg = '2154' # code EPSG de la projection géographique en entrée.
|
||||
crs = 'EPSG:%s'%epsg
|
||||
chunk = 100000
|
||||
|
||||
# Il existe parfois des doublons en raison d'orthographes voisinent (entre autres)
|
||||
# dans les tables de sortie du du plugin qgis "Cadastre"
|
||||
FIND_DOUBLON = [{
|
||||
'tab_in': 'proprietaire', # nom de la table où des doublons se trouvent
|
||||
'on_col': ['ddenom', 'dprnlp', 'dldnss','jdatnss','ccogrm','dsglpm','dnatpr'] } # nom des champs où des corrections sont nécessaires
|
||||
]
|
||||
|
||||
DICT_TAB = [{
|
||||
'table_in' : 'proprietaire', # Table source qui provient de la sortie du plugin cadastre de qgis
|
||||
'index_tab': 'proprietaire', # Pkey de la table source
|
||||
'columns_in': ['ccodep', 'ccocom', 'dnupro', # Liste exaustive des champs à récupérer dans la table source
|
||||
'dnuper', 'ccoqua', 'ddenom', 'jdatnss', 'dldnss', 'dsglpm', 'dlign3', 'dlign4', 'dlign5', 'dlign6', 'dnatpr', 'gtoper', 'ccogrm'],
|
||||
'table_out': [{
|
||||
'name': 'cptprop{}'.format(sufx_nom_tab), # Nom de la table cible
|
||||
'geom': None, # Existance d'une géometrie à récupérer pour insertion (Non: None, Oui: cf tab_out parcelle_xx ci-dessous)
|
||||
'drop_escape': False, # Supprime les champs vides à l'intérieure des chaines de carractères
|
||||
'columns_in': ['ccodep', 'ccocom', 'dnupro'], # Liste des columns à récupérer en entrée.
|
||||
'columns_add': {'dnupro': ['ccodep', 'ccocom', 'dnupro']}, # Définition des champs composés devant être ajoutés
|
||||
'unique': {'cols': ['dnupro'], 'keep': 'first'}, # Champs devant être uniques à l'intérieur de la table en sortie, keep: ['first', 'last', False]
|
||||
'dict': None, # Dictionnaire pour renommer les champs {'ancien_nom1': 'nouveau_nom1', 'ancien_nom2': 'nouveau_nom2', ...}
|
||||
'join': [{ # Jointure de tables à réaliser.
|
||||
'bdd': 'in', # ['in', 'out']: jointure des tables à l'import / avant export
|
||||
'table': 'suf', # Nom de la table à joindre
|
||||
'select_cols' : ['ccodep', 'ccocom', 'dnupro'], # Nom des champs à récupérer
|
||||
'on': ['ccodep', 'ccocom', 'dnupro'], # Nom des champs sur lesquelles faire la jointure
|
||||
'type': 'concat' # Type de jointure à réaliser ['concat', 'merge', 'isin', 'notin']
|
||||
# 'concat': concatène les 2 tables; 'merge': merge les 2 tables en fonction du paramètre 'on'
|
||||
# 'isin': Conservation des données présentent dans les 2 tables en fonction du paramètre 'on'
|
||||
# 'notin': Conservation des données NON présentent dans la table 'join' en fonction du paramètre 'on'
|
||||
},{
|
||||
'bdd': 'in', 'table': 'lots', 'on': ['ccodep', 'ccocom', 'dnupro'], 'type': 'concat',
|
||||
'select_cols' : ['ccodep', 'ccocom', 'dnuprol'],'dict': {'dnuprol': 'dnupro'}},{
|
||||
'bdd': 'in', 'table': 'parcelle', 'on': ['ccodep', 'ccocom', 'dnupro'], 'type': 'concat',
|
||||
'select_cols' : ['ccodep', 'ccocom', 'dnupro']},]
|
||||
},{
|
||||
'name': 'proprios{}'.format(sufx_nom_tab),
|
||||
'geom': None,
|
||||
'drop_escape': True,
|
||||
'columns_in': ['ccodep', 'dnuper', 'ccoqua', 'ddenom', 'jdatnss', 'dldnss', 'dsglpm', 'dlign3', 'dlign4', 'dlign5', 'dlign6', 'dnatpr', 'gtoper', 'ccogrm'],
|
||||
'columns_add': {'dnuper': ['ccodep', 'dnuper']},
|
||||
'unique': {'cols': ['dnuper'], 'keep': 'first'},
|
||||
'dict': None,
|
||||
'join': False
|
||||
},{
|
||||
'name': 'r_prop_cptprop{}'.format(sufx_nom_tab),
|
||||
'geom': None,
|
||||
'drop_escape': True,
|
||||
'columns_in': ['ccodep', 'dnuper', 'ccocom', 'dnupro', 'dnomlp', 'dprnlp', 'epxnee', 'dnomcp', 'dprncp', 'ccodro', 'ccodem'],
|
||||
'columns_add': {
|
||||
'dnuper': ['ccodep', 'dnuper'],
|
||||
'dnupro': ['ccodep', 'ccocom', 'dnupro']},
|
||||
'unique': {'cols': ['dnupro', 'dnuper'], 'keep': 'first'},
|
||||
'dict': None,
|
||||
'join': False
|
||||
},]
|
||||
},{
|
||||
'table_in' : 'parcelle',
|
||||
'index_tab': 'parcelle',
|
||||
'columns_in' : ['ccodep', 'ccocom', 'ccopre', 'ccosec', 'dnupla', 'ccovoi', 'dparpi', 'dcntpa', 'ccocomm', 'ccoprem', 'ccosecm', 'dnuplam', 'dvoilib', 'type_filiation'],
|
||||
'table_out': [{
|
||||
'name': 'vl{}'.format(sufx_nom_tab),
|
||||
'geom': None,
|
||||
'drop_escape': False,
|
||||
'columns_in' : ['ccodep', 'ccocom', 'ccovoi', 'dvoilib'],
|
||||
'columns_add': {
|
||||
'vl_id': ['ccodep', 'ccocom', 'ccovoi'],
|
||||
'geom': None},
|
||||
'unique': {'cols': ['vl_id'], 'keep': 'first'},
|
||||
'dict': {'dvoilib': 'libelle'},
|
||||
'join': [{
|
||||
'bdd': 'in', 'table': 'voie', 'on': ['ccodep', 'ccocom', 'ccovoi'], 'type': 'concat',
|
||||
'select_cols' : ['ccodep', 'ccocom', 'codvoi', 'libvoi'],
|
||||
'dict': {'libvoi': 'libelle', 'codvoi': 'ccovoi'},
|
||||
}]
|
||||
},{
|
||||
'name': 'parcelles{}'.format(sufx_nom_tab),
|
||||
'geom': {
|
||||
'table_geom_in': 'geo_parcelle',
|
||||
'index_geom': 'geo_parcelle'
|
||||
},
|
||||
'drop_escape': True,
|
||||
'columns_in' : ['ccodep', 'ccocom', 'ccopre', 'ccosec', 'dnupla', 'ccovoi', 'dparpi', 'dcntpa', 'ccocomm', 'ccoprem', 'ccosecm', 'dnuplam', 'type_filiation'],
|
||||
'columns_add': {
|
||||
'par_id': ['ccodep', 'ccocom', 'ccopre','ccosec', 'dnupla'],
|
||||
'codcom': ['ccodep', 'ccocom'],
|
||||
'vl_id': ['ccodep', 'ccocom', 'ccovoi'],
|
||||
'typprop_id': None },
|
||||
'unique': False,
|
||||
'dict': {'type_filiation': 'type'},
|
||||
'join': False
|
||||
},{
|
||||
'name': 'lots{}'.format(sufx_nom_tab),
|
||||
'geom': None,
|
||||
'drop_escape': True,
|
||||
'columns_in' : ['ccodep', 'ccocom', 'ccopre', 'ccosec', 'dnupla', 'dcntpa'],
|
||||
'columns_add': {
|
||||
'lot_id': ['ccodep', 'ccocom', 'ccopre', 'ccosec', 'dnupla'],
|
||||
'par_id': ['ccodep', 'ccocom', 'ccopre', 'ccosec', 'dnupla'],
|
||||
'dnulot': None, },
|
||||
'unique': False,
|
||||
'dict': {'dcntpa': 'dcntlo'},
|
||||
'join': [{'bdd': 'out', 'table': 'parcelles{}'.format(sufx_nom_tab), 'on': ['par_id'], 'type': 'isin',
|
||||
'select_cols' :['par_id'] }]
|
||||
},]
|
||||
},{
|
||||
'table_in' : 'lots',
|
||||
'index_tab': 'lots',
|
||||
'columns_in' : ['ccodep', 'ccocom', 'ccopre', 'ccosec', 'dnupla', 'dnulot', 'dnupdl', 'dcntlo', 'dnuprol'],
|
||||
'table_out': [{
|
||||
'name': 'lots{}'.format(sufx_nom_tab),
|
||||
'geom': None,
|
||||
'drop_escape': True,
|
||||
'columns_in' : ['ccodep', 'ccocom', 'ccopre', 'ccosec', 'dnupla', 'dnulot', 'dnupdl', 'dcntlo'],
|
||||
'columns_add': {
|
||||
'lot_id': ['ccodep', 'ccocom', 'ccopre', 'ccosec', 'dnupla', 'dnulot'],
|
||||
'par_id': ['ccodep', 'ccocom', 'ccopre', 'ccosec', 'dnupla'],},
|
||||
'unique': {'cols': ['lot_id'], 'keep': 'first'},
|
||||
'dict': None,
|
||||
'join': [{'bdd': 'out', 'table': 'parcelles{}'.format(sufx_nom_tab), 'on': ['par_id'], 'type': 'isin',
|
||||
'select_cols' :['par_id'] }]
|
||||
},{
|
||||
'name': 'lots_natcult{}'.format(sufx_nom_tab),
|
||||
'geom': None,
|
||||
'drop_escape': True,
|
||||
'columns_in' : ['ccodep', 'ccocom', 'ccopre', 'ccosec', 'dnupla', 'dnulot'],
|
||||
'columns_add': {
|
||||
'lot_id': ['ccodep', 'ccocom', 'ccopre', 'ccosec', 'dnupla', 'dnulot'],},
|
||||
'unique': {'cols': ['lot_id'], 'keep': 'first'},
|
||||
'dict': None,
|
||||
'join': [{
|
||||
'bdd': 'in', 'table': 'suf', 'on': ['ccodep', 'ccocom', 'ccopre', 'ccosec', 'dnupla', 'dnulot'], 'type': 'merge',
|
||||
'select_cols' : ['ccodep', 'ccocom', 'ccopre', 'ccosec', 'dnupla', 'dnulot','dsgrpf','cnatsp','dclssf','ccosub','dcntsf'],
|
||||
},{
|
||||
'bdd': 'out', 'table': 'lots{}'.format(sufx_nom_tab), 'on': ['lot_id'], 'type': 'isin',
|
||||
'select_cols' :['lot_id'] }]
|
||||
},{
|
||||
'name': 'cadastre{}'.format(sufx_nom_tab),
|
||||
'geom': None,
|
||||
'drop_escape': True,
|
||||
'columns_in' : ['ccodep', 'ccocom', 'ccopre', 'ccosec', 'dnupla', 'dnulot', 'dnuprol'],
|
||||
'columns_add': {
|
||||
'lot_id': ['ccodep', 'ccocom', 'ccopre', 'ccosec', 'dnupla', 'dnulot'],
|
||||
'dnupro': ['ccodep', 'ccocom', 'dnuprol'],},
|
||||
'unique': {'cols': ['lot_id', 'dnupro'], 'keep': 'first'},
|
||||
'dict': None,
|
||||
'join': [{
|
||||
'bdd': 'in', 'table': 'suf', 'on': ['ccodep', 'ccocom', 'ccopre', 'ccosec', 'dnupla', 'dnulot', 'dnuprol'], 'type': 'concat',
|
||||
'select_cols' : ['ccodep', 'ccocom', 'ccopre', 'ccosec', 'dnupla', 'dnulot', 'dnupro'], 'dict': {'dnupro': 'dnuprol'}
|
||||
},{
|
||||
'bdd': 'in', 'table': 'parcelle', 'on': ['ccodep', 'ccocom', 'ccopre', 'ccosec', 'dnupla', 'dnuprol'], 'type': 'concat',
|
||||
'select_cols' : ['ccodep', 'ccocom', 'ccopre', 'ccosec', 'dnupla', 'dnupro'], 'dict': {'dnupro': 'dnuprol'}
|
||||
},{
|
||||
'bdd': 'out', 'table': 'lots{}'.format(sufx_nom_tab), 'on': ['lot_id'], 'type': 'isin',
|
||||
'select_cols' :['lot_id'] },{
|
||||
'bdd': 'out', 'table': 'cptprop{}'.format(sufx_nom_tab), 'on': ['dnupro'], 'type': 'isin',
|
||||
'select_cols' :['dnupro'] },]
|
||||
},]
|
||||
}]
|
||||
|
||||
|
||||
|
||||
################################
|
||||
########## Fonctions ##########
|
||||
################################
|
||||
start_time = dt.datetime.today()
|
||||
def time_exec (init_time):
|
||||
time = dt.datetime.today() - init_time
|
||||
return str(time)
|
||||
|
||||
|
||||
def replace_escape_by_0 (df):
|
||||
# Remplacement des espaces dans les chaines de caractères par des 0
|
||||
# if 'ccopre' in df.columns:
|
||||
# df['ccopre'].replace([None, '', ' '], '000', inplace=True)
|
||||
|
||||
cols = ['ccopre', 'ccosec', 'dnupla', 'dparpi', 'dnuplam', 'dclssf', 'ccovoi']
|
||||
for col in cols:
|
||||
if col in df.columns:
|
||||
df[col].replace([' '], '0', regex=True, inplace=True)
|
||||
|
||||
return df
|
||||
|
||||
|
||||
def join_data (df, join, schema_in):
|
||||
# Jointure des données avec une autre table
|
||||
table = join['table']
|
||||
bdd = join['bdd']
|
||||
typ = join['type']
|
||||
on = join['on']
|
||||
if bdd == 'out':
|
||||
con = engine_fon
|
||||
sch = schema_fon
|
||||
if bdd == 'in':
|
||||
con = engine_cad
|
||||
sch = schema_in
|
||||
select_col = []
|
||||
if 'select_cols' in join.keys():
|
||||
select_col.extend(join['select_cols'])
|
||||
if 'where' in join.keys():
|
||||
select_col.extend(join['where'].keys())
|
||||
|
||||
tmp = pd.read_sql_table(
|
||||
table_name = table,
|
||||
con = con,
|
||||
schema = sch,
|
||||
columns = select_col
|
||||
)
|
||||
tmp = replace_escape_by_0(tmp)
|
||||
if 'dict' in join.keys():
|
||||
tmp.rename(columns=join['dict'], inplace=True)
|
||||
if 'where' in join.keys():
|
||||
where = join['where']
|
||||
for key in where.keys():
|
||||
tmp = tmp[tmp[key] == where[key] ]
|
||||
|
||||
if typ in ['isin', 'notin']:
|
||||
for d in [df, tmp]:
|
||||
d['on'] = ''
|
||||
for col in on:
|
||||
d['on'] += d[col].astype(str)
|
||||
if typ == 'isin':
|
||||
df = df[df['on'].isin(tmp['on'])]
|
||||
if typ == 'notin':
|
||||
df = df[~df['on'].isin(tmp['on'])]
|
||||
df.drop(columns='on', inplace=True)
|
||||
if typ == 'merge':
|
||||
df = df.merge(tmp, on = on, how='left')
|
||||
if typ == 'concat':
|
||||
df = pd.concat([df,tmp], ignore_index=True).drop_duplicates()
|
||||
|
||||
return df
|
||||
|
||||
def get_geom_parcelle (df,get_geo,schema):
|
||||
print('INIT import geodata ........... %s sec'%( time_exec(start_time) ))
|
||||
|
||||
# Définition des variables géometriques
|
||||
ind_geo = get_geo['index_geom']
|
||||
tab_geo = get_geo['table_geom_in']
|
||||
|
||||
sql = """select distinct on (t2.{0})
|
||||
t2.{0},
|
||||
t1.geom,
|
||||
t1.supf::integer as dcntpa -- récupération de la contenance cadastrale associée car présence de géometrie non référencées dans la table "parcelles"
|
||||
FROM "{1}".{2} t1
|
||||
INNER JOIN (select distinct on ({0}) {0}, max(creat_date) creat_date, max(update_dat) update_dat FROM "{1}".{2} GROUP BY ({0})) t2
|
||||
USING ({0}, creat_date, update_dat)""".format(ind_geo, schema, tab_geo)
|
||||
tmp = gpd.read_postgis(
|
||||
sql = sql,
|
||||
con = engine_cad,
|
||||
geom_col = 'geom',
|
||||
crs = crs,
|
||||
chunksize = chunk,
|
||||
)
|
||||
|
||||
if chunk:
|
||||
gdf = gpd.GeoDataFrame(pd.concat(tmp, ignore_index=True))
|
||||
else:
|
||||
gdf = tmp.copy()
|
||||
del tmp
|
||||
gdf.set_index(ind_geo, inplace=True)
|
||||
gdf.index.name = ind_in
|
||||
print('END import geodata ........... %s sec'%( time_exec(start_time) ))
|
||||
|
||||
|
||||
print('INIT merge data - geodata ........... %s sec'%( time_exec(start_time) ))
|
||||
if not gdf[gdf.dcntpa.isna()].empty:
|
||||
gdf.dcntpa.fillna(0, inplace=True)
|
||||
gdf['dcntpa'] = gdf['dcntpa'].astype(df.dtypes['dcntpa'].type)
|
||||
tmp = gdf.merge(df, on = [ind_in, 'dcntpa'], how='right')
|
||||
tmp = tmp.set_geometry('geom', drop=True, crs=crs)
|
||||
tmp.rename(columns={'geometry': 'geom'}, inplace=True)
|
||||
|
||||
if tmp[tmp.geom.isna()].empty:
|
||||
lst_ind_df = tmp[tmp.geom.isna()].index.tolist()
|
||||
lst_ind_gdf = gdf.loc[gdf.index.isin(lst_ind_df)].index.tolist()
|
||||
tmp.loc[tmp.index.isin(lst_ind_gdf), 'geom'] = gdf.loc[gdf.index.isin(lst_ind_gdf), 'geom']
|
||||
|
||||
del [gdf, df]
|
||||
gdf = tmp.copy()
|
||||
del tmp
|
||||
export_data(gdf)
|
||||
|
||||
|
||||
def export_data(df):
|
||||
print('INIT export data TO {0}, {1} ........... {2} sec'.format(tab_out, df.shape[0], time_exec(start_time) ))
|
||||
rang = [e for e in range(0, df.shape[0], chunk*5)]
|
||||
|
||||
cd1 = 'jdatnss' in df.columns
|
||||
if cd1 :
|
||||
tmp = df.jdatnss.str.split(r'/',expand=True)
|
||||
if tmp.shape[1] == 3 and tmp[2].str.len().max() == 4 and tmp[1].astype(int).max() <= 12:
|
||||
df.jdatnss = ['%s-%s-%s'%(i[2],i[1],i[0]) for i in df.jdatnss.str.split(r'/').sort_index()]
|
||||
|
||||
for i, j in enumerate(rang):
|
||||
if j == max(rang) :
|
||||
jj = df.shape[0]
|
||||
else:
|
||||
jj = rang[i+1]
|
||||
|
||||
df_imp = df[j:jj].copy()
|
||||
|
||||
print('INIT export data TO {0} ..... {1}/{2} ...... {3} sec'.format(tab_out, jj, df.shape[0], time_exec(start_time) ))
|
||||
if 'geom' in df.columns and not df[~df['geom'].isna()].empty :
|
||||
df_imp = df_imp.set_geometry('geom', drop=True, crs=crs)
|
||||
df_imp.rename(columns={'geometry': 'geom'}, inplace=True)
|
||||
df_imp.to_postgis(
|
||||
name = tab_out,
|
||||
con = engine_fon,
|
||||
schema = schema_fon,
|
||||
index = False,
|
||||
if_exists = 'append',
|
||||
geom_col = 'geom',
|
||||
chunksize = chunk,
|
||||
)
|
||||
else:
|
||||
df_imp.to_sql(
|
||||
name = tab_out,
|
||||
con = engine_fon,
|
||||
schema = schema_fon,
|
||||
index = False,
|
||||
if_exists = 'append',
|
||||
chunksize = chunk,
|
||||
method = 'multi',
|
||||
)
|
||||
print('END export data TO {0} ........... {1} sec'.format(tab_out, time_exec(start_time) ))
|
||||
|
||||
def optimize_data_frame(df):
|
||||
columns = df.columns
|
||||
for col in columns:
|
||||
# dtype = df[col].dtypes
|
||||
# if dtype == 'int64' or dtype == 'int32':
|
||||
len_col = len(df[col].unique())
|
||||
if len_col <= df.shape[0]*0.8:
|
||||
df[col] = df[col].astype('category')
|
||||
|
||||
return df
|
||||
|
||||
|
||||
# Initiation des connexions bdd
|
||||
engine_cad = create_engine('postgresql+psycopg2://{0}:{1}@{2}:{3}/{4}'.format(user_cad,pwd_cad,adr_cad,port_cad,base_cad), echo=False)
|
||||
engine_fon = create_engine('postgresql+psycopg2://{0}:{1}@{2}:{3}/{4}'.format(user_fon,pwd_fon,adr_fon,port_fon,base_fon), echo=False)
|
||||
con_cad = engine_cad.connect()
|
||||
con_fon = engine_fon.connect()
|
||||
|
||||
|
||||
################################
|
||||
########## Main ##########
|
||||
################################
|
||||
if __name__ == "__main__":
|
||||
################
|
||||
# CORRECTION DUPLICATES TABLE_IN
|
||||
################
|
||||
if check_duplicates:
|
||||
for DOUBLON in FIND_DOUBLON:
|
||||
tab = DOUBLON['tab_in']
|
||||
on_col = DOUBLON['on_col']
|
||||
for col in on_col:
|
||||
for dep in list_dep:
|
||||
schema_in = dep + '_' + schema_cad
|
||||
sql = '''
|
||||
-- il existe des doublons en raison d'orthographes voisines :
|
||||
-- recherche de ces doublons
|
||||
SELECT DISTINCT '{0}' as insee_dep, dnuper, string_agg(DISTINCT {1},' / ') as orthographes_voisines
|
||||
FROM "{2}".{3} GROUP BY dnuper HAVING count(DISTINCT {1}) > 1'''.format(dep, col, schema_in, tab)
|
||||
df = pd.read_sql(
|
||||
sql = sql,
|
||||
con = engine_cad,
|
||||
)
|
||||
if df.empty:
|
||||
print('No duplicate value dep {0} table {1} column {2} ====> next request'.format(dep, tab, col))
|
||||
continue
|
||||
|
||||
for i, row in df.iterrows():
|
||||
dnuper = row.dnuper
|
||||
choix = row.orthographes_voisines.split(' / ')
|
||||
choix = [i.strip() for i in choix]
|
||||
Question = input("""Des orthographes voisines existent pour l'identifiant : {0}
|
||||
dans la colonne : {1}.
|
||||
Les valeurs voisines sont : {2}
|
||||
Ecrire la mise à jour du champs {1} à enregistrer (c cancel) :""".format(dnuper,col, choix))
|
||||
if Question.lower() == 'c' or Question.lower() == 'cancel':
|
||||
continue
|
||||
|
||||
update = '''UPDATE "{0}".{1}
|
||||
SET {2} = '{3}'
|
||||
WHERE {2} like '{4}%'
|
||||
AND dnuper = '{5}';'''.format(schema_in, tab, col, Question, "%' OR {} like '".format(col).join(map(str,choix)), dnuper)
|
||||
try:
|
||||
con_cad.execute(text(update))
|
||||
print('''
|
||||
Update OK !''')
|
||||
except Exception as exept:
|
||||
print('ERROR : {0}'.format(update))
|
||||
print(exept)
|
||||
sys.exit()
|
||||
|
||||
|
||||
|
||||
################
|
||||
# TRUNCATE TABLE OUT
|
||||
################
|
||||
if not debug:
|
||||
for i, DICT in enumerate(DICT_TAB):
|
||||
tab_in = DICT_TAB[i]['table_in']
|
||||
col_in = DICT_TAB[i]['columns_in']
|
||||
ind_in = DICT_TAB[i]['index_tab']
|
||||
tabs_out = DICT_TAB[i]['table_out']
|
||||
|
||||
for tab_out in reversed(tabs_out):
|
||||
sql = "TRUNCATE TABLE {0}.{1} CASCADE".format(schema_fon, tab_out['name'])
|
||||
print(sql)
|
||||
con_fon.execute(sql)
|
||||
|
||||
|
||||
|
||||
################
|
||||
# IMPORT IN TABLE OUT
|
||||
################
|
||||
for dep in list_dep:
|
||||
schema_in = dep + '_' + schema_cad
|
||||
print('''
|
||||
|
||||
INIT import data FROM {}
|
||||
|
||||
'''.format(schema_in))
|
||||
for i, DICT in enumerate(DICT_TAB):
|
||||
tab_in = DICT_TAB[i]['table_in']
|
||||
col_in = DICT_TAB[i]['columns_in']
|
||||
ind_in = DICT_TAB[i]['index_tab']
|
||||
tabs_out = DICT_TAB[i]['table_out']
|
||||
|
||||
# Import data
|
||||
print('''
|
||||
INIT import data FROM {0}........... {1} sec'''.format(tab_in, time_exec(start_time) ))
|
||||
tmp = pd.read_sql_table(
|
||||
table_name = tab_in,
|
||||
con = engine_cad,
|
||||
schema = schema_in,
|
||||
columns = col_in + [ind_in],
|
||||
chunksize = chunk,
|
||||
)
|
||||
|
||||
# Mise en forme des données
|
||||
if chunk:
|
||||
DF = pd.concat(tmp, ignore_index=True)
|
||||
else:
|
||||
DF = tmp.copy()
|
||||
|
||||
DF.drop_duplicates(inplace=True)
|
||||
del tmp
|
||||
DF.set_index(ind_in, inplace=True)
|
||||
print('END import data ........... %s sec'%( time_exec(start_time) ))
|
||||
|
||||
for tab in tabs_out:
|
||||
tab_out = tab['name']
|
||||
dictio = tab['dict']
|
||||
col_df = tab['columns_in']
|
||||
col_ad = tab['columns_add']
|
||||
get_geo = tab['geom']
|
||||
drp_esc = tab['drop_escape']
|
||||
unique = tab['unique']
|
||||
join = tab['join']
|
||||
|
||||
print('INIT TABLE {0} ........... {1} sec'.format(tab_out, time_exec(start_time) ))
|
||||
df = DF[DF.columns.intersection(col_df)].copy()
|
||||
|
||||
|
||||
# Remplacement des espaces dans les chaines de caractères par des 0
|
||||
df = replace_escape_by_0(df)
|
||||
if drp_esc:
|
||||
df_obj = df.select_dtypes(['object'])
|
||||
df[df_obj.columns] = df_obj.apply(lambda x: x.str.strip())
|
||||
|
||||
if dictio :
|
||||
df.rename(columns=dictio, inplace=True)
|
||||
|
||||
if join :
|
||||
for j in join:
|
||||
if j['bdd'] == 'in' :
|
||||
df = join_data(df, j, schema_in)
|
||||
if df.empty:
|
||||
print('df EMPTY ====> next table')
|
||||
continue
|
||||
|
||||
# Ajout des champs additionnels
|
||||
if col_ad :
|
||||
print('INIT addition columns ........... %s sec'%( time_exec(start_time) ))
|
||||
for key in col_ad.keys():
|
||||
if key in df.columns:
|
||||
df[key + '_tmp'] = df[key].copy()
|
||||
col_ad[key] = [x if x != key else key+'_tmp' for x in col_ad[key]]
|
||||
|
||||
aggreg = col_ad[key]
|
||||
if aggreg :
|
||||
df[key] = ''
|
||||
for col in aggreg:
|
||||
df[key] += df[col].fillna('')
|
||||
else:
|
||||
df[key] = aggreg
|
||||
|
||||
print('ADD column {0} : {1} ........... {2} sec'.format(key,aggreg, time_exec(start_time) ))
|
||||
|
||||
if tab_out == 'proprios%s'%sufx_nom_tab:
|
||||
add = pd.DataFrame(data={'dnuper': ['%sY99999'%dep], 'ddenom': ['PROPRIETAIRES NON RENSEIGNES']})
|
||||
df = pd.concat([df,add])
|
||||
|
||||
# JOINTURE
|
||||
if join :
|
||||
for j in join:
|
||||
if j['bdd'] == 'out' :
|
||||
df = join_data(df, j, schema_in)
|
||||
if df.empty:
|
||||
print('df EMPTY ====> next table')
|
||||
continue
|
||||
|
||||
if unique:
|
||||
df.drop_duplicates(unique['cols'], keep=unique['keep'], inplace=True)
|
||||
|
||||
# Conservation des champs utiles à l'insertion en bdd
|
||||
name_col_out = engine_fon.dialect.get_columns(engine_fon, tab_out, schema=schema_fon)
|
||||
name_col_out = [ sub['name'] for sub in name_col_out ]
|
||||
if 'geom' in name_col_out and 'geom' not in df.columns:
|
||||
name_col_out.remove('geom')
|
||||
df = df[df.columns.intersection(name_col_out)]
|
||||
|
||||
####################
|
||||
# Read geodataframe
|
||||
# Dans le cas où un champs géometrique est nécessaire.
|
||||
if get_geo:
|
||||
get_geom_parcelle(df=df, get_geo=get_geo, schema=schema_in)
|
||||
else:
|
||||
export_data(df)
|
||||
# del df
|
||||
|
||||
# Si insertion de données dans r_prop_cptprop,
|
||||
# attribution d'un compte 'PROPRIETAIRES NON RENSEIGNES' au cptprop sans proprio
|
||||
if tab_out == 'r_prop_cptprop%s'%sufx_nom_tab:
|
||||
print('''ATTRIBUTION d'un compte 'PROPRIETAIRES NON RENSEIGNES' au cptprop sans proprio''')
|
||||
df = pd.read_sql_table(
|
||||
con = engine_fon,
|
||||
table_name = 'cptprop%s'%sufx_nom_tab,
|
||||
schema = schema_fon,
|
||||
columns = ['dnupro'] )
|
||||
tmp = pd.read_sql_table(
|
||||
con = engine_fon,
|
||||
table_name = 'r_prop_cptprop%s'%sufx_nom_tab,
|
||||
schema = schema_fon,
|
||||
columns = ['dnupro'] )
|
||||
df = df[~df.dnupro.isin(tmp.dnupro)]
|
||||
if df.empty:
|
||||
print('TOUS les propriétaires sont renseignés ===> NEXT !')
|
||||
continue
|
||||
df['dnuper'] = '%sY99999'%dep
|
||||
export_data(df)
|
||||
del df
|
||||
del DF
|
||||
|
||||
|
||||
print('END transfert data FROM département {0} ........... {1} sec'.format(dep, time_exec(start_time) ))
|
||||
print('END SCRIPT')
|
||||
Reference in New Issue
Block a user