File size: 3,800 Bytes
4f6d1c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""parse.py: read a model reply into {decision, confidence, ...}; the last JSON object with a decision field wins."""
import json, math, re

DONT, RUN = "don't run", "run"


def norm_decision(s):
    s = str(s or "").strip().lower().replace("’", "'").replace("‘", "'")
    s = re.sub(r"[\s_\-]+", " ", s).strip(" .!\"'`*")
    if s in ("don't run", "dont run", "do not run", "don't", "no run", "not run", "hold", "hold it back"):
        return DONT, s in ("hold", "hold it back")
    if s in ("run", "run it", "send", "send it"):
        return RUN, s in ("send", "send it")
    return None, False


def json_objects(text):
    """Every balanced {...} that parses as a JSON object, in order of appearance."""
    out = []
    for m in re.finditer(r"\{", text):
        depth, instr, esc = 0, False, False
        for j in range(m.start(), len(text)):
            c = text[j]
            if instr:
                esc = (c == "\\" and not esc)
                if c == '"' and not esc:
                    instr = False
                continue
            if c == '"':
                instr = True
            elif c == "{":
                depth += 1
            elif c == "}":
                depth -= 1
                if depth == 0:
                    try:
                        o = json.loads(text[m.start():j + 1])
                        if isinstance(o, dict):
                            out.append(o)
                    except ValueError:
                        pass
                    break
    return out


def parse_answer(text):
    """{"decision", "confidence", "key_condition", "reason", "decisive_records", "how", "legacy_label", "conf_rescaled"} or None."""
    t = re.sub(r"<think>.*?</think>", "", text or "", flags=re.S).strip()
    if not t:
        return None
    objs = [o for o in json_objects(t) if "decision" in o]
    how = "json"
    if objs and re.search(r"```", t):
        how = "fenced_json"
    if objs:
        o = objs[-1]
        d, legacy = norm_decision(o.get("decision"))
        if d:
            conf, resc = norm_conf(o.get("confidence"))
            recs = o.get("decisive_records")
            recs = [str(r).strip() for r in recs] if isinstance(recs, list) else ([str(recs)] if recs else [])
            return {"decision": d, "confidence": conf, "key_condition": str(o.get("key_condition") or ""),
                    "reason": str(o.get("reason") or ""), "decisive_records": recs, "how": how,
                    "legacy_label": legacy, "conf_rescaled": resc}
    m = re.findall(r'"decision"\s*:\s*"([^"]{1,20})"', t, re.I)
    how = "decision_field"
    if not m:
        m = re.findall(r"\bdecision\b[\s:*\-=]{0,6}(don['’]?t run|do not run|run)\b", t, re.I)
        how = "decision_word"
    if not m and norm_decision(t)[0]:
        m, how = [t], "bare_word"
    if m:
        d, legacy = norm_decision(m[-1])
        if d:
            cm = re.findall(r'"?confidence"?\s*[:=]\s*"?([0-9.]+)', t, re.I)
            conf, resc = norm_conf(cm[-1] if cm else None)
            return {"decision": d, "confidence": conf, "key_condition": "", "reason": "", "decisive_records": [],
                    "how": how, "legacy_label": legacy, "conf_rescaled": resc}
    return None


def norm_conf(c):
    """Confidence in percent (0 to 100). A fraction below 1 written as a float is read as a probability and rescaled."""
    if c is None or isinstance(c, bool):
        return None, False
    try:
        v = float(str(c).strip().rstrip("%"))
    except ValueError:
        return None, False
    if math.isnan(v):
        return None, False
    resc = False
    if 0 < v < 1 or (isinstance(c, float) and v == 1.0 and "." in str(c)):
        v, resc = v * 100, True
    return max(0.0, min(100.0, v)), resc


# ---------- text helpers ----------