"""FUENTES-A-LA-CADENA (13-nov-2026) · COPIA de ficha360/b/py/segunda.py (md5 d20526a258312fb2fe8d0bf8fadbb2a6) que solo AÑADE las noches del refresco incremental de la BDNS (argv[4]: la carpeta bdns; /nuevas_pj.jsonl.gz con fecha de concesión ≥ 2022) y quita las retiradas (/retiradas.tsv, por id) de las concesiones. Pre-registro INC (ae6754ec…) §2.2. Texto de la copia original: FICHA360-B · segunda implementación (pre-registro §4): Python puro (gzip + json en streaming, pyarrow solo para leer la lista de fichas y escribir/comparar), sin DuckDB. Recalcula la tabla desde los crudos y la compara con vias_empresa_legible.parquet.""" import glob, gzip, json, re, sys, collections import pyarrow.parquet as pq B = "/BDNS" CIF = re.compile(r"^[ABCDEFGHJNPQRSUVW][0-9]{7}[0-9A-J]$") def instr(s): u = (s or "").strip().upper() if u.startswith("SUBVENCI"): return "subvencion" if u in ("PRÉSTAMO", "PRESTAMO"): return "prestamo" if u.startswith("GARANT"): return "garantia" if u == "VENTAJA FISCAL": return "ventaja_fiscal" return "otros" def num(v): if v is None or v == "": return None try: return float(v) except (TypeError, ValueError): return None import pyarrow.dataset as ds # fichas: NIF con alguna fila en unified (la copia de trabajo de la web sale de él) y NIF válido; por otro camino que la principal fichas = set() for rb in ds.dataset(sys.argv[1], format="parquet", partitioning="hive").to_batches(columns=["adjudicatario_nif", "adjudicatario_nif_valid"], batch_size=500000): d = rb.to_pydict() fichas.update(n for n, v in zip(d["adjudicatario_nif"], d["adjudicatario_nif_valid"]) if v and n) INC = sys.argv[4] if len(sys.argv) > 4 else None retiradas = set() for f in (sorted(glob.glob(f"{INC}/2*/retiradas.tsv")) if INC else []): for l in open(f, encoding="utf-8"): p = l.strip().split("\t") if p and p[0].isdigit(): retiradas.add(int(p[0])) vistos = set(); agg = collections.defaultdict(lambda: [0, None, 0.0, False]) def mete(via, cod, fecha, ben, ins, imp, eq, edp, idc=None): if edp: return if via == "concesion" and idc is not None and int(idc) in retiradas: return tok = (ben or "").strip().split(" ")[0].upper() if not CIF.match(tok) or tok[0] not in "ABCDFGHNRUVW": return if (via, cod) in vistos: return vistos.add((via, cod)) if tok not in fichas: return a = agg[(tok, via, instr(ins), int(fecha[:4]))] a[0] += 1 if imp is not None: a[1] = (a[1] or 0.0) + imp if eq is not None: a[2] += eq; a[3] = True for f in sorted(glob.glob(f"{B}/barrido_2022_20261111/paginas/*.json.gz")): for x in json.load(gzip.open(f))["content"]: if str(x.get("fechaConcesion") or "").startswith("2022"): mete("concesion", x.get("codConcesion"), x["fechaConcesion"], x.get("beneficiario"), x.get("instrumento"), num(x.get("importe")), num(x.get("ayudaEquivalente")), False, x.get("id")) def lineas(pat): for f in sorted(glob.glob(pat)): for l in gzip.open(f, "rt"): yield json.loads(l) for x in lineas(f"{B}/concesiones/*/*.jsonl.gz"): if str(x.get("fechaConcesion") or "") >= "2023": mete("concesion", x.get("codConcesion"), x["fechaConcesion"], x.get("beneficiario"), x.get("instrumento"), num(x.get("importe")), num(x.get("ayudaEquivalente")), bool(x.get("_entidad_de_personas")), x.get("id")) for x in (lineas(f"{INC}/2*/nuevas_pj.jsonl.gz") if INC else []): if str(x.get("fechaConcesion") or "") >= "2022": mete("concesion", x.get("codConcesion"), x["fechaConcesion"], x.get("beneficiario"), x.get("instrumento"), num(x.get("importe")), num(x.get("ayudaEquivalente")), bool(x.get("_entidad_de_personas")), x.get("id")) for x in lineas(f"{B}/ayudasestado/*/*.jsonl.gz"): fe = str(x.get("fechaConcesion") or "") if "2016" <= fe < "2022": mete("ayuda_estado", x.get("codConcesion"), fe, x.get("beneficiario"), x.get("instrumento"), num(x.get("importe")), num(x.get("ayudaEquivalente")), bool(x.get("_entidad_de_personas"))) for x in lineas(f"{B}/minimis/*/*.jsonl.gz"): fe = str(x.get("fechaConcesion") or "") if "2016" <= fe < "2022": mete("minimis", x.get("codigoConcesion"), fe, x.get("beneficiario"), x.get("instrumento"), None, num(x.get("ayudaEquivalente")), bool(x.get("_entidad_de_personas"))) uno = {k: v for k, v in agg.items()} t = pq.read_table(sys.argv[2]).to_pydict() dos = {(n, v, i, a): (nn, im, eq) for n, v, i, a, nn, im, eq in zip(t["nif"], t["via"], t["instrumento"], t["anio"], t["n"], t["importe"], t["equivalente"])} dif = {"solo_segunda": 0, "solo_principal": 0, "n": 0, "importe": 0, "equivalente": 0, "ejemplos": []} for k in set(uno) | set(dos): if k not in dos: dif["solo_segunda"] += 1; continue if k not in uno: dif["solo_principal"] += 1; continue a, b = uno[k], dos[k] if a[0] != b[0]: dif["n"] += 1 if (a[1] is None) != (b[1] is None) or (a[1] is not None and abs(a[1] - b[1]) > 0.01): dif["importe"] += 1 if (b[2] is None) != (not a[3]) or (a[3] and abs(a[2] - b[2]) > 0.01): dif["equivalente"] += 1 if len(dif["ejemplos"]) < 5 and (a[0] != b[0]): dif["ejemplos"].append(str(k[1:])) r = {"claves_segunda": len(uno), "claves_principal": len(dos), "codigos_validos_vistos": len(vistos), "retiradas": len(retiradas), "incremental": INC, **dif, "pasa": all(dif[x] == 0 for x in ("solo_segunda", "solo_principal", "n", "importe", "equivalente"))} print(json.dumps(r, ensure_ascii=False)); json.dump(r, open(sys.argv[3], "w"), ensure_ascii=False, indent=1)