Repository navigation
Expand file tree
/
Copy pathcli.py
More file actions
66 lines (62 loc) · 3.2 KB
/
Copy pathcli.py
File metadata and controls
66 lines (62 loc) · 3.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""La misma máquina, desde la terminal. Corre todas las preguntas del set."""
import argparse, numpy as np, textwrap, rag
ap = argparse.ArgumentParser()
ap.add_argument("--estrategia", default="fija", choices=["fija", "oracion"])
ap.add_argument("--tamano", type=int, default=260)
ap.add_argument("--solape", type=int, default=0)
ap.add_argument("--k", type=int, default=3)
ap.add_argument("--contextual", action="store_true",
help="agrega un resumen situador a cada pedazo (necesita credencial)")
a = ap.parse_args()
if a.estrategia == "oracion":
a.solape = 0
if a.contextual and not rag.hay_modelo():
raise SystemExit("--contextual necesita ANTHROPIC_API_KEY")
ped, indexados, _, costo_idx = rag.indice(a.estrategia, a.tamano, a.solape, a.contextual)
print(f"estrategia={a.estrategia} tamaño={a.tamano} solape={a.solape} k={a.k}"
f"{' contextual' if a.contextual else ''}")
print(f"{len(rag.texto())} caracteres -> {len(ped)} pedazos")
if costo_idx:
print(f"contexto agregado a {len(ped)} pedazos · ${costo_idx:.4f} (se paga una vez)")
print()
acum, gasto, lat, sin_resp, neg = [], costo_idx, [], 0, 0
for p in rag.PREGUNTAS:
_, _, res, _ = rag.buscar(p["q"], a.estrategia, a.tamano, a.solape, a.k, a.contextual)
idx = [i for i, _ in res]
oro = rag.dorados(ped, p["requiere"])
print(f'❯ {p["q"]}')
if p["requiere"] is None:
print(" (la respuesta NO está en el texto)")
elif not oro:
print(" ⚠ NINGÚN pedazo contiene el dato entero — el corte lo partió")
for puesto, (i, s) in enumerate(res, 1):
print(f' {"★" if i in oro else " "} {puesto}º pedazo {i+1:2d} {s:.3f} {ped[i][:52].strip()}…')
if p["requiere"]:
m = rag.metricas(idx, oro, a.k); acum.append(m)
print(f' recall@{a.k} {m["recall"]:.2f} · precisión@{a.k} {m["precision"]:.2f} · MRR {m["mrr"]:.2f}')
r = rag.responder(p["q"], indexados, idx)
if r:
gasto += r["costo"]; lat.append(r["ms"])
print(f' → {textwrap.shorten(r["texto"], 92)}')
print(f' {r["tok_in"]}→{r["tok_out"]} tok · ${r["costo"]:.5f} · {r["ms"]:.0f} ms · cita {r["cita"]}')
if p["requiere"] is None:
sin_resp += 1; neg += int(r["rechazo"])
print()
print("═" * 74)
if acum:
imp = [m for m in acum if m["imposible"]]
vivas = [m for m in acum if not m["imposible"]]
print(f"RECUPERACIÓN — {len(acum)} preguntas que el TEXTO puede contestar")
for nom, key in (("recall", "recall"), ("precisión", "precision"), ("MRR", "mrr"), ("hit", "hit")):
print(f" {nom+f'@{a.k}':13s} {np.mean([m[key] for m in acum]):.3f}")
if imp:
print(f"\n ⚠ {len(imp)} de {len(acum)} quedaron IMPOSIBLES por el corte: cuentan 0.")
print(f" Si las sacaras del promedio, recall@{a.k} daría "
f"{np.mean([m['recall'] for m in vivas]):.3f} — y sería mentira.")
if lat:
print(f"GENERACIÓN\n se negó bien {neg}/{sin_resp} preguntas sin respuesta")
print(f" latencia {np.mean(lat):.0f} ms promedio")
print(f" costo total ${gasto:.4f}"
+ (f" (de los cuales ${costo_idx:.4f} fue armar el índice)" if costo_idx else ""))