| |
| import argparse |
| import json |
| from pathlib import Path |
|
|
|
|
| def load_cases(path: Path): |
| cases = [] |
| with path.open() as f: |
| for line in f: |
| line = line.strip() |
| if not line: |
| continue |
| cases.append(json.loads(line)) |
| return cases |
|
|
|
|
| def keyword_score(query: str, text: str) -> float: |
| query_terms = [term.lower() for term in query.replace("?", " ").replace(",", " ").split() if len(term) >= 3] |
| text_lower = text.lower() |
| score = 0.0 |
| for term in query_terms: |
| if term in text_lower: |
| score += 1.0 |
| return score |
|
|
|
|
| def run_keyword_baseline(cases): |
| results = [] |
| hits_at_1 = 0 |
| hits_at_5 = 0 |
| for case in cases: |
| scored = [] |
| for entry in case["entries"]: |
| score = keyword_score(case["query"], entry["text"]) |
| scored.append((score, entry["id"])) |
| scored.sort(key=lambda item: (-item[0], item[1])) |
| ranked_ids = [item[1] for item in scored] |
| relevant = set(case["relevant_ids"]) |
| hit1 = ranked_ids[:1] and ranked_ids[0] in relevant |
| hit5 = any(item in relevant for item in ranked_ids[:5]) |
| hits_at_1 += 1 if hit1 else 0 |
| hits_at_5 += 1 if hit5 else 0 |
| results.append({ |
| "id": case["id"], |
| "adversary_type": case["adversary_type"], |
| "query": case["query"], |
| "relevant_ids": case["relevant_ids"], |
| "ranked_ids": ranked_ids, |
| "hit_at_1": bool(hit1), |
| "hit_at_5": bool(hit5), |
| }) |
| total = len(cases) or 1 |
| return { |
| "cases": len(cases), |
| "recall_at_1": hits_at_1 / total, |
| "recall_at_5": hits_at_5 / total, |
| "results": results, |
| } |
|
|
|
|
| def main() -> int: |
| parser = argparse.ArgumentParser(description="Run a simple FalseMemBench keyword baseline") |
| parser.add_argument("--data", default=str(Path(__file__).resolve().parents[1] / "data" / "cases.jsonl")) |
| parser.add_argument("--out", default="") |
| args = parser.parse_args() |
|
|
| cases = load_cases(Path(args.data)) |
| report = run_keyword_baseline(cases) |
| print(json.dumps({"cases": report["cases"], "recall_at_1": report["recall_at_1"], "recall_at_5": report["recall_at_5"]}, indent=2)) |
| if args.out: |
| out_path = Path(args.out) |
| out_path.parent.mkdir(parents=True, exist_ok=True) |
| out_path.write_text(json.dumps(report, indent=2)) |
| return 0 |
|
|
|
|
| if __name__ == "__main__": |
| raise SystemExit(main()) |
|
|