File size: 3,274 Bytes
8510f62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
93
94
95
96
97
98
99
100
101
"""Shared dataset loading and schema helpers for CCRB."""

from __future__ import annotations

import csv
import json
from dataclasses import dataclass
from pathlib import Path
from typing import Any

TRACKS: tuple[str, ...] = (
    "cve",
    "cwe",
    "attack",
    "advisories",
    "remediation",
    "code",
)

VALID_RELEVANCE_GRADES: frozenset[int] = frozenset({0, 1, 2, 3})
VALID_SPLITS: frozenset[str] = frozenset({"dev", "test"})
VALID_QUERY_TYPES: frozenset[str] = frozenset({"nl", "code", "hybrid"})


@dataclass(frozen=True)
class QueryRecord:
    """Validated query entry from data/queries/<track>.jsonl."""

    query_id: str
    query: str
    track: str
    split: str | None = None
    query_type: str | None = None


@dataclass(frozen=True)
class DocumentRecord:
    """Validated document entry from data/documents/<track>.jsonl."""

    document_id: str
    title: str
    text: str
    source: str
    track: str


def load_jsonl(path: Path) -> list[tuple[int, dict[str, Any]]]:
    """Load non-empty lines from a JSONL file as (1-based line number, dict)."""
    records: list[tuple[int, dict[str, Any]]] = []
    with path.open("r", encoding="utf-8") as handle:
        for line_no, raw_line in enumerate(handle, start=1):
            stripped = raw_line.strip()
            if not stripped:
                continue
            obj = json.loads(stripped)
            if not isinstance(obj, dict):
                raise ValueError(f"{path}:{line_no}: expected JSON object, got {type(obj).__name__}")
            records.append((line_no, obj))
    return records


def load_qrels(path: Path) -> dict[str, dict[str, int]]:
    """Load a TSV qrels file into {query_id: {document_id: relevance}}.

    Supports optional header row (`query_id\\tdocument_id\\trelevance`).
    """
    qrels: dict[str, dict[str, int]] = {}
    with path.open("r", encoding="utf-8", newline="") as handle:
        reader = csv.reader(handle, delimiter="\t")
        for row_no, row in enumerate(reader, start=1):
            if not row or all(not cell.strip() for cell in row):
                continue
            if row_no == 1 and [c.strip().lower() for c in row[:3]] == [
                "query_id",
                "document_id",
                "relevance",
            ]:
                continue
            if len(row) != 3:
                raise ValueError(
                    f"{path}:{row_no}: expected 3 tab-separated columns, got {len(row)}"
                )
            query_id, document_id, rel_raw = (cell.strip() for cell in row)
            try:
                rel = int(rel_raw)
            except ValueError as exc:
                raise ValueError(
                    f"{path}:{row_no}: relevance must be integer in 0..3, got {rel_raw!r}"
                ) from exc
            if rel not in VALID_RELEVANCE_GRADES:
                raise ValueError(
                    f"{path}:{row_no}: relevance must be in 0..3, got {rel}"
                )
            doc_map = qrels.setdefault(query_id, {})
            if document_id in doc_map:
                raise ValueError(
                    f"{path}:{row_no}: duplicate (query_id={query_id!r}, document_id={document_id!r})"
                )
            doc_map[document_id] = rel
    return qrels