"""FUENTES-A-LA-CADENA (13-nov-2026) · COPIA de ficha360/b/py/cotejo.py (md5 0f1678a002ab3dd340978be98b1e2c7c) para el incremental (pre-registro INC ae6754ec… §2.4): 20 sociedades al azar ENTRE LAS QUE GANAN FILAS con el incremental (semilla 20261113; argv[3] = el parquet publicado de antes); el recuento aparte lee además las noches (nuevas_pj.jsonl.gz, fecha de concesión ≥ 2022) y quita las retiradas por id. Texto de la copia original: FICHA360-B · cotejo con la fuente (pre-registro §5): 30 sociedades al azar con filas y 5 sin ninguna (semilla sellada). La salida de la función de la web (app/vias_empresa.construir sobre el Parquet de la web) frente a un recuento aparte de sus filas crudas, localizadas por el CIF en el texto de cada página o línea. Corre en la imagen de la web con el worktree en /app.""" import glob, gzip, json, random, re, sys import duckdb sys.path.insert(0, "/app") from app import vias_empresa as ve B = "/BDNS" SEM = 20261113 INC = "/bdns" ANTES = sys.argv[3] PQ = "/app/app/datos/vias_empresa.parquet" m = json.load(open("/app/app/datos/vias_empresa.json")) con = duckdb.connect() con.execute("ATTACH '/aggregations/web.duckdb' AS w (READ_ONLY)") con_nifs = sorted(r[0] for r in con.execute(f"""SELECT DISTINCT nif FROM (SELECT nif, c, anio, n, importe, equivalente FROM read_parquet('{PQ}') EXCEPT SELECT nif, c, anio, n, importe, equivalente FROM read_parquet('{ANTES}'))""").fetchall()) rnd = random.Random(SEM) con30 = rnd.sample(con_nifs, 20) retiradas = set() for f in sorted(glob.glob(f"{INC}/2*/retiradas.tsv")): for l in open(f, encoding="utf-8"): p = l.strip().split("\t") if p and p[0].isdigit(): retiradas.add(int(p[0])) fichas = con.execute(f"""SELECT DISTINCT adjudicatario_nif FROM w.contratos WHERE adjudicatario_nif_valid AND regexp_matches(adjudicatario_nif, '^[ABCDFGHNRUVW][0-9]{{7}}[0-9A-J]$') AND adjudicatario_nif NOT IN (SELECT DISTINCT nif FROM read_parquet('{PQ}')) ORDER BY 1""").fetchall() sin5 = rnd.sample([r[0] for r in fichas], 5) objetivo = set(con30) | set(sin5) rx = re.compile("|".join(objetivo)) def instr(s): u = (s or "").strip().upper() return "subvencion" if u.startswith("SUBVENCI") else "prestamo" if u in ("PRÉSTAMO", "PRESTAMO") else "garantia" if u.startswith("GARANT") else "ventaja_fiscal" if u == "VENTAJA FISCAL" else "otros" crudo = {n: {} for n in objetivo} # nif -> {(via, cod): (anio, instr, importe, equiv)} def mira(via, x, cod_k): tok = (x.get("beneficiario") or "").strip().split(" ")[0].upper() if via == "concesion" and x.get("id") is not None and int(x["id"]) in retiradas: return if tok in crudo and not x.get("_entidad_de_personas"): imp = None if via == "minimis" else (float(x["importe"]) if x.get("importe") not in (None, "") else None) eq = float(x["ayudaEquivalente"]) if x.get("ayudaEquivalente") not in (None, "") else None crudo[tok][(via, x.get(cod_k))] = (int(x["fechaConcesion"][:4]), instr(x.get("instrumento")), imp, eq) for f in sorted(glob.glob(f"{B}/barrido_2022_20261111/paginas/*.json.gz")): t = gzip.open(f, "rt").read() if rx.search(t): for x in json.loads(t)["content"]: if str(x.get("fechaConcesion", "")).startswith("2022"): mira("concesion", x, "codConcesion") for via, pat, ck, cond in (("concesion", "concesiones", "codConcesion", lambda a: a >= 2023), ("ayuda_estado", "ayudasestado", "codConcesion", lambda a: 2016 <= a <= 2021), ("minimis", "minimis", "codigoConcesion", lambda a: 2016 <= a <= 2021)): for f in sorted(glob.glob(f"{B}/{pat}/*/*.jsonl.gz")): for l in gzip.open(f, "rt"): if rx.search(l): x = json.loads(l) if cond(int(str(x.get("fechaConcesion", "0000"))[:4] or 0)): mira(via, x, ck) for f in sorted(glob.glob(f"{INC}/2*/nuevas_pj.jsonl.gz")): for l in gzip.open(f, "rt"): if rx.search(l): x = json.loads(l) if int(str(x.get("fechaConcesion", "0000"))[:4] or 0) >= 2022: mira("concesion", x, "codConcesion") def celdas_crudo(n): out = {} for (via, cod), (a, i, imp, eq) in crudo[n].items(): k = (a, i, via); o = out.setdefault(k, [0, None, None]) o[0] += 1 if imp is not None: o[1] = (o[1] or 0) + imp if eq is not None: o[2] = (o[2] or 0) + eq return out def celdas_web(n): filas = con.execute(f"SELECT c, anio, n, importe, equivalente FROM read_parquet('{PQ}') WHERE nif = ? ORDER BY anio, c", [n]).fetchall() v = ve.construir(n, filas, m) out = {} for f in v["anios"]: for i, x in f["celdas"].items(): for p in (x or {}).get("partes", []): out[(f["anio"], i, p["via"])] = [p["n"], p["importe"], p["equivalente"]] return out, v def igual(a, b): return a[0] == b[0] and all((x is None and y is None) or (x is not None and y is not None and abs(x - y) <= 0.01) for x, y in zip(a[1:], b[1:])) res = [] for n in con30: w, v = celdas_web(n); c = celdas_crudo(n) ok = set(w) == set(c) and all(igual(w[k], c[k]) for k in w) res.append({"grupo": "con_filas", "ok": ok, "celdas": len(w), "filas_crudas": len(crudo[n])}) for n in sin5: w, v = celdas_web(n) ok = not w and not crudo[n] and not any(r["consta"] for r in v["registros"][:2]) res.append({"grupo": "cero", "ok": ok, "celdas": len(w), "filas_crudas": len(crudo[n])}) r = {"semilla": SEM, "aciertos": sum(x["ok"] for x in res if x["grupo"] == "con_filas"), "de": 20, "universo_ganan": len(con_nifs), "retiradas": len(retiradas), "cero": [sum(x["ok"] for x in res if x["grupo"] == "cero"), 5], "celdas": sum(x["celdas"] for x in res), "filas_crudas": sum(x["filas_crudas"] for x in res), "casos": res} r["pasa"] = r["aciertos"] == 20 and r["cero"][0] == 5 json.dump(r, open(sys.argv[1], "w"), ensure_ascii=False, indent=1) json.dump({"con_filas": con30, "cero": sin5}, open(sys.argv[2], "w")) print(json.dumps({k: v for k, v in r.items() if k != "casos"}, ensure_ascii=False))