"""EJ2 · 50 · muestra del cotejo (§8): 20 + 10 reservas de la franja [19 %, 20 %) con documento de modificación""" import duckdb, json c=duckdb.connect(); x=c.execute x("SET threads=4; SET memory_limit='6GB'; SET temp_directory='/w/tmp/duck'; SET max_temp_directory_size='5GB'") DOC="'/d/unified_20261018.documentos/documentos.parquet'" x("CREATE TABLE fr AS SELECT * FROM '/w/interno/u.parquet' WHERE s >= 0.19 AND s < 0.20") x(f"""CREATE TABLE d AS SELECT * FROM (SELECT licitacion_id, documento_id, nombre, url, fecha_ultima_version, row_number() OVER (PARTITION BY licitacion_id ORDER BY fecha_ultima_version DESC NULLS LAST, documento_id) rk FROM {DOC} WHERE tipo_documento='modificacion' AND licitacion_id IN (SELECT licitacion_id FROM fr)) WHERE rk=1""") x("""CREATE TABLE cand AS SELECT fr.*, d.documento_id, d.nombre doc_nombre, d.url doc_url, md5('20261022|ej2|' || fr.licitacion_id) h FROM fr JOIN d USING (licitacion_id)""") print('franja', x("SELECT count(*) FROM fr").fetchone(), 'con doc', x("SELECT count(*) FROM cand").fetchone()) filas = x("SELECT licitacion_id, anio, tipo, organo_clave, A, sM, s, nM, documento_id, doc_nombre, doc_url FROM cand ORDER BY h").fetchall() sel=[]; por_anio={}; org=set() for f in filas: if por_anio.get(f[1],0) >= 4 or f[3] in org: continue sel.append(f); por_anio[f[1]]=por_anio.get(f[1],0)+1; org.add(f[3]) if len(sel)==30: break m = x("SELECT licitacion_id, list(importe_modificacion_sin_iva ORDER BY orden_modificacion) FROM '/w/interno/m.parquet' GROUP BY 1").fetchall() mm = dict(m) out=[] for i,f in enumerate(sel): out.append({'c': f'c{i+1:02d}', 'reserva': i>=20, 'licitacion_id': f[0], 'anio': f[1], 'tipo': f[2], 'A': f[4], 'sM': f[5], 's': f[6], 'nM': f[7], 'importes_M': mm[f[0]], 'documento_id': f[8], 'doc_nombre': f[9], 'doc_url': f[10]}) json.dump(out, open('/w/interno/cotejo/muestra.json','w'), ensure_ascii=False, indent=1, default=float) for o in out: print(o['c'], o['anio'], o['tipo'], round(o['s']*100,2), o['importes_M'], o['doc_nombre'][:50] if o['doc_nombre'] else None, (o['doc_url'] or '')[:80])