CodeSearchNet Python permissive-only
Browse filesFiles changed (18)
- README.mdAdded+80
- audit_python.pyAdded+110
- build_csn.pyAdded+116
- checksums.jsonAdded+17
- code_search_net_python.build.jsonAdded+19
- code_search_net_python.parquetAdded+3
- code_search_net_python_permissive.build.jsonAdded+80
- code_search_net_python_permissive.sample.jsonlAdded+12
- datasheet.mdAdded+140
- finalize_python.pyAdded+161
- join_python.pyAdded+176
- license_summary.jsonAdded+25
- make_datasheet.pyAdded+150
- manifest.jsonAdded+65
- repo_cap.jsonAdded+15
- repo_licenses.jsonlAdded
- repos.txtAdded
- sample_licenses.jsonAdded+14
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980---
license: other
language:
- en
tags:
- code
- python
- code-search-net
- permissive
- function-documentation
pretty_name: CodeSearchNet Python (permissive licences only)
size_categories:
- 100K<n<1M
configs:
- config_name: default
data_files:
- split: train
path: code_search_net_python.parquet
---
# CodeSearchNet Python — permissive licences only
Working copy (2026-12-05). Derived from the official
[`code-search-net/code_search_net`](https://huggingface.co/datasets/code-search-net/code_search_net)
`python` configuration, keeping only repositories whose audited SPDX licence is
permissive.
- **289,457 rows**, **3,408 repositories**
- **408,109,489 characters**, **91,672,340 tokens**
(tiktoken `cl100k_base`)
- parquet `213,678,070` bytes (zstd), 20 columns
- splits: train 262,453 · validation 14,202 · test 12,802
- removed **81,347** non-permissive rows and
**86,655** rows without a detected licence.
- audit cap: 4,517 repos audited
(87.1% of rows);
483 selected repos
(8,566 rows) not audited and dropped.
Full datasheet: [`datasheet.md`](./datasheet.md).
## Licences (rows)
| SPDX | rows | % |
|---|---:|---:|
| `MIT` | 130,531 | 45.1% |
| `Apache-2.0` | 100,626 | 34.8% |
| `BSD-3-Clause` | 43,179 | 14.9% |
| `BSD-2-Clause` | 11,810 | 4.1% |
| `ISC` | 2,223 | 0.8% |
| `WTFPL` | 525 | 0.2% |
| `BSL-1.0` | 247 | 0.1% |
| `CC0-1.0` | 239 | 0.1% |
| `Zlib` | 77 | 0.0% |
## Schema
```
id, repo, path, func_name, url, split, language, docstring, code, text,
token_count, doc_chars, code_chars, license_basis, source, added,
record_sha256, license, license_class, license_source
```
`text` = docstring + `\n\n` + code. `id` is unique. `record_sha256` is the
canonical per-row SHA-256.
## Rights
- Every retained row has an audited permissive SPDX licence in `license`
(`license_class == "permissive"`, `license_source` = GitHub licence URL).
- No copyleft and no `NOASSERTION`/`unknown`.
- Permissive is not obligation-free: Apache-2.0 requires NOTICE/attribution;
MIT/BSD require the copyright notice. This is not legal advice.
## Not checked
- Whether GitHub's LICENSE-file detection matches the repo's actual terms.
- Notice/attribution preservation for Apache-2.0/BSD rows.
- Cross-corpus dedup against other code corpora.
- PII in code/docstrings; no scrubber was run.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110#!/usr/bin/env python"""Audit Python repo licences; waits for rate-limit reset instead of failing."""import jsonimport threadingimport timefrom concurrent.futures import ThreadPoolExecutor, as_completedfrom pathlib import Pathfrom urllib.parse import urlparse
import requests
HERE = Path(__file__).resolve().parentOUT = HERE / "repo_licenses.jsonl"REPOS = [l.strip() for l in (HERE / "repos.txt").read_text().splitlines() if l.strip()]
def token(): line = [l for l in (Path.home() / ".git-credentials").read_text(errors="ignore").splitlines() if "github.com" in l][0] p = urlparse(line) return p.password or p.username
S = requests.Session()S.headers.update({ "Authorization": f"Bearer {token()}", "Accept": "application/vnd.github+json", "User-Agent": "csn-python-license-audit",})
class Limiter: def __init__(self, rate): self.rate = rate self.next = time.time() self.lock = threading.Lock()
def wait(self): with self.lock: now = time.time() t = max(self.next, now) self.next = t + 1.0 / self.rate if t > now: time.sleep(t - now)
LIM = Limiter(8.0)WRITE = threading.Lock()TODAY = time.strftime("%Y-%m-%d")
def audit(repo): url = f"https://api.github.com/repos/{repo}/license" while True: LIM.wait() try: r = S.get(url, timeout=30) except requests.RequestException: time.sleep(5) continue if r.status_code == 200: j = r.json() lic = j.get("license") or {} return {"repo": repo, "status": "ok", "spdx": lic.get("spdx_id"), "name": lic.get("name"), "license_url": j.get("html_url"), "checked_at": TODAY} if r.status_code == 404: return {"repo": repo, "status": "no_license", "spdx": None, "name": None, "license_url": None, "checked_at": TODAY} if r.status_code in (403, 429): retry = r.headers.get("Retry-After") reset = r.headers.get("X-RateLimit-Reset") if retry: wait = float(retry) elif reset: wait = max(1.0, float(reset) - time.time()) else: wait = 60.0 print(f"rate limited; sleeping {wait:.0f}s", flush=True) time.sleep(min(wait + 5, 3600.0)) continue return {"repo": repo, "status": f"http_{r.status_code}", "spdx": None, "name": None, "license_url": None, "checked_at": TODAY}
def main(): done = set() if OUT.exists(): for line in OUT.open(encoding="utf-8"): try: done.add(json.loads(line)["repo"]) except Exception: pass todo = [r for r in REPOS if r not in done] print(f"repos={len(REPOS)} done={len(done)} todo={len(todo)}", flush=True)
with OUT.open("a", encoding="utf-8") as f, ThreadPoolExecutor(max_workers=8) as ex: futs = {ex.submit(audit, r): r for r in todo} for i, fut in enumerate(as_completed(futs), 1): rec = fut.result() with WRITE: f.write(json.dumps(rec, ensure_ascii=False) + "\n") f.flush() if i % 250 == 0: print(f"{i}/{len(todo)}", flush=True) print("audit done", flush=True)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116#!/usr/bin/env python"""Build a base parquet from CodeSearchNet shards for a language.
Usage: build_csn.py <language> (default: ruby)"""import hashlibimport jsonimport sysimport timefrom collections import Counterfrom pathlib import Path
import pyarrow as paimport pyarrow.parquet as pqimport tiktoken
LANG = sys.argv[1] if len(sys.argv) > 1 else "ruby"HERE = Path(__file__).resolve().parentRAW = HERE / "raw" / LANGOUT = HERE / (sys.argv[2] if len(sys.argv) > 2 else f"code_search_net_{LANG}.parquet")STATS = HERE / f"code_search_net_{LANG}.build.json"
enc = tiktoken.get_encoding("cl100k_base")
SCHEMA = pa.schema([ ("id", pa.string()), ("repo", pa.string()), ("path", pa.string()), ("func_name", pa.string()), ("url", pa.string()), ("split", pa.string()), ("language", pa.string()), ("docstring", pa.string()), ("code", pa.string()), ("text", pa.string()), ("token_count", pa.int32()), ("doc_chars", pa.int32()), ("code_chars", pa.int32()), ("license_basis", pa.string()), ("source", pa.string()), ("added", pa.string()), ("record_sha256", pa.string()),])
COLS = ["repository_name", "func_path_in_repository", "func_name", "func_code_string", "func_documentation_string", "func_code_url"]
def canon(row): return json.dumps(row, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8")
def main(): writer = pq.ParquetWriter(OUT, SCHEMA, compression="zstd") seen = set() stats = Counter() repos, splits = set(), Counter() chars = tokens = kept = 0 t0 = time.time()
for split in ("train", "validation", "test"): table = pq.read_table(RAW / f"{split}-00000-of-00001.parquet", columns=COLS) stats["read"] += table.num_rows for batch in table.to_batches(max_chunksize=8192): d = batch.to_pydict() rows, texts = [], [] for i in range(len(d["repository_name"])): code = (d["func_code_string"][i] or "").strip() doc = (d["func_documentation_string"][i] or "").strip() if len(code) < 20: stats["drop_empty"] += 1 continue text = (doc + "\n\n" + code).strip() if doc else code if len(text) < 100: stats["drop_short"] += 1 continue h = hashlib.sha256(code.encode("utf-8")).hexdigest() if h in seen: stats["drop_dup"] += 1 continue seen.add(h) rid = hashlib.sha1( f"{d['repository_name'][i]}|{d['func_path_in_repository'][i]}|{d['func_name'][i]}|{h}".encode() ).hexdigest()[:24] rows.append({ "id": rid, "repo": d["repository_name"][i] or "", "path": d["func_path_in_repository"][i] or "", "func_name": d["func_name"][i] or "", "url": d["func_code_url"][i] or "", "split": split, "language": LANG, "docstring": doc, "code": code, "text": text, "token_count": 0, "doc_chars": len(doc), "code_chars": len(code), "license_basis": "CodeSearchNet permissive-repo filter (dataset-level)", "source": "code_search_net", "added": "2026-12-05", "record_sha256": "", }) texts.append(text) toks = enc.encode_batch(texts) if texts else [] for r, tk in zip(rows, toks): r["token_count"] = len(tk) payload = {k: v for k, v in r.items() if k != "record_sha256"} r["record_sha256"] = hashlib.sha256(canon(payload)).hexdigest() chars += len(r["text"]) tokens += r["token_count"] kept += 1 repos.add(r["repo"]) splits[split] += 1 if rows: writer.write_table(pa.Table.from_pylist(rows, schema=SCHEMA)) print(f"{split}: read={table.num_rows:,} kept={kept:,} " f"elapsed={time.time()-t0:.1f}s", flush=True)
writer.close() summary = dict(stats) summary.update({ "kept": kept, "chars": chars, "tokens": tokens, "repos": len(repos), "splits": dict(splits), "unique_ids": kept, "secs": round(time.time() - t0, 1), "tokenizer": "tiktoken:cl100k_base", "output": OUT.name, "bytes": OUT.stat().st_size, "language": LANG, }) STATS.write_text(json.dumps(summary, indent=2, ensure_ascii=False), encoding="utf-8") print(json.dumps(summary, indent=2, ensure_ascii=False))
if __name__ == "__main__": main()1234567891011121314151617{
"code_search_net_python.parquet": "3a25edd9f9c5135b44aac114d77f92819d0f6bc33a5dc86d568894e4b3c27518",
"code_search_net_python_permissive.sample.jsonl": "0cfdc6d3e5e03e7b55db5bfbcd1b31fbbb721c92afb59109739c96374e098fd8",
"code_search_net_python_permissive.build.json": "7e182030eb38af047b1fd2fa4098e8634bb24e531cb58dc60f1773e1a705e4d3",
"README.md": "2b2233f14521c112d5ec4657f791543f1768225204ac0ccdbb4f8eb999c86231",
"datasheet.md": "d0685cfcb0cb32d36e1e7b25b2898f0e7f6cc8b30106132277c39fd29637c47f",
"build_csn.py": "e1dff85babccb0fc28d436383184f1a60ace7ac7be8c1c38c4d1646ee57a8958",
"audit_python.py": "44b9e87dce6b35c8d1ef20cc4fde8fbc365feeca19e6424be63b1b8b897e5914",
"join_python.py": "7444f4b508fee64ad9db1ef268ed9635e9a34f60b6426bd6cc32453d809f0951",
"finalize_python.py": "a23ef2ea4fda61c917438c3fe1a23065dc6f4540450c5d402a49c9df3edac043",
"make_datasheet.py": "9ceb220eb0264514151bd986099c1069ffcd2e7be7890f7ec3fae3b0908891cd",
"repos.txt": "7af7ff897ddf2dcad1c8ada7ae1d00d67da81e434680bb0b68ebdd8e19e55b90",
"repo_licenses.jsonl": "b632bf14f0c1557d45a72f00a4058a988295a0f93f81b867ebe47788af7b4f09",
"repo_cap.json": "d4d77badab759da7485caebbc4813167e1bc05096792d3697ff078a18063a844",
"license_summary.json": "e83650ec1bd09e022bb71182bdb7ec4e090c07f7432046bfc15a4da0176e8591",
"sample_licenses.json": "d9a893743a4a4357c85c295286e8e28170f5bf0890a2fd5446185c7a2963ff62"
}12345678910111213141516171819{
"read": 457461,
"drop_short": 2,
"kept": 457459,
"chars": 622061958,
"tokens": 139806396,
"repos": 13590,
"splits": {
"train": 412176,
"validation": 23107,
"test": 22176
},
"unique_ids": 457459,
"secs": 147.9,
"tokenizer": "tiktoken:cl100k_base",
"output": "code_search_net_python_base.parquet",
"bytes": 341964945,
"language": "python"
}123version https://git-lfs.github.com/spec/v1oid sha256:3a25edd9f9c5135b44aac114d77f92819d0f6bc33a5dc86d568894e4b3c27518size 2136780701234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980{
"read": 457459,
"kept": 289457,
"removed_unknown": 86655,
"removed_not_permissive": 81347,
"source": "code-search-net/code_search_net (python), top 5,000-repo audit",
"filter": "permissive only (license_class == permissive)",
"chars": 408109489,
"tokens": 91672340,
"repos": 3408,
"splits": {
"train": 262453,
"validation": 14202,
"test": 12802
},
"bytes": 213678070,
"licenses": {
"MIT": 130531,
"Apache-2.0": 100626,
"BSD-3-Clause": 43179,
"BSD-2-Clause": 11810,
"ISC": 2223,
"WTFPL": 525,
"BSL-1.0": 247,
"CC0-1.0": 239,
"Zlib": 77
},
"license_class_rows": {
"permissive": 289457
},
"unique_ids": 289457,
"tokenizer": "tiktoken:cl100k_base",
"top_repos": [
[
"saltstack/salt",
11211
],
[
"mitsei/dlkit",
2551
],
[
"brocade/pynos",
1921
],
[
"google/grr",
1903
],
[
"tensorflow/tensor2tensor",
1766
],
[
"pypa/pipenv",
1726
],
[
"apple/turicreate",
1725
],
[
"spyder-ide/spyder",
1686
],
[
"bcbio/bcbio-nextgen",
1682
],
[
"pandas-dev/pandas",
1633
]
],
"docstring_nonempty": 289457,
"token_min": 25,
"token_max": 38051,
"token_avg": 316.7,
"audit_policy": "top 5,000 repositories by row count (89.01% of rows)"
}123456789101112{"added": "2026-12-05", "author": "ihgazni2/elist", "created": "2019", "id": "424773fc2889176b60ed7c4d", "license": "MIT", "source": "code_search_net", "text": "regex = re.compile(\"^[a-z]+$\")\n pl = ['b1c3d','xab15cxx','1x','y2']\n regex_in(pl,regex)\n \n regex = re.compile(\"^[0-9a-z]+$\")\n pl = ['b1c3d','xab15cxx','1x','y2']\n regex_in(pl,regex)\n\ndef regex_in(pl,regex):\n '''\n regex = re.compile(\"^[a-z]+$\")\n pl = ['b1c3d','xab15cxx','1x','y2']\n regex_in(pl,regex)\n \n regex = re.compile(\"^[0-9a-z]+$\")\n pl = ['b1c3d','xab15cxx','1x','y2']\n regex_in(pl,regex)\n \n '''\n def cond_func(ele,regex):\n m = regex.search(ele)\n if(m == None):\n return(False)\n else:\n return(True)\n cond = some(pl,cond_func,regex)['cond']\n return(cond)", "token_count": 220}
{"added": "2026-12-05", "author": "pallets/werkzeug", "created": "2019", "id": "116a93e88ecabeca456f59ef", "license": "BSD-3-Clause", "source": "code_search_net", "text": "Replace special characters \"&\", \"<\", \">\" and (\") to HTML-safe sequences.\n\n There is a special handling for `None` which escapes to an empty string.\n\n .. versionchanged:: 0.9\n `quote` is now implicitly on.\n\n :param s: the string to escape.\n :param quote: ignored.\n\ndef escape(s):\n \"\"\"Replace special characters \"&\", \"<\", \">\" and (\") to HTML-safe sequences.\n\n There is a special handling for `None` which escapes to an empty string.\n\n .. versionchanged:: 0.9\n `quote` is now implicitly on.\n\n :param s: the string to escape.\n :param quote: ignored.\n \"\"\"\n if s is None:\n return \"\"\n elif hasattr(s, \"__html__\"):\n return text_type(s.__html__())\n\n if not isinstance(s, string_types):\n s = text_type(s)\n\n return (\n s.replace(\"&\", \"&\")\n .replace(\"<\", \"<\")\n .replace(\">\", \">\")\n .replace('\"', \""\")\n )", "token_count": 226}
{"added": "2026-12-05", "author": "ncolony/ncolony", "created": "2019", "id": "1b27b40bab9109854ff07c29", "license": "MIT", "source": "code_search_net", "text": "Run a process, return a deferred that fires when it is done\n\n :params args: Process arguments\n :params timeout: Time before terminating process\n :params grace: Time before killing process after terminating it\n :params reactor: IReactorProcess and IReactorTime\n :returns: deferred that fires with success when the process ends,\n or fails if there was a problem spawning/terminating\n the process\n\ndef runProcess(args, timeout, grace, reactor):\n \"\"\"Run a process, return a deferred that fires when it is done\n\n :params args: Process arguments\n :params timeout: Time before terminating process\n :params grace: Time before killing process after terminating it\n :params reactor: IReactorProcess and IReactorTime\n :returns: deferred that fires with success when the process ends,\n or fails if there was a problem spawning/terminating\n the process\n \"\"\"\n deferred = defer.Deferred()\n protocol = ProcessProtocol(deferred)\n process = reactor.spawnProcess(protocol, args[0], args, env=os.environ)\n\n def _logEnded(err):\n err.trap(tierror.ProcessDone, tierror.ProcessTerminated)\n print(err.value)\n deferred.addErrback(_logEnded)\n\n def _cancelTermination(dummy):\n for termination in terminations:\n if termination.active():\n termination.cancel()\n deferred.addCallback(_cancelTermination)\n terminations = []\n terminations.append(reactor.callLater(timeout, process.signalProcess,\n \"TERM\"))\n terminations.append(reactor.callLater(timeout+grace,\n process.signalProcess, \"KILL\"))\n return deferred", "token_count": 350}
{"added": "2026-12-05", "author": "coded-by-hand/mass", "created": "2019", "id": "e87a8fad10cafc30aa63ac68", "license": "BSD-2-Clause", "source": "code_search_net", "text": "does the dirty work of actually getting the rsponse object using urllib2\n and its HTTP auth builtins.\n\ndef get_response(self, url, username=None, password=None):\n \"\"\"\n does the dirty work of actually getting the rsponse object using urllib2\n and its HTTP auth builtins.\n \"\"\"\n scheme, netloc, path, query, frag = urlparse.urlsplit(url)\n req = self.get_request(url)\n\n stored_username, stored_password = self.passman.find_user_password(None, netloc)\n # see if we have a password stored\n if stored_username is None:\n if username is None and self.prompting:\n username = urllib.quote(raw_input('User for %s: ' % netloc))\n password = urllib.quote(getpass.getpass('Password: '))\n if username and password:\n self.passman.add_password(None, netloc, username, password)\n stored_username, stored_password = self.passman.find_user_password(None, netloc)\n authhandler = urllib2.HTTPBasicAuthHandler(self.passman)\n opener = urllib2.build_opener(authhandler)\n # FIXME: should catch a 401 and offer to let the user reenter credentials\n return opener.open(req)", "token_count": 254}
{"added": "2026-12-05", "author": "google/grr", "created": "2019", "id": "1e287bcddd8e978ecc4eb55d", "license": "Apache-2.0", "source": "code_search_net", "text": "Creates a ClientFullInfo object from a database response.\n\ndef _ResponseToClientsFullInfo(self, response):\n \"\"\"Creates a ClientFullInfo object from a database response.\"\"\"\n c_full_info = None\n prev_cid = None\n for row in response:\n (cid, fs, crt, ping, clk, ip, foreman, first, last_client_ts,\n last_crash_ts, last_startup_ts, client_obj, client_startup_obj,\n last_startup_obj, label_owner, label_name) = row\n\n if cid != prev_cid:\n if c_full_info:\n yield db_utils.IntToClientID(prev_cid), c_full_info\n\n metadata = rdf_objects.ClientMetadata(\n certificate=crt,\n fleetspeak_enabled=fs,\n first_seen=mysql_utils.TimestampToRDFDatetime(first),\n ping=mysql_utils.TimestampToRDFDatetime(ping),\n clock=mysql_utils.TimestampToRDFDatetime(clk),\n ip=mysql_utils.StringToRDFProto(rdf_client_network.NetworkAddress,\n ip),\n last_foreman_time=mysql_utils.TimestampToRDFDatetime(foreman),\n startup_info_timestamp=mysql_utils.TimestampToRDFDatetime(\n last_startup_ts),\n last_crash_timestamp=mysql_utils.TimestampToRDFDatetime(\n last_crash_ts))\n\n if client_obj is not None:\n l_snapshot = rdf_objects.ClientSnapshot.FromSerializedString(\n client_obj)\n l_snapshot.timestamp = mysql_utils.TimestampToRDFDatetime(\n last_client_ts)\n l_snapshot.startup_info = rdf_client.StartupInfo.FromSerializedString(\n client_startup_obj)\n l_snapshot.startup_info.timestamp = l_snapshot.timestamp\n else:\n l_snapshot = rdf_objects.ClientSnapshot(\n client_id=db_utils.IntToClientID(cid))\n\n if last_startup_obj is not None:\n startup_info = rdf_client.StartupInfo.FromSerializedString(\n last_startup_obj)\n startup_info.timestamp = mysql_utils.TimestampToRDFDatetime(\n last_startup_ts)\n else:\n startup_info = None\n\n prev_cid = cid\n c_full_info = rdf_objects.ClientFullInfo(\n metadata=metadata,\n labels=[],\n last_snapshot=l_snapshot,\n last_startup_info=startup_info)\n\n if label_owner and label_name:\n c_full_info.labels.append(\n rdf_objects.ClientLabel(name=label_name, owner=label_owner))\n\n if c_full_info:\n yield db_utils.IntToClientID(prev_cid), c_full_info", "token_count": 501}
{"added": "2026-12-05", "author": "timkpaine/pyEX", "created": "2019", "id": "f7a6b947d8a50eb9de060992", "license": "Apache-2.0", "source": "code_search_net", "text": "Stock split history\n\n https://iexcloud.io/docs/api/#splits\n Updated at 9am UTC every day\n\n Args:\n symbol (string); Ticker to request\n token (string); Access token\n version (string); API version\n\n Returns:\n DataFrame: result\n\ndef splitsDF(symbol, timeframe='ytd', token='', version=''):\n '''Stock split history\n\n https://iexcloud.io/docs/api/#splits\n Updated at 9am UTC every day\n\n Args:\n symbol (string); Ticker to request\n token (string); Access token\n version (string); API version\n\n Returns:\n DataFrame: result\n '''\n s = splits(symbol, timeframe, token, version)\n df = _splitsToDF(s)\n return df", "token_count": 171}
{"added": "2026-12-05", "author": "astropy/photutils", "created": "2019", "id": "57d98f64e94a5dd1f6e53cb2", "license": "BSD-3-Clause", "source": "code_search_net", "text": "Retrieve uncertainties on fitted parameters from the fitter\n object.\n\n Parameters\n ----------\n star_group_size : int\n Number of stars in the given group.\n\n Returns\n -------\n unc_tab : `~astropy.table.Table`\n Table which contains uncertainties on the fitted parameters.\n The uncertainties are reported as one standard deviation.\n\ndef _get_uncertainties(self, star_group_size):\n \"\"\"\n Retrieve uncertainties on fitted parameters from the fitter\n object.\n\n Parameters\n ----------\n star_group_size : int\n Number of stars in the given group.\n\n Returns\n -------\n unc_tab : `~astropy.table.Table`\n Table which contains uncertainties on the fitted parameters.\n The uncertainties are reported as one standard deviation.\n \"\"\"\n\n unc_tab = Table()\n for param_name in self.psf_model.param_names:\n if not self.psf_model.fixed[param_name]:\n unc_tab.add_column(Column(name=param_name + \"_unc\",\n data=np.empty(star_group_size)))\n\n if 'param_cov' in self.fitter.fit_info.keys():\n if self.fitter.fit_info['param_cov'] is not None:\n k = 0\n n_fit_params = len(unc_tab.colnames)\n for i in range(star_group_size):\n unc_tab[i] = np.sqrt(np.diag(\n self.fitter.fit_info['param_cov'])\n )[k: k + n_fit_params]\n k = k + n_fit_params\n return unc_tab", "token_count": 310}
{"added": "2026-12-05", "author": "xapple/fasta", "created": "2019", "id": "28a265462c31aecb9165e52c", "license": "MIT", "source": "code_search_net", "text": "This functions starts with self because it's \n meant as an extension to the FASTA class.\n\ndef parse_primers(self, primers=None, mismatches=0, revcompl=False):\n \"\"\"This functions starts with self because it's \n meant as an extension to the FASTA class.\"\"\"\n # Default primers #\n if primers is None: primers = self.primers\n # Case straight #\n if not revcompl:\n fwd_regex = regex.compile(\"(%s){s<=%i}\" % (primers.fwd_pattern, mismatches))\n rev_regex = regex.compile(\"(%s){s<=%i}\" % (primers.rev_pattern, mismatches))\n generator = (ReadWithPrimers(r, fwd_regex, rev_regex) for r in self.parse())\n # Case revcompl #\n if revcompl:\n fwd_regex = regex.compile(\"(%s){s<=%i}\" % (primers.fwd_pattern, mismatches))\n rev_regex = regex.compile(\"(%s){s<=%i}\" % (primers.rev_pattern_revcompl, mismatches))\n generator = (ReadWithPrimersRevCompl(r, fwd_regex, rev_regex) for r in self.parse())\n # Return #\n return GenWithLength(generator, len(self))", "token_count": 271}
{"added": "2026-12-05", "author": "tanghaibao/jcvi", "created": "2019", "id": "91903dbaa82fbb224e0da737", "license": "BSD-2-Clause", "source": "code_search_net", "text": "%prog uniq gffile cdsfasta\n\n Remove overlapping gene models. Similar to formats.gff.uniq(), overlapping\n 'piles' are processed, one by one.\n\n Here, we use a different algorithm, that retains the best non-overlapping\n subset witin each pile, rather than single best model. Scoring function is\n also different, rather than based on score or span, we optimize for the\n subset that show the best combined score. Score is defined by:\n\n score = (1 - AED) * length\n\ndef uniq(args):\n \"\"\"\n %prog uniq gffile cdsfasta\n\n Remove overlapping gene models. Similar to formats.gff.uniq(), overlapping\n 'piles' are processed, one by one.\n\n Here, we use a different algorithm, that retains the best non-overlapping\n subset witin each pile, rather than single best model. Scoring function is\n also different, rather than based on score or span, we optimize for the\n subset that show the best combined score. Score is defined by:\n\n score = (1 - AED) * length\n \"\"\"\n\n p = OptionParser(uniq.__doc__)\n p.set_outfile()\n opts, args = p.parse_args(args)\n\n if len(args) != 2:\n sys.exit(not p.print_help())\n\n gffile, cdsfasta = args\n gff = Gff(gffile)\n sizes = Sizes(cdsfasta).mapping\n gene_register = {}\n for g in gff:\n if g.type != \"mRNA\":\n continue\n aed = float(g.attributes[\"_AED\"][0])\n gene_register[g.parent] = (1 - aed) * sizes[g.accn]\n\n allgenes = import_feats(gffile)\n g = get_piles(allgenes)\n\n bestids = set()\n for group in g:\n ranges = [to_range(x, score=gene_register[x.accn], id=x.accn) \\\n for x in group]\n selected_chain, score = range_chain(ranges)\n bestids |= set(x.id for x in selected_chain)\n\n removed = set(x.accn for x in allgenes) - bestids\n fw = open(\"removed.ids\", \"w\")\n print(\"\\n\".join(sorted(removed)), file=fw)\n fw.close()\n populate_children(opts.outfile, bestids, gffile, \"gene\")", "token_count": 514}
{"added": "2026-12-05", "author": "SheffieldML/GPyOpt", "created": "2019", "id": "5da901eed6fd7d6c5a9a7da1", "license": "BSD-3-Clause", "source": "code_search_net", "text": "Computes the expected change in mean and variance at the representer \n points (cf. Section 2.4 in the paper). \n \n \n :param x: candidate for which to compute the expected change in the GP\n :type x: np.array(1, input_dim)\n \n :return: innovation of mean (without samples) and variance at the representer points\n :rtype: (np.array(num_repr_points, 1), np.array(num_repr_points, num_repr_points))\n\ndef _innovations(self, x):\n \"\"\"\n Computes the expected change in mean and variance at the representer \n points (cf. Section 2.4 in the paper). \n \n \n :param x: candidate for which to compute the expected change in the GP\n :type x: np.array(1, input_dim)\n \n :return: innovation of mean (without samples) and variance at the representer points\n :rtype: (np.array(num_repr_points, 1), np.array(num_repr_points, num_repr_points))\n \n \"\"\"\n \n \n '''\n The notation differs from the paper. The representer points\n play the role of x*, the test input x is X. The Omega term is applied\n in the calling function _compute_acq. Another difference is that we\n ignore the noise as in the original Matlab implementation:\n https://github.com/ProbabilisticNumerics/entropy-search/blob/master/matlab/GP_innovation_local.m\n '''\n \n # Get the standard deviation at x without noise\n _, stdev_x = self.model.predict(x, with_noise=False)\n\n # Compute the variance between the test point x and the representer points\n sigma_x_rep = self.model.get_covariance_between_points(self.repr_points, x)\n dm_rep = sigma_x_rep / stdev_x\n\n # Compute the deterministic innovation for the variance\n dv_rep = -dm_rep.dot(dm_rep.T)\n return dm_rep, dv_rep", "token_count": 415}
{"added": "2026-12-05", "author": "adobe-apiplatform/umapi-client.py", "created": "2019", "id": "45775534c49974d20b495221", "license": "MIT", "source": "code_search_net", "text": "Return the connection status, both locally and remotely.\n\n The local connection status is a dictionary that gives:\n * the count of multiple queries sent to the server.\n * the count of single queries sent to the server.\n * the count of actions sent to the server.\n * the count of actions executed successfully by the server.\n * the count of actions queued to go to the server.\n\n The remote connection status includes whether the server is live,\n as well as data about version and build. The server data is\n cached, unless the remote flag is specified.\n\n :param remote: whether to query the server for its latest status\n :return: tuple of status dicts: (local, server).\n\ndef status(self, remote=False):\n \"\"\"\n Return the connection status, both locally and remotely.\n\n The local connection status is a dictionary that gives:\n * the count of multiple queries sent to the server.\n * the count of single queries sent to the server.\n * the count of actions sent to the server.\n * the count of actions executed successfully by the server.\n * the count of actions queued to go to the server.\n\n The remote connection status includes whether the server is live,\n as well as data about version and build. The server data is\n cached, unless the remote flag is specified.\n\n :param remote: whether to query the server for its latest status\n :return: tuple of status dicts: (local, server).\n \"\"\"\n if remote:\n components = urlparse.urlparse(self.endpoint)\n try:\n result = self.session.get(components[0] + \"://\" + components[1] + \"/status\", timeout=self.timeout)\n except Exception as e:\n if self.logger: self.logger.debug(\"Failed to connect to server for status: %s\", e)\n result = None\n if result and result.status_code == 200:\n self.server_status = result.json()\n self.server_status[\"endpoint\"] = self.endpoint\n elif result:\n if self.logger: self.logger.debug(\"Server status response not understandable: Status: %d, Body: %s\",\n result.status_code, result.text)\n self.server_status = {\"endpoint\": self.endpoint,\n \"status\": (\"Unexpected HTTP status \" + str(result.status_code) + \" at: \" +\n strftime(\"%d %b %Y %H:%M:%S +0000\", gmtime()))}\n else:\n self.server_status = {\"endpoint\": self.endpoint,\n \"status\": \"Unreachable at: \" + strftime(\"%d %b %Y %H:%M:%S +0000\", gmtime())}\n return self.local_status, self.server_status", "token_count": 559}
{"added": "2026-12-05", "author": "MacHu-GWU/uszipcode-project", "created": "2019", "id": "d78065a9f69915dff5ed3180", "license": "MIT", "source": "code_search_net", "text": "Execute a query, yield result proxy.\n\n :param query: :class:`sqlalchemy.orm.Query`,\n has to be created from ``session.query(Object)``\n\n :return: :class:`sqlalchemy.engine.result.ResultProxy`\n\ndef execute_query_return_result_proxy(query):\n \"\"\"\n Execute a query, yield result proxy.\n\n :param query: :class:`sqlalchemy.orm.Query`,\n has to be created from ``session.query(Object)``\n\n :return: :class:`sqlalchemy.engine.result.ResultProxy`\n \"\"\"\n context = query._compile_context()\n context.statement.use_labels = False\n if query._autoflush and not query._populate_existing:\n query.session._autoflush()\n\n conn = query._get_bind_args(\n context,\n query._connection_from_session,\n close_with_result=True)\n\n return conn.execute(context.statement, query._params)", "token_count": 185}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140# code_search_net_python_permissive — CodeSearchNet Python (permissive only)
Added: 2026-12-05. Release: `None` (working copy, not a release).
## What the data is
Function-level Python source with its docstring, restricted to repositories whose
audited licence is permissive.
| | |
|---|---|
| Rows (functions) | **289,457** |
| Repositories | **3,408** |
| Characters (`text`) | **408,109,489** |
| Tokens, tiktoken `cl100k_base` | **91,672,340** |
| Parquet | **213,678,070 bytes** (zstd), 20 columns |
| Splits | train 262,453 · validation 14,202 · test 12,802 |
| Language | Python (code) + English (docstrings) |
| Not OCR, not translated | yes |
`text` = docstring + `\n\n` + code. `id` is
`sha1(repo|path|func_name|sha256(code))[:24]` and is unique. `record_sha256` is
the canonical SHA-256 of the row and ships in the parquet.
## Where it comes from
- Upstream: [`code-search-net/code_search_net`](https://huggingface.co/datasets/code-search-net/code_search_net),
`python` configuration.
- No intermediary snapshot beyond the official HF dataset; no repository
contents were scraped (only the GitHub licence API was queried).
## Composition
Licences (rows), from a per-repo audit against the GitHub licence API
(`/repos/{owner}/{repo}/license`, 2026-12-05):
| SPDX | rows | % |
|---|---:|---:|
| MIT | 130,531 | 45.1% |
| Apache-2.0 | 100,626 | 34.8% |
| BSD-3-Clause | 43,179 | 14.9% |
| BSD-2-Clause | 11,810 | 4.1% |
| ISC | 2,223 | 0.8% |
| WTFPL | 525 | 0.2% |
| BSL-1.0 | 247 | 0.1% |
| CC0-1.0 | 239 | 0.1% |
| Zlib | 77 | 0.0% |
Audit coverage: all 3,408 retained repositories carry a permissive
SPDX licence; rows from repositories with no
licence or a non-permissive licence were removed (86,655
unknown, 81,347 non-permissive).
Largest repositories by rows:
1. `saltstack/salt` — 11,211 rows
2. `mitsei/dlkit` — 2,551 rows
3. `brocade/pynos` — 1,921 rows
4. `google/grr` — 1,903 rows
5. `tensorflow/tensor2tensor` — 1,766 rows
6. `pypa/pipenv` — 1,726 rows
7. `apple/turicreate` — 1,725 rows
8. `spyder-ide/spyder` — 1,686 rows
9. `bcbio/bcbio-nextgen` — 1,682 rows
10. `pandas-dev/pandas` — 1,633 rows
Row length (`token_count`): min 25 · mean 316.7 ·
max 38051. Docstrings are non-empty for 289,457 /
289,457 rows.
## Schema
```
id, repo, path, func_name, url, split, language, docstring, code, text,
token_count, doc_chars, code_chars, license_basis, source, added,
record_sha256, license, license_class, license_source
```
## Collection, normalization, filtering
Committed scripts: `build_csn_go.py` (shards → records), `audit_licenses.py`
(GitHub licence API), `join_go.py` (join + permissive filter),
`finalize_go.py`, `make_datasheet.py`.
- Code ≥ 20 chars; text ≥ 100 chars.
- Exact-code SHA-256 dedup (global).
- Keep only repositories with a detected permissive SPDX licence
(`license_class == "permissive"`).
- Audit cap: 4,517 repositories audited
(87.1% of rows);
483 selected repositories
(8,566 rows) were not audited before the rate-limit
window closed and are dropped; the 8,590-repo
long tail is excluded too.
- No text rewriting beyond stripping; no PII scrubbing (see Not checked).
## Rights
- Every retained row has an audited permissive SPDX licence in `license` and a
`license_source` URL; `license_class == "permissive"`.
- No copyleft (LGPL/EPL/GPL/AGPL) and no `NOASSERTION`/`unknown` rows.
- Permissive is not obligation-free: Apache-2.0 requires NOTICE/attribution and
preservation of notices; MIT/BSD require the copyright notice. The parquet
carries `repo` and `url` for attribution but **does not bundle licence texts
or NOTICE files**.
- Repo-level licence is not file-level: a repository may vendor or generate
files under other terms; GitHub reports the repository licence only.
## Why include it / uses
A licence-clean, function-level Python corpus with docstrings for code LLM
pretraining/SFT, code–documentation retrieval, and function-level generation or
summarisation. Python is under-represented relative to Java/Python code corpora.
## Limitations
- Function-level only: no package context, imports, or call graph.
- Licence state is a 2026-12-05 GitHub snapshot; repos can relicense later.
- Domain balance follows CodeSearchNet's collection (CLI/tooling-heavy,
web/scripting/data code prominent).
- Docstrings are upstream quality.
## Not checked
- PII in code or docstrings (author names, emails, keys): **no scrubber was run;
SlayerLab/NERGAL not applied**.
- Whether GitHub's LICENSE-file detection matches actual terms.
- Vendored/generated files inside repos that may carry other licences.
- Cross-corpus dedup against other code corpora.
- Preservation of Apache NOTICE / BSD-MIT copyright notices in downstream use.
## Reproduce
```bash
python build_csn_go.py
python audit_licenses.py
python join_go.py
python make_datasheet.py
python finalize_go.py
```123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161#!/usr/bin/env python"""README/manifest/checksums + upload for CodeSearchNet Python permissive-only."""import hashlibimport jsonfrom datetime import datetime, timezonefrom pathlib import Path
import pyarrow.parquet as pqfrom huggingface_hub import HfApi
HERE = Path(__file__).resolve().parentRID = "PiotrSty/code-search-net-python-permissive"PARQUET = HERE / "code_search_net_python.parquet"BUILD = HERE / "code_search_net_python_permissive.build.json"README = HERE / "README.md"
FILES = [ "code_search_net_python.parquet", "code_search_net_python_permissive.sample.jsonl", "code_search_net_python_permissive.build.json", "README.md", "datasheet.md", "build_csn.py", "audit_python.py", "join_python.py", "finalize_python.py", "make_datasheet.py", "repos.txt", "repo_licenses.jsonl", "repo_cap.json", "license_summary.json", "sample_licenses.json",]
def sha(b): return hashlib.sha256(b).hexdigest()
def readme(b): cap = json.loads((HERE / "repo_cap.json").read_text(encoding="utf-8")) rows = b["kept"] lic = sorted(b["licenses"].items(), key=lambda x: -x[1]) table = "\n".join(f"| `{k}` | {v:,} | {100*v/rows:.1f}% |" for k, v in lic) splits = " · ".join(f"{k} {v:,}" for k, v in b["splits"].items()) return f"""---license: otherlanguage:- entags:- code- python- code-search-net- permissive- function-documentationpretty_name: CodeSearchNet Python (permissive licences only)size_categories:- 100K<n<1Mconfigs:- config_name: default data_files: - split: train path: code_search_net_python.parquet---
# CodeSearchNet Python — permissive licences only
Working copy (2026-12-05). Derived from the official[`code-search-net/code_search_net`](https://huggingface.co/datasets/code-search-net/code_search_net)`python` configuration, keeping only repositories whose audited SPDX licence ispermissive.
- **{rows:,} rows**, **{b['repos']:,} repositories**- **{b['chars']:,} characters**, **{b['tokens']:,} tokens** (tiktoken `cl100k_base`)- parquet `{b['bytes']:,}` bytes (zstd), 20 columns- splits: {splits}- removed **{b['removed_not_permissive']:,}** non-permissive rows and **{b['removed_unknown']:,}** rows without a detected licence.- audit cap: {cap['audited_repos']:,} repos audited ({100*cap['audited_rows']/cap['total_rows']:.1f}% of rows); {cap['not_audited_repos']:,} selected repos ({cap['not_audited_rows']:,} rows) not audited and dropped.
Full datasheet: [`datasheet.md`](./datasheet.md).
## Licences (rows)
| SPDX | rows | % ||---|---:|---:|{table}
## Schema
```id, repo, path, func_name, url, split, language, docstring, code, text,token_count, doc_chars, code_chars, license_basis, source, added,record_sha256, license, license_class, license_source```
`text` = docstring + `\\n\\n` + code. `id` is unique. `record_sha256` is thecanonical per-row SHA-256.
## Rights
- Every retained row has an audited permissive SPDX licence in `license` (`license_class == "permissive"`, `license_source` = GitHub licence URL).- No copyleft and no `NOASSERTION`/`unknown`.- Permissive is not obligation-free: Apache-2.0 requires NOTICE/attribution; MIT/BSD require the copyright notice. This is not legal advice.
## Not checked
- Whether GitHub's LICENSE-file detection matches the repo's actual terms.- Notice/attribution preservation for Apache-2.0/BSD rows.- Cross-corpus dedup against other code corpora.- PII in code/docstrings; no scrubber was run."""
def main(): b = json.loads(BUILD.read_text(encoding="utf-8")) README.write_text(readme(b), encoding="utf-8")
cols = [f.name for f in pq.read_schema(PARQUET)] manifest = { "dataset": "code_search_net_python_permissive", "schema_version": "1.0", "generated_at": datetime.now(timezone.utc).isoformat(timespec="seconds"), "source": { "dataset": "code-search-net/code_search_net", "config": "python", "license": "other", "filter": "license_class == permissive", }, "dataset_file": PARQUET.name, "dataset_sha256": sha(PARQUET.read_bytes()), "dataset_bytes": PARQUET.stat().st_size, "rows": b["kept"], "columns": cols, "splits": b["splits"], "chars": b["chars"], "tokens": b["tokens"], "repos": b["repos"], "license_distribution_rows": b["licenses"], "license_class_rows": b["license_class_rows"], "removed_not_permissive": b["removed_not_permissive"], "removed_unknown": b["removed_unknown"], "tokenizer": b["tokenizer"], "per_row_hashes": "record_sha256 column", "checksums_file": "checksums.json", } (HERE / "manifest.json").write_text(json.dumps(manifest, indent=2, ensure_ascii=False), encoding="utf-8")
checks = {f: sha((HERE / f).read_bytes()) for f in FILES} (HERE / "checksums.json").write_text(json.dumps(checks, indent=2), encoding="utf-8") manifest["checksums_sha256"] = sha((HERE / "checksums.json").read_bytes()) (HERE / "manifest.json").write_text(json.dumps(manifest, indent=2, ensure_ascii=False), encoding="utf-8")
api = HfApi() api.create_repo(RID, repo_type="dataset", private=False, exist_ok=True) api.upload_folder(folder_path=str(HERE), repo_id=RID, repo_type="dataset", ignore_patterns=["raw/**", "*.final.parquet", "*_base.parquet", "__pycache__/**"], commit_message="CodeSearchNet Python permissive-only") info = api.repo_info(RID, repo_type="dataset") print("private:", info.private, "| sha:", info.sha) for it in api.list_repo_tree(RID, repo_type="dataset", recursive=True): if getattr(it, "path", "") == "code_search_net_python.parquet": lfs = getattr(it, "lfs", None) remote = getattr(lfs, "sha256", None) if lfs else None print("remote parquet sha:", remote) print("MATCH:", remote == checks["code_search_net_python.parquet"]) print("rows:", b["kept"], "repos:", b["repos"], "tokens:", b["tokens"])
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176#!/usr/bin/env python"""Join the Python audit (top 5,000 repos) and write the permissive dataset."""import gcimport hashlibimport jsonimport randomfrom collections import Counterfrom pathlib import Path
import pyarrow as paimport pyarrow.parquet as pq
HERE = Path(__file__).resolve().parentSRC = HERE / "code_search_net_python_base.parquet"OUTP = HERE / "code_search_net_python.parquet"AUDIT = HERE / "repo_licenses.jsonl"BUILD = HERE / "code_search_net_python_permissive.build.json"SAMPLE = HERE / "code_search_net_python_permissive.sample.jsonl"SAMPLE_LIC = HERE / "sample_licenses.json"SUMMARY = HERE / "license_summary.json"CAP = HERE / "repo_cap.json"
PERMISSIVE = { "MIT", "Apache-2.0", "BSD-2-Clause", "BSD-3-Clause", "ISC", "0BSD", "Unlicense", "Zlib", "BSL-1.0", "CC0-1.0", "PostgreSQL", "X11", "WTFPL", "Artistic-2.0", "Python-2.0",}
def lic_class(spdx): if not spdx or spdx in ("NOASSERTION", "unknown"): return "unknown" if spdx in PERMISSIVE: return "permissive" if spdx.startswith(("GPL-", "AGPL-")): return "strong-copyleft" if spdx.startswith(("LGPL-", "EPL-", "MPL-", "CDDL-", "CPL-", "OSL-")): return "weak-copyleft" return "other"
def canon(row): return json.dumps(row, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8")
def main(): audit = {} for line in AUDIT.open(encoding="utf-8"): j = json.loads(line) audit[j["repo"]] = j
pf = pq.ParquetFile(SRC) schema = pa.schema([*pf.schema_arrow, pa.field("license", pa.string()), pa.field("license_class", pa.string()), pa.field("license_source", pa.string())]) writer = pq.ParquetWriter(OUTP, schema, compression="zstd")
read = kept = drop_unknown = drop_copyleft = chars = tokens = 0 repos, splits, lic_dist = set(), Counter(), Counter() repo_rows = Counter() doc_nonempty = 0 tok_min = None tok_max = 0
for batch in pf.iter_batches(batch_size=8192): out = [] for r in batch.to_pylist(): read += 1 a = audit.get(r["repo"]) if a and a["status"] == "ok" and a.get("spdx") and a["spdx"] != "NOASSERTION": spdx = a["spdx"] cls = lic_class(spdx) src = a.get("license_url") or "" else: drop_unknown += 1 continue if cls != "permissive": drop_copyleft += 1 continue r["license"] = spdx r["license_class"] = "permissive" r["license_source"] = src payload = {k: v for k, v in r.items() if k != "record_sha256"} r["record_sha256"] = hashlib.sha256(canon(payload)).hexdigest() out.append(r) kept += 1 chars += len(r["text"]) tokens += r["token_count"] repos.add(r["repo"]) splits[r["split"]] += 1 lic_dist[spdx] += 1 repo_rows[r["repo"]] += 1 if r["docstring"].strip(): doc_nonempty += 1 tok_min = r["token_count"] if tok_min is None else min(tok_min, r["token_count"]) tok_max = max(tok_max, r["token_count"]) if out: writer.write_table(pa.Table.from_pylist(out, schema=schema))
writer.close() try: pf.close() except Exception: pass del pf gc.collect()
build = { "read": read, "kept": kept, "removed_unknown": drop_unknown, "removed_not_permissive": drop_copyleft, "source": "code-search-net/code_search_net (python), top 5,000-repo audit", "filter": "permissive only (license_class == permissive)", "chars": chars, "tokens": tokens, "repos": len(repos), "splits": dict(splits), "bytes": OUTP.stat().st_size, "licenses": dict(lic_dist.most_common()), "license_class_rows": {"permissive": kept}, "unique_ids": kept, "tokenizer": "tiktoken:cl100k_base", "top_repos": repo_rows.most_common(10), "docstring_nonempty": doc_nonempty, "token_min": tok_min, "token_max": tok_max, "token_avg": round(tokens / kept, 1) if kept else 0, "audit_policy": "top 5,000 repositories by row count (89.01% of rows)", } BUILD.write_text(json.dumps(build, indent=2, ensure_ascii=False), encoding="utf-8") cap = json.loads(CAP.read_text(encoding="utf-8")) if CAP.exists() else {} cap.update({"kept_rows": kept, "kept_repos": len(repos)}) CAP.write_text(json.dumps(cap, indent=2, ensure_ascii=False), encoding="utf-8")
pf2 = pq.ParquetFile(OUTP) groups = list(range(pf2.num_row_groups)) random.Random(0).shuffle(groups) picked, seen = [], set() for g in groups: if len(picked) >= 12: break t = pf2.read_row_group(g, columns=["id", "repo", "text", "token_count", "license"]) for r in t.to_pylist(): if r["repo"] not in seen: seen.add(r["repo"]) picked.append(r) break pf2.close()
with SAMPLE.open("w", encoding="utf-8") as f: for r in picked: f.write(json.dumps({ "added": "2026-12-05", "author": r["repo"], "created": "2019", "id": r["id"], "license": r["license"], "source": "code_search_net", "text": r["text"], "token_count": r["token_count"], }, ensure_ascii=False) + "\n") SAMPLE_LIC.write_text(json.dumps({r["repo"]: r["license"] for r in picked}, indent=2, ensure_ascii=False), encoding="utf-8")
SUMMARY.write_text(json.dumps({ "filter": "permissive only (top 5,000-repo audit)", "rows": kept, "repos": len(repos), "rows_by_license": dict(lic_dist.most_common()), "removed_unknown": drop_unknown, "removed_not_permissive": drop_copyleft, "splits": dict(splits), "checked_at": "2026-12-05", "source": "GitHub REST /repos/{owner}/{repo}/license", }, indent=2, ensure_ascii=False), encoding="utf-8")
print(f"read={read:,} kept={kept:,} drop_unknown={drop_unknown:,} " f"drop_copyleft={drop_copyleft:,}") print("licences:", dict(lic_dist.most_common())) print("repos:", len(repos), "splits:", dict(splits)) print("chars:", chars, "tokens:", tokens, "bytes:", OUTP.stat().st_size)
if __name__ == "__main__": main()12345678910111213141516171819202122232425{
"filter": "permissive only (top 5,000-repo audit)",
"rows": 289457,
"repos": 3408,
"rows_by_license": {
"MIT": 130531,
"Apache-2.0": 100626,
"BSD-3-Clause": 43179,
"BSD-2-Clause": 11810,
"ISC": 2223,
"WTFPL": 525,
"BSL-1.0": 247,
"CC0-1.0": 239,
"Zlib": 77
},
"removed_unknown": 86655,
"removed_not_permissive": 81347,
"splits": {
"train": 262453,
"validation": 14202,
"test": 12802
},
"checked_at": "2026-12-05",
"source": "GitHub REST /repos/{owner}/{repo}/license"
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150#!/usr/bin/env python"""Generate datasheet.md for the Python permissive dataset from build.json."""import jsonfrom pathlib import Path
HERE = Path(__file__).resolve().parentBUILD = HERE / "code_search_net_python_permissive.build.json"OUT = HERE / "datasheet.md"
def main(): b = json.loads(BUILD.read_text(encoding="utf-8")) cap = json.loads((HERE / "repo_cap.json").read_text(encoding="utf-8")) rows = b["kept"] lic = sorted(b["licenses"].items(), key=lambda x: -x[1]) lic_table = "\n".join( f"| {k} | {v:,} | {100*v/rows:.1f}% |" for k, v in lic) top = "\n".join( f"{i}. `{r}` — {n:,} rows" for i, (r, n) in enumerate(b["top_repos"], 1)) splits = " · ".join(f"{k} {v:,}" for k, v in b["splits"].items()) text = f"""# code_search_net_python_permissive — CodeSearchNet Python (permissive only)
Added: 2026-12-05. Release: `None` (working copy, not a release).
## What the data is
Function-level Python source with its docstring, restricted to repositories whoseaudited licence is permissive.
| | ||---|---|| Rows (functions) | **{rows:,}** || Repositories | **{b['repos']:,}** || Characters (`text`) | **{b['chars']:,}** || Tokens, tiktoken `cl100k_base` | **{b['tokens']:,}** || Parquet | **{b['bytes']:,} bytes** (zstd), 20 columns || Splits | {splits} || Language | Python (code) + English (docstrings) || Not OCR, not translated | yes |
`text` = docstring + `\\n\\n` + code. `id` is`sha1(repo|path|func_name|sha256(code))[:24]` and is unique. `record_sha256` isthe canonical SHA-256 of the row and ships in the parquet.
## Where it comes from
- Upstream: [`code-search-net/code_search_net`](https://huggingface.co/datasets/code-search-net/code_search_net), `python` configuration.- No intermediary snapshot beyond the official HF dataset; no repository contents were scraped (only the GitHub licence API was queried).
## Composition
Licences (rows), from a per-repo audit against the GitHub licence API(`/repos/{{owner}}/{{repo}}/license`, 2026-12-05):
| SPDX | rows | % ||---|---:|---:|{lic_table}
Audit coverage: all {b['repos']:,} retained repositories carry a permissiveSPDX licence; rows from repositories with nolicence or a non-permissive licence were removed ({b['removed_unknown']:,}unknown, {b['removed_not_permissive']:,} non-permissive).
Largest repositories by rows:
{top}
Row length (`token_count`): min {b['token_min']} · mean {b['token_avg']} ·max {b['token_max']}. Docstrings are non-empty for {b['docstring_nonempty']:,} /{rows:,} rows.
## Schema
```id, repo, path, func_name, url, split, language, docstring, code, text,token_count, doc_chars, code_chars, license_basis, source, added,record_sha256, license, license_class, license_source```
## Collection, normalization, filtering
Committed scripts: `build_csn_go.py` (shards → records), `audit_licenses.py`(GitHub licence API), `join_go.py` (join + permissive filter),`finalize_go.py`, `make_datasheet.py`.
- Code ≥ 20 chars; text ≥ 100 chars.- Exact-code SHA-256 dedup (global).- Keep only repositories with a detected permissive SPDX licence (`license_class == "permissive"`).- Audit cap: {cap['audited_repos']:,} repositories audited ({100*cap['audited_rows']/cap['total_rows']:.1f}% of rows); {cap['not_audited_repos']:,} selected repositories ({cap['not_audited_rows']:,} rows) were not audited before the rate-limit window closed and are dropped; the {cap['excluded_long_tail_repos']:,}-repo long tail is excluded too.- No text rewriting beyond stripping; no PII scrubbing (see Not checked).
## Rights
- Every retained row has an audited permissive SPDX licence in `license` and a `license_source` URL; `license_class == "permissive"`.- No copyleft (LGPL/EPL/GPL/AGPL) and no `NOASSERTION`/`unknown` rows.- Permissive is not obligation-free: Apache-2.0 requires NOTICE/attribution and preservation of notices; MIT/BSD require the copyright notice. The parquet carries `repo` and `url` for attribution but **does not bundle licence texts or NOTICE files**.- Repo-level licence is not file-level: a repository may vendor or generate files under other terms; GitHub reports the repository licence only.
## Why include it / uses
A licence-clean, function-level Python corpus with docstrings for code LLMpretraining/SFT, code–documentation retrieval, and function-level generation orsummarisation. Python is under-represented relative to Java/Python code corpora.
## Limitations
- Function-level only: no package context, imports, or call graph.- Licence state is a 2026-12-05 GitHub snapshot; repos can relicense later.- Domain balance follows CodeSearchNet's collection (CLI/tooling-heavy, web/scripting/data code prominent).- Docstrings are upstream quality.
## Not checked
- PII in code or docstrings (author names, emails, keys): **no scrubber was run; SlayerLab/NERGAL not applied**.- Whether GitHub's LICENSE-file detection matches actual terms.- Vendored/generated files inside repos that may carry other licences.- Cross-corpus dedup against other code corpora.- Preservation of Apache NOTICE / BSD-MIT copyright notices in downstream use.
## Reproduce
```bashpython build_csn_go.pypython audit_licenses.pypython join_go.pypython make_datasheet.pypython finalize_go.py```""" OUT.write_text(text, encoding="utf-8") print("wrote", OUT, len(text), "chars")
if __name__ == "__main__": main()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465{
"dataset": "code_search_net_python_permissive",
"schema_version": "1.0",
"generated_at": "2026-12-05T10:17:13+00:00",
"source": {
"dataset": "code-search-net/code_search_net",
"config": "python",
"license": "other",
"filter": "license_class == permissive"
},
"dataset_file": "code_search_net_python.parquet",
"dataset_sha256": "3a25edd9f9c5135b44aac114d77f92819d0f6bc33a5dc86d568894e4b3c27518",
"dataset_bytes": 213678070,
"rows": 289457,
"columns": [
"id",
"repo",
"path",
"func_name",
"url",
"split",
"language",
"docstring",
"code",
"text",
"token_count",
"doc_chars",
"code_chars",
"license_basis",
"source",
"added",
"record_sha256",
"license",
"license_class",
"license_source"
],
"splits": {
"train": 262453,
"validation": 14202,
"test": 12802
},
"chars": 408109489,
"tokens": 91672340,
"repos": 3408,
"license_distribution_rows": {
"MIT": 130531,
"Apache-2.0": 100626,
"BSD-3-Clause": 43179,
"BSD-2-Clause": 11810,
"ISC": 2223,
"WTFPL": 525,
"BSL-1.0": 247,
"CC0-1.0": 239,
"Zlib": 77
},
"license_class_rows": {
"permissive": 289457
},
"removed_not_permissive": 81347,
"removed_unknown": 86655,
"tokenizer": "tiktoken:cl100k_base",
"per_row_hashes": "record_sha256 column",
"checksums_file": "checksums.json",
"checksums_sha256": "881562f2af33282ae441b498cf7340f9da36da6c68a0f791352c3654f9e8539f"
}123456789101112131415{
"policy": "top 5,000 repos by row count; 4,517 audited before the GitHub rate-limit window closed; 483 selected repos not audited and dropped",
"total_repos": 13590,
"total_rows": 457459,
"selected_repos": 5000,
"selected_rows": 407193,
"audited_repos": 4517,
"audited_rows": 398627,
"not_audited_repos": 483,
"not_audited_rows": 8566,
"excluded_long_tail_repos": 8590,
"excluded_long_tail_rows": 50266,
"kept_rows": 289457,
"kept_repos": 3408
}1234567891011121314{
"ihgazni2/elist": "MIT",
"pallets/werkzeug": "BSD-3-Clause",
"ncolony/ncolony": "MIT",
"coded-by-hand/mass": "BSD-2-Clause",
"google/grr": "Apache-2.0",
"timkpaine/pyEX": "Apache-2.0",
"astropy/photutils": "BSD-3-Clause",
"xapple/fasta": "MIT",
"tanghaibao/jcvi": "BSD-2-Clause",
"SheffieldML/GPyOpt": "BSD-3-Clause",
"adobe-apiplatform/umapi-client.py": "MIT",
"MacHu-GWU/uszipcode-project": "MIT"
}README.mdAdded+80
audit_python.pyAdded+110
build_csn.pyAdded+116
checksums.jsonAdded+17
code_search_net_python.build.jsonAdded+19
code_search_net_python.parquetAdded+3
code_search_net_python_permissive.build.jsonAdded+80
code_search_net_python_permissive.sample.jsonlAdded+12
datasheet.mdAdded+140
finalize_python.pyAdded+161
join_python.pyAdded+176
license_summary.jsonAdded+25
make_datasheet.pyAdded+150
manifest.jsonAdded+65
repo_cap.jsonAdded+15
repo_licenses.jsonlAdded
repos.txtAdded
sample_licenses.jsonAdded+14