WorkSurface-Build / scripts /score_predictions.py
lhpku20010120's picture
Release WorkSurface-Build v0.1.0 public benchmark inputs
b6beed8 verified
Raw
History Blame Contribute Delete
9.23 kB
#!/usr/bin/env python3
"""Score arbitrary Builder outputs without requiring a canonical surface schema.
Answer and Efficiency reuse the official WorkSurface-Bench implementations.
Evidence is projected back to raw Workspace-Bench files, so a Builder is not
penalized for choosing different chunks, table names, schemas, or graph IDs.
"""
from __future__ import annotations
import argparse
import json
import re
import sys
from pathlib import Path
from typing import Any
HERE = Path(__file__).resolve().parent
PROJECT = HERE.parent
DEFAULT_OFFICIAL_REPO = PROJECT / "official_worksurface_bench"
DEFAULT_WSB_LOCK = DEFAULT_OFFICIAL_REPO / "data" / "wsb_lock.json"
def read_jsonl(path: Path) -> list[dict[str, Any]]:
return [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line]
def norm_filename(value: str) -> str:
return re.sub(r"[^a-z0-9]+", "", Path(value).name.lower())
def strip_canonical_prefix(value: str, source_id: str) -> str:
name = Path(value).name
name = re.sub(rf"^t{re.escape(source_id)}__", "", name)
if name.endswith(".md"):
name = name[:-3]
return name
def match_raw_name(candidate: str, raw_names: list[str]) -> str | None:
key = norm_filename(candidate)
exact = {norm_filename(name): name for name in raw_names}
if key in exact:
return exact[key]
matches = [
name for name in raw_names
if key.startswith(norm_filename(Path(name).stem))
or norm_filename(Path(name).stem).startswith(key)
]
if not matches:
return None
return max(matches, key=lambda name: len(norm_filename(Path(name).stem)))
def table_to_raw(table: str, source_id: str, raw_names: list[str]) -> str | None:
candidate = re.sub(rf"^t{re.escape(source_id)}__", "", table)
table_key = norm_filename(candidate)
matches = [
name for name in raw_names
if table_key.startswith(norm_filename(Path(name).stem))
]
return max(matches, key=lambda name: len(norm_filename(Path(name).stem))) if matches else None
def gold_raw_files(evidence: dict[str, Any], source_id: str, raw_names: list[str]) -> tuple[list[str], bool]:
"""Return evaluator raw files and whether every file is required."""
complete = evidence.get("verified_complete_set") or evidence.get("verified_required_tabular_inputs")
if complete:
mapped = [match_raw_name(str(item).split("::", 1)[-1], raw_names) for item in complete]
return [item for item in mapped if item], True
if evidence.get("source_file"):
mapped = match_raw_name(str(evidence["source_file"]), raw_names)
return ([mapped] if mapped else []), False
if evidence.get("surface") == "rag" and evidence.get("file"):
mapped = match_raw_name(strip_canonical_prefix(str(evidence["file"]), source_id), raw_names)
return ([mapped] if mapped else []), False
path = evidence.get("graph_path") or []
if path:
terminal = str(path[-1]).split("::", 1)[-1]
mapped = match_raw_name(terminal, raw_names)
if mapped:
return [mapped], False
if evidence.get("table"):
mapped = table_to_raw(str(evidence["table"]), source_id, raw_names)
return ([mapped] if mapped else []), False
return [], False
def predicted_raw_files(trace: dict[str, Any], source_id: str, raw_names: list[str]) -> set[str]:
candidates: list[str] = []
for ref in trace.get("evidence_refs", []):
if ref.get("source_file"):
candidates.append(str(ref["source_file"]))
candidates.extend(map(str, trace.get("rag_files", [])))
for node in trace.get("graph_nodes", []):
candidates.append(str(node).split("::", 1)[-1])
for ref in trace.get("table_sources", []):
if isinstance(ref, dict) and ref.get("source_file"):
candidates.append(str(ref["source_file"]))
elif isinstance(ref, str):
candidates.append(ref)
mapped = {
match_raw_name(strip_canonical_prefix(candidate, source_id), raw_names)
for candidate in candidates
}
return {item for item in mapped if item}
def score_source_evidence(task: dict[str, Any], trace: dict[str, Any], lock: dict[str, Any]) -> dict[str, Any]:
source_id = str(task["source"]["task_id"])
raw_names = list(lock["task_id_to_file_hashes"][source_id])
predicted = predicted_raw_files(trace, source_id, raw_names)
outcomes: list[tuple[str, bool]] = []
unscorable = 0
for evidence in task.get("gold_evidence", []):
expected, require_all = gold_raw_files(evidence, source_id, raw_names)
if not expected:
unscorable += 1
continue
hit = all(item in predicted for item in expected) if require_all else any(item in predicted for item in expected)
outcomes.append((evidence["surface"], hit))
per_surface: dict[str, float] = {}
for surface in sorted({surface for surface, _ in outcomes}):
values = [hit for current, hit in outcomes if current == surface]
per_surface[surface] = round(sum(values) / len(values), 4)
score = sum(hit for _, hit in outcomes) / len(outcomes) if outcomes else None
total = len(outcomes) + unscorable
return {
"score": round(score, 4) if score is not None else None,
"per_surface": per_surface,
"scorable_items": len(outcomes),
"unscorable_items": unscorable,
"coverage": round(len(outcomes) / total, 4) if total else 0.0,
"predicted_raw_files": sorted(predicted),
}
def mean(values: list[float | None]) -> float | None:
present = [value for value in values if value is not None]
return round(sum(present) / len(present), 4) if present else None
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--gold", type=Path, required=True)
parser.add_argument("--predictions", type=Path, required=True)
parser.add_argument("--output", type=Path, required=True)
parser.add_argument("--official-repo", type=Path, default=DEFAULT_OFFICIAL_REPO)
parser.add_argument("--wsb-lock", type=Path, default=DEFAULT_WSB_LOCK)
args = parser.parse_args()
sys.path.insert(0, str(args.official_repo))
from scoring.answer import score_answer # type: ignore
from scoring.efficiency_safety import score_efficiency # type: ignore
tasks = read_jsonl(args.gold)
traces = {row["id"]: row for row in read_jsonl(args.predictions)}
lock = json.loads(args.wsb_lock.read_text(encoding="utf-8"))
rows: list[dict[str, Any]] = []
for task in tasks:
trace = traces.get(task["id"])
if trace is None:
continue
answer = score_answer(task, trace.get("answer"), anchors=task.get("qualitative_anchors"))
evidence = score_source_evidence(task, trace, lock)
efficiency = score_efficiency(trace.get("total_tokens", 0), task.get("efficiency_budget_tokens"))
if evidence["score"] is None:
# A small set of graph-only tasks has no raw-file-addressable gold
# evidence. Do not force a canonical graph schema merely to score
# them; renormalize Answer and Efficiency for those tasks.
utility = (0.55 * answer.score + 0.10 * efficiency) / 0.65
else:
utility = 0.55 * answer.score + 0.35 * evidence["score"] + 0.10 * efficiency
rows.append({
"id": task["id"],
"source_task_id": str(task["source"]["task_id"]),
"task_type": task["task_type"],
"answer": {"score": answer.score, "detail": answer.detail},
"source_evidence": evidence,
"efficiency": efficiency,
"query_utility": round(utility, 4),
})
overall = {
"n": len(rows),
"answer": mean([row["answer"]["score"] for row in rows]),
"source_evidence": mean([row["source_evidence"]["score"] for row in rows]),
"source_evidence_coverage": mean([row["source_evidence"]["coverage"] for row in rows]),
"efficiency": mean([row["efficiency"] for row in rows]),
"query_utility": mean([row["query_utility"] for row in rows]),
"missing_predictions": len(tasks) - len(rows),
}
by_type = {}
for task_type in sorted({row["task_type"] for row in rows}):
subset = [row for row in rows if row["task_type"] == task_type]
by_type[task_type] = {
"n": len(subset),
"answer": mean([row["answer"]["score"] for row in subset]),
"source_evidence": mean([row["source_evidence"]["score"] for row in subset]),
"query_utility": mean([row["query_utility"] for row in subset]),
}
report = {
"scorer": "worksurface_build_source_grounded_v0.1",
"weights": {"answer": 0.55, "source_evidence": 0.35, "efficiency": 0.10},
"overall": overall,
"by_task_type": by_type,
"per_task": rows,
}
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
print(json.dumps(overall, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()