641071660J commited on
Commit
75ea5f2
·
verified ·
1 Parent(s): 15d1f1d

Add evaluation code

Browse files
evaluation/action_metrics.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """Compare action types, coordinates, numeric inputs, and control sequences."""
3
+
4
+ from decimal import Decimal, InvalidOperation
5
+ import json
6
+ import math
7
+ import re
8
+
9
+
10
+ TYPE_NUMBER_PATTERN = re.compile(
11
+ r"[+-]?(?:(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?)"
12
+ )
13
+
14
+
15
+ def numeric_type_signature(value):
16
+ """Normalize numeric spelling while preserving all keyboard controls."""
17
+ if not isinstance(value, str):
18
+ return None
19
+ normalized = value.replace("\r\n", "\n").replace("\r", "\n")
20
+ matches = list(TYPE_NUMBER_PATTERN.finditer(normalized))
21
+ if not matches:
22
+ return None
23
+ numbers = []
24
+ separators = []
25
+ cursor = 0
26
+ try:
27
+ for match in matches:
28
+ separators.append(normalized[cursor:match.start()])
29
+ number = Decimal(match.group(0))
30
+ if not number.is_finite():
31
+ return None
32
+ numbers.append(number)
33
+ cursor = match.end()
34
+ except InvalidOperation:
35
+ return None
36
+ separators.append(normalized[cursor:])
37
+ return tuple(numbers), tuple(separators)
38
+
39
+
40
+ def parameter_coordinates(value):
41
+ """Decode a coordinate pair independently of the predicted action tag."""
42
+ candidate = value
43
+ if isinstance(candidate, str):
44
+ try:
45
+ candidate = json.loads(candidate.strip())
46
+ except Exception:
47
+ return None
48
+ if not isinstance(candidate, (list, tuple)) or len(candidate) != 2:
49
+ return None
50
+ try:
51
+ result = [float(candidate[0]), float(candidate[1])]
52
+ except (TypeError, ValueError):
53
+ return None
54
+ if not all(math.isfinite(item) for item in result):
55
+ return None
56
+ return result
57
+
58
+
59
+ def compare_to_reference(generated, expected, record=None,
60
+ screen_size=(1920, 1080)):
61
+ """Compare two parsed actions using the canonical CAD-Drawer protocol."""
62
+ result = {
63
+ "action_match": generated.action == expected.action,
64
+ "parameter_match": False,
65
+ "step_success": False,
66
+ "full_match": False,
67
+ }
68
+
69
+ # Parameters use the reference action schema. Thus click and double_click
70
+ # at the same target can have Parameter=1 while Action=0 and Step=0.
71
+ if expected.action in ("click", "double_click"):
72
+ generated_coordinates = parameter_coordinates(generated.parameters)
73
+ if generated_coordinates is None:
74
+ return result
75
+ dx = generated_coordinates[0] - expected.parameters[0]
76
+ dy = generated_coordinates[1] - expected.parameters[1]
77
+ result["normalized_l2"] = round(math.hypot(dx, dy), 8)
78
+ result["pixel_l2_at_1920x1080"] = round(math.hypot(
79
+ dx * float(screen_size[0]), dy * float(screen_size[1])), 3)
80
+
81
+ bounds = None
82
+ if record is not None:
83
+ values = [record.get(name) for name in (
84
+ "x_min_norm", "x_max_norm", "y_min_norm", "y_max_norm")]
85
+ if all(value is not None for value in values):
86
+ bounds = [float(value) for value in values]
87
+ if bounds is not None:
88
+ x_min, x_max, y_min, y_max = bounds
89
+ result["parameter_match"] = (
90
+ x_min <= generated_coordinates[0] <= x_max and
91
+ y_min <= generated_coordinates[1] <= y_max
92
+ )
93
+ result["target_bbox_norm"] = bounds
94
+ else:
95
+ result["parameter_match"] = math.hypot(
96
+ dx * float(screen_size[0]),
97
+ dy * float(screen_size[1]),
98
+ ) <= 5.0
99
+ elif expected.action == "type":
100
+ generated_signature = numeric_type_signature(generated.parameters)
101
+ expected_signature = numeric_type_signature(expected.parameters)
102
+ if generated_signature is not None and expected_signature is not None:
103
+ result["parameter_match"] = (
104
+ generated_signature == expected_signature)
105
+ result["parameter_match_mode"] = (
106
+ "numeric_value_and_control_sequence")
107
+ else:
108
+ generated_text = (
109
+ generated.parameters.replace("\r\n", "\n").replace("\r", "\n")
110
+ if isinstance(generated.parameters, str) else None)
111
+ expected_text = (
112
+ expected.parameters.replace("\r\n", "\n").replace("\r", "\n")
113
+ if isinstance(expected.parameters, str) else None)
114
+ result["parameter_match"] = generated_text == expected_text
115
+ result["parameter_match_mode"] = "exact_control_text"
116
+ else:
117
+ result["parameter_match"] = (
118
+ generated.parameters == expected.parameters)
119
+
120
+ result["step_success"] = (
121
+ result["action_match"] and result["parameter_match"])
122
+ result["full_match"] = result["step_success"]
123
+ return result
evaluation/action_parser.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Parse model action responses and dataset reference actions."""
2
+
3
+ import ast
4
+ import json
5
+ import math
6
+ import re
7
+
8
+
9
+ EXPECTED_SCREEN = (1920, 1080)
10
+
11
+
12
+ ALLOWED_ACTIONS = {"click", "double_click", "type", "finish"}
13
+
14
+
15
+ class RunnerError(RuntimeError):
16
+ pass
17
+
18
+
19
+ class ParsedAction(object):
20
+ def __init__(self, action, parameters, reasoning="", raw=""):
21
+ self.action = action
22
+ self.parameters = parameters
23
+ self.reasoning = reasoning
24
+ self.raw = raw
25
+
26
+ def as_dict(self):
27
+ return {
28
+ "action": self.action,
29
+ "parameters": self.parameters,
30
+ "reasoning": self.reasoning,
31
+ }
32
+
33
+
34
+ def _tag_body(text, tag, preserve_payload=False, required=True):
35
+ pattern = r"<%s\b[^>]*>(.*?)</%s>" % (re.escape(tag), re.escape(tag))
36
+ match = re.search(pattern, text, flags=re.IGNORECASE | re.DOTALL)
37
+ if not match:
38
+ if required:
39
+ raise RunnerError("Missing <%s>...</%s> block" % (tag, tag))
40
+ return ""
41
+
42
+ body = match.group(1)
43
+ if not preserve_payload:
44
+ return body.strip()
45
+
46
+ # Remove exactly the formatting newline after the opening tag and before
47
+ # the closing tag. A second trailing newline belongs to the type payload
48
+ # and means Enter in the SFT schema.
49
+ if body.startswith("\r\n"):
50
+ body = body[2:]
51
+ elif body.startswith("\n"):
52
+ body = body[1:]
53
+ if body.endswith("\r\n"):
54
+ body = body[:-2]
55
+ elif body.endswith("\n"):
56
+ body = body[:-1]
57
+ return body
58
+
59
+
60
+ def _decode_type_payload(payload):
61
+ # Some serving stacks return literal backslash escapes instead of actual
62
+ # control characters. Decode only the control sequences used by this data.
63
+ if "\\t" in payload:
64
+ payload = payload.replace("\\t", "\t")
65
+ if "\\r\\n" in payload:
66
+ payload = payload.replace("\\r\\n", "\n")
67
+ if "\\n" in payload:
68
+ payload = payload.replace("\\n", "\n")
69
+ return payload
70
+
71
+
72
+ def parse_model_output(text):
73
+ if not isinstance(text, str) or not text.strip():
74
+ raise RunnerError("Model output is empty")
75
+
76
+ action = _tag_body(text, "action").lower().replace("-", "_")
77
+ if action not in ALLOWED_ACTIONS:
78
+ raise RunnerError("Unsupported action: %r" % action)
79
+
80
+ payload = _tag_body(text, "parameters", preserve_payload=True)
81
+ reasoning = _tag_body(text, "ui_reasoning", required=False)
82
+
83
+ if action in ("click", "double_click"):
84
+ value = payload.strip()
85
+ try:
86
+ params = json.loads(value)
87
+ except Exception:
88
+ try:
89
+ params = ast.literal_eval(value)
90
+ except Exception as exc:
91
+ raise RunnerError("Invalid click parameters: %r" % value) from exc
92
+ if not isinstance(params, (list, tuple)) or len(params) != 2:
93
+ raise RunnerError("Click parameters must be [x_norm, y_norm]")
94
+ try:
95
+ params = [float(params[0]), float(params[1])]
96
+ except Exception as exc:
97
+ raise RunnerError("Click coordinates must be numeric") from exc
98
+ if not all(math.isfinite(v) and 0.0 <= v <= 1.0 for v in params):
99
+ raise RunnerError("Normalized click coordinates must be in [0, 1]")
100
+ elif action == "type":
101
+ params = _decode_type_payload(payload)
102
+ if not params:
103
+ raise RunnerError("Type payload is empty")
104
+ else:
105
+ params = []
106
+
107
+ return ParsedAction(action, params, reasoning=reasoning, raw=text)
108
+
109
+
110
+ def assistant_text(row):
111
+ for message in row.get("messages", []):
112
+ if message.get("role") == "assistant":
113
+ return message.get("content", "")
114
+ raise RunnerError("JSONL row has no assistant message")
evaluation/evaluate.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Evaluate saved GUI action predictions against dataset references.
2
+
3
+ Prediction records contain a zero-based `_idx` and the model response in
4
+ `prediction`. The response uses <action> and <parameters> tags, with an optional
5
+ <ui_reasoning> block. An `error` field records an inference failure.
6
+ """
7
+ import argparse
8
+ from pathlib import Path
9
+
10
+ if __package__:
11
+ from .metrics import ScoringError, score_predictions, write_json, write_jsonl
12
+ else:
13
+ from metrics import ScoringError, score_predictions, write_json, write_jsonl
14
+
15
+
16
+ def main():
17
+ parser = argparse.ArgumentParser(description='Evaluate CAD GUI action predictions.')
18
+ parser.add_argument(
19
+ '--dataset', type=Path,
20
+ default=Path(__file__).resolve().parent.parent / 'GUI/annotations/test_final.jsonl.gz',
21
+ help='Reference dataset in JSONL or JSONL.GZ format.',
22
+ )
23
+ parser.add_argument('--predictions', type=Path, required=True,
24
+ help='JSONL or JSONL.GZ records with _idx and prediction fields.')
25
+ parser.add_argument('--output-dir', type=Path, required=True,
26
+ help='Directory for metrics.json and details.jsonl.')
27
+ parser.add_argument('--start-index', type=int, default=0)
28
+ parser.add_argument('--limit', type=int, default=0, help='Maximum reference rows. Zero selects all remaining rows.')
29
+ parser.add_argument('--num-shards', type=int, default=1)
30
+ parser.add_argument('--shard-index', type=int, default=0)
31
+ args = parser.parse_args()
32
+
33
+ try:
34
+ summary, details = score_predictions(
35
+ args.dataset, args.predictions, start_index=args.start_index,
36
+ limit=args.limit, num_shards=args.num_shards, shard_index=args.shard_index,
37
+ )
38
+ write_json(args.output_dir / 'metrics.json', summary)
39
+ write_jsonl(args.output_dir / 'details.jsonl', details)
40
+ except (ScoringError, OSError) as error:
41
+ parser.exit(1, f'Evaluation failed: {error}\n')
42
+
43
+ by_action = summary['by_gt_action']
44
+ main_metrics = [
45
+ ('Action Acc.', summary['metrics']['action_accuracy']),
46
+ ('Click Param. Acc.', by_action.get('click', {}).get('parameter_accuracy')),
47
+ ('Double-click Param. Acc.', by_action.get('double_click', {}).get('parameter_accuracy')),
48
+ ('Input Param. Acc.', by_action.get('type', {}).get('parameter_accuracy')),
49
+ ('Step Acc.', summary['metrics']['step_accuracy']),
50
+ ]
51
+ for label, value in main_metrics:
52
+ displayed = 'N/A' if value is None else f'{value * 100:.2f}%'
53
+ print(f'{label:<25} {displayed}')
54
+ print(f'Results saved to {args.output_dir.resolve()}')
55
+
56
+
57
+ if __name__ == '__main__':
58
+ main()
evaluation/metrics.py ADDED
@@ -0,0 +1,823 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """Action, parameter, step, subtask, and part metrics for CAD-Drawer.
4
+
5
+ The dataset is the sole source of ground truth. Prediction artifacts contribute
6
+ only a global row index (_idx) and raw model text (prediction).
7
+ Missing/unparseable/error rows remain in the fixed reference denominator.
8
+ """
9
+
10
+ from collections import Counter, defaultdict
11
+ import gzip
12
+ import hashlib
13
+ import json
14
+ import os
15
+ from pathlib import Path
16
+ import re
17
+
18
+
19
+ if __package__:
20
+ from . import action_metrics, action_parser as action_runner
21
+ else:
22
+ import action_metrics
23
+ import action_parser as action_runner
24
+
25
+
26
+ CANONICAL_TEST_FINAL_SHA256 = (
27
+ "a0a9c3bd89641b33b4c45237157374f0db0e64711d6cf6a1260a419c47bdda7d"
28
+ )
29
+ CANONICAL_TEST_FINAL_SLOTS = 29239
30
+ STRATIFIED_TEST_50_SHA256 = (
31
+ "ca1c3b0764f4774dca7b51d0b2bb9fd6660224d6e97e201974645895a45c5a32"
32
+ )
33
+ STRATIFIED_TEST_50_SLOTS = 3352
34
+ HELDOUT_TEST_364_SHA256 = (
35
+ "991983a4945c1124ce067a521810ad7f04ef8fd65f8c5a6fc8ca1d2f95d8e9ec"
36
+ )
37
+ HELDOUT_TEST_364_SLOTS = 25887
38
+
39
+
40
+ REGISTERED_DATASET_CONTRACTS = {
41
+ "canonical_test_final_414": {
42
+ "sha256": CANONICAL_TEST_FINAL_SHA256,
43
+ "slots": CANONICAL_TEST_FINAL_SLOTS,
44
+ "parts": 414,
45
+ "canonical_full_test": True,
46
+ },
47
+ "stratified_test_50_seed42": {
48
+ "sha256": STRATIFIED_TEST_50_SHA256,
49
+ "slots": STRATIFIED_TEST_50_SLOTS,
50
+ "parts": 50,
51
+ "canonical_full_test": False,
52
+ },
53
+ "heldout_test_364_seed42_complement": {
54
+ "sha256": HELDOUT_TEST_364_SHA256,
55
+ "slots": HELDOUT_TEST_364_SLOTS,
56
+ "parts": 364,
57
+ "canonical_full_test": False,
58
+ "model_selection_heldout": True,
59
+ "complement_of": "stratified_test_50_seed42",
60
+ },
61
+ }
62
+
63
+
64
+ class ScoringError(RuntimeError):
65
+ """Prediction artifact or reference contract is invalid."""
66
+
67
+
68
+ def identify_dataset_contract(records, dataset_hash):
69
+ """Return a registered immutable benchmark contract, if one matches."""
70
+ part_count = len({
71
+ record.get("part_id") for record in records
72
+ if record.get("part_id") is not None
73
+ })
74
+ for name, contract in REGISTERED_DATASET_CONTRACTS.items():
75
+ if (
76
+ len(records) == contract["slots"] and
77
+ part_count == contract["parts"] and
78
+ dataset_hash == contract["sha256"]
79
+ ):
80
+ return {"name": name, **contract}
81
+ return None
82
+
83
+
84
+ def dataset_sha256(path, chunk_size=1024 * 1024):
85
+ digest = hashlib.sha256()
86
+ opener = gzip.open if Path(path).suffix.lower() == ".gz" else open
87
+ with opener(path, "rb") as handle:
88
+ while True:
89
+ block = handle.read(chunk_size)
90
+ if not block:
91
+ break
92
+ digest.update(block)
93
+ return digest.hexdigest()
94
+
95
+
96
+ def read_jsonl(path):
97
+ rows = []
98
+ opener = gzip.open if Path(path).suffix.lower() == ".gz" else open
99
+ with opener(path, "rt", encoding="utf-8") as handle:
100
+ for line_number, line in enumerate(handle, 1):
101
+ if not line.strip():
102
+ continue
103
+ try:
104
+ value = json.loads(line)
105
+ except json.JSONDecodeError as exc:
106
+ raise ScoringError(
107
+ "%s:%d is invalid JSON: %s" %
108
+ (path, line_number, exc)) from exc
109
+ if not isinstance(value, dict):
110
+ raise ScoringError(
111
+ "%s:%d must contain a JSON object" %
112
+ (path, line_number))
113
+ rows.append(value)
114
+ return rows
115
+
116
+
117
+ def reference_slice(records, start_index=0, limit=0):
118
+ if isinstance(start_index, bool) or start_index < 0:
119
+ raise ScoringError("start_index must be a non-negative integer")
120
+ if isinstance(limit, bool) or limit < 0:
121
+ raise ScoringError("limit must be a non-negative integer")
122
+ if start_index > len(records):
123
+ raise ScoringError(
124
+ "start_index %d exceeds dataset size %d" %
125
+ (start_index, len(records)))
126
+ end_index = len(records)
127
+ if limit:
128
+ end_index = min(end_index, start_index + limit)
129
+ return range(start_index, end_index)
130
+
131
+
132
+ def reference_indices(records, start_index=0, limit=0,
133
+ num_shards=1, shard_index=0):
134
+ """Select a deterministic modulo shard from a canonical reference slice."""
135
+ if isinstance(num_shards, bool) or num_shards <= 0:
136
+ raise ScoringError("num_shards must be a positive integer")
137
+ if (
138
+ isinstance(shard_index, bool) or shard_index < 0 or
139
+ shard_index >= num_shards
140
+ ):
141
+ raise ScoringError(
142
+ "shard_index must be in [0, %d)" % num_shards)
143
+ base = reference_slice(
144
+ records, start_index=start_index, limit=limit)
145
+ return [
146
+ index for index in base
147
+ if index % num_shards == shard_index
148
+ ]
149
+
150
+
151
+ def load_prediction_map(path, allowed_indices):
152
+ allowed = set(allowed_indices)
153
+ predictions = {}
154
+ for line_number, row in enumerate(read_jsonl(path), 1):
155
+ if "_idx" not in row:
156
+ raise ScoringError(
157
+ "prediction record %d has no _idx" % line_number)
158
+ index = row["_idx"]
159
+ if isinstance(index, bool) or not isinstance(index, int):
160
+ raise ScoringError(
161
+ "prediction record %d has non-integer _idx=%r" %
162
+ (line_number, index))
163
+ if index not in allowed:
164
+ raise ScoringError(
165
+ "prediction record %d has out-of-slice _idx=%d" %
166
+ (line_number, index))
167
+ if index in predictions:
168
+ raise ScoringError(
169
+ "duplicate prediction _idx=%d (record %d)" %
170
+ (index, line_number))
171
+ predictions[index] = row
172
+ return predictions
173
+
174
+
175
+ FORMAT_PATTERN = re.compile(
176
+ r"^\s*<ui_reasoning\b[^>]*>.*?</ui_reasoning>\s*"
177
+ r"<action\b[^>]*>.*?</action>\s*"
178
+ r"<parameters\b[^>]*>.*?</parameters>\s*$",
179
+ flags=re.IGNORECASE | re.DOTALL,
180
+ )
181
+
182
+
183
+ def is_format_compliant(text):
184
+ if not isinstance(text, str):
185
+ return False
186
+ if not FORMAT_PATTERN.fullmatch(text):
187
+ return False
188
+ lowered = text.lower()
189
+ return all(lowered.count("<%s" % tag) == 1 for tag in (
190
+ "ui_reasoning", "action", "parameters"))
191
+
192
+
193
+ def _empty_counts():
194
+ return {
195
+ "slots": 0,
196
+ "parseable": 0,
197
+ "format_compliant": 0,
198
+ "action_correct": 0,
199
+ "parameter_correct": 0,
200
+ "step_correct": 0,
201
+ }
202
+
203
+
204
+ def _with_rates(counts):
205
+ result = dict(counts)
206
+ denominator = counts["slots"]
207
+ for numerator, rate_name in (
208
+ ("parseable", "parse_rate"),
209
+ ("format_compliant", "format_compliance_rate"),
210
+ ("action_correct", "action_accuracy"),
211
+ ("parameter_correct", "parameter_accuracy"),
212
+ ("step_correct", "step_accuracy"),
213
+ ):
214
+ result[rate_name] = (
215
+ counts[numerator] / denominator if denominator else None)
216
+ return result
217
+
218
+ def _record_part_fields(record):
219
+ """Return the canonical identity fields for a complete part trajectory."""
220
+ return {
221
+ "part_key": (
222
+ record.get("source_part_relpath") or record.get("part_id")),
223
+ "part_id": record.get("part_id"),
224
+ }
225
+
226
+
227
+ def _record_subtask_fields(record):
228
+ """Return the canonical fields needed to identify and order a subtask."""
229
+ present_task = record.get("present_task")
230
+ if not isinstance(present_task, dict):
231
+ present_task = {}
232
+ task_progress = record.get("task_progress")
233
+ if not isinstance(task_progress, dict):
234
+ task_progress = {}
235
+ return {
236
+ "part_key": _record_part_fields(record)["part_key"],
237
+ "task_id": (
238
+ present_task.get("task_id") or record.get("task_id")),
239
+ "action_index_in_task": task_progress.get("action_index_in_task"),
240
+ "total_actions_in_task": task_progress.get("total_actions_in_task"),
241
+ }
242
+
243
+
244
+ def build_subtask_contract(records):
245
+ """Validate canonical subtask grouping and ordering for a dataset.
246
+
247
+ A subtask is scoped by ``(part_key, task_id)``. ``part_key`` prefers the
248
+ source-relative part path because task IDs restart for every part. This
249
+ function does not inspect predictions; it validates only dataset metadata.
250
+ Invalid metadata disables subtask-level metrics without changing slot-level
251
+ Action/Parameter/Step scoring.
252
+ """
253
+ groups = defaultdict(list)
254
+ index_to_key = {}
255
+ errors = []
256
+
257
+ for index, record in enumerate(records):
258
+ present_task = record.get("present_task")
259
+ nested_task_id = (
260
+ present_task.get("task_id")
261
+ if isinstance(present_task, dict) else None)
262
+ top_task_id = record.get("task_id")
263
+ if (
264
+ nested_task_id is not None and top_task_id is not None and
265
+ str(nested_task_id) != str(top_task_id)
266
+ ):
267
+ errors.append(
268
+ "_idx=%d has conflicting nested/top-level task_id (%r/%r)" % (
269
+ index, nested_task_id, top_task_id))
270
+ continue
271
+ fields = _record_subtask_fields(record)
272
+ missing = [
273
+ name for name, value in fields.items()
274
+ if value is None or value == ""
275
+ ]
276
+ if missing:
277
+ errors.append(
278
+ "_idx=%d missing %s" % (index, ",".join(missing)))
279
+ continue
280
+ action_index = fields["action_index_in_task"]
281
+ total_actions = fields["total_actions_in_task"]
282
+ if (
283
+ isinstance(action_index, bool) or
284
+ not isinstance(action_index, int) or action_index <= 0 or
285
+ isinstance(total_actions, bool) or
286
+ not isinstance(total_actions, int) or total_actions <= 0
287
+ ):
288
+ errors.append(
289
+ "_idx=%d has invalid task progress (%r/%r)" % (
290
+ index, action_index, total_actions))
291
+ continue
292
+ key = (str(fields["part_key"]), str(fields["task_id"]))
293
+ groups[key].append({
294
+ "_idx": index,
295
+ "action_index_in_task": action_index,
296
+ "total_actions_in_task": total_actions,
297
+ })
298
+ index_to_key[index] = key
299
+
300
+ for key, rows in sorted(groups.items()):
301
+ rows.sort(key=lambda item: item["_idx"])
302
+ declared_totals = {
303
+ item["total_actions_in_task"] for item in rows}
304
+ if len(declared_totals) != 1:
305
+ errors.append(
306
+ "subtask %r has inconsistent total_actions_in_task=%r" % (
307
+ key, sorted(declared_totals)))
308
+ continue
309
+ declared_total = next(iter(declared_totals))
310
+ observed_order = [
311
+ item["action_index_in_task"] for item in rows]
312
+ expected_order = list(range(1, declared_total + 1))
313
+ if len(rows) != declared_total or observed_order != expected_order:
314
+ errors.append(
315
+ "subtask %r expected ordered actions %r but observed %r" % (
316
+ key, expected_order, observed_order))
317
+ global_indices = [item["_idx"] for item in rows]
318
+ if global_indices != list(range(
319
+ global_indices[0], global_indices[-1] + 1)):
320
+ errors.append(
321
+ "subtask %r is not contiguous in the dataset" % (key,))
322
+
323
+ return {
324
+ "valid": not errors,
325
+ "groups": groups,
326
+ "index_to_key": index_to_key,
327
+ "error_count": len(errors),
328
+ "errors_preview": errors[:50],
329
+ }
330
+
331
+
332
+ def build_part_contract(records):
333
+ """Validate canonical part grouping and global trajectory ordering."""
334
+ groups = defaultdict(list)
335
+ index_to_key = {}
336
+ errors = []
337
+
338
+ for index, record in enumerate(records):
339
+ fields = _record_part_fields(record)
340
+ part_key = fields["part_key"]
341
+ if part_key is None or part_key == "":
342
+ errors.append("_idx=%d missing part identity" % index)
343
+ continue
344
+ key = str(part_key)
345
+ groups[key].append({
346
+ "_idx": index,
347
+ "part_id": fields["part_id"],
348
+ })
349
+ index_to_key[index] = key
350
+
351
+ for key, rows in sorted(groups.items()):
352
+ rows.sort(key=lambda item: item["_idx"])
353
+ global_indices = [item["_idx"] for item in rows]
354
+ if global_indices != list(range(
355
+ global_indices[0], global_indices[-1] + 1)):
356
+ errors.append(
357
+ "part %r is not contiguous in the dataset" % key)
358
+
359
+ return {
360
+ "valid": not errors,
361
+ "groups": groups,
362
+ "index_to_key": index_to_key,
363
+ "error_count": len(errors),
364
+ "errors_preview": errors[:50],
365
+ }
366
+
367
+
368
+ def _empty_subtask_metrics():
369
+ return {
370
+ "subtasks_touched": 0,
371
+ "complete_subtasks": 0,
372
+ "partial_subtasks_excluded": 0,
373
+ "successful_subtasks": 0,
374
+ "subtask_exact_match": None,
375
+ "prefix_correct_steps": 0,
376
+ "complete_subtask_steps": 0,
377
+ "subtask_prefix_completion_macro": None,
378
+ "subtask_prefix_step_accuracy": None,
379
+ "subtask_metrics_complete": False,
380
+ }
381
+
382
+
383
+ def _empty_part_metrics():
384
+ return {
385
+ "parts_touched": 0,
386
+ "complete_parts": 0,
387
+ "partial_parts_excluded": 0,
388
+ "successful_parts": 0,
389
+ "part_exact_match": None,
390
+ "step_correct_steps": 0,
391
+ "prefix_correct_steps": 0,
392
+ "complete_part_steps": 0,
393
+ "part_step_accuracy_macro": None,
394
+ "part_step_accuracy_micro": None,
395
+ "part_prefix_completion_macro": None,
396
+ "part_prefix_step_accuracy": None,
397
+ "part_metrics_complete": False,
398
+ }
399
+
400
+
401
+ def _validate_reference(index, record):
402
+ try:
403
+ expected = action_runner.parse_model_output(
404
+ action_runner.assistant_text(record))
405
+ except Exception as exc:
406
+ raise ScoringError(
407
+ "canonical reference _idx=%d cannot be parsed: %s" %
408
+ (index, exc)) from exc
409
+ label = record.get("label_action_type")
410
+ if label is not None and label != expected.action:
411
+ raise ScoringError(
412
+ "canonical reference _idx=%d action label %r != parsed %r" %
413
+ (index, label, expected.action))
414
+ return expected
415
+
416
+ def _score_subtask_metrics(contract, selected_indices, details):
417
+ """Aggregate per-slot step success into complete subtasks."""
418
+ result = _empty_subtask_metrics()
419
+ result.update({
420
+ "subtask_contract_valid": contract["valid"],
421
+ "subtask_contract_error_count": contract["error_count"],
422
+ "subtask_contract_errors_preview": contract["errors_preview"],
423
+ })
424
+ selected = set(selected_indices)
425
+ detail_by_index = {item["_idx"]: item for item in details}
426
+ complete_groups = []
427
+ partial_groups = []
428
+
429
+ for key, rows in contract["groups"].items():
430
+ group_indices = [item["_idx"] for item in rows]
431
+ overlap = selected.intersection(group_indices)
432
+ if not overlap:
433
+ continue
434
+ result["subtasks_touched"] += 1
435
+ if len(overlap) == len(group_indices):
436
+ complete_groups.append((key, rows))
437
+ else:
438
+ partial_groups.append((key, rows))
439
+ for index in overlap:
440
+ detail_by_index[index]["subtask_metric_included"] = False
441
+ detail_by_index[index]["subtask_partial_in_slice"] = True
442
+
443
+ result["complete_subtasks"] = len(complete_groups)
444
+ result["partial_subtasks_excluded"] = len(partial_groups)
445
+ result["subtask_metrics_complete"] = (
446
+ contract["valid"] and not partial_groups)
447
+
448
+ if not contract["valid"]:
449
+ return result
450
+
451
+ macro_prefix_sum = 0.0
452
+ for key, rows in complete_groups:
453
+ flags = [
454
+ bool(detail_by_index[item["_idx"]]["step_success"])
455
+ for item in rows
456
+ ]
457
+ prefix_correct = 0
458
+ for flag in flags:
459
+ if not flag:
460
+ break
461
+ prefix_correct += 1
462
+ successful = all(flags)
463
+ total_steps = len(flags)
464
+ prefix_fraction = (
465
+ prefix_correct / total_steps if total_steps else 0.0)
466
+ result["successful_subtasks"] += int(successful)
467
+ result["prefix_correct_steps"] += prefix_correct
468
+ result["complete_subtask_steps"] += total_steps
469
+ macro_prefix_sum += prefix_fraction
470
+
471
+ for item in rows:
472
+ detail = detail_by_index[item["_idx"]]
473
+ detail.update({
474
+ "subtask_metric_included": True,
475
+ "subtask_partial_in_slice": False,
476
+ "subtask_success": successful,
477
+ "subtask_prefix_correct_steps": prefix_correct,
478
+ "subtask_prefix_completion": prefix_fraction,
479
+ })
480
+
481
+ denominator = result["complete_subtasks"]
482
+ if denominator:
483
+ result["subtask_exact_match"] = (
484
+ result["successful_subtasks"] / denominator)
485
+ result["subtask_prefix_completion_macro"] = (
486
+ macro_prefix_sum / denominator)
487
+ step_denominator = result["complete_subtask_steps"]
488
+ if step_denominator:
489
+ result["subtask_prefix_step_accuracy"] = (
490
+ result["prefix_correct_steps"] / step_denominator)
491
+ return result
492
+
493
+
494
+ def _score_part_metrics(contract, selected_indices, details):
495
+ """Aggregate per-slot correctness into complete part trajectories."""
496
+ result = _empty_part_metrics()
497
+ result.update({
498
+ "part_contract_valid": contract["valid"],
499
+ "part_contract_error_count": contract["error_count"],
500
+ "part_contract_errors_preview": contract["errors_preview"],
501
+ })
502
+ selected = set(selected_indices)
503
+ detail_by_index = {item["_idx"]: item for item in details}
504
+ complete_groups = []
505
+ partial_groups = []
506
+
507
+ for key, rows in contract["groups"].items():
508
+ group_indices = [item["_idx"] for item in rows]
509
+ overlap = selected.intersection(group_indices)
510
+ if not overlap:
511
+ continue
512
+ result["parts_touched"] += 1
513
+ if len(overlap) == len(group_indices):
514
+ complete_groups.append((key, rows))
515
+ else:
516
+ partial_groups.append((key, rows))
517
+ for index in overlap:
518
+ detail_by_index[index]["part_metric_included"] = False
519
+ detail_by_index[index]["part_partial_in_slice"] = True
520
+
521
+ result["complete_parts"] = len(complete_groups)
522
+ result["partial_parts_excluded"] = len(partial_groups)
523
+ result["part_metrics_complete"] = (
524
+ contract["valid"] and not partial_groups)
525
+
526
+ if not contract["valid"]:
527
+ return result
528
+
529
+ macro_step_sum = 0.0
530
+ macro_prefix_sum = 0.0
531
+ for key, rows in complete_groups:
532
+ flags = [
533
+ bool(detail_by_index[item["_idx"]]["step_success"])
534
+ for item in rows
535
+ ]
536
+ correct_steps = sum(flags)
537
+ prefix_correct = 0
538
+ for flag in flags:
539
+ if not flag:
540
+ break
541
+ prefix_correct += 1
542
+ successful = all(flags)
543
+ total_steps = len(flags)
544
+ step_fraction = (
545
+ correct_steps / total_steps if total_steps else 0.0)
546
+ prefix_fraction = (
547
+ prefix_correct / total_steps if total_steps else 0.0)
548
+
549
+ result["successful_parts"] += int(successful)
550
+ result["step_correct_steps"] += correct_steps
551
+ result["prefix_correct_steps"] += prefix_correct
552
+ result["complete_part_steps"] += total_steps
553
+ macro_step_sum += step_fraction
554
+ macro_prefix_sum += prefix_fraction
555
+
556
+ for item in rows:
557
+ detail = detail_by_index[item["_idx"]]
558
+ detail.update({
559
+ "part_metric_included": True,
560
+ "part_partial_in_slice": False,
561
+ "part_success": successful,
562
+ "part_total_steps": total_steps,
563
+ "part_step_correct_steps": correct_steps,
564
+ "part_step_accuracy": step_fraction,
565
+ "part_prefix_correct_steps": prefix_correct,
566
+ "part_prefix_completion": prefix_fraction,
567
+ })
568
+
569
+ part_denominator = result["complete_parts"]
570
+ if part_denominator:
571
+ result["part_exact_match"] = (
572
+ result["successful_parts"] / part_denominator)
573
+ result["part_step_accuracy_macro"] = (
574
+ macro_step_sum / part_denominator)
575
+ result["part_prefix_completion_macro"] = (
576
+ macro_prefix_sum / part_denominator)
577
+
578
+ step_denominator = result["complete_part_steps"]
579
+ if step_denominator:
580
+ result["part_step_accuracy_micro"] = (
581
+ result["step_correct_steps"] / step_denominator)
582
+ result["part_prefix_step_accuracy"] = (
583
+ result["prefix_correct_steps"] / step_denominator)
584
+ return result
585
+
586
+
587
+ def score_predictions(dataset_path, prediction_path, start_index=0, limit=0,
588
+ num_shards=1, shard_index=0):
589
+ """Score a prediction JSONL against a fixed canonical reference slice."""
590
+ dataset_path = Path(dataset_path).resolve()
591
+ prediction_path = Path(prediction_path).resolve()
592
+ records = read_jsonl(dataset_path)
593
+ subtask_contract = build_subtask_contract(records)
594
+ part_contract = build_part_contract(records)
595
+ index_list = reference_indices(
596
+ records,
597
+ start_index=start_index,
598
+ limit=limit,
599
+ num_shards=num_shards,
600
+ shard_index=shard_index,
601
+ )
602
+ predictions = load_prediction_map(prediction_path, index_list)
603
+
604
+ overall = _empty_counts()
605
+ by_action = defaultdict(_empty_counts)
606
+ confusion = defaultdict(Counter)
607
+ details = []
608
+ missing_indices = []
609
+ inference_error_slots = 0
610
+
611
+ for index in index_list:
612
+ record = records[index]
613
+ task_fields = _record_subtask_fields(record)
614
+ expected = _validate_reference(index, record)
615
+ action_name = expected.action
616
+ overall["slots"] += 1
617
+ by_action[action_name]["slots"] += 1
618
+
619
+ prediction_row = predictions.get(index)
620
+ prediction_text = (
621
+ prediction_row.get("prediction")
622
+ if prediction_row is not None else None)
623
+ if prediction_row is None:
624
+ missing_indices.append(index)
625
+ parse_error = "missing_prediction_record"
626
+ generated = None
627
+ else:
628
+ inference_error = prediction_row.get("error")
629
+ if inference_error:
630
+ inference_error_slots += 1
631
+ prediction_text = None
632
+ generated = None
633
+ parse_error = "inference_error: %s" % inference_error
634
+ else:
635
+ parse_error = None
636
+ try:
637
+ generated = action_runner.parse_model_output(
638
+ prediction_text)
639
+ except Exception as exc:
640
+ generated = None
641
+ parse_error = str(exc)
642
+
643
+ comparison = {
644
+ "action_match": False,
645
+ "parameter_match": False,
646
+ "step_success": False,
647
+ }
648
+ pred_action = "<missing>" if prediction_row is None else "<parse_error>"
649
+ if generated is not None:
650
+ overall["parseable"] += 1
651
+ by_action[action_name]["parseable"] += 1
652
+ pred_action = generated.action
653
+ comparison = action_metrics.compare_to_reference(
654
+ generated, expected, record=record,
655
+ screen_size=action_runner.EXPECTED_SCREEN)
656
+ format_compliant = is_format_compliant(prediction_text)
657
+ if format_compliant:
658
+ overall["format_compliant"] += 1
659
+ by_action[action_name]["format_compliant"] += 1
660
+
661
+ for key, metric_name in (
662
+ ("action_match", "action_correct"),
663
+ ("parameter_match", "parameter_correct"),
664
+ ("step_success", "step_correct"),
665
+ ):
666
+ if comparison[key]:
667
+ overall[metric_name] += 1
668
+ by_action[action_name][metric_name] += 1
669
+ confusion[action_name][pred_action] += 1
670
+ details.append({
671
+ "_idx": index,
672
+ "part_id": record.get("part_id"),
673
+ "part_key": task_fields["part_key"],
674
+ "task_id": task_fields["task_id"],
675
+ "action_index_in_task": task_fields["action_index_in_task"],
676
+ "total_actions_in_task": task_fields["total_actions_in_task"],
677
+ "gt_action": action_name,
678
+ "pred_action": pred_action,
679
+ "prediction_present": prediction_row is not None,
680
+ "parse_ok": generated is not None,
681
+ "parse_error": parse_error,
682
+ "format_compliant": format_compliant,
683
+ "action_match": comparison["action_match"],
684
+ "parameter_match": comparison["parameter_match"],
685
+ "step_success": comparison["step_success"],
686
+ })
687
+
688
+ subtask_metrics = _score_subtask_metrics(
689
+ subtask_contract, index_list, details)
690
+ part_metrics = _score_part_metrics(
691
+ part_contract, index_list, details)
692
+ dataset_hash = dataset_sha256(dataset_path)
693
+ coverage_complete = len(predictions) == len(index_list)
694
+ full_dataset = (
695
+ start_index == 0 and limit == 0 and num_shards == 1 and
696
+ len(index_list) == len(records))
697
+ dataset_contract = identify_dataset_contract(records, dataset_hash)
698
+ dataset_contract_name = (
699
+ dataset_contract["name"] if dataset_contract else None)
700
+ canonical_contract = bool(
701
+ dataset_contract and dataset_contract["canonical_full_test"])
702
+ stratified_test_50_contract = (
703
+ dataset_contract_name == "stratified_test_50_seed42")
704
+ heldout_test_364_contract = (
705
+ dataset_contract_name == "heldout_test_364_seed42_complement")
706
+ registered_benchmark_metrics_valid = (
707
+ coverage_complete and full_dataset and dataset_contract is not None and
708
+ inference_error_slots == 0 and
709
+ subtask_metrics["subtask_metrics_complete"] and
710
+ part_metrics["part_metrics_complete"])
711
+ summary = {
712
+ "protocol": "cad_drawer_evaluation_v1",
713
+ "metric_suite_version": "cad_drawer_l1_metrics_v4",
714
+ "dataset": str(dataset_path),
715
+ "dataset_sha256": dataset_hash,
716
+ "prediction_file": str(prediction_path),
717
+ "dataset_total_slots": len(records),
718
+ "slice_start_index": start_index,
719
+ "slice_end_index_exclusive": (
720
+ index_list[-1] + 1 if index_list else start_index),
721
+ "reference_slots": len(index_list),
722
+ "num_shards": num_shards,
723
+ "shard_index": shard_index,
724
+ "prediction_records": len(predictions),
725
+ "missing_slots": len(missing_indices),
726
+ "missing_indices_preview": missing_indices[:50],
727
+ "inference_error_slots": inference_error_slots,
728
+ "coverage_complete": coverage_complete,
729
+ "evaluation_slice_complete": coverage_complete,
730
+ "registered_dataset_contract": dataset_contract_name,
731
+ "registered_dataset_contract_details": dataset_contract,
732
+ "canonical_test_final_contract": canonical_contract,
733
+ "stratified_test_50_contract": stratified_test_50_contract,
734
+ "heldout_test_364_contract": heldout_test_364_contract,
735
+ "inference_clean": inference_error_slots == 0,
736
+ "registered_benchmark_metrics_valid": (
737
+ registered_benchmark_metrics_valid),
738
+ "official_full_test_metrics_valid": (
739
+ registered_benchmark_metrics_valid and canonical_contract),
740
+ "official_test_50_metrics_valid": (
741
+ registered_benchmark_metrics_valid and
742
+ stratified_test_50_contract),
743
+ "official_test_364_metrics_valid": (
744
+ registered_benchmark_metrics_valid and
745
+ heldout_test_364_contract),
746
+ "metrics": _with_rates(overall),
747
+ "subtask_metrics": subtask_metrics,
748
+ "part_metrics": part_metrics,
749
+ "by_gt_action": {
750
+ name: _with_rates(counts)
751
+ for name, counts in sorted(by_action.items())
752
+ },
753
+ "action_confusion": {
754
+ expected: dict(sorted(predicted.items()))
755
+ for expected, predicted in sorted(confusion.items())
756
+ },
757
+ "definitions": {
758
+ "action_accuracy": "predicted action equals the GT action",
759
+ "parameter_accuracy": (
760
+ "parameters match under the GT action schema; independent "
761
+ "from predicted action correctness"),
762
+ "step_accuracy": (
763
+ "per-slot conjunction of action_match and parameter_match"),
764
+ "subtask_exact_match": (
765
+ "fraction of complete reference subtasks whose every "
766
+ "step is correct"),
767
+ "subtask_prefix_completion_macro": (
768
+ "mean, with equal weight per complete subtask, of the "
769
+ "consecutive correct prefix length divided by task length"),
770
+ "subtask_prefix_step_accuracy": (
771
+ "total consecutive correct prefix slots divided by all slots "
772
+ "in complete subtasks; longer subtasks receive more weight"),
773
+ "subtask_scope": (
774
+ "subtasks are grouped by part identity and task_id; partial "
775
+ "subtasks at a requested slice boundary are excluded and make "
776
+ "subtask_metrics_complete false"),
777
+ "part_step_accuracy_macro": (
778
+ "mean per-part fraction of independently correct reference "
779
+ "steps; every complete part has equal weight"),
780
+ "part_step_accuracy_micro": (
781
+ "total correct steps divided by all steps in complete parts; "
782
+ "equivalent to overall step accuracy on a complete full run"),
783
+ "part_prefix_completion_macro": (
784
+ "mean per-part fraction of consecutive correct steps before "
785
+ "the first failure; every complete part has equal weight"),
786
+ "part_prefix_step_accuracy": (
787
+ "total consecutive correct prefix steps divided by all steps "
788
+ "in complete parts; longer parts receive more weight"),
789
+ "part_exact_match": (
790
+ "fraction of complete reference part trajectories whose "
791
+ "every step is correct"),
792
+ "part_scope": (
793
+ "parts are grouped by source-relative part identity and must "
794
+ "be contiguous; partial parts are excluded"),
795
+ "parse_rate": (
796
+ "canonical FreeCAD action parser accepts the model output"),
797
+ "denominator": (
798
+ "all canonical reference slots in the requested slice; "
799
+ "missing, inference-error, and parse-error slots score zero"),
800
+ },
801
+ }
802
+ return summary, details
803
+
804
+
805
+ def write_json(path, value):
806
+ path = Path(path)
807
+ path.parent.mkdir(parents=True, exist_ok=True)
808
+ temporary = path.with_name(
809
+ path.name + ".tmp.%d" % os.getpid())
810
+ with temporary.open("w", encoding="utf-8") as handle:
811
+ json.dump(value, handle, ensure_ascii=False, indent=2)
812
+ handle.write("\n")
813
+ handle.flush()
814
+ os.fsync(handle.fileno())
815
+ os.replace(temporary, path)
816
+
817
+
818
+ def write_jsonl(path, rows):
819
+ path = Path(path)
820
+ path.parent.mkdir(parents=True, exist_ok=True)
821
+ with path.open("w", encoding="utf-8") as handle:
822
+ for row in rows:
823
+ handle.write(json.dumps(row, ensure_ascii=False) + "\n")