| |
| """Loading helpers for the CVE proof corpus. |
| |
| Plain Python, no dependencies: |
| |
| from loader import load_corpus |
| for rec in load_corpus(): |
| print(rec["cve"], rec["relation_in_words"]) |
| |
| With `datasets` installed: |
| |
| from datasets import load_dataset |
| ds = load_dataset("json", data_files="cve-proof-corpus.jsonl", split="train") |
| """ |
|
|
| from __future__ import annotations |
|
|
| import json |
| from collections.abc import Iterator |
| from pathlib import Path |
| from typing import Any |
|
|
| DEFAULT_PATH = Path(__file__).resolve().parent / "cve-proof-corpus.jsonl" |
|
|
|
|
| def load_corpus(path: Path | str = DEFAULT_PATH) -> list[dict[str, Any]]: |
| """Read every record into a list.""" |
| p = Path(path) |
| return [json.loads(line) for line in p.read_text(encoding="utf-8").splitlines() if line.strip()] |
|
|
|
|
| def iter_corpus(path: Path | str = DEFAULT_PATH) -> Iterator[dict[str, Any]]: |
| """Stream records one at a time.""" |
| p = Path(path) |
| with p.open(encoding="utf-8") as fh: |
| for line in fh: |
| if line.strip(): |
| yield json.loads(line) |
|
|
|
|
| def to_certkit(record: dict[str, Any]) -> tuple[dict[str, Any], dict[str, Any]]: |
| """Split a record into the (spec, certificate) pair certkit expects.""" |
| return record["spec"], record["certificate"] |
|
|
|
|
| def by_cwe(path: Path | str = DEFAULT_PATH) -> dict[str, list[str]]: |
| """Group record ids by weakness class.""" |
| out: dict[str, list[str]] = {} |
| for rec in iter_corpus(path): |
| out.setdefault(rec["cwe"], []).append(rec["id"]) |
| return out |
|
|
|
|
| if __name__ == "__main__": |
| corpus = load_corpus() |
| print(f"{len(corpus)} records") |
| for rec in corpus: |
| print(f" {rec['id']:24s} {rec['cve']:16s} {rec['cwe']:9s} {rec['project']}") |
| print() |
| print("by weakness:") |
| for cwe, ids in sorted(by_cwe().items()): |
| print(f" {cwe}: {', '.join(ids)}") |
|
|