"""TL-T4-120 · 05: banco de 20 casos a mano (regla prereg/BANCO_REGLA.md 652431bc, escrita antes). Elige por estrato (solo 2018-2023, sin personas físicas), copia todas las versiones del ATOM (ZIP en disco, sin red) a /o/priv/banco// y deja casos.tsv (ref y número de versiones, SIN estrato ni valores) y medida.json (lo que lee la medida), que no se abre hasta escribir la lectura. No imprime ningún valor de la medida. Ningún intervalo.""" import sys, json, re, os, time, hashlib, zipfile, collections sys.path.insert(0, '/o/py') import duckdb, emer T0 = time.time() c = duckdb.connect() for s_ in ("SET memory_limit='1500MB'", "SET threads=2", "SET temp_directory='/o/priv/tmp05'", "SET preserve_insertion_order=false"): c.execute(s_) emer.crear(c) H = emer.H c.execute("CREATE TEMP TABLE up AS SELECT * FROM read_parquet('/o/priv/u_placsp.parquet') WHERE anio BETWEEN 2018 AND 2023") c.execute("""CREATE TEMP TABLE cand AS SELECT id, any_value(conjunto) conj, min(anio) anio, count(*) n_res, bool_or(pf) any_pf, bool_or(sp IS NOT NULL) has_sp, bool_or(sr IS NOT NULL) has_sr, bool_or(sp < a) sp_antes_a, greatest(max(n_a_ver), max(n_sr_ver), max(n_sp_ver)) n_ver_fecha, bool_or(day(sp) = 1) sp_dia1, bool_or(sr = f) sr_igual_f, false cero FROM up GROUP BY id""") # cero resultados: emergencia de la 643 sin resultado adjudicado, año de publicación (o versión) 2018-2023, sin adjudicatario persona física c.execute(f"""INSERT INTO cand SELECT l.id, l.conjunto, year(coalesce(l.fpub, l.fupd::DATE)), 0, coalesce(bool_or(r.pf) FILTER (WHERE r.rc IS NOT NULL AND r.pf AND r.rc IN ('3','4','5','6','7') AND false), false), false, false, false, 0, false, false, true FROM lic l LEFT JOIN res r USING(id) WHERE l.urgencia='3' AND l.conjunto='licitaciones' AND year(coalesce(l.fpub, l.fupd::DATE)) BETWEEN 2018 AND 2023 AND NOT EXISTS (SELECT 1 FROM res x WHERE x.id = l.id AND x.rc IN {emer.ADJ}) GROUP BY l.id, l.conjunto, l.fpub, l.fupd""") rows = c.execute("SELECT * FROM cand WHERE NOT any_pf").fetchall(); cols = [d[0] for d in c.description] C = [dict(zip(cols, r)) for r in rows] SEM = '|tl-t4-120-banco-10nov' h = lambda i: hashlib.md5((i + SEM).encode()).hexdigest() L = lambda x: x['conj'] == 'licitaciones' and not x['cero'] EST = [('E1a', 2, lambda x: L(x) and x['has_sp'] and x['anio'] == 2020), ('E1b', 2, lambda x: L(x) and x['has_sp'] and 2021 <= x['anio'] <= 2023), ('E2', 3, lambda x: L(x) and x['has_sr'] and not x['has_sp']), ('E3a', 2, lambda x: L(x) and not x['has_sr'] and not x['has_sp'] and x['anio'] == 2020), ('E3b', 2, lambda x: L(x) and not x['has_sr'] and not x['has_sp'] and 2021 <= x['anio'] <= 2023), ('E4', 2, lambda x: L(x) and x['sp_antes_a']), ('E5', 1, lambda x: L(x) and x['n_res'] >= 2), ('E6', 1, lambda x: L(x) and (x['n_ver_fecha'] or 0) >= 2), ('E7', 1, lambda x: x['cero']), ('E8', 2, lambda x: x['conj'] == 'agregacion' and not x['cero']), ('E9', 1, lambda x: L(x) and x['sp_dia1']), ('E10', 1, lambda x: L(x) and x['sr_igual_f'])] pool = sorted(C, key=lambda x: h(x['id'])); usados = set(); M = []; cortos = [] for est, k, f in EST: sel = [x for x in pool if x['id'] not in usados and f(x)][:k] if len(sel) < k: cortos.append([est, len(sel)]) sel += [x for x in pool if x['id'] not in usados and EST[0][2](x) and x not in sel][:k - len(sel)] for x in sel: usados.add(x['id']); M.append(dict(x, estrato=est)) M.sort(key=lambda x: hashlib.md5((x['id'] + '|ref').encode()).hexdigest()) for n, x in enumerate(M, 1): x['ref'] = f'B{n:02d}'; x['clave'] = '/'.join(x['id'].split('/')[-2:]) ids = [m['id'] for m in M] med = {} for m in M: rs = c.execute("""SELECT r.lote, r.rc, r.ord, r.a, r.sr, r.f FROM res r WHERE r.id = ? ORDER BY r.lote, r.ord""", [m['id']]).fetchall() am = c.execute("SELECT sp, spf FROM amp WHERE id = ?", [m['id']]).fetchall() li = c.execute("SELECT urgencia, conjunto FROM lic WHERE id = ?", [m['id']]).fetchall() adj = [r for r in rs if r[1] in ('1', '2', '8', '9')] med[m['ref']] = dict(ref=m['ref'], id=m['id'], estrato=m['estrato'], anio=m['anio'], conjunto=li[0][1] if li else None, emergencia=(li[0][0] == '3') if li else None, entra=bool(adj), A=sorted({str(r[3]) for r in adj if r[3]}), SR=sorted({str(r[4]) for r in adj if r[4]}), F=sorted({str(r[5]) for r in adj if r[5]}), SP=str(am[0][0]) if am and am[0][0] else None, SPF=str(am[0][1]) if am and am[0][1] else None, resultados=[[r[0], r[1], str(r[3]) if r[3] else None, str(r[4]) if r[4] else None, str(r[5]) if r[5] else None] for r in rs]) arch = c.execute(f"SELECT DISTINCT id, archivo_origen, conjunto, zip_historico FROM read_parquet('{H}.parquet') WHERE id IN (SELECT unnest(?))", [ids]).fetchall() por = collections.defaultdict(set) for i, z, con, zh in arch: for p in (f'/h/nacional/zips/{con}/{z}', f'/h/nacional/zips/{con}/_historico/{zh}' if zh else None, f'/h/nacional/zips/{con}/_historico/{z}'): if p and os.path.exists(p): por[p].add('/'.join(i.split('/')[-2:])); break else: print('falta zip', z, zh, flush=True) RE_ID = re.compile(rb'https?://contratacion(?:delestado\.es|delsectorpublico\.gob\.es)/sindicacion/([^<]+)') RE_UPD = re.compile(rb'([^<]+)') ver = collections.defaultdict(dict) for zp, cl in por.items(): with zipfile.ZipFile(zp) as z: for nm in z.namelist(): if not nm.endswith('.atom'): continue data = z.read(nm) for mm in RE_ID.finditer(data): k = '/'.join(mm.group(1).decode().split('/')[-2:]) if k not in cl: continue i0 = data.rfind(b'', mm.end()) if i0 < 0 or i1 < 0: continue ent = data[i0:i1 + 8]; u = RE_UPD.search(ent); upd = u.group(1).decode() if u else '' ver[k].setdefault(upd, ent) del data print('zip', os.path.basename(zp), len(cl), round(time.time() - T0), flush=True) os.makedirs('/o/priv/banco', exist_ok=True) with open('/o/priv/banco/casos.tsv', 'w') as fh: fh.write('ref\tversiones\n') for x in M: vs = sorted(ver.get(x['clave'], {}).items()); d = f"/o/priv/banco/{x['ref']}"; os.makedirs(d, exist_ok=True) for u, ent in vs: open(f"{d}/v_{re.sub(r'[^0-9T]', '', u)[:20]}.xml", 'wb').write(ent) med[x['ref']]['n_versiones_zip'] = len(vs); fh.write(f"{x['ref']}\t{len(vs)}\n") json.dump(list(med.values()), open('/o/priv/banco/medida.json', 'w'), indent=0, default=str) print(json.dumps(dict(casos=len(M), estratos_cortos=cortos, sin_versiones=sum(1 for x in med.values() if not x['n_versiones_zip']), segundos=round(time.time() - T0))))