"""MOD-REC · paso 11: muestra del cotejo a mano del casado (pre-registro 1, §5). Imagen etl:v2, sin red. 20 resoluciones casadas con E o D, semilla `modrec-cotejo-20`, orden por md5(semilla + id), estratos fijos. Para cada una: los campos de la resolución (PDF: expediente, órgano, objeto, valor, fecha del anuncio + fragmentos del texto donde salen; o la fila del índice) y los de la licitación de la PLACSP en unified_20261101. Salida: /w/priv/cotejo_casado.jsonl (700). """ import json, gzip, hashlib, re, sys import duckdb SEM = 'modrec-cotejo-20' U = '/d/unified_20261101' cas = [json.loads(l) for l in open('/w/priv/casado.jsonl')] cas = [c for c in cas if c['estado'] == 'casada' and c['grupo'] in ('E', 'D')] h = lambda i: hashlib.md5((SEM + i).encode()).hexdigest() ESTR = [('tarcja_adj', lambda c: c['tribunal'] == 'tarcja' and c['acto'] in ('adjudicacion', 'exclusion'), 6), ('tarcja_pli', lambda c: c['tribunal'] == 'tarcja' and c['acto'] == 'pliegos', 3), ('tccsp_pli', lambda c: c['tribunal'] == 'tccsp' and c['acto'] == 'pliegos', 3), ('tarccyl', lambda c: c['tribunal'] == 'tarccyl', 3), ('tacpa', lambda c: c['tribunal'] == 'tacpa' and c['via'] in ('indice', 'ambas'), 3), ('tacpc', lambda c: c['tribunal'] == 'tacpc', 2)] sel = [] for nombre, f, n in ESTR: xs = sorted([c for c in cas if f(c)], key=lambda c: h(c['id']))[:n] for x in xs: x['estrato'] = nombre sel += xs pdf = {} for f in ['/val/priv/p3_resoluciones.jsonl', '/trib/resoluciones.jsonl']: for l in open(f): r = json.loads(l); pdf[r['id']] = r idx = {} for t in ('tarcja', 'tccsp', 'tacpa', 'tacpc', 'tarccyl'): for l in open(f'/trib/{t}/indice.jsonl'): x = json.loads(l); idx[f"{t}:{x['numero']}"] = x def texto(r): rel = r.get('texto') for base in ('/b2trib', '/trib'): try: return gzip.open(f'{base}/{rel}', 'rt', encoding='utf-8', errors='replace').read() except Exception: pass return '' def frag(t, pat, ancho=160, maxn=2): out = [] for m in re.finditer(pat, t, flags=re.I): out.append(re.sub(r'\s+', ' ', t[max(0, m.start() - 40): m.end() + ancho])) if len(out) >= maxn: break return out con = duckdb.connect(); con.execute("SET memory_limit='2GB'; SET threads=3") ids = [s['licitacion_id'] for s in sel] q = con.execute(f"""SELECT licitacion_id, any_value(expediente), any_value(organo_nombre), any_value(objeto), min(fecha_pub), max(coalesce(valor_estimado_eur_expediente, valor_estimado_eur, imp_lic_eur_expediente, imp_lic_eur)), any_value(url_origen), min(fecha_adj), any_value(tipo_contrato) FROM read_parquet('{U}/source=PLACSP/*/*.parquet', hive_partitioning=1, union_by_name=1) WHERE licitacion_id IN ({','.join("'" + i.replace("'", "''") + "'" for i in ids)}) GROUP BY 1""").fetchall() lic = {r[0]: dict(zip(['licitacion_id', 'expediente', 'organo', 'objeto', 'fecha_pub', 've', 'url', 'fecha_adj', 'tipo'], r)) for r in q} with open('/w/priv/cotejo_casado.jsonl', 'w') as fh: for s in sel: r = pdf.get(s['id'], {}); x = idx.get(s['id'], {}) t = texto(r) if r else '' fila = {'estrato': s['estrato'], 'id': s['id'], 'acto': s['acto'], 'sentido': s['sentido'], 'fecha': s['fecha'], 'via': s['via'], 'claves_pdf': s.get('claves_pdf'), 'res': {'expedientes': r.get('expedientes'), 'organo': r.get('organo'), 'objeto': r.get('objeto'), 've': r.get('valor_estimado'), 'fecha_anuncio': r.get('fecha_anuncio'), 'indice_organo': x.get('organo'), 'indice_objeto': x.get('objeto'), 'tipo_indice': x.get('tipo_contrato')}, 'texto_expediente': frag(t, r'expedient|expte'), 'texto_organo': frag(t, r'convocad|licitad|tramitad|promovid|[oó]rgano de contrataci'), 'lic': {k: (str(v) if v is not None else None) for k, v in lic.get(s['licitacion_id'], {}).items()}} fh.write(json.dumps(fila, ensure_ascii=False) + '\n') print(len(sel), [s['estrato'] for s in sel])