Beyond-Chunking / scripts /representations /06_build_l3_fields.py
RaiyanKhaan's picture
Upload complete Beyond-Chunking reproducibility package and benchmark datasets
5f0f37c verified
Raw History Blame Contribute Delete
6.44 kB
#!/usr/bin/env python3
"""
06_build_l3_fields.py
Builds and validates the L3 Structured BM25F representation across Agriculture,
Legal, and Education domains.
In L3, each record is partitioned into discrete, named field slots matching the official
knowledge schema (Appendix Table 7), exposing field boundaries for selective weighting
and identifying designated query-aligned anchor fields.
Usage:
python 06_build_l3_fields.py [--data_dir PATH] [--output_dir PATH]
"""
import os
import sys
import json
import argparse
from pathlib import Path
from typing import List, Dict
if hasattr(sys.stdout, "reconfigure"):
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
SCRIPT_DIR = Path(__file__).resolve().parent
REPO_ROOT = SCRIPT_DIR.parent.parent.parent
DEFAULT_DATA_DIR = REPO_ROOT / "reproducibility" / "dataset"
SCHEMA_MAPPING = {
"agriculture": {
"anchor": "disease_pest_name_bn",
"functional_groups": {
"identity": ["disease_pest_name_bn", "colloquial_aliases", "scientific_name"],
"diagnostic": ["symptoms", "favorable_conditions_bn"],
"procedural": ["management", "prevention", "chemical_management_bn"],
"contextual": ["affected_crop_bn"],
"safety_metadata": ["safety_advisory"]
}
},
"legal": {
"anchor": "act_title_bn",
"functional_groups": {
"identity": ["act_title_bn", "short_title_bn", "act_no_bn"],
"diagnostic": ["preamble_bn", "definitions_bn"],
"procedural": ["section_titles_bn", "powers_bn", "procedures_bn"],
"contextual": ["penalties_bn"],
"safety_metadata": ["status_bn"]
}
},
"education": {
"anchor": "experiment_name_bn",
"functional_groups": {
"identity": ["experiment_name_bn"],
"diagnostic": ["apparatus_and_chemicals", "observation_conclusion"],
"procedural": ["procedure_steps"],
"safety_metadata": ["precautions"]
}
}
}
def extract_fielded_record(node: Dict, domain: str) -> Dict:
"""Extracts standardized fielded representation with functional group tagging."""
spec = SCHEMA_MAPPING[domain]
anchor = spec["anchor"]
fielded_data = {
"node_id": node["node_id"],
"domain": domain,
"anchor_field": anchor,
"anchor_value": str(node.get(anchor, "")).strip(),
"fields": {},
"groups": {}
}
for grp_name, field_list in spec["functional_groups"].items():
grp_tokens = []
for field in field_list:
raw_val = node.get(field)
if isinstance(raw_val, list):
val_clean = " ".join(str(x) for x in raw_val if x)
elif isinstance(raw_val, dict):
val_clean = " ".join(f"{k}: {v}" for k, v in raw_val.items() if v)
else:
val_clean = str(raw_val).strip() if raw_val is not None else ""
fielded_data["fields"][field] = val_clean
if val_clean:
grp_tokens.append(val_clean)
fielded_data["groups"][grp_name] = "\n".join(grp_tokens)
return fielded_data
def build_l3_fields(data_dir: Path, output_dir: Path = None) -> bool:
print("=" * 70)
print("06_BUILD_L3_FIELDS: L3 (Structured BM25F) Representation Builder")
print("=" * 70)
domains = ["agriculture", "legal", "education"]
expected_nodes = {"agriculture": 1028, "legal": 735, "education": 190}
all_ok = True
total_l3 = 0
for domain in domains:
nodes_file = data_dir / "processed" / domain / "structured_nodes.json"
print(f"\nProcessing domain: {domain.upper()} from {nodes_file}...")
if not nodes_file.exists():
print(f" [ERROR] File not found: {nodes_file}")
all_ok = False
continue
with open(nodes_file, "r", encoding="utf-8") as fp:
nodes = json.load(fp)
fielded_corpus = []
for n in nodes:
fielded_doc = extract_fielded_record(n, domain)
fielded_corpus.append(fielded_doc)
count = len(fielded_corpus)
total_l3 += count
expected = expected_nodes[domain]
anchor = SCHEMA_MAPPING[domain]["anchor"]
print(f" - Generated L3 fielded records: {count} / {expected}")
if count == expected:
print(f" - [OK] Fielded record census matches expected node count.")
else:
print(f" - [FAIL] Record census mismatch!")
all_ok = False
# Sample inspection
sample = fielded_corpus[0]
print(f" - Sample node ID: '{sample['node_id']}'")
print(f" - Designated anchor: '{anchor}' -> '{sample['anchor_value'][:50]}...'")
print(f" - Active field slots: {len(sample['fields'])} distinct fields")
print(f" - Functional groups: {list(sample['groups'].keys())}")
if output_dir:
out_domain_dir = output_dir / "l3_fields" / domain
out_domain_dir.mkdir(parents=True, exist_ok=True)
out_file = out_domain_dir / "l3_fielded_records.json"
with open(out_file, "w", encoding="utf-8") as fp:
json.dump(fielded_corpus, fp, ensure_ascii=False, indent=2)
print(f" - [SAVED] Exported L3 fielded records to {out_file}")
print("\n" + "=" * 70)
print(f"TOTAL L3 FIELDED RECORDS: {total_l3} / 1,953")
if all_ok and total_l3 == 1953:
print("L3 STRUCTURED REPRESENTATION: VERIFIED & OPERATIONAL")
else:
print("L3 STRUCTURED REPRESENTATION: FAILED")
print("=" * 70)
return all_ok and (total_l3 == 1953)
def main():
parser = argparse.ArgumentParser(description="Build and verify L3 Structured BM25F representation.")
parser.add_argument("--data_dir", type=str, default=str(DEFAULT_DATA_DIR), help="Path to reproducibility/dataset folder")
parser.add_argument("--output_dir", type=str, default=None, help="Optional directory to export representation")
args = parser.parse_args()
data_dir = Path(args.data_dir).resolve()
out_dir = Path(args.output_dir).resolve() if args.output_dir else None
success = build_l3_fields(data_dir, out_dir)
sys.exit(0 if success else 1)
if __name__ == "__main__":
main()