ccrb / scripts /pipeline_utils.py
prshrs's picture
Upload CCRB v0.2-dev cybersecurity retrieval benchmark
8510f62 verified
Raw History Blame Contribute Delete
3.27 kB
"""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