from __future__ import annotations import argparse from pathlib import Path from typing import Any from src.analysis.compare_predictions import compare_prediction_maps, load_prediction_map, row_id from src.data.io_utils import read_jsonl, write_jsonl BIOMEDICAL_RELATIONS = {"TREATS", "PREVENTS", "CAUSES", "INCREASES_RISK", "DECREASES_RISK"} def compact(text: Any, limit: int = 220) -> str: value = " ".join(str(text or "").split()) if len(value) <= limit: return value clipped = value[:limit].rsplit(" ", 1)[0].strip() return f"{clipped}..." def load_map(path: Path) -> dict[str, dict[str, Any]]: return {row_id(row): row for row in read_jsonl(path)} def load_claims_map(path: Path) -> dict[str, dict[str, Any]]: rows = read_jsonl(path) mapping: dict[str, dict[str, Any]] = {} for row in rows: for key in ("pair_id", "claim_id"): value = row.get(key) if value: mapping[str(value)] = row return mapping def group_rows(path: Path, key_field: str = "claim_id") -> dict[str, list[dict[str, Any]]]: grouped: dict[str, list[dict[str, Any]]] = {} for row in read_jsonl(path): grouped.setdefault(str(row.get(key_field, "")), []).append(row) return grouped def evidence_rows(topk_row: dict[str, Any] | None, limit: int = 3) -> list[dict[str, Any]]: if not topk_row: return [] rows: list[dict[str, Any]] = [] for item in (topk_row.get("candidates") or [])[:limit]: rows.append( { "candidate_id": item.get("candidate_id") or item.get("doc_id"), "rank": item.get("rank_wikikg") or item.get("final_rank") or item.get("rank_reranker"), "wikikg_score": item.get("wikikg_final_score"), "reranker_score": item.get("reranker_score"), "text": compact(item.get("text", ""), limit=260), } ) return rows def path_rows(subgraph: dict[str, Any] | None, topk_row: dict[str, Any] | None, limit: int = 3) -> list[dict[str, Any]]: if not subgraph: return [] preferred = { str(item.get("candidate_id") or item.get("doc_id")) for item in (topk_row or {}).get("candidates", [])[:5] } triples = list(subgraph.get("triples") or []) triples.sort( key=lambda row: ( 0 if str(row.get("source_doc_id", "")) in preferred else 1, str(row.get("triple_id", "")), ) ) output: list[dict[str, Any]] = [] for triple in triples[:limit]: output.append( { "path_text": f"{triple.get('head', '')} -- {triple.get('relation', '')} -- {triple.get('tail', '')}", "source_doc_id": triple.get("source_doc_id", ""), "source_text": compact(triple.get("source_text", ""), limit=260), } ) return output def unsupported_rows(unsupported: list[dict[str, Any]], limit: int = 3) -> list[dict[str, Any]]: rows = sorted( unsupported, key=lambda row: ( 0 if "relation_demoted_to_associated" in set(row.get("removal_reasons") or []) | set(row.get("rule_notes") or []) else 1, str(row.get("claim_id", "")), ), ) output: list[dict[str, Any]] = [] for row in rows[:limit]: output.append( { "path_text": f"{row.get('head', '')} -- {row.get('relation', '')} -- {row.get('tail', '')}", "nli_label": row.get("nli_label", ""), "removal_reasons": row.get("removal_reasons", []), "source_text": compact(row.get("source_text", ""), limit=260), } ) return output def feature_summary(feature_row: dict[str, Any] | None) -> dict[str, Any]: if not feature_row: return {} candidates = list(feature_row.get("candidate_features") or []) if not candidates: return {} max_final = max(float(item.get("final_score") or 0.0) for item in candidates) max_path = max(float(item.get("kg_path_score") or 0.0) for item in candidates) max_provenance = max(float(item.get("provenance_confidence") or 0.0) for item in candidates) max_contradiction = max(float(item.get("contradiction_signal") or 0.0) for item in candidates) return { "max_final_score": round(max_final, 6), "max_kg_path_score": round(max_path, 6), "max_provenance_confidence": round(max_provenance, 6), "max_contradiction_signal": round(max_contradiction, 6), } def build_prediction_case( comparison: dict[str, Any], category: str, claims_map: dict[str, dict[str, Any]], topk_map: dict[str, dict[str, Any]], feature_map: dict[str, dict[str, Any]], subgraph_map: dict[str, dict[str, Any]], unsupported_map: dict[str, list[dict[str, Any]]], ) -> dict[str, Any]: claim_id = comparison["id"] claim_row = claims_map.get(claim_id, {}) topk_row = topk_map.get(claim_id) subgraph = subgraph_map.get(claim_id) unsupported = unsupported_map.get(claim_id, []) return { "dataset": comparison["dataset"], "split": comparison["split"], "category": category, "id": claim_id, "claim": comparison["claim"], "gold": comparison["gold"], "baseline_prediction": comparison["baseline_prediction"], "wikikg_prediction": comparison["wikikg_prediction"], "alternate_prediction": comparison["alternate_prediction"], "baseline_correct": comparison["baseline_correct"], "wikikg_correct": comparison["wikikg_correct"], "alternate_correct": comparison["alternate_correct"], "label": claim_row.get("label", ""), "metadata": claim_row.get("metadata", {}), "retrieval_metrics": {} if not topk_row else topk_row.get("metrics", {}), "path_summary": feature_summary(feature_map.get(claim_id)), "num_verified_facts": 0 if not subgraph else int(subgraph.get("num_facts") or 0), "num_verified_triples": 0 if not subgraph else int(subgraph.get("num_triples") or 0), "top_evidence": evidence_rows(topk_row), "top_verified_paths": path_rows(subgraph, topk_row), "top_unsupported_triples": unsupported_rows(unsupported), } def pick_prediction_cases( comparisons: list[dict[str, Any]], dataset: str, claims_map: dict[str, dict[str, Any]], topk_map: dict[str, dict[str, Any]], feature_map: dict[str, dict[str, Any]], subgraph_map: dict[str, dict[str, Any]], unsupported_map: dict[str, list[dict[str, Any]]], sample_per_category: int, ) -> list[dict[str, Any]]: used: set[str] = set() output: list[dict[str, Any]] = [] def take(category: str, predicate) -> None: count = 0 for row in sorted(comparisons, key=lambda item: item["id"]): if row["id"] in used or not predicate(row): continue output.append( build_prediction_case( row, category, claims_map, topk_map, feature_map, subgraph_map, unsupported_map, ) ) used.add(row["id"]) count += 1 if count >= sample_per_category: break if dataset == "averitec": take("baseline_wrong_wikikg_right", lambda row: row["baseline_correct"] is False and row["wikikg_correct"] is True) take( "verified_beats_unfiltered", lambda row: row["wikikg_correct"] is True and row["alternate_correct"] is False, ) take( "nei_recovered_by_paths", lambda row: row["gold"] == "NEI" and row["baseline_correct"] is False and row["wikikg_correct"] is True, ) take("conflicting_failure", lambda row: row["gold"] == "CONFLICTING" and row["wikikg_correct"] is False) take("wikikg_hurt_case", lambda row: row["baseline_correct"] is True and row["wikikg_correct"] is False) else: take("baseline_wrong_wikikg_right", lambda row: row["baseline_correct"] is False and row["wikikg_correct"] is True) take("wikikg_hurt_case", lambda row: row["baseline_correct"] is True and row["wikikg_correct"] is False) take( "good_path_wrong_verdict", lambda row: row["wikikg_correct"] is False and (subgraph_map.get(row["id"], {}).get("num_triples", 0) or subgraph_map.get(row["id"], {}).get("num_facts", 0)), ) return output def pick_healthver_relation_cases( claims_map: dict[str, dict[str, Any]], verified_map: dict[str, list[dict[str, Any]]], unsupported_map: dict[str, list[dict[str, Any]]], baseline_map: dict[str, dict[str, Any]] | None, wikikg_map: dict[str, dict[str, Any]] | None, sample_per_category: int, ) -> list[dict[str, Any]]: used: set[tuple[str, str]] = set() output: list[dict[str, Any]] = [] def add_case(category: str, row: dict[str, Any]) -> None: key = (category, str(row.get("triple_id", ""))) if key in used: return claim_id = str(row.get("claim_id", "")) claim_row = claims_map.get(claim_id, {}) baseline_pred = "" if not baseline_map or claim_id not in baseline_map else baseline_map[claim_id].get("prediction", "") wikikg_pred = "" if not wikikg_map or claim_id not in wikikg_map else wikikg_map[claim_id].get("prediction", "") output.append( { "dataset": "healthver", "split": row.get("split", ""), "category": category, "id": claim_id, "claim": row.get("claim", ""), "gold": claim_row.get("label", ""), "baseline_prediction": baseline_pred, "wikikg_prediction": wikikg_pred, "relation_original": row.get("relation_original", ""), "relation": row.get("relation", ""), "nli_label": row.get("nli_label", ""), "entailment_score": row.get("entailment_score", ""), "rule_notes": row.get("rule_notes", []), "removal_reasons": row.get("removal_reasons", []), "source_text": compact(row.get("source_text", ""), limit=320), "verbalized_triple": row.get("verbalized_triple", ""), "metadata": claim_row.get("metadata", {}), } ) used.add(key) demoted_verified = [ row for rows in verified_map.values() for row in rows if row.get("relation_original") and row.get("relation_original") != row.get("relation") ] demoted_removed = [ row for rows in unsupported_map.values() for row in rows if "relation_demoted_to_associated" in set(row.get("removal_reasons") or []) | set(row.get("rule_notes") or []) ] strong_verified = [ row for rows in verified_map.values() for row in rows if row.get("relation") in BIOMEDICAL_RELATIONS and not row.get("relation_original") ] strong_removed = [ row for rows in unsupported_map.values() for row in rows if row.get("relation") in BIOMEDICAL_RELATIONS or row.get("relation_original") in BIOMEDICAL_RELATIONS ] for bucket_name, rows in ( ("demoted_verified_relation", demoted_verified), ("removed_strong_relation", demoted_removed), ("verified_strong_relation", strong_verified), ("unsupported_biomedical_relation", strong_removed), ): count = 0 for row in sorted(rows, key=lambda item: str(item.get("claim_id", ""))): add_case(bucket_name, row) count += 1 if count >= sample_per_category: break return output def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--dataset", required=True, choices=["averitec", "vifactcheck", "healthver"]) parser.add_argument("--split", required=True) parser.add_argument("--claims", type=Path, required=True) parser.add_argument("--retrieval-topk", type=Path) parser.add_argument("--path-features", type=Path) parser.add_argument("--verified-subgraphs", type=Path) parser.add_argument("--verified-triples", type=Path, required=True) parser.add_argument("--unsupported-triples", type=Path, required=True) parser.add_argument("--baseline-pred", type=Path) parser.add_argument("--wikikg-pred", type=Path) parser.add_argument("--alternate-pred", type=Path) parser.add_argument("--sample-per-category", type=int, default=3) parser.add_argument("--output", type=Path, required=True) args = parser.parse_args() claims_map = load_claims_map(args.claims) verified_map = group_rows(args.verified_triples) unsupported_map = group_rows(args.unsupported_triples) if args.dataset == "healthver": baseline_map = load_prediction_map(args.baseline_pred) if args.baseline_pred else None wikikg_map = load_prediction_map(args.wikikg_pred) if args.wikikg_pred else None rows = pick_healthver_relation_cases( claims_map=claims_map, verified_map=verified_map, unsupported_map=unsupported_map, baseline_map=baseline_map, wikikg_map=wikikg_map, sample_per_category=args.sample_per_category, ) write_jsonl(args.output, rows) print(f"Wrote {len(rows)} healthver relation cases to {args.output}") return if not (args.baseline_pred and args.wikikg_pred and args.retrieval_topk and args.path_features and args.verified_subgraphs): raise SystemExit("Prediction-comparison datasets require baseline/wikikg predictions and retrieval/subgraph inputs") baseline_map = load_prediction_map(args.baseline_pred) wikikg_map = load_prediction_map(args.wikikg_pred) alternate_map = load_prediction_map(args.alternate_pred) if args.alternate_pred else None comparisons = compare_prediction_maps(baseline_map, wikikg_map, alternate_map) topk_map = load_map(args.retrieval_topk) feature_map = load_map(args.path_features) subgraph_map = load_map(args.verified_subgraphs) rows = pick_prediction_cases( comparisons=comparisons, dataset=args.dataset, claims_map=claims_map, topk_map=topk_map, feature_map=feature_map, subgraph_map=subgraph_map, unsupported_map=unsupported_map, sample_per_category=args.sample_per_category, ) write_jsonl(args.output, rows) print(f"Wrote {len(rows)} case studies to {args.output}") if __name__ == "__main__": main()