"""PG1 · 10 · unidades (§2) y hashes (§3): ceses y nombramientos de altos cargos (BOE, Aragón, Cataluña), autorizaciones OCI y placebos N4. Escribe interno/10_unidades.parquet (con nombre: interno 700) y interno/10_hashes.txt.""" import sys, json, re, csv, random, datetime; sys.path.insert(0, '/w/py') from comun import * import duckdb MES = {m: i for i, m in enumerate('enero febrero marzo abril mayo junio julio agosto septiembre octubre noviembre diciembre'.split(), 1)} def fecha_disp(tit, fpub): m = re.search(r', de (\d{1,2}) de (enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre)(?: de (\d{4}))?[,.]', tit) if not m: return fpub, 'pub' d, mes = int(m.group(1)), MES[m.group(2)] y = int(m.group(3)) if m.group(3) else (fpub.year if mes <= fpub.month else fpub.year - 1) try: return datetime.date(y, mes, d), 'disp' except ValueError: return fpub, 'pub' RANGO = {k: i for i, k in enumerate(PRIM_CLASES)} c = duckdb.connect(); U = [] # --- BOE (AGE) for (bid, fpub, dep, tipo, tit, nom, cargo, cl) in c.execute("SELECT id, fecha_pub, departamento, tipo, titulo, nombre, cargo, clase FROM '/w/interno/00_boe.parquet' WHERE nombre IS NOT NULL").fetchall(): f, via = fecha_disp(tit, fpub) t = 'cese' if tipo == 'cese' else 'nombramiento' U.append(dict(fuente='BOE', id=bid, tipo=t, fecha=f, fecha_via=via, clase=cl, cargo=cargo, dep=dep, ambito=carteras(dep), nombre=nom, cad=sorted(cadenas_boe(nom, 2)), cad1=sorted(cadenas_boe(nom, 1) - cadenas_boe(nom, 2)))) # --- Aragón (BOA) raw = open('/w/interno/datos/ccaa/aragon/boa_altos_cargos.json', 'rb').read() try: s = raw.decode('utf-8') except UnicodeDecodeError: s = raw.decode('latin-1') DON = r'(?:don|doña|D\.ª|Dª|D\.|Dña\.?)' for r in json.loads(s, strict=False): tit = re.sub(r'\s+', ' ', r['Titulo']); f = datetime.date(int(r['Fechadisposicion'][:4]), int(r['Fechadisposicion'][4:6]), int(r['Fechadisposicion'][6:8])) if re.search(r'\bcese\b', tit): m = re.search(r'cese,?\s+(?:de\s+)?' + DON + r'\s+(?P[^,]+?),?\s+como\s+(?P.+?)(?:,| del anterior| en el anterior|\.|$)', tit); t = 'cese' else: m = re.search(r'se nombra\s+(?:a\s+' + DON + r'\s+(?P[^,]+?),\s+|)(?P.+?)\s+(?:a\s+' + DON + r'\s+(?P[^,.]+)|$)', tit); t = 'nombramiento' if not m: continue nom = (m.groupdict().get('nom') or m.groupdict().get('nom2') or '').strip(' .') cargo = m.group('cargo').strip(' ,.') if not nom or re.search(r'\b(y|e)\s+' + DON, tit[m.start():]): continue cg = sa(cargo).lower() if re.match(r'consejer[oa] de\b|vicepresident[ea]|president[ea] del gobierno de aragon', cg): cl = 'ministro' elif re.match(r'secretari[oa] general', cg): cl = 'secretario_general' elif re.match(r'director[a]? general', cg): cl = 'director_general' elif re.match(r'(director[a]?( gerente)?|gerente|president[ea]|director[a]? ejecutiv[oa]) (de|del)', cg) and not re.search(r'gabinete', cg): cl = 'presidente_director_organismo' else: cl = 'otro' U.append(dict(fuente='BOA', id=r['DOCN'], tipo=t, fecha=f, fecha_via='disp', clase=cl, cargo=cargo, dep=r['Emisor'], ambito=['CCAA:Aragón'], nombre=nom, cad=sorted(cadenas_boe(nom, 2)), cad1=sorted(cadenas_boe(nom, 1) - cadenas_boe(nom, 2)))) # --- Cataluña (consellers) def dmy(z): try: d, m, y = z.strip().split('/'); return datetime.date(int(y), int(m), int(d)) except Exception: return None for i, r in enumerate(csv.DictReader(open('/w/interno/datos/ccaa/cat/ej77-hz8x_titulars_conselleries.csv', encoding='utf-8'))): a1, a2, nm = r['Primer cognom'].strip(), r['Segon cognom'].strip(), r['Nom'].strip() cad = sorted({re.sub(r'\s+', ' ', limpia(f'{a1} {a2} {nm}'))}) if a1 and a2 else [] for t, fz in (('nombramiento', dmy(r["Data inici de l'ocupació"])), ('cese', dmy(r["Data fi de l'ocupació"]))): if fz: U.append(dict(fuente='CAT', id=f'cat{i}', tipo=t, fecha=fz, fecha_via='disp', clase='ministro', cargo=r['Nomenclatura del càrrec'], dep='Generalitat de Catalunya', ambito=['CCAA:Cataluña'], nombre=f'{nm} {a1} {a2}', cad=cad, cad1=[])) # --- OCI for i, r in enumerate(csv.DictReader(open('/w/interno/datos/oci/autorizaciones_oci.csv', encoding='utf-8'))): fz = dmy(r['Fecha de cese'] or '') U.append(dict(fuente='OCI', id=f'oci{i}', tipo='oci', fecha=fz, fecha_via='oci', clase=None, cargo=r['Alto cargo'], dep=r['Ministerio'], ambito=carteras(r['Ministerio']), nombre=r['Nombre'], cad=sorted(cadenas_oci(r['Nombre'])), cad1=[], actividad=r['Empresa / Atividad autorizada'], fecha_aut=str(dmy(r['Fecha de autorización'] or '')))) for u in U: u['hashes'] = hashes(u['cad']); u['hashes1'] = sorted(set(hashes(u['cad1'])) - set(u['hashes'])) u['pkey'] = ' '.join(sa(limpia(u['cad'][0] if u['cad'] else u['nombre'])).split()) if (u['cad'] or u['nombre']) else None u.setdefault('actividad', None); u.setdefault('fecha_aut', None) # --- unidades primarias for u in U: u['primaria_salida'] = (u['tipo'] == 'cese' and u['clase'] in PRIM_CLASES and bool(u['ambito']) and u['fecha'] is not None and datetime.date(2012, 1, 1) <= u['fecha'] <= datetime.date(2024, 12, 31) and bool(u['hashes'])) u['primaria_entrada'] = (u['tipo'] == 'nombramiento' and u['clase'] in PRIM_CLASES and bool(u['ambito']) and u['fecha'] is not None and datetime.date(2011, 1, 1) <= u['fecha'] <= datetime.date(2024, 12, 31) and bool(u['hashes'])) # dedupe: mismo nombre y misma fecha (cese) -> la de mayor rango for flag in ('primaria_salida', 'primaria_entrada'): best = {} for j, u in enumerate(U): if not u[flag]: continue k = (u['fuente'] in ('BOE',), u['pkey'], u['fecha']) if k not in best or RANGO[u['clase']] < RANGO[U[best[k]]['clase']]: best[k] = j keep = set(best.values()) for j, u in enumerate(U): if u[flag] and j not in keep: u[flag] = False; u[flag + '_dup'] = True # --- N4: catedráticos y profesores titulares nombrados en el BOE (clase otro) prof = [j for j, u in enumerate(U) if u['fuente'] == 'BOE' and u['tipo'] == 'nombramiento' and u['clase'] == 'otro' and u['cargo'] and re.match(r'(catedratic[oa]|profesor[a]? titular)', sa(u['cargo']).lower()) and u['hashes']] for j in prof: U[j]['n4'] = True for j, u in enumerate(U): u['uid'] = f'u{j:06d}' cols = ['uid', 'fuente', 'id', 'tipo', 'fecha', 'fecha_via', 'clase', 'cargo', 'dep', 'ambito', 'nombre', 'pkey', 'cad', 'hashes', 'hashes1', 'primaria_salida', 'primaria_entrada', 'actividad', 'fecha_aut'] c.execute("CREATE TABLE u (uid VARCHAR, fuente VARCHAR, id VARCHAR, tipo VARCHAR, fecha DATE, fecha_via VARCHAR, clase VARCHAR, cargo VARCHAR, dep VARCHAR, ambito VARCHAR[], nombre VARCHAR, pkey VARCHAR, cad VARCHAR[], hashes VARCHAR[], hashes1 VARCHAR[], primaria_salida BOOLEAN, primaria_entrada BOOLEAN, actividad VARCHAR, fecha_aut VARCHAR, n4 BOOLEAN)") c.executemany("INSERT INTO u VALUES (" + ",".join("?" * 20) + ")", [[u.get(k) for k in cols] + [bool(u.get('n4'))] for u in U]) c.execute("COPY u TO '/w/interno/10_unidades.parquet'") c.execute("COPY (SELECT DISTINCT h FROM (SELECT unnest(hashes) h FROM u UNION ALL SELECT unnest(hashes1) FROM u) WHERE h IS NOT NULL ORDER BY 1) TO '/w/interno/10_hashes.txt' (HEADER false)") R = {'unidades': c.execute("SELECT fuente, tipo, count(*), count(*) FILTER (WHERE primaria_salida), count(*) FILTER (WHERE primaria_entrada), count(*) FILTER (WHERE n4) FROM u GROUP BY 1, 2 ORDER BY 1, 2").fetchall(), 'salida_por_clase': c.execute("SELECT fuente, clase, count(*) FROM u WHERE primaria_salida GROUP BY 1, 2 ORDER BY 1, 3 DESC").fetchall(), 'salida_por_anio': c.execute("SELECT year(fecha), count(*), count(DISTINCT pkey) FROM u WHERE primaria_salida GROUP BY 1 ORDER BY 1").fetchall(), 'entrada_por_anio': c.execute("SELECT year(fecha), count(*) FROM u WHERE primaria_entrada GROUP BY 1 ORDER BY 1").fetchall(), 'fecha_via': c.execute("SELECT fecha_via, count(*) FROM u WHERE primaria_salida GROUP BY 1").fetchall(), 'hashes_distintos': c.execute("SELECT count(DISTINCT h) FROM (SELECT unnest(hashes) h FROM u UNION ALL SELECT unnest(hashes1) FROM u)").fetchone()[0], 'cadenas_por_unidad_salida': c.execute("SELECT len(cad), count(*) FROM u WHERE primaria_salida GROUP BY 1 ORDER BY 1").fetchall()} json.dump(R, open('/w/salidas/10_unidades.json', 'w'), indent=1, default=str, ensure_ascii=False); print(json.dumps(R, default=str, ensure_ascii=False))