File size: 3,155 Bytes
46e547f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
81
82
83
84
85
86
87
88
89
90
91
92
"""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()