"""MUNI-1 (b) · lectura ciega · originales por caso (pre-registro §4). Sin red, etl:v2 (run_etl.sh, MEM=3g). Lee priv/sel.json; escribe priv/orig/_/{dir3_eell.tsv, pmp_2025.tsv, atom/...} y priv/orig/indice.json.""" import collections, csv, glob, gzip, hashlib, json, os, re, sys, time, zipfile from pathlib import Path sys.path.insert(0, '/code'); os.umask(0o077) import duckdb from etl.v2.entes import leer_xlsx W = Path('/w/priv'); O = W / 'orig'; O.mkdir(parents=True, exist_ok=True) sel = json.load(open(W / 'sel.json', encoding='utf-8'))['casos'] norm = lambda v: re.sub(r'[\s-]', '', (v or '')).upper() nom = lambda v: re.sub(r'\s+', ' ', (v or '').strip().upper()) idx = {} # DIR3 hojas = leer_xlsx(Path('/r/dir3/Unidades_EELL.xlsx')) cab = filas = None for n, fs in hojas: for i, f in enumerate(fs[:20]): if 'C_ID_UD_ORGANICA' in f: cab, filas = f, fs[i + 1:]; break if cab: break assert cab quedan = [j for j, c in enumerate(cab) if 'CONTACT' not in c.upper()] ci = {c: j for j, c in enumerate(cab)} COD, NIF, TIPO, NIV = ci['C_ID_UD_ORGANICA'], ci['NIF_CIF'], ci['C_ID_TIPO_ENT_PUBLICA'], ci['N_NIVEL_JERARQUICO'] print('dir3 filas', len(filas), flush=True) # PMP: provincias del CSV y filas de los 4 trimestres de 2025 prov = {} with gzip.open('/code/app/datos/pmp_entidad_anio.csv.gz', 'rt', encoding='utf-8', newline='') as f: for r in csv.DictReader(f): if r['anio'] == '2025': prov[r['nif']] = r['provincia'] qs = [(1, 'eell_2025_03'), (2, 'eell_2025_06'), (3, 'eell_2025_09'), (4, 'eell_2025_12')] pmp_rows = {} cabs_pmp = {} for tr, f in qs: p = Path(f'/p/{f}.xlsx') if not p.exists(): print('falta', p); continue hj = dict(leer_xlsx(p)) for hoja in ('Cesión', 'Cesion', 'Variables'): if hoja not in hj: continue rows = hj[hoja] h = next((i for i, r in enumerate(rows[:20]) if len(r) > 1 and r[1] == 'Comunidad Autónoma'), None) if h is None: continue c = [str(x) if x is not None else '' for x in rows[h]] cabs_pmp[hoja] = c for r in rows[h + 1:]: r = (list(r) + [None] * 12)[:len(c) if len(c) > 11 else 12] pmp_rows.setdefault((tr, hoja), []).append(r) print('hojas pmp', sorted({(t, h) for t, h in pmp_rows}), flush=True) def buscar_pmp(ent, provincia): n = nom(ent); pv = nom(provincia) out = [] for (tr, hoja), rows in pmp_rows.items(): cand = [r for r in rows if nom(str(r[5]) if len(r) > 5 else '') == n and (not pv or pv in nom(str(r[2])))] for r in cand: out.append((tr, hoja, r)) return out # Casos por_clave = collections.defaultdict(list) # para ATOM for c in sel: d = O / f"{c['lista']}_{c['ine']}"; d.mkdir(parents=True, exist_ok=True) fi = idx[f"{c['lista']}_{c['ine']}"] = {'dir': d.name} raiz = [f for f in filas if f[COD].startswith('L01' + c['ine']) and f[TIPO] == 'AY' and f[NIV] == '1'] with open(d / 'dir3_eell.tsv', 'w', encoding='utf-8', newline='') as fh: w = csv.writer(fh, delimiter='\t'); w.writerow(['por_que_esta_fila'] + [cab[j] for j in quedan]) for f in raiz: w.writerow(['unidad raíz del ayuntamiento del municipio de la afirmación (código L01 + su código INE)'] + [f[j] if j < len(f) else '' for j in quedan]) fi['raiz'] = len(raiz) if c['lista'] == 'pmp': filas_p = buscar_pmp(c['medida']['entidad'], prov.get(c['nif'])) with open(d / 'pmp_2025.tsv', 'w', encoding='utf-8', newline='') as fh: w = csv.writer(fh, delimiter='\t') cols = max((len(cabs_pmp.get(h) or []) for _, h, _ in filas_p), default=12) w.writerow(['trimestre_2025', 'hoja'] + list(next(iter(cabs_pmp.values())))[:cols]) for tr, hoja, r in sorted(filas_p, key=lambda x: (x[0], x[1])): w.writerow([tr, hoja] + ['' if x is None else x for x in r[:cols]]) fi['pmp_filas'] = len(filas_p); fi['pmp_trimestres'] = sorted({t for t, _, _ in filas_p}) else: lid = c['contrato']['id_canonical'] t = lid.split(':', 1)[1] if lid.startswith('PLACSP:') else lid t = t.split('|')[0]; a, b = t.split('/')[-2:]; k = a.split(':')[-1] + '/' + b por_clave[k].append(f"{c['lista']}_{c['ine']}"); fi['clave'] = k print('casos', len(idx), flush=True) # ATOM (como muni1 91_originales.py) con = duckdb.connect(); con.execute("SET threads=2; SET memory_limit='1200MB'") arch = con.execute("""SELECT DISTINCT regexp_extract(id,'[^/]+/[^/]+$') k, archivo_origen, conjunto FROM read_parquet('/n/salida/licitaciones_completo_2012_2026.parquet') WHERE regexp_extract(id,'[^/]+/[^/]+$') IN (SELECT unnest(?))""", [sorted(por_clave)]).fetchall() por_zip = collections.defaultdict(set); sin = [] for k, z, conj in arch: for p in (f'/n/zips/{conj}/{z}', f'/n/zips/{conj}/_historico/{z}'): if os.path.exists(p): por_zip[p].add(k); break else: sin.append((k, z)) print('claves', len(por_clave), 'zips', len(por_zip), 'sin', sin[:5], flush=True) RE_ID = re.compile(rb'https?://contratacion(?:delestado\.es|delsectorpublico\.gob\.es)/sindicacion/([^<]+)') RE_UPD = re.compile(rb'([^<]+)') ver = collections.defaultdict(dict) for zp, cl in sorted(por_zip.items()): with zipfile.ZipFile(zp) as z: for n in z.namelist(): if not n.endswith('.atom') and not n.endswith('.xml'): continue b = z.read(n) for ent in re.split(rb'(?=])', b): if not ent.startswith(b'') if fin < 0: continue ent = ent[:fin + 8] m = RE_ID.search(ent) if not m: continue k = '/'.join(m.group(1).decode().split('/')[-2:]) if k in cl: upd = RE_UPD.search(ent) u = upd.group(1).decode() if upd else f'sin_fecha_{len(ver[k])}' ver[k].setdefault(u, (ent, n)) print(zp, len(ver), flush=True) for k, lista in por_clave.items(): for caso in lista: d = O / caso / 'atom'; d.mkdir(parents=True, exist_ok=True) vs = [] for u, (ent, n) in sorted(ver.get(k, {}).items()): fn = re.sub(r'[^0-9A-Za-z.-]', '_', u) + '.xml' (d / fn).write_bytes(ent) vs.append({'fichero': fn, 'updated': u, 'origen': n}) idx[caso]['atom'] = vs json.dump(idx, open(O / 'indice.json', 'w', encoding='utf-8'), ensure_ascii=False, indent=1) print('sin atom', [c for c, v in idx.items() if v.get('atom') == []]) print('pmp filas', collections.Counter(v.get('pmp_filas') for v in idx.values() if 'pmp_filas' in v))