File size: 4,617 Bytes
2ef05ec | 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 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 | #!/usr/bin/env python3
"""Build SecureCodePairs v1.2.0 JSONL splits from curated records.
- Injects cvss_vector for every code record (derived from severity + flags).
- Splits code records into train / validation / test / benchmark (fixed seed).
- Writes LLM security trajectories to a separate file (trajectories.jsonl).
- benchmark split is a curated, balanced subset for leaderboard-style eval.
"""
import json
import os
import random
from data import RECORDS, TRAJECTORIES
from cvss import compute_cvss
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DATASET_DIR = os.path.join(ROOT, "data")
SEED = 42
VERSION = "1.2.0"
VALID_LANGS = {
"Python", "Java", "JavaScript", "TypeScript", "Go", "PHP", "C#",
"Kotlin", "Swift", "Rust", "Ruby", "C", "C++", "Scala", "YAML",
}
REQUIRED_FIELDS = [
"id", "language", "framework", "title", "description",
"owasp", "owasp_api", "owasp_llm", "cwe", "mitre_attack",
"severity", "difficulty", "vulnerable_code", "secure_code", "patch",
"root_cause", "attack", "impact", "fix", "guideline", "tags", "metadata",
"cvss_vector",
]
def validate_records():
errs = []
ids = set()
for r in RECORDS:
rid = r.get("id")
if rid in ids:
errs.append(f"duplicate id {rid}")
ids.add(rid)
for f in REQUIRED_FIELDS:
v = r.get(f)
if f in ("owasp_api", "owasp_llm"):
if v and not (str(v).startswith("API") or str(v).startswith("LLM")):
errs.append(f"{rid}: odd {f}: {v}")
continue
if v is None or (isinstance(v, str) and not v.strip()):
errs.append(f"{rid}: missing/empty {f}")
if r.get("language") not in VALID_LANGS:
errs.append(f"{rid}: invalid language {r.get('language')}")
if not isinstance(r.get("tags"), list) or not r.get("tags"):
errs.append(f"{rid}: tags must be non-empty list")
if not isinstance(r.get("metadata"), dict):
errs.append(f"{rid}: metadata must be dict")
if not str(r.get("cwe", "")).startswith("CWE-"):
errs.append(f"{rid}: bad cwe {r.get('cwe')}")
if not str(r.get("cvss_vector", "")).startswith("CVSS:"):
errs.append(f"{rid}: bad cvss_vector {r.get('cvss_vector')}")
return errs
def main():
# Inject cvss_vector for code records
for r in RECORDS:
if "cvss_vector" not in r or not str(r["cvss_vector"]).startswith("CVSS:"):
r["cvss_vector"] = compute_cvss(r)
errs = validate_records()
if errs:
print("VALIDATION FAILED:")
for e in errs[:40]:
print(" -", e)
raise SystemExit(1)
print(f"Validated {len(RECORDS)} code records OK (cvss_vector injected).")
rng = random.Random(SEED)
items = list(RECORDS)
rng.shuffle(items)
n = len(items)
n_test = max(1, round(n * 0.12))
n_val = max(1, round(n * 0.12))
n_bench = max(1, round(n * 0.10))
test = items[:n_test]
val = items[n_test:n_test + n_val]
bench = items[n_test + n_val:n_test + n_val + n_bench]
train = items[n_test + n_val + n_bench:]
os.makedirs(DATASET_DIR, exist_ok=True)
for name, split in (("train", train), ("validation", val),
("test", test), ("benchmark", bench)):
path = os.path.join(DATASET_DIR, f"{name}.jsonl")
with open(path, "w", encoding="utf-8") as f:
for rec in split:
f.write(json.dumps(rec, ensure_ascii=False) + "\n")
print(f"Wrote {len(split)} records -> {path}")
# Trajectories (separate collection, outside dataset/ so the viewer
# auto-detects code splits cleanly without schema mismatch)
traj_dir = os.path.join(ROOT, "trajectories")
os.makedirs(traj_dir, exist_ok=True)
traj_path = os.path.join(traj_dir, "trajectories.jsonl")
with open(traj_path, "w", encoding="utf-8") as f:
for t in TRAJECTORIES:
f.write(json.dumps(t, ensure_ascii=False) + "\n")
print(f"Wrote {len(TRAJECTORIES)} trajectories -> {traj_path}")
manifest = {
"version": VERSION,
"total_code_records": n,
"total_trajectories": len(TRAJECTORIES),
"splits": {"train": len(train), "validation": len(val),
"test": len(test), "benchmark": len(bench)},
"seed": SEED,
"languages": sorted(VALID_LANGS),
}
with open(os.path.join(ROOT, "manifest.json"), "w", encoding="utf-8") as f:
json.dump(manifest, f, indent=2)
print("Done.")
if __name__ == "__main__":
main()
|