File size: 3,215 Bytes
52ec3b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Deterministic graders for the three legal-review tasks. Each returns a score in [0.0, 1.0].
"""

from __future__ import annotations

from typing import Dict, Iterable, Set

CLAUSE_TYPES = frozenset({"liability", "termination", "auto_renewal"})


def normalize_clause_type(raw: str | None) -> str | None:
    if raw is None:
        return None
    x = raw.lower().strip().replace("-", "_").replace(" ", "_")
    aliases = {
        "auto_renew": "auto_renewal",
        "autorenewal": "auto_renewal",
        "auto_renewal": "auto_renewal",
    }
    x = aliases.get(x, x)
    return x if x in CLAUSE_TYPES else x


def grade_task_classify(
    predictions: Dict[int, str], ground_truth: Dict[int, str]
) -> float:
    """Exact match ratio over all clauses (easy task)."""
    if not ground_truth:
        return 1.0
    correct = 0
    for idx, gt in ground_truth.items():
        pred = normalize_clause_type(predictions.get(idx))
        if pred == normalize_clause_type(gt):
            correct += 1
    return correct / len(ground_truth)


def grade_task_risk(
    pred_risk: Dict[int, bool], ground_truth_risk: Dict[int, bool]
) -> float:
    """
    Medium task: score = 0.6 * recall + 0.4 * precision for the positive class (risky=True).
    Missing predictions are treated as False.
    """
    tp = fp = fn = 0
    for idx, gt in ground_truth_risk.items():
        pr = bool(pred_risk.get(idx, False))
        if gt and pr:
            tp += 1
        elif gt and not pr:
            fn += 1
        elif not gt and pr:
            fp += 1
    precision = tp / (tp + fp) if (tp + fp) else 1.0
    recall = tp / (tp + fn) if (tp + fn) else 1.0
    return 0.6 * recall + 0.4 * precision


def _fix_keywords(clause_type: str) -> list[set[str]]:
    """Ordered groups: match any token in a group counts toward that idea."""
    ct = normalize_clause_type(clause_type) or clause_type
    if ct == "liability":
        return [{"cap", "capped", "limit", "limited", "1x", "fees", "fee"}]
    if ct == "termination":
        return [{"terminat", "notice", "30"}]
    if ct == "auto_renewal":
        return [{"notice", "prior", "30", "renew"}]
    return []


def keyword_fix_score(suggestion: str, clause_type: str) -> float:
    """
    Hard task: 1.0 if all keyword groups hit, partial credit per group, penalty if too long.
    """
    if not suggestion or not suggestion.strip():
        return 0.0
    text = suggestion.lower()
    groups = _fix_keywords(clause_type)
    if not groups:
        return 0.0
    hits = 0
    for g in groups:
        if any(k in text for k in g):
            hits += 1
    base = hits / len(groups)
    # discourage very verbose outputs
    if len(suggestion) > 400:
        base *= 0.7
    return float(min(1.0, max(0.0, base)))


def grade_task_fix(
    suggestions: Dict[int, str],
    risky_indices: Iterable[int],
    clause_types: Dict[int, str],
) -> float:
    """Average keyword score over ground-truth risky clauses."""
    risky: Set[int] = set(risky_indices)
    if not risky:
        return 1.0
    total = 0.0
    for idx in risky:
        ct = clause_types[idx]
        total += keyword_fix_score(suggestions.get(idx, ""), ct)
    return total / len(risky)