File size: 4,764 Bytes
9124411
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python
"""Drop rows whose repository has no detected open licence.

Keeps every detected SPDX licence (permissive, weak/strong copyleft, other
open licences such as MulanPSL/EUPL); removes NOASSERTION/unknown.
Rebuilds the 12-row sample and the stats/summary files.
"""
import gc
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_java.parquet"
TMP = HERE / "code_search_net_java.open.parquet"
BUILD = HERE / "code_search_net_java.build.json"
SAMPLE = HERE / "code_search_net_java.sample.jsonl"
SAMPLE_LIC = HERE / "sample_licenses.json"
SUMMARY = HERE / "license_summary.json"

DROP = {"unknown", "NOASSERTION", ""}


def main():
    pf = pq.ParquetFile(SRC)
    schema = pf.schema_arrow
    writer = pq.ParquetWriter(TMP, schema, compression="zstd")

    read = kept = removed = chars = tokens = 0
    repos, splits = set(), Counter()
    lic_dist, class_dist = Counter(), Counter()

    for batch in pf.iter_batches(batch_size=8192):
        out = []
        for r in batch.to_pylist():
            read += 1
            lic = r.get("license")
            if not lic or lic in DROP:
                removed += 1
                continue
            out.append(r)
            kept += 1
            chars += len(r["text"])
            tokens += r["token_count"]
            repos.add(r["repo"])
            splits[r["split"]] += 1
            lic_dist[lic] += 1
            class_dist[r["license_class"]] += 1
        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 attempt 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 = json.loads(BUILD.read_text(encoding="utf-8"))
    build.update({
        "rows": kept,
        "chars": chars,
        "tokens": tokens,
        "repos": len(repos),
        "splits": dict(splits),
        "bytes": SRC.stat().st_size,
        "unique_ids": kept,
        "filtered_out_unknown_rows": removed,
        "filtered_out_unknown_repos": build.get("license_class_repos", {}).get("unknown", 0),
        "license_distribution_rows": dict(lic_dist.most_common()),
        "license_class_rows": dict(class_dist.most_common()),
        "filter": "keep rows with a detected SPDX open licence; drop NOASSERTION/unknown",
    })
    BUILD.write_text(json.dumps(build, indent=2, ensure_ascii=False), encoding="utf-8")

    # rebuild the 12-row sample from the filtered parquet
    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 = json.loads(SUMMARY.read_text(encoding="utf-8")) if SUMMARY.exists() else {}
    summary.update({
        "filtered": True,
        "removed_rows": removed,
        "removed_repos": build["filtered_out_unknown_repos"],
        "rows": kept,
        "repos": len(repos),
        "rows_by_class": build["license_class_rows"],
        "rows_by_license": build["license_distribution_rows"],
        "splits": build["splits"],
    })
    SUMMARY.write_text(json.dumps(summary, indent=2, ensure_ascii=False), encoding="utf-8")

    print(f"read={read:,} kept={kept:,} removed={removed:,}")
    print("rows by class:", build["license_class_rows"])
    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()