#!/usr/bin/env python3 """Synthetic secret-injection dataset generator with cross-document coreference (v3). Streams permissively-licensed files from codeparrot/github-code-clean (parquet shards on the Hugging Face Hub), groups files into clusters (real multi-file repos, synthetic "bundles" of unrelated files, or singletons), gives every cluster an entity pool of secrets / emails / synthetic persons, injects format-correct synthetic secrets at positions drawn from Samsung/CredData placement priors (priors.json) with entities recurring across the files of a cluster, injects labeled hard negatives, and writes span-labeled JSONL plus a per-cluster entity table (gold replacements included). Examples # 2 GB using the first shards, 4 worker processes, downloading shards on the fly python generate_dataset.py --out /data/poc --target-bytes 2e9 --workers 4 # scale: ~40 GB python generate_dataset.py --out /data/full --target-bytes 40e9 --workers 8 --start-shard 0 # use pre-downloaded shards python generate_dataset.py --out /data/poc --shard-dir ./shards --target-bytes 2e9 Dependencies: python>=3.9, pyarrow, faker (stdlib otherwise). """ import argparse, base64, hashlib, json, os, random, re, string, sys, time, unicodedata, uuid, urllib.request from multiprocessing import Pool try: import pyarrow.parquet as pq import pyarrow.compute as pc except ImportError: sys.exit("pip install pyarrow") try: from faker import Faker except ImportError: sys.exit("pip install faker") HF_URL = "https://huggingface.co/datasets/codeparrot/github-code-clean/resolve/main/data/train-{i:05d}-of-00880.parquet" N_SHARDS = 880 PERMISSIVE = {"mit", "apache-2.0", "bsd-3-clause", "bsd-2-clause", "isc", "unlicense", "cc0-1.0"} # -------------------------------------------------------------------------------------- # Language syntax table: comment prefix, assignment template, quote char, extra forms # -------------------------------------------------------------------------------------- # assign: how a hardcoded variable looks. {n}=name {q}=quote {v}=value LANG = { "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},"]), "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},"]), "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},"]), "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});"]), "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},"]), "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},"]), "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},"]), "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},"]), "C": dict(c="//", assign=["const char *{n} = {q}{v}{q};", "static const char {n}[] = {q}{v}{q};", "#define {N} {q}{v}{q}"], q=['"'], kw=[]), "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=[]), "Rust": dict(c="//", assign=["let {n} = {q}{v}{q};", "const {N}: &str = {q}{v}{q};", "static {N}: &str = {q}{v}{q};"], q=['"'], kw=[]), "Scala": dict(c="//", assign=["val {n} = {q}{v}{q}", "private val {n} = {q}{v}{q}"], q=['"'], kw=["{q}{n}{q} -> {q}{v}{q},"]), "Kotlin": dict(c="//", assign=["val {n} = {q}{v}{q}", "const val {N} = {q}{v}{q}"], q=['"'], kw=[]), "Shell": dict(c="#", assign=["{N}={q}{v}{q}", "export {N}={q}{v}{q}", "{n}={q}{v}{q}"], q=['"', "'", ""], kw=["--{n} {q}{v}{q} \\"]), "PowerShell": dict(c="#", assign=["${n} = {q}{v}{q}", "$env:{N} = {q}{v}{q}"], q=['"', "'"], kw=[]), "Batchfile": dict(c="REM", assign=["set {N}={v}", "SET {N}={v}"], q=[""], kw=[]), "Perl": dict(c="#", assign=["my ${n} = {q}{v}{q};", "${n} = {q}{v}{q};"], q=["'", '"'], kw=["{n} => {q}{v}{q},"]), "Lua": dict(c="--", assign=["local {n} = {q}{v}{q}", "{n} = {q}{v}{q}"], q=['"', "'"], kw=["{n} = {q}{v}{q},"]), "Julia": dict(c="#", assign=["{n} = {q}{v}{q}", "const {N} = {q}{v}{q}"], q=['"'], kw=[]), "Haskell": dict(c="--", assign=["{n} = {q}{v}{q}"], q=['"'], kw=[]), "SQL": dict(c="--", assign=["SET @{n} = {q}{v}{q};", "IDENTIFIED BY {q}{v}{q};", "CREATE USER '{u}'@'%' IDENTIFIED BY {q}{v}{q};"], q=["'"], kw=[]), "Dockerfile": dict(c="#", assign=["ENV {N}={v}", "ENV {N} {v}", "ARG {N}={v}"], q=[""], kw=[]), "Makefile": dict(c="#", assign=["{N} = {v}", "{N} := {v}", "export {N}={v}"], q=[""], kw=[]), "CMake": dict(c="#", assign=["set({N} {q}{v}{q})"], q=['"'], kw=[]), "HTML": dict(c="" if c == "/*": line += " */" elif ctx == "url_credential": scheme = R.choice(["postgres", "postgresql", "mysql", "mongodb", "mongodb+srv", "redis", "amqp", "https", "http", "ftp", "sftp"]) host = R.choice([fake.hostname(), "localhost", fake.ipv4(), fake.domain_name()]) url = f"{scheme}://{U()}:{value}@{host}" + R.choice([":5432/app", "/", ":6379/0", "/db", "/api/v1", ":3306/prod", ""]) a = R.choice(L["assign"]) if ctx != "pem_block" else "{n} = {q}{v}{q}" if lang == "SQL": a = "{n} = {q}{v}{q}" 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=U()) elif ctx == "auth_header": if label == "token" and R.random() < 0.6: hv = f"Bearer {value}" else: hv = f"Basic {value}" if re.fullmatch(r"[A-Za-z0-9+/=]+", value) else f"Bearer {value}" tmpls = AUTH_TMPL.get(lang, ['{q}Authorization{q}: {q}{hv}{q},', "Authorization: {hv}"]) tmpl = R.choice(tmpls) line = tmpl.format(q=q or '"', hv=hv) elif ctx in ("json_key", "yaml_key", "env_assignment", "ini_or_props", "function_arg") and L["kw"] and ctx != "env_assignment": line = R.choice(L["kw"]).format(n=n, N=upper, q=(q if q in ("'", '"') else '"'), v=value) elif ctx == "env_assignment": 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=U()) else: line = R.choice(L["assign"]).format(n=n, N=upper, q=q, v=value, u=U()) s = line.rindex(value) user_pos = None if user_given: for m in re.finditer(re.escape(_u[0]), line): if m.end() <= s and (m.end() == len(line) or not line[m.end()].isalnum()) and (m.start() == 0 or not line[m.start() - 1].isalnum()): user_pos = (m.start(), m.end()) return line, s, s + len(value), "literal", user_pos AUTH_TMPL = { "Python": ['headers[{q}Authorization{q}] = {q}{hv}{q}', 'headers = {{{q}Authorization{q}: {q}{hv}{q}}}', '{q}Authorization{q}: {q}{hv}{q},'], "JavaScript": ['{q}Authorization{q}: {q}{hv}{q},', 'headers.Authorization = {q}{hv}{q};', "xhr.setRequestHeader({q}Authorization{q}, {q}{hv}{q});"], "TypeScript": ['{q}Authorization{q}: {q}{hv}{q},', 'headers.set({q}Authorization{q}, {q}{hv}{q});'], "GO": ['req.Header.Set({q}Authorization{q}, {q}{hv}{q})', 'req.Header.Add({q}Authorization{q}, {q}{hv}{q})'], "Java": ['conn.setRequestProperty({q}Authorization{q}, {q}{hv}{q});', '.header({q}Authorization{q}, {q}{hv}{q})', 'headers.set({q}Authorization{q}, {q}{hv}{q});'], "C#": ['client.DefaultRequestHeaders.Add({q}Authorization{q}, {q}{hv}{q});', 'request.Headers[{q}Authorization{q}] = {q}{hv}{q};'], "PHP": ["'Authorization: {hv}',", "$headers[{q}Authorization{q}] = {q}{hv}{q};"], "Ruby": ["request[{q}Authorization{q}] = {q}{hv}{q}", "headers: {{ {q}Authorization{q} => {q}{hv}{q} }}"], "Shell": ["-H {q}Authorization: {hv}{q} \\", "curl -H {q}Authorization: {hv}{q} https://api.example.com/v1/me"], "Markdown": [" Authorization: {hv}", "`Authorization: {hv}`"], "Rust": ['.header({q}Authorization{q}, {q}{hv}{q})'], "C": ['headers = curl_slist_append(headers, {q}Authorization: {hv}{q});'], "C++": ['headers = curl_slist_append(headers, {q}Authorization: {hv}{q});'], "PowerShell": ['$headers = @{{ Authorization = {q}{hv}{q} }}'], } NEG_NAME_LABEL = {"example_email": "email", "public_key_pem": "private_key", "ssh_public_key": "private_key"} NEG_NAMES = { "private_key": {"public_key": 30, "pubkey": 10, "ssh_public_key": 10, "authorized_key": 5, "verify_key": 5, "cert": 5}, "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}, "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}, "version_or_id": {"version": 20, "host": 10, "ip": 10, "app_id": 10, "path": 10, "package": 5, "bundle_id": 5, "build": 5, "server": 5}, "base64_non_secret": {"payload": 20, "data": 10, "body": 10, "encoded": 10, "message": 10, "content": 5, "blob": 5}, "person": {"author": 20, "owner": 10, "user": 10, "maintainer": 10, "name": 10, "username": 8, "created_by": 5, "contact": 5}, } 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", "placeholder_name": "person"} CTX_ALLOWED = {"assignment", "json_key", "yaml_key", "env_assignment", "comment", "url_credential", "auth_header", "function_arg", "pem_block"} PERSON_CTX = {"comment": 45, "assignment": 35, "json_key": 10, "yaml_key": 10} NO_ENTITY = {"entity_id": None, "surface_form_type": None, "replacement": None} def span_meta(ent, label, vt, ctx, form, surface_key): repl = ent["replacement_forms"][surface_key] if form == "escaped_literal": repl = repl.replace(*PEM_ESCAPE) return {"label": label, "value_type": vt, "context": ctx, "synthetic": True, "entity_id": ent["entity_id"], "surface_form_type": form if surface_key == "literal" else surface_key, "replacement": repl} def inject(text, lang, priors, n_secrets, n_negs, pool, doc_index, cfg, n_person_mentions=0): """Insert n_secrets secret lines (entities drawn from / added to the cluster pool), n_person_mentions person mentions and n_negs hard-negative lines into text. Returns (text, spans, negs).""" lines = text.split("\n") nl = len(lines) inserts = [] # (line_index, rendered_line, [(rel_start, rel_end, meta), ...]) used_here = [] ents = {e["entity_id"]: e for e in pool.entities} for _ in range(n_secrets): label = priors.sample_label() if used_here and R.random() < cfg["p_repeat"]: # second mention of an entity already in this file ent = R.choice(used_here); label = ent["entity_type"] elif pool.secrets and R.random() < cfg["p_reuse"]: # recurrence of a cluster entity (any label), preferably one not yet in this file ent = R.choice([e for e in pool.secrets if e not in used_here] or pool.secrets); label = ent["entity_type"] else: owner = R.choice(pool.persons) if pool.persons and label != "email" and R.random() < cfg["p_owner"] else None ent = pool.new_secret(label, owner) ctx = priors.sample_ctx(label, CTX_ALLOWED) name = priors.sample_name(label) owner = ents.get(ent["owner_entity_id"]) # owners are persons, all created before the first document line, s, e, form, upos = render(ctx, lang, label, name, ent["canonical"], user=owner["forms"]["username"] if owner else None) if label == "private_key": ctx = "pem_block" parts = [(s, e, span_meta(ent, label, ent["value_type"], ctx, form, "literal"))] pool.note(ent, doc_index); used_here.append(ent) if upos: parts.append((upos[0], upos[1], span_meta(owner, "username", "username", ctx, "literal", "username"))) pool.note(owner, doc_index) inserts.append((R.randint(0, nl), line, parts)) for _ in range(n_person_mentions): person = R.choice(pool.persons) fk = pool.person_form(person) ctx = R.choices(list(PERSON_CTX), list(PERSON_CTX.values()))[0] name = R.choices(list(PERSON_NAMES[fk]), list(PERSON_NAMES[fk].values()))[0] line, s, e, form, _ = render(ctx, lang, PERSON_FORM_LABEL[fk], name, person["forms"][fk], comment_tmpls=PERSON_COMMENT_TMPL[fk]) inserts.append((R.randint(0, nl), line, [(s, e, span_meta(person, PERSON_FORM_LABEL[fk], "email" if fk == "email" else fk, ctx, "literal", fk))])) pool.note(person, doc_index) for _ in range(n_negs): vt, fn = R.choice(HARD_NEGATIVES) value = fn() if vt in ("env_var_reference",): 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") s = line.rindex(value); e = s + len(value) else: label_like = NEG_NAME_LABEL.get(vt) or R.choice(["api_key", "password", "token"]) ctx = priors.sample_ctx(label_like, CTX_ALLOWED - {"pem_block", "auth_header", "url_credential"}) if "\n" in value: ctx = "pem_block" grp = NEG_NAME_GROUP.get(vt) name = R.choices(list(NEG_NAMES[grp]), list(NEG_NAMES[grp].values()))[0] if grp else priors.sample_name(label_like) line, s, e, _, _ = render(ctx, lang, "api_key" if label_like == "private_key" else label_like, name, value, is_negative=True) inserts.append((R.randint(0, nl), line, [(s, e, dict({"label": "not_secret", "value_type": vt, "context": None, "synthetic": True}, **NO_ENTITY))])) inserts.sort(key=lambda x: x[0]) out = []; spans = []; negs = []; pos = 0; li = 0 for idx, line, parts in inserts: while li < idx: out.append(lines[li]); pos += len(lines[li]) + 1; li += 1 ref = lines[idx] if idx < nl else (lines[-1] if lines else "") indent = re.match(r"[ \t]*", ref).group(0) if lang != "Markdown" else "" if "\n" in line and lang not in ("Python",): indent = "" full = indent + line for s, e, meta in parts: rec = dict(meta, start=pos + len(indent) + s, end=pos + len(indent) + e) (negs if meta["label"] == "not_secret" else spans).append(rec) out.append(full); pos += len(full) + 1 while li < nl: out.append(lines[li]); pos += len(lines[li]) + 1; li += 1 spans.sort(key=lambda r: r["start"]); negs.sort(key=lambda r: r["start"]) return "\n".join(out), spans, negs # -------------------------------------------------------------------------------------- # Shard processing # -------------------------------------------------------------------------------------- def fetch_shard(i, shard_dir, keep): os.makedirs(shard_dir, exist_ok=True) p = os.path.join(shard_dir, f"train-{i:05d}-of-00880.parquet") if os.path.exists(p): return p, False tmp = p + ".part" urllib.request.urlretrieve(HF_URL.format(i=i), tmp) os.replace(tmp, p) return p, not keep BUNDLE_SIZE = {2: 35, 3: 25, 4: 15, 5: 10, 6: 7, 7: 4, 8: 4} N_PERSONS_MULTI = ([0, 1, 2, 3], [30, 40, 20, 10]) N_PERSONS_SINGLE = ([0, 1], [70, 30]) N_PERSON_MENTIONS = ([0, 1, 2], [65, 25, 10]) def rec_id(i, ex): return f"ghcc-{i:05d}-" + hashlib.sha1(f"{ex['repo_name']}/{ex['path']}".encode()).hexdigest()[:16] def plan_clusters(pf, i, cfg, stats): """Pass 1 (cheap: no text is kept): decide which kept rows form which cluster. Returns (row_index -> cluster_key, {cluster_key: {"kind", "members": [row_index...], "key"}}).""" rows = [] # (kept, repo, lang, rid) per row of the shard for rg in range(pf.metadata.num_row_groups): tb = pf.read_row_group(rg, columns=["repo_name", "path", "license", "language", "code"]) lens = pc.utf8_length(tb["code"]).to_pylist() for repo, path, lic, lang, n in zip(tb["repo_name"].to_pylist(), tb["path"].to_pylist(), tb["license"].to_pylist(), tb["language"].to_pylist(), lens): if cfg["max_rows"] and len(rows) >= cfg["max_rows"]: rows.append(None); continue if lic not in PERMISSIVE: stats["skipped_license"] += 1; rows.append(None); continue if not (cfg["min_bytes"] <= n <= cfg["max_bytes"]): stats["skipped_size"] += 1; rows.append(None); continue rows.append((repo, lang, rec_id(i, {"repo_name": repo, "path": path}))) by_repo = {} for idx, r in enumerate(rows): if r: by_repo.setdefault(r[0], []).append(idx) clusters = {}; plan = {} def add(kind, key, members): ck = f"{kind}:{key}" clusters[ck] = {"kind": kind, "key": key, "members": members} for m in members: plan[m] = ck loose = [] for repo, idxs in by_repo.items(): if len(idxs) >= 2 and not cfg["no_repo_clusters"]: k = -(-len(idxs) // cfg["cluster_cap"]) # split big repos into near-equal chunks <= cap per = -(-len(idxs) // k) for c in range(k): add("repo", f"{repo}#{c}", idxs[c * per:(c + 1) * per]) else: loose.extend(idxs) loose.sort() queues = {} # bundle queues: per language (mono-language bundles) and one mixed; bounded buffering in pass 2 def flush(qk): mem = queues.pop(qk)["m"] if len(mem) >= 2: add("bundle", "+".join(sorted(rows[m][2] for m in mem)), mem) else: for m in mem: add("singleton", rows[m][2], [m]) for idx in loose: if R.random() < cfg["singleton_frac"]: add("singleton", rows[idx][2], [idx]); continue qk = rows[idx][1] if R.random() < 0.5 else "*" q = queues.setdefault(qk, {"m": [], "n": R.choices(list(BUNDLE_SIZE), list(BUNDLE_SIZE.values()))[0]}) q["m"].append(idx) if len(q["m"]) >= q["n"]: flush(qk) for qk in list(queues): flush(qk) return plan, clusters def emit_cluster(c, i, cfg, priors, fh, stats): kind = c["kind"] cid = "c-%05d-%s" % (i, hashlib.blake2b(f"{kind}:{c['key']}".encode(), digest_size=8).hexdigest()) seed = int.from_bytes(hashlib.blake2b(f"{cfg['seed']}:{cid}".encode(), digest_size=8).digest(), "big") R.seed(seed); Faker.seed(seed) members = [c["buf"][m] for m in c["members"]] n = len(members) np_ = 0 if cfg["no_persons"] else R.choices(*(N_PERSONS_MULTI if n > 1 else N_PERSONS_SINGLE))[0] pool = EntityPool(cid, np_) recs = [] for doc_index, ex in enumerate(members): text, lang = ex["code"], ex["language"] spans, negs = [], [] if R.random() < cfg["inject_frac"]: n_sec = priors.sample_nsec() if R.random() < 0.85 else 0 n_neg = R.choice([0, 0, 1, 1, 1, 2, 2, 3]) n_pm = R.choices(*N_PERSON_MENTIONS)[0] if pool.persons else 0 if n_sec or n_neg or n_pm: text, spans, negs = inject(text, lang, priors, n_sec, n_neg, pool, doc_index, cfg, n_pm) for s in spans + negs: v = text[s["start"]:s["end"]] assert len(v) == s["end"] - s["start"] and v.strip() == v and len(v) > 0, (s, v) s["value"] = v recs.append({"id": rec_id(i, ex), "source": "codeparrot/github-code-clean", "repo": ex["repo_name"], "license": ex["license"], "language": lang, "path": ex["path"], "text": text, "spans": spans, "hard_negatives": negs, "cluster_id": cid, "cluster_kind": kind, "cluster_size": n, "doc_index": doc_index, "entities": None}) table = pool.table() recs[0]["entities"] = table for e in table: stats["entities"] += 1 stats["entity_type"][e["entity_type"]] = stats["entity_type"].get(e["entity_type"], 0) + 1 stats["docs_per_entity"][str(min(e["n_docs"], 6))] = stats["docs_per_entity"].get(str(min(e["n_docs"], 6)), 0) + 1 stats["mentions_per_entity"][str(min(e["n_mentions"], 8))] = stats["mentions_per_entity"].get(str(min(e["n_mentions"], 8)), 0) + 1 if e["owner_entity_id"]: stats["owned_entities"] += 1 if n > 1: stats["recurring_entities"] += sum(1 for e in table if e["n_docs"] > 1) stats["multi_entities"] += len(table) stats["clusters"] += 1 stats["cluster_kind"][kind] = stats["cluster_kind"].get(kind, 0) + 1 stats["cluster_size"][str(n)] = stats["cluster_size"].get(str(n), 0) + 1 for rec in recs: spans, negs, lang = rec["spans"], rec["hard_negatives"], rec["language"] line = json.dumps(rec, ensure_ascii=False) + "\n" fh.write(line) stats["files"] += 1; stats["bytes"] += len(line.encode("utf-8", "replace")) stats["injected_files" if spans else "clean_files"] += 1 stats["spans"] += len(spans); stats["negs"] += len(negs) stats["lang"][lang] = stats["lang"].get(lang, 0) + 1 stats["records_by_kind"][kind] = stats["records_by_kind"].get(kind, 0) + 1 for s in spans: stats["label"][s["label"]] = stats["label"].get(s["label"], 0) + 1 stats["value_type"][s["value_type"]] = stats["value_type"].get(s["value_type"], 0) + 1 stats["context"][s["context"]] = stats["context"].get(s["context"], 0) + 1 stats["surface_form"][s["surface_form_type"]] = stats["surface_form"].get(s["surface_form_type"], 0) + 1 for s in negs: stats["value_type"]["neg:" + s["value_type"]] = stats["value_type"].get("neg:" + s["value_type"], 0) + 1 def process_shard(args): i, cfg = args R.seed(cfg["seed"] * 100003 + i); Faker.seed(cfg["seed"] * 100003 + i) priors = Priors(cfg["priors"]) path, delete_after = fetch_shard(i, cfg["shard_dir"], cfg["keep_shards"]) out_path = os.path.join(cfg["out"], f"part-{i:05d}.jsonl") stats = {"shard": i, "files": 0, "injected_files": 0, "clean_files": 0, "bytes": 0, "spans": 0, "negs": 0, "label": {}, "value_type": {}, "lang": {}, "context": {}, "skipped_license": 0, "skipped_size": 0, "clusters": 0, "cluster_kind": {}, "cluster_size": {}, "records_by_kind": {}, "entities": 0, "entity_type": {}, "docs_per_entity": {}, "mentions_per_entity": {}, "owned_entities": 0, "recurring_entities": 0, "multi_entities": 0, "surface_form": {}, "peak_buffered_rows": 0} t0 = time.time() pf = pq.ParquetFile(path) plan, clusters = plan_clusters(pf, i, cfg, stats) stats["seconds_plan"] = round(time.time() - t0, 1) buffered = 0; idx = 0 with open(out_path + ".tmp", "w", encoding="utf-8") as fh: for rg in range(pf.metadata.num_row_groups): for ex in pf.read_row_group(rg, columns=["code", "repo_name", "path", "language", "license"]).to_pylist(): ck = plan.get(idx); idx += 1 if ck is None: continue c = clusters[ck] c.setdefault("buf", {})[idx - 1] = ex; buffered += 1 stats["peak_buffered_rows"] = max(stats["peak_buffered_rows"], buffered) if len(c["buf"]) == len(c["members"]): emit_cluster(c, i, cfg, priors, fh, stats) buffered -= len(c["members"]); del clusters[ck] assert not clusters, f"{len(clusters)} clusters never completed" os.replace(out_path + ".tmp", out_path) if delete_after: os.remove(path) stats["seconds"] = round(time.time() - t0, 1) with open(os.path.join(cfg["out"], f"part-{i:05d}.stats.json"), "w") as fh: json.dump(stats, fh) 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) return stats def main(): ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("--out", required=True) ap.add_argument("--priors", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "priors.json")) 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)") ap.add_argument("--start-shard", type=int, default=0) ap.add_argument("--max-shards", type=int, default=N_SHARDS) ap.add_argument("--shard-dir", default="./shards", help="where parquet shards are cached/downloaded") ap.add_argument("--keep-shards", action="store_true", help="do not delete downloaded shards after processing") ap.add_argument("--workers", type=int, default=max(1, os.cpu_count() - 1)) ap.add_argument("--inject-frac", type=float, default=0.75, help="fraction of files that get any injection (rest are pure negatives)") ap.add_argument("--min-bytes", type=int, default=200) ap.add_argument("--max-bytes", type=int, default=200_000) ap.add_argument("--seed", type=int, default=1) ap.add_argument("--max-rows", type=int, default=0, help="debug: only consider the first N rows of each shard") g = ap.add_argument_group("clusters / coreference (v3)") g.add_argument("--cluster-cap", type=int, default=8, help="max files per cluster; bigger repos are split into near-equal chunks") g.add_argument("--singleton-frac", type=float, default=0.35, help="share of files outside multi-file repos that stay singletons (rest go into bundles)") g.add_argument("--p-reuse", type=float, default=0.7, help="P(a secret slot reuses an existing cluster entity not yet in the file; its label replaces the drawn one)") g.add_argument("--p-repeat", type=float, default=0.15, help="P(a secret slot repeats an entity already mentioned in the same file)") g.add_argument("--p-owner", type=float, default=0.5, help="P(a new secret is owned by a cluster person, when persons exist)") g.add_argument("--no-persons", action="store_true", help="v2-compatible label set: no person entities / person_name / username spans") g.add_argument("--no-bundles", action="store_true", help="no synthetic bundles (all loose files stay singletons)") g.add_argument("--no-repo-clusters", action="store_true", help="treat multi-file repos like loose files") a = ap.parse_args() os.makedirs(a.out, exist_ok=True) 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, max_rows=a.max_rows, cluster_cap=a.cluster_cap, singleton_frac=1.0 if a.no_bundles else a.singleton_frac, p_reuse=a.p_reuse, p_repeat=a.p_repeat, p_owner=a.p_owner, no_persons=a.no_persons, no_repo_clusters=a.no_repo_clusters) t0 = time.time(); total = 0; done = [] shard_iter = iter(range(a.start_shard, min(N_SHARDS, a.start_shard + a.max_shards))) with Pool(a.workers) as pool: pending = [] def launch(): i = next(shard_iter, None) if i is not None: pending.append(pool.apply_async(process_shard, ((i, cfg),))) for _ in range(a.workers): launch() while pending: r = pending.pop(0) st = r.get(); done.append(st); total += st["bytes"] if total < a.target_bytes: launch() dt = time.time() - t0 summary = {"shards": len(done), "files": sum(s["files"] for s in done), "bytes": total, "spans": sum(s["spans"] for s in done), "hard_negatives": sum(s["negs"] for s in done), "clusters": sum(s["clusters"] for s in done), "entities": sum(s["entities"] for s in done), "seconds": round(dt, 1), "MB_per_s": round(total / 1e6 / dt, 2), "workers": a.workers, "config": {k: cfg[k] for k in ("seed", "inject_frac", "cluster_cap", "singleton_frac", "p_reuse", "p_repeat", "p_owner", "no_persons")}} with open(os.path.join(a.out, "summary.json"), "w") as fh: json.dump(summary, fh, indent=1) print(json.dumps(summary, indent=1)) if __name__ == "__main__": main()