File size: 7,117 Bytes
8df6aa0
d38f080
8df6aa0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d38f080
8df6aa0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
#!/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()