"""Corrige el paquete de H: la fila del fichero original, por fila_origen del dato, no casando por NIF y objeto. Dice qué cambia. Sin puntuar.""" import sys, json, hashlib, glob, collections, re; sys.path.insert(0, "/lect") from comun import * c = con(); x = c.execute D = "/data/unified_20261103"; RAW = "/data/raw_preserved/20261103/" DIR = {"CATALUNYA_PSCP": "catalunya", "CATALUNYA": "catalunya", "LA_RIOJA": "la_rioja", "ARAGON": "aragon", "MUNICIPIOS": "municipios", "VALENCIA_MENORES": "valencia_menores", "GALICIA": "galicia", "ASTURIAS": "asturias", "CANARIAS": "canarias", "CASTILLA_LEON": "castilla_leon", "MURCIA": "murcia", "EXTREMADURA": "extremadura", "CASTILLA_LA_MANCHA": "castilla_la_mancha", "VALENCIA": "valencia", "CANTABRIA": "cantabria", "MADRID_AYTO": "ayto_madrid"} for h in ("h1", "h3"): T = json.load(open(f"/o/v2_{h}_top.json"))["org"] fs = [(p, f) for p, o in enumerate(T, 1) for f in o["leer"]] res = collections.Counter(); det = [] for s in sorted({f["source"] for _, f in fs if f["source"] in DIR}): filas = {r[0]: r[1:] for r in x(f"SELECT id_canonical, fila_origen, tabla_origen FROM read_parquet('{D}/source={s}/**/*.parquet', hive_partitioning=1, union_by_name=1) WHERE id_canonical IN (SELECT unnest(?))", [[f["id"] for _, f in fs if f["source"] == s]]).fetchall()} for pos, f in fs: if f["source"] != s: continue p = f"/rec/v2_{h}/interno/para_lector/originales/" + hashlib.md5(f["id"].encode()).hexdigest() + ".json" d = json.load(open(p)); fo_ant = d.get("fichero_original") if not fo_ant: res[(s, "sin fichero en el paquete")] += 1; continue fo, tabla = filas.get(f["id"], (None, None)) cand = glob.glob(RAW + DIR[s] + f"/**/{tabla}.parquet", recursive=True) if fo is None or not cand: res[(s, "sin fila_origen o sin fichero")] += 1; continue cols = [r[0] for r in x(f"DESCRIBE SELECT * FROM read_parquet('{cand[0]}')").fetchall()] v = x(f"SELECT * FROM read_parquet('{cand[0]}', file_row_number=true) WHERE file_row_number = ?", [fo]).fetchone() if not v: res[(s, "fila no encontrada")] += 1; continue fila = {k: (str(w)[:300] if w is not None else None) for k, w in zip(cols, v)}; fila.pop("file_row_number", None) tx = " ".join(str(w) for w in fila.values() if w); nif = (f.get("nif") or f["empresa"] or "").upper() igual = {k: (str(w)[:300] if w is not None else None) for k, w in fo_ant["fila"].items()} == {k: fila.get(k) for k in fo_ant["fila"]} res[(s, "misma fila" if igual else "otra fila")] += 1 if not igual: det.append((pos, s, f["F"][:10], nif in tx.upper())) d["fichero_original"] = {"fichero": cand[0].replace(RAW, ""), "fila_origen": fo, "fila": fila} json.dump(d, open(p, "w"), ensure_ascii=False, indent=0) print(h, sorted(res.items(), key=str)); print(" otra fila (puesto, fuente, F, NIF en la fila correcta):", det)