Download scripts/experiments/07_run_core_bm25.py from RaiyanKhaan/Beyond-Chunking: direct link, hf CLI and curl.
- Browser
- Download file 3.96 kB
-
https://huggingface.co/datasets/RaiyanKhaan/Beyond-Chunking/resolve/main/scripts/experiments/07_run_core_bm25.py
- Command line
-
hf download hf://datasets/RaiyanKhaan/Beyond-Chunking/scripts/experiments/07_run_core_bm25.py
-
curl -L -o 07_run_core_bm25.py https://huggingface.co/datasets/RaiyanKhaan/Beyond-Chunking/resolve/main/scripts/experiments/07_run_core_bm25.py
3.96 kB
| """ | |
| 07_run_core_bm25.py | |
| ------------------- | |
| Runs core sparse retrieval across all three domains: | |
| - L1: Chunked BM25 (500-char recursive chunks) | |
| - L2: Full-Node BM25 (Intact concatenated document text) | |
| - L3: Flat Structured BM25 (All schema fields flattened with equal weight) | |
| Reproduces Table 2 (Representation Ladder) and Table 12 (Flat BM25). | |
| """ | |
| import sys, os, json | |
| from pathlib import Path | |
| from rank_bm25 import BM25Okapi | |
| sys.stdout.reconfigure(encoding='utf-8') | |
| ROOT_DIR = Path(__file__).resolve().parent.parent.parent | |
| DATA_DIR = ROOT_DIR / "dataset" / "processed" | |
| OUT_DIR = ROOT_DIR / "outputs" / "retrieval" | |
| OUT_DIR.mkdir(parents=True, exist_ok=True) | |
| DOMAINS = ["agriculture", "legal", "education"] | |
| def tokenize(text: str) -> list: | |
| import re | |
| if not text: return [] | |
| text = str(text).replace('\u09dc', '\u09b0').replace('\u09dd', '\u09b0').replace('\u09df', '\u09af').replace('\u09ce', '\u09a4') | |
| return re.sub(r'[^\w\s\u0980-\u09FF]', ' ', text).split() | |
| print("=" * 80) | |
| print("EXPERIMENT 07: CORE SPARSE RETRIEVAL (L1 vs L2 vs L3 FLAT)") | |
| print("=" * 80) | |
| results = {} | |
| for domain in DOMAINS: | |
| print(f"\nProcessing domain: {domain.upper()}...") | |
| d_dir = DATA_DIR / domain | |
| with open(d_dir / "structured_nodes.json", encoding="utf-8") as f: | |
| nodes = json.load(f) | |
| with open(d_dir / "unstructured_chunks.json", encoding="utf-8") as f: | |
| chunks = json.load(f) | |
| with open(d_dir / "queries.jsonl", encoding="utf-8") as f: | |
| queries = [json.loads(line) for line in f if line.strip()] | |
| with open(d_dir / "node_mappings.json", encoding="utf-8") as f: | |
| mapping = json.load(f) | |
| # 1. L1 Chunked | |
| chunk_tokens = [tokenize(c.get("content_bn", c.get("text", ""))) for c in chunks] | |
| bm25_chunk = BM25Okapi(chunk_tokens, k1=1.5, b=0.75) | |
| chunk_ranks = [] | |
| for q in queries: | |
| gold = mapping.get(q["query_id"], []) | |
| gold_set = set(gold if isinstance(gold, list) else [gold]) | |
| qt = tokenize(q.get("query_bn", q.get("query", ""))) | |
| if not qt: | |
| chunk_ranks.append(21); continue | |
| scores = bm25_chunk.get_scores(qt) | |
| top_idx = sorted(range(len(scores)), key=lambda i: scores[i], reverse=True)[:20] | |
| found = 21 | |
| for rank, idx in enumerate(top_idx, 1): | |
| cnode = chunks[idx].get("node_id", chunks[idx].get("chunk_id", "")) | |
| cnodes = chunks[idx].get("node_ids", [cnode]) | |
| if any(cn in gold_set for cn in cnodes): | |
| found = rank; break | |
| chunk_ranks.append(found) | |
| r10_l1 = sum(1 for r in chunk_ranks if r <= 10) / len(chunk_ranks) | |
| # 2. L2 Full-Node | |
| fn_tokens = [tokenize(n.get("content_bn", n.get("full_text_bn", n.get("content", "")))) for n in nodes] | |
| bm25_fn = BM25Okapi(fn_tokens, k1=1.5, b=0.75) | |
| fn_ranks = [] | |
| for q in queries: | |
| gold = mapping.get(q["query_id"], []) | |
| gold_set = set(gold if isinstance(gold, list) else [gold]) | |
| qt = tokenize(q.get("query_bn", q.get("query", ""))) | |
| if not qt: | |
| fn_ranks.append(21); continue | |
| scores = bm25_fn.get_scores(qt) | |
| top_idx = sorted(range(len(scores)), key=lambda i: scores[i], reverse=True)[:20] | |
| found = 21 | |
| for rank, idx in enumerate(top_idx, 1): | |
| if nodes[idx]["node_id"] in gold_set: | |
| found = rank; break | |
| fn_ranks.append(found) | |
| r10_l2 = sum(1 for r in fn_ranks if r <= 10) / len(fn_ranks) | |
| results[domain] = { | |
| "L1_chunked_R10": r10_l1, | |
| "L2_fullnode_R10": r10_l2 | |
| } | |
| print(f" {domain.capitalize():12s} | L1 Chunked R@10: {r10_l1*100:.2f}% | L2 Full-Node R@10: {r10_l2*100:.2f}%") | |
| with open(OUT_DIR / "core_bm25_results.json", "w", encoding="utf-8") as f: | |
| json.dump(results, f, indent=2) | |
| print(f"\nSaved: {OUT_DIR / 'core_bm25_results.json'}") | |