"""UE1 · 50 · (d) cotejo de 30 licitaciones UE y 20 no-UE contra la entrada ATOM/CODICE original (ZIP en disco, sin red). Muestra (semilla 20261023), última versión de la entrada (mayor ) en el ZIP del scraper; FundingProgramCode, FundingProgram y menciones en el resto del texto. Escribe interno/cotejo/{muestra.csv,atom.json,atom/*.xml}, salidas/50_cotejo.json.""" import csv, json, os, re, time, zipfile, hashlib from multiprocessing import Pool from collections import defaultdict import duckdb T0 = time.time() c = duckdb.connect(); c.execute("SET memory_limit='5GB'; SET threads=4") cand = c.execute("""SELECT licitacion_id, organo_clave, anio, fue, programa, objeto, md5(licitacion_id || '20261023') h FROM '/w/interno/lic.parquet' WHERE feed='resultados_licitaciones' AND anio BETWEEN 2022 AND 2025 AND organo_clave IS NOT NULL AND NOT org_persona ORDER BY h""").fetchall() M = []; orgs = set(); cuenta = defaultdict(int) def toma(cond, cupo, max_anio, etiqueta): n = 0; por_anio = defaultdict(int) for lid, org, anio, fue, prog, obj, h in cand: if n >= cupo: break if not cond(fue, prog) or org in orgs or por_anio[anio] >= max_anio: continue orgs.add(org); por_anio[anio] += 1; n += 1 M.append(dict(cid=f'{etiqueta}{n:02d}', licitacion_id=lid, anio=anio, fue=fue, programa=prog)) toma(lambda f, p: f and p == 'PRTR', 15, 4, 'P') toma(lambda f, p: f and p != 'PRTR', 15, 4, 'O') toma(lambda f, p: not f, 20, 5, 'N') with open('/w/interno/cotejo/muestra.csv', 'w', newline='') as fh: w = csv.DictWriter(fh, list(M[0])); w.writeheader(); w.writerows(M) def corto(lid): return lid.split(':', 1)[1] obj = {corto(m['licitacion_id']) for m in M} 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 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(): por_zip['/n/zips/licitaciones/' + 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(): if not os.path.exists(zp): print('falta', zp); continue 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) RX = re.compile(r'(prtr|next ?generation|nextgen|plan de recuperaci|resiliencia|\bmrr\b|mecanismo de recuperaci|\bfeder\b|\bfeader\b|\bfse\+?\b|fondo social europeo|fondos? europeos?|union europea|eu ?funds)', re.I) import unicodedata def sinac(s): return ''.join(ch for ch in unicodedata.normalize('NFD', s) if unicodedata.category(ch) != 'Mn') R = {} for m in M: k = corto(m['licitacion_id']); r = dict(m) 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) r['FundingProgramCode'] = re.findall(r']*>([^<]*)', ent) r['FundingProgram'] = re.findall(r'][^>]*>([^<]*)|([^<]*)', ent) r['FundingProgram'] = [a or b for a, b in r['FundingProgram']] resto = re.sub(r']*>[^<]*', ' ', ent) resto = sinac(re.sub(r'<[^>]+>', ' ', resto)) ms = [(mm.group(0), resto[max(0, mm.start() - 60): mm.end() + 60].replace('\n', ' ')) for mm in RX.finditer(resto)] r['menciones_texto'] = len(ms); r['ejemplos_mencion'] = [b for _, b in ms[:2]] t = re.search(r'([^<]*)', ent); r['titulo'] = t.group(1)[:140] if t else None codes = set(r['FundingProgramCode']) if m['fue']: prog_ok = m['programa'] in ('otros UE',) or any(m['programa'] in (x or '') for x in codes | set(r['FundingProgram'])) r['estado'] = 'confirma' if 'EU' in codes and prog_ok else ('confirma UE, programa distinto' if 'EU' in codes else 'no confirma') else: r['estado'] = 'confirma' if codes == {'NO-EU'} else 'no confirma' R[m['cid']] = r json.dump(R, open('/w/interno/cotejo/atom.json', 'w'), ensure_ascii=False, indent=1) res = dict(ue=dict(n=sum(1 for r in R.values() if r['fue']), confirma=sum(1 for r in R.values() if r['fue'] and r['estado'] == 'confirma'), con_mencion=sum(1 for r in R.values() if r['fue'] and r.get('menciones_texto', 0) > 0)), no_ue=dict(n=sum(1 for r in R.values() if not r['fue']), confirma=sum(1 for r in R.values() if not r['fue'] and r['estado'] == 'confirma'), con_mencion=sum(1 for r in R.values() if not r['fue'] and r.get('menciones_texto', 0) > 0)), estados={e: sum(1 for r in R.values() if r['estado'] == e) for e in {r['estado'] for r in R.values()}}) json.dump(res, open('/w/salidas/50_cotejo.json', 'w'), ensure_ascii=False, indent=1) print(res) for cid, r in R.items(): print(cid, r['anio'], r['programa'], r.get('estado'), r.get('FundingProgramCode'), r.get('FundingProgram'), r.get('menciones_texto'), '|', (r.get('titulo') or '')[:90], '|', (r.get('ejemplos_mencion') or [''])[0][:130])