Download research/build.py from Helinity/python-security-benchmark: direct link, hf CLI and curl.
- Browser
- Download file 5.11 kB
-
https://huggingface.co/datasets/Helinity/python-security-benchmark/resolve/main/research/build.py
- Command line
-
hf download hf://datasets/Helinity/python-security-benchmark/research/build.py
-
curl -L -o build.py https://huggingface.co/datasets/Helinity/python-security-benchmark/resolve/main/research/build.py
5.11 kB
| """Generate or verify all research release files while preserving the legacy corpus.""" | |
| import argparse | |
| from collections import Counter | |
| from hashlib import sha256 | |
| import json | |
| from pathlib import Path | |
| import subprocess | |
| from scripts.generate_dataset import write_dataset | |
| from .catalog import BASELINE_SHA256, build_records, validate_rows | |
| from .leakage import MIN_TOKENS, NEAR_THRESHOLD, SEED, SHINGLE_SIZE, SPLITS | |
| from .leakage import grouped_assignments, similarity, validate_split_boundaries | |
| from .verify import run_verification | |
| OUTPUT = Path(__file__).resolve().parents[1] / "data" / "research" | |
| def json_bytes(value): | |
| return (json.dumps(value, ensure_ascii=False, indent=2, sort_keys=True) + "\n").encode("utf-8") | |
| def jsonl_bytes(rows): | |
| return "".join(json.dumps(row, ensure_ascii=False, sort_keys=True) + "\n" for row in rows).encode("utf-8") | |
| def counts(rows): | |
| return { | |
| "samples": len(rows), | |
| "labels": dict(Counter(row["label"] for row in rows)), | |
| "provenance_sets": dict(Counter(row["provenance"]["collection"] for row in rows)), | |
| "verification_statuses": dict(Counter(row["verification_status"] for row in rows)), | |
| "cwe_count": len({row["cwe_id"] for row in rows}), | |
| "pairs": len({row["pair_id"] for row in rows if row["pair_id"]}), | |
| "hard_negatives": sum(row["hard_negative"] for row in rows), | |
| } | |
| def release(evidence): | |
| rows = build_records(evidence) | |
| report = similarity(rows) | |
| assignments, group_counts = grouped_assignments(rows, report) | |
| for row in rows: | |
| row["split"], row["leakage_group_id"] = assignments[row["sample_id"]] | |
| validate_rows(rows, evidence) | |
| validate_split_boundaries(rows, report) | |
| verified = [row for row in rows if row["verification_status"] == "behavior_verified"] | |
| # Verified variants must travel together. A partial pair cannot enter the benchmark. | |
| verified_pair_members = Counter(row["pair_id"] for row in verified if row["pair_id"]) | |
| if any(count != 2 for count in verified_pair_members.values()): | |
| raise ValueError("A behavior-verified pair is incomplete") | |
| statistics = { | |
| "baseline_sha256": BASELINE_SHA256, | |
| "corpus": counts(rows), | |
| "benchmark": counts(verified), | |
| "cwes": { | |
| cwe: { | |
| "corpus": counts([row for row in rows if row["cwe_id"] == cwe]), | |
| "benchmark": counts([row for row in verified if row["cwe_id"] == cwe]), | |
| } | |
| for cwe in sorted({row["cwe_id"] for row in rows}, key=lambda cwe: int(cwe.split("-")[1])) | |
| }, | |
| "splits": {}, | |
| "sha256": {}, | |
| } | |
| files = {"evidence.json": json_bytes(evidence)} | |
| for split in SPLITS: | |
| corpus_split = [row for row in rows if row["split"] == split] | |
| benchmark_split = [row for row in verified if row["split"] == split] | |
| if {row["label"] for row in benchmark_split} != {"insecure", "secure"}: | |
| raise ValueError(f"Benchmark split {split} must include both target classes") | |
| statistics["splits"][split] = { | |
| "groups": group_counts[split], | |
| "corpus": counts(corpus_split), | |
| "benchmark": counts(benchmark_split), | |
| "families": sorted({row["scenario_family_id"] for row in corpus_split}), | |
| } | |
| files[f"corpus/{split}.jsonl"] = jsonl_bytes(corpus_split) | |
| files[f"benchmark/{split}.jsonl"] = jsonl_bytes(benchmark_split) | |
| files["leakage.json"] = json_bytes({ | |
| "seed": SEED, | |
| "weight_targets": SPLITS, | |
| "normalized_token_shingle_size": SHINGLE_SIZE, | |
| "minimum_tokens": MIN_TOKENS, | |
| "token_jaccard_threshold": NEAR_THRESHOLD, | |
| "cross_split_violations": 0, | |
| "component_counts": group_counts, | |
| **report, | |
| }) | |
| statistics["sha256"] = {name: sha256(content).hexdigest() for name, content in sorted(files.items())} | |
| files["statistics.json"] = json_bytes(statistics) | |
| return files, statistics | |
| def compare_release(files, output=OUTPUT): | |
| stale = [name for name, content in files.items() if not (output / name).is_file() or (output / name).read_bytes() != content] | |
| if stale: | |
| raise ValueError("Missing or stale research files: " + ", ".join(stale)) | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--check", action="store_true", help="verify fixtures and compare generated bytes") | |
| args = parser.parse_args() | |
| try: | |
| files, statistics = release(run_verification()) | |
| if args.check: | |
| compare_release(files) | |
| else: | |
| for name, content in files.items(): | |
| write_dataset(OUTPUT / name, content) | |
| except (SyntaxError, ValueError, OSError, subprocess.TimeoutExpired) as error: | |
| parser.exit(1, f"{error}\n") | |
| action = "Verified" if args.check else "Generated" | |
| print( | |
| f"{action} {statistics['corpus']['samples']} annotated samples, " | |
| f"{statistics['benchmark']['samples']} behavior-verified samples, {len(files)} release files." | |
| ) | |
| if __name__ == "__main__": | |
| main() | |