Datasets:
Download sources/qwen-current/scripts/evaluate_date_normalization.py from Monyzik/compactfact-training-data: direct link, hf CLI and curl.
- Browser
- Download file 5.83 kB
-
https://huggingface.co/datasets/Monyzik/compactfact-training-data/resolve/main/sources/qwen-current/scripts/evaluate_date_normalization.py
- Command line
-
hf download hf://datasets/Monyzik/compactfact-training-data/sources/qwen-current/scripts/evaluate_date_normalization.py
-
curl -L -o evaluate_date_normalization.py https://huggingface.co/datasets/Monyzik/compactfact-training-data/resolve/main/sources/qwen-current/scripts/evaluate_date_normalization.py
5.83 kB
| """Apply source-calendar normalization to frozen predictions and compare scores.""" | |
| import argparse | |
| from collections import Counter | |
| import hashlib | |
| import importlib.util | |
| import json | |
| from pathlib import Path | |
| from compact_fact_extraction.normalization.facts import VERSION, normalize_fact_dates | |
| def read_records(path): | |
| records = {} | |
| with Path(path).open(encoding="utf-8") as stream: | |
| for line in stream: | |
| if not line.strip(): | |
| continue | |
| record = json.loads(line) | |
| if record["call_id"] in records: | |
| raise ValueError(f"Duplicate call_id in {path}: {record['call_id']}") | |
| records[record["call_id"]] = record | |
| return records | |
| def sha256(path): | |
| return hashlib.sha256(Path(path).read_bytes()).hexdigest() | |
| def load_scorer(path): | |
| spec = importlib.util.spec_from_file_location("date_normalization_official_scorer", path) | |
| module = importlib.util.module_from_spec(spec) | |
| spec.loader.exec_module(module) | |
| if hasattr(module, "load_catalog"): | |
| module.load_catalog(str(path)) | |
| return module | |
| def score(scorer, calls, predictions): | |
| from datetime import datetime | |
| metrics = scorer.evaluate(calls, predictions) | |
| matched, temporal_correct = 0, 0 | |
| for call_id, call in calls.items(): | |
| recovered = set() | |
| for turn in call["turns"]: | |
| recovered.update(scorer.recover_dates(turn["text"], datetime.fromisoformat(call["started_at"]).date())) | |
| recovered = {d.isoformat() for d in recovered} | |
| for expected, actual, _ in scorer.match_facts(call["facts"], predictions[call_id]["facts"]): | |
| matched += 1 | |
| days = {scorer._day(expected.get(field)) for field in ("valid_from", "valid_to")} - {None} | |
| if expected["attribute"] in scorer.TEMPORAL_ATTRS and days & recovered: | |
| temporal_correct += all(scorer._day(expected.get(field)) == scorer._day(actual.get(field)) | |
| for field in ("valid_from", "valid_to")) | |
| metrics.update(n_matched_facts=matched, n_temporal_correct=temporal_correct, | |
| fact_f1=2 * matched / (metrics["n_gold_facts"] + metrics["n_pred_facts"]) | |
| if metrics["n_gold_facts"] + metrics["n_pred_facts"] else 0.) | |
| return metrics | |
| def evaluate(args): | |
| calls, predictions = read_records(args.calls), read_records(args.predictions) | |
| if not calls: | |
| raise ValueError("Empty evaluation corpus") | |
| if set(calls) - set(predictions): | |
| raise ValueError("Every evaluated call must have an explicit prediction, including empty facts") | |
| predictions = {key: predictions[key] for key in calls} | |
| args.output.mkdir(parents=True, exist_ok=False) | |
| normalized, statuses, changes = {}, Counter(), 0 | |
| with (args.output / "predictions.jsonl").open("x", encoding="utf-8") as dst, \ | |
| (args.output / "audit.jsonl").open("x", encoding="utf-8") as trace: | |
| for call_id, call in calls.items(): | |
| clean = {key: call[key] for key in ("call_id", "started_at", "turns")} | |
| original = predictions[call_id]["facts"] | |
| facts, audit = normalize_fact_dates(clean, original) | |
| if len(facts) != len(original): | |
| raise AssertionError("Changed fact count") | |
| for old, new in zip(original, facts): | |
| if {k: v for k, v in old.items() if k not in {"valid_from", "valid_to"}} != \ | |
| {k: v for k, v in new.items() if k not in {"valid_from", "valid_to"}}: | |
| raise AssertionError("Changed a protected field") | |
| statuses.update(a["status"] for a in audit) | |
| changes += sum(a["changed"] for a in audit) | |
| normalized[call_id] = {"call_id": call_id, "facts": facts} | |
| dst.write(json.dumps(normalized[call_id], ensure_ascii=False) + "\n") | |
| trace.write(json.dumps({"call_id": call_id, "audit": audit}, ensure_ascii=False) + "\n") | |
| scorer = load_scorer(args.scorer) | |
| before, after = score(scorer, calls, predictions), score(scorer, calls, normalized) | |
| # Date-only rewriting cannot change official pairing or its denominator. | |
| for key in ("n_matched_facts", "n_temporal", "n_pred_facts", "fact_f1", "grounding_turn", "grounding_span"): | |
| if before[key] != after[key]: | |
| raise AssertionError(f"Date-only normalization changed {key}") | |
| root = Path(__file__).resolve().parents[1] | |
| result = {"version": VERSION, "calls": len(calls), "changed_facts": changes, | |
| "statuses": dict(statuses), "before": before, "after": after, | |
| "delta_temporal_correct": after["n_temporal_correct"] - before["n_temporal_correct"], | |
| "date_only": True, "gold_used_by_normalizer": False, | |
| "inputs_sha256": {str(path): sha256(path) for path in (args.calls, args.predictions, args.scorer)}, | |
| "source_sha256": {str(p.relative_to(root)): sha256(p) for p in ( | |
| Path(__file__).resolve(), root / "src/compact_fact_extraction/normalization/facts.py", | |
| root / "src/compact_fact_extraction/normalization/dates.py")}} | |
| (args.output / "metrics.json").write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") | |
| print(json.dumps(result, ensure_ascii=False, indent=2)) | |
| return result | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--calls", type=Path, required=True) | |
| parser.add_argument("--predictions", type=Path, required=True) | |
| parser.add_argument("--output", type=Path, required=True) | |
| parser.add_argument("--scorer", type=Path, default=Path("МТС MWS CompactFactExtraction/Данные кейса/case_metrics.py")) | |
| evaluate(parser.parse_args()) | |
| if __name__ == "__main__": | |
| main() | |