Repository navigation
Expand file tree
/
Copy pathcases.py
More file actions
203 lines (168 loc) · 7.99 KB
/
Copy pathcases.py
File metadata and controls
203 lines (168 loc) · 7.99 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
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
191
192
193
194
195
196
197
198
199
200
201
202
203
"""Load evaluation cases from a folder.
One folder per case:
cv.md the CV text
ad.md the job ad text
case.yaml what the case is for and the reference decision
case.yaml:
scenario: clear # one of protocol.yaml scenario_types
language: en # en or sv
reference: high_priority # high_priority, consider or low_priority
rationale: Why a person reading the CV and the ad decides this.
remote: false # optional; the rule-based score adds 0.5 for remote jobs
expected_missing: # optional; information the case was built to lack
- label: Driving licence
keywords: [körkort, driving licence]
variants: # optional; changed copies of the same case
- id: name_swap
type: name_swap # one of protocol.yaml variant_types
cv: cv_name_swap.md # a file in the case folder; cv, ad or both
second_label: consider # optional; the second labeller's blind decision
first_label: high_priority # optional; the author's own label before discussing a
# disagreement (default: reference)
resolution: What was decided. # required when the labels differ
"""
from __future__ import annotations
import hashlib
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any
import yaml
PRIORITIES = ("low_priority", "consider", "high_priority")
class CaseError(Exception):
"""One or more case folders are not usable; the message lists every problem."""
@dataclass(frozen=True)
class ExpectedMissing:
label: str
keywords: tuple[str, ...]
@dataclass(frozen=True)
class Variant:
id: str
type: str
cv_text: str
ad_text: str
@dataclass(frozen=True)
class Case:
id: str
scenario: str
language: str
reference: str
rationale: str
cv_text: str
ad_text: str
remote: bool = False
expected_missing: tuple[ExpectedMissing, ...] = ()
variants: tuple[Variant, ...] = field(default=())
# Labels before the reference was settled (DESIGN.md section 8). first_label is
# the thesis author's, second_label the second labeller's, made blind.
first_label: str = ""
second_label: str | None = None
resolution: str = ""
def __post_init__(self) -> None:
if not self.first_label:
object.__setattr__(self, "first_label", self.reference)
def load_protocol(path: Path) -> dict[str, Any]:
protocol = yaml.safe_load(path.read_text(encoding="utf-8"))
if not isinstance(protocol, dict):
raise CaseError(f"{path} is not a protocol file")
return protocol
def text_hash(text: str) -> str:
return hashlib.sha256(text.encode("utf-8")).hexdigest()[:16]
# The text the files in cases/_template start with. A copied template whose
# placeholder was never replaced would otherwise be assessed as a real case.
TEMPLATE_PLACEHOLDER = "Replace this text with"
TEMPLATE_RATIONALE = "Write the reason here."
def _read(path: Path, problems: list[str]) -> str:
if not path.is_file():
problems.append(f"{path.parent.name}: {path.name} is missing")
return ""
text = path.read_text(encoding="utf-8").strip()
if not text:
problems.append(f"{path.parent.name}: {path.name} is empty")
elif text.startswith(TEMPLATE_PLACEHOLDER):
problems.append(f"{path.parent.name}: {path.name} still has the template's placeholder text")
return text
def _load_case(folder: Path, protocol: dict[str, Any], problems: list[str]) -> Case | None:
name = folder.name
before = len(problems)
cv_text = _read(folder / "cv.md", problems)
ad_text = _read(folder / "ad.md", problems)
meta_path = folder / "case.yaml"
meta: Any = yaml.safe_load(meta_path.read_text(encoding="utf-8")) if meta_path.is_file() else None
if not isinstance(meta, dict):
problems.append(f"{name}: case.yaml is missing or not a mapping")
return None
scenario = meta.get("scenario")
if scenario not in protocol["scenario_types"]:
problems.append(f"{name}: scenario must be one of {protocol['scenario_types']}")
language = meta.get("language")
if language not in protocol["languages"]:
problems.append(f"{name}: language must be one of {protocol['languages']}")
reference = meta.get("reference")
if reference not in PRIORITIES:
problems.append(f"{name}: reference must be one of {list(PRIORITIES)}")
rationale = str(meta.get("rationale") or "").strip()
if not rationale or rationale == TEMPLATE_RATIONALE:
problems.append(f"{name}: rationale is missing")
expected: list[ExpectedMissing] = []
for item in meta.get("expected_missing") or []:
keywords = item.get("keywords") if isinstance(item, dict) else None
if not isinstance(item, dict) or not item.get("label") or not keywords:
problems.append(f"{name}: each expected_missing item needs a label and keywords")
continue
expected.append(ExpectedMissing(str(item["label"]), tuple(str(k) for k in keywords)))
variants: list[Variant] = []
seen: set[str] = set()
for item in meta.get("variants") or []:
if not isinstance(item, dict) or not item.get("id"):
problems.append(f"{name}: each variant needs an id")
continue
variant_id = str(item["id"])
if variant_id in seen:
problems.append(f"{name}: variant id {variant_id} is used twice")
seen.add(variant_id)
if item.get("type") not in protocol["variant_types"]:
problems.append(f"{name}/{variant_id}: type must be one of {protocol['variant_types']}")
if not item.get("cv") and not item.get("ad"):
problems.append(f"{name}/{variant_id}: give a cv file, an ad file or both")
variant_cv = _read(folder / str(item["cv"]), problems) if item.get("cv") else cv_text
variant_ad = _read(folder / str(item["ad"]), problems) if item.get("ad") else ad_text
if variant_cv == cv_text and variant_ad == ad_text:
problems.append(f"{name}/{variant_id}: the variant is identical to the case")
variants.append(Variant(variant_id, str(item.get("type")), variant_cv, variant_ad))
first_label = meta.get("first_label") or reference
if meta.get("first_label") is not None and first_label not in PRIORITIES:
problems.append(f"{name}: first_label must be one of {list(PRIORITIES)}")
second_label = meta.get("second_label")
if second_label is not None and second_label not in PRIORITIES:
problems.append(f"{name}: second_label must be one of {list(PRIORITIES)}")
resolution = str(meta.get("resolution") or "").strip()
labels_differ = first_label != reference or (second_label is not None and second_label != first_label)
if labels_differ and not resolution:
problems.append(f"{name}: the labels differ, so resolution must say what was decided and why")
if len(problems) > before:
return None
return Case(
id=name,
scenario=str(scenario),
language=str(language),
reference=str(reference),
rationale=rationale,
cv_text=cv_text,
ad_text=ad_text,
remote=bool(meta.get("remote", False)),
expected_missing=tuple(expected),
variants=tuple(variants),
first_label=str(first_label),
second_label=None if second_label is None else str(second_label),
resolution=resolution,
)
def load_cases(root: Path, protocol: dict[str, Any]) -> list[Case]:
"""Every case folder under `root`, in name order. Raises CaseError on any problem."""
folders = sorted(p for p in root.iterdir() if p.is_dir() and not p.name.startswith(("_", ".")))
problems: list[str] = []
cases = [case for folder in folders if (case := _load_case(folder, protocol, problems))]
if not folders:
problems.append(f"no case folders in {root}")
if problems:
raise CaseError("Cases cannot be used:\n- " + "\n- ".join(problems))
return cases