File size: 4,751 Bytes
c032c6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python
"""Build a base parquet from CodeSearchNet shards for a language.

Usage: build_csn.py <language>   (default: ruby)
"""
import hashlib
import json
import sys
import time
from collections import Counter
from pathlib import Path

import pyarrow as pa
import pyarrow.parquet as pq
import tiktoken

LANG = sys.argv[1] if len(sys.argv) > 1 else "ruby"
HERE = Path(__file__).resolve().parent
RAW = HERE / "raw" / LANG
OUT = 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()