"""ETL-MENORES-CASA · SEGUNDA implementación, independiente (pre-registro §6): Python con pyarrow en la imagen del scraper, sin DuckDB ni las macros del ETL ni el SQL de py/regla.py. Escrita otra vez desde el texto del pre-registro §2 y §4. Reproduce C-SMS, C-CARM y P-PALMA (claves, nº de líneas, sumas), D1, D2 (de uno a uno, CANT-1), copias, actos, P-NIF, P-IVA, P-UMBRAL y las cifras de E2 (Murcia e Illes Balears por año, en las dos vistas) y escribe datos/segunda.json y priv/m_segunda.parquet (fuente, clave, suma, fecha, n de los contratos que entran). python3 -I p_segunda.py (correr_scr.sh: /h, /u y /c montados)""" import datetime as dt import json import re import time import unicodedata import gc from collections import defaultdict from itertools import groupby import pyarrow as pa import pyarrow.compute as pc import pyarrow.dataset as ds import pyarrow.parquet as pq H, U, C = "", "/unified_20261108", "" UMB = json.load(open(f"{C}/prereg/umbrales.json"))["puertas"] MIN = 1.5 t0 = time.time() # ------------------------------------------------------------------------------------------------------------- lecturas def t(v): if v is None: return None s = str(v).strip() return s or None def es_num(s): return bool(re.match(r"^\s*[-+]?\s*[0-9.,][0-9.,\s]*\s*(€|eur|euros)?\s*$", s, flags=re.I)) and bool(re.search(r"[0-9]", s)) def imp_punto(v): """Punto decimal; una coma sola seguida de 1-2 cifras al final es decimal.""" s = t(v) if s is None or not es_num(s): return None if re.match(r"^[^.]*,[0-9]{1,2}$", s): s = re.sub(r"[^0-9,\-]", "", s).replace(",", ".") else: s = re.sub(r"[^0-9.\-]", "", s) try: return float(s) except ValueError: return None def imp_mixto(v): """Con '.' y ',' manda el último; con solo ',' decimal (salvo miles repetidos); con solo '.' decimal (salvo miles repetidos).""" s = t(v) if s is None or not es_num(s): return None n = re.sub(r"[^0-9,.\-]", "", s) if not n: return None try: if "," in n and "." in n: return float(n.replace(".", "").replace(",", ".")) if n.rfind(",") > n.rfind(".") else float(n.replace(",", "")) if "," in n: return float(n.replace(",", "")) if re.match(r"^-?[0-9]{1,3}(,[0-9]{3}){2,}$", n) else float(n.replace(",", ".")) if re.match(r"^-?[0-9]{1,3}(\.[0-9]{3}){2,}$", n): return float(n.replace(".", "")) return float(n) except ValueError: return None def ambiguo(v): s = t(v) return bool(s and re.match(r"^-?[0-9]{1,3}[.,][0-9]{3}$", re.sub(r"[^0-9,.\-]", "", s))) def fec(v, mdy=False): s = t(v) if s is None: return None s0 = s.split(" ")[0].split("T")[0] try: m = re.match(r"^(\d{4})-(\d{1,2})-(\d{1,2})$", s0) if m: return dt.date(int(m[1]), int(m[2]), int(m[3])) m = re.match(r"^(\d{1,2})-(\d{1,2})-(\d{2})$", s0) if m: return dt.date(2000 + int(m[3]), int(m[1]), int(m[2])) m = re.match(r"^(\d{1,2})/(\d{1,2})/(\d{2}|\d{4})$", s0) if m: a = int(m[3]) if len(m[3]) == 4 else 2000 + int(m[3]) return dt.date(a, int(m[2]), int(m[1])) if re.match(r"^\d{5}(\.\d+)?$", s0): return dt.date(1899, 12, 30) + dt.timedelta(days=int(float(s0))) except ValueError: return None return None def kemp(v): s = t(v) if s is None: return None if "*" in s: z = s.upper().replace(" ", "") return z if re.match(r"^(\*{3}\d{4}\*{2}|\*{4}\d{4}\*)$", z) else None z = re.sub(r"[^A-Za-z0-9]", "", s).upper() if re.match(r"^ES([0-9]{8}[A-Z]|[XYZ][0-9]{7}[A-Z]|[ABCDEFGHJKLMNPQRSUVW][0-9]{7}[A-Z0-9])$", z): z = z[2:] return z or None def mk_de(raw): s = (raw or "").upper() return "***" + s[3:7] + "**" if re.match(r"^([0-9]{8}|[XYZ][0-9]{7})[A-Z]$", s) else None def nn(s): if s is None: return "" s = "".join(ch for ch in unicodedata.normalize("NFD", str(s)) if unicodedata.category(ch) != "Mn").upper() return re.sub(r"[^A-Z0-9]+", " ", s).strip() def first(d, cols, f=t): for c in cols: v = f(d.get(c)) if c in d else None if v is not None: return v return None def filas(ruta, cols): """Las filas del Parquet (solo esas columnas), por lotes, con su nº de fila de origen.""" pf = pq.ParquetFile(ruta) n = 0 for bt in pf.iter_batches(batch_size=50000, columns=[c for c in cols if c in pf.schema_arrow.names]): for r in bt.to_pylist(): yield n, r n += 1 # ---------------------------------------------------------------------------------------------------------------- PLACSP d = ds.dataset(f"{U}/source=PLACSP", format="parquet", partitioning="hive") ftr = (pc.field("unidad") == "adjudicacion") & (pc.field("ccaa").isin(["MC", "IB"]) | pc.field("organo_ccaa").isin(["MC", "IB"])) P = [] # (id, com, ua, ks, vs, ex, fecha): tuplas, para que quepa en 2 GB for bt in d.to_batches(columns=["id_canonical", "expediente", "ccaa", "organo_ccaa", "adjudicatario_nif", "adjudicatario_nif_raw", "imp_adj_eur", "imp_adj_eur_sin_iva", "imp_adj_eur_con_iva", "anio", "year", "fecha_adj"], filter=ftr): for r in bt.to_pylist(): P.append((r["id_canonical"], "MC" if "MC" in (r["ccaa"], r["organo_ccaa"]) else "IB", r["anio"] if r["anio"] is not None else r["year"], tuple(x for x in ((r["adjudicatario_nif"] or "").upper() or None, mk_de(r["adjudicatario_nif_raw"])) if x), tuple(sorted({round(x, 2) for x in (r["imp_adj_eur"], r["imp_adj_eur_sin_iva"], r["imp_adj_eur_con_iva"]) if x is not None and x >= MIN})), (r["expediente"] or "").strip(), r["fecha_adj"])) print("PLACSP", len(P), flush=True) def d2(cand, com, usados): """cand: lista de (id, k, v, y, d). Uno a uno: (k, v, y) por fecha; después (k, v) con el año a ±1. Solo se guardan las adjudicaciones de la PLACSP cuya (empresa, importe) sale en algún candidato (para caber en 2 GB: no cambia el resultado).""" c = [x for x in cand if x[1] is not None and x[2] is not None and x[2] >= MIN] kv = {(x[1], x[2]) for x in c} uimp = set() for (uid, ucom, ua, ks, vs, ex, uf) in P: if ucom != com or uid in usados: continue for k in ks: for v in vs: if (k, v) in kv: uimp.add((uid, k, v, ua, uf)) big = dt.date(9999, 12, 31) def rangos(items, clave, orden): g = defaultdict(list) for it in items: g[clave(it)].append(it) out = {} for kk, lst in g.items(): for n, it in enumerate(sorted(lst, key=orden), 1): out[(kk, n)] = it return out a1 = rangos([x for x in c if x[3] is not None], lambda x: (x[1], x[2], x[3]), lambda x: (x[4] or big, x[0])) b1 = rangos(list(uimp), lambda u: (u[1], u[2], u[3]), lambda u: (u[4] or big, u[0])) pares = [(a1[kk][0], b1[kk][0]) for kk in a1 if kk in b1] p1_ids, p1_u = {p[0] for p in pares}, {p[1] for p in pares} a2 = rangos([x for x in c if x[0] not in p1_ids], lambda x: (x[1], x[2]), lambda x: (x[3] if x[3] is not None else 99999, x[4] or big, x[0])) b2 = rangos([u for u in uimp if u[0] not in p1_u], lambda u: (u[1], u[2]), lambda u: (u[3], u[4] or big, u[0])) for kk in a2: if kk in b2: a, b = a2[kk], b2[kk] if a[3] is not None and abs(a[3] - b[3]) <= 1: pares.append((a[0], b[0])) res = defaultdict(set) for i, u in pares: res[i].add(u) return {i: min(us) for i, us in res.items()} # --------------------------------------------------------------------------------------------------------- SMS y CARM # Línea o pago: (id, k, imp, f, fila, arch, tipo). Grupo: id -> (n, nif_ok, k, suma, d, tipo, suma_ok) def agrupa(lineas, orden): lineas.sort(key=lambda x: x[0]) out = {} for i, it in groupby(lineas, key=lambda x: x[0]): ls = list(it) ks = {x[1] for x in ls} imps = [x[2] for x in ls if x[2] is not None] fs = [x[3] for x in ls if x[3] is not None] p = min(ls, key=orden) out[i] = (len(ls), len(ks) == 1 and None not in ks, next(iter(ks)) if len(ks) == 1 else None, sum(imps) if imps else None, min(fs) if fs else None, p[6], bool(imps) and sum(imps) > 0) return out def fuente_mc(lineas, orden, d1_de): g = agrupa(lineas, orden) usados, d1 = set(), set() for i in g: us = d1_de(i) if us: d1.add(i) usados.update(us) cand = [(i, x[2], round(x[3], 2), x[4].year if x[4] else None, x[4]) for i, x in g.items() if x[1] and x[6] and i not in d1] m2 = d2(cand, "MC", usados) contrato = {i for i, x in g.items() if x[1] and x[6] and i not in d1 and i not in m2} return g, d1, set(m2), contrato SMS_PED = ["Ref. Contrato", "Doc.compras", "Doc.compr."] SMS_NIF = ["ADJUDICATARIO CÓDIGO OF", "ADJUDICATARIO CÓDIGO", "NIF Adj", " Cif", "Adjudicatario NIF"] SMS_FEC = ["F.FORMALIZACIÓN", "Fecha Formalizacion", "Fecha Formalización"] sms = filas(f"{H}/murcia/contratos_menores_sms.parquet", SMS_PED + SMS_NIF + SMS_FEC + [" Valor neto", "Importe Adjudicacion", "Importe Adjudicación EUR", "Importe Adjudicación"]) L = [] for n, r in sms: p = first(r, SMS_PED) if p is None or not re.match(r"^[0-9]{6,}$", p): continue raw_imp = first(r, [" Valor neto", "Importe Adjudicacion", "Importe Adjudicación EUR"]) or (t(r.get("Importe Adjudicación")) if t(r.get("Ref. Contrato")) else None) L.append((p, kemp(first(r, SMS_NIF)), imp_punto(raw_imp), first(r, SMS_FEC, fec), n, 0, None)) digitos = defaultdict(list) for (uid, ucom, ua, ks, vs, ex, uf) in P: if ucom == "MC": dg = re.sub(r"[^0-9]", "", ex) if len(dg) >= 6: digitos[dg].append(uid) SMSg, SMSd1, SMSd2, SMSc = fuente_mc(L, lambda x: (x[5], x[4]), lambda i: digitos.get(i, ())) del digitos gc.collect() print("SMS", len(SMSg), flush=True) carm = filas(f"{H}/murcia/contratos_menores_carm.parquet", ["CODEXPEDIENTE", "ADJUDICATARIO_CIF", "ADJUDICATARIOCODIGO", "ADJUDICATARIO_DESCRIPCION", "ADJUDICATARIODESCRIPCION", "IMPORTE(IVAINCLUIDO)", "VALORCONTABPAGO", "IMPORTECONTABPAGO", "FECHA", "FECHACONTABPAGO", "TIPOCONTRATO", "TIPO_CONTRATO", "_anio_fichero"]) LC = [] for n, r in carm: e = t(r.get("CODEXPEDIENTE")) if e is None or not re.match(r"^(20[0-9]{2})/[0-9]{6}$", e) or int(e[:4]) < 2023: continue if t(r.get("FECHA")) is not None: # 2014-2019 (registros, no pagos): fuera; no traen expediente continue if first(r, ["ADJUDICATARIO_CIF", "ADJUDICATARIOCODIGO", "ADJUDICATARIO_DESCRIPCION", "ADJUDICATARIODESCRIPCION", "IMPORTE(IVAINCLUIDO)", "VALORCONTABPAGO", "IMPORTECONTABPAGO"]) is None: # fila vacía: no es un pago continue raw = first(r, ["VALORCONTABPAGO", "IMPORTECONTABPAGO"]) if raw and raw[0] in ",.": raw = "0" + raw LC.append((e, kemp(first(r, ["ADJUDICATARIO_CIF", "ADJUDICATARIOCODIGO"])), imp_mixto(raw), fec(r.get("FECHACONTABPAGO"), mdy=True), n, r.get("_anio_fichero"), first(r, ["TIPO_CONTRATO", "TIPOCONTRATO"]))) pref = defaultdict(list) for (uid, ucom, ua, ks, vs, ex, uf) in P: m = re.match(r"^(20[0-9]{2}/[0-9]{6})(/[0-9]+)?$", ex) if ucom == "MC" and m: pref[m[1]].append(uid) CARMg, CARMd1, CARMd2, CARMc = fuente_mc(LC, lambda x: (x[3] or dt.date(9999, 1, 1), x[5], x[4]), lambda i: pref.get(i, ())) print("CARM", len(CARMg), flush=True) # --------------------------------------------------------------------------------------------------------------- Palma # En el Parquet las columnas se llaman 'Data' e 'Import' (DuckDB las lee como 'Data_1' e 'Import_1' porque sin distinguir # mayúsculas chocan con 'DATA' e 'IMPORT'); pyarrow las lee con su nombre pal = filas(f"{H}/municipios/palma_menores.parquet", ["DATA", "Fecha", "Data", "IMPORT", "Importe", "Import", "EMPRESA ADJUDICATÀRIA", "Nombre Ter.", "CIF EMPRESA ADJUDICATÀRIA", "OBJECTE CONTRACTE", "Texto Libre", "_anio", "_trimestre", "_hoja", "_archivo_origen"]) PF = [] for n, r in pal: hoja = t(r.get("_hoja")) or "" anio = t(r.get("_anio")) tri = t(r.get("_trimestre")) if anio is None: m = re.search(r"(20[0-9]{2})", hoja) anio = m[1] if m else None if tri is None: m = re.search(r"([1-4])[^0-9]*20[0-9]{2}", hoja) tri = m[1] if m else None raw_imp = first(r, ["IMPORT", "Importe", "Import"]) x = {"fila": n, "fecha": first(r, ["DATA", "Fecha", "Data"], fec), "imp": imp_mixto(raw_imp), "imp_txt": raw_imp, "amb": ambiguo(raw_imp), "emp": first(r, ["EMPRESA ADJUDICATÀRIA", "Nombre Ter."]), "k": kemp(r.get("CIF EMPRESA ADJUDICATÀRIA")), "obj": first(r, ["OBJECTE CONTRACTE", "Texto Libre"]), "arch": t(r.get("_archivo_origen")), "anio": int(anio) if anio else None, "tri": int(tri) if tri else None} x["es_contrato"] = hoja != "INVERSOS" and (x["emp"] is not None or x["obj"] is not None) x["reg"] = "|".join([x["fecha"].isoformat() if x["fecha"] else "", "" if x["imp"] is None else repr(round(x["imp"], 2)), nn(x["emp"]), re.sub(r"\s+", " ", (x["obj"] or "").strip()).lower()]) x["orden"] = (x["anio"] or 9999, x["tri"] or 9, x["arch"] or "") o = "".join(ch for ch in unicodedata.normalize("NFD", (x["obj"] or "").lower()) if unicodedata.category(ch) != "Mn") x["acto"] = bool(re.match(r"^(ampliacio|complement|increment|augment|reajust|modificacio)", re.sub(r"^[^a-z0-9]+", "", o))) PF.append(x) primero = {} for x in PF: primero[x["reg"]] = min(primero.get(x["reg"], x["orden"]), x["orden"]) for x in PF: x["copia"] = x["es_contrato"] and x["orden"] > primero[x["reg"]] x["unidad"] = (None if not x["es_contrato"] else "acto:abono" if (x["imp"] is not None and x["imp"] < 0) else "acto:modificacion" if x["acto"] else "sin_datos" if (x["emp"] is None and (x["imp"] or 0) == 0) else "adjudicacion") candp = [(str(x["fila"]), x["k"], round(x["imp"], 2), x["fecha"].year if x["fecha"] else None, x["fecha"]) for x in PF if x["es_contrato"] and not x["copia"] and not x["acto"] and x["imp"] is not None and x["imp"] > 0 and x["k"] is not None] m2p = d2(candp, "IB", set()) for x in PF: x["d2"] = str(x["fila"]) in m2p x["cuenta"] = x["es_contrato"] and not x["copia"] and x["unidad"] == "adjudicacion" and not x["d2"] print("Palma", len(PF), flush=True) # --------------------------------------------------------------------------------------------------------------- puertas def piva(vals): vals = [v for v in vals if v is not None] a = sum(1 for v in vals if 16650 < v <= 18150) b = sum(1 for v in vals if 18150 < v <= 19650) c = sum(1 for v in vals if 13500 < v <= 15000) dd = sum(1 for v in vals if 15000 < v <= 16500) r = "sin" if (c + dd >= 30 and c >= 3 * dd) else ("con" if (a >= 30 and a >= 3 * b) else "no_consta") return {"a": a, "b": b, "c": c, "d": dd, "resultado": r} pu = {} GR = {"SMS": (SMSg, SMSd1, SMSd2, SMSc), "CARM": (CARMg, CARMd1, CARMd2, CARMc)} for f, (g, gd1, gd2, gc_) in GR.items(): n = len(g) mal = sum(1 for x in g.values() if not x[1]) con = [g[i] for i in gc_] obras = (lambda x: x[5] == "Obras") if f == "CARM" else (lambda x: False) iv = piva([x[3] for x in con if not obras(x)]) lim = 15000 if iv["resultado"] == "sin" else 18150 fuera = sum(1 for x in con if (x[3] > 48400 if obras(x) else x[3] > lim)) pu[f] = {"P_NIF": {"candidatos": n, "mezcla_o_sin_nif": mal, "pasa": mal / n <= 0.02}, "P_IVA": iv, "P_UMBRAL": {"contratos": len(con), "por_encima": fuera, "pasa": fuera / len(con) <= 0.05 if con else False}} pu[f]["entra"] = pu[f]["P_NIF"]["pasa"] and pu[f]["P_UMBRAL"]["pasa"] cp = [x for x in PF if x["cuenta"]] iv = piva([x["imp"] for x in cp]) lim = 40000 if iv["resultado"] == "sin" else 48400 fuera = sum(1 for x in cp if x["imp"] is not None and x["imp"] > lim) pu["Palma"] = {"P_IVA": iv, "P_UMBRAL": {"contratos": len(cp), "por_encima": fuera, "pasa": fuera / len(cp) <= 0.05, "info_por_encima_18150": sum(1 for x in cp if x["imp"] is not None and x["imp"] > 18150)}} pu["Palma"]["entra"] = pu["Palma"]["P_UMBRAL"]["pasa"] # ------------------------------------------------------------------------------------------------------------ E1 y salida nuevos = [] for f, (g, gd1, gd2, gc_) in GR.items(): if pu[f]["entra"]: nuevos += [(f, i, round(g[i][3], 2), g[i][4], g[i][0], "MC") for i in gc_] if pu["Palma"]["entra"]: nuevos += [("Palma", str(x["fila"]), round(x["imp"], 2) if x["imp"] is not None else None, x["fecha"], 1, "IB") for x in cp] pq.write_table(pa.table({"fuente": [x[0] for x in nuevos], "clave": [x[1] for x in nuevos], "suma": [x[2] for x in nuevos], "fecha": [x[3] for x in nuevos], "n": [x[4] for x in nuevos]}), f"{C}/priv/m_segunda.parquet") e1 = defaultdict(lambda: [0, 0, 0.0]) for f, i, s, dd, n, cc in nuevos: k = f"{f} {dd.year if dd else (next((x['anio'] for x in PF if str(x['fila']) == i), None) if f == 'Palma' else None)}" e1[k][0] += 1 e1[k][1] += n e1[k][2] += s or 0 d1d2 = {f: {"d1": len(gd1), "d2": len(gd2), "contratos": len(gc_)} for f, (g, gd1, gd2, gc_) in GR.items()} d1d2["Palma"] = {"copias": sum(1 for x in PF if x["copia"]), "actos": sum(1 for x in PF if x["es_contrato"] and not x["copia"] and x["unidad"] == "acto:modificacion"), "abonos": sum(1 for x in PF if x["es_contrato"] and not x["copia"] and x["unidad"] == "acto:abono"), "d2": sum(1 for x in PF if x["d2"]), "cuentan": len(cp), "importe_ambiguo": sum(1 for x in PF if x["amb"])} # --------------------------------------------------------------------------------- líneas de los contratos (para E2, aparte) lineas_fila = [] for f, lin in (("SMS", L), ("CARM", LC)): if pu[f]["entra"]: tab = "contratos_menores_sms" if f == "SMS" else "contratos_menores_carm" gc_ = GR[f][3] lineas_fila += [f"{tab}:{x[4]}" for x in lin if x[0] in gc_] pq.write_table(pa.table({"clave_fila": lineas_fila}), f"{C}/priv/lineas_segunda.parquet") e1_json = {k: {"contratos": v[0], "lineas_o_pagos": v[1], "importe": round(v[2], 2)} for k, v in sorted(e1.items())} nuevos_ccaa_anio = defaultdict(lambda: [0, 0.0]) for f, i, s_, dd, n, cc in nuevos: k = f"{cc} {dd.year if dd else (next((x['anio'] for x in PF if str(x['fila']) == i), None) if f == 'Palma' else None)}" nuevos_ccaa_anio[k][0] += 1 nuevos_ccaa_anio[k][1] += s_ if (s_ is not None and abs(s_) <= 1e9) else 0 out = {"puertas": pu, "E1": {"por_fuente_anio": e1_json, "conjuntos": d1d2}, "nuevos_por_ccaa_anio": {k: [v[0], round(v[1], 2)] for k, v in nuevos_ccaa_anio.items()}, "segundos": round(time.time() - t0)} json.dump(out, open(f"{C}/datos/segunda.json", "w"), ensure_ascii=False, indent=1, default=str) print(json.dumps(pu, ensure_ascii=False)) print(json.dumps(d1d2, ensure_ascii=False)) print(f"segunda: {out['segundos']} s")