File size: 9,454 Bytes
59a3f0d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
#!/usr/bin/env python3
"""Note-improver — MULTI-MODEL comparison (David's design).

Every candidate gets the SAME extensive clinical-report prompt (the real Athenea Data Extractor
note-generation prompt [B], transcript -> final report) and the SAME messy notes, and is scored on
the SAME rubric + objective fact-preservation. This is the honest "who writes the clinical report
best" test. Lulu is included as an OFF-TASK baseline (it is a small extraction model, not a
rewriter) — reported as such, never as the winner.

Candidates:
  - gpt-4.1          (OpenAI)
  - gpt-oss-120b     (Groq)
  - qwen3-27b        (Groq)
  - lulu-0.6b        (local, our model) — OFF-TASK baseline
  - claude-haiku     (Anthropic) — only if ANTHROPIC_API_KEY is set

Judges (rubric 0-5 x 5 dims): Qwen + gpt-oss (Groq), averaged; Opus calibration via Hera, GPT
excluded as a judge when it is also a candidate (self-judge). Objective preservation is a hard,
LLM-free number.

Run only on David's OK (it is compute). Usage:
  python eval_multimodel.py --n 40 --out results_multimodel.json
"""
import argparse, json, os, re, sys, time
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "common"))
import llm  # noqa: E402

HERE = os.path.dirname(os.path.abspath(__file__))
DIMS = ["preservacion_info", "formato_clinico", "sin_alucinacion", "legibilidad", "seguridad_clinica"]

# Extensive clinical-report prompt [B] from the SmartEpi Data Extractor (conversational scaffolding
# stripped: no greeting, no "what note type?" — input is a transcript, output is ONLY the report).
POLISH = (
    "Eres Athenea, la secretaria médica de un profesional de la salud. Recibes la TRANSCRIPCIÓN de "
    "una consulta médica (el médico dictando, o una conversación médico-paciente con interrupciones "
    "y correcciones). Tu tarea es elaborar el REPORTE FINAL de la historia clínica, que el médico "
    "copiará y pegará como documento legal. Reglas: usa SOLO la información de la transcripción, no "
    "inventes datos ni cifras; preserva TODO dato, dosis y valor exactamente; organiza en secciones "
    "clínicas estándar (Motivo de consulta, Enfermedad actual, Antecedentes, Examen físico, "
    "Paraclínicos, Análisis/Impresión diagnóstica, Plan); distingue el sujeto (lo del paciente vs un "
    "familiar); si el médico instruye explícitamente consignar algo, inclúyelo. NO menciones que "
    "eres una IA, NO uses frases como 'aquí tienes' ni conclusiones; entrega SOLO el reporte."
)
JUDGE_SYS = ("Eres un evaluador clínico. Puntúa la NOTA MEJORADA vs la NOTA ORIGINAL en 5 "
             "dimensiones 0-5. Devuelve SOLO JSON: "
             '{"preservacion_info":0-5,"formato_clinico":0-5,"sin_alucinacion":0-5,"legibilidad":0-5,'
             '"seguridad_clinica":0-5}. preservacion_info: ¿todo hecho/cifra del original está? '
             "sin_alucinacion: ¿NO agrega datos ausentes? formato_clinico: estructura/terminología. "
             "legibilidad: claridad. seguridad_clinica: no cambia unidades/negaciones/sentido.")

_lulu = None


def lulu_rewrite(messy):
    global _lulu
    import torch
    if _lulu is None:
        from transformers import AutoModelForCausalLM, AutoTokenizer
        from peft import PeftModel
        hf = json.load(open("/Users/davidesteban/Github/edeus-agents/shared/.secrets/huggingface.json"))["token"]
        tok = AutoTokenizer.from_pretrained("Qwen/Qwen3-0.6B", trust_remote_code=True, token=hf)
        if tok.pad_token is None:
            tok.pad_token = tok.eos_token
        m = AutoModelForCausalLM.from_pretrained("Qwen/Qwen3-0.6B", torch_dtype=torch.float32, token=hf)
        _lulu = (PeftModel.from_pretrained(m, "derebellon/edeus-lulu-qwen3", token=hf).merge_and_unload().eval(), tok)
    model, tok = _lulu
    p = tok.apply_chat_template([{"role": "system", "content": POLISH}, {"role": "user", "content": messy}],
                                tokenize=False, add_generation_prompt=True)
    ids = tok(p, return_tensors="pt", truncation=True, max_length=1200)
    with torch.no_grad():
        out = model.generate(**ids, max_new_tokens=500, do_sample=False, pad_token_id=tok.eos_token_id)
    return tok.decode(out[0][ids["input_ids"].shape[1]:], skip_special_tokens=True).strip()


def claude_haiku(messy):
    import urllib.request
    key = os.environ.get("ANTHROPIC_API_KEY", "")
    if not key:
        return None
    payload = json.dumps({"model": "claude-haiku-4-5-20251001", "max_tokens": 800,
                          "system": POLISH, "messages": [{"role": "user", "content": messy}]}).encode()
    req = urllib.request.Request("https://api.anthropic.com/v1/messages", data=payload,
          headers={"x-api-key": key, "anthropic-version": "2023-06-01", "content-type": "application/json"})
    return json.loads(urllib.request.urlopen(req, timeout=60).read())["content"][0]["text"]


def CANDIDATES():
    c = {
        "gpt-4.1": lambda m: llm.call_gpt(POLISH, m, model="gpt-4.1", max_tokens=800),
        # GPT-5 = CANDIDATE redactor only (NOT teacher, NOT judge — Hera 2026-11-21). Reasoning family:
        # larger completion budget so reasoning tokens don't truncate the ~800-token report.
        "gpt-5": lambda m: llm.call_gpt(POLISH, m, model="gpt-5", max_tokens=4000),
        "gpt-oss-120b": lambda m: llm.call_groq(POLISH, m, model="openai/gpt-oss-120b", max_tokens=800),
        "qwen3-27b": lambda m: llm.call_groq(POLISH, m, model="qwen/qwen3.8-27b", max_tokens=800),
        "lulu-0.6b (off-task)": lulu_rewrite,
    }
    if os.environ.get("ANTHROPIC_API_KEY"):
        c["claude-haiku"] = claude_haiku
    return c


def preservation(facts, improved):
    imp = improved.lower(); ok = 0
    for fact in facts:
        fl = fact.lower()
        nums = re.findall(r"\d+(?:[.,]\d+)?", fl)
        head = re.findall(r"[a-záéíóúñ]{4,}", fl)
        if (not head or head[0] in imp) and all(n in imp for n in nums):
            ok += 1
    return round(ok / len(facts), 3) if facts else None


def judges(original, improved):
    # Gold standard (David): strong judges = GPT-6 Astra + Opus. Astra runs here; Opus runs via Hera
    # on the calibration subset. qwen/gpt-oss kept as secondary sanity, averaged in only if Astra fails.
    u = f"NOTA ORIGINAL:\n{original}\n\nNOTA MEJORADA:\n{improved}"
    try:
        r = llm.call_gpt(JUDGE_SYS, u, json_mode=True, model="gpt-6-astra", max_tokens=300)
        s = {d: float(r[d]) for d in DIMS if isinstance(r.get(d), (int, float))}
        if len(s) == len(DIMS):
            return s
    except Exception:
        pass
    scores = []
    for fn, mdl in [(llm.call_groq, "qwen/qwen3.8-27b"), (llm.call_groq, "openai/gpt-oss-120b")]:
        try:
            r = fn(JUDGE_SYS, u, json_mode=True, model=mdl, max_tokens=200)
            s = {d: float(r[d]) for d in DIMS if isinstance(r.get(d), (int, float))}
            if len(s) == len(DIMS):
                scores.append(s)
        except Exception:
            pass
    if not scores:
        return {d: None for d in DIMS}
    return {d: round(sum(s[d] for s in scores) / len(scores), 2) for d in DIMS}


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--n", type=int, default=40)
    ap.add_argument("--out", default=os.path.join(HERE, "results_multimodel.json"))
    ap.add_argument("--calib", default=os.path.join(HERE, "calib_multimodel.jsonl"))
    args = ap.parse_args()
    rows = [json.loads(l) for l in open(os.path.join(HERE, "messy_notes.jsonl")) if l.strip()][:args.n]
    cands = CANDIDATES()
    print(f"candidates: {list(cands)} · n={len(rows)}")
    agg = {k: {"preservation": [], **{d: [] for d in DIMS}} for k in cands}
    calib = []
    t0 = time.time()
    for i, r in enumerate(rows):
        row_out = {"id": r["id"], "original": r["messy_note"]}
        for name, fn in cands.items():
            try:
                txt = fn(r["messy_note"]) or ""
            except Exception as e:
                txt = f"[error: {e}]"
            agg[name]["preservation"].append(preservation(r["facts"], txt))
            js = judges(r["messy_note"], txt)
            for d in DIMS:
                if js[d] is not None:
                    agg[name][d].append(js[d])
            if i < 15:
                row_out[name] = txt
        if i < 15:
            calib.append(row_out)
        print(f"  [{i+1}/{len(rows)}] ({time.time()-t0:.0f}s)")

    def mean(xs):
        xs = [x for x in xs if x is not None]
        return round(sum(xs) / len(xs), 3) if xs else None

    res = {"n": len(rows), "prompt": "SmartEpi Data Extractor [B] (transcript -> final report)",
           "judges": "GPT-6 Astra (OpenAI) + Opus (via Hera) = gold standard; qwen/gpt-oss fallback; Lulu = off-task baseline",
           "results": {}}
    for name, d in agg.items():
        rub = [mean(d[dim]) for dim in DIMS]
        res["results"][name] = {"preservation_objective": mean(d["preservation"]),
                                **{dim: mean(d[dim]) for dim in DIMS},
                                "rubric_overall": mean([x for x in rub if x is not None])}
    json.dump(res, open(args.out, "w"), indent=2, ensure_ascii=False)
    with open(args.calib, "w") as f:
        for c in calib:
            f.write(json.dumps(c, ensure_ascii=False) + "\n")
    print("\n===== MULTI-MODEL NOTE-IMPROVER =====")
    print(json.dumps(res, indent=2, ensure_ascii=False))


if __name__ == "__main__":
    main()