"""MK1 · 53 · lectura de las fichas del cotejo (d): ¿existe el lote, coincide el nº de ofertas y el adjudicatario? Sin nombres en la salida pública: solo coincide / no / no legible. Escribe salidas/50_cotejo.md y interno/cotejo/lectura.json.""" import csv, html, json, re, unicodedata M = list(csv.DictReader(open('/w/interno/cotejo/muestra.csv'))) def norm(s): s = unicodedata.normalize('NFKD', s or '').encode('ascii', 'ignore').decode().upper() s = re.sub(r'\b(S\.?\s?A\.?U?|S\.?\s?L\.?U?|S\.?\s?COOP\.?|SOCIEDAD ANONIMA|SOCIEDAD LIMITADA|UNIPERSONAL|UTE|U\.T\.E\.?)\b', ' ', s) return set(w for w in re.findall(r'[A-Z0-9]{2,}', s)) def txt(p): s = open(p, encoding='utf-8', errors='replace').read(); t = re.sub(r'', ' ', s, flags=re.S) return html.unescape(re.sub(r'\s+', ' ', re.sub(r'<[^>]+>', ' ', t))) R = []; L = ['# MK1 · Cotejo (d): 20 unidades contra la ficha pública', '', 'Un lote por unidad (§6d). Ficha descargada con red `mk1-fetch`, 20 peticiones, pausa 4 s (`interno/cotejo/peticiones.csv`).', '', '| caso | grupo | feed | año | lote existe | nº ofertas (nuestro → ficha) | adjudicatario | veredicto |', '|---|---|---|---|---|---|---|---|'] for m in M: t = txt(f"/w/interno/cotejo/html/{m['cid']}.html"); r = {'cid': m['cid'], 'grupo': m['grupo']} nl = re.findall(r'N[ºo°] de Licitadores Presentados\s+(\d+)', t) ad = re.findall(r'Adjudicatario\s+(.{3,160}?)\s+N[ºo°] de Licitadores', t) if not nl: # otras plataformas (p. ej. Galicia) nl = re.findall(r'(?:N[úu]mero de (?:licitadores|ofertas)(?: recibidas| presentadas)?|Ofertas recibidas)\s*:?\s*(\d+)', t, flags=re.I) exp_ok = bool(re.search(re.escape(m['licitacion_id'].split(':')[-1].split('|')[0][-6:]), t)) if m['licitacion_id'] else False ad = [x for x in ad if 'Ver detalle' not in x] # ficha con lotes: el resultado está en otra página (no legible) r['ficha_nof'] = nl; r['ficha_adj'] = ad existe = 'sí' if (nl or ad) else 'no legible' nofs = 'no legible' if not nl else ('coincide' if str(int(float(m['nof']))) in nl else 'NO coincide') if ad: ours = norm(m['adjudicatario_nombre']); best = max(len(ours & norm(a)) / max(1, min(len(ours), len(norm(a)))) for a in ad) nif_ok = bool(m['adjudicatario_nif']) and m['adjudicatario_nif'] in t adjs = 'coincide' if (best >= 0.6 or nif_ok) else 'NO coincide' r['sim'] = round(best, 2) else: adjs = 'no legible' vered = 'no legible' if 'no legible' in (nofs, adjs) and 'NO coincide' not in (nofs, adjs) else ('confirmado' if nofs == adjs == 'coincide' else 'contradicción') r.update({'existe': existe, 'nof': nofs, 'adj': adjs, 'veredicto': vered, 'nuestro_nof': m['nof']}); R.append(r) lote = 'sin lotes' if not m['lote_id'] else 'con lote' fn = (m['nof'] + ' → ' + '/'.join(nl)) if nl else m['nof'] + ' → —' L.append(f"| {m['cid']} | {m['grupo']} | {'propio' if m['feed']=='p' else 'agregación'} | {m['anio']} | {existe} | {fn} ({nofs}) | {adjs} | {vered} |") from collections import Counter cv = Counter(r['veredicto'] for r in R); leg = sum(1 for r in R if r['veredicto'] != 'no legible'); contra = cv.get('contradicción', 0) L += ['', f"**Resultado**: {cv.get('confirmado',0)} confirmados, {contra} contradicciones, {cv.get('no legible',0)} no legibles; " f"legibles {leg}. Umbral sellado: ≤ 2 contradicciones y ≥ 12 legibles → **{'PASA' if contra <= 2 and leg >= 12 else 'NO PASA'}**."] open('/w/salidas/50_cotejo.md', 'w').write('\n'.join(L) + '\n'); json.dump(R, open('/w/interno/cotejo/lectura.json', 'w'), ensure_ascii=False, indent=1) print('\n'.join(L[-23:]))