File size: 5,148 Bytes
a64817d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 | #!/usr/bin/env python
"""Build a viewer-friendly Java dataset from CodeSearchNet Java.
Input : raw/java/{train,validation,test}-00000-of-00001.parquet
Output: code_search_net_java.parquet + code_search_net_java.build.json
Filters: non-empty code, text >= 100 chars, exact-code dedup (global).
Per-row record_sha256 is stored in the parquet (no giant JSON manifest).
"""
import hashlib
import json
import time
from collections import Counter
from pathlib import Path
import pyarrow as pa
import pyarrow.parquet as pq
import tiktoken
HERE = Path(__file__).resolve().parent
RAW = HERE / "raw" / "java"
OUT = HERE / "code_search_net_java.parquet"
STATS = HERE / "code_search_net_java.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"]
LICENSE_BASIS = "CodeSearchNet permissive-repo filter (dataset-level; per-row license absent)"
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 = set()
splits = Counter()
chars = tokens = kept = 0
t0 = time.time()
for split in ("train", "validation", "test"):
f = RAW / f"{split}-00000-of-00001.parquet"
table = pq.read_table(f, 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]}".encode()
).hexdigest()[:16]
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": "java",
"docstring": doc,
"code": code,
"text": text,
"token_count": 0,
"doc_chars": len(doc),
"code_chars": len(code),
"license_basis": LICENSE_BASIS,
"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),
"secs": round(time.time() - t0, 1),
"tokenizer": "tiktoken:cl100k_base",
"output": OUT.name,
"bytes": OUT.stat().st_size,
})
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()
|