josh-hud commited on
Commit
ed663e5
·
verified ·
1 Parent(s): 5e666bf

Add shards 8-23, eval set, docs, generator

Browse files
.gitattributes CHANGED
@@ -58,3 +58,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
 
 
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
61
+ eval_creddata.jsonl filter=lfs diff=lfs merge=lfs -text
DATA_DICTIONARY.md ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # code-pii POC dataset: data dictionary
2
+
3
+ Span-labeled source code for training detectors of **code-related sensitive data** (passwords, API keys, tokens, private keys, emails). Not classic PII (no names/addresses/SSNs). Proof of concept; everything is generated by `generate_dataset.py` and reproducible with `--seed`.
4
+
5
+ ## 1. How the dataset is built
6
+
7
+ **Seed dataset.** The only human-labeled input is [Samsung/CredData](https://github.com/Samsung/CredData) (Apache-2.0): 67,896 candidate lines in 11,565 real GitHub files across 337 repositories, each line marked GroundTruth `T` (real credential, 15,753), `F` (looks like a credential but is not, 48,061) or `X` (ambiguous, 4,082), with a category and, for most `T` rows, the column range of the secret value. CredData's own pipeline (`download_data.py`) clones the repos, keeps only files that have at least one labeled line and format-preservingly obfuscates every true secret, so no live credential is ever present. `build_priors.py` parses the CSVs plus the rebuilt files and extracts `priors.json`: the label distribution (after collapsing ~200 fine-grained CredData categories into `api_key`/`password`/`token`/`private_key`, with UUID demoted to a hard negative), the syntactic context of each secret (assignment, JSON key, YAML key, env assignment, comment, URL credential, auth header, function argument, PEM block, derived by regexes over the text preceding the value), the variable-name vocabulary per label (top 40, e.g. `password` 1,383, `key` 3,454, `sharedsecret` 846), value length/charset statistics per label, quote style, file-extension frequencies for both true and false rows, and the number of secrets per file. The same pass emits `eval_creddata.jsonl`: every labeled CredData line with +-3 lines of context, as real, non-synthetic evaluation data (true positives and the `F` rows as gold hard negatives).
8
+
9
+ **Base corpus.** [codeparrot/github-code-clean](https://huggingface.co/datasets/codeparrot/github-code-clean) (880 parquet shards, 30 languages, per-file `license` column, not gated: the Hub API reports `gated: false`). Shards are fetched directly over HTTPS so nothing but the shards actually consumed is downloaded. Rows are kept only if `license` is in {mit, apache-2.0, bsd-2-clause, bsd-3-clause, isc, unlicense, cc0-1.0} (about 63% of rows) and the file is 200 B to 200 KB. Of the dropped rows, GPL/LGPL/AGPL/MPL/EPL account for nearly all.
10
+
11
+ **Injection.** For each kept file a coin with `--inject-frac` (0.75) decides whether anything is injected; 85% of those receive 1-5 secrets (count sampled from CredData's secrets-per-file histogram with the "10+" bucket damped) and 0-3 hard negatives. The rest (~36% of records end up with zero secret spans) are pure negatives. For each secret: a label is drawn from the CredData label distribution (plus a fixed 12% share for `email`, which CredData does not annotate); a syntactic context is drawn from CredData's per-label context distribution; a variable name from the per-label vocabulary; a value from the generators below. A language table (31 languages + generic fallback) renders the construct in the file's syntax: assignments (`const x = "..."`, `String x = "..."`, `#define X "..."`, `ENV X=...`, `set(X "...")`...), dictionary/object keys, `.env`/shell exports, comments with the language's comment leader, URL credentials (`postgres://user:PASS@host/db`, span = password only), `Authorization: Bearer/Basic` headers in the language's HTTP idiom, and PEM blocks as heredocs/template literals/concatenated string literals. The rendered line is inserted at a uniformly random line boundary, indented like the following line. Offsets are computed during assembly and asserted (`text[start:end] == value`) for every span before writing.
12
+
13
+ **Value generators.** `api_key`: AWS access key id (`AKIA`+16), AWS secret (40 base64), Google (`AIza`+35), Stripe (`sk_live_`/`sk_test_`/`rk_live_`+24), SendGrid, Twilio, Mailgun, OpenAI, Anthropic, Azure client secret, and generic hex (32-64), base64 (24-64 raw bytes) and alphanumeric keys (weighted toward generic, as in CredData). `token`: GitHub classic (`ghp_/gho_/ghs_`+36) and fine-grained PATs, Slack tokens and webhooks, JWTs (real base64url header.payload.signature), GitLab, npm, Discord, DigitalOcean, Hugging Face, opaque bearer tokens, Basic-auth base64 of `user:password`. `password`: Faker passwords, word+digits+symbol patterns, short lowercase alphanumerics (length distribution follows CredData: median 9, p90 21). `private_key`: PEM blocks (RSA/EC/DSA/OPENSSH/PKCS8 headers, 64-char base64 lines, realistic lengths). `email`: Faker free/company/domain emails, never `example.*`.
14
+
15
+ **Hard negatives** (label `not_secret`): placeholders (`CHANGEME`, `<YOUR_API_KEY>`, AWS's documented `AKIAIOSFODNN7EXAMPLE`, `ghp_xxx...`, `********`), `example.com`/`test.com`/`localhost` emails, UUIDs, MD5/SHA-1/SHA-256 hex digests, environment-variable references (`os.environ["API_KEY"]`, `${{ secrets.TOKEN }}`...), public keys (PEM `PUBLIC KEY`, `ssh-rsa ...`), base64 of plain text, and version/IP/path/package identifiers. Negatives are rendered with the same constructs but with names that fit the value (`checksum`, `commit`, `request_id`, `public_key`, `version`, ...), except placeholders, example emails and env references, which deliberately use secret-like names (`password = "<YOUR_API_KEY>"`).
16
+
17
+ **Validation.** `validate.py` re-checks offsets on every span (0 failures on 151k records), tabulates labels/value types/contexts/languages, runs a gitleaks-style regex scanner for 15 value types (100% of injected spans of those types are found exactly at the labeled offsets, i.e. quoting/escaping/indentation did not mangle them), and prints 20 random records for eyeballing.
18
+
19
+ **Known limitations and biases.** (1) Injected lines are syntactically plausible but semantically disconnected from the surrounding file (a Java constant may land inside a method body, a PEM block inside HTML); a model can learn "line that does not fit" as a cue. (2) Placement is at random line boundaries, not where a human would put config; CredData priors drive *what* and *in which construct*, not *where in the file*. (3) The base corpus is "clean-ish": github-code-clean removed auto-generated files and near-duplicates but was never scrubbed for secrets or PII, so unlabeled real emails, keys or tokens exist in the base text and are implicitly negatives (label noise; eval on `eval_creddata.jsonl` instead of on synthetic splits). (4) Variable-name vocabulary inherits CredData quirks (e.g. `sharedsecret`, `nonce`, `salt` are frequent because a few repos dominate). (5) `generic_hex_key` positives and hash negatives are the same character class; they are disambiguated only by the variable name, which is intentional but means a 40-hex value is not labelable in isolation. (6) Scope is secrets + emails only; names, addresses, phone numbers, SSNs are neither injected nor labeled. (7) Language mix mirrors github-code-clean (Java/JS/HTML/PHP/C heavy; little YAML/JSON/.env, which are where CredData sees most real secrets). (8) CredData values in the eval set are obfuscated by CredData's pipeline (format-preserving), not the originals.
20
+
21
+ ## 2. Record schema (`data/*.parquet`, `sample.jsonl`)
22
+
23
+ One record per source file. Identical schema in JSONL and Parquet.
24
+
25
+ | field | type | nullable | description |
26
+ |---|---|---|---|
27
+ | `id` | string | no | `ghcc-<shard:05d>-<sha1(repo/path)[:16]>`; unique within the dataset |
28
+ | `source` | string | no | always `codeparrot/github-code-clean` |
29
+ | `repo` | string | no | GitHub `owner/name` of the base file |
30
+ | `license` | string | no | base-file license, one of `mit`, `apache-2.0`, `bsd-3-clause`, `bsd-2-clause`, `isc`, `unlicense`, `cc0-1.0` |
31
+ | `language` | string | no | github-code-clean language name (30 values, e.g. `Python`, `JavaScript`, `GO`, `C#`, `Shell`, `Markdown`) |
32
+ | `path` | string | no | path of the file inside its repo |
33
+ | `text` | string | no | full file content **after** injection (UTF-8; may be identical to the base file) |
34
+ | `spans` | list<Span> | no (may be empty) | secret spans; empty list = file has no injected secret |
35
+ | `hard_negatives` | list<Span> | no (may be empty) | spans that look like secrets but are labeled `not_secret` |
36
+
37
+ Span (same struct in both lists):
38
+
39
+ | field | type | nullable | description |
40
+ |---|---|---|---|
41
+ | `start` | int64 | no | start offset into `text`, **0-based, counted in Unicode code points** (Python `str` indexing), not bytes |
42
+ | `end` | int64 | no | end offset, **exclusive**: `text[start:end] == value` |
43
+ | `label` | string | no | `api_key`, `password`, `token`, `private_key`, `email` in `spans`; always `not_secret` in `hard_negatives` |
44
+ | `value_type` | string | no | fine-grained generator id (tables below) |
45
+ | `context` | string | yes (null for hard negatives) | syntactic construct the span was rendered in: `assignment`, `json_key`, `yaml_key`, `env_assignment`, `comment`, `url_credential`, `auth_header`, `function_arg`, `pem_block` |
46
+ | `synthetic` | bool | no | always `true` in the generated data; `false` only in `eval_creddata.jsonl` |
47
+ | `value` | string | no | the exact surface string (redundant with offsets; convenient for checks and for byte-offset recomputation) |
48
+
49
+ Spans never overlap and are sorted by `start`. Multi-line spans occur only for `private_key` and `public_key_pem` (value contains `\n`; inside Java/C/C#/C++ string concatenations the value contains literal `\n" +\n "` sequences, exactly as it appears in `text`). To convert to UTF-8 byte offsets: `len(text[:start].encode())`.
50
+
51
+ Example record (abridged `text`):
52
+
53
+ ```json
54
+ {"id": "ghcc-00001-e57c494c57748745", "source": "codeparrot/github-code-clean",
55
+ "repo": "acme/widgets", "license": "mit", "language": "Python", "path": "app/settings.py",
56
+ "text": "import os\n\nDEBUG = False\nSTRIPE_KEY = 'sk_live_4neiV5Vb5n0oSUNB7MWmlEfQ'\n# login as deploy / Hd7!kq2z\nrequest_id = \"b044a92c-d543-47f6-874a-2ff8411d9576\"\nDATABASE_URL = os.environ['DATABASE_URL']\n",
57
+ "spans": [
58
+ {"start": 39, "end": 71, "label": "api_key", "value_type": "stripe_secret_key", "context": "assignment", "synthetic": true, "value": "sk_live_4neiV5Vb5n0oSUNB7MWmlEfQ"},
59
+ {"start": 93, "end": 101, "label": "password", "value_type": "password", "context": "comment", "synthetic": true, "value": "Hd7!kq2z"}],
60
+ "hard_negatives": [
61
+ {"start": 116, "end": 152, "label": "not_secret", "value_type": "uuid", "context": null, "synthetic": true, "value": "b044a92c-d543-47f6-874a-2ff8411d9576"}]}
62
+ ```
63
+
64
+ ### `eval_creddata.jsonl` schema (real data, different fields)
65
+
66
+ | field | type | description |
67
+ |---|---|---|
68
+ | `id` | string | `creddata-<repo>-<CredData row Id>` |
69
+ | `source` | string | `Samsung/CredData` |
70
+ | `path`, `repo` | string | CredData's anonymized path/repo id (`data/<repo>/<scope>/<file>.<ext>`) |
71
+ | `language_ext` | string | file extension (`py`, `go`, `yml`, `json`, `txt`, ...); `(none)` if absent |
72
+ | `line_start`, `line_end` | int | 1-based line range of the labeled candidate in the original file |
73
+ | `ground_truth` | string | CredData label: `T` real credential, `F` false positive, `X` ambiguous |
74
+ | `category` | string | CredData's raw category string (e.g. `Password`, `AWS Client ID`, `Key:Secret`) |
75
+ | `label` | string / null | collapsed label for `T` rows (`api_key`, `password`, `token`, `private_key`, `uuid`, `other`); null otherwise |
76
+ | `text` | string | the labeled line(s) with 3 lines of context before and after |
77
+ | `spans` | list<Span> | one span (`synthetic: false`, `value_type` = raw category) when `T` and CredData gave value columns; 14,626 of 15,753 `T` rows have a span (the rest are line-level only) |
78
+ | `hard_negatives` | list<Span> | one span with `label: not_secret` when `F` and value columns exist |
79
+
80
+ ## 3. Label taxonomy
81
+
82
+ | label | value_type | format | fake example | placement prior |
83
+ |---|---|---|---|---|
84
+ | api_key | aws_access_key_id | `AKIA[A-Z0-9]{16}` | `AKIASEL09DPS7UX387YV` | CredData "AWS Client ID"/"Key" rows (assignment 73%, json/yaml 14%) |
85
+ | api_key | aws_secret_access_key | 40 base64 chars | `cl8MIYQhAPh1mI57o/dTl/GqlHyezZbNRAi84pOC` | same |
86
+ | api_key | google_api_key | `AIza[0-9A-Za-z_-]{35}` | `AIzaSyD9x...` | same |
87
+ | api_key | stripe_secret_key | `(sk\|rk)_(live\|test)_[A-Za-z0-9]{24}` | `sk_live_4neiV5Vb5n0oSUNB7MWmlEfQ` | same |
88
+ | api_key | sendgrid_api_key | `SG.<22>.<43>` | `SG.abc...` | same |
89
+ | api_key | twilio_api_key | `SK[0-9a-f]{32}` | `SK3f...` | same |
90
+ | api_key | mailgun_api_key | `key-[0-9a-f]{32}` | `key-7a...` | same |
91
+ | api_key | openai_api_key | `sk-(proj-)?[A-Za-z0-9]{48}` | `sk-Fc8sLrF4g3dRlV...` | same |
92
+ | api_key | anthropic_api_key | `sk-ant-api03-<93>AA` | `sk-ant-api03-...AA` | same |
93
+ | api_key | azure_client_secret | 40 chars `[A-Za-z0-9~._-]` | `YJYGkd2XGEbq0xHBUYUN9wY7-ts1F1dO0raZXm1s` | same |
94
+ | api_key | generic_hex_key | 32/40/48/64 lowercase hex | `b4a9fa3ca185cc40da7c9edce315ac17f112fbd4` | CredData "Key"/"Secret"/"Salt"/"Nonce" (hex is the dominant charset: 70%) |
95
+ | api_key | generic_base64_secret | base64 of 24-64 bytes | `r/Y+kPmu4sQFtSoBF4iSX7XKFgdpVk4QiiAx2H5Lwk8=` | same |
96
+ | api_key | generic_alnum_key | 20-40 alphanumerics | `PU5lRtqn363qL3CA2bH1jYRJ` | same |
97
+ | token | github_pat | `gh[pos]_[A-Za-z0-9]{36}` | `ghp_Ig187tXPStYwqtbfh7hArK9jNHCrkejKHHRL` | CredData "Token"/"Bearer Authorization" (auth header 37%, json 24%) |
98
+ | token | github_fine_grained_pat | `github_pat_<22>_<59>` | `github_pat_...` | same |
99
+ | token | slack_token | `xox[abp]-<digits>-<digits>-<24>` | `xoxb-8270581127-6265886739-yPzdfqWY1JoCvnD1cSnmLsxS` | same |
100
+ | token | slack_webhook | `https://hooks.slack.com/services/T../B../..` | ... | same |
101
+ | token | jwt | `eyJ..\.eyJ..\.<sig>` | `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOi...` | same |
102
+ | token | gitlab_pat / npm_token / hf_token / digitalocean_pat / discord_bot_token | `glpat-<20>`, `npm_<36>`, `hf_<34>`, `dop_v1_<64hex>`, `<24>.<6>.<27>` | `hf_Lk...` | same |
103
+ | token | bearer_token_opaque | 32-64 base64url | `YJYGkd2XGEbq0xHBUYUN9wY7...` | same |
104
+ | token | basic_auth_b64 | base64(`user:password`) | `ZGVwbG95OkhkNyFrcTJ6` | CredData "Basic Authorization" |
105
+ | password | password | 5-20 chars, Faker/word-based | `dbComputer@1601`, `pecn95` | CredData "Password"/"URL Credentials" (assignment 33%, yaml 22%, comment 11%, url 8%) |
106
+ | private_key | pem_private_key | `-----BEGIN (RSA\|EC\|DSA\|OPENSSH\|) PRIVATE KEY-----` + base64 lines | see example in `sample.jsonl` | CredData "PEM Private Key" (89% standalone block) |
107
+ | email | email | RFC-ish `local@domain.tld`, never example.* | `stacie16@gardner.com` | not in CredData; fixed mix: assignment 40%, comment 35%, json/yaml 20% |
108
+ | not_secret | placeholder | known dummy values | `AKIAIOSFODNN7EXAMPLE`, `<YOUR_API_KEY>` | secret-like names |
109
+ | not_secret | example_email | `*@example.com/.org`, `test.com`, `localhost`, `company.com` | `nroman@company.com` | email names |
110
+ | not_secret | uuid | RFC 4122 v4, upper or lower | `b044a92c-d543-47f6-874a-2ff8411d9576` | id-like names (CredData labels some UUIDs `T`; here always negative) |
111
+ | not_secret | md5_hash / sha1_git_sha / sha256_hash | 32/40/64 hex | `18ee391e0f19f9f2ed705859ee729aba` | checksum/commit names |
112
+ | not_secret | env_var_reference | code that *reads* a secret | `os.getenv('SECRET_KEY')`, `${{ secrets.TOKEN }}` | secret-like names |
113
+ | not_secret | public_key_pem / ssh_public_key | `-----BEGIN PUBLIC KEY-----`, `ssh-rsa AAAA... user@host` | ... | public-key names |
114
+ | not_secret | base64_non_secret | base64 of an English sentence | `QXVkaWVuY2UgYXJndWUg...` | payload/body names |
115
+ | not_secret | version_or_id | IPv4, semver, package id, path, numeric id | `v7.20.44`, `151.134.43.138` | version/host names |
116
+
117
+ Label counts for this release (24 shards, 1,810,060 records): api_key 1.01M, password 482k, token 364k, email 249k, private_key 216k secret spans; 1.70M hard negatives split evenly over 11 types. See `stats.md`.
118
+
119
+ ## 4. Files
120
+
121
+ | file | what | size / count |
122
+ |---|---|---|
123
+ | `data/part-000NN.parquet` | generated records, one Parquet file per base-corpus shard, zstd; ~75k records / ~600 MB JSONL / ~160 MB Parquet each | 24 files, shards 0-23: 1,810,060 records, 14.4 GB JSONL, 3.84 GB Parquet |
124
+ | `sample.jsonl` | 500 records reservoir-sampled from shards 0-1, same schema | 500 |
125
+ | `eval_creddata.jsonl` | real CredData lines (+-3 lines context), **not synthetic**; use only for evaluation / threshold tuning, never for training if you want an honest number. `T` rows = positives, `F` rows = hard negatives, `X` rows = ignore. Offsets are code-point based like the synthetic data | 67,896 rows; 15,753 T / 48,061 F / 4,082 X; ~90 MB |
126
+ | `priors.json` | CredData-derived statistics that drive the generator | 12 KB |
127
+ | `stats.md` | counts by label/value_type/context/language, size histogram, throughput | |
128
+ | `generate_dataset.py`, `build_priors.py`, `validate.py`, `to_parquet.py`, `make_stats.py`, `requirements.txt` | code | |
129
+
130
+ There is no train/validation split inside the synthetic data; split by `id` hash or by shard (shards are independent samples of the base corpus). Records from the same `repo` can appear in several shards.
131
+
132
+ ## 5. Quick start
133
+
134
+ ```python
135
+ import pyarrow.parquet as pq, glob
136
+ for f in sorted(glob.glob("data/part-*.parquet")): # or: datasets.load_dataset("josh-hud/code-pii", data_files="data/*.parquet", streaming=True)
137
+ for batch in pq.ParquetFile(f).iter_batches(batch_size=1000):
138
+ for rec in batch.to_pylist():
139
+ text = rec["text"]
140
+ for s in rec["spans"]: # positives
141
+ assert text[s["start"]:s["end"]] == s["value"]
142
+ print(rec["language"], s["label"], s["value_type"], s["context"], s["value"][:40])
143
+ for s in rec["hard_negatives"]: # label == "not_secret"
144
+ pass
145
+ ```
146
+
147
+ Regenerate (any size): `python generate_dataset.py --out ./out --target-bytes 40e9 --workers 8` (see README).
README.md ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: other
3
+ license_name: mixed-permissive
4
+ license_details: >-
5
+ Generated records: each record keeps the license of its base file (MIT, Apache-2.0,
6
+ BSD-2/3-Clause, ISC, Unlicense or CC0-1.0, see the `license` column) as redistributed by
7
+ codeparrot/github-code-clean (Apache-2.0 for the compilation). eval_creddata.jsonl and
8
+ priors.json derive from Samsung/CredData (Apache-2.0; source files keep their own
9
+ permissive OSS licenses). Generator code: Apache-2.0.
10
+ task_categories:
11
+ - token-classification
12
+ language:
13
+ - code
14
+ - en
15
+ tags:
16
+ - secrets-detection
17
+ - credential-detection
18
+ - pii
19
+ - code
20
+ - synthetic
21
+ - span-labels
22
+ - security
23
+ pretty_name: code-pii (POC) - span-labeled secrets in source code
24
+ size_categories:
25
+ - 1M<n<10M
26
+ configs:
27
+ - config_name: default
28
+ data_files:
29
+ - split: train
30
+ path: data/*.parquet
31
+ ---
32
+
33
+ # code-pii (proof of concept)
34
+
35
+ Span-labeled source files for fine-tuning an LLM / token classifier to detect **code-related sensitive data**: passwords, API keys, tokens, private keys and emails. Out of scope: names, addresses, phone numbers, SSNs.
36
+
37
+ Built by taking permissively-licensed real files from `codeparrot/github-code-clean` and injecting **format-correct synthetic secrets** at positions and in constructs whose distribution is learned from the human-annotated [Samsung/CredData](https://github.com/Samsung/CredData) corpus, plus labeled **hard negatives** (placeholders, hashes, UUIDs, env-var references, public keys, example.com emails). ~36% of files are left without any secret as pure negatives. CredData's real labeled lines ship separately as a held-out evaluation set.
38
+
39
+ Full field-by-field documentation: [`DATA_DICTIONARY.md`](DATA_DICTIONARY.md). Counts: [`stats.md`](stats.md).
40
+
41
+ ## Contents
42
+
43
+ | path | description |
44
+ |---|---|
45
+ | `data/part-000NN.parquet` | generated training records (one file per base-corpus shard, ~75k records / ~160 MB each, zstd) |
46
+ | `sample.jsonl` | 500 records, same schema, for a quick look |
47
+ | `eval_creddata.jsonl` | 67,896 **real** labeled lines from CredData (+-3 lines of context): 15,753 true secrets, 48,061 annotated false positives, 4,082 ambiguous. Evaluation only. |
48
+ | `priors.json` | CredData-derived placement statistics that drive the generator |
49
+ | `stats.md` | label / value_type / context / language counts, sizes, throughput |
50
+ | `DATA_DICTIONARY.md` | construction narrative, schema, taxonomy, limitations |
51
+ | `generate_dataset.py`, `build_priors.py`, `validate.py`, `to_parquet.py`, `make_stats.py`, `requirements.txt` | everything needed to regenerate at any size |
52
+
53
+ ## Schema
54
+
55
+ ```text
56
+ id string ghcc-<shard>-<sha1(repo/path)[:16]>
57
+ source string "codeparrot/github-code-clean"
58
+ repo, path string origin of the base file
59
+ license string mit | apache-2.0 | bsd-3-clause | bsd-2-clause | isc | unlicense | cc0-1.0
60
+ language string 30 github-code-clean language names
61
+ text string full file after injection
62
+ spans list secret spans (may be empty)
63
+ hard_negatives list look-alike spans labeled not_secret (may be empty)
64
+ span: {start:int64, end:int64, label:str, value_type:str, context:str|null, synthetic:bool, value:str}
65
+ ```
66
+
67
+ Offsets are **0-based Unicode code-point offsets into `text`, end-exclusive**: `text[start:end] == value` holds for every span (asserted at generation time and again by `validate.py`). Convert to bytes with `len(text[:start].encode("utf-8"))`.
68
+
69
+ `label` in `spans`: `api_key`, `password`, `token`, `private_key`, `email`. In `hard_negatives` it is always `not_secret`.
70
+
71
+ `value_type` (positives): `aws_access_key_id`, `aws_secret_access_key`, `google_api_key`, `stripe_secret_key`, `sendgrid_api_key`, `twilio_api_key`, `mailgun_api_key`, `openai_api_key`, `anthropic_api_key`, `azure_client_secret`, `generic_hex_key`, `generic_base64_secret`, `generic_alnum_key`, `github_pat`, `github_fine_grained_pat`, `slack_token`, `slack_webhook`, `jwt`, `gitlab_pat`, `npm_token`, `discord_bot_token`, `digitalocean_pat`, `hf_token`, `bearer_token_opaque`, `basic_auth_b64`, `password`, `pem_private_key`, `email`.
72
+ `value_type` (hard negatives): `placeholder`, `example_email`, `uuid`, `sha256_hash`, `sha1_git_sha`, `md5_hash`, `env_var_reference`, `public_key_pem`, `ssh_public_key`, `version_or_id`, `base64_non_secret`.
73
+
74
+ `context` (how the secret was rendered): `assignment`, `json_key`, `yaml_key`, `env_assignment`, `comment`, `url_credential` (span = the password inside `scheme://user:PASS@host`), `auth_header` (span = the token after `Bearer `/`Basic `), `function_arg`, `pem_block`.
75
+
76
+ Example (abridged):
77
+
78
+ ```json
79
+ {"id":"ghcc-00001-e57c494c57748745","language":"Python","path":"app/settings.py","license":"mit",
80
+ "text":"import os\n\nSTRIPE_KEY = 'sk_live_4neiV5Vb5n0oSUNB7MWmlEfQ'\n# login as deploy / Hd7!kq2z\nrequest_id = \"b044a92c-d543-47f6-874a-2ff8411d9576\"\n",
81
+ "spans":[{"start":25,"end":57,"label":"api_key","value_type":"stripe_secret_key","context":"assignment","synthetic":true,"value":"sk_live_4neiV5Vb5n0oSUNB7MWmlEfQ"},
82
+ {"start":79,"end":87,"label":"password","value_type":"password","context":"comment","synthetic":true,"value":"Hd7!kq2z"}],
83
+ "hard_negatives":[{"start":102,"end":138,"label":"not_secret","value_type":"uuid","context":null,"synthetic":true,"value":"b044a92c-d543-47f6-874a-2ff8411d9576"}]}
84
+ ```
85
+
86
+ ## How it is built (short)
87
+
88
+ 1. **Priors** (`build_priors.py`): parse CredData's `meta/*.csv` (67,896 rows with line + column offsets, category, GroundTruth) and the rebuilt, CredData-obfuscated files. Collapse ~200 categories to the label set, classify each true secret's syntactic context by regex on the text before the value, collect variable-name vocabularies, value length/charset stats, quote style, extension frequencies and secrets-per-file histogram into `priors.json`. Emit every labeled line as `eval_creddata.jsonl`.
89
+ 2. **Base corpus**: stream `codeparrot/github-code-clean` parquet shards over HTTPS (ungated, no click-through), keep rows whose `license` is MIT/Apache-2.0/BSD/ISC/Unlicense/CC0 (~63%) and 200 B-200 KB.
90
+ 3. **Injection** (`generate_dataset.py`): 75% of files get 1-5 secrets (CredData histogram) and 0-3 hard negatives; label, construct and variable name are sampled from the priors; the value comes from a per-type generator; a 31-language syntax table renders the line (assignment, dict/object key, `.env`/export, comment, URL credential, `Authorization` header in the language's HTTP idiom, PEM as heredoc/template literal/string concatenation); the line is inserted at a random line boundary with the neighbor's indentation; offsets are asserted.
91
+ 4. **Validation** (`validate.py`): offsets re-checked (0 failures), label tables, regex scanner with gitleaks-style patterns finds 100% of injected spans of 15 pattern-bearing types at the labeled offsets, 20 random records printed for review.
92
+
93
+ ## Statistics (this release: shards 0-23)
94
+
95
+ 1,810,060 records, 2,319,190 secret spans (api_key 43.5%, password 20.8%, token 15.7%, email 10.7%, private_key 9.3%), 1,696,239 hard negatives, 63.7% of files with >=1 secret, 14.4 GB JSONL / 3.84 GB Parquet (24 files). Languages follow github-code-clean: Java 19%, JavaScript 12%, HTML 11%, PHP 9%, C 8%, Markdown 7%, C# 7%, Python 6%, C++ 5%, Ruby 5%, Go 3%, TypeScript 2%, 18 others. Detailed tables in `stats.md`.
96
+
97
+ ## Regenerating / scaling to 40 GB
98
+
99
+ ```bash
100
+ pip install -r requirements.txt
101
+ # generate 40 GB of JSONL (downloads shards on the fly, ~67 shards, deletes them after use)
102
+ python generate_dataset.py --out ./out40 --target-bytes 40e9 --workers 8 --seed 1
103
+ # optional: convert to parquet (zstd, ~2.3x smaller) and aggregate stats
104
+ python to_parquet.py ./out40 ./out40_parquet 8
105
+ python make_stats.py ./out40 stats.md ./out40_parquet
106
+ python validate.py --data ./out40 --sample-files 2 --write-sample sample.jsonl
107
+ ```
108
+
109
+ Measured throughput: **~90 MB/s of JSONL on 4 vCPUs** (23 MB/s per worker, CPU-bound; shard download is ~35 MB/s per stream and overlaps with processing). 40 GB therefore takes roughly **8 min on 4 cores, ~4 min on 8** plus parquet conversion (~2x generation time). Flags: `--inject-frac` (default 0.75), `--start-shard/--max-shards` to pick disjoint shard ranges for train/validation, `--shard-dir --keep-shards` to reuse downloaded shards, `--min-bytes/--max-bytes`.
110
+
111
+ To rebuild `priors.json` / `eval_creddata.jsonl`: clone CredData, `pip install -r CredData/requirements.txt && python download_data.py --jobs 12` (clones 337 repos, ~14 GB temporary), then `python build_priors.py --creddata CredData`.
112
+
113
+ ## Using `eval_creddata.jsonl`
114
+
115
+ Real code, real annotations, obfuscated secret values (CredData's pipeline replaces every true credential with a format-preserving fake). `ground_truth == "T"` rows are positives (span available for 14,626 of 15,753), `"F"` rows are annotated false positives (treat as hard negatives), `"X"` rows are ambiguous (skip). Its `label` set includes `uuid` and `other`, which the synthetic data treats as negatives/does not emit; map accordingly. Do not train on it.
116
+
117
+ ## Caveats
118
+
119
+ - Injected lines are syntactically plausible but semantically unrelated to the file and placed at random lines; models can learn "out-of-place line" as a cue. Mix with real data (CredData, your own) before trusting precision numbers.
120
+ - The base corpus was never scrubbed for secrets or PII: pre-existing real emails/keys in base files are unlabeled (label noise in the negative class).
121
+ - Hex key positives vs hash negatives are the same character class and are disambiguated only by variable name, by design.
122
+ - Variable-name vocabulary inherits CredData's repo skew (`sharedsecret`, `nonce`, `salt` are over-represented).
123
+ - Language mix is code-heavy; YAML/JSON/.env/properties files, where CredData sees most real secrets, are under-represented because github-code-clean has few of them.
124
+ - Secrets + emails only; no names/addresses/SSNs.
125
+
126
+ ## Licenses
127
+
128
+ - Base corpus: [codeparrot/github-code-clean](https://huggingface.co/datasets/codeparrot/github-code-clean) (dataset compilation Apache-2.0; ungated). Only files whose per-file `license` is MIT, Apache-2.0, BSD-2/3-Clause, ISC, Unlicense or CC0-1.0 are included and each record carries that license; attribution requirements of those licenses apply to the `repo`/`path` listed in each record.
129
+ - Seed / eval: [Samsung/CredData](https://github.com/Samsung/CredData), Apache-2.0 for the repository and annotations; each embedded source file keeps its own permissive license (see CredData's `snapshot.json` and per-repo LICENSE handling).
130
+ - Synthetic values were produced by the generator and Faker; any resemblance to a real credential is coincidental and all values are inert.
131
+ - Generator code in this repo: Apache-2.0.
build_priors.py ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Derive secret-placement priors + a held-out eval set from Samsung/CredData.
3
+
4
+ Usage: python build_priors.py --creddata /path/to/CredData --out-priors priors.json --out-eval eval_creddata.jsonl
5
+
6
+ Requires CredData's `data/` directory to be built (python download_data.py) so the
7
+ labeled lines can be read. Values in CredData `data/` are already obfuscated by the
8
+ CredData pipeline (format-preserving), so the eval set contains no live credentials.
9
+ """
10
+ import argparse, csv, glob, json, os, re, collections, math
11
+
12
+ # Map CredData's fine-grained categories onto the POC label set.
13
+ LABEL_MAP = [
14
+ (r"PEM Private Key|BASE64 Private Key|BASE64 encoded PEM|NKEY Seed|JWK", "private_key"),
15
+ (r"AWS Client ID|AWS Multi|Alibaba|Google API Key|Slack Token|Github|MailGun|Stripe|Twilio|Dropbox|Grafana|Perplexity|Anthropic|WunderGraph|PostHog|Postman|Salesforce|Akamai|Tencent|Azure Access Token|Google OAuth", "api_key"),
16
+ (r"JSON Web Token|PASETO|Bearer Authorization|Basic Authorization|NTLM|Token|OTP", "token"),
17
+ (r"Password|URL Credentials|CURL User Password|SQL Password|CMD Password|Credential", "password"),
18
+ (r"Key|Secret|Auth|API|Salt|Nonce", "api_key"),
19
+ (r"UUID", "uuid"),
20
+ (r".*", "other"),
21
+ ]
22
+
23
+ def map_label(cat):
24
+ for pat, lab in LABEL_MAP:
25
+ if re.search(pat, cat):
26
+ return lab
27
+ return "other"
28
+
29
+ NAME_HINT_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_.\-]*")
30
+
31
+ def classify_context(line, vstart, ext):
32
+ """Coarse syntactic context of the secret within its line."""
33
+ before = line[:vstart]
34
+ b = before.strip()
35
+ low = before.lower()
36
+ if re.search(r"^\s*(#|//|/\*|\*|--|;|<!--|%|')", before):
37
+ ctx = "comment"
38
+ elif re.search(r"[a-z]+://[^/\s]*$", low) or re.search(r"://[^@\s]*:?$", low):
39
+ ctx = "url_credential"
40
+ elif re.search(r"-----BEGIN", line):
41
+ ctx = "pem_block"
42
+ elif re.search(r"(authorization|bearer|basic)\b", low) and re.search(r"(bearer|basic)\s*['\"]?\s*$", low):
43
+ ctx = "auth_header"
44
+ elif re.search(r"[\"'][A-Za-z_][\w.\-]*[\"']\s*:\s*[\"']?$", before):
45
+ ctx = "json_key"
46
+ elif re.search(r"^\s*[\w.\-]+\s*:\s*[\"']?$", before):
47
+ ctx = "yaml_key"
48
+ elif re.search(r"^\s*(export\s+)?[A-Z][A-Z0-9_]*\s*=\s*[\"']?$", before):
49
+ ctx = "env_assignment"
50
+ elif re.search(r"[\w\]\)]\s*(=|:=|=>|<-)\s*(new\s+\w+\()?[\"'`]?$", before) or re.search(r"\b(var|let|const|final|private|public|static|String|string)\b.*=\s*[\"']?$", before):
51
+ ctx = "assignment"
52
+ elif re.search(r"\(\s*[\"']?$", before) or re.search(r",\s*[\"']?$", before):
53
+ ctx = "function_arg"
54
+ elif re.search(r"<[^>]*(value|password)\s*=\s*[\"']$", low) or "<" in b and ">" in b:
55
+ ctx = "xml_attr_or_tag"
56
+ elif re.search(r"[\w\-]+\s*=\s*[\"']?$", before):
57
+ ctx = "ini_or_props"
58
+ elif b == "":
59
+ ctx = "bare_value_line"
60
+ else:
61
+ ctx = "other"
62
+ return ctx
63
+
64
+ def var_name(line, vstart):
65
+ before = line[:vstart]
66
+ m = re.findall(r"([A-Za-z_][A-Za-z0-9_.\-]*)\s*(?:=|:|=>|:=|\()\s*(?:new\s+\w+\()?[\"'`]?\s*$", before)
67
+ if m:
68
+ return m[-1].split(".")[-1].split("-")[-1] if len(m[-1]) < 60 else None
69
+ m = re.findall(r"[\"']([A-Za-z_][A-Za-z0-9_.\-]*)[\"']\s*:\s*[\"']?\s*$", before)
70
+ if m:
71
+ return m[-1]
72
+ return None
73
+
74
+ def charset(v):
75
+ s = set()
76
+ if re.search(r"[a-z]", v): s.add("lower")
77
+ if re.search(r"[A-Z]", v): s.add("upper")
78
+ if re.search(r"[0-9]", v): s.add("digit")
79
+ if re.search(r"[^A-Za-z0-9]", v): s.add("symbol")
80
+ return "+".join(sorted(s))
81
+
82
+ def main():
83
+ ap = argparse.ArgumentParser()
84
+ ap.add_argument("--creddata", required=True)
85
+ ap.add_argument("--out-priors", default="priors.json")
86
+ ap.add_argument("--out-eval", default="eval_creddata.jsonl")
87
+ ap.add_argument("--context-lines", type=int, default=3, help="lines of context around each labeled line in eval")
88
+ a = ap.parse_args()
89
+
90
+ rows = []
91
+ for f in sorted(glob.glob(os.path.join(a.creddata, "meta", "*.csv"))):
92
+ with open(f, newline="", encoding="utf-8") as fh:
93
+ rows.extend(csv.DictReader(fh))
94
+ print("meta rows", len(rows))
95
+
96
+ file_cache = {}
97
+ def read_file(p):
98
+ if p not in file_cache:
99
+ fp = os.path.join(a.creddata, p)
100
+ try:
101
+ with open(fp, "rb") as fh:
102
+ file_cache[p] = fh.read().decode("utf-8", "replace").split("\n")
103
+ except OSError:
104
+ file_cache[p] = None
105
+ return file_cache[p]
106
+
107
+ C = collections.Counter
108
+ pri = {
109
+ "source": "Samsung/CredData meta/*.csv (Apache-2.0)",
110
+ "n_rows": len(rows), "n_true": 0, "n_false": 0, "n_x": 0,
111
+ "category_raw": C(), "label": C(), "context_by_label": collections.defaultdict(C),
112
+ "context": C(), "ext_true": C(), "ext_false": C(), "var_names_by_label": collections.defaultdict(C),
113
+ "value_len_by_label": collections.defaultdict(list), "charset_by_label": collections.defaultdict(C),
114
+ "quote_style": C(), "line_len_true": [], "secrets_per_file": C(), "false_positive_categories": C(),
115
+ "value_prefix_by_label": collections.defaultdict(C),
116
+ }
117
+ per_file_true = C()
118
+ eval_rows = []
119
+ missing = 0
120
+ for r in rows:
121
+ gt = r["GroundTruth"]
122
+ if gt == "T": pri["n_true"] += 1
123
+ elif gt == "F": pri["n_false"] += 1
124
+ else: pri["n_x"] += 1
125
+ cat = r["Category"]
126
+ lab = map_label(cat)
127
+ ext = os.path.splitext(r["FilePath"])[1].lstrip(".").lower() or "(none)"
128
+ lines = read_file(r["FilePath"])
129
+ if lines is None:
130
+ missing += 1
131
+ continue
132
+ try:
133
+ ls = int(r["LineStart"]); le = int(r["LineEnd"] or ls)
134
+ except ValueError:
135
+ continue
136
+ if ls < 1 or ls > len(lines):
137
+ continue
138
+ line = lines[ls - 1]
139
+ vs = r["ValueStart"]; ve = r["ValueEnd"]
140
+ value = None
141
+ if vs not in ("", "-1") and ve not in ("", "-1"):
142
+ vs = int(vs); ve = int(ve)
143
+ if ls == le and 0 <= vs < ve <= len(line):
144
+ value = line[vs:ve]
145
+ elif le > ls: # multiline (PEM)
146
+ value = "\n".join(lines[ls - 1:le])
147
+ if gt == "T":
148
+ pri["category_raw"][cat] += 1
149
+ pri["label"][lab] += 1
150
+ pri["ext_true"][ext] += 1
151
+ per_file_true[r["FilePath"]] += 1
152
+ if value is not None and ls == le:
153
+ ctx = classify_context(line, vs, ext)
154
+ pri["context"][ctx] += 1
155
+ pri["context_by_label"][lab][ctx] += 1
156
+ vn = var_name(line, vs)
157
+ if vn:
158
+ pri["var_names_by_label"][lab][vn.lower()] += 1
159
+ pri["value_len_by_label"][lab].append(len(value))
160
+ pri["charset_by_label"][lab][charset(value)] += 1
161
+ q = line[vs - 1] if vs > 0 else ""
162
+ pri["quote_style"][q if q in "\"'`" else "none"] += 1
163
+ pri["line_len_true"].append(len(line))
164
+ m = re.match(r"[A-Za-z]{2,6}[_\-]", value)
165
+ if m: pri["value_prefix_by_label"][lab][m.group(0)] += 1
166
+ elif le > ls:
167
+ pri["context"]["pem_block"] += 1
168
+ pri["context_by_label"][lab]["pem_block"] += 1
169
+ pri["value_len_by_label"][lab].append(len(value or ""))
170
+ elif gt == "F":
171
+ pri["ext_false"][ext] += 1
172
+ pri["false_positive_categories"][cat] += 1
173
+ # eval record
174
+ lo = max(0, ls - 1 - a.context_lines); hi = min(len(lines), le + a.context_lines)
175
+ text = "\n".join(lines[lo:hi])
176
+ rec = {"id": f"creddata-{r['RepoName']}-{r['Id']}", "source": "Samsung/CredData", "path": r["FilePath"],
177
+ "repo": r["RepoName"], "language_ext": ext, "line_start": ls, "line_end": le, "ground_truth": gt,
178
+ "category": cat, "label": lab if gt == "T" else None, "text": text, "spans": [], "hard_negatives": []}
179
+ if value is not None:
180
+ off = sum(len(l) + 1 for l in lines[lo:ls - 1])
181
+ if ls == le:
182
+ start = off + vs; end = off + ve
183
+ else:
184
+ start = off; end = off + len(value)
185
+ if text[start:end] == value:
186
+ s = {"start": start, "end": end, "label": lab, "value_type": cat, "synthetic": False}
187
+ if gt == "T": rec["spans"].append(s)
188
+ elif gt == "F": rec["hard_negatives"].append(dict(s, label="not_secret"))
189
+ eval_rows.append(rec)
190
+
191
+ for p, n in per_file_true.items():
192
+ pri["secrets_per_file"][min(n, 10)] += 1
193
+
194
+ def stats(xs):
195
+ if not xs: return {}
196
+ xs = sorted(xs); n = len(xs)
197
+ return {"n": n, "min": xs[0], "p10": xs[n // 10], "median": xs[n // 2], "p90": xs[9 * n // 10], "max": xs[-1], "mean": round(sum(xs) / n, 1)}
198
+
199
+ out = {
200
+ "source": pri["source"], "n_rows": pri["n_rows"], "n_true": pri["n_true"], "n_false": pri["n_false"], "n_x": pri["n_x"],
201
+ "missing_files": missing,
202
+ "label_distribution": dict(pri["label"].most_common()),
203
+ "category_raw_top50": dict(pri["category_raw"].most_common(50)),
204
+ "context_distribution": dict(pri["context"].most_common()),
205
+ "context_by_label": {k: dict(v.most_common()) for k, v in pri["context_by_label"].items()},
206
+ "ext_true_top40": dict(pri["ext_true"].most_common(40)),
207
+ "ext_false_top40": dict(pri["ext_false"].most_common(40)),
208
+ "false_positive_categories_top30": dict(pri["false_positive_categories"].most_common(30)),
209
+ "var_names_by_label_top40": {k: dict(v.most_common(40)) for k, v in pri["var_names_by_label"].items()},
210
+ "value_len_by_label": {k: stats(v) for k, v in pri["value_len_by_label"].items()},
211
+ "charset_by_label": {k: dict(v.most_common()) for k, v in pri["charset_by_label"].items()},
212
+ "quote_style": dict(pri["quote_style"].most_common()),
213
+ "line_len_true": stats(pri["line_len_true"]),
214
+ "secrets_per_file_hist": dict(sorted(pri["secrets_per_file"].items())),
215
+ "value_prefix_by_label_top20": {k: dict(v.most_common(20)) for k, v in pri["value_prefix_by_label"].items()},
216
+ }
217
+ with open(a.out_priors, "w") as fh:
218
+ json.dump(out, fh, indent=1)
219
+ with open(a.out_eval, "w") as fh:
220
+ for r in eval_rows:
221
+ fh.write(json.dumps(r, ensure_ascii=False) + "\n")
222
+ print("eval rows", len(eval_rows), "missing files", missing)
223
+ print(json.dumps({k: out[k] for k in ("label_distribution", "context_distribution", "quote_style")}, indent=1))
224
+
225
+ if __name__ == "__main__":
226
+ main()
data/part-00008.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:af55b0c723673aee3770b2037ac76921c00f699202cc56eff716b2ccce944861
3
+ size 156932668
data/part-00009.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4376745b32430a411c08213094708e92feeee1cca8ffc6e87ab843a23afffb6c
3
+ size 163511052
data/part-00010.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:accf01d2cece6a6b2088b0e67015aa19dcea25fbf7abfb8c42ce19e908b4b02b
3
+ size 157608460
data/part-00011.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a5ca30450827c6a50cbdb0e52145ccd12aadc312f9d0d61e5fd4f16712df8b27
3
+ size 160831338
data/part-00012.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9024ed29e41c806511f71c2cc09b8751016da2a6e28d8682d9bd03859ba4ab94
3
+ size 157231805
data/part-00013.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b3329b842594e437f055fae850a4656b2c5b6062f1c3b1411f2dde611779aa91
3
+ size 162674672
data/part-00014.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:96ee1f12e0c6cde22cfd01e9a4abe9a3062b6a795ac828738b49000c942f3874
3
+ size 158412882
data/part-00015.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1250f2e88e4f6b93eee8a79b74093e3fdb76bec1a58156b16f2e449ee29d0df3
3
+ size 161960948
data/part-00016.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d9ca64fe280c8cbde1d840568c890d094ee31750101a5d741949095a19e77b91
3
+ size 157745434
data/part-00017.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b47cfaf0c82988b58c2809d1d80b513b1dc8bb3330361f8fdebaa8a77908075d
3
+ size 161972403
data/part-00018.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:668956b678c15e4ec290c356b40bbf49acb82ef4f4af3974ca81c5f8b60ee864
3
+ size 155522962
data/part-00019.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:78b27fee3e92decf94cc6fd1af49bebfe93aa8542d1c9f677396fda5e04d16fe
3
+ size 162810732
data/part-00020.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cc986ba36137aa1c044eed2d8a78799cd484371f07f0f2049343ee51411864f7
3
+ size 157559410
data/part-00021.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e39380bd2fa952bd064281caeb521187bc5f9300729c3707542106c5f7ea754f
3
+ size 162164664
data/part-00022.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bfb7aac86dc47df16d471ffdf98407f151868a7fd21caa4b1bbbe9762f4d96af
3
+ size 159624230
data/part-00023.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8e28bff5b27d4cdada138659f5b9e672b20f2d67bd4559fb59d927c5fac2239c
3
+ size 162676071
eval_creddata.jsonl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:42fa1ff58f61a3d09246abc24c6c77258750e32c7ecb6c9544ffa951909794b8
3
+ size 89698587
generate_dataset.py ADDED
@@ -0,0 +1,474 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Synthetic secret-injection dataset generator (proof of concept).
3
+
4
+ Streams permissively-licensed files from codeparrot/github-code-clean (parquet shards
5
+ on the Hugging Face Hub), injects format-correct synthetic secrets at positions drawn
6
+ from Samsung/CredData placement priors (priors.json), injects labeled hard negatives,
7
+ and writes span-labeled JSONL.
8
+
9
+ Examples
10
+ # 2 GB using the first shards, 4 worker processes, downloading shards on the fly
11
+ python generate_dataset.py --out /data/poc --target-bytes 2e9 --workers 4
12
+
13
+ # scale: ~40 GB
14
+ python generate_dataset.py --out /data/full --target-bytes 40e9 --workers 8 --start-shard 0
15
+
16
+ # use pre-downloaded shards
17
+ python generate_dataset.py --out /data/poc --shard-dir ./shards --target-bytes 2e9
18
+
19
+ Dependencies: python>=3.9, pyarrow, faker (stdlib otherwise).
20
+ """
21
+ import argparse, base64, hashlib, json, os, random, re, string, sys, time, uuid, urllib.request
22
+ from multiprocessing import Pool
23
+
24
+ try:
25
+ import pyarrow.parquet as pq
26
+ except ImportError:
27
+ sys.exit("pip install pyarrow")
28
+ try:
29
+ from faker import Faker
30
+ except ImportError:
31
+ sys.exit("pip install faker")
32
+
33
+ HF_URL = "https://huggingface.co/datasets/codeparrot/github-code-clean/resolve/main/data/train-{i:05d}-of-00880.parquet"
34
+ N_SHARDS = 880
35
+ PERMISSIVE = {"mit", "apache-2.0", "bsd-3-clause", "bsd-2-clause", "isc", "unlicense", "cc0-1.0"}
36
+
37
+ # --------------------------------------------------------------------------------------
38
+ # Language syntax table: comment prefix, assignment template, quote char, extra forms
39
+ # --------------------------------------------------------------------------------------
40
+ # assign: how a hardcoded variable looks. {n}=name {q}=quote {v}=value
41
+ LANG = {
42
+ "Python": dict(c="#", assign=["{n} = {q}{v}{q}", "{N} = {q}{v}{q}", "self.{n} = {q}{v}{q}", "os.environ[{q}{N}{q}] = {q}{v}{q}"], q=["'", '"'], kw=["{q}{n}{q}: {q}{v}{q},", "{n}={q}{v}{q},"]),
43
+ "JavaScript": dict(c="//", assign=["const {n} = {q}{v}{q};", "let {n} = {q}{v}{q};", "var {n} = {q}{v}{q};", "const {N} = {q}{v}{q};", "process.env.{N} = {q}{v}{q};"], q=["'", '"', "`"], kw=["{n}: {q}{v}{q},", "{q}{n}{q}: {q}{v}{q},"]),
44
+ "TypeScript": dict(c="//", assign=["const {n} = {q}{v}{q};", "private {n} = {q}{v}{q};", "const {N}: string = {q}{v}{q};", "export const {N} = {q}{v}{q};"], q=["'", '"'], kw=["{n}: {q}{v}{q},"]),
45
+ "Java": dict(c="//", assign=["String {n} = {q}{v}{q};", "private static final String {N} = {q}{v}{q};", "final String {n} = {q}{v}{q};"], q=['"'], kw=["props.setProperty({q}{n}{q}, {q}{v}{q});"]),
46
+ "C#": dict(c="//", assign=["string {n} = {q}{v}{q};", "private const string {N} = {q}{v}{q};", "var {n} = {q}{v}{q};"], q=['"'], kw=["[{q}{n}{q}] = {q}{v}{q},"]),
47
+ "GO": dict(c="//", assign=["{n} := {q}{v}{q}", "const {n} = {q}{v}{q}", "var {n} = {q}{v}{q}", "{N} = {q}{v}{q}"], q=['"', "`"], kw=["{q}{n}{q}: {q}{v}{q},", "{n}: {q}{v}{q},"]),
48
+ "PHP": dict(c="//", assign=["${n} = {q}{v}{q};", "define({q}{N}{q}, {q}{v}{q});", "$config[{q}{n}{q}] = {q}{v}{q};"], q=["'", '"'], kw=["{q}{n}{q} => {q}{v}{q},"]),
49
+ "Ruby": dict(c="#", assign=["{n} = {q}{v}{q}", "{N} = {q}{v}{q}", "@{n} = {q}{v}{q}", "ENV[{q}{N}{q}] = {q}{v}{q}"], q=["'", '"'], kw=["{n}: {q}{v}{q},", ":{n} => {q}{v}{q},"]),
50
+ "C": dict(c="//", assign=["const char *{n} = {q}{v}{q};", "static const char {n}[] = {q}{v}{q};", "#define {N} {q}{v}{q}"], q=['"'], kw=[]),
51
+ "C++": dict(c="//", assign=["const std::string {n} = {q}{v}{q};", "std::string {n} = {q}{v}{q};", "#define {N} {q}{v}{q}", "static const char* {n} = {q}{v}{q};"], q=['"'], kw=[]),
52
+ "Rust": dict(c="//", assign=["let {n} = {q}{v}{q};", "const {N}: &str = {q}{v}{q};", "static {N}: &str = {q}{v}{q};"], q=['"'], kw=[]),
53
+ "Scala": dict(c="//", assign=["val {n} = {q}{v}{q}", "private val {n} = {q}{v}{q}"], q=['"'], kw=["{q}{n}{q} -> {q}{v}{q},"]),
54
+ "Kotlin": dict(c="//", assign=["val {n} = {q}{v}{q}", "const val {N} = {q}{v}{q}"], q=['"'], kw=[]),
55
+ "Shell": dict(c="#", assign=["{N}={q}{v}{q}", "export {N}={q}{v}{q}", "{n}={q}{v}{q}"], q=['"', "'", ""], kw=["--{n} {q}{v}{q} \\"]),
56
+ "PowerShell": dict(c="#", assign=["${n} = {q}{v}{q}", "$env:{N} = {q}{v}{q}"], q=['"', "'"], kw=[]),
57
+ "Batchfile": dict(c="REM", assign=["set {N}={v}", "SET {N}={v}"], q=[""], kw=[]),
58
+ "Perl": dict(c="#", assign=["my ${n} = {q}{v}{q};", "${n} = {q}{v}{q};"], q=["'", '"'], kw=["{n} => {q}{v}{q},"]),
59
+ "Lua": dict(c="--", assign=["local {n} = {q}{v}{q}", "{n} = {q}{v}{q}"], q=['"', "'"], kw=["{n} = {q}{v}{q},"]),
60
+ "Julia": dict(c="#", assign=["{n} = {q}{v}{q}", "const {N} = {q}{v}{q}"], q=['"'], kw=[]),
61
+ "Haskell": dict(c="--", assign=["{n} = {q}{v}{q}"], q=['"'], kw=[]),
62
+ "SQL": dict(c="--", assign=["SET @{n} = {q}{v}{q};", "IDENTIFIED BY {q}{v}{q};", "CREATE USER '{u}'@'%' IDENTIFIED BY {q}{v}{q};"], q=["'"], kw=[]),
63
+ "Dockerfile": dict(c="#", assign=["ENV {N}={v}", "ENV {N} {v}", "ARG {N}={v}"], q=[""], kw=[]),
64
+ "Makefile": dict(c="#", assign=["{N} = {v}", "{N} := {v}", "export {N}={v}"], q=[""], kw=[]),
65
+ "CMake": dict(c="#", assign=["set({N} {q}{v}{q})"], q=['"'], kw=[]),
66
+ "HTML": dict(c="<!--", assign=['<input type="hidden" name="{n}" value="{v}">', '<meta name="{n}" content="{v}">', "var {n} = {q}{v}{q};"], q=['"'], kw=[]),
67
+ "CSS": dict(c="/*", assign=["/* {n}: {v} */"], q=[""], kw=[]),
68
+ "Markdown": dict(c="", assign=["`{n}={v}`", "{n}: `{v}`", " {N}={v}", "- **{n}**: `{v}`"], q=[""], kw=[]),
69
+ "TeX": dict(c="%", assign=["\\newcommand{{\\{n}}}{{{v}}}"], q=[""], kw=[]),
70
+ "Visual Basic": dict(c="'", assign=["Dim {n} As String = {q}{v}{q}", "Const {N} As String = {q}{v}{q}"], q=['"'], kw=[]),
71
+ "FORTRAN": dict(c="!", assign=["character(len=*), parameter :: {n} = {q}{v}{q}"], q=["'", '"'], kw=[]),
72
+ "Assembly": dict(c=";", assign=["{n} db {q}{v}{q}, 0"], q=['"'], kw=[]),
73
+ }
74
+ GENERIC = dict(c="#", assign=["{n} = {q}{v}{q}", "{N}={v}"], q=['"', ""], kw=[])
75
+
76
+ # --------------------------------------------------------------------------------------
77
+ # Value generators. Each returns (value, value_type).
78
+ # --------------------------------------------------------------------------------------
79
+ R = random.Random()
80
+ fake = Faker()
81
+ HEX = "0123456789abcdef"
82
+ B62 = string.ascii_letters + string.digits
83
+ B64 = B62 + "+/"
84
+ B64URL = B62 + "-_"
85
+
86
+ def rs(alpha, n):
87
+ return "".join(R.choice(alpha) for _ in range(n))
88
+
89
+ def b64(n):
90
+ return base64.b64encode(os.urandom(n)).decode()
91
+
92
+ def b64url(n):
93
+ raw = n if isinstance(n, bytes) else os.urandom(n)
94
+ return base64.urlsafe_b64encode(raw).decode().rstrip("=")
95
+
96
+ def gen_jwt():
97
+ hdr = b64url(json.dumps({"alg": R.choice(["HS256", "RS256"]), "typ": "JWT"}).encode())
98
+ pl = b64url(json.dumps({"sub": str(R.randint(1000, 999999)), "name": fake.name(), "iat": R.randint(1500000000, 1750000000), "exp": R.randint(1750000000, 1900000000)}).encode())
99
+ return f"{hdr}.{pl}.{b64url(32)}"
100
+
101
+ def gen_password():
102
+ k = R.random()
103
+ if k < 0.45:
104
+ return fake.password(length=R.randint(8, 16), special_chars=R.random() < 0.4)
105
+ if k < 0.70:
106
+ return R.choice(["", "", "admin", "root", "dev", "test", "db", "qa"]) + fake.word().capitalize() + R.choice(["", "!", "#", "@"]) + str(R.randint(1, 2024))
107
+ if k < 0.85:
108
+ return rs(string.ascii_lowercase + string.digits, R.randint(6, 12))
109
+ return fake.word() + "_" + fake.word() + str(R.randint(10, 99))
110
+
111
+ def gen_pem():
112
+ kind = R.choice(["RSA PRIVATE KEY", "RSA PRIVATE KEY", "PRIVATE KEY", "EC PRIVATE KEY", "OPENSSH PRIVATE KEY", "DSA PRIVATE KEY"])
113
+ nbytes = {"EC PRIVATE KEY": R.randint(100, 160), "OPENSSH PRIVATE KEY": R.randint(300, 420)}.get(kind, R.randint(600, 1200))
114
+ body = b64(nbytes)
115
+ lines = [body[i:i + 64] for i in range(0, len(body), 64)]
116
+ return f"-----BEGIN {kind}-----\n" + "\n".join(lines) + f"\n-----END {kind}-----"
117
+
118
+ def gen_email():
119
+ k = R.random()
120
+ if k < 0.5:
121
+ return fake.free_email()
122
+ if k < 0.75:
123
+ return fake.user_name() + "@" + fake.domain_name()
124
+ if k < 0.9:
125
+ return fake.company_email()
126
+ return fake.first_name().lower() + "." + fake.last_name().lower() + "@" + R.choice(["gmail.com", "outlook.com", "yahoo.com", "protonmail.com", "qq.com"])
127
+
128
+ # label -> list of (weight, value_type, fn)
129
+ GENERATORS = {
130
+ "api_key": [
131
+ (3, "aws_access_key_id", lambda: "AKIA" + rs(string.ascii_uppercase + string.digits, 16)),
132
+ (3, "aws_secret_access_key", lambda: rs(B64, 40)),
133
+ (2, "google_api_key", lambda: "AIza" + rs(B64URL, 35)),
134
+ (2, "stripe_secret_key", lambda: R.choice(["sk_live_", "sk_test_", "rk_live_"]) + rs(B62, 24)),
135
+ (1, "sendgrid_api_key", lambda: "SG." + rs(B64URL, 22) + "." + rs(B64URL, 43)),
136
+ (1, "twilio_api_key", lambda: "SK" + rs(HEX, 32)),
137
+ (1, "mailgun_api_key", lambda: "key-" + rs(HEX, 32)),
138
+ (1, "openai_api_key", lambda: "sk-" + R.choice(["", "proj-"]) + rs(B62, 48)),
139
+ (1, "anthropic_api_key", lambda: "sk-ant-api03-" + rs(B64URL, 93) + "AA"),
140
+ (1, "azure_client_secret", lambda: rs(B62 + "~._-", 40)),
141
+ (6, "generic_hex_key", lambda: rs(HEX, R.choice([32, 32, 40, 48, 64, 64]))),
142
+ (4, "generic_base64_secret", lambda: b64(R.choice([24, 32, 32, 48, 64]))),
143
+ (2, "generic_alnum_key", lambda: rs(B62, R.choice([20, 24, 32, 40]))),
144
+ ],
145
+ "token": [
146
+ (3, "github_pat", lambda: R.choice(["ghp_", "gho_", "ghs_"]) + rs(B62, 36)),
147
+ (1, "github_fine_grained_pat", lambda: "github_pat_" + rs(B62, 22) + "_" + rs(B62, 59)),
148
+ (2, "slack_token", lambda: R.choice(["xoxb-", "xoxp-", "xoxa-2-"]) + str(R.randint(10 ** 10, 10 ** 12)) + "-" + str(R.randint(10 ** 10, 10 ** 12)) + "-" + rs(B62, 24)),
149
+ (1, "slack_webhook", lambda: "https://hooks.slack.com/services/T" + rs(string.ascii_uppercase + string.digits, 8) + "/B" + rs(string.ascii_uppercase + string.digits, 8) + "/" + rs(B62, 24)),
150
+ (4, "jwt", gen_jwt),
151
+ (1, "gitlab_pat", lambda: "glpat-" + rs(B62 + "_-", 20)),
152
+ (1, "npm_token", lambda: "npm_" + rs(B62, 36)),
153
+ (1, "discord_bot_token", lambda: rs(B64URL, 24) + "." + rs(B64URL, 6) + "." + rs(B64URL, 27)),
154
+ (1, "digitalocean_pat", lambda: "dop_v1_" + rs(HEX, 64)),
155
+ (1, "hf_token", lambda: "hf_" + rs(B62, 34)),
156
+ (3, "bearer_token_opaque", lambda: rs(B64URL, R.choice([32, 40, 43, 64]))),
157
+ (2, "basic_auth_b64", lambda: base64.b64encode(f"{fake.user_name()}:{gen_password()}".encode()).decode()),
158
+ ],
159
+ "password": [(1, "password", gen_password)],
160
+ "private_key": [(1, "pem_private_key", gen_pem)],
161
+ "email": [(1, "email", gen_email)],
162
+ }
163
+
164
+ def pick_weighted(items):
165
+ tot = sum(w for w, *_ in items)
166
+ r = R.uniform(0, tot)
167
+ for it in items:
168
+ r -= it[0]
169
+ if r <= 0:
170
+ return it
171
+ return items[-1]
172
+
173
+ def gen_value(label):
174
+ w, vt, fn = pick_weighted(GENERATORS[label])
175
+ return fn(), vt
176
+
177
+ # Hard negatives: (value_type, fn, label_of_similar_secret)
178
+ HARD_NEGATIVES = [
179
+ ("placeholder", lambda: R.choice(["CHANGEME", "changeme", "<YOUR_API_KEY>", "YOUR_API_KEY_HERE", "xxxxxxxxxxxxxxxxxxxx", "********", "REPLACE_ME", "TODO", "<password>", "${PASSWORD}", "your-secret-here", "EXAMPLE_KEY", "AKIAIOSFODNN7EXAMPLE", "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY", "sk_test_XXXXXXXXXXXXXXXXXXXXXXXX", "ghp_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "dummy", "secret", "password", "123456", "test"])),
180
+ ("example_email", lambda: fake.user_name() + "@" + R.choice(["example.com", "example.org", "test.com", "localhost", "domain.com", "email.com", "company.com"])),
181
+ ("uuid", lambda: str(uuid.uuid4()) if R.random() < 0.8 else str(uuid.uuid4()).upper()),
182
+ ("sha256_hash", lambda: hashlib.sha256(os.urandom(8)).hexdigest()),
183
+ ("sha1_git_sha", lambda: hashlib.sha1(os.urandom(8)).hexdigest()),
184
+ ("md5_hash", lambda: hashlib.md5(os.urandom(8)).hexdigest()),
185
+ ("env_var_reference", lambda: R.choice(["os.environ['{N}']", "os.getenv('{N}')", "process.env.{N}", "${{{N}}}", "$({N})", "ENV['{N}']", "System.getenv(\"{N}\")", "{{{{ secrets.{N} }}}}", "${{{{ secrets.{N} }}}}", "Environment.GetEnvironmentVariable(\"{N}\")"]).format(N=R.choice(["API_KEY", "SECRET_KEY", "DB_PASSWORD", "GITHUB_TOKEN", "AWS_SECRET_ACCESS_KEY", "TOKEN", "PASSWORD"]))),
186
+ ("public_key_pem", lambda: "-----BEGIN PUBLIC KEY-----\n" + "\n".join([b64(220)[i:i + 64] for i in range(0, 294, 64)]) + "\n-----END PUBLIC KEY-----"),
187
+ ("ssh_public_key", lambda: "ssh-rsa " + b64(R.randint(150, 279)) + " " + fake.user_name() + "@" + fake.hostname()),
188
+ ("version_or_id", lambda: R.choice([fake.ipv4(), "v" + str(R.randint(0, 9)) + "." + str(R.randint(0, 20)) + "." + str(R.randint(0, 50)), "com.example." + fake.word(), str(R.randint(10 ** 9, 10 ** 12)), "/usr/local/share/" + fake.word()])),
189
+ ("base64_non_secret", lambda: base64.b64encode(fake.sentence().encode()).decode()),
190
+ ]
191
+
192
+ # --------------------------------------------------------------------------------------
193
+ # Placement logic (driven by priors.json)
194
+ # --------------------------------------------------------------------------------------
195
+ class Priors:
196
+ def __init__(self, path):
197
+ p = json.load(open(path))
198
+ ld = p["label_distribution"]
199
+ # keep the POC label set; CredData's UUID class becomes a hard negative, 'other' dropped
200
+ self.labels = [l for l in ("api_key", "password", "token", "private_key") if l in ld]
201
+ self.label_w = [ld[l] for l in self.labels]
202
+ # emails are not a CredData class; give them a fixed share
203
+ self.labels.append("email"); self.label_w.append(int(0.12 * sum(self.label_w)))
204
+ self.ctx_by_label = {l: p["context_by_label"].get(l, {"assignment": 1}) for l in self.labels}
205
+ self.ctx_by_label["email"] = {"assignment": 40, "comment": 35, "json_key": 10, "yaml_key": 10}
206
+ self.names = {l: p["var_names_by_label_top40"].get(l, {"secret": 1}) for l in self.labels}
207
+ self.names["email"] = {"email": 30, "admin_email": 10, "user_email": 10, "from_email": 8, "contact": 5, "author_email": 5, "smtp_user": 5, "mail": 4, "username": 4}
208
+ self.names["token"] = dict(self.names["token"]); self.names["token"].update({"token": 50, "access_token": 30, "auth_token": 20, "api_token": 15, "github_token": 10, "slack_token": 8, "bearer": 5})
209
+ self.names["api_key"] = dict(self.names["api_key"]); self.names["api_key"].update({"api_key": 60, "apikey": 30, "secret_key": 30, "aws_secret_access_key": 20, "aws_access_key_id": 20, "client_secret": 20, "private_key": 5, "stripe_key": 5})
210
+ self.names["private_key"] = {"private_key": 30, "key": 20, "rsa_key": 10, "ssh_key": 10, "pem": 5, "signing_key": 5, "server_key": 5}
211
+ h = p.get("secrets_per_file_hist", {"1": 60, "2": 20, "3": 10, "4": 5})
212
+ # CredData's last bucket is "10+", dominated by a few credential-dump files; damp it
213
+ self.nsec = [min(int(k), 5) for k in h]; self.nsec_w = [h[k] / (4 if int(k) >= 10 else 1) for k in h]
214
+ self.quote_style = p.get("quote_style", {})
215
+
216
+ def sample_label(self):
217
+ return R.choices(self.labels, self.label_w)[0]
218
+
219
+ def sample_ctx(self, label, allowed):
220
+ d = {k: v for k, v in self.ctx_by_label[label].items() if k in allowed}
221
+ if not d:
222
+ return "assignment"
223
+ return R.choices(list(d), list(d.values()))[0]
224
+
225
+ def sample_name(self, label):
226
+ d = self.names[label]
227
+ return R.choices(list(d), list(d.values()))[0]
228
+
229
+ def sample_nsec(self):
230
+ return R.choices(self.nsec, self.nsec_w)[0]
231
+
232
+ def name_variants(n):
233
+ """Return (snake, UPPER, camel) forms of a variable name."""
234
+ n = re.sub(r"[^a-z0-9_]", "_", n.lower()).strip("_") or "secret"
235
+ parts = n.split("_")
236
+ camel = parts[0] + "".join(x.capitalize() for x in parts[1:])
237
+ return n, n.upper(), camel
238
+
239
+ def render(ctx, lang, label, name, value, is_negative=False):
240
+ """Render one injected line (may be multi-line for PEM). Returns (line_text, rel_start, rel_end)."""
241
+ L = LANG.get(lang, GENERIC)
242
+ snake, upper, camel = name_variants(name)
243
+ n = R.choice([snake, snake, camel]) if lang in ("JavaScript", "TypeScript", "Java", "C#", "GO", "Scala", "Kotlin") else snake
244
+ q = R.choice(L["q"]) if L["q"] else '"'
245
+ if value and ("'" in value or '"' in value or " " in value) and q == "":
246
+ q = '"'
247
+ if q and q in value:
248
+ q = "'" if q == '"' else '"'
249
+ if q in value:
250
+ value = value.replace(q, "")
251
+ user = fake.user_name()
252
+ if label == "private_key" or "\n" in value:
253
+ ctx = "pem_block"
254
+ if ctx == "pem_block":
255
+ if lang in ("Python", "JavaScript", "TypeScript", "Ruby", "GO", "PHP", "Shell"):
256
+ opener = {"Python": f'{n} = """', "JavaScript": f"const {n} = `", "TypeScript": f"const {n} = `", "Ruby": f"{n} = <<~KEY\n", "GO": f"{n} := `", "PHP": f"${n} = <<<KEY\n", "Shell": f"cat > ~/.ssh/id_rsa <<'EOF'\n"}[lang]
257
+ closer = {"Python": '"""', "JavaScript": "`;", "TypeScript": "`;", "Ruby": "\nKEY", "GO": "`", "PHP": "\nKEY;", "Shell": "\nEOF"}[lang]
258
+ line = opener + value + closer
259
+ elif lang in ("Java", "C#", "C", "C++"):
260
+ esc = value.replace("\n", "\\n\" +\n \"")
261
+ line = f'String {n} = "{esc}";' if lang == "Java" else f'const char *{n} = "{esc}";' if lang in ("C", "C++") else f'string {n} = "{esc}";'
262
+ value = esc
263
+ else:
264
+ line = value
265
+ s = line.index(value)
266
+ return line, s, s + len(value)
267
+ if ctx == "comment":
268
+ c = L["c"] or "#"
269
+ tmpl = R.choice(["{c} {n}: {v}", "{c} {n} = {v}", "{c} TODO: remove hardcoded {n} {v}", "{c} old {n}: {v}", "{c} {n}={v}", "{c} login as {u} / {v}"])
270
+ line = tmpl.format(c=c, n=n, v=value, u=user)
271
+ if c == "<!--": line += " -->"
272
+ if c == "/*": line += " */"
273
+ elif ctx == "url_credential":
274
+ scheme = R.choice(["postgres", "postgresql", "mysql", "mongodb", "mongodb+srv", "redis", "amqp", "https", "http", "ftp", "sftp"])
275
+ host = R.choice([fake.hostname(), "localhost", fake.ipv4(), fake.domain_name()])
276
+ url = f"{scheme}://{user}:{value}@{host}" + R.choice([":5432/app", "/", ":6379/0", "/db", "/api/v1", ":3306/prod", ""])
277
+ a = R.choice(L["assign"]) if ctx != "pem_block" else "{n} = {q}{v}{q}"
278
+ if lang == "SQL": a = "{n} = {q}{v}{q}"
279
+ line = a.format(n=R.choice(["database_url", "db_url", "conn_str", "connection_string", "url", "uri", "mongo_uri", "redis_url", "broker_url", "dsn"]) if "{n}" in a else "", N=R.choice(["DATABASE_URL", "DB_URI", "MONGO_URL", "REDIS_URL", "CONNECTION_STRING"]), q=q, v=url, u=user)
280
+ elif ctx == "auth_header":
281
+ if label == "token" and R.random() < 0.6:
282
+ hv = f"Bearer {value}"
283
+ else:
284
+ hv = f"Basic {value}" if re.fullmatch(r"[A-Za-z0-9+/=]+", value) else f"Bearer {value}"
285
+ tmpls = AUTH_TMPL.get(lang, ['{q}Authorization{q}: {q}{hv}{q},', "Authorization: {hv}"])
286
+ tmpl = R.choice(tmpls)
287
+ line = tmpl.format(q=q or '"', hv=hv)
288
+ elif ctx in ("json_key", "yaml_key", "env_assignment", "ini_or_props", "function_arg") and L["kw"] and ctx != "env_assignment":
289
+ line = R.choice(L["kw"]).format(n=n, N=upper, q=(q if q in ("'", '"') else '"'), v=value)
290
+ elif ctx == "env_assignment":
291
+ line = R.choice(["{N}={v}", "{N}={q}{v}{q}", "export {N}={q}{v}{q}", "ENV {N}={v}"]).format(N=upper, q=q, v=value) if lang in ("Shell", "Dockerfile", "Makefile", "Markdown") else R.choice(L["assign"]).format(n=n, N=upper, q=q, v=value, u=user)
292
+ else:
293
+ line = R.choice(L["assign"]).format(n=n, N=upper, q=q, v=value, u=user)
294
+ s = line.rindex(value)
295
+ return line, s, s + len(value)
296
+
297
+ AUTH_TMPL = {
298
+ "Python": ['headers[{q}Authorization{q}] = {q}{hv}{q}', 'headers = {{{q}Authorization{q}: {q}{hv}{q}}}', '{q}Authorization{q}: {q}{hv}{q},'],
299
+ "JavaScript": ['{q}Authorization{q}: {q}{hv}{q},', 'headers.Authorization = {q}{hv}{q};', "xhr.setRequestHeader({q}Authorization{q}, {q}{hv}{q});"],
300
+ "TypeScript": ['{q}Authorization{q}: {q}{hv}{q},', 'headers.set({q}Authorization{q}, {q}{hv}{q});'],
301
+ "GO": ['req.Header.Set({q}Authorization{q}, {q}{hv}{q})', 'req.Header.Add({q}Authorization{q}, {q}{hv}{q})'],
302
+ "Java": ['conn.setRequestProperty({q}Authorization{q}, {q}{hv}{q});', '.header({q}Authorization{q}, {q}{hv}{q})', 'headers.set({q}Authorization{q}, {q}{hv}{q});'],
303
+ "C#": ['client.DefaultRequestHeaders.Add({q}Authorization{q}, {q}{hv}{q});', 'request.Headers[{q}Authorization{q}] = {q}{hv}{q};'],
304
+ "PHP": ["'Authorization: {hv}',", "$headers[{q}Authorization{q}] = {q}{hv}{q};"],
305
+ "Ruby": ["request[{q}Authorization{q}] = {q}{hv}{q}", "headers: {{ {q}Authorization{q} => {q}{hv}{q} }}"],
306
+ "Shell": ["-H {q}Authorization: {hv}{q} \\", "curl -H {q}Authorization: {hv}{q} https://api.example.com/v1/me"],
307
+ "Markdown": [" Authorization: {hv}", "`Authorization: {hv}`"],
308
+ "Rust": ['.header({q}Authorization{q}, {q}{hv}{q})'],
309
+ "C": ['headers = curl_slist_append(headers, {q}Authorization: {hv}{q});'],
310
+ "C++": ['headers = curl_slist_append(headers, {q}Authorization: {hv}{q});'],
311
+ "PowerShell": ['$headers = @{{ Authorization = {q}{hv}{q} }}'],
312
+ }
313
+ NEG_NAME_LABEL = {"example_email": "email", "public_key_pem": "private_key", "ssh_public_key": "private_key"}
314
+ NEG_NAMES = {
315
+ "private_key": {"public_key": 30, "pubkey": 10, "ssh_public_key": 10, "authorized_key": 5, "verify_key": 5, "cert": 5},
316
+ "hash": {"checksum": 20, "sha256": 10, "sha1": 10, "md5": 10, "digest": 10, "commit": 10, "etag": 5, "integrity": 5, "file_hash": 5, "revision": 5, "content_hash": 5, "ref": 3, "git_sha": 3},
317
+ "uuid": {"id": 20, "request_id": 10, "tenant_id": 10, "client_id": 10, "device_id": 8, "correlation_id": 8, "trace_id": 5, "job_id": 5, "uuid": 10, "guid": 5, "instance_id": 5},
318
+ "version_or_id": {"version": 20, "host": 10, "ip": 10, "app_id": 10, "path": 10, "package": 5, "bundle_id": 5, "build": 5, "server": 5},
319
+ "base64_non_secret": {"payload": 20, "data": 10, "body": 10, "encoded": 10, "message": 10, "content": 5, "blob": 5},
320
+ }
321
+ NEG_NAME_GROUP = {"sha256_hash": "hash", "sha1_git_sha": "hash", "md5_hash": "hash", "uuid": "uuid", "version_or_id": "version_or_id", "base64_non_secret": "base64_non_secret", "public_key_pem": "private_key", "ssh_public_key": "private_key"}
322
+
323
+ CTX_ALLOWED = {"assignment", "json_key", "yaml_key", "env_assignment", "comment", "url_credential", "auth_header", "function_arg", "pem_block"}
324
+
325
+ def inject(text, lang, priors, n_secrets, n_negs):
326
+ """Insert n_secrets secret lines and n_negs hard-negative lines into text. Returns (text, spans, negs)."""
327
+ lines = text.split("\n")
328
+ nl = len(lines)
329
+ inserts = [] # (line_index, rendered_line, rel_start, rel_end, meta)
330
+ for _ in range(n_secrets):
331
+ label = priors.sample_label()
332
+ ctx = priors.sample_ctx(label, CTX_ALLOWED)
333
+ name = priors.sample_name(label)
334
+ value, vt = gen_value(label)
335
+ line, s, e = render(ctx, lang, label, name, value)
336
+ inserts.append((R.randint(0, nl), line, s, e, {"label": label, "value_type": vt, "context": ctx, "synthetic": True}))
337
+ for _ in range(n_negs):
338
+ vt, fn = R.choice(HARD_NEGATIVES)
339
+ value = fn()
340
+ if vt in ("env_var_reference",):
341
+ line = R.choice(LANG.get(lang, GENERIC)["assign"]).format(n=R.choice(["api_key", "password", "token", "secret"]), N=R.choice(["API_KEY", "PASSWORD", "TOKEN"]), q="", v=value, u="u")
342
+ s = line.rindex(value); e = s + len(value)
343
+ else:
344
+ label_like = NEG_NAME_LABEL.get(vt) or R.choice(["api_key", "password", "token"])
345
+ ctx = priors.sample_ctx(label_like, CTX_ALLOWED - {"pem_block", "auth_header", "url_credential"})
346
+ if "\n" in value: ctx = "pem_block"
347
+ grp = NEG_NAME_GROUP.get(vt)
348
+ name = R.choices(list(NEG_NAMES[grp]), list(NEG_NAMES[grp].values()))[0] if grp else priors.sample_name(label_like)
349
+ line, s, e = render(ctx, lang, "api_key" if label_like == "private_key" else label_like, name, value, is_negative=True)
350
+ inserts.append((R.randint(0, nl), line, s, e, {"label": "not_secret", "value_type": vt, "synthetic": True}))
351
+ inserts.sort(key=lambda x: x[0])
352
+ out = []; spans = []; negs = []; pos = 0; li = 0
353
+ for idx, line, s, e, meta in inserts:
354
+ while li < idx:
355
+ out.append(lines[li]); pos += len(lines[li]) + 1; li += 1
356
+ ref = lines[idx] if idx < nl else (lines[-1] if lines else "")
357
+ indent = re.match(r"[ \t]*", ref).group(0) if lang != "Markdown" else ""
358
+ if "\n" in line and lang not in ("Python",):
359
+ indent = ""
360
+ full = indent + line
361
+ rec = dict(meta, start=pos + len(indent) + s, end=pos + len(indent) + e)
362
+ (negs if meta["label"] == "not_secret" else spans).append(rec)
363
+ out.append(full); pos += len(full) + 1
364
+ while li < nl:
365
+ out.append(lines[li]); pos += len(lines[li]) + 1; li += 1
366
+ return "\n".join(out), spans, negs
367
+
368
+ # --------------------------------------------------------------------------------------
369
+ # Shard processing
370
+ # --------------------------------------------------------------------------------------
371
+ def fetch_shard(i, shard_dir, keep):
372
+ os.makedirs(shard_dir, exist_ok=True)
373
+ p = os.path.join(shard_dir, f"train-{i:05d}-of-00880.parquet")
374
+ if os.path.exists(p):
375
+ return p, False
376
+ tmp = p + ".part"
377
+ urllib.request.urlretrieve(HF_URL.format(i=i), tmp)
378
+ os.replace(tmp, p)
379
+ return p, not keep
380
+
381
+ def process_shard(args):
382
+ i, cfg = args
383
+ R.seed(cfg["seed"] * 100003 + i); Faker.seed(cfg["seed"] * 100003 + i)
384
+ priors = Priors(cfg["priors"])
385
+ path, delete_after = fetch_shard(i, cfg["shard_dir"], cfg["keep_shards"])
386
+ out_path = os.path.join(cfg["out"], f"part-{i:05d}.jsonl")
387
+ stats = {"shard": i, "files": 0, "injected_files": 0, "clean_files": 0, "bytes": 0, "spans": 0, "negs": 0,
388
+ "label": {}, "value_type": {}, "lang": {}, "context": {}, "skipped_license": 0, "skipped_size": 0}
389
+ t0 = time.time()
390
+ pf = pq.ParquetFile(path)
391
+ with open(out_path + ".tmp", "w", encoding="utf-8") as fh:
392
+ for rg in range(pf.metadata.num_row_groups):
393
+ for ex in pf.read_row_group(rg, columns=["code", "repo_name", "path", "language", "license"]).to_pylist():
394
+ if ex["license"] not in PERMISSIVE:
395
+ stats["skipped_license"] += 1; continue
396
+ text = ex["code"]
397
+ if not (cfg["min_bytes"] <= len(text) <= cfg["max_bytes"]):
398
+ stats["skipped_size"] += 1; continue
399
+ lang = ex["language"]
400
+ spans, negs = [], []
401
+ if R.random() < cfg["inject_frac"]:
402
+ n_sec = priors.sample_nsec() if R.random() < 0.85 else 0
403
+ n_neg = R.choice([0, 0, 1, 1, 1, 2, 2, 3])
404
+ if n_sec or n_neg:
405
+ text, spans, negs = inject(text, lang, priors, n_sec, n_neg)
406
+ for s in spans + negs:
407
+ v = text[s["start"]:s["end"]]
408
+ assert len(v) == s["end"] - s["start"] and v.strip() == v and len(v) > 0, (s, v)
409
+ s["value"] = v
410
+ rid = hashlib.sha1(f"{ex['repo_name']}/{ex['path']}".encode()).hexdigest()[:16]
411
+ rec = {"id": f"ghcc-{i:05d}-{rid}", "source": "codeparrot/github-code-clean", "repo": ex["repo_name"], "license": ex["license"],
412
+ "language": lang, "path": ex["path"], "text": text, "spans": spans, "hard_negatives": negs}
413
+ line = json.dumps(rec, ensure_ascii=False) + "\n"
414
+ fh.write(line)
415
+ stats["files"] += 1; stats["bytes"] += len(line.encode("utf-8", "replace"))
416
+ stats["injected_files" if spans else "clean_files"] += 1
417
+ stats["spans"] += len(spans); stats["negs"] += len(negs)
418
+ stats["lang"][lang] = stats["lang"].get(lang, 0) + 1
419
+ for s in spans:
420
+ stats["label"][s["label"]] = stats["label"].get(s["label"], 0) + 1
421
+ stats["value_type"][s["value_type"]] = stats["value_type"].get(s["value_type"], 0) + 1
422
+ stats["context"][s["context"]] = stats["context"].get(s["context"], 0) + 1
423
+ for s in negs:
424
+ stats["value_type"]["neg:" + s["value_type"]] = stats["value_type"].get("neg:" + s["value_type"], 0) + 1
425
+ os.replace(out_path + ".tmp", out_path)
426
+ if delete_after:
427
+ os.remove(path)
428
+ stats["seconds"] = round(time.time() - t0, 1)
429
+ with open(os.path.join(cfg["out"], f"part-{i:05d}.stats.json"), "w") as fh:
430
+ json.dump(stats, fh)
431
+ print(f"shard {i}: {stats['files']} files, {stats['bytes']/1e6:.0f} MB, {stats['spans']} spans in {stats['seconds']}s ({stats['bytes']/1e6/stats['seconds']:.1f} MB/s)", flush=True)
432
+ return stats
433
+
434
+ def main():
435
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
436
+ ap.add_argument("--out", required=True)
437
+ ap.add_argument("--priors", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "priors.json"))
438
+ ap.add_argument("--target-bytes", type=float, default=2e9, help="stop launching new shards once output exceeds this (approx; one shard ~= 500-600 MB output)")
439
+ ap.add_argument("--start-shard", type=int, default=0)
440
+ ap.add_argument("--max-shards", type=int, default=N_SHARDS)
441
+ ap.add_argument("--shard-dir", default="./shards", help="where parquet shards are cached/downloaded")
442
+ ap.add_argument("--keep-shards", action="store_true", help="do not delete downloaded shards after processing")
443
+ ap.add_argument("--workers", type=int, default=max(1, os.cpu_count() - 1))
444
+ ap.add_argument("--inject-frac", type=float, default=0.75, help="fraction of files that get any injection (rest are pure negatives)")
445
+ ap.add_argument("--min-bytes", type=int, default=200)
446
+ ap.add_argument("--max-bytes", type=int, default=200_000)
447
+ ap.add_argument("--seed", type=int, default=1)
448
+ a = ap.parse_args()
449
+ os.makedirs(a.out, exist_ok=True)
450
+ cfg = dict(priors=a.priors, out=a.out, shard_dir=a.shard_dir, keep_shards=a.keep_shards, inject_frac=a.inject_frac, min_bytes=a.min_bytes, max_bytes=a.max_bytes, seed=a.seed)
451
+ t0 = time.time(); total = 0; done = []
452
+ shard_iter = iter(range(a.start_shard, min(N_SHARDS, a.start_shard + a.max_shards)))
453
+ with Pool(a.workers) as pool:
454
+ pending = []
455
+ def launch():
456
+ i = next(shard_iter, None)
457
+ if i is not None:
458
+ pending.append(pool.apply_async(process_shard, ((i, cfg),)))
459
+ for _ in range(a.workers):
460
+ launch()
461
+ while pending:
462
+ r = pending.pop(0)
463
+ st = r.get(); done.append(st); total += st["bytes"]
464
+ if total < a.target_bytes:
465
+ launch()
466
+ dt = time.time() - t0
467
+ summary = {"shards": len(done), "files": sum(s["files"] for s in done), "bytes": total, "spans": sum(s["spans"] for s in done),
468
+ "hard_negatives": sum(s["negs"] for s in done), "seconds": round(dt, 1), "MB_per_s": round(total / 1e6 / dt, 2), "workers": a.workers}
469
+ with open(os.path.join(a.out, "summary.json"), "w") as fh:
470
+ json.dump(summary, fh, indent=1)
471
+ print(json.dumps(summary, indent=1))
472
+
473
+ if __name__ == "__main__":
474
+ main()
make_stats.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Aggregate part-*.stats.json + summary.json from a generated dataset dir into stats.md."""
3
+ import glob, json, os, sys, collections
4
+
5
+ d = sys.argv[1]; out = sys.argv[2]
6
+ parts = [json.load(open(p)) for p in sorted(glob.glob(os.path.join(d, "part-*.stats.json")))]
7
+ summ = json.load(open(os.path.join(d, "summary.json")))
8
+ C = collections.Counter
9
+ agg = {k: C() for k in ("label", "value_type", "lang", "context")}
10
+ tot = C()
11
+ for p in parts:
12
+ for k in agg:
13
+ agg[k].update(p[k])
14
+ for k in ("files", "injected_files", "clean_files", "bytes", "spans", "negs", "skipped_license", "skipped_size"):
15
+ tot[k] += p[k]
16
+ pq_files = sorted(glob.glob(os.path.join(sys.argv[3], "*.parquet"))) if len(sys.argv) > 3 else []
17
+ pq_bytes = sum(os.path.getsize(p) for p in pq_files)
18
+
19
+ def table(c, h1, n=None, total=None):
20
+ rows = c.most_common(n)
21
+ total = total or sum(c.values())
22
+ s = f"| {h1} | count | % |\n|---|---:|---:|\n"
23
+ for k, v in rows:
24
+ s += f"| {k} | {v:,} | {100*v/total:.1f} |\n"
25
+ return s
26
+
27
+ L = []
28
+ L.append("# Dataset statistics\n")
29
+ L.append(f"Generated from {summ['shards']} shards of `codeparrot/github-code-clean` (shards 0-{summ['shards']-1}), permissive licenses only.\n")
30
+ L.append("## Totals\n")
31
+ L.append("| metric | value |\n|---|---:|")
32
+ L.append(f"| records (files) | {tot['files']:,} |")
33
+ L.append(f"| files with >=1 secret span | {tot['injected_files']:,} ({100*tot['injected_files']/tot['files']:.1f}%) |")
34
+ L.append(f"| files with no secret span (pure negatives; may contain hard negatives) | {tot['clean_files']:,} ({100*tot['clean_files']/tot['files']:.1f}%) |")
35
+ L.append(f"| secret spans | {tot['spans']:,} |")
36
+ L.append(f"| hard-negative spans | {tot['negs']:,} |")
37
+ L.append(f"| JSONL bytes | {tot['bytes']:,} ({tot['bytes']/1e9:.2f} GB) |")
38
+ if pq_files:
39
+ L.append(f"| Parquet files / bytes (zstd) | {len(pq_files)} / {pq_bytes:,} ({pq_bytes/1e9:.2f} GB) |")
40
+ L.append(f"| base-corpus rows skipped: non-permissive license | {tot['skipped_license']:,} |")
41
+ L.append(f"| base-corpus rows skipped: size outside [200 B, 200 KB] | {tot['skipped_size']:,} |")
42
+ L.append(f"| wall time | {summ['seconds']} s with {summ['workers']} workers |")
43
+ L.append(f"| throughput (JSONL output) | {summ['MB_per_s']} MB/s aggregate, ~{summ['MB_per_s']/summ['workers']:.0f} MB/s per worker |\n")
44
+ L.append("## Throughput / scaling\n")
45
+ mbps = summ["MB_per_s"]
46
+ L.append(f"- Measured on a 4-vCPU VM with pre-downloaded shards: **{mbps:.0f} MB/s** of JSONL output ({mbps/summ['workers']:.0f} MB/s per worker process; CPU-bound).")
47
+ L.append(f"- One input shard (~355 MB parquet) yields ~600 MB JSONL (~75k records) in ~30 s per worker; shard download from the Hub measured at ~35 MB/s per stream (~10 s per shard), so download roughly matches processing when run with `--workers 4`.")
48
+ L.append(f"- Extrapolation: 40 GB JSONL ~= 67 shards -> ~{40e3/mbps/60:.0f} min of processing at {mbps:.0f} MB/s (plus ~11 min of downloads if not overlapped; the script overlaps them per worker). On 8 cores expect roughly half. Parquet conversion (zstd) adds ~2x the generation time and shrinks size ~2.3x.")
49
+ L.append(f"- Full 880-shard corpus (permissive subset) would yield ~{880*0.6:.0f} GB JSONL.\n")
50
+ L.append("## Secret spans by label\n"); L.append(table(agg["label"], "label"))
51
+ L.append("## Secret spans by value_type\n"); L.append(table(agg["value_type"] - C({k: v for k, v in agg["value_type"].items() if k.startswith("neg:")}), "value_type"))
52
+ neg = C({k[4:]: v for k, v in agg["value_type"].items() if k.startswith("neg:")})
53
+ L.append("## Hard-negative spans by value_type\n"); L.append(table(neg, "value_type"))
54
+ L.append("## Secret spans by syntactic context\n"); L.append(table(agg["context"], "context"))
55
+ L.append("## Records by language\n"); L.append(table(agg["lang"], "language"))
56
+ L.append("## File size distribution (text field, sample of 2 shards)\n")
57
+ L.append("| bucket | records |\n|---|---:|\n| <1 KB | 29,976 |\n| 1-10 KB | 99,191 |\n| 10-100 KB | 21,311 |\n| >=100 KB | 858 |\n")
58
+ L.append("## Validation (2 shards, 151,336 records)\n")
59
+ L.append("- Offset assertion `text[start:end] == value` on every span and hard negative: **0 failures** (also asserted at generation time for all records).")
60
+ L.append("- Regex scanner (gitleaks-style patterns for 15 value types) finds **100%** of injected spans of those types at the labeled offsets (secrets are not mangled by quoting/escaping/indentation).")
61
+ L.append("- 20 random records eyeballed; see `validate.py --n-eyeball 20`.\n")
62
+ L.append("## Held-out eval (eval_creddata.jsonl)\n")
63
+ L.append("- 67,896 real labeled lines from Samsung/CredData (+-3 lines context): 15,753 GroundTruth=T, 48,061 F (hard negatives), 4,082 X (ambiguous/unclear, no span).")
64
+ open(out, "w").write("\n".join(L))
65
+ print(open(out).read()[:1500])
priors.json ADDED
@@ -0,0 +1,683 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "source": "Samsung/CredData meta/*.csv (Apache-2.0)",
3
+ "n_rows": 67896,
4
+ "n_true": 15753,
5
+ "n_false": 48061,
6
+ "n_x": 4082,
7
+ "missing_files": 0,
8
+ "label_distribution": {
9
+ "api_key": 6457,
10
+ "password": 3099,
11
+ "token": 2326,
12
+ "uuid": 2316,
13
+ "private_key": 1384,
14
+ "other": 171
15
+ },
16
+ "category_raw_top50": {
17
+ "Key": 3822,
18
+ "Password": 2573,
19
+ "UUID": 2316,
20
+ "Secret": 1263,
21
+ "PEM Private Key": 1161,
22
+ "Auth:Basic Authorization": 601,
23
+ "Token": 583,
24
+ "URL Credentials": 213,
25
+ "Auth": 174,
26
+ "Token:UUID": 169,
27
+ "AWS Client ID": 162,
28
+ "Nonce": 148,
29
+ "Key:Secret": 124,
30
+ "API:Token": 112,
31
+ "NTLM Token:Bearer Authorization:Auth": 105,
32
+ "AWS S3 Bucket": 92,
33
+ "Basic Authorization": 89,
34
+ "Salt": 85,
35
+ "Auth:Token": 85,
36
+ "JSON Web Token": 84,
37
+ "Auth:Bearer Authorization": 79,
38
+ "JWK": 78,
39
+ "Credential": 76,
40
+ "Bearer Authorization": 75,
41
+ "PASERK Keys": 72,
42
+ "API:Key": 66,
43
+ "PASETO Token:Token": 61,
44
+ "NKEY Seed": 58,
45
+ "JSON Web Token:Token": 48,
46
+ "Auth:Key": 48,
47
+ "Tencent WeChat API App ID": 47,
48
+ "Dropbox App secret:Password": 44,
49
+ "Secret:Key": 39,
50
+ "SQL Password": 39,
51
+ "Firebase Domain": 38,
52
+ "AWS Client ID:Key": 36,
53
+ "Auth:Password": 31,
54
+ "AWS Multi": 31,
55
+ "BASE64 Private Key": 30,
56
+ "Twilio Credentials": 30,
57
+ "Auth:Nonce": 27,
58
+ "Secret:OTP / 2FA Secret": 26,
59
+ "UUID:Token": 26,
60
+ "CMD Password": 25,
61
+ "PEM Private Key:Key:Secret": 23,
62
+ "API": 21,
63
+ "Key:Password": 19,
64
+ "API:Password": 18,
65
+ "Password:Secret": 18,
66
+ "NTLM Token": 18
67
+ },
68
+ "context_distribution": {
69
+ "assignment": 6086,
70
+ "json_key": 1913,
71
+ "yaml_key": 1684,
72
+ "other": 1464,
73
+ "pem_block": 1273,
74
+ "auth_header": 874,
75
+ "comment": 752,
76
+ "url_credential": 642,
77
+ "function_arg": 528,
78
+ "env_assignment": 258,
79
+ "xml_attr_or_tag": 103,
80
+ "bare_value_line": 52
81
+ },
82
+ "context_by_label": {
83
+ "password": {
84
+ "assignment": 1026,
85
+ "yaml_key": 696,
86
+ "comment": 337,
87
+ "other": 337,
88
+ "json_key": 272,
89
+ "url_credential": 261,
90
+ "env_assignment": 103,
91
+ "function_arg": 64,
92
+ "xml_attr_or_tag": 2
93
+ },
94
+ "api_key": {
95
+ "assignment": 4699,
96
+ "json_key": 508,
97
+ "yaml_key": 390,
98
+ "other": 344,
99
+ "env_assignment": 123,
100
+ "comment": 106,
101
+ "function_arg": 101,
102
+ "url_credential": 101,
103
+ "pem_block": 33,
104
+ "auth_header": 20,
105
+ "xml_attr_or_tag": 8,
106
+ "bare_value_line": 6
107
+ },
108
+ "uuid": {
109
+ "json_key": 581,
110
+ "other": 471,
111
+ "yaml_key": 452,
112
+ "function_arg": 241,
113
+ "assignment": 206,
114
+ "comment": 178,
115
+ "url_credential": 104,
116
+ "xml_attr_or_tag": 73,
117
+ "env_assignment": 7,
118
+ "bare_value_line": 3
119
+ },
120
+ "token": {
121
+ "auth_header": 854,
122
+ "json_key": 552,
123
+ "other": 285,
124
+ "assignment": 150,
125
+ "yaml_key": 146,
126
+ "comment": 113,
127
+ "function_arg": 98,
128
+ "url_credential": 55,
129
+ "env_assignment": 25,
130
+ "bare_value_line": 24,
131
+ "xml_attr_or_tag": 13
132
+ },
133
+ "private_key": {
134
+ "pem_block": 1231,
135
+ "bare_value_line": 19,
136
+ "comment": 16,
137
+ "function_arg": 7,
138
+ "other": 7,
139
+ "xml_attr_or_tag": 6,
140
+ "assignment": 5
141
+ },
142
+ "other": {
143
+ "url_credential": 121,
144
+ "other": 20,
145
+ "function_arg": 17,
146
+ "pem_block": 9,
147
+ "comment": 2,
148
+ "xml_attr_or_tag": 1
149
+ }
150
+ },
151
+ "ext_true_top40": {
152
+ "txt": 5242,
153
+ "json": 1821,
154
+ "go": 1470,
155
+ "yml": 1300,
156
+ "md": 795,
157
+ "js": 708,
158
+ "py": 663,
159
+ "java": 380,
160
+ "rb": 355,
161
+ "(none)": 259,
162
+ "cs": 243,
163
+ "ts": 232,
164
+ "yaml": 198,
165
+ "php": 156,
166
+ "html": 146,
167
+ "sql": 126,
168
+ "key": 105,
169
+ "mjs": 89,
170
+ "log": 76,
171
+ "example": 72,
172
+ "sh": 68,
173
+ "pem": 67,
174
+ "rst": 67,
175
+ "ndjson": 67,
176
+ "properties": 66,
177
+ "conf": 64,
178
+ "markdown": 63,
179
+ "asciidoc": 62,
180
+ "response": 59,
181
+ "kt": 50,
182
+ "toml": 43,
183
+ "scala": 38,
184
+ "idl": 37,
185
+ "tfstate": 35,
186
+ "edited": 30,
187
+ "original": 30,
188
+ "c": 29,
189
+ "hs": 26,
190
+ "rsp": 24,
191
+ "m": 21
192
+ },
193
+ "ext_false_top40": {
194
+ "json": 10050,
195
+ "txt": 5680,
196
+ "go": 5372,
197
+ "py": 3107,
198
+ "js": 2790,
199
+ "rb": 2363,
200
+ "md": 1808,
201
+ "ts": 1788,
202
+ "php": 1414,
203
+ "java": 1249,
204
+ "yml": 1074,
205
+ "cs": 940,
206
+ "c": 775,
207
+ "(none)": 763,
208
+ "cc": 614,
209
+ "bundle": 463,
210
+ "sh": 462,
211
+ "kt": 369,
212
+ "yaml": 363,
213
+ "storyboard": 338,
214
+ "rrc": 334,
215
+ "asciidoc": 333,
216
+ "xaml": 295,
217
+ "ndjson": 289,
218
+ "rst": 275,
219
+ "rs": 207,
220
+ "j2": 199,
221
+ "groovy": 195,
222
+ "exs": 188,
223
+ "m": 183,
224
+ "resx": 177,
225
+ "xib": 164,
226
+ "vue": 164,
227
+ "lock": 138,
228
+ "strings": 136,
229
+ "tl": 131,
230
+ "html": 126,
231
+ "tsx": 120,
232
+ "crt": 119,
233
+ "mjs": 116
234
+ },
235
+ "false_positive_categories_top30": {
236
+ "Key": 19770,
237
+ "Password": 8733,
238
+ "Token": 4213,
239
+ "UUID": 3652,
240
+ "API": 3598,
241
+ "Auth": 3253,
242
+ "Secret": 1595,
243
+ "Basic Authorization": 538,
244
+ "Credential": 474,
245
+ "Key:Token": 262,
246
+ "Auth:Token": 236,
247
+ "URL Credentials": 144,
248
+ "Dropbox App secret": 112,
249
+ "CMD Password": 112,
250
+ "Salt": 105,
251
+ "Nonce": 98,
252
+ "Password:URL Credentials": 80,
253
+ "PEM Private Key": 71,
254
+ "API:Key": 63,
255
+ "AWS Multi": 61,
256
+ "JSON Web Token": 60,
257
+ "UUID:Key": 37,
258
+ "URL Credentials:Password": 33,
259
+ "API:Password": 33,
260
+ "Password:Auth": 30,
261
+ "Key:API": 30,
262
+ "Password:API": 30,
263
+ "Secret:Key": 27,
264
+ "Password:Key": 25,
265
+ "AWS Client ID": 24
266
+ },
267
+ "var_names_by_label_top40": {
268
+ "password": {
269
+ "password": 1383,
270
+ "master_password": 118,
271
+ "pass": 63,
272
+ "credential": 61,
273
+ "mysql_root_password": 52,
274
+ "postgres_password": 50,
275
+ "mysql_password": 40,
276
+ "password1": 30,
277
+ "some": 30,
278
+ "password2": 28,
279
+ "user": 27,
280
+ "userpassword": 24,
281
+ "password_confirmation": 20,
282
+ "new_password1": 20,
283
+ "postgres": 19,
284
+ "new_password2": 19,
285
+ "passwd": 18,
286
+ "ruser": 17,
287
+ "testpassword": 16,
288
+ "admin_password": 14,
289
+ "new_password": 14,
290
+ "elastic": 14,
291
+ "masteruserpassword": 14,
292
+ "pgpassword": 12,
293
+ "sa_password": 12,
294
+ "newpassword": 12,
295
+ "passphrase": 11,
296
+ "db_pass": 11,
297
+ "pwd": 11,
298
+ "root": 10,
299
+ "db_password": 10,
300
+ "secret": 9,
301
+ "rsync_password": 9,
302
+ "tcppassword": 9,
303
+ "basic_auth_password": 9,
304
+ "admin": 8,
305
+ "domainpassword": 8,
306
+ "rcuschemapassword": 8,
307
+ "envpassword": 7,
308
+ "stringvalue": 7
309
+ },
310
+ "api_key": {
311
+ "key": 3454,
312
+ "sharedsecret": 846,
313
+ "secret": 204,
314
+ "nonce": 97,
315
+ "paserk": 72,
316
+ "salt": 62,
317
+ "nkey": 58,
318
+ "credential": 57,
319
+ "hexkey": 50,
320
+ "appid": 45,
321
+ "apikey": 42,
322
+ "secret_key": 40,
323
+ "nonce_str": 38,
324
+ "password": 35,
325
+ "auth": 33,
326
+ "id": 33,
327
+ "string": 32,
328
+ "hexstringtouint8array": 30,
329
+ "client_secret": 26,
330
+ "secretaccesskey": 23,
331
+ "clientsecret": 22,
332
+ "accesskeyid": 22,
333
+ "consumer_secret": 19,
334
+ "sid": 19,
335
+ "userid": 19,
336
+ "key_material_base64": 19,
337
+ "consumer_key": 18,
338
+ "oauth_consumer_key": 16,
339
+ "hexsecret": 16,
340
+ "api_key": 14,
341
+ "oauth_verifier": 14,
342
+ "oauth_nonce": 14,
343
+ "hexsalt": 13,
344
+ "secret-key": 12,
345
+ "secret_key_base": 12,
346
+ "unique_id": 11,
347
+ "sealing-secret-key": 10,
348
+ "cookiesecret": 10,
349
+ "secretkey": 9,
350
+ "privatekeyraw": 9
351
+ },
352
+ "uuid": {
353
+ "id": 356,
354
+ "uid": 221,
355
+ "_postman_id": 99,
356
+ "collectionid": 91,
357
+ "examples": 69,
358
+ "folder": 57,
359
+ "uuid": 53,
360
+ "values": 52,
361
+ "example": 37,
362
+ "kid": 31,
363
+ "request": 18,
364
+ "requestid": 14,
365
+ "new": 13,
366
+ "resource": 11,
367
+ "app": 10,
368
+ "claimuid": 10,
369
+ "poduid": 9,
370
+ "value": 9,
371
+ "jti": 9,
372
+ "clientid": 8,
373
+ "user": 8,
374
+ "run": 8,
375
+ "guid": 7,
376
+ "friendly_name": 7,
377
+ "revisionid": 7,
378
+ "lineage": 7,
379
+ "sid": 7,
380
+ "d": 6,
381
+ "checksum": 6,
382
+ "jobid": 6,
383
+ "nxsessionid": 6,
384
+ "race_id": 6,
385
+ "client_id": 5,
386
+ "activityid": 5,
387
+ "scalingpolicy": 5,
388
+ "systemuuid": 5,
389
+ "x-github-request-id": 4,
390
+ "external_id": 4,
391
+ "object_path": 4,
392
+ "outputid": 4
393
+ },
394
+ "token": {
395
+ "token": 255,
396
+ "changetoken": 126,
397
+ "apitoken": 100,
398
+ "access_token": 89,
399
+ "oauth_token": 54,
400
+ "nexttoken": 41,
401
+ "refresh_token": 40,
402
+ "secret": 38,
403
+ "oauth_token_secret": 24,
404
+ "accesstoken": 18,
405
+ "token_secret": 14,
406
+ "new": 14,
407
+ "refreshtoken": 12,
408
+ "setauthtoken": 11,
409
+ "sessiontoken": 10,
410
+ "_oauth_request_token": 8,
411
+ "value": 7,
412
+ "string": 6,
413
+ "persistence_token": 6,
414
+ "private_token": 6,
415
+ "clientrequesttoken": 6,
416
+ "broken_token": 5,
417
+ "key": 5,
418
+ "hec_token": 5,
419
+ "tokenvalue": 4,
420
+ "auth_token": 4,
421
+ "id_token": 4,
422
+ "operator": 4,
423
+ "totpsecret": 4,
424
+ "temp_clone_token": 3,
425
+ "jwt": 3,
426
+ "app_secret_token": 3,
427
+ "identitytoken": 3,
428
+ "idtoken": 3,
429
+ "ad2vb6c25dqpeuuq7kjbufx2j4znvbpohscbisc7vfzxvwxza7vasqzg": 3,
430
+ "aws_security_token": 3,
431
+ "searchtokenvalue": 3,
432
+ "encrypted_github_access_token": 3,
433
+ "encrypted_github_access_token_iv": 3,
434
+ "generate": 3
435
+ },
436
+ "private_key": {
437
+ "byte": 7,
438
+ "accseed": 2,
439
+ "seed": 1,
440
+ "seed1": 1,
441
+ "nkey": 1,
442
+ "seed2": 1,
443
+ "private": 1
444
+ },
445
+ "other": {
446
+ "host": 1
447
+ }
448
+ },
449
+ "value_len_by_label": {
450
+ "password": {
451
+ "n": 3098,
452
+ "min": 4,
453
+ "p10": 5,
454
+ "median": 9,
455
+ "p90": 21,
456
+ "max": 128,
457
+ "mean": 12.5
458
+ },
459
+ "api_key": {
460
+ "n": 6439,
461
+ "min": 5,
462
+ "p10": 20,
463
+ "median": 48,
464
+ "p90": 64,
465
+ "max": 2379,
466
+ "mean": 57.6
467
+ },
468
+ "uuid": {
469
+ "n": 2316,
470
+ "min": 36,
471
+ "p10": 36,
472
+ "median": 36,
473
+ "p90": 36,
474
+ "max": 36,
475
+ "mean": 36.0
476
+ },
477
+ "token": {
478
+ "n": 2315,
479
+ "min": 7,
480
+ "p10": 16,
481
+ "median": 41,
482
+ "p90": 208,
483
+ "max": 6368,
484
+ "mean": 81.2
485
+ },
486
+ "private_key": {
487
+ "n": 1291,
488
+ "min": 0,
489
+ "p10": 0,
490
+ "median": 0,
491
+ "p90": 886,
492
+ "max": 4367,
493
+ "mean": 207.4
494
+ },
495
+ "other": {
496
+ "n": 170,
497
+ "min": 5,
498
+ "p10": 10,
499
+ "median": 33,
500
+ "p90": 48,
501
+ "max": 404,
502
+ "mean": 45.4
503
+ }
504
+ },
505
+ "charset_by_label": {
506
+ "password": {
507
+ "lower": 1510,
508
+ "digit+lower": 488,
509
+ "digit+lower+symbol+upper": 318,
510
+ "digit+lower+upper": 227,
511
+ "lower+symbol": 210,
512
+ "digit+lower+symbol": 124,
513
+ "lower+upper": 102,
514
+ "lower+symbol+upper": 37,
515
+ "digit": 31,
516
+ "upper": 28,
517
+ "digit+symbol+upper": 7,
518
+ "digit+upper": 7,
519
+ "symbol+upper": 5,
520
+ "symbol": 3,
521
+ "digit+symbol": 1
522
+ },
523
+ "api_key": {
524
+ "digit+lower": 4485,
525
+ "digit+lower+symbol+upper": 567,
526
+ "digit+upper": 539,
527
+ "digit+lower+upper": 304,
528
+ "lower": 182,
529
+ "digit+lower+symbol": 129,
530
+ "upper": 45,
531
+ "digit+symbol": 42,
532
+ "digit": 31,
533
+ "lower+upper": 30,
534
+ "lower+symbol": 22,
535
+ "digit+symbol+upper": 16,
536
+ "lower+symbol+upper": 14
537
+ },
538
+ "uuid": {
539
+ "digit+lower+symbol": 2148,
540
+ "digit+symbol+upper": 149,
541
+ "digit+lower+symbol+upper": 19
542
+ },
543
+ "token": {
544
+ "digit+lower+symbol+upper": 936,
545
+ "digit+lower+upper": 453,
546
+ "digit+lower": 402,
547
+ "digit+lower+symbol": 339,
548
+ "digit+upper": 90,
549
+ "digit+symbol+upper": 19,
550
+ "lower": 17,
551
+ "lower+symbol+upper": 17,
552
+ "upper": 16,
553
+ "lower+upper": 9,
554
+ "digit": 9,
555
+ "lower+symbol": 8
556
+ },
557
+ "other": {
558
+ "digit+lower+symbol": 96,
559
+ "lower+symbol": 42,
560
+ "lower": 9,
561
+ "digit+lower": 7,
562
+ "digit+lower+symbol+upper": 5,
563
+ "lower+upper": 2
564
+ },
565
+ "private_key": {
566
+ "digit+upper": 60
567
+ }
568
+ },
569
+ "quote_style": {
570
+ "none": 8273,
571
+ "\"": 4520,
572
+ "'": 1490,
573
+ "": 47,
574
+ "`": 26
575
+ },
576
+ "line_len_true": {
577
+ "n": 14356,
578
+ "min": 14,
579
+ "p10": 36,
580
+ "median": 62,
581
+ "p90": 185,
582
+ "max": 150826,
583
+ "mean": 190.7
584
+ },
585
+ "secrets_per_file_hist": {
586
+ "1": 1763,
587
+ "2": 554,
588
+ "3": 284,
589
+ "4": 197,
590
+ "5": 128,
591
+ "6": 83,
592
+ "7": 44,
593
+ "8": 37,
594
+ "9": 31,
595
+ "10": 202
596
+ },
597
+ "value_prefix_by_label_top20": {
598
+ "api_key": {
599
+ "cosmo_": 11,
600
+ "akab-": 6,
601
+ "key-": 6,
602
+ "xoxb-": 6,
603
+ "glsa_": 3,
604
+ "phc_": 3,
605
+ "xoxt-": 3,
606
+ "xoxp-": 3,
607
+ "PMAK-": 2,
608
+ "pplx-": 2,
609
+ "xapp-": 2,
610
+ "ghs_": 1,
611
+ "sk-": 1,
612
+ "Phoef-": 1,
613
+ "Zna-": 1,
614
+ "Qibil-": 1,
615
+ "Xez-": 1,
616
+ "xqxb_": 1,
617
+ "sk_": 1,
618
+ "pk_": 1
619
+ },
620
+ "other": {
621
+ "uotvfl-": 1,
622
+ "ucucqo-": 1,
623
+ "pawfre-": 1,
624
+ "ejliot-": 1,
625
+ "yztztr-": 1,
626
+ "woxbay-": 1,
627
+ "mzcave-": 1,
628
+ "yzjdua-": 1,
629
+ "im-": 1,
630
+ "pltqy-": 1,
631
+ "iukupq-": 1,
632
+ "zmjoiz-": 1,
633
+ "finzqk-": 1,
634
+ "hsdigf-": 1,
635
+ "bdfsua-": 1,
636
+ "cihind-": 1,
637
+ "binxiq-": 1,
638
+ "urjuxb-": 1,
639
+ "vpzofd-": 1,
640
+ "ynbewu-": 1
641
+ },
642
+ "password": {
643
+ "cwheg_": 1,
644
+ "seh-": 1,
645
+ "chlz-": 1,
646
+ "jame-": 1,
647
+ "ryoov_": 1,
648
+ "DGXA_": 1,
649
+ "bjy-": 1,
650
+ "gug_": 1,
651
+ "cg-": 1,
652
+ "avy_": 1,
653
+ "qxx_": 1,
654
+ "no-": 1,
655
+ "kk-": 1,
656
+ "qn-": 1,
657
+ "AOG-": 1,
658
+ "holldk_": 1,
659
+ "hbsnly_": 1,
660
+ "ypm_": 1,
661
+ "rar_": 1,
662
+ "nty_": 1
663
+ },
664
+ "token": {
665
+ "akab-": 2,
666
+ "SWMTKN-": 2,
667
+ "ff_": 1,
668
+ "fT-": 1,
669
+ "djspuv-": 1,
670
+ "vdstvw-": 1,
671
+ "yepz-": 1,
672
+ "ucih-": 1,
673
+ "lgpa-": 1,
674
+ "krva-": 1,
675
+ "zzys-": 1,
676
+ "zvsk-": 1,
677
+ "tkly-": 1,
678
+ "sypp-": 1,
679
+ "dsu-": 1,
680
+ "wr-": 1
681
+ }
682
+ }
683
+ }
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ pyarrow>=15
2
+ faker>=20
3
+ huggingface_hub>=0.25 # only for pushing to the Hub
4
+ # build_priors.py needs CredData's own requirements (see CredData/requirements.txt) only to run its download_data.py
sample.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
stats.md ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Dataset statistics
2
+
3
+ Generated from 24 shards of `codeparrot/github-code-clean` (shards 0-23), permissive licenses only.
4
+
5
+ ## Totals
6
+
7
+ | metric | value |
8
+ |---|---:|
9
+ | records (files) | 1,810,060 |
10
+ | files with >=1 secret span | 1,153,616 (63.7%) |
11
+ | files with no secret span (pure negatives; may contain hard negatives) | 656,444 (36.3%) |
12
+ | secret spans | 2,319,190 |
13
+ | hard-negative spans | 1,696,239 |
14
+ | JSONL bytes | 14,426,362,622 (14.43 GB) |
15
+ | Parquet files / bytes (zstd) | 24 / 3,835,016,221 (3.84 GB) |
16
+ | base-corpus rows skipped: non-permissive license | 1,075,029 |
17
+ | base-corpus rows skipped: size outside [200 B, 200 KB] | 161,111 |
18
+ | wall time | 217 s (53 s for shards 0-7 with pre-downloaded shards = 90 MB/s; 164 s for shards 8-23 including on-the-fly downloads = 59 MB/s) with 4 workers |
19
+ | throughput (JSONL output) | 66.39 MB/s aggregate, ~17 MB/s per worker |
20
+
21
+ ## Throughput / scaling
22
+
23
+ - Measured on a 4-vCPU VM: **90 MB/s** with pre-downloaded shards, **~60 MB/s** when shards are downloaded on the fly by the same 4 workers of JSONL output (~23 MB/s per worker process; CPU-bound).
24
+ - One input shard (~355 MB parquet) yields ~600 MB JSONL (~75k records) in ~30 s per worker; shard download from the Hub measured at ~35 MB/s per stream (~10 s per shard), so download roughly matches processing when run with `--workers 4`.
25
+ - Extrapolation: 40 GB JSONL ~= 67 shards -> ~7.5 min at 90 MB/s, ~11 min at 60 MB/s with downloads (plus ~11 min of downloads if not overlapped; the script overlaps them per worker). On 8 cores expect roughly half. Parquet conversion (zstd) adds ~2x the generation time and shrinks size ~2.3x.
26
+ - Full 880-shard corpus (permissive subset) would yield ~528 GB JSONL.
27
+
28
+ ## Secret spans by label
29
+
30
+ | label | count | % |
31
+ |---|---:|---:|
32
+ | api_key | 1,008,714 | 43.5 |
33
+ | password | 482,135 | 20.8 |
34
+ | token | 363,752 | 15.7 |
35
+ | email | 248,630 | 10.7 |
36
+ | private_key | 215,959 | 9.3 |
37
+
38
+ ## Secret spans by value_type
39
+
40
+ | value_type | count | % |
41
+ |---|---:|---:|
42
+ | password | 482,135 | 20.8 |
43
+ | email | 248,630 | 10.7 |
44
+ | pem_private_key | 215,959 | 9.3 |
45
+ | generic_hex_key | 215,759 | 9.3 |
46
+ | generic_base64_secret | 143,999 | 6.2 |
47
+ | aws_access_key_id | 108,440 | 4.7 |
48
+ | aws_secret_access_key | 107,670 | 4.6 |
49
+ | generic_alnum_key | 72,287 | 3.1 |
50
+ | stripe_secret_key | 72,231 | 3.1 |
51
+ | google_api_key | 72,035 | 3.1 |
52
+ | jwt | 69,314 | 3.0 |
53
+ | github_pat | 52,267 | 2.3 |
54
+ | bearer_token_opaque | 51,927 | 2.2 |
55
+ | mailgun_api_key | 36,176 | 1.6 |
56
+ | anthropic_api_key | 36,090 | 1.6 |
57
+ | sendgrid_api_key | 36,048 | 1.6 |
58
+ | twilio_api_key | 36,039 | 1.6 |
59
+ | openai_api_key | 35,976 | 1.6 |
60
+ | azure_client_secret | 35,964 | 1.6 |
61
+ | basic_auth_b64 | 34,582 | 1.5 |
62
+ | slack_token | 34,404 | 1.5 |
63
+ | discord_bot_token | 17,510 | 0.8 |
64
+ | hf_token | 17,355 | 0.7 |
65
+ | digitalocean_pat | 17,313 | 0.7 |
66
+ | gitlab_pat | 17,297 | 0.7 |
67
+ | slack_webhook | 17,266 | 0.7 |
68
+ | npm_token | 17,265 | 0.7 |
69
+ | github_fine_grained_pat | 17,252 | 0.7 |
70
+
71
+ ## Hard-negative spans by value_type
72
+
73
+ | value_type | count | % |
74
+ |---|---:|---:|
75
+ | ssh_public_key | 154,826 | 9.1 |
76
+ | sha256_hash | 154,820 | 9.1 |
77
+ | version_or_id | 154,375 | 9.1 |
78
+ | public_key_pem | 154,348 | 9.1 |
79
+ | uuid | 154,284 | 9.1 |
80
+ | md5_hash | 154,226 | 9.1 |
81
+ | placeholder | 154,133 | 9.1 |
82
+ | sha1_git_sha | 153,941 | 9.1 |
83
+ | base64_non_secret | 153,819 | 9.1 |
84
+ | example_email | 153,763 | 9.1 |
85
+ | env_var_reference | 153,704 | 9.1 |
86
+
87
+ ## Secret spans by syntactic context
88
+
89
+ | context | count | % |
90
+ |---|---:|---:|
91
+ | assignment | 1,091,580 | 47.1 |
92
+ | json_key | 258,561 | 11.1 |
93
+ | yaml_key | 239,092 | 10.3 |
94
+ | pem_block | 216,577 | 9.3 |
95
+ | comment | 191,427 | 8.3 |
96
+ | auth_header | 159,434 | 6.9 |
97
+ | url_credential | 72,576 | 3.1 |
98
+ | function_arg | 47,252 | 2.0 |
99
+ | env_assignment | 42,691 | 1.8 |
100
+
101
+ ## Records by language
102
+
103
+ | language | count | % |
104
+ |---|---:|---:|
105
+ | Java | 347,001 | 19.2 |
106
+ | JavaScript | 210,187 | 11.6 |
107
+ | HTML | 195,124 | 10.8 |
108
+ | PHP | 154,047 | 8.5 |
109
+ | C | 144,024 | 8.0 |
110
+ | Markdown | 128,952 | 7.1 |
111
+ | C# | 128,866 | 7.1 |
112
+ | Python | 116,954 | 6.5 |
113
+ | C++ | 94,112 | 5.2 |
114
+ | Ruby | 83,580 | 4.6 |
115
+ | GO | 48,747 | 2.7 |
116
+ | TypeScript | 40,648 | 2.2 |
117
+ | CSS | 26,863 | 1.5 |
118
+ | Scala | 18,369 | 1.0 |
119
+ | Shell | 17,885 | 1.0 |
120
+ | SQL | 6,795 | 0.4 |
121
+ | Haskell | 6,498 | 0.4 |
122
+ | Makefile | 6,405 | 0.4 |
123
+ | Rust | 6,296 | 0.3 |
124
+ | Lua | 5,003 | 0.3 |
125
+ | Perl | 4,947 | 0.3 |
126
+ | Dockerfile | 3,153 | 0.2 |
127
+ | PowerShell | 3,105 | 0.2 |
128
+ | TeX | 2,930 | 0.2 |
129
+ | CMake | 2,478 | 0.1 |
130
+ | Visual Basic | 1,969 | 0.1 |
131
+ | Batchfile | 1,844 | 0.1 |
132
+ | FORTRAN | 1,316 | 0.1 |
133
+ | Julia | 1,242 | 0.1 |
134
+ | Assembly | 720 | 0.0 |
135
+
136
+ ## File size distribution (text field, sample of 2 shards)
137
+
138
+ | bucket | records |
139
+ |---|---:|
140
+ | <1 KB | 29,976 |
141
+ | 1-10 KB | 99,191 |
142
+ | 10-100 KB | 21,311 |
143
+ | >=100 KB | 858 |
144
+
145
+ ## Validation (shards 0-1, 151,336 records)
146
+
147
+ - Offset assertion `text[start:end] == value` on every span and hard negative: **0 failures** (also asserted at generation time for all records).
148
+ - Regex scanner (gitleaks-style patterns for 15 value types) finds **100%** of injected spans of those types at the labeled offsets (secrets are not mangled by quoting/escaping/indentation).
149
+ - 20 random records eyeballed; see `validate.py --n-eyeball 20`.
150
+
151
+ ## Held-out eval (eval_creddata.jsonl)
152
+
153
+ - 67,896 real labeled lines from Samsung/CredData (+-3 lines context): 15,753 GroundTruth=T, 48,061 F (hard negatives), 4,082 X (ambiguous/unclear, no span).
to_parquet.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Convert generated part-*.jsonl files to Parquet (one parquet per JSONL part, zstd)."""
3
+ import glob, json, os, sys
4
+ import pyarrow as pa, pyarrow.parquet as pq
5
+ from multiprocessing import Pool
6
+
7
+ SPAN = pa.struct([("start", pa.int64()), ("end", pa.int64()), ("label", pa.string()), ("value_type", pa.string()),
8
+ ("context", pa.string()), ("synthetic", pa.bool_()), ("value", pa.string())])
9
+ SCHEMA = pa.schema([("id", pa.string()), ("source", pa.string()), ("repo", pa.string()), ("license", pa.string()),
10
+ ("language", pa.string()), ("path", pa.string()), ("text", pa.string()),
11
+ ("spans", pa.list_(SPAN)), ("hard_negatives", pa.list_(SPAN))])
12
+
13
+ def conv(args):
14
+ src, dst = args
15
+ w = pq.ParquetWriter(dst + ".tmp", SCHEMA, compression="zstd")
16
+ buf = []
17
+ def flush():
18
+ if buf:
19
+ w.write_table(pa.Table.from_pylist(buf, schema=SCHEMA)); buf.clear()
20
+ with open(src, encoding="utf-8") as fh:
21
+ for line in fh:
22
+ r = json.loads(line)
23
+ for s in r["hard_negatives"]:
24
+ s.setdefault("context", None)
25
+ buf.append(r)
26
+ if len(buf) >= 10000:
27
+ flush()
28
+ flush(); w.close(); os.replace(dst + ".tmp", dst)
29
+ return dst, os.path.getsize(dst)
30
+
31
+ if __name__ == "__main__":
32
+ src_dir, dst_dir = sys.argv[1], sys.argv[2]
33
+ os.makedirs(dst_dir, exist_ok=True)
34
+ jobs = [(p, os.path.join(dst_dir, os.path.basename(p).replace(".jsonl", ".parquet"))) for p in sorted(glob.glob(os.path.join(src_dir, "part-*.jsonl")))]
35
+ with Pool(int(sys.argv[3]) if len(sys.argv) > 3 else 4) as pool:
36
+ for dst, n in pool.imap_unordered(conv, jobs):
37
+ print(dst, f"{n/1e6:.0f} MB", flush=True)
validate.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Validate a generated dataset directory: offsets, label counts, regex detectability, random samples.
3
+
4
+ Usage: python validate.py --data /path/to/dataset [--sample-files 2] [--n-eyeball 20] [--write-sample sample.jsonl --sample-n 500]
5
+ """
6
+ import argparse, collections, glob, json, os, random, re
7
+
8
+ SCANNER = { # a deliberately simple regex scanner (gitleaks-like) used only as a sanity check
9
+ "aws_access_key_id": re.compile(r"AKIA[0-9A-Z]{16}"),
10
+ "github_pat": re.compile(r"gh[pos]_[A-Za-z0-9]{36}"),
11
+ "github_fine_grained_pat": re.compile(r"github_pat_[A-Za-z0-9]{22}_[A-Za-z0-9]{59}"),
12
+ "slack_token": re.compile(r"xox[abp]-[0-9A-Za-z-]{10,}"),
13
+ "jwt": re.compile(r"eyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+"),
14
+ "google_api_key": re.compile(r"AIza[0-9A-Za-z_-]{35}"),
15
+ "stripe_secret_key": re.compile(r"(?:sk|rk)_(?:live|test)_[0-9A-Za-z]{24}"),
16
+ "pem_private_key": re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----"),
17
+ "email": re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}"),
18
+ "sendgrid_api_key": re.compile(r"SG\.[A-Za-z0-9_-]{22}\.[A-Za-z0-9_-]{43}"),
19
+ "openai_api_key": re.compile(r"sk-(?:proj-)?[A-Za-z0-9]{48}"),
20
+ "hf_token": re.compile(r"hf_[A-Za-z0-9]{34}"),
21
+ "gitlab_pat": re.compile(r"glpat-[A-Za-z0-9_-]{20}"),
22
+ "npm_token": re.compile(r"npm_[A-Za-z0-9]{36}"),
23
+ "generic_hex_key": re.compile(r"\b[0-9a-f]{32,64}\b"),
24
+ }
25
+
26
+ def main():
27
+ ap = argparse.ArgumentParser()
28
+ ap.add_argument("--data", required=True)
29
+ ap.add_argument("--sample-files", type=int, default=2)
30
+ ap.add_argument("--n-eyeball", type=int, default=20)
31
+ ap.add_argument("--write-sample")
32
+ ap.add_argument("--sample-n", type=int, default=500)
33
+ ap.add_argument("--seed", type=int, default=0)
34
+ a = ap.parse_args()
35
+ random.seed(a.seed)
36
+ parts = sorted(glob.glob(os.path.join(a.data, "part-*.jsonl")))
37
+ use = parts[:a.sample_files]
38
+ C = collections.Counter
39
+ st = dict(files=0, injected=0, clean=0, spans=0, negs=0, bad_offsets=0, label=C(), vtype=C(), ctx=C(), lang=C(), negtype=C(),
40
+ size_hist=C(), spans_per_file=C(), bytes=0)
41
+ det = C(); det_tot = C()
42
+ reservoir = []; n_seen = 0
43
+ for p in use:
44
+ with open(p, encoding="utf-8") as fh:
45
+ for line in fh:
46
+ r = json.loads(line); t = r["text"]
47
+ st["files"] += 1; st["bytes"] += len(line)
48
+ st["lang"][r["language"]] += 1
49
+ st["size_hist"][("<1KB" if len(t) < 1024 else "<10KB" if len(t) < 10240 else "<100KB" if len(t) < 102400 else ">=100KB")] += 1
50
+ st["spans_per_file"][min(len(r["spans"]), 6)] += 1
51
+ st["injected" if r["spans"] else "clean"] += 1
52
+ for s in r["spans"] + r["hard_negatives"]:
53
+ if t[s["start"]:s["end"]] != s["value"]:
54
+ st["bad_offsets"] += 1
55
+ for s in r["spans"]:
56
+ st["spans"] += 1; st["label"][s["label"]] += 1; st["vtype"][s["value_type"]] += 1; st["ctx"][s["context"]] += 1
57
+ rx = SCANNER.get(s["value_type"])
58
+ if rx:
59
+ det_tot[s["value_type"]] += 1
60
+ if rx.search(s["value"]) and any(m.start() <= s["start"] < m.end() for m in rx.finditer(t)):
61
+ det[s["value_type"]] += 1
62
+ for s in r["hard_negatives"]:
63
+ st["negs"] += 1; st["negtype"][s["value_type"]] += 1
64
+ n_seen += 1
65
+ if len(reservoir) < a.sample_n:
66
+ reservoir.append(r)
67
+ else:
68
+ j = random.randrange(n_seen)
69
+ if j < a.sample_n: reservoir[j] = r
70
+ assert st["bad_offsets"] == 0, st["bad_offsets"]
71
+ out = {k: (dict(v.most_common()) if isinstance(v, C) else v) for k, v in st.items()}
72
+ out["regex_detectability"] = {k: f"{det[k]}/{det_tot[k]} ({100*det[k]/det_tot[k]:.1f}%)" for k in sorted(det_tot)}
73
+ print(json.dumps(out, indent=1))
74
+ if a.write_sample:
75
+ with open(a.write_sample, "w", encoding="utf-8") as fh:
76
+ for r in reservoir:
77
+ fh.write(json.dumps(r, ensure_ascii=False) + "\n")
78
+ print("\n===== EYEBALL SAMPLES =====")
79
+ eye = [r for r in reservoir if r["spans"] or r["hard_negatives"]]
80
+ for r in random.sample(eye, min(a.n_eyeball, len(eye))):
81
+ t = r["text"]
82
+ print(f"\n--- {r['id']} {r['language']} {r['path']}")
83
+ for s in r["spans"] + r["hard_negatives"]:
84
+ ls = t.rfind("\n", 0, s["start"]) + 1; le = t.find("\n", s["end"]); le = len(t) if le < 0 else le
85
+ print(f" [{s['label']}/{s['value_type']}] {t[ls:le][:160]!r}")
86
+
87
+ if __name__ == "__main__":
88
+ main()