Download licitabench/ciegas.py from Changetheblock/LicitaBench: direct link, hf CLI and curl.
- Browser
- Download file 35.7 kB
-
https://huggingface.co/datasets/Changetheblock/LicitaBench/resolve/main/licitabench/ciegas.py
- Command line
-
hf download hf://datasets/Changetheblock/LicitaBench/licitabench/ciegas.py
-
curl -L -o ciegas.py https://huggingface.co/datasets/Changetheblock/LicitaBench/resolve/main/licitabench/ciegas.py
35.7 kB
| """Revisión previa de Codex y muestra a ciegas. | |
| Dos piezas que acompañan a la verificación humana (verificar.py): | |
| 1. Revisión previa por IA. Codex contrasta las etiquetas propuestas por Claude con el | |
| pliego y deja su opinión en verificacion/revision_codex.jsonl, una línea por item | |
| (si hay varias para el mismo item, vale la última). Codex nunca escribe en | |
| pendientes.jsonl ni en verificados.jsonl. Formato de cada línea: | |
| {"id_verificacion": "T2-placsp-...", "revisor": "Codex", "modelo": "...", "fecha": "AAAA-MM-DD", | |
| "veredicto": "conforme" | "corregir" | "duda" | "no_verificable", | |
| "etiquetas_corregidas": {mismo esquema que etiquetas_propuestas} o null, | |
| "cambios": [{"campo": "criterios[2].puntos", "antes": 20, "despues": 25, "evidencia": "cita del pliego"}], | |
| "dudas": ["..."], "evidencia": ["cita del pliego que sostiene la etiqueta"]} | |
| 2. Muestra a ciegas. Una persona etiqueta N items de una tarea leyendo solo el pliego, | |
| sin ver lo que propusieron Claude ni Codex. Después se mide el acuerdo entre esa | |
| etiqueta y las de los modelos. Mientras un item de la muestra no esté anotado a | |
| ciegas, verificar.py no deja verificarlo (verlo antes rompería el experimento). | |
| Uso: | |
| python -m licitabench.ciegas preparar --tarea T2 --n 20 | |
| python -m licitabench.ciegas anotar --por "Nombre Apellido" | |
| python -m licitabench.ciegas comparar | |
| python -m licitabench.ciegas preparar --tarea T3 --n 10 --excluir 19900117,19779433 | |
| python -m licitabench.ciegas anotar --tarea T3 --por "Nombre Apellido" | |
| python -m licitabench.ciegas comparar --tarea T3 | |
| python -m licitabench.ciegas anotar --tarea T4 --por "Nombre Apellido" # sí, no o ambigua | |
| Cada tarea tiene su propia muestra (T2 en muestra_ciega.json, las demás en | |
| muestra_ciega_<tarea>.json) y su propio informe de acuerdo. Las anotaciones de todas las | |
| tareas van a ciegas.jsonl, cada una con su tarea. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import hashlib | |
| import json | |
| import re | |
| import time | |
| from pathlib import Path | |
| from typing import Dict, List, Optional | |
| from . import metricas, revision, tareas | |
| from .evaluate import RUTA_PENDIENTES, RUTA_VERIFICADOS, _leer_jsonl | |
| RUTA_CODEX = Path("verificacion/revision_codex.jsonl") | |
| RUTA_MUESTRA = Path("verificacion/muestra_ciega.json") | |
| RUTA_CIEGAS = Path("verificacion/ciegas.jsonl") | |
| RUTA_ACUERDO = Path("verificacion/acuerdo_ciego.md") | |
| VEREDICTOS = {"conforme", "corregir", "duda", "no_verificable"} | |
| PLANTILLA_T2 = { | |
| "_ayuda": ("Rellena con lo que dice el pliego. tipo: automatico o juicio_valor. es_precio: true solo " | |
| "para la oferta económica. Añade o borra criterios. Si dejas puntos_automaticos o " | |
| "puntos_juicio_valor en null se calculan sumando. Esta línea se borra sola."), | |
| "criterios": [ | |
| {"nombre": "", "puntos": None, "tipo": "automatico", "es_precio": True}, | |
| {"nombre": "", "puntos": None, "tipo": "juicio_valor", "es_precio": False}, | |
| ], | |
| "puntos_automaticos": None, | |
| "puntos_juicio_valor": None, | |
| "formula_precio": None, | |
| "umbral_minimo_tecnico": None, | |
| } | |
| NIVELES_ENS = ("BÁSICO", "MEDIO", "ALTO") | |
| PLANTILLA_T3 = { | |
| "_ayuda": ("Rellena con lo que dice el pliego, según las reglas de T3 de verificacion/README.md. " | |
| "umbral_importe: volumen anual de negocios mínimo en euros o null. certificaciones: nombre de la " | |
| "lista " + ", ".join(tareas.CERTIFICACIONES) + "; nivel solo para ENS (BÁSICO, MEDIO, ALTO). Esta línea se borra sola."), | |
| "solvencia_economica": {"exigida": True, "umbral_importe": None, "descripcion": None}, | |
| "solvencia_tecnica": {"exigida": True, "descripcion": None}, | |
| "certificaciones": [], | |
| "habilitacion_empresarial": {"exigida": False, "descripcion": None}, | |
| } | |
| PLANTILLA_T4 = { | |
| "_ayuda": ("Responde a la pregunta de la mesa solo con el PCAP, según las reglas de T4 de verificacion/README.md: " | |
| "respuesta si, no o ambigua (si admite dos lecturas o falta información); justificación con la cláusula. " | |
| "Esta línea se borra sola."), | |
| "respuesta": "si | no | ambigua", | |
| "justificacion": "", | |
| } | |
| RESPUESTAS_T4 = ("si", "no", "ambigua") | |
| def ruta_muestra(tarea: str) -> Path: | |
| """T2 conserva su fichero de siempre; las demás tareas tienen el suyo.""" | |
| return RUTA_MUESTRA if tarea == "T2" else RUTA_MUESTRA.with_name(f"muestra_ciega_{tarea}.json") | |
| def ruta_acuerdo(tarea: str) -> Path: | |
| return RUTA_ACUERDO if tarea == "T2" else RUTA_ACUERDO.with_name(f"acuerdo_ciego_{tarea}.md") | |
| # ------------------------------------------------------------ revisión de Codex | |
| def revisiones_codex(ruta: Optional[Path] = None) -> Dict[str, Dict]: | |
| """Última revisión de Codex por id_verificacion.""" | |
| out: Dict[str, Dict] = {} | |
| for r in _leer_jsonl(ruta or RUTA_CODEX): | |
| if r.get("id_verificacion"): | |
| out[r["id_verificacion"]] = r | |
| return out | |
| def resumen_revision_previa(rev: Optional[Dict]) -> Optional[Dict]: | |
| """Lo que se guarda en el item verificado sobre la revisión previa.""" | |
| if not rev: | |
| return None | |
| return {"revisor": rev.get("revisor") or "Codex", "modelo": rev.get("modelo"), "fecha": rev.get("fecha"), | |
| "veredicto": rev.get("veredicto"), "propone_cambios": bool(rev.get("etiquetas_corregidas")), | |
| "n_cambios": len(rev.get("cambios") or []), "n_dudas": len(rev.get("dudas") or [])} | |
| def bloque_codex(rev: Optional[Dict]) -> str: | |
| """Texto para la pantalla de verificación.""" | |
| if not rev: | |
| return "Revisión previa de Codex: no hay." | |
| L = [f"Revisión previa de {rev.get('revisor') or 'Codex'} ({rev.get('modelo') or 'modelo sin dato'}, {rev.get('fecha') or '?'}): " | |
| f"{rev.get('veredicto') or 'sin veredicto'}"] | |
| for c in rev.get("cambios") or []: | |
| L.append(f"- Cambio en {c.get('campo')}: {c.get('antes')!r} pasa a {c.get('despues')!r}. Evidencia: {c.get('evidencia') or 'sin cita'}") | |
| for d in rev.get("dudas") or []: | |
| L.append(f"- Duda: {d}") | |
| for e in (rev.get("evidencia") or [])[:3]: | |
| L.append(f"- Evidencia: {e}") | |
| if rev.get("etiquetas_corregidas"): | |
| L.append("Codex propone etiquetas corregidas: tecla [x] para verlas y aceptarlas.") | |
| return "\n".join(L) | |
| # ------------------------------------------------------------------ muestra | |
| def _orden_estable(id_: str, semilla: int) -> str: | |
| return hashlib.sha256(f"{semilla}:{id_}".encode("utf-8")).hexdigest() | |
| _ORDEN_ORIGINAL: Dict[str, int] = {} | |
| def _orden_cola(id_: str) -> int: | |
| """Posición del item en la cola tal como se generó (la de REVISAR.md), guardada en orden_cola.""" | |
| if not _ORDEN_ORIGINAL: | |
| import subprocess | |
| try: | |
| orig = subprocess.run(["git", "show", "375c54b:verificacion/pendientes.jsonl"], capture_output=True, text=True, check=True).stdout | |
| for k, l in enumerate(x for x in orig.splitlines() if x.strip()): | |
| _ORDEN_ORIGINAL[json.loads(l)["id_verificacion"]] = k | |
| except Exception: | |
| pass | |
| return _ORDEN_ORIGINAL.get(id_, 10 ** 6) | |
| def preparar(tarea: str, n: int, semilla: int = 7, ruta: Optional[Path] = None, saltar_primeros: int = 0, | |
| excluir: Optional[List[str]] = None) -> List[str]: | |
| """Elige n items pendientes de la tarea (nunca uno ya verificado) con un orden estable. | |
| saltar_primeros deja fuera los primeros items de la tarea en el orden de la cola, que son los | |
| que REVISAR.md enseña con la propuesta de Claude: quien los haya leído ya no los ve a ciegas. | |
| excluir deja fuera items concretos (id de PLACSP o id_verificacion) cuyo contenido ya conoce | |
| quien va a anotar; quedan registrados en la muestra. | |
| """ | |
| ruta = ruta or ruta_muestra(tarea) | |
| if ruta.exists(): | |
| raise SystemExit(f"Ya existe {ruta}: la muestra no se cambia una vez hecha.") | |
| verificados = {r["id_verificacion"] for r in _leer_jsonl(RUTA_VERIFICADOS)} | |
| de_la_tarea = [r["id_verificacion"] for r in _leer_jsonl(RUTA_VERIFICADOS) + _leer_jsonl(RUTA_PENDIENTES) if r["tarea"] == tarea] | |
| vistos = set(sorted(de_la_tarea, key=_orden_cola)[:saltar_primeros]) | |
| fuera = set() | |
| for x in excluir or []: | |
| x = str(x).strip() | |
| if x: | |
| fuera.add(x if x.startswith(tarea + "-") else f"{tarea}-placsp-{x.replace('placsp-', '')}") | |
| vistos |= fuera | |
| candidatos = [r["id_verificacion"] for r in _leer_jsonl(RUTA_PENDIENTES) | |
| if r["tarea"] == tarea and r["id_verificacion"] not in verificados and r["id_verificacion"] not in vistos] | |
| ids = sorted(candidatos, key=lambda i: _orden_estable(i, semilla))[:n] | |
| datos = {"tarea": tarea, "n": len(ids), "semilla": semilla, "saltados_por_vistos": sorted(vistos), "fecha": time.strftime("%Y-%m-%d"), "ids": ids} | |
| if fuera: | |
| datos["excluidos_por_contenido_conocido"] = sorted(fuera) | |
| ruta.write_text(json.dumps(datos, ensure_ascii=False, indent=1) + "\n", encoding="utf-8") | |
| return ids | |
| def sustituir(id_: str, motivo: str, ruta: Optional[Path] = None, tarea: str = "T2") -> str: | |
| """Saca un item de la muestra (por ejemplo, porque su documento no contiene los criterios) | |
| y pone en su lugar el siguiente candidato en el mismo orden estable. Queda registrado en | |
| "excluidos" con el motivo. Devuelve el id del sustituto.""" | |
| ruta = ruta or ruta_muestra(tarea) | |
| m = json.loads(ruta.read_text(encoding="utf-8")) | |
| if id_ not in m["ids"]: | |
| raise SystemExit(f"{id_} no está en la muestra.") | |
| if not motivo or not motivo.strip(): | |
| raise SystemExit("Hace falta un motivo.") | |
| excluidos = m.setdefault("excluidos", []) | |
| fuera = set(m["ids"]) | {e["id"] for e in excluidos} | set(m.get("saltados_por_vistos", [])) | |
| fuera |= {r["id_verificacion"] for r in _leer_jsonl(RUTA_VERIFICADOS)} | |
| candidatos = [r["id_verificacion"] for r in _leer_jsonl(RUTA_PENDIENTES) | |
| if r["tarea"] == m["tarea"] and r["id_verificacion"] not in fuera] | |
| if not candidatos: | |
| raise SystemExit("No quedan candidatos para sustituir.") | |
| nuevo = sorted(candidatos, key=lambda i: _orden_estable(i, m["semilla"]))[0] | |
| m["ids"] = [nuevo if i == id_ else i for i in m["ids"]] | |
| excluidos.append({"id": id_, "motivo": motivo.strip(), "sustituido_por": nuevo, "fecha": time.strftime("%Y-%m-%d")}) | |
| ruta.write_text(json.dumps(m, ensure_ascii=False, indent=1) + "\n", encoding="utf-8") | |
| return nuevo | |
| def muestra(ruta: Optional[Path] = None, tarea: Optional[str] = None) -> List[str]: | |
| """Ids de la muestra de una tarea; sin tarea ni ruta, los de todas las tareas (T2 primero).""" | |
| if ruta is None and tarea is None: | |
| out: List[str] = [] | |
| for t in ("T2", "T3", "T4"): | |
| out += muestra(tarea=t) | |
| return out | |
| ruta = ruta or ruta_muestra(tarea) | |
| if not ruta.exists(): | |
| return [] | |
| return json.loads(ruta.read_text(encoding="utf-8")).get("ids", []) | |
| def anotadas(ruta: Optional[Path] = None) -> Dict[str, Dict]: | |
| return {r["id_verificacion"]: r for r in _leer_jsonl(ruta or RUTA_CIEGAS)} | |
| def bloqueados_por_ciegas() -> set: | |
| """Items de la muestra que aún no tienen anotación a ciegas: no se pueden verificar todavía.""" | |
| hechas = anotadas() | |
| return {i for i in muestra() if i not in hechas} | |
| def completar_sumas(et: Dict) -> Dict: | |
| et = {k: v for k, v in et.items() if not k.startswith("_")} | |
| for clave, tipo in (("puntos_automaticos", "automatico"), ("puntos_juicio_valor", "juicio_valor")): | |
| if et.get(clave) is None: | |
| crit = et.get("criterios") or [] | |
| pts = [c.get("puntos") for c in crit if c.get("tipo") == tipo] | |
| if pts and all(isinstance(p, (int, float)) for p in pts): | |
| et[clave] = float(sum(pts)) | |
| elif crit and not pts and all(isinstance(c.get("puntos"), (int, float)) for c in crit): | |
| et[clave] = 0.0 # todos los criterios tienen puntos y ninguno es de este tipo | |
| return et | |
| def validar_t2(et: Dict) -> Optional[str]: | |
| """Devuelve el problema si la anotación no cumple el esquema de T2.""" | |
| crit = et.get("criterios") | |
| if not isinstance(crit, list) or not crit: | |
| return "hace falta al menos un criterio" | |
| for k, c in enumerate(crit, 1): | |
| if not any(ch.isalnum() for ch in str(c.get("nombre") or "")): | |
| return f"el criterio {k} no tiene nombre (sin letras ni números)" | |
| if c.get("tipo") not in ("automatico", "juicio_valor"): | |
| return f"el criterio {k} tiene un tipo que no es automatico ni juicio_valor" | |
| if c.get("puntos") is not None and not isinstance(c.get("puntos"), (int, float)): | |
| return f"los puntos del criterio {k} no son un número" | |
| if not isinstance(c.get("es_precio"), bool): | |
| return f"es_precio del criterio {k} tiene que ser true o false" | |
| return None | |
| def guardar_anotacion(id_verificacion: str, tarea: str, por: str, etiquetas: Dict, ruta: Optional[Path] = None) -> Dict: | |
| if not por or not por.strip(): | |
| raise SystemExit("--por es obligatorio") | |
| reg = {"id_verificacion": id_verificacion, "tarea": tarea, "anotado_por": por.strip(), | |
| "fecha": time.strftime("%Y-%m-%d"), "etiquetas": etiquetas} | |
| with (ruta or RUTA_CIEGAS).open("a", encoding="utf-8") as f: | |
| f.write(json.dumps(reg, ensure_ascii=False) + "\n") | |
| return reg | |
| def _numero(s: str) -> Optional[float]: | |
| s = s.strip().replace(" ", "") | |
| if not s: | |
| return None | |
| if "," in s: | |
| s = s.replace(".", "").replace(",", ".") | |
| try: | |
| v = float(s) | |
| except ValueError: | |
| raise ValueError(s) | |
| return int(v) if v == int(v) else v | |
| def _limpiar(s: str) -> str: | |
| """Quita lo que meten las flechas, Escape y otras teclas especiales del terminal.""" | |
| s = re.sub(r"\x1b\[[0-9;]*[A-Za-z~]|\x1b[O]?[A-Za-z]?", "", s or "") | |
| return "".join(ch for ch in s if ch.isprintable()).strip() | |
| def preguntar_t2(entrada=input) -> Optional[Dict]: | |
| """Anotación guiada de T2: pregunta criterio a criterio. Devuelve None si se cancela.""" | |
| while True: | |
| print("Escribe lo que dice el pliego. Criterios de primer nivel, sin subcriterios. " | |
| "Deja el nombre vacío y pulsa Enter para terminar la lista.") | |
| criterios: List[Dict] = [] | |
| while True: | |
| nombre = _limpiar(entrada(f"Criterio {len(criterios) + 1}, nombre: ")) | |
| if not nombre: | |
| if criterios: | |
| break | |
| print("Hace falta al menos un criterio."); continue | |
| while True: | |
| try: | |
| puntos = _numero(entrada(" Puntos (Enter si el pliego no los da): ")); break | |
| except ValueError: | |
| print(" Escribe solo el número, por ejemplo 25 o 12,5.") | |
| while True: | |
| r = entrada(" ¿Automático por fórmula (a) o juicio de valor (j)? ").strip().lower() | |
| if r in ("a", "j"): | |
| break | |
| tipo = "automatico" if r == "a" else "juicio_valor" | |
| es_precio = tipo == "automatico" and entrada(" ¿Es el precio u oferta económica? [s/n] ").strip().lower() == "s" | |
| criterios.append({"nombre": nombre, "puntos": puntos, "tipo": tipo, "es_precio": es_precio}) | |
| formula = _limpiar(entrada("Fórmula del precio tal como la escribe el pliego (Enter si no hay): ")) or None | |
| umbral = _limpiar(entrada("Puntuación técnica mínima para seguir, si la hay (Enter si no hay): ")) or None | |
| et = completar_sumas({"criterios": criterios, "puntos_automaticos": None, "puntos_juicio_valor": None, | |
| "formula_precio": formula, "umbral_minimo_tecnico": umbral}) | |
| print("\nResumen:") | |
| for c in criterios: | |
| print(f"- {c['nombre']}: {c['puntos'] if c['puntos'] is not None else 'sin puntos'} " | |
| f"({'precio' if c['es_precio'] else c['tipo'].replace('_', ' ')})") | |
| print(f"Automáticos {et['puntos_automaticos']} | Juicio de valor {et['puntos_juicio_valor']} | " | |
| f"Fórmula: {formula or 'ninguna'} | Umbral: {umbral or 'ninguno'}") | |
| r = entrada("¿Guardar? [s] sí [r] repetir este item [x] cancelar: ").strip().lower() | |
| if r == "s": | |
| return et | |
| if r == "x": | |
| return None | |
| def validar_t3(et: Dict) -> Optional[str]: | |
| """Devuelve el problema si la anotación no cumple el esquema de T3.""" | |
| for clave in ("solvencia_economica", "solvencia_tecnica", "habilitacion_empresarial"): | |
| bloque = et.get(clave) | |
| if not isinstance(bloque, dict): | |
| return f"falta {clave}" | |
| if not isinstance(bloque.get("exigida"), bool): | |
| return f"{clave}.exigida tiene que ser true o false" | |
| u = et["solvencia_economica"].get("umbral_importe") | |
| if u is not None and (isinstance(u, bool) or not isinstance(u, (int, float))): | |
| return "umbral_importe no es un número" | |
| certs = et.get("certificaciones") | |
| if not isinstance(certs, list): | |
| return "certificaciones tiene que ser una lista (vacía si no hay)" | |
| for k, c in enumerate(certs, 1): | |
| if c.get("nombre") not in tareas.CERTIFICACIONES: | |
| return f"la certificación {k} no es de la lista: {', '.join(tareas.CERTIFICACIONES)}" | |
| if c.get("nombre") == "ENS" and str(c.get("nivel") or "").upper() not in NIVELES_ENS: | |
| return f"la certificación {k} es ENS y le falta el nivel (BÁSICO, MEDIO o ALTO)" | |
| if not isinstance(c.get("obligatoria"), bool): | |
| return f"obligatoria de la certificación {k} tiene que ser true o false" | |
| return None | |
| def limpiar_t3(et: Dict) -> Dict: | |
| """Quita las claves de ayuda y completa los campos opcionales del esquema.""" | |
| et = {k: v for k, v in et.items() if not k.startswith("_")} | |
| et.setdefault("certificaciones", []) | |
| for c in et["certificaciones"]: | |
| c.setdefault("nivel", None); c.setdefault("detalle", None) | |
| for clave in ("solvencia_economica", "solvencia_tecnica", "habilitacion_empresarial"): | |
| if isinstance(et.get(clave), dict): | |
| et[clave].setdefault("descripcion", None) | |
| if isinstance(et.get("solvencia_economica"), dict): | |
| et["solvencia_economica"].setdefault("umbral_importe", None) | |
| return et | |
| def _si_no(entrada, pregunta: str) -> bool: | |
| while True: | |
| r = entrada(pregunta).strip().lower() | |
| if r in ("s", "n"): | |
| return r == "s" | |
| def preguntar_t3(entrada=input) -> Optional[Dict]: | |
| """Anotación guiada de T3: solvencias, certificaciones y habilitación. None si se cancela.""" | |
| while True: | |
| print("Escribe lo que dice el pliego, según las reglas de T3 (lote 1 si hay lotes).") | |
| se = {"exigida": _si_no(entrada, "¿Exige solvencia económica? [s/n] "), "umbral_importe": None, "descripcion": None} | |
| if se["exigida"]: | |
| while True: | |
| try: | |
| se["umbral_importe"] = _numero(entrada(" Volumen anual de negocios mínimo en euros (Enter si no hay cifra): ")); break | |
| except ValueError: | |
| print(" Escribe solo el número, por ejemplo 150000 o 107.750,00.") | |
| se["descripcion"] = _limpiar(entrada(" Descripción breve (Enter para omitir): ")) or None | |
| st = {"exigida": _si_no(entrada, "¿Exige solvencia técnica? [s/n] "), "descripcion": None} | |
| if st["exigida"]: | |
| st["descripcion"] = _limpiar(entrada(" Descripción breve (Enter para omitir): ")) or None | |
| certs: List[Dict] = [] | |
| lista = " ".join(f"[{k}] {n}" for k, n in enumerate(tareas.CERTIFICACIONES, 1)) | |
| print(f"Certificaciones exigidas o que puntúan. {lista}") | |
| while True: | |
| r = entrada(f"Certificación {len(certs) + 1}: número de la lista (Enter si no hay más): ").strip() | |
| if not r: | |
| break | |
| if not r.isdigit() or not 1 <= int(r) <= len(tareas.CERTIFICACIONES): | |
| print(" Escribe un número de la lista."); continue | |
| nombre = tareas.CERTIFICACIONES[int(r) - 1] | |
| nivel = None | |
| if nombre == "ENS": | |
| while True: | |
| n = entrada(" Nivel: [b] BÁSICO [m] MEDIO [a] ALTO: ").strip().lower() | |
| if n in ("b", "m", "a"): | |
| nivel = {"b": "BÁSICO", "m": "MEDIO", "a": "ALTO"}[n]; break | |
| elif nombre == "otra": | |
| nivel = _limpiar(entrada(" Nivel, si lo hay (Enter si no): ")) or None | |
| obligatoria = _si_no(entrada, " ¿Hace falta para ser admitido o adjudicatario (s) o solo puntúa (n)? ") | |
| detalle = _limpiar(entrada(" Detalle (para 'otra', qué es; Enter para omitir): ")) or None | |
| certs.append({"nombre": nombre, "nivel": nivel, "obligatoria": obligatoria, "detalle": detalle}) | |
| hab = {"exigida": _si_no(entrada, "¿Exige alguna habilitación, registro o autorización oficial? [s/n] "), "descripcion": None} | |
| if hab["exigida"]: | |
| hab["descripcion"] = _limpiar(entrada(" Cuál (Enter para omitir): ")) or None | |
| et = {"solvencia_economica": se, "solvencia_tecnica": st, "certificaciones": certs, "habilitacion_empresarial": hab} | |
| print("\nResumen:") | |
| print(f"- Solvencia económica: {'sí' if se['exigida'] else 'no'}" | |
| + (f", mínimo {se['umbral_importe']} €" if se["umbral_importe"] is not None else "")) | |
| print(f"- Solvencia técnica: {'sí' if st['exigida'] else 'no'}") | |
| for c in certs: | |
| print(f"- {c['nombre']}{' ' + c['nivel'] if c['nivel'] else ''}: {'obligatoria' if c['obligatoria'] else 'solo puntúa'}") | |
| print(f"- Habilitación: {'sí' if hab['exigida'] else 'no'}") | |
| r = entrada("¿Guardar? [s] sí [r] repetir este item [x] cancelar: ").strip().lower() | |
| if r == "s": | |
| return et | |
| if r == "x": | |
| return None | |
| def validar_t4(et: Dict) -> Optional[str]: | |
| """Devuelve el problema si la anotación no cumple el esquema de T4.""" | |
| r = str(et.get("respuesta") or "").strip().lower().replace("í", "i") | |
| if r not in RESPUESTAS_T4: | |
| return "respuesta tiene que ser si, no o ambigua" | |
| j = et.get("justificacion") | |
| if j is not None and not isinstance(j, str): | |
| return "justificacion tiene que ser texto" | |
| return None | |
| def limpiar_t4(et: Dict) -> Dict: | |
| et = {k: v for k, v in et.items() if not k.startswith("_")} | |
| et["respuesta"] = str(et.get("respuesta") or "").strip().lower().replace("í", "i") | |
| et["justificacion"] = _limpiar(str(et.get("justificacion") or "")) or None | |
| return et | |
| def preguntar_t4(entrada=input) -> Optional[Dict]: | |
| """Anotación guiada de T4: sí, no o ambigua, y la cláusula. None si se cancela.""" | |
| while True: | |
| print("Responde solo con el PCAP. Lo que la pregunta no menciona se da por cumplido.") | |
| r = "" | |
| while r not in ("s", "n", "a", "x"): | |
| r = entrada("¿Respuesta? [s] sí [n] no [a] ambigua o falta información [x] cancelar: ").strip().lower() | |
| if r == "x": | |
| return None | |
| respuesta = {"s": "si", "n": "no", "a": "ambigua"}[r] | |
| just = _limpiar(entrada("Cláusula o motivo (Enter para dejarlo vacío): ")) or None | |
| print(f"- Respuesta: {respuesta}" + (f" | {just}" if just else "")) | |
| ok = entrada("¿Guardar? [s] sí [r] repetir este item [x] cancelar: ").strip().lower() | |
| if ok == "s": | |
| return {"respuesta": respuesta, "justificacion": just} | |
| if ok == "x": | |
| return None | |
| _POR_TAREA = { | |
| "T2": {"preguntar": "preguntar_t2", "validar": "validar_t2", "plantilla": "PLANTILLA_T2", "limpiar": "completar_sumas", | |
| "buscar": r"criterios? de adjudicaci|criterios? de valoraci"}, | |
| "T3": {"preguntar": "preguntar_t3", "validar": "validar_t3", "plantilla": "PLANTILLA_T3", "limpiar": "limpiar_t3", | |
| "buscar": r"solvencia econ[oó]mica|solvencia|habilitaci[oó]n"}, | |
| "T4": {"preguntar": "preguntar_t4", "validar": "validar_t4", "plantilla": "PLANTILLA_T4", "limpiar": "limpiar_t4", | |
| "buscar": r"solvencia econ[oó]mica|solvencia|habilitaci[oó]n"}, | |
| } | |
| def _func(tarea: str, clave: str): | |
| if tarea not in _POR_TAREA: | |
| raise SystemExit(f"La muestra a ciegas no está preparada para {tarea}.") | |
| return globals()[_POR_TAREA[tarea][clave]] | |
| def _resumen_anotacion(tarea: str, et: Dict) -> str: | |
| if tarea == "T2": | |
| crit = et.get("criterios") or [] | |
| return f"{len(crit)} criterios: " + ", ".join(_limpiar(str(c.get("nombre"))) or "(vacío)" for c in crit)[:80] | |
| if tarea == "T4": | |
| return f"respuesta {et.get('respuesta')}" | |
| se = et.get("solvencia_economica") or {} | |
| return (f"económica {se.get('umbral_importe')}, certificaciones " | |
| + (", ".join(c.get("nombre", "?") for c in et.get("certificaciones") or []) or "ninguna")) | |
| def corregir(por: str, numero: Optional[int] = None, entrada=input, tarea: str = "T2") -> None: | |
| """Vuelve a anotar un item ya anotado. La anotación nueva sustituye a la anterior | |
| (en ciegas.jsonl vale la última línea de cada item; la anterior queda como historial).""" | |
| ids = muestra(tarea=tarea) | |
| hechas = anotadas() | |
| hechos = [i for i in ids if i in hechas] | |
| if not hechos: | |
| print("Todavía no hay items anotados."); return | |
| if numero is None: | |
| print("Items anotados (número según el orden de la muestra):") | |
| for i in hechos: | |
| print(f" {ids.index(i) + 1:2d}. {i} {_resumen_anotacion(tarea, hechas[i]['etiquetas'])}") | |
| r = entrada("¿Qué número quieres volver a anotar? (Enter para salir): ").strip() | |
| if not r: | |
| return | |
| try: | |
| numero = int(r) | |
| except ValueError: | |
| print("Escribe solo el número."); return | |
| if not 1 <= numero <= len(ids) or ids[numero - 1] not in hechas: | |
| print(f"El número {numero} no corresponde a un item anotado."); return | |
| anotar(por, solo=[ids[numero - 1]], tarea=tarea) | |
| def anotar(por: str, solo: Optional[List[str]] = None, tarea: str = "T2") -> None: | |
| """Recorre la muestra mostrando solo el pliego, nunca las etiquetas de los modelos.""" | |
| from .verificar import _editar_json | |
| if not por or not por.strip(): | |
| raise SystemExit("--por es obligatorio") | |
| ids = muestra(tarea=tarea) | |
| if not ids: | |
| raise SystemExit(f"No hay muestra de {tarea}. Primero: python -m licitabench.ciegas preparar --tarea {tarea} --n 10") | |
| preguntar, validar, limpiar = _func(tarea, "preguntar"), _func(tarea, "validar"), _func(tarea, "limpiar") | |
| plantilla = _func(tarea, "plantilla") | |
| hechas = anotadas() | |
| regs = {r["id_verificacion"]: r for r in _leer_jsonl(RUTA_PENDIENTES) + _leer_jsonl(RUTA_VERIFICADOS)} | |
| faltan = list(solo) if solo else [i for i in ids if i not in hechas] | |
| if solo: | |
| print("Vuelves a anotar este item desde cero; al guardar, sustituye a lo que había.") | |
| else: | |
| print(f"Muestra a ciegas: {len(ids)} items, {len(ids) - len(faltan)} anotados, faltan {len(faltan)}.") | |
| print("Aquí no se enseña lo que propusieron los modelos. Teclas: [a] anotar respondiendo preguntas " | |
| "[t] más texto del pliego [o] abrir el PDF [e] anotar en un editor de texto (avanzado) [p] saltar [q] salir\n") | |
| for k, id_ in enumerate(faltan, 1): | |
| reg = regs.get(id_) | |
| if not reg: | |
| print(f"{id_} no está en la cola; se salta."); continue | |
| texto = revision.leer_texto(reg) | |
| print("=" * 100); print(f"[{k}/{len(faltan)}]") | |
| print("\n".join(l for l in revision.cabecera(reg) if not l.startswith("Expediente"))) | |
| if tarea == "T4": | |
| print(f"\nPREGUNTA DE LA MESA:\n{reg.get('pregunta') or '(sin pregunta)'}") | |
| if texto and tarea == "T2": | |
| sec = revision.fragmentos_t2(texto, {})["seccion"] | |
| print(f"\nSección de criterios del pliego:\n{sec or 'no localizada; usa [t] o [o]'}") | |
| elif texto: | |
| fr = revision.fragmentos_t3(texto, {}) | |
| for clave, rotulo in (("solvencia_economica", "Solvencia económica"), ("solvencia_tecnica", "Solvencia técnica"), | |
| ("habilitacion", "Habilitación")): | |
| print(f"\n{rotulo} (fragmento del pliego):\n{fr.get(clave) or 'no localizada; usa [t] o [o]'}") | |
| print("-" * 100) | |
| while True: | |
| r = input("¿Qué hago? [a] anotar [t] más texto [o] PDF [p] saltar [q] salir: ").strip().lower() | |
| if r == "a": | |
| et = preguntar() | |
| if et is None: | |
| continue | |
| problema = validar(et) | |
| if problema: | |
| print(f"No se guarda: {problema}."); continue | |
| guardar_anotacion(id_, reg["tarea"], por, et); print("Guardado."); break | |
| if r == "e": | |
| et = _editar_json(plantilla) | |
| if et is None: | |
| continue | |
| et = limpiar(et) | |
| problema = validar(et) | |
| if problema: | |
| print(f"No se guarda: {problema}. Vuelve a pulsar [e]."); continue | |
| guardar_anotacion(id_, reg["tarea"], por, et); print("Guardado."); break | |
| if r == "t": | |
| if texto is None: | |
| print("Sin texto local.") | |
| else: | |
| import re as _re | |
| m = _re.search(_POR_TAREA[tarea]["buscar"], texto, _re.I) | |
| ini = m.start() if m else 0 | |
| print(texto[ini: ini + 6000]); print("...") | |
| continue | |
| if r == "o": | |
| import webbrowser | |
| webbrowser.open(reg["documento"]["url"]); continue | |
| if r == "p": | |
| break | |
| if r == "q": | |
| return | |
| print() | |
| # ------------------------------------------------------------------ acuerdo | |
| def _media(vals: List[float]) -> Optional[float]: | |
| return sum(vals) / len(vals) if vals else None | |
| CLAVES_T3 = ["exactitud_solvencia_economica_exigida", "exactitud_umbral_solvencia_economica", "exactitud_solvencia_tecnica_exigida", | |
| "f1_certificaciones", "f1_certificaciones_con_obligatoriedad", "exactitud_habilitacion_exigida"] | |
| CLAVES_T4 = ["exactitud"] | |
| CABECERA_T4 = "| Fuente | n | Exactitud (sí/no) |" | |
| CABECERA_T3 = ("| Fuente | n | Económica exigida | Umbral (±1 %) | Técnica exigida | F1 certificaciones | " | |
| "F1 certificaciones con obligatoriedad | Habilitación |") | |
| def comparar(escribir: bool = True, tarea: str = "T2") -> Dict: | |
| """Acuerdo de la anotación a ciegas con Claude, con Codex y con la verificación final.""" | |
| medir = {"T2": metricas.metricas_t2, "T3": metricas.metricas_t3, "T4": metricas.metricas_t4}.get(tarea) | |
| if medir is None: | |
| raise SystemExit(f"La comparación a ciegas no está preparada para {tarea}.") | |
| hechas = anotadas() | |
| regs = {r["id_verificacion"]: r for r in _leer_jsonl(RUTA_PENDIENTES)} | |
| regs.update({r["id_verificacion"]: r for r in _leer_jsonl(RUTA_VERIFICADOS)}) | |
| codex = revisiones_codex() | |
| fuentes = {"claude": [], "codex": [], "verificacion_final": []} | |
| en_muestra = set(muestra(tarea=tarea)) | |
| ambiguas: List[str] = [] | |
| for id_, a in hechas.items(): | |
| if en_muestra and id_ not in en_muestra: | |
| continue | |
| reg = regs.get(id_) | |
| if not reg or reg.get("tarea") != tarea: | |
| continue | |
| gold = a["etiquetas"] | |
| if tarea == "T4" and gold.get("respuesta") == "ambigua": | |
| ambiguas.append(id_) | |
| continue | |
| fuentes["claude"].append(medir(gold, reg["etiquetas_propuestas"])) | |
| rev = codex.get(id_) | |
| if rev: | |
| fuentes["codex"].append(medir(gold, rev.get("etiquetas_corregidas") or reg["etiquetas_propuestas"])) | |
| if reg.get("estado") == "verificado" and reg.get("etiquetas_verificadas"): | |
| fuentes["verificacion_final"].append(medir(gold, reg["etiquetas_verificadas"])) | |
| claves = (["f1_criterios", "f1_criterios_puntos_tipo", "exactitud_puntos_automaticos", | |
| "exactitud_puntos_juicio_valor", "f1_tokens_formula_precio", "exactitud_umbral_presente"] | |
| if tarea == "T2" else CLAVES_T4 if tarea == "T4" else CLAVES_T3) | |
| res = {f: {"n": len(v), **{c: _media([m[c] for m in v]) for c in claves}} for f, v in fuentes.items()} | |
| if escribir: | |
| cabecera = ("| Fuente | n | F1 criterios | F1 puntos y tipo | Suma automáticos | Suma juicio de valor | Fórmula (F1 palabras) | Umbral |" | |
| if tarea == "T2" else CABECERA_T4 if tarea == "T4" else CABECERA_T3) | |
| L = [f"# Acuerdo de la anotación a ciegas ({tarea})", "", | |
| f"Generado el {time.strftime('%Y-%m-%d')} con `python -m licitabench.ciegas comparar{'' if tarea == 'T2' else ' --tarea ' + tarea}`. " | |
| "Referencia: lo que anotó una persona leyendo solo el pliego. Cada fila mide cuánto coincide otra fuente con esa referencia.", "", | |
| cabecera, "|---|---|" + "---|" * len(claves)] | |
| for f, v in res.items(): | |
| celdas = " | ".join("sin dato" if v[c] is None else f"{v[c] * 100:.1f} %" for c in claves) | |
| L.append(f"| {f} | {v['n']} | {celdas} |") | |
| if tarea == "T4": | |
| L += ["", f"Preguntas que quien anotó a ciegas marcó como ambiguas (fuera del cálculo): " | |
| f"{len(ambiguas)}{': ' + ', '.join(sorted(ambiguas)) if ambiguas else ''}."] | |
| ruta_acuerdo(tarea).write_text("\n".join(L) + "\n", encoding="utf-8") | |
| if tarea == "T4": | |
| res["ambiguas"] = sorted(ambiguas) | |
| return res | |
| def main(argv=None): | |
| ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) | |
| sub = ap.add_subparsers(dest="cmd", required=True) | |
| p = sub.add_parser("preparar"); p.add_argument("--tarea", default="T2"); p.add_argument("--n", type=int, default=20); p.add_argument("--semilla", type=int, default=7) | |
| p.add_argument("--saltar-primeros", type=int, default=0, help="dejar fuera los primeros N de la cola (vistos en REVISAR.md)") | |
| p.add_argument("--excluir", default="", help="ids separados por comas cuyo contenido ya conoce quien anota") | |
| p = sub.add_parser("anotar"); p.add_argument("--por", required=True); p.add_argument("--tarea", default="T2") | |
| p = sub.add_parser("sustituir", help="sacar un item de la muestra y poner el siguiente candidato") | |
| p.add_argument("--id", required=True); p.add_argument("--motivo", required=True); p.add_argument("--tarea", default="T2") | |
| p = sub.add_parser("corregir", help="volver a anotar un item ya guardado") | |
| p.add_argument("--por", required=True); p.add_argument("--numero", type=int, help="número del item en la muestra") | |
| p.add_argument("--tarea", default="T2") | |
| p = sub.add_parser("comparar"); p.add_argument("--tarea", default="T2") | |
| a = ap.parse_args(argv) | |
| if a.cmd == "preparar": | |
| ids = preparar(a.tarea, a.n, a.semilla, saltar_primeros=a.saltar_primeros, excluir=a.excluir.split(",")) | |
| print(f"Muestra de {len(ids)} items de {a.tarea} en {ruta_muestra(a.tarea)}") | |
| elif a.cmd == "anotar": | |
| anotar(a.por, tarea=a.tarea) | |
| elif a.cmd == "sustituir": | |
| print(f"Sustituido por {sustituir(a.id, a.motivo, tarea=a.tarea)}") | |
| elif a.cmd == "corregir": | |
| corregir(a.por, a.numero, tarea=a.tarea) | |
| else: | |
| comparar(tarea=a.tarea) | |
| print(ruta_acuerdo(a.tarea).read_text(encoding="utf-8")) | |
| if __name__ == "__main__": | |
| main() | |