"""PID-addressable sparse corpus backed by JSONL offsets.""" from __future__ import annotations from dataclasses import dataclass from functools import lru_cache import hashlib import json from pathlib import Path from rag_assignment.utils.load_utils import DocEntry FIELDS = {"pid", "title", "original_text", "lexical_text", "position_idx"} RAW_FIELDS = {"pid", "title", "text"} def iter_jsonl(path: Path): with path.open(encoding="utf-8") as source: for line in source: if line.strip(): yield json.loads(line) @dataclass(frozen=True, slots=True) class Passage: pid: int | str title: str original_text: str position_idx: int @property def pair_text(self) -> str: return f"{self.title}\n{self.original_text}" def as_doc(self) -> DocEntry: return DocEntry(self.pid, self.title, self.original_text) class ProcessedCorpus: def __init__(self, path: Path, *, raw: bool = False): self.path = path self.raw = raw keys: dict[str, int] = {} digest = hashlib.sha256() evidence_digest = hashlib.sha256() with path.open("rb") as stream: while line := stream.readline(): digest.update(line) if not line.strip(): continue row = json.loads(line) if set(row) != (RAW_FIELDS if raw else FIELDS): expected = "raw assignment corpus" if raw else "sparse processed corpus" raise ValueError(f"Invalid schema in {path}; expected the {expected}") pid = str(row["pid"]) if pid in keys or type(row["pid"]) not in (int, str) or not pid: raise ValueError(f"Invalid or duplicate PID {pid!r}") if not raw and (type(row["position_idx"]) is not int or row["position_idx"] < 0): raise ValueError(f"Invalid position_idx for PID {pid!r}") if not raw: evidence_digest.update(json.dumps( (row["pid"], row["title"], row["original_text"]), ensure_ascii=False, separators=(",", ":"), ).encode("utf-8")) evidence_digest.update(b"\n") keys[pid] = stream.tell() - len(line) if not keys: raise ValueError(f"Empty corpus: {path}") self.sha256 = digest.hexdigest() self.evidence_sha256 = evidence_digest.hexdigest() self.offsets = keys self.keys = tuple(keys) self._source = path.open("rb") self.get = lru_cache(maxsize=8192)(self._read) def _read(self, pid: str) -> Passage: self._source.seek(self.offsets[pid]) row = json.loads(self._source.readline()) return Passage(row["pid"], row["title"], row["text"] if self.raw else row["original_text"], 0 if self.raw else row["position_idx"]) def close(self): self._source.close() self.get.cache_clear() def __enter__(self): return self def __exit__(self, *args): self.close()