bpHigh commited on
Commit
e13057d
·
1 Parent(s): a57d682

Add graders

Browse files
Files changed (2) hide show
  1. graders/__init__.py +471 -0
  2. graders/docx_metrics.py +581 -0
graders/__init__.py ADDED
@@ -0,0 +1,471 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Grading functions for the Financial Task Environment.
2
+
3
+ Two grading modes:
4
+ 1. QA tasks — compare agent text answer against reference text
5
+ (numeric extraction + keyword matching)
6
+ 2. MODIFY tasks — compare agent-produced xlsx against reference xlsx
7
+ (cell-level comparison with tolerance)
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import re
13
+ import traceback
14
+ from pathlib import Path
15
+ from typing import Any, Dict, List, Optional, Sequence
16
+
17
+ import openpyxl
18
+ from openpyxl.utils import get_column_letter
19
+
20
+
21
+ # ---------------------------------------------------------------------------
22
+ # Numeric helpers
23
+ # ---------------------------------------------------------------------------
24
+
25
+ def _extract_numbers(text: str) -> List[float]:
26
+ """Extract all numeric values from text, handling commas, $, %."""
27
+ cleaned = text.replace("$", "").replace("€", "").replace("£", "")
28
+ pattern = r"-?\d{1,3}(?:,\d{3})*(?:\.\d+)?|-?\d+(?:\.\d+)?"
29
+ raw = re.findall(pattern, cleaned)
30
+ results: List[float] = []
31
+ for r in raw:
32
+ try:
33
+ results.append(float(r.replace(",", "")))
34
+ except ValueError:
35
+ continue
36
+ return results
37
+
38
+
39
+ def _number_close(actual: float, expected: float, rel_tol: float = 0.05) -> bool:
40
+ if expected == 0:
41
+ return abs(actual) < 1e-6
42
+ return abs(actual - expected) / abs(expected) <= rel_tol
43
+
44
+
45
+ def _best_number_match(numbers: List[float], target: float, rel_tol: float = 0.05) -> bool:
46
+ return any(_number_close(n, target, rel_tol) for n in numbers)
47
+
48
+
49
+ # ---------------------------------------------------------------------------
50
+ # QA grading (text answer)
51
+ # ---------------------------------------------------------------------------
52
+
53
+ def grade_qa(answer: str, reference_answer: str) -> float:
54
+ """Grade a text answer against a reference. Returns 0.0–1.0."""
55
+ if not answer.strip():
56
+ return 0.0
57
+
58
+ ref_nums = _extract_numbers(reference_answer)
59
+ ans_nums = _extract_numbers(answer)
60
+
61
+ if ref_nums:
62
+ # Numeric comparison: what fraction of reference numbers appear?
63
+ matched = sum(1 for r in ref_nums if _best_number_match(ans_nums, r))
64
+ num_score = matched / len(ref_nums)
65
+ else:
66
+ num_score = 0.0
67
+
68
+ # Keyword overlap
69
+ ref_words = set(re.findall(r"[a-zA-Z]{3,}", reference_answer.lower()))
70
+ ans_words = set(re.findall(r"[a-zA-Z]{3,}", answer.lower()))
71
+ if ref_words:
72
+ kw_score = len(ref_words & ans_words) / len(ref_words)
73
+ else:
74
+ kw_score = 0.0
75
+
76
+ # Weighted combination (numbers matter more for financial tasks)
77
+ if ref_nums:
78
+ # If all numbers match perfectly, give full score
79
+ if num_score >= 1.0:
80
+ return 1.0
81
+ return round(min(0.8 * num_score + 0.2 * kw_score, 1.0), 4)
82
+ else:
83
+ return round(kw_score, 4)
84
+
85
+
86
+ # ---------------------------------------------------------------------------
87
+ # MODIFY grading (xlsx comparison)
88
+ # ---------------------------------------------------------------------------
89
+
90
+ def _load_wb_values(path: str):
91
+ """Load workbook in data_only mode, return dict of {(sheet, row, col): value}."""
92
+ wb = openpyxl.load_workbook(path, data_only=True)
93
+ cells = {}
94
+ sheets = set()
95
+ for name in wb.sheetnames:
96
+ sheets.add(name)
97
+ ws = wb[name]
98
+ for row in ws.iter_rows():
99
+ for cell in row:
100
+ if cell.value is not None:
101
+ cells[(name, cell.row, cell.column)] = cell.value
102
+ wb.close()
103
+ return cells, sheets
104
+
105
+
106
+ def grade_xlsx(output_path: str, reference_path: str) -> float:
107
+ """Compare agent output xlsx with reference xlsx. Returns 0.0–1.0.
108
+
109
+ Scoring breakdown:
110
+ - 30% sheet-level: does the output have all reference sheets?
111
+ - 70% cell-level: fraction of reference cells matched (with tolerance for numbers)
112
+ """
113
+ try:
114
+ ref_cells, ref_sheets = _load_wb_values(reference_path)
115
+ out_cells, out_sheets = _load_wb_values(output_path)
116
+ except Exception:
117
+ return 0.0
118
+
119
+ # --- Sheet score (30%) ---
120
+ if ref_sheets:
121
+ sheet_score = len(ref_sheets & out_sheets) / len(ref_sheets)
122
+ else:
123
+ sheet_score = 1.0
124
+
125
+ # --- Cell score (70%) ---
126
+ if not ref_cells:
127
+ return round(0.3 * sheet_score + 0.7 * 1.0, 4)
128
+
129
+ matched = 0
130
+ total = len(ref_cells)
131
+
132
+ for key, ref_val in ref_cells.items():
133
+ out_val = out_cells.get(key)
134
+ if out_val is None:
135
+ continue
136
+ if ref_val == out_val:
137
+ matched += 1
138
+ continue
139
+ # Numeric tolerance
140
+ try:
141
+ rv = float(ref_val)
142
+ ov = float(out_val)
143
+ if _number_close(ov, rv, rel_tol=0.02):
144
+ matched += 1
145
+ continue
146
+ except (ValueError, TypeError):
147
+ pass
148
+ # String comparison (case-insensitive, whitespace-normalized)
149
+ try:
150
+ if str(ref_val).strip().lower() == str(out_val).strip().lower():
151
+ matched += 1
152
+ except Exception:
153
+ pass
154
+
155
+ cell_score = matched / total if total > 0 else 1.0
156
+
157
+ return round(0.3 * sheet_score + 0.7 * cell_score, 4)
158
+
159
+
160
+ # ---------------------------------------------------------------------------
161
+ # Dispatcher
162
+ # ---------------------------------------------------------------------------
163
+
164
+ def _clamp_score(score: float) -> float:
165
+ """Clamp score to open interval (0.001, 0.999) — evaluator rejects exact 0.0 and 1.0."""
166
+ return max(0.001, min(0.999, score))
167
+
168
+
169
+ # ---------------------------------------------------------------------------
170
+ # DOCX grading — 3-layer composition
171
+ # 1. Validity gate file parses with python-docx (binary, gates the rest)
172
+ # 2. Generic diff paragraph-level fuzzy compare to gold (0–1)
173
+ # 3. Per-task OSWorld evaluator function(s) (0–1)
174
+ # Final = clamp( 0.4 * diff + 0.6 * primary ) iff validity gate passes.
175
+ # ---------------------------------------------------------------------------
176
+
177
+ def _docx_validity(path: str) -> bool:
178
+ try:
179
+ from docx import Document
180
+ Document(path)
181
+ return True
182
+ except Exception:
183
+ return False
184
+
185
+
186
+ def _docx_diff(working: str, gold: str) -> float:
187
+ """Generic paragraph-level fuzzy ratio against the primary gold."""
188
+ if not gold:
189
+ return 0.0
190
+ try:
191
+ from graders.docx_metrics import compare_docx_files
192
+ return float(compare_docx_files(working, gold, ignore_blanks=True, fuzzy_match=True))
193
+ except Exception:
194
+ return 0.0
195
+
196
+
197
+ def grade_docx(task: Dict[str, Any], output_path: str) -> float:
198
+ if not _docx_validity(output_path):
199
+ return 0.001 # corruption / not a docx → fail outright
200
+
201
+ # Layer 2: generic diff vs the first gold file
202
+ primary_gold = task.get("reference_file", "")
203
+ diff_score = _docx_diff(output_path, primary_gold) if primary_gold else 0.0
204
+
205
+ # Layer 3: per-task evaluator (OSWorld checks)
206
+ evaluator = task.get("evaluator") or {}
207
+ conj = evaluator.get("conj", "and")
208
+ checks = evaluator.get("checks") or []
209
+ if checks:
210
+ from graders.docx_metrics import run_evaluator
211
+ # Resolve relative paths in expected_files against the repo root.
212
+ # __file__ is graders/__init__.py → parent is graders/, parent.parent is repo root.
213
+ from pathlib import Path as _P
214
+ repo_root = _P(__file__).resolve().parent.parent
215
+ resolved_checks: List[Dict[str, Any]] = []
216
+ for c in checks:
217
+ ef = c.get("expected_files") or []
218
+ ef_abs = [str(repo_root / f) if not _P(f).is_absolute() else f for f in ef]
219
+ resolved_checks.append({**c, "expected_files": ef_abs})
220
+ primary_score = run_evaluator(
221
+ conj=conj,
222
+ checks=resolved_checks,
223
+ working_file=output_path,
224
+ source_file=task.get("source_file", ""),
225
+ )
226
+ else:
227
+ primary_score = diff_score # no per-task evaluator → diff carries it all
228
+
229
+ return round(0.4 * diff_score + 0.6 * primary_score, 4)
230
+
231
+
232
+ # ---------------------------------------------------------------------------
233
+ # PPTX grading — 2-layer composition
234
+ # 1. Validity gate file parses with python-pptx (binary, gates the rest)
235
+ # 2. Structural diff slide-count match (30%)
236
+ # + per-(slide_idx, shape_idx) text match (70%)
237
+ # Per-task evaluator (PPTArena's VLM judge) is intentionally NOT wired:
238
+ # it's expensive and non-deterministic. See edits.md for plan.
239
+ # ---------------------------------------------------------------------------
240
+
241
+ def _pptx_validity(path: str) -> bool:
242
+ try:
243
+ from pptx import Presentation
244
+ Presentation(path)
245
+ return True
246
+ except Exception:
247
+ return False
248
+
249
+
250
+ def _shape_style(shape) -> Dict[str, Any]:
251
+ """Extract per-shape style attributes. All values are tolerant — any
252
+ attribute that can't be read (placeholder inheritance, unsupported shape
253
+ type, None color, exception) becomes None. Two None values on the same
254
+ key match; one None vs one non-None counts as a mismatch."""
255
+ style: Dict[str, Any] = {
256
+ "fill_rgb": None, # solid fill RGB hex (str)
257
+ "line_rgb": None, # line/border RGB hex (str)
258
+ "font_name": None, # first run, str
259
+ "font_size_pt": None, # first run, float
260
+ "font_bold": None, # first run, bool/None (None = inherited)
261
+ "font_italic": None, # first run, bool/None
262
+ "font_rgb": None, # first run, RGB hex (str)
263
+ }
264
+ # ---- shape fill / line colors ----
265
+ try:
266
+ from pptx.enum.dml import MSO_FILL_TYPE
267
+ if shape.fill.type == MSO_FILL_TYPE.SOLID:
268
+ style["fill_rgb"] = str(shape.fill.fore_color.rgb)
269
+ except Exception:
270
+ pass
271
+ try:
272
+ style["line_rgb"] = str(shape.line.color.rgb)
273
+ except Exception:
274
+ pass
275
+ # ---- first-run font properties ----
276
+ try:
277
+ if shape.has_text_frame:
278
+ tf = shape.text_frame
279
+ if tf.paragraphs and tf.paragraphs[0].runs:
280
+ run = tf.paragraphs[0].runs[0]
281
+ style["font_name"] = run.font.name
282
+ if run.font.size is not None:
283
+ style["font_size_pt"] = float(run.font.size.pt)
284
+ style["font_bold"] = run.font.bold
285
+ style["font_italic"] = run.font.italic
286
+ try:
287
+ style["font_rgb"] = str(run.font.color.rgb)
288
+ except Exception:
289
+ pass
290
+ except Exception:
291
+ pass
292
+ return style
293
+
294
+
295
+ def _pptx_load_slides(path: str):
296
+ """Returns (slide_w, slide_h, [ [shape_dict, ...] per slide ])
297
+ where shape_dict has: text, left, top, width, height (None if inherited),
298
+ and `style` (per-attribute dict from _shape_style).
299
+ Dimensions are in EMU (English Metric Units, python-pptx native)."""
300
+ from pptx import Presentation
301
+ prs = Presentation(path)
302
+ slide_w = prs.slide_width or 9144000 # default 10in if unset
303
+ slide_h = prs.slide_height or 6858000 # default 7.5in
304
+ slides = []
305
+ for slide in prs.slides:
306
+ shapes = []
307
+ for shape in slide.shapes:
308
+ try:
309
+ text = shape.text_frame.text.strip() if shape.has_text_frame else ""
310
+ except Exception:
311
+ text = ""
312
+ shapes.append({
313
+ "text": text,
314
+ "left": getattr(shape, "left", None),
315
+ "top": getattr(shape, "top", None),
316
+ "width": getattr(shape, "width", None),
317
+ "height": getattr(shape, "height", None),
318
+ "style": _shape_style(shape),
319
+ })
320
+ slides.append(shapes)
321
+ return slide_w, slide_h, slides
322
+
323
+
324
+ def _coord_match(r_val, o_val, denom: int) -> float:
325
+ """Tolerance-based score for one coordinate (left/top/width/height).
326
+
327
+ Both None → 1.0 (placeholder inheriting from layout, treated as match)
328
+ Either None or denom 0 → 0.0
329
+ delta <= 2% of denom → 1.0 (visually indistinguishable)
330
+ delta >= 20% of denom → 0.0 (clearly different)
331
+ in between → linear falloff
332
+ """
333
+ if r_val is None and o_val is None:
334
+ return 1.0
335
+ if r_val is None or o_val is None or not denom:
336
+ return 0.0
337
+ delta = abs(r_val - o_val) / denom
338
+ if delta <= 0.02:
339
+ return 1.0
340
+ if delta >= 0.20:
341
+ return 0.0
342
+ return 1.0 - (delta - 0.02) / 0.18 # linear 1.0 → 0.0 over 2%–20%
343
+
344
+
345
+ _STYLE_WEIGHTS = {
346
+ "fill_rgb": 0.30, # most often-edited attribute in styling tasks
347
+ "line_rgb": 0.10,
348
+ "font_name": 0.10,
349
+ "font_size_pt": 0.15,
350
+ "font_bold": 0.075,
351
+ "font_italic": 0.075,
352
+ "font_rgb": 0.20,
353
+ }
354
+
355
+
356
+ def _style_match_score(ref_style: Dict[str, Any], out_style: Dict[str, Any]) -> float:
357
+ """Weighted attribute-by-attribute match. Both None on a key counts as
358
+ match (both inheriting from layout/theme). Partial credit: matches sum,
359
+ mismatches don't — score = sum(weighted matches) / sum(weights).
360
+ """
361
+ total_w = 0.0
362
+ score = 0.0
363
+ for key, w in _STYLE_WEIGHTS.items():
364
+ r = ref_style.get(key)
365
+ o = out_style.get(key)
366
+ total_w += w
367
+ if r == o: # works for both None==None and value equality
368
+ score += w
369
+ return (score / total_w) if total_w > 0 else 1.0
370
+
371
+
372
+ def _shape_match_score(ref: dict, out: dict, slide_w: int, slide_h: int) -> float:
373
+ """Per-shape composite: 40% text + 20% style + 20% position + 20% size."""
374
+ # Text: exact match → 1.0; rapidfuzz fallback (ratio/100) so partial edits
375
+ # get partial credit instead of binary fail.
376
+ if ref["text"] == out["text"]:
377
+ text_score = 1.0
378
+ elif ref["text"] and out["text"]:
379
+ try:
380
+ from rapidfuzz import fuzz
381
+ text_score = fuzz.ratio(ref["text"], out["text"]) / 100.0
382
+ except Exception:
383
+ text_score = 0.0
384
+ else:
385
+ text_score = 0.0
386
+
387
+ style_score = _style_match_score(ref.get("style") or {}, out.get("style") or {})
388
+
389
+ pos_score = (
390
+ _coord_match(ref["left"], out["left"], slide_w)
391
+ + _coord_match(ref["top"], out["top"], slide_h)
392
+ ) / 2.0
393
+ size_score = (
394
+ _coord_match(ref["width"], out["width"], slide_w)
395
+ + _coord_match(ref["height"], out["height"], slide_h)
396
+ ) / 2.0
397
+
398
+ return (
399
+ 0.40 * text_score
400
+ + 0.20 * style_score
401
+ + 0.20 * pos_score
402
+ + 0.20 * size_score
403
+ )
404
+
405
+
406
+ def grade_pptx(task: Dict[str, Any], output_path: str) -> float:
407
+ if not _pptx_validity(output_path):
408
+ return 0.001
409
+
410
+ ref_path = task.get("reference_file", "")
411
+ if not ref_path or not Path(ref_path).exists():
412
+ return 0.001
413
+
414
+ try:
415
+ out_w, out_h, out_slides = _pptx_load_slides(output_path)
416
+ ref_w, ref_h, ref_slides = _pptx_load_slides(ref_path)
417
+ except Exception:
418
+ return 0.001
419
+
420
+ # Slide-count score (20%)
421
+ if not ref_slides:
422
+ slide_score = 1.0
423
+ else:
424
+ delta = abs(len(out_slides) - len(ref_slides))
425
+ slide_score = max(0.0, 1.0 - (delta / max(len(ref_slides), 1)))
426
+
427
+ # Per-shape avg score (80%) — text + position + size, weighted internally
428
+ shape_scores: List[float] = []
429
+ # Use ref's slide dimensions for normalization (the gold's coordinate frame)
430
+ for s_i, ref_shapes in enumerate(ref_slides):
431
+ out_shapes = out_slides[s_i] if s_i < len(out_slides) else []
432
+ for sh_i, ref_shape in enumerate(ref_shapes):
433
+ if sh_i < len(out_shapes):
434
+ shape_scores.append(
435
+ _shape_match_score(ref_shape, out_shapes[sh_i], ref_w, ref_h)
436
+ )
437
+ else:
438
+ shape_scores.append(0.0) # missing shape in agent's output
439
+ avg_shape = sum(shape_scores) / len(shape_scores) if shape_scores else 1.0
440
+
441
+ return round(0.2 * slide_score + 0.8 * avg_shape, 4)
442
+
443
+
444
+ def grade_task(task: Dict[str, Any], answer: str = "", output_path: str = "") -> float:
445
+ """Grade a task. Returns score in (0.001, 0.999).
446
+
447
+ For QA tasks: uses *answer* (text) vs task["reference_answer"].
448
+ For MODIFY tasks (xlsx): cell-diff against task["reference_file"].
449
+ For MODIFY tasks (docx): validity + diff + OSWorld evaluator.
450
+ For MODIFY tasks (pptx): validity + slide-count + per-shape text diff.
451
+ """
452
+ task_type = task.get("task_type", "QA")
453
+ family = task.get("family", "xlsx")
454
+
455
+ if task_type == "QA":
456
+ ref = task.get("reference_answer", "")
457
+ return _clamp_score(grade_qa(answer, ref))
458
+ elif task_type == "MODIFY":
459
+ if not output_path or not Path(output_path).exists():
460
+ return 0.001
461
+ if family == "docx":
462
+ return _clamp_score(grade_docx(task, output_path))
463
+ if family == "pptx":
464
+ return _clamp_score(grade_pptx(task, output_path))
465
+ # xlsx (default) and any future families fall back to cell-diff
466
+ ref_path = task.get("reference_file", "")
467
+ if not ref_path or not Path(ref_path).exists():
468
+ return 0.001
469
+ return _clamp_score(grade_xlsx(output_path, ref_path))
470
+ else:
471
+ return 0.001
graders/docx_metrics.py ADDED
@@ -0,0 +1,581 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Ported OSWorld libreoffice_writer evaluator functions.
2
+
3
+ These are programmatic graders for our 21 OSWorld-Verified docx tasks. Each
4
+ function returns a float in [0, 1] (pass = 1, fail = 0; some are fractional).
5
+
6
+ Source: https://github.com/xlang-ai/OSWorld/blob/main/desktop_env/evaluators/metrics/docs.py
7
+ Apache-2.0 license — ports adapted to our manifest's `evaluator.checks` schema.
8
+
9
+ Differences from upstream:
10
+ - Removed verbose stdout prints / colored output.
11
+ - Heavy deps (easyocr, skimage) are imported lazily; unavailable → return 0.
12
+ - `find_default_font` is stubbed (operates on a LibreOffice config XML that
13
+ doesn't exist in our headless code-execution sandbox).
14
+ - `infeasible` semantic added: pass iff the working file is byte-identical
15
+ to the source (the agent correctly refused to modify).
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import logging
21
+ import re
22
+ from io import BytesIO
23
+ from typing import Any, Callable, Dict, List
24
+
25
+ logger = logging.getLogger("docx_metrics")
26
+
27
+ # All evaluators are wrapped to be tolerant: any unexpected exception → 0.0.
28
+
29
+
30
+ # ---------------------------------------------------------------------------
31
+ # compare_docx_files — content (paragraph) comparison with options
32
+ # ---------------------------------------------------------------------------
33
+
34
+ def compare_docx_files(file1: str, file2: str, **options) -> float:
35
+ if not file1 or not file2:
36
+ return 0.0
37
+
38
+ ignore_blanks = options.get("ignore_blanks", True)
39
+ ignore_case = options.get("ignore_case", False)
40
+ ignore_order = options.get("ignore_order", False)
41
+ content_only = options.get("content_only", False)
42
+ fuzzy_match = options.get("fuzzy_match", False)
43
+ delete_empty_lines = options.get("delete_empty_lines", False)
44
+
45
+ try:
46
+ from docx import Document
47
+ doc1 = Document(file1)
48
+ doc2 = Document(file2)
49
+ except Exception as e:
50
+ logger.debug(f"compare_docx_files load failed: {e}")
51
+ return 0.0
52
+
53
+ p1 = [p.text for p in doc1.paragraphs]
54
+ p2 = [p.text for p in doc2.paragraphs]
55
+ if ignore_order:
56
+ p1, p2 = sorted(p1), sorted(p2)
57
+ if delete_empty_lines:
58
+ p1 = [p for p in p1 if p.strip()]
59
+ p2 = [p for p in p2 if p.strip()]
60
+
61
+ def _fuzzy_ratio(a: str, b: str) -> float:
62
+ try:
63
+ from rapidfuzz import fuzz
64
+ return fuzz.ratio(a, b) / 100.0
65
+ except Exception:
66
+ # Fallback to a deterministic, dep-free Levenshtein-ish ratio
67
+ from difflib import SequenceMatcher
68
+ return SequenceMatcher(None, a, b).ratio()
69
+
70
+ if content_only:
71
+ text1 = re.sub(r"\s+", " ", "\n".join(p1)).strip()
72
+ text2 = re.sub(r"\s+", " ", "\n".join(p2)).strip()
73
+ if ignore_case:
74
+ text1, text2 = text1.lower(), text2.lower()
75
+ return _fuzzy_ratio(text1, text2)
76
+
77
+ if ignore_blanks:
78
+ text1 = re.sub(r"\s+", " ", "\n".join(p1)).strip()
79
+ text2 = re.sub(r"\s+", " ", "\n".join(p2)).strip()
80
+ if ignore_case:
81
+ text1, text2 = text1.lower(), text2.lower()
82
+ if fuzzy_match:
83
+ return _fuzzy_ratio(text1, text2)
84
+ return 1.0 if text1 == text2 else 0.0
85
+
86
+ if len(p1) != len(p2):
87
+ return 0.0
88
+ if fuzzy_match:
89
+ if not p1:
90
+ return 1.0
91
+ total = 0.0
92
+ for a, b in zip(p1, p2):
93
+ if ignore_case:
94
+ a, b = a.lower(), b.lower()
95
+ total += _fuzzy_ratio(a, b)
96
+ return total / len(p1)
97
+ for a, b in zip(p1, p2):
98
+ if ignore_case:
99
+ a, b = a.lower(), b.lower()
100
+ if a != b:
101
+ return 0.0
102
+ return 1.0
103
+
104
+
105
+ # ---------------------------------------------------------------------------
106
+ # Table / image / line-spacing / font / structural checks
107
+ # ---------------------------------------------------------------------------
108
+
109
+ def compare_docx_tables(file1: str, file2: str, **_options) -> float:
110
+ if not file1 or not file2:
111
+ return 0.0
112
+ try:
113
+ from docx import Document
114
+ d1 = Document(file1)
115
+ d2 = Document(file2)
116
+ except Exception:
117
+ return 0.0
118
+ t1, t2 = d1.tables, d2.tables
119
+ if len(t1) != len(t2):
120
+ return 0.0
121
+ for x, y in zip(t1, t2):
122
+ if len(x.rows) != len(y.rows) or len(x.columns) != len(y.columns):
123
+ return 0.0
124
+ for i in range(len(x.rows)):
125
+ for j in range(len(x.columns)):
126
+ if x.cell(i, j).text.strip() != y.cell(i, j).text.strip():
127
+ return 0.0
128
+ return 1.0
129
+
130
+
131
+ def compare_docx_images(file1: str, file2: str, **_options) -> float:
132
+ if not file1 or not file2:
133
+ return 0.0
134
+ try:
135
+ from docx import Document
136
+ from PIL import Image
137
+ d1 = Document(file1)
138
+ d2 = Document(file2)
139
+ except Exception:
140
+ return 0.0
141
+
142
+ def _imgs(d):
143
+ out = []
144
+ for rel in d.part.rels.values():
145
+ if "image" in rel.reltype:
146
+ out.append(BytesIO(rel.target_part.blob))
147
+ return out
148
+
149
+ a, b = _imgs(d1), _imgs(d2)
150
+ if len(a) != len(b):
151
+ return 0.0
152
+ for x, y in zip(a, b):
153
+ try:
154
+ if Image.open(x).tobytes() != Image.open(y).tobytes():
155
+ return 0.0
156
+ except Exception:
157
+ return 0.0
158
+ return 1.0
159
+
160
+
161
+ def compare_line_spacing(file1: str, file2: str, **_options) -> float:
162
+ if not file1 or not file2:
163
+ return 0.0
164
+ if compare_docx_files(file1, file2) == 0.0:
165
+ return 0.0
166
+ try:
167
+ from docx import Document
168
+ d1 = Document(file1)
169
+ d2 = Document(file2)
170
+ except Exception:
171
+ return 0.0
172
+ if len(d1.paragraphs) != len(d2.paragraphs):
173
+ return 0.0
174
+ for a, b in zip(d1.paragraphs, d2.paragraphs):
175
+ if a.paragraph_format.line_spacing != b.paragraph_format.line_spacing:
176
+ return 0.0
177
+ return 1.0
178
+
179
+
180
+ def compare_subscript_contains(file1: str, file2: str, **_options) -> float:
181
+ if not file1 or not file2:
182
+ return 0.0
183
+ try:
184
+ from docx import Document
185
+ d1 = Document(file1)
186
+ d2 = Document(file2)
187
+ except Exception:
188
+ return 0.0
189
+ for a, b in zip(d1.paragraphs, d2.paragraphs):
190
+ for ra, rb in zip(a.runs, b.runs):
191
+ if ra.font.subscript and rb.font.subscript:
192
+ return 1.0
193
+ return 0.0
194
+
195
+
196
+ def check_tabstops(file1: str, file2: str, **kwargs) -> float:
197
+ if not file1 or not file2:
198
+ return 0.0
199
+ try:
200
+ from docx import Document
201
+ from docx.enum.text import WD_TAB_ALIGNMENT
202
+ d1 = Document(file1)
203
+ d2 = Document(file2)
204
+ except Exception:
205
+ return 0.0
206
+
207
+ p1 = [p for p in d1.paragraphs if p.text.strip()]
208
+ p2 = [p for p in d2.paragraphs if p.text.strip()]
209
+ if len(p1) != len(p2):
210
+ return 0.0
211
+
212
+ if kwargs.get("word_number_split_by_tabstop") is not None:
213
+ number = kwargs["word_number_split_by_tabstop"]
214
+ index = kwargs.get("index", 0)
215
+ for p in p1:
216
+ splits = p.text.split("\t")
217
+ if len(splits) == 0 or index >= len(splits):
218
+ return 0.0
219
+ words = [w for w in re.split(r"\s", splits[index]) if w.strip()]
220
+ if len(words) != number:
221
+ return 0.0
222
+
223
+ section = d2.sections[0]
224
+ page_w = section.page_width - section.left_margin - section.right_margin
225
+
226
+ def _ignore(t):
227
+ return t.alignment == WD_TAB_ALIGNMENT.CLEAR or (
228
+ t.alignment == WD_TAB_ALIGNMENT.LEFT and t.position == 0
229
+ )
230
+
231
+ minus = 0.0
232
+ for a, b in zip(p1, p2):
233
+ ta = [t for t in a.paragraph_format.tab_stops if not _ignore(t)]
234
+ tb = [t for t in b.paragraph_format.tab_stops if not _ignore(t)]
235
+ if len(ta) != len(tb):
236
+ return 0.0
237
+ diff = 0.0
238
+ for ta_i, tb_i in zip(ta, tb):
239
+ if ta_i.alignment != tb_i.alignment:
240
+ return 0.0
241
+ diff += abs(ta_i.position - tb_i.position)
242
+ minus += diff / page_w
243
+ return max(0.0, 1.0 - (minus / max(1, len(p1))))
244
+
245
+
246
+ # ---------------------------------------------------------------------------
247
+ # Single-file property assertions
248
+ # ---------------------------------------------------------------------------
249
+
250
+ def has_page_numbers_in_footers(file1: str, **_options) -> float:
251
+ if not file1:
252
+ return 0.0
253
+ try:
254
+ from docx import Document
255
+ d = Document(file1)
256
+ except Exception:
257
+ return 0.0
258
+ for section in d.sections:
259
+ footer = section.footer
260
+ if footer is None:
261
+ return 0.0
262
+ text = footer.paragraphs[0].text if footer.paragraphs else ""
263
+ if not any(c.isdigit() for c in text):
264
+ return 0.0
265
+ return 1.0
266
+
267
+
268
+ def is_first_line_centered(file1: str, **_options) -> float:
269
+ if not file1:
270
+ return 0.0
271
+ try:
272
+ from docx import Document
273
+ from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
274
+ d = Document(file1)
275
+ except Exception:
276
+ return 0.0
277
+ if not d.paragraphs:
278
+ return 0.0
279
+ return 1.0 if d.paragraphs[0].paragraph_format.alignment == WD_PARAGRAPH_ALIGNMENT.CENTER else 0.0
280
+
281
+
282
+ def contains_page_break(file1: str, **options) -> float:
283
+ if not file1:
284
+ return 0.0
285
+ try:
286
+ from docx import Document
287
+ d = Document(file1)
288
+ except Exception:
289
+ return 0.0
290
+ expected = options.get("page_break_count")
291
+ ns = {"w": "http://schemas.openxmlformats.org/wordprocessingml/2006/main"}
292
+ count = 0
293
+ for p in d.paragraphs:
294
+ for run in p.runs:
295
+ for br in run.element.findall(".//w:br", ns):
296
+ t = br.attrib.get(
297
+ "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}type"
298
+ )
299
+ if t == "page":
300
+ count += 1
301
+ if expected is not None and count != expected:
302
+ return 0.0
303
+ return 1.0 if count > 0 else 0.0
304
+
305
+
306
+ def compare_font_names(file1: str, **options) -> float:
307
+ """Single-file evaluator. `options['font_name']` is the expected font."""
308
+ if not file1:
309
+ return 0.0
310
+ try:
311
+ from docx import Document
312
+ d = Document(file1)
313
+ except Exception:
314
+ return 0.0
315
+ expected = options.get("font_name")
316
+ if expected is None:
317
+ return 0.0
318
+ for p in d.paragraphs:
319
+ for run in p.runs:
320
+ if run.font.name != expected:
321
+ return 0.0
322
+ return 1.0
323
+
324
+
325
+ def check_italic_font_size_14(file1: str, file2: str, **_options) -> float:
326
+ if not file1 or not file2:
327
+ return 0.0
328
+ if compare_docx_files(file1, file2) == 0.0:
329
+ return 0.0
330
+ try:
331
+ from docx import Document
332
+ d = Document(file1)
333
+ except Exception:
334
+ return 0.0
335
+ for p in d.paragraphs:
336
+ for run in p.runs:
337
+ if run.italic:
338
+ if run.font.size is None or run.font.size.pt != 14:
339
+ return 0.0
340
+ return 1.0
341
+
342
+
343
+ def evaluate_strike_through_last_paragraph(file1: str, file2: str, **_options) -> float:
344
+ if not file1 or not file2:
345
+ return 0.0
346
+ if compare_docx_files(file1, file2) == 0.0:
347
+ return 0.0
348
+ try:
349
+ from docx import Document
350
+ d = Document(file1)
351
+ except Exception:
352
+ return 0.0
353
+ if not d.paragraphs:
354
+ return 0.0
355
+ last = d.paragraphs[-1]
356
+ if not last.runs:
357
+ return 0.0
358
+ for run in last.runs:
359
+ if not run.font.strike:
360
+ return 0.0
361
+ return 1.0
362
+
363
+
364
+ def evaluate_colored_words_in_tables(file1: str, file2: str, **options) -> float:
365
+ """Vowel-initial words red, others blue (CIE delta-E 2000 distance check)."""
366
+ if not file1 or not file2:
367
+ return 0.0
368
+ if compare_docx_files(file1, file2) == 0.0:
369
+ return 0.0
370
+ try:
371
+ from docx import Document
372
+ from docx.shared import RGBColor
373
+ except Exception:
374
+ return 0.0
375
+ try:
376
+ # skimage is optional; if missing, fall back to a strict RGB equality check.
377
+ from skimage.color import deltaE_ciede2000, rgb2lab # type: ignore
378
+ _have_skimage = True
379
+ except Exception:
380
+ _have_skimage = False
381
+
382
+ threshold = options.get("threshold", 3.5)
383
+
384
+ def _color_diff(a, b):
385
+ if _have_skimage:
386
+ la = rgb2lab([a[0] / 255.0, a[1] / 255.0, a[2] / 255.0])
387
+ lb = rgb2lab([b[0] / 255.0, b[1] / 255.0, b[2] / 255.0])
388
+ return float(deltaE_ciede2000(la, lb))
389
+ return 0.0 if (a == b) else 999.0 # fallback: equality only
390
+
391
+ try:
392
+ d = Document(file1)
393
+ except Exception:
394
+ return 0.0
395
+
396
+ red = RGBColor(255, 0, 0)
397
+ blue = RGBColor(0, 0, 255)
398
+ for table in d.tables:
399
+ for row in table.rows:
400
+ for cell in row.cells:
401
+ for p in cell.paragraphs:
402
+ for run in p.runs:
403
+ word = run.text
404
+ if not word:
405
+ continue
406
+ rgb = run.font.color.rgb
407
+ if rgb is None:
408
+ return 0.0
409
+ first = word[0].lower()
410
+ if first in "aeiou":
411
+ if _color_diff((rgb[0], rgb[1], rgb[2]), (255, 0, 0)) > threshold:
412
+ return 0.0
413
+ else:
414
+ if _color_diff((rgb[0], rgb[1], rgb[2]), (0, 0, 255)) > threshold:
415
+ return 0.0
416
+ return 1.0
417
+
418
+
419
+ # ---------------------------------------------------------------------------
420
+ # Multi-file evaluator — compare_unique_train_records
421
+ # ---------------------------------------------------------------------------
422
+
423
+ def compare_unique_train_records(processed_file: str, expected_files: List[str], **_options) -> float:
424
+ """expected_files = [gold, initial]. Returns 1 iff:
425
+ - Every processed line appeared in initial
426
+ - No duplicate train_ids in processed
427
+ - Set of train_ids matches gold
428
+ - Line counts match
429
+ """
430
+ if not processed_file or not isinstance(expected_files, list) or len(expected_files) < 2:
431
+ return 0.0
432
+ try:
433
+ from docx import Document
434
+ except Exception:
435
+ return 0.0
436
+
437
+ gold, initial = expected_files[0], expected_files[1]
438
+ if not gold or not initial:
439
+ return 0.0
440
+
441
+ def _lines_and_ids(path):
442
+ try:
443
+ d = Document(path)
444
+ lines = [p.text.strip() for p in d.paragraphs if p.text.strip()]
445
+ ids = [ln.split(",")[1].strip() for ln in lines if len(ln.split(",")) == 4]
446
+ return lines, ids
447
+ except Exception:
448
+ return None, None
449
+
450
+ proc_l, proc_ids = _lines_and_ids(processed_file)
451
+ if proc_l is None:
452
+ return 0.0
453
+ gold_l, gold_ids = _lines_and_ids(gold)
454
+ if gold_l is None:
455
+ return 0.0
456
+ init_l, _ = _lines_and_ids(initial)
457
+ if init_l is None:
458
+ return 0.0
459
+
460
+ if not set(proc_l).issubset(set(init_l)):
461
+ return 0.0
462
+ if len(proc_ids) != len(set(proc_ids)):
463
+ return 0.0
464
+ if set(proc_ids) != set(gold_ids):
465
+ return 0.0
466
+ if len(proc_l) != len(gold_l):
467
+ return 0.0
468
+ return 1.0
469
+
470
+
471
+ # ---------------------------------------------------------------------------
472
+ # Special: infeasible / unsupported
473
+ # ---------------------------------------------------------------------------
474
+
475
+ def infeasible(file1: str, source_file: str | None = None, **_options) -> float:
476
+ """Pass iff the agent's file is byte-identical to the source — i.e. the
477
+ agent correctly recognized the task as impossible and didn't modify."""
478
+ if not file1 or not source_file:
479
+ return 0.0
480
+ try:
481
+ with open(file1, "rb") as f:
482
+ a = f.read()
483
+ with open(source_file, "rb") as f:
484
+ b = f.read()
485
+ return 1.0 if a == b else 0.0
486
+ except Exception:
487
+ return 0.0
488
+
489
+
490
+ def find_default_font(file1: str, **_options) -> float:
491
+ """Stub — operates on LibreOffice's XML config which doesn't exist in our
492
+ headless code-execution sandbox. Always returns 0 so the docx grader can
493
+ fall back to the diff layer."""
494
+ return 0.0
495
+
496
+
497
+ # ---------------------------------------------------------------------------
498
+ # Dispatcher
499
+ # ---------------------------------------------------------------------------
500
+
501
+ # Two argument styles:
502
+ # binary: f(working_file, gold_file, **options)
503
+ # single: f(working_file, **options) -- options carry the rule
504
+ # multi: f(working_file, expected_files: list, **options)
505
+
506
+ _BINARY: Dict[str, Callable] = {
507
+ "compare_docx_files": compare_docx_files,
508
+ "compare_docx_tables": compare_docx_tables,
509
+ "compare_docx_images": compare_docx_images,
510
+ "compare_line_spacing": compare_line_spacing,
511
+ "compare_subscript_contains": compare_subscript_contains,
512
+ "check_tabstops": check_tabstops,
513
+ "check_italic_font_size_14": check_italic_font_size_14,
514
+ "evaluate_strike_through_last_paragraph": evaluate_strike_through_last_paragraph,
515
+ "evaluate_colored_words_in_tables": evaluate_colored_words_in_tables,
516
+ }
517
+
518
+ _SINGLE: Dict[str, Callable] = {
519
+ "has_page_numbers_in_footers": has_page_numbers_in_footers,
520
+ "is_first_line_centered": is_first_line_centered,
521
+ "contains_page_break": contains_page_break,
522
+ "compare_font_names": compare_font_names,
523
+ "find_default_font": find_default_font,
524
+ }
525
+
526
+ _MULTI: Dict[str, Callable] = {
527
+ "compare_unique_train_records": compare_unique_train_records,
528
+ }
529
+
530
+
531
+ def run_check(
532
+ func: str,
533
+ working_file: str,
534
+ expected_files: List[str],
535
+ options: Dict[str, Any],
536
+ source_file: str | None = None,
537
+ ) -> float:
538
+ """Run one OSWorld evaluator check. Returns float in [0, 1]."""
539
+ try:
540
+ opts = options or {}
541
+ if func == "infeasible":
542
+ return infeasible(working_file, source_file=source_file)
543
+ if func in _BINARY:
544
+ gold = expected_files[0] if expected_files else ""
545
+ return float(_BINARY[func](working_file, gold, **opts))
546
+ if func in _SINGLE:
547
+ return float(_SINGLE[func](working_file, **opts))
548
+ if func in _MULTI:
549
+ return float(_MULTI[func](working_file, expected_files, **opts))
550
+ except Exception as e:
551
+ logger.debug(f"run_check {func} crashed: {e}")
552
+ return 0.0
553
+ return 0.0
554
+
555
+
556
+ def run_evaluator(
557
+ conj: str,
558
+ checks: List[Dict[str, Any]],
559
+ working_file: str,
560
+ source_file: str | None = None,
561
+ ) -> float:
562
+ """Combine `conj` ('and' | 'or') over a list of checks.
563
+
564
+ Each check dict has: func (str), options (dict), expected_files (list[str]).
565
+ `and`: min over scores. `or`: max over scores.
566
+ """
567
+ if not checks:
568
+ return 0.0
569
+ scores = [
570
+ run_check(
571
+ func=c.get("func", ""),
572
+ working_file=working_file,
573
+ expected_files=c.get("expected_files") or [],
574
+ options=c.get("options") or {},
575
+ source_file=source_file,
576
+ )
577
+ for c in checks
578
+ ]
579
+ if conj == "or":
580
+ return max(scores)
581
+ return min(scores)