"""REC2-H: medida según DEFINICIONES_PREVIAS, muestra 2023. Cifras fuera; filas a priv; originales para el lector. Sin lectura ni puntuación.""" import sys, re, csv, json, math, glob, hashlib, collections, unicodedata; sys.path.insert(0, "/lect") from comun import * c = con(); x = c.execute D = "/data/unified_20261103"; RAW = "/data/raw_preserved/20261103/" def nz(s): return unicodedata.normalize("NFKD", s or "").encode("ascii", "ignore").decode().lower() R = json.load(open("/o/h1_filas.json")); prim = json.load(open("/o/h1_top.json"))["listas"] EMER = re.compile(r"emergenc|covid|coronavirus|\bdana\b|paiporta|riada|inundaci|nevada|filomena|temporal de") NOCOMPRA = re.compile(r"(^|[^a-z])(venta|ventas|enajenacion)([^a-z]|$)|adquisicion de (un |una |el |la |los |las )?(inmueble|finca|solar|parcela|vivienda|local)") def fuera2(r): if (r["fuera"] or "")[:2] in ("F1", "F2", "F3", "F4"): return r["fuera"] t = nz(r["objeto"]) if r["tc"] == "Patrimonial" or NOCOMPRA.search(t): return "F5 no es compra" if (r["base"] is not None and r["base"] <= 1) or "conclusion de acuerdo marco" in t: return "F6 importe ficticio" if "prorrog" in t + " " + nz(r["exp"]): return "F7 prórroga" if (r["tram"] or "") == "emergencia" or EMER.search(t): return "F8 emergencia" return None for r in R: r["f2"] = fuera2(r) base = {} for b in csv.DictReader(open("/app/app/datos/cumplimiento_em6v3_organo_anio.csv", encoding="utf8")): base[(b["organo_clave"], int(b["anio_ref"]))] = {"n": int(float(b["n_ev2"] or 0)), "nP": int(float(b["n_P"] or 0)), "nombre": b["organo"]} def wil(k, n, z=1.959963984540054): p = k / n; d = 1 + z*z/n; return (p + z*z/(2*n) - z*math.sqrt(p*(1-p)/n + z*z/(4*n*n))) / d sal = {} for h in ("h1", "h3"): F = collections.Counter(r["f2"] for r in R if r[h] and r["f2"]) tot = sum(1 for r in R if r[h]); q = [r for r in R if r[h] and not r["f2"]] print(f"{h}: {tot} -> {len(q)}; {sorted(F.items())}; % {[(k[:2], round(100*v/tot,1)) for k, v in sorted(F.items())]}; 2023: {sum(1 for r in R if r[h] and r['anio']==2023)} -> {sum(1 for r in q if r['anio']==2023)}", flush=True) excl = {o["organo"] for o in prim[h] if o["anio"] == 2023} print(" excluidos por ya leídos:", len(excl)) por = collections.defaultdict(list) for r in q: if r["anio"]: por[(r["organo"], r["anio"])].append(r) orden = [] for a in (2023, 2022, 2021): fs = [] for (o, y), xs in por.items(): if y != a or (o, y) not in base or (y == 2023 and o in excl): continue b = base[(o, y)] if b["n"] < 30 or (len(xs) == 1 and b["nP"] < 10): continue fs.append({"oc": o, "anio": y, "k": len(xs), "n": b["n"], "lo": wil(len(xs), b["n"]), "nombre": b["nombre"], "leer": xs}) fs.sort(key=lambda f: (-f["lo"], f["oc"])) print(f" {a}: {len(fs)} órganos") orden += fs if len(orden) >= 30: break sal[h] = orden[:30] print(" filas a leer", sum(len(o["leer"]) for o in orden[:30]), "fuentes", collections.Counter(f["source"] for o in orden[:30] for f in o["leer"]).most_common(9), flush=True) # licitacion_id de la Plataforma ids = [f["id"] for h in sal for o in sal[h] for f in o["leer"] if f["source"] == "PLACSP"] x("CREATE TEMP TABLE w AS SELECT unnest(?) i", [ids]) lid = dict(x(f"SELECT id_canonical, licitacion_id FROM read_parquet('{D}/source=PLACSP/**/*.parquet', hive_partitioning=1, union_by_name=1) WHERE id_canonical IN (SELECT i FROM w)").fetchall()) for h in sal: for o in sal[h]: for f in o["leer"]: f["lid"] = lid.get(f["id"]) json.dump({"org": sal[h], "total": len(sal[h])}, open(f"/o/v2_{h}_top.json", "w"), ensure_ascii=False, default=str) json.dump({o["oc"]: o["nombre"] for o in sal[h]}, open(f"/rec/v2_{h}/interno/para_lector/organos.json", "w"), ensure_ascii=False) # BORME entero: solo actos concursales y de cierre bns = sorted({f["bn"] for h in sal for o in sal[h] for f in o["leer"]}) csv.field_size_limit(10**9) mapa = dict(x("SELECT empresa_norm, borme_norm FROM read_parquet('/ca/mapa_norm.parquet') WHERE borme_norm IN (SELECT unnest(?))", [bns]).fetchall()) bo = collections.defaultdict(list) for a in csv.DictReader(open("/ca/h1_actos.csv", encoding="utf8")): b = mapa.get(a["empresa_norm"]) if not b: continue res = [] for campo in re.sub(r"\s+", " ", a["actos_detalle"] or "").split("|"): if campo.startswith("Situación concursal="): for it in campo.split("=", 1)[1].split(";"): it = it.strip() if re.match(r"(?i)(auto|sentencia|resoluci|fe de|decreto|acuerdo|apertura|reapertura)", it): res.append(it[:120]) elif re.match(r"(?i)(extinci|reactivaci|fe de erratas)", campo): res.append(campo.split("=")[0][:30]) bo[b].append({"fecha_borme": a["fecha_borme"][:10], "pdf": a["pdf_filename"], "provincia": a["provincia"], "actos": res}) # Fila del fichero original, en las fuentes sin ficha por contrato o con ficha que es un listado 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", "ANDALUCIA_MENORES": "andalucia_menores"} porf = collections.defaultdict(list) for h in sal: for o in sal[h]: for f in o["leer"]: if f["source"] in DIR and (not (f.get("url") or "").startswith("http") or f["source"] in ("CATALUNYA_PSCP", "CATALUNYA")): porf[f["source"]].append(f) hall = {} for s, fs in porf.items(): nifs = sorted({(f.get("nif") or f["empresa"] or "").upper() for f in fs} - {""}) for a in glob.glob(RAW + DIR[s] + "/**/*.parquet", recursive=True): try: cols = [r[0] for r in x(f"DESCRIBE SELECT * FROM read_parquet('{a}')").fetchall() if r[1] == "VARCHAR"] if not cols or len(cols) * len(nifs) > 400: continue q = " OR ".join(f"contains(upper(coalesce(\"{k}\",'')), ?)" for k in cols for _ in nifs) fil = x(f"SELECT {', '.join(chr(34)+k+chr(34) for k in cols)} FROM read_parquet('{a}') WHERE {q}", [n for k in cols for n in nifs]).fetchall() except Exception: continue for v in fil: t = " | ".join(w for w in v if w); U = re.sub(r"\s+", " ", t.upper()) for f in fs: if f["id"] in hall: continue n = (f.get("nif") or f["empresa"] or "").upper(); ob = re.sub(r"\s+", " ", (f.get("objeto") or "").upper())[:24] if n and n in U and ob and ob in U: hall[f["id"]] = {"fichero": a.replace(RAW, ""), "fila": {k: (w[:300] if w else w) for k, w in zip(cols, v)}} print("originales de fichero:", len(hall), "de", sum(len(v) for v in porf.values()), flush=True) for h in sal: for o in sal[h]: for f in o["leer"]: json.dump({"F": f["F"][:10], "borme": sorted(bo.get(f["bn"], []), key=lambda z: z["fecha_borme"]), "fichero_original": hall.get(f["id"])}, open(f"/rec/v2_{h}/interno/para_lector/originales/" + hashlib.md5(f["id"].encode()).hexdigest() + ".json", "w"), ensure_ascii=False, indent=0) print("escrito")