|
| 1 | +import json |
| 2 | +from pathlib import Path |
| 3 | +from typing import List, Dict, Any |
| 4 | + |
| 5 | +import pandas as pd |
| 6 | + |
| 7 | + |
| 8 | +def _safe_mean(series: pd.Series): |
| 9 | + s = pd.to_numeric(series, errors="coerce") |
| 10 | + return s.mean() |
| 11 | + |
| 12 | + |
| 13 | +def _coverage(series: pd.Series): |
| 14 | + s = pd.to_numeric(series, errors="coerce") |
| 15 | + return s.notna().mean() |
| 16 | + |
| 17 | + |
| 18 | +def _retrieved_ids(row: pd.Series, key: str) -> list[str]: |
| 19 | + contexts = row.get("contexts") |
| 20 | + if not isinstance(contexts, list): |
| 21 | + return [] |
| 22 | + values = [] |
| 23 | + for ctx in contexts: |
| 24 | + if isinstance(ctx, dict) and ctx.get(key): |
| 25 | + values.append(str(ctx.get(key))) |
| 26 | + return values |
| 27 | + |
| 28 | + |
| 29 | +def _expected_ids(row: pd.Series, key: str) -> list[str]: |
| 30 | + values = row.get(key) |
| 31 | + if isinstance(values, list): |
| 32 | + return [str(v) for v in values if v] |
| 33 | + return [] |
| 34 | + |
| 35 | + |
| 36 | +def _recall_at_k(expected: list[str], retrieved: list[str], k: int = 5): |
| 37 | + if not expected: |
| 38 | + return None |
| 39 | + return len(set(expected) & set(retrieved[:k])) / len(set(expected)) |
| 40 | + |
| 41 | + |
| 42 | +def _mrr(expected: list[str], retrieved: list[str]): |
| 43 | + if not expected: |
| 44 | + return None |
| 45 | + expected_set = set(expected) |
| 46 | + for idx, item in enumerate(retrieved, start=1): |
| 47 | + if item in expected_set: |
| 48 | + return 1 / idx |
| 49 | + return 0.0 |
| 50 | + |
| 51 | + |
| 52 | +def _precision_at_k(expected: list[str], retrieved: list[str], k: int = 5): |
| 53 | + retrieved_k = [item for item in retrieved[:k] if item] |
| 54 | + if not retrieved_k: |
| 55 | + return None |
| 56 | + if not expected: |
| 57 | + return None |
| 58 | + return len(set(expected) & set(retrieved_k)) / len(set(retrieved_k)) |
| 59 | + |
| 60 | + |
| 61 | +def _citation_ids(row: pd.Series, key: str) -> list[str]: |
| 62 | + citations = row.get("citations") |
| 63 | + if not isinstance(citations, list): |
| 64 | + return [] |
| 65 | + values = [] |
| 66 | + for citation in citations: |
| 67 | + if isinstance(citation, dict) and citation.get(key): |
| 68 | + values.append(str(citation.get(key))) |
| 69 | + return values |
| 70 | + |
| 71 | + |
| 72 | +def analyze_and_report(results: List[Dict[str, Any]], output_dir: str): |
| 73 | + Path(output_dir).mkdir(parents=True, exist_ok=True) |
| 74 | + raw_path = Path(output_dir) / "raw_results.json" |
| 75 | + with open(raw_path, "w") as f: |
| 76 | + json.dump(results, f, indent=2, default=float) |
| 77 | + if not results: |
| 78 | + return |
| 79 | + df = pd.json_normalize(results) |
| 80 | + for id_kind, expected_col, metric_prefix in [ |
| 81 | + ("chunk_id", "relevant_chunk_ids", "chunk"), |
| 82 | + ("doc_id", "relevant_doc_ids", "doc"), |
| 83 | + ]: |
| 84 | + recalls = [] |
| 85 | + mrrs = [] |
| 86 | + precisions = [] |
| 87 | + for _, row in df.iterrows(): |
| 88 | + expected = _expected_ids(row, expected_col) |
| 89 | + retrieved = _retrieved_ids(row, id_kind) |
| 90 | + recalls.append(_recall_at_k(expected, retrieved, 5)) |
| 91 | + mrrs.append(_mrr(expected, retrieved)) |
| 92 | + precisions.append(_precision_at_k(expected, retrieved, 5)) |
| 93 | + df[f"retrieval.{metric_prefix}_recall_at_5"] = recalls |
| 94 | + df[f"retrieval.{metric_prefix}_mrr"] = mrrs |
| 95 | + df[f"retrieval.{metric_prefix}_precision_at_5"] = precisions |
| 96 | + df["retrieval.context_count"] = df.apply(lambda r: len(r.get("contexts")) if isinstance(r.get("contexts"), list) else 0, axis=1) |
| 97 | + df["retrieval.citation_grounding_accuracy"] = df.apply( |
| 98 | + lambda r: _precision_at_k( |
| 99 | + _expected_ids(r, "relevant_chunk_ids") + _expected_ids(r, "relevant_doc_ids"), |
| 100 | + _citation_ids(r, "chunk_id") + _citation_ids(r, "doc_id"), |
| 101 | + 5, |
| 102 | + ), |
| 103 | + axis=1, |
| 104 | + ) |
| 105 | + df.to_csv(Path(output_dir) / "results.csv", index=False) |
| 106 | + |
| 107 | + metrics = [ |
| 108 | + "judge.depth_compliance", |
| 109 | + "judge.answer_quality", |
| 110 | + "judge.citation_accuracy", |
| 111 | + "judge.faithfulness", |
| 112 | + "deepeval.deepeval_relevancy", |
| 113 | + "deepeval.deepeval_faithfulness", |
| 114 | + "ragas.ragas_answer_relevancy", |
| 115 | + "ragas.ragas_faithfulness", |
| 116 | + "retrieval.chunk_recall_at_5", |
| 117 | + "retrieval.chunk_precision_at_5", |
| 118 | + "retrieval.chunk_mrr", |
| 119 | + "retrieval.doc_recall_at_5", |
| 120 | + "retrieval.doc_precision_at_5", |
| 121 | + "retrieval.doc_mrr", |
| 122 | + "retrieval.citation_grounding_accuracy", |
| 123 | + "retrieval.context_count", |
| 124 | + ] |
| 125 | + depth = df[df["system"] == "depthapi"] |
| 126 | + base = df[df["system"] == "langchain_baseline"] |
| 127 | + |
| 128 | + report = Path(output_dir) / "summary_comparison.md" |
| 129 | + with report.open("w") as f: |
| 130 | + f.write("# DepthAPI Evaluation Benchmark Report\n\n") |
| 131 | + f.write("## Overall Comparison\n\n| Metric | DepthAPI | Baseline |\n|---|---|---|\n") |
| 132 | + for m in metrics: |
| 133 | + if m in df.columns: |
| 134 | + f.write(f"| {m} | {_safe_mean(depth[m]):.4f} | {_safe_mean(base[m]):.4f} |\n") |
| 135 | + f.write("\n## Evaluator Success/Coverage\n\n") |
| 136 | + f.write("| Metric | DepthAPI Coverage | Baseline Coverage |\n|---|---|---|\n") |
| 137 | + for m in metrics: |
| 138 | + if m in df.columns: |
| 139 | + f.write(f"| {m} | {_coverage(depth[m]):.2%} | {_coverage(base[m]):.2%} |\n") |
| 140 | + |
| 141 | + print(f"Reports generated in {output_dir}") |
0 commit comments