AppSecBench / scripts /statistics.py
ismailtasdelen's picture
Upload folder using huggingface_hub
d38f080 verified
Raw
History Blame Contribute Delete
7.12 kB
#!/usr/bin/env python3
"""AppSecBench v1.1.0 statistics + summaries (CSV + JSON + Markdown charts)."""
import csv
import json
import os
from collections import Counter, OrderedDict
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DATASET_DIR = os.path.join(ROOT, "dataset")
STAT_DIR = os.path.join(ROOT, "statistics")
SPLITS = ("train", "validation", "test")
def load_all():
recs = []
for name in SPLITS:
with open(os.path.join(DATASET_DIR, f"{name}.jsonl"), encoding="utf-8") as f:
for line in f:
line = line.strip()
if line:
recs.append(json.loads(line))
return recs
def write_csv(path, rows, header):
with open(path, "w", newline="", encoding="utf-8") as f:
w = csv.writer(f)
w.writerow(header)
w.writerows(rows)
def bar(label, count, total, width=36):
n = max(1, int(round(count / max(total, 1) * width)))
return f"{label[:34]:<34} | {'#' * n} {count} ({count / max(total, 1) * 100:.0f}%)"
def main():
recs = load_all()
total = len(recs)
os.makedirs(STAT_DIR, exist_ok=True)
langs = Counter(r["language"] for r in recs)
fw = Counter(r["framework"] for r in recs if r["framework"] != "None")
sev = Counter(r["expected_severity"] for r in recs)
cwe = Counter(r["expected_cwe"] for r in recs)
owasp = Counter(r["expected_owasp"] for r in recs)
cat = Counter(r["category"] for r in recs)
diff = Counter(r["metadata"]["difficulty"] for r in recs)
vuln = Counter(r["vulnerability_name"] for r in recs)
app = Counter(r["application_type"] for r in recs)
conf = Counter(r["expected_confidence"] for r in recs)
src = Counter(r["source_type"] for r in recs)
# CVSS score buckets
buckets = Counter()
for r in recs:
s = r["expected_cvss_score"]
if s >= 9.0:
buckets["Critical (9.0-10.0)"] += 1
elif s >= 7.0:
buckets["High (7.0-8.9)"] += 1
elif s >= 4.0:
buckets["Medium (4.0-6.9)"] += 1
else:
buckets["Low (0.1-3.9)"] += 1
write_csv(os.path.join(STAT_DIR, "language_distribution.csv"),
[(k, v) for k, v in langs.most_common()], ["language", "count"])
write_csv(os.path.join(STAT_DIR, "framework_distribution.csv"),
[(k, v) for k, v in fw.most_common()], ["framework", "count"])
write_csv(os.path.join(STAT_DIR, "severity_distribution.csv"),
[(k, v) for k, v in sev.most_common()], ["severity", "count"])
write_csv(os.path.join(STAT_DIR, "cwe_distribution.csv"),
[(k, v) for k, v in cwe.most_common()], ["cwe", "count"])
write_csv(os.path.join(STAT_DIR, "owasp_distribution.csv"),
[(k, v) for k, v in owasp.most_common()], ["owasp", "count"])
write_csv(os.path.join(STAT_DIR, "category_distribution.csv"),
[(k, v) for k, v in cat.most_common()], ["category", "count"])
write_csv(os.path.join(STAT_DIR, "difficulty_distribution.csv"),
[(k, v) for k, v in diff.most_common()], ["difficulty", "count"])
write_csv(os.path.join(STAT_DIR, "vulnerability_distribution.csv"),
[(k, v) for k, v in vuln.most_common()], ["vulnerability", "count"])
write_csv(os.path.join(STAT_DIR, "application_type_distribution.csv"),
[(k, v) for k, v in app.most_common()], ["application_type", "count"])
write_csv(os.path.join(STAT_DIR, "cvss_score_distribution.csv"),
[(k, v) for k, v in buckets.most_common()], ["cvss_band", "count"])
write_csv(os.path.join(STAT_DIR, "confidence_distribution.csv"),
[(k, v) for k, v in conf.most_common()], ["confidence", "count"])
write_csv(os.path.join(STAT_DIR, "source_type_distribution.csv"),
[(k, v) for k, v in src.most_common()], ["source_type", "count"])
# Split sizes
split_sizes = OrderedDict()
for name in SPLITS:
with open(os.path.join(DATASET_DIR, f"{name}.jsonl")) as f:
split_sizes[name] = sum(1 for _ in f if _.strip())
summary = {
"name": "AppSecBench",
"version": "1.1.0",
"total_records": total,
"splits": split_sizes,
"languages": dict(langs),
"frameworks": dict(fw),
"categories": dict(cat),
"severities": dict(sev),
"cwes": dict(cwe),
"owasps": dict(owasp),
"difficulties": dict(diff),
"vulnerabilities": dict(vuln),
"application_types": dict(app),
"cvss_bands": dict(buckets),
"confidence": dict(conf),
"source_types": dict(src),
"unique_languages": len(langs),
"unique_frameworks": len(fw),
"unique_cwes": len(cwe),
"unique_owasps": len(owasp),
"unique_vulnerabilities": len(vuln),
"unique_categories": len(cat),
}
with open(os.path.join(STAT_DIR, "summary.json"), "w", encoding="utf-8") as f:
json.dump(summary, f, indent=2)
# Markdown charts
lines = [f"# AppSecBench — Statistics (v1.0.0)", "",
f"Total records: **{total}**", "",
f"Splits: train={split_sizes['train']}, validation={split_sizes['validation']}, test={split_sizes['test']}", "",
"## Language distribution", ""]
for k, v in langs.most_common():
lines.append(bar(k, v, total))
lines += ["", "## Framework distribution", ""]
for k, v in fw.most_common():
lines.append(bar(k, v, total))
lines += ["", "## Severity distribution", ""]
for k in ("Critical", "High", "Medium", "Low"):
if k in sev:
lines.append(bar(k, sev[k], total))
lines += ["", "## CVSS score band", ""]
for k, v in buckets.most_common():
lines.append(bar(k, v, total))
lines += ["", "## Category distribution", ""]
for k, v in cat.most_common():
lines.append(bar(k, v, total))
lines += ["", "## Vulnerability distribution", ""]
for k, v in vuln.most_common():
lines.append(bar(k, v, total))
lines += ["", "## OWASP distribution", ""]
for k, v in owasp.most_common():
lines.append(bar(k, v, total))
lines += ["", "## CWE distribution (top 20)", ""]
for k, v in cwe.most_common(20):
lines.append(bar(k, v, total))
lines += ["", "## Difficulty distribution", ""]
for k in ("Beginner", "Intermediate", "Advanced", "Expert", "Real-world enterprise"):
if k in diff:
lines.append(bar(k, diff[k], total))
lines += ["", "## Application type distribution", ""]
for k, v in app.most_common():
lines.append(bar(k, v, total))
lines += ["", "## Source type distribution", ""]
for k, v in src.most_common():
lines.append(bar(k, v, total))
with open(os.path.join(STAT_DIR, "statistics.md"), "w", encoding="utf-8") as f:
f.write("\n".join(lines))
print(f"Statistics written for {total} records -> {STAT_DIR}")
print(f"languages={len(langs)} frameworks={len(fw)} cwes={len(cwe)} owasps={len(owasp)} vulns={len(vuln)}")
if __name__ == "__main__":
main()