"""T5-168 · banco de 20 enlaces o1 para leer a mano (regla: prereg/BANCO_REGLA.md, md5 fe60e4b8f893fa1fd552290eb495fe70). Saca la muestra con la semilla de la regla y arma el material SIN IMPORTES: campos de la construcción (unified_20261108) y la última versión del ATOM original en disco (/h/nacional/zips), quitando todo subárbol de importes, de contacto y de adjudicatario. Salida: priv/banco/material.txt (con identificadores; 700) y salidas/04_banco_meta.json (sin identificadores). Uso: py.sh py/04_banco.py banco""" import duckdb, json, re, os, time, zipfile, collections import xml.etree.ElementTree as ET T0 = time.time() U = '/d/unified_20261108'; SEM = 't5168-banco-10nov' os.makedirs('/o/priv/banco', exist_ok=True) c = duckdb.connect(); c.execute("SET memory_limit='1200MB'"); c.execute("SET threads=2") mu = c.execute(f"SELECT did, mid, casilla, dias FROM read_parquet('/o/priv/01_final_o1.parquet') ORDER BY hash(did || mid || '{SEM}') LIMIT 20").fetchall() ids = [x for r in mu for x in r[:2]] COLS = """id_canonical, unidad, estado, procedimiento_native, organo_nombre, objeto, expediente, licitacion_id, lote_id, cpv_code, tipo_contrato, fecha_pub, fecha_adj, fecha_formalizacion, tramitacion, num_ofertas, anio_ref, duracion_meses, tabla_origen""" fil = {r[0]: r for r in c.execute(f"""SELECT {COLS} FROM read_parquet('{U}/source=PLACSP/*/*.parquet', hive_partitioning=true, union_by_name=true) WHERE id_canonical IN (SELECT unnest(?))""", [ids]).fetchall()} cn = [x.strip() for x in COLS.split(',')] def clave(idc): return idc.split(':', 2)[2].split('|')[0] claves = sorted({clave(i) for i in ids}) ver = collections.defaultdict(set) for k, z, co in c.execute("""SELECT regexp_extract(id, '[^/]+/[^/]+$') k, archivo_origen, conjunto FROM read_parquet('/h/nacional/salida/licitaciones_completo_2012_2026.parquet') WHERE regexp_extract(id, '[^/]+/[^/]+$') IN (SELECT unnest(?))""", [claves]).fetchall(): ver[k].add((z, co)) c.close() print('pares', len(mu), 'claves', len(claves), 'con versión', len(ver), round(time.time() - T0), 's', flush=True) por_zip = collections.defaultdict(set) for k, v in ver.items(): for z, co in v: por_zip[f'/h/nacional/zips/{co}/{z}'].add(k) RE_ID = re.compile(rb'https://contrataciondelestado\.es/sindicacion/([^<]+)'); RE_UPD = re.compile(rb'([^<]+)') enc = {} for zp, cl in sorted(por_zip.items()): if not os.path.exists(zp): print('falta', zp, flush=True); continue with zipfile.ZipFile(zp) as z: for n in z.namelist(): if not n.endswith('.atom'): continue data = z.read(n) for mm in RE_ID.finditer(data): kk = '/'.join(mm.group(1).decode().split('/')[-2:]) if kk not in cl: continue i0 = data.rfind(b'', mm.end()); ent = data[i0:i1 + 8] u = RE_UPD.search(ent); upd = u.group(1).decode() if u else '' if kk not in enc or upd > enc[kk][0]: enc[kk] = (upd, ent.decode('utf-8', 'replace')) del data print('zip', zp.split('/')[-1], 'entradas', len(enc), round(time.time() - T0), 's', flush=True) def ln(e): return e.tag.split('}')[-1] def parse(ent): e2 = re.sub(r'\sxmlns(:[\w\-]+)?="[^"]*"', '', ent); e2 = re.sub(r'\s[\w\-]+:[\w\-]+="[^"]*"', '', e2); e2 = re.sub(r'<(/?)[A-Za-z\-]+:', r'<\1', e2) return ET.fromstring(e2) FUERA = re.compile(r'Amount|Price|Monetary|Budget|Contact|WinningParty|Telephone|ElectronicMail|Telefax|Person', re.I) GUARDA = {'title', 'updated', 'ContractFolderID', 'ContractFolderStatusCode', 'Name', 'TypeCode', 'SubTypeCode', 'ItemClassificationCode', 'ID', 'ResultCode', 'AwardDate', 'Description', 'ReceivedTenderQuantity', 'ProcurementProjectLotID', 'ProcedureCode', 'UrgencyCode', 'DurationMeasure', 'StartDate', 'EndDate', 'FileName', 'CountrySubentity', 'CityName', 'IssueDate', 'Note', 'Justification', 'ProcessReasonCode', 'ReasonCode', 'StatusCode'} def material(ent): try: root = parse(ent) except Exception as e: return [f'(no se pudo leer el XML: {str(e)[:80]})'] out = [] def walk(e, ruta): t = ln(e) if FUERA.search(t): return r2 = ruta + [t] if t == 'summary' and e.text: out.append('summary: ' + re.sub(r'Importe:[^;]*;?', 'Importe: [quitado];', e.text.strip())[:300]) elif t in GUARDA and e.text and e.text.strip() and len(out) < 90: out.append('/'.join(r2[-3:]) + ': ' + e.text.strip()[:300]) for h in e: walk(h, r2) walk(root, []) vistos, res = set(), [] for l in out: if l not in vistos: vistos.add(l); res.append(l) return res meta = [] with open('/o/priv/banco/material.txt', 'w') as fh: for i, (did, mid, cas, dias) in enumerate(mu, 1): fh.write(f"\n######## B{i:02d} · casilla {cas} · días entre desierta y negociado: {dias}\n") for lado, idc in (('DESIERTA', did), ('NEGOCIADO', mid)): f = fil.get(idc) fh.write(f"--- {lado} {idc}\n") if f: for k, v in zip(cn, f): if k != 'id_canonical' and v is not None: fh.write(f" [constr] {k}: {str(v)[:400]}\n") k = clave(idc) if k in enc: fh.write(f" [ATOM] versión updated={enc[k][0]}\n") for l in material(enc[k][1]): fh.write(f" [ATOM] {l}\n") else: fh.write(" [ATOM] no encontrado en los ZIP en disco\n") meta.append({'b': f'B{i:02d}', 'casilla': cas, 'dias': dias, 'atom_desierta': clave(did) in enc, 'atom_negociado': clave(mid) in enc}) json.dump({'semilla': SEM, 'regla': 'prereg/BANCO_REGLA.md fe60e4b8f893fa1fd552290eb495fe70', 'pares': meta, 'segundos': round(time.time() - T0)}, open('/o/salidas/04_banco_meta.json', 'w'), ensure_ascii=False, indent=1) print('OK', round(time.time() - T0), 's')