#!/usr/bin/env python3 """CAT-08 / T-53-SUSP · validación del lector con cita según lector/VALIDACION_REGLA.md (sellada antes de mirar). SEGUNDA IMPLEMENTACIÓN de la comprobación de citas y fechas: no importa anotar.py ni verifica.py (bloques, cita por secuencia de palabras, fechas por fichas). python3 -I valida.py [--consolidado priv/consolidacion/consolidado.jsonl] [--oro2 oro2/lectura_E/etiquetas_oro2.jsonl] Oro: los 40 del banco 2 (priv/banco2_lectura.jsonl a7a21849…) + los 40 de oro2 (etiquetador; cada cita del oro tiene que verificarse aquí o no se valida). Umbral: I correcta >= 76/80, 0 errores que alarguen la ventana, 100 % de citas verificables en lo aceptado. Imprime y escribe solo recuentos e ids (salidas/valida.json).""" import argparse, collections, datetime as dt, glob, hashlib, json, os, re, sys, unicodedata X = os.path.dirname(os.path.realpath(__file__)) L = os.path.dirname(X) O = os.path.dirname(L) LOTES = os.path.join(O, 'priv', 'lector_finv1', 'para_lector', 'lotes') REGLA, REGLA_MD5F = os.path.join(L, 'VALIDACION_REGLA_v2.md'), os.path.join(L, 'VALIDACION_REGLA_v2.md5') USAR_B2 = False # v2: el banco 2 y el oro2 están QUEMADOS; solo para pruebas B2_LECT, B2_SEL, B2_MD5 = os.path.join(O, 'priv', 'banco2_lectura.jsonl'), os.path.join(O, 'priv', 'banco2_sel.json'), 'a7a21849' ORO2_SEL = os.path.join(L, 'oro3', 'mapa', 'seleccion.json') ORO_N, ORO_NOMBRE = 80, 'oro3' ORO_LOTES = os.path.join(L, 'oro3', 'para_etiquetador', 'lotes') JUEZ_LOTES = os.path.join(L, 'juez_v2', 'lotes') # adenda 2: las citas del juez son del fragmento v1.1 # el oro se etiqueta sobre el fragmento F-INV v1.1 (adenda de la v2) ORO2_ETQ = [os.path.join(L, 'oro3', 'lectura_E', f'etiquetas_oro3{x}.jsonl') for x in 'ab'] CONS = os.path.join(L, 'priv', 'consolidacion_v2', 'consolidado.jsonl') SAL = os.path.join(L, 'salidas', 'valida_v2.json') N_ORO, UMBRAL_I = 80, 76 ACEPTA = ('aceptado', 'juez', 'indice') MES = {'enero': 1, 'febrero': 2, 'marzo': 3, 'abril': 4, 'mayo': 5, 'junio': 6, 'julio': 7, 'agosto': 8, 'septiembre': 9, 'setiembre': 9, 'octubre': 10, 'noviembre': 11, 'diciembre': 12, 'gener': 1, 'febrer': 2, 'març': 3, 'marc': 3, 'maig': 5, 'juny': 6, 'juliol': 7, 'agost': 8, 'setembre': 9, 'novembre': 11, 'desembre': 12} md5f = lambda p: hashlib.md5(open(p, 'rb').read()).hexdigest() def leer_bloques(d): """{id: (R date|None, [líneas crudas])}: recorre línea a línea; '### RESOLUCIÓN ' abre bloque.""" out, cur = {}, None for f in sorted(glob.glob(os.path.join(d, '*.txt'))): for ln in open(f, encoding='utf-8'): if ln.startswith('### RESOLUCIÓN '): rid = ln[len('### RESOLUCIÓN '):].split(' | ')[0].strip() m = re.search(r'fecha (\d{4})-(\d{2})-(\d{2})', ln) cur = out[rid] = (dt.date(int(m.group(1)), int(m.group(2)), int(m.group(3))) if m else None, []) elif cur is not None and ln.strip(): cur[1].append(ln) rc = os.path.join(L, 'paquete', 'R_cabecera.tsv') # dato (no código): fecha de v3 en la cabecera del texto entero si el índice no la trae tsv = {x.split('\t')[0]: x.split('\t')[1].strip() for x in open(rc, encoding='utf-8').read().splitlines()[1:]} if os.path.exists(rc) else {} for rid, (R, lns) in list(out.items()): if R is None and rid in tsv: y, m, d = map(int, tsv[rid].split('-')) out[rid] = (dt.date(y, m, d), lns); continue if R is None: # sin fecha en el índice: primera fecha con año de la cabecera (con R=None, fechas2 solo da fechas con año) cab = next((x for x in lns if x.startswith('[CABECERA]')), '') fs = fechas2(cab, None) if fs: pos = {d: min([i for i in (cab.find(str(d.day)),) if i >= 0] or [10 ** 6]) for d in fs} out[rid] = (min(fs, key=lambda d: pos[d]), lns) return out def palabras(s): return unicodedata.normalize('NFC', s or '').split() def literal2(cita, lineas): """Cita como secuencia contigua de palabras de una línea (la primera puede ser final de palabra y la última principio).""" c = palabras(cita) if not c or not 15 <= len(' '.join(c)) <= 300: return False n = len(c) for ln in lineas: w = palabras(ln) for i in range(len(w) - n + 1): if n == 1: if c[0] in w[i]: return True continue if w[i].endswith(c[0]) and w[i + n - 1].startswith(c[-1]) and w[i + 1:i + n - 1] == c[1:-1]: return True return False def fechas2(s, R): """Fechas por fichas («18 de abril de 2022», «3 d'abril», «1r de juny del 2023») y numéricas dd/mm/aaaa.""" t = unicodedata.normalize('NFC', s or '').lower().replace('’', "'") tk = re.findall(r"\d+|[a-zçñáéíóúàèòïü]+", t) out = set() for i, x in enumerate(tk): if not (x.isdigit() and len(x) <= 2): continue j = i + 1 if j < len(tk) and tk[j] in ('r', 'er', 'o'): j += 1 if j < len(tk) and tk[j] in ('de', 'd'): j += 1 if j >= len(tk) or tk[j] not in MES: continue mes, j, y = MES[tk[j]], j + 1, None while j < len(tk) and tk[j] in ('de', 'del', 'año', 'any') and j - i < 6: j += 1 if j < len(tk) and tk[j].isdigit() and len(tk[j]) == 4: y = int(tk[j]) try: if y is None: if R is None: continue d = dt.date(R.year, mes, int(x)) d = d if d <= R else dt.date(R.year - 1, mes, int(x)) else: d = dt.date(y, mes, int(x)) out.add(d) except ValueError: pass for m in re.finditer(r'(? g['R']: al.append('R_posterior') gl = g['L'] if gl[0] in ('levanta', 'previa', 'levanta_sin_fecha', 'no_dice') and pL and pL['estado'] == 'ninguna': al.append('L_omitida') if gl[0] == 'levanta' and gl[1] and pL and pL['estado'] == 'levanta' and pL['fecha'] and pL['fecha'] > gl[1]: al.append('L_posterior') for f, d in cp.items(): if d.get('estado') not in ACEPTA or not d.get('citas'): continue cit_tot += 1 v = d['v'] fe = v if f in ('I', 'R') else (v.get('fecha') if f == 'L' and isinstance(v, dict) and v.get('estado') == 'levanta' else None) bl = Bk[rid] bueno = all(literal2(x, bl[1] + Bj.get(rid, (None, []))[1]) for x in d['citas']) and (not fe or any(dt.date.fromisoformat(fe) in fechas2(x, bl[0]) for x in d['citas'])) cit_ok += bueno if not bueno: k['cita_no_verificable_' + f] += 1 fuente_A = I.get('A'); fuente_B = I.get('B'); fuente_v3 = I.get('tercero') k['acierto_I'] += ok; k['alarga'] += bool(al); k['oro_no_consta'] += g['I'] is None; k['pipeline_no_consta'] += pI is None k['A_acierta_I'] += fuente_A == g['I']; k['B_acierta_I'] += fuente_B == g['I']; k['v3_acierta_I'] += fuente_v3 == g['I'] k['estado_I_' + str(I.get('estado'))] += 1 k[f'{g["fuente"]}_acierto_I'] += ok k[f'{c.get("tribunal")}_n'] += 1; k[f'{c.get("tribunal")}_acierto_I'] += ok filas.append(dict(id=rid, fuente=g['fuente'], acierto_I=ok, estado_I=I.get('estado'), alarga=al, signo=None if ok or not (pI and g['I']) else ('anterior' if pI < g['I'] else 'posterior'))) n = len(filas) pasa = not prob and n == n_oro and k['acierto_I'] >= umbral and k['alarga'] == 0 and cit_tot > 0 and cit_ok == cit_tot out = dict(regla=md5f(REGLA) if os.path.exists(REGLA) else None, n=n, I_correctas=k['acierto_I'], umbral_I=f'>= {umbral}/{n_oro}', errores_que_alargan=k['alarga'], citas_verificables=f'{cit_ok}/{cit_tot}', pasa=pasa, problemas=prob, diagnostico={x: v for x, v in sorted(k.items()) if x not in ('acierto_I', 'alarga')}, errores=[f for f in filas if not f['acierto_I'] or f['alarga']], entradas=dict(consolidado=md5f(cons) if os.path.exists(cons) else None, oro=[md5f(p) for p in (etq if isinstance(etq, (list, tuple)) else [etq]) if p and os.path.exists(p)], banco2=md5f(B2_LECT)), codigo=md5f(os.path.realpath(__file__))) if salida: json.dump(out, open(salida, 'w', encoding='utf-8'), ensure_ascii=False, indent=1) print(json.dumps({x: out[x] for x in ('n', 'I_correctas', 'umbral_I', 'errores_que_alargan', 'citas_verificables', 'pasa')}, ensure_ascii=False)) if prob: print('PROBLEMAS (no se valida):', prob[:10]) return out def main(argv=None): ap = argparse.ArgumentParser() ap.add_argument('--consolidado', default=CONS); ap.add_argument('--oro', nargs='*', default=ORO2_ETQ) a = ap.parse_args(argv) return 0 if validar(a.consolidado, a.oro)['pasa'] else 1 if __name__ == '__main__': sys.exit(main())