"""OU1 · 51 · cotejo (1) contra la entrada ATOM/CODICE original (ZIP de la sindicación en disco, sin red). Para cada lote de interno/cotejo/muestra.csv: última versión de la entrada (mayor ) en el ZIP que dice el scraper (es_ultima_version); todos sus TenderResult: lote, ResultCode, ReceivedTenderQuantity. Escribe interno/cotejo/atom.json y las entradas en atom/.""" import csv, json, os, re, time, zipfile import xml.etree.ElementTree as ET from multiprocessing import Pool from collections import defaultdict import duckdb T0 = time.time() M = list(csv.DictReader(open('/w/interno/cotejo/muestra.csv'))) def corto(lid): return lid.split(':', 1)[1] obj = {corto(m['licitacion_id']) for m in M} c = duckdb.connect(); c.execute("SET memory_limit='5GB'; SET threads=4") ver = {r[0]: r[1] for r in c.execute("""SELECT regexp_extract(id, '[^/]+/[^/]+$') k, archivo_origen FROM '/n/salida/licitaciones_completo.parquet' WHERE es_ultima_version AND conjunto IN ('licitaciones','agregacion') AND regexp_extract(id, '[^/]+/[^/]+$') IN (SELECT unnest(?))""", [sorted(obj)]).fetchall()} print('objetivo', len(obj), 'con versión', len(ver), flush=True) por_zip = defaultdict(set) for k, z in ver.items(): d = '/n/zips/licitaciones/' if z.startswith('licitaciones') else '/n/zips/agregacion/' por_zip[d + z].add(k) RE_ID = re.compile(rb'https://contrataciondelestado\.es/sindicacion/([^<]+)') RE_UPD = re.compile(rb'([^<]+)') def buscar(a): zp, mi, claves = a; out = [] with zipfile.ZipFile(zp) as z: data = z.read(mi) for m in RE_ID.finditer(data): k = m.group(1).decode() if k not in claves: continue i0 = data.rfind(b'', m.end()) if i0 < 0 or i1 < 0: continue ent = data[i0:i1 + 8]; u = RE_UPD.search(ent) out.append((k, u.group(1).decode() if u else '', zp.split('/')[-1] + '::' + mi, ent.decode('utf-8', 'replace'))) return out tareas = [] for zp, cl in por_zip.items(): with zipfile.ZipFile(zp) as z: tareas += [(zp, n, cl) for n in z.namelist() if n.endswith('.atom')] print('atom a leer', len(tareas), flush=True) enc = {} with Pool(4) as p: for res in p.imap_unordered(buscar, tareas, chunksize=4): for k, upd, donde, ent in res: if k not in enc or upd > enc[k][0]: enc[k] = (upd, donde, ent) print('encontradas', len(enc), round(time.time() - T0), 's', flush=True) def ln(e): return e.tag.split('}')[-1] def todos(e, n): return [x for x in e.iter() if ln(x) == n] def txt(e): return e.text.strip() if e is not None and e.text else None os.makedirs('/w/interno/cotejo/atom', exist_ok=True) R = {} for m in M: k = corto(m['licitacion_id']); r = {'cid': m['cid'], 'clave': k, 'lote_u': m['lote_u']} if k not in enc: r['estado'] = 'no encontrada'; R[m['cid']] = r; continue upd, donde, ent = enc[k]; r['updated'] = upd; r['donde'] = donde open(f"/w/interno/cotejo/atom/{m['cid']}.xml", 'w').write(ent) root = ET.fromstring('' + re.sub(r']*>', '', ent, count=1) + '') if False else None try: root = ET.fromstring(ent.replace('', '', 1)) except ET.ParseError: # declarar prefijos que falten pref = set(re.findall(r'<(/?)([A-Za-z\-]+):', ent)); decl = ' '.join(f'xmlns:{p}="urn:x:{p}"' for _, p in pref if p) e2 = re.sub(r']*)>', lambda mm: '', ent, count=1) root = ET.fromstring(e2) trs = [] for tr in todos(root, 'TenderResult'): lot = None; rtq = None; code = None for x in tr.iter(): n = ln(x) if n == 'ProcurementProjectLotID' and lot is None: lot = txt(x) if n == 'ReceivedTenderQuantity' and rtq is None: rtq = txt(x) if n == 'ResultCode' and code is None: code = txt(x) trs.append({'lote': lot, 'ResultCode': code, 'ReceivedTenderQuantity': rtq}) r['tender_results'] = trs r['n_lotes_proyecto'] = len(todos(root, 'ProcurementProjectLot')) titulo = [txt(x) for x in root.iter() if ln(x) == 'title']; r['titulo'] = titulo[0] if titulo else None lote = m['lote_u'].split('|')[1] if '|' in m['lote_u'] else None r['lote_nuestro'] = lote cand = [t for t in trs if (lote is None) or (t['lote'] is not None and t['lote'].lstrip('0') == lote.lstrip('0'))] r['cand'] = cand vals = {t['ReceivedTenderQuantity'] for t in cand} r['atom_dice'] = sorted(v for v in vals if v is not None) + (['(vacío)'] if None in vals else []) r['estado'] = 'confirma' if cand and vals == {'1'} else ('no confirma' if cand else 'lote no encontrado') R[m['cid']] = r json.dump(R, open('/w/interno/cotejo/atom.json', 'w'), ensure_ascii=False, indent=1) for cid, r in R.items(): print(cid, r.get('estado'), r.get('lote_nuestro'), r.get('atom_dice'), len(r.get('tender_results', [])), (r.get('titulo') or '')[:60])