File size: 6,524 Bytes
bbfe90a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
#!/usr/bin/env python
"""Join the Ruby licence audit and keep permissive rows only."""
import gc
import hashlib
import json
import os
import random
import time
from collections import Counter
from pathlib import Path

import pyarrow as pa
import pyarrow.parquet as pq

HERE = Path(__file__).resolve().parent
SRC = HERE / "code_search_net_ruby.parquet"
TMP = HERE / "code_search_net_ruby.final.parquet"
AUDIT = HERE / "repo_licenses.jsonl"
BUILD = HERE / "code_search_net_ruby_permissive.build.json"
SAMPLE = HERE / "code_search_net_ruby_permissive.sample.jsonl"
SAMPLE_LIC = HERE / "sample_licenses.json"
SUMMARY = HERE / "license_summary.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(TMP, 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()

    for _ in range(8):
        try:
            os.replace(TMP, SRC)
            break
        except PermissionError:
            gc.collect()
            time.sleep(1)
    else:
        raise SystemExit("could not replace parquet (locked)")

    build = {
        "read": read, "kept": kept,
        "removed_unknown": drop_unknown,
        "removed_not_permissive": drop_copyleft,
        "source": "code-search-net/code_search_net (ruby)",
        "filter": "permissive only (license_class == permissive)",
        "chars": chars, "tokens": tokens, "repos": len(repos),
        "splits": dict(splits), "bytes": SRC.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,
    }
    BUILD.write_text(json.dumps(build, indent=2, ensure_ascii=False), encoding="utf-8")

    # 12-row sample
    pf2 = pq.ParquetFile(SRC)
    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",
        "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:", SRC.stat().st_size)
    print("sample:", [(r["repo"], r["license"]) for r in picked])


if __name__ == "__main__":
    main()