"""INF-ORG · C1 · el cotejo (pre-registro PREREGISTRO_C1.md): por cada fila de la muestra, (a) la fecha más antigua de la tabla de documentos de la ficha frente a fecha_pub y (b) AwardDate de la última versión de la entrada de la sindicación frente a fecha_adj. Sin red. Uso: 75_cotejo_c1.py [cid,cid,…: los que se cotejan; por defecto, los principales]. Salida: priv/c1_cotejo.csv (con ids) y salidas/c1_cotejo.json (publicable: sin ids, ni órgano, ni objeto, ni expediente).""" import csv, datetime as dt, html, json, os, re, sys M = {r['cid']: r for r in csv.DictReader(open('/w/priv/c1_muestra.csv', encoding='utf-8'))} A = json.load(open('/w/priv/c1_atom.json')) cids = sys.argv[1].split(',') if len(sys.argv) > 1 else [c for c, r in M.items() if r['reserva'] == '0'] FECHA = re.compile(r'^(\d{2})/(\d{2})/(\d{4})( \d{2}:\d{2}(:\d{2})?)?$') def lineas(p): s = open(p, encoding='utf-8', errors='replace').read() s = re.sub(r'', '', s, flags=re.S); s = re.sub(r'', '', s, flags=re.S) s = re.sub(r'', '\n', s); s = re.sub(r'<[^>]+>', '\n', s); s = html.unescape(s) return [re.sub(r'\s+', ' ', l).strip() for l in s.split('\n') if l.strip()] def docs(ls): out = [] for i, l in enumerate(ls): m = FECHA.match(l) if m and i + 1 < len(ls) and not FECHA.match(ls[i + 1]): out.append((f'{m.group(3)}-{m.group(2)}-{m.group(1)}', ls[i + 1])) return out def fin_trim_sig(d): m = 3 * ((d.month - 1) // 3) + 1 + 6 return dt.date(d.year + (m - 1) // 12, (m - 1) % 12 + 1, 1) - dt.timedelta(days=1) filas = [] for cid in cids: r = M[cid]; f = f'/w/priv/c1_html/{cid}.html'; a = A.get(cid) or {} pub_ficha = None; nd = 0; primero = '' if os.path.exists(f) and os.path.getsize(f) > 5000: d = docs(lineas(f)); nd = len(d) if d: pub_ficha = min(x[0] for x in d); primero = next(x[1] for x in d if x[0] == pub_ficha)[:40] aw = a.get('award_ultima') or [] ok_pub = pub_ficha == r['fecha_pub'] if pub_ficha else None ok_adj = (r['fecha_adj'] in aw) if aw else None if ok_pub is None or ok_adj is None: v = 'no verificable' elif ok_pub and ok_adj: v = 'confirmada' else: v = 'discrepa' # Cambiaría de lado con las fechas de la Plataforma lado = None if pub_ficha and aw: fa = dt.date.fromisoformat(r['fecha_adj'] if r['fecha_adj'] in aw else aw[0]) lado = (dt.date.fromisoformat(pub_ficha) > fin_trim_sig(fa)) == (r['estrato'] == 'despues') filas.append({'cid': cid, 'estrato': r['estrato'], 'anio': r['anio'], 'veredicto': v, 'fecha_adj': r['fecha_adj'], 'adj_atom': '|'.join(aw), 'adj_ok': ok_adj, 'fecha_pub': r['fecha_pub'], 'pub_ficha': pub_ficha, 'pub_ok': ok_pub, 'documentos_ficha': nd, 'primer_documento': primero, 'mismo_lado': lado}) n_c = sum(x['veredicto'] == 'confirmada' for x in filas); n_d = sum(x['veredicto'] == 'discrepa' for x in filas); n_n = sum(x['veredicto'] == 'no verificable' for x in filas) with open('/w/priv/c1_cotejo.csv', 'w', newline='', encoding='utf-8') as h: w = csv.DictWriter(h, fieldnames=list(filas[0]) + ['id_canonical', 'url'], lineterminator='\n'); w.writeheader() for x in filas: w.writerow({**x, 'id_canonical': M[x['cid']]['id_canonical'], 'url': M[x['cid']]['url']}) pub = {'cotejadas': len(filas), 'confirmadas': n_c, 'discrepan': n_d, 'no_verificables': n_n, 'filas': [{k: x[k] for k in ('cid', 'estrato', 'anio', 'veredicto', 'adj_ok', 'pub_ok', 'documentos_ficha', 'primer_documento', 'mismo_lado')} for x in filas]} json.dump(pub, open('/w/salidas/c1_cotejo.json', 'w'), ensure_ascii=False, indent=1) print({k: v for k, v in pub.items() if k != 'filas'}) for x in filas: print(x['cid'], x['anio'], x['veredicto'], 'adj', x['fecha_adj'], x['adj_atom'], x['adj_ok'], 'pub', x['fecha_pub'], x['pub_ficha'], x['pub_ok'], 'docs', x['documentos_ficha'], x['primer_documento'][:24], 'lado', x['mismo_lado'])