File size: 2,524 Bytes
25be136
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5ecbe81
 
25be136
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#!/usr/bin/env python3
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())