"""MUNI-1 · A2 · segunda implementación de la tabla MUN-MAP: pyarrow + Python, sin DuckDB ni el SQL ni las funciones del módulo (etl/organo_municipio.py); mismas entradas (identidad publicada y padrón de app/datos). Escribe tmp/mapa_om_b.parquet y compara con tmp/mapa_om.parquet (la del módulo) → salidas/10_segunda.json.""" import csv, json, re, unicodedata, collections, sys import pyarrow.parquet as pq import pyarrow as pa I = '/d/unified_20261103.identidad/' PAD = '/code/app/datos/padron_municipios_2019_2025.csv' def leer(f, cols): t = pq.read_table(I + f, columns=cols) return t.to_pylist() def nz(s): s = unicodedata.normalize('NFD', s or '') s = ''.join(ch for ch in s if unicodedata.category(ch) != 'Mn').lower() out = [] for ch in s: out.append(ch if ch.isalnum() else ' ') return ' '.join(''.join(out).split()) # Padrón: formas del nombre → INE formas = collections.defaultdict(set) with open(PAD, encoding='utf-8') as f: for r in csv.DictReader(f): nombre, ine = r['municipio'], r['ine'] vs = {nz(nombre)} for parte in nombre.split('/'): if ', ' in parte: base, art = parte.split(', ', 1) else: base, art = parte, '' vs.add(nz(base)) if art: vs.add(nz(art + ' ' + base)) for v in vs: if v: formas[v].add(ine) ines_pad = set().union(*formas.values()) HON = {'excmo', 'excma', 'excm', 'exmo', 'ilmo', 'ilma', 'ilustre', 'ilustrisimo', 'excelentisimo'} HON2 = [('il', 'lustre'), ('il', 'lustrisim'), ('excel', 'lentissim'), ('muy', 'ilustre'), ('m', 'i')] HON3 = [('molt', 'il', 'lustre')] ENT = {'ayuntamiento', 'ajuntament', 'ajuntaments', 'concello', 'ayto', 'udala'} ENL = {('de', 'la'): 'la', ('de', 'las'): 'las', ('de', 'los'): 'los', ('de', 'les'): 'les', ('del',): 'el', ('dels',): 'els', ('de', 'l'): 'l', ('des',): 'es', ('de',): None, ('d',): None, ('da',): 'a', ('do',): 'o', ('dos',): 'os', ('das',): 'as'} def muni_nombre(nombre): w = nz(nombre).split() if not w: return None cand = [] i = 0 while True: # honoríficos delante if i + 3 <= len(w) and tuple(w[i:i + 3]) in HON3: i += 3; continue if i + 2 <= len(w) and tuple(w[i:i + 2]) in HON2: i += 2; continue if i < len(w) and w[i] in HON: i += 1; continue break if i < len(w) - 1 and w[i] in ENT: resto = w[i + 1:] cand.append(' '.join(resto)) for e, art in ENL.items(): k = len(e) if len(resto) > k and tuple(resto[:k]) == e: sin = resto[k:] cand.append(' '.join(sin)) if art: cand.append(art + ' ' + ' '.join(sin)) if len(w) >= 2 and w[-1] == 'udala': b = ' '.join(w[:-1]) cand.append(b) for s in ('eko', 'ko', 'go'): if b.endswith(s) and len(b) > len(s) + 2: cand.append(b[:-len(s)]) hits = set() for c in cand: hits |= formas.get(c, set()) return next(iter(hits)) if len(hits) == 1 else None MARCA = re.compile(r'\b(ayuntamiento|ajuntament|concello|conello|ayto)\b') VILLA = re.compile(r'^(?:la |el )?(?:muy noble y leal |noble |real )?(?:villa|ciudad)(?: y puerto)? de (.+)$') def muni_unidad(nombre): """N2 (enmienda 1), escrito aparte: lo que sigue a la última marca, sin enlace ni paréntesis, de un solo municipio.""" sin_par = re.sub(r'\([^)]*\)', ' ', nombre or '') n = nz(sin_par) ms = list(MARCA.finditer(n)) if not ms: return None resto = n[ms[-1].end():].strip() lista = [] w = resto.split(' ') if len(w) >= 2 and w[0] in ('de', 'del', 'd', 'do', 'da', 'dels', 'des'): sin = ' '.join(w[1:]) lista.append(sin) art = {'del': 'el', 'dels': 'els', 'des': 'es', 'do': 'o', 'da': 'a'}.get(w[0]) if art: lista.append(art + ' ' + sin) lista.append(resto) for y in list(lista): v = VILLA.match(y) if v: lista.append(v.group(1)) if n.endswith(' udala'): b = n[:-len(' udala')].strip() lista.append(b) for suf in ('eko', 'ko', 'go'): if b.endswith(suf) and len(b) > len(suf) + 2: lista.append(b[:-len(suf)]) vistos = [] for y in lista: y = y.strip() if y and y not in vistos: vistos.append(y) for y in vistos: if y == n: continue h = formas.get(y) if h and len(h) == 1: return next(iter(h)) return None def nifn(v): if v is None: return None v = str(v).strip().replace('-', '').replace(' ', '').upper() return v or None # DIR3 raíz de ayuntamientos d3 = {}; nifm = {}; nifrep = set() for r in leer('dir3_unidades.parquet', ['codigo', 'listado', 'tipo_ent', 'nivel_jer', 'nif']): c = r['codigo'] or '' if r['listado'] == 'EELL' and r['tipo_ent'] == 'AY' and r['nivel_jer'] == '1' and c.startswith('L01'): ine = c[3:8] if ine in ines_pad: d3[c] = ine n = nifn(r['nif']) if n: if n in nifm and nifm[n] != ine: nifrep.add(n) nifm.setdefault(n, ine) for n in nifrep: nifm.pop(n, None) # INVENTE (matriz ayuntamiento, unanimidad) vot = collections.defaultdict(set) for r in leer('entes.parquet', ['matriz_nif', 'matriz_tipo', 'municipio_ine']): if r['matriz_tipo'] == 'ayuntamiento' and r['matriz_nif'] and r['municipio_ine']: vot[nifn(r['matriz_nif'])].add(r['municipio_ine']) inv = {n: next(iter(s)) for n, s in vot.items() if n and len(s) == 1 and next(iter(s)) in ines_pad and n not in nifm} tipo = {r['organo_clave']: r['tipo'] for r in leer('organos_tipo.parquet', ['organo_clave', 'tipo'])} orgs = [r for r in leer('organos.parquet', ['organo_clave', 'nombre', 'dir3_oficial', 'nif_oficial', 'entidad_clave']) if tipo.get(r['organo_clave']) in ('ayuntamiento', 'empresa_fundacion_consorcio')] claves = {r['organo_clave'] for r in orgs} sd = collections.defaultdict(collections.Counter); sn = collections.defaultdict(collections.Counter) filas = leer('organos_filas.parquet', ['organo_clave', 'organo_nif', 'organo_nif_inferido', 'dir3', 'dir3_propagado', 'filas']) filas += [dict(r, organo_nif_inferido=None, dir3_propagado=None) for r in leer('organos_filas_ccaa.parquet', ['organo_clave', 'organo_nif', 'dir3', 'filas'])] for r in filas: k = r['organo_clave'] if k not in claves: continue d = r['dir3'] if r['dir3'] is not None else r['dir3_propagado'] n = r['organo_nif'] if r['organo_nif'] is not None else r['organo_nif_inferido'] if d is not None: sd[k][d] += r['filas'] or 0 if n is not None: sn[k][n] += r['filas'] or 0 def mejor(cnt): if not cnt: return None return sorted(cnt.items(), key=lambda kv: (-kv[1], kv[0]))[0][0] rx_nif = re.compile(r'^[A-Z][0-9]{7}[0-9A-Z]$') out = []; conf = [] for r in orgs: k = r['organo_clave'] dir3 = r['dir3_oficial'] if r['dir3_oficial'] is not None else mejor(sd.get(k)) if r['nif_oficial'] is not None and nifn(r['nif_oficial']): nif = nifn(r['nif_oficial']) elif r['entidad_clave'] and rx_nif.match(r['entidad_clave']): nif = r['entidad_clave'] else: nif = nifn(mejor(sn.get(k))) md = d3.get((dir3 or '').strip().upper()) mf = nifm.get(nif or '') or inv.get(nif or '') mn = muni_nombre(r['nombre']) if mn: out.append((k, mn, 'nombre')) elif md and mf and md != mf: conf.append(k) elif md: out.append((k, md, 'dir3')) elif mf: out.append((k, mf, 'nif_raiz')) else: mu = muni_unidad(r['nombre']) if mu: out.append((k, mu, 'nombre_unidad')) pq.write_table(pa.table({'organo_clave': [o[0] for o in out], 'municipio_ine': [o[1] for o in out], 'via': [o[2] for o in out]}), '/w/tmp/mapa_om_b.parquet') a = {(r['organo_clave']): (r['municipio_ine'], r['via']) for r in pq.read_table('/w/tmp/mapa_om.parquet').to_pylist()} b = {o[0]: (o[1], o[2]) for o in out} ca = {r['organo_clave'] for r in pq.read_table('/w/tmp/mapa_om_conflictos.parquet').to_pylist()} dif = [(k, a.get(k), b.get(k)) for k in sorted(set(a) | set(b)) if a.get(k) != b.get(k)] R = {'organos': len(orgs), 'filas_a': len(a), 'filas_b': len(b), 'diferencias': len(dif), 'ejemplos': dif[:20], 'conflictos_a': len(ca), 'conflictos_b': len(conf), 'conflictos_distintos': len(ca ^ set(conf)), 'por_via_b': dict(collections.Counter(o[2] for o in out)), 'pasa': not dif and ca == set(conf)} json.dump(R, open('/w/salidas/10_segunda.json', 'w'), indent=1, ensure_ascii=False) print(json.dumps(R, ensure_ascii=False))