"""SALTO · idea 4 · sorteos (cotejo y lectura) y originales ATOM (pre-registro PREREGISTRO_CURVA.md fe26ef8e… §6 y §9; enmienda 1 58082734…). Contenedor buscalicitaciones-etl:v2, sin red, 2 GB, solo lectura de /d (construcción) y /h (licitaciones-historico); escribe en /w/priv (700). 1. población final (§2, la misma consulta que sql/10_curva.sql) y celdas; 2. sorteos de la enmienda 1: cotejo (30), celdas de la lectura (30 + 10) y sus lotes (centrales + 2 al azar); 3. versión del original de cada licitación: la última con ≤ 2026-11-08T23:59:59 según el fichero plano del raspador, buscada en su zip con el índice de la primera entrada de cada .atom; la entrada entera se guarda en /w/priv/orig//.xml; 4. los campos del cotejo, leídos del XML (ElementTree), en /w/priv/originales.json. Por pantalla, solo recuentos.""" import bisect, collections, datetime as dt, json, os, random, re, statistics, time, zipfile import xml.etree.ElementTree as ET import duckdb T0 = time.time() os.umask(0o077) W = "/w/priv" os.makedirs(W + "/orig", exist_ok=True) CORTE = dt.datetime(2026, 11, 8, 23, 59, 59, tzinfo=dt.timezone(dt.timedelta(hours=1))) PJ = re.compile(r"^[ABCDEFGHJNPQRSUVW][0-9]{7}[0-9A-J]$") con = duckdb.connect(config={"threads": 2, "memory_limit": "1200MB"}) _sql = open("/w/sql/10_curva.sql").read().split("SELECT *, (SELECT count(*) FROM f) final FROM excl;")[0] for _st in [s for s in _sql.split(";") if s.strip() and not all(l.strip().startswith("--") or not l.strip() for l in s.splitlines())]: con.execute(_st) filas = con.execute("""SELECT f.id_canonical, f.licitacion_id, f.lote_id, f.cpv_division, f.anio, f.num_ofertas, f.tramo, f.imp_lic_eur, f.imp_adj_eur, f.baja, f.igual, f.adjudicatario_nif, f.imp_lic_reparto, u.imp_lic_eur_con_iva, u.cpv_code FROM f JOIN (SELECT id_canonical, imp_lic_eur_con_iva, cpv_code FROM read_parquet('/d/unified_20261108/source=PLACSP/year=202[2-4]/*.parquet', union_by_name=true)) u USING (id_canonical) ORDER BY f.id_canonical""").fetchall() C = ["id", "licitacion_id", "lote_id", "division", "anio", "num_ofertas", "tramo", "lic", "adj", "baja", "igual", "nif", "reparto", "lic_con_iva", "cpv"] lotes = [dict(zip(C, r)) for r in filas] for x in lotes: x["apto"] = bool(x["nif"]) and bool(PJ.match(x["nif"])) print("población final", len(lotes), "aptos para muestra", sum(x["apto"] for x in lotes), round(time.time() - T0, 1), "s", flush=True) # celdas por_div = collections.defaultdict(list) for x in lotes: por_div[x["division"]].append(x) grandes = {d for d, xs in por_div.items() if len(xs) >= 300} celdas = collections.defaultdict(list) for x in lotes: celdas[("ES", x["tramo"])].append(x) if x["division"] in grandes: celdas[(x["division"], x["tramo"])].append(x) validas_div = sorted(k for k, xs in celdas.items() if k[0] != "ES" and len(xs) >= 30) # 1 · cotejo (enmienda 1, punto 3) rng_a, rng_b, rng_c = random.Random(20261115), random.Random(20261115), random.Random(20261115) cotejo = [] for t in range(1, 7): ids = sorted(x["id"] for x in lotes if x["tramo"] == t and x["apto"]) cotejo += rng_a.sample(ids, 5) # 2 · celdas de la lectura (punto 4) cabeza = [("ES", t) for t in range(1, 7)] for t in range(1, 7): cabeza += rng_b.sample([k for k in validas_div if k[1] == t], 4) resto = [k for k in validas_div if k not in cabeza] positivos = rng_b.sample(resto, 5) resto2 = [k for k in resto if k not in positivos] negativos = rng_b.sample(resto2, 5) def centrales(xs): o = sorted(xs, key=lambda x: (x["baja"], x["id"])) n = len(o) pos = sorted({(n - 1) // 2, n // 2}) elegidos = [] for p in pos: if o[p]["apto"]: elegidos.append((o[p], "central")) continue b = o[p]["baja"] cand = [(abs(i - p), i) for i in range(n) if o[i]["apto"] and o[i]["baja"] == b and o[i] not in [e[0] for e in elegidos]] if cand: elegidos.append((o[min(cand)[1]], "misma_baja")) else: cand = [(abs(i - p), i) for i in range(n) if o[i]["apto"] and o[i] not in [e[0] for e in elegidos]] elegidos.append((o[min(cand)[1]], "mas_cercano")) return elegidos, statistics.median([x["baja"] for x in xs]) lectura = [] for grupo, ks in (("cabeza", cabeza), ("positivo", positivos), ("negativo", negativos)): for k in ks: xs = celdas[k] cen, med = centrales(xs) ids_cen = {e[0]["id"] for e in cen} otros = rng_c.sample(sorted(x["id"] for x in xs if x["apto"] and x["id"] not in ids_cen), 2) lectura.append(dict(grupo=grupo, ambito=k[0], tramo=k[1], n=len(xs), mediana=med, k_igual=sum(1 for x in xs if x["igual"]), centrales=[dict(id=e[0]["id"], como=e[1]) for e in cen], otros=otros)) necesarios = set(cotejo) | {c["id"] for l in lectura for c in l["centrales"]} | {i for l in lectura for i in l["otros"]} # para el negativo «lote de otra división»: un lote apto de otra división grande y del mismo tramo (rng_c) for l in lectura: if l["grupo"] == "negativo": ajenos = sorted(x["id"] for x in lotes if x["apto"] and x["tramo"] == l["tramo"] and x["division"] in grandes and x["division"] != l["ambito"]) l["ajeno"] = rng_c.choice(ajenos) necesarios.add(l["ajeno"]) por_id = {x["id"]: x for x in lotes} json.dump(dict(cotejo=cotejo, lectura=lectura, lotes={i: {k: v for k, v in por_id[i].items()} for i in sorted(necesarios)}, validas_div=len(validas_div), divisiones_grandes=sorted(grandes)), open(W + "/sorteo.json", "w"), ensure_ascii=False, indent=1, default=str) print("cotejo", len(cotejo), "· celdas de lectura", len(lectura), "· lotes necesarios", len(necesarios), "· celdas válidas de división", len(validas_div), flush=True) # 3 · versiones y zips def clave_atom(lid): t = lid.split(":", 1)[1].split("|")[0] a, b = t.split("/")[-2:] return a.split(":")[-1] + "/" + b claves = sorted({clave_atom(i) for i in necesarios}) ver = con.execute("""SELECT regexp_extract(id, '[^/]+/[^/]+$') k, archivo_origen, conjunto, strftime(fecha_updated AT TIME ZONE 'UTC', '%Y-%m-%dT%H:%M:%S') u FROM '/h/nacional/salida/licitaciones_completo.parquet' WHERE regexp_extract(id, '[^/]+/[^/]+$') IN (SELECT unnest(?))""", [claves]).fetchall() vers = collections.defaultdict(list) for k, z, conj, u in ver: vers[k].append((u, z, conj)) corte_utc = CORTE.astimezone(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%S") eleccion = {} for k in claves: vs = sorted(set(vers.get(k, []))) antes = [v for v in vs if v[0] and v[0] <= corte_utc] eleccion[k] = (antes[-1], "ultima_antes_del_corte") if antes else ((vs[0], "primera_despues") if vs else (None, "sin_version")) print("claves", len(claves), "con versión", sum(1 for v in eleccion.values() if v[0]), round(time.time() - T0, 1), "s", flush=True) RE_ID = re.compile(rb"https?://contratacion(?:delestado\.es|delsectorpublico\.gob\.es)/sindicacion/([^<]+)") RE_UPD = re.compile(rb"([^<]+)") def a_utc(s): s = s.strip() d = dt.datetime.fromisoformat(s.replace("Z", "+00:00")) if d.tzinfo is None: d = d.replace(tzinfo=dt.timezone.utc) return d.astimezone(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%S") def ruta_zip(conj, z): for p in (f"/h/nacional/zips/{conj}/{z}", f"/h/nacional/zips/{conj}/_historico/{z}", f"/h/nacional/zips/licitaciones/{z}", f"/h/nacional/zips/agregacion/{z}"): if os.path.exists(p): return p return None indices = {} def indice(zp): if zp not in indices: z = zipfile.ZipFile(zp) idx = [] for m in z.infolist(): if not m.filename.endswith(".atom"): continue with z.open(m) as fh: cab = fh.read(60000) e = cab.find(b"= 0 else None if u: idx.append((a_utc(u.group(1).decode()), m.filename)) idx.sort() indices[zp] = (z, idx) return indices[zp] def entradas(b): cab_fin = b.find(b" 0 else b"" for ent in re.split(rb"(?=])", b): if not ent.startswith(b"") if fin < 0: continue yield cab, ent[:fin + 8] encontrados, sin_original, por_todo_el_zip = {}, [], 0 for k in claves: v, como = eleccion[k] if not v: sin_original.append(k) continue u, z, conj = v zp = ruta_zip(conj, z) if not zp: sin_original.append(k) continue zf, idx = indice(zp) i = bisect.bisect_left(idx, (u, "")) cand = [m for _, m in idx[i:i + 2]] hallado = None # ARREGLO 09:2x: la búsqueda por todo el zip recorre TODOS los .atom (no solo los del índice: hay ficheros cuya primera entrada está # más allá de los primeros 60.000 bytes y no entraban en el índice) for pasada in (cand, [m.filename for m in zf.infolist() if m.filename.endswith(".atom")]): for m in pasada: b = zf.read(m) if ("/" + k + "").encode() not in b: continue for cab, ent in entradas(b): mm = RE_ID.search(ent) if mm and "/".join(mm.group(1).decode().split("/")[-2:]) == k: uu = RE_UPD.search(ent) uu = a_utc(uu.group(1).decode()) if uu else "" if uu == u: hallado = (cab, ent, m) break if hallado: break if hallado: break por_todo_el_zip += 1 if not hallado: sin_original.append(k) continue cab, ent, m = hallado d = W + "/orig/" + k.replace("/", "_") os.makedirs(d, exist_ok=True) ns = re.search(rb"]*)>", cab) open(d + f"/{u.replace(':', '')}.xml", "wb").write(b"\n" + ent + b"\n\n") encontrados[k] = dict(updated=u, como=como, zip=os.path.basename(zp), atom=m, fichero=d + f"/{u.replace(':', '')}.xml") print("originales", len(encontrados), "sin original", len(sin_original), "búsquedas por todo el zip", por_todo_el_zip, round(time.time() - T0, 1), "s", flush=True) # 4 · campos del cotejo N = {"cbc": "urn:dgpe:names:draft:codice:schema:xsd:CommonBasicComponents-2", "cac": "urn:dgpe:names:draft:codice:schema:xsd:CommonAggregateComponents-2", "ext": "urn:dgpe:names:draft:codice-place-ext:schema:xsd:CommonAggregateComponents-2", "cbcx": "urn:dgpe:names:draft:codice-place-ext:schema:xsd:CommonBasicComponents-2"} def num(e): try: return float(e.text) if e is not None and e.text not in (None, "") else None except ValueError: return None def campos(ruta): r = ET.parse(ruta).getroot() cfs = r.find(".//ext:ContractFolderStatus", N) if cfs is None: return {"error": "sin ContractFolderStatus"} pp = cfs.find("cac:ProcurementProject", N) out = dict(tipo=(pp.findtext("cbc:TypeCode", None, N) if pp is not None else None), presupuesto_expediente=num(pp.find("cac:BudgetAmount/cbc:TaxExclusiveAmount", N)) if pp is not None else None, cpv_expediente=[c.text for c in pp.findall("cac:RequiredCommodityClassification/cbc:ItemClassificationCode", N)] if pp is not None else [], estado=cfs.findtext("cbcx:ContractFolderStatusCode", None, N), procedimiento=cfs.findtext("cac:TenderingProcess/cbc:ProcedureCode", None, N), sistema=cfs.findtext("cac:TenderingProcess/cbc:ContractingSystemCode", None, N), lotes={}, resultados=[]) for lt in cfs.findall("cac:ProcurementProjectLot", N): out["lotes"][lt.findtext("cbc:ID", "", N)] = dict(presupuesto=num(lt.find("cac:ProcurementProject/cac:BudgetAmount/cbc:TaxExclusiveAmount", N)), cpv=[c.text for c in lt.findall("cac:ProcurementProject/cac:RequiredCommodityClassification/cbc:ItemClassificationCode", N)]) for tr in cfs.findall("cac:TenderResult", N): out["resultados"].append(dict(resultado=tr.findtext("cbc:ResultCode", None, N), ofertas=num(tr.find("cbc:ReceivedTenderQuantity", N)), lote=tr.findtext("cac:AwardedTenderedProject/cbc:ProcurementProjectLotID", None, N), adjudicacion=num(tr.find("cac:AwardedTenderedProject/cac:LegalMonetaryTotal/cbc:TaxExclusiveAmount", N)), ganador=[p.text for p in tr.findall("cac:WinningParty/cac:PartyIdentification/cbc:ID", N)])) return out orig = {} for k, e in encontrados.items(): try: orig[k] = dict(e, campos=campos(e["fichero"])) except ET.ParseError as ex: orig[k] = dict(e, campos={"error": "XML ilegible: " + str(ex)[:80]}) json.dump(dict(eleccion={k: dict(version=v[0], como=v[1]) for k, v in eleccion.items()}, originales=orig, sin_original=sin_original), open(W + "/originales.json", "w"), ensure_ascii=False, indent=1, default=str) print("hecho", round(time.time() - T0, 1), "s")