niqun123123 commited on
Commit
d405b59
·
verified ·
1 Parent(s): a4131bd

Upload view_row_licenses.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. view_row_licenses.py +251 -0
view_row_licenses.py ADDED
@@ -0,0 +1,251 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """View per-row upstream dataset licenses for single-record-v1.
3
+
4
+ single-record-v1/train.jsonl is a projection of threemix-v1/train.jsonl with
5
+ origin metadata removed. Row order is 1:1 (row i == parent row i, verified by
6
+ lockstep payload comparison). Each parent row keeps `source.{dataset, config,
7
+ license, license_use}`, which we resolve against the upstream-license tables:
8
+
9
+ - tasksource rows: config -> tasksource_sources.tsv -> real HF dataset_id
10
+ - direct roots: dataset -> direct_source_roots.tsv -> dataset-level terms
11
+
12
+ license_use is a best-effort classification: commercial, non-commercial or
13
+ unspecified; it is not legal clearance. The per-row embedded value wins when
14
+ present; the dataset-level table is the fallback; conflicts are retained in
15
+ the audit columns, never silently reconciled.
16
+
17
+ Usage:
18
+ python3 view_row_licenses.py # full pass, all outputs
19
+ python3 view_row_licenses.py --row 123456 # one row's upstream evidence
20
+ python3 view_row_licenses.py --list-rows 100 # first N rows, table view
21
+ python3 view_row_licenses.py --filter commercial # count rows by license_use
22
+ """
23
+
24
+ import argparse
25
+ import csv
26
+ import json
27
+ import os
28
+ import sys
29
+ from collections import Counter, defaultdict
30
+
31
+ DATA_ROOT_DEFAULT = "/upfs_mnt/secbasemodel/dev_up/111649/experiments/jev/20261018-threemix-recipe-initbio4b-v1/data"
32
+ SOURCES_DIR_DEFAULT = os.path.join(
33
+ os.path.dirname(os.path.abspath(__file__)), "..",
34
+ "analysis-single-record-v1-upstream-licenses-20261103-v1")
35
+ TASKSOURCE_DATASET = "tasksource/tasksource-jev-typed-decisions"
36
+ VALID_USE = {"commercial", "non-commercial", "unspecified"}
37
+
38
+
39
+ def load_tables(sources_dir):
40
+ ts = {}
41
+ ts_path = os.path.join(sources_dir, "tasksource_sources.tsv")
42
+ with open(ts_path) as f:
43
+ for r in csv.DictReader(f, delimiter="\t"):
44
+ ts[r["config"]] = {
45
+ "dataset_id": r["dataset_id"],
46
+ "license": r["license"],
47
+ "license_use": r["license_use"].strip(),
48
+ "hf_url": r["hf_url"],
49
+ "table_rows": int(r["rows"]),
50
+ }
51
+ dr = {}
52
+ dr_path = os.path.join(sources_dir, "direct_source_roots.tsv")
53
+ with open(dr_path) as f:
54
+ for r in csv.DictReader(f, delimiter="\t"):
55
+ dr[r["root_name"]] = {
56
+ "license": r["license"],
57
+ "license_use": r["license_use"].strip(),
58
+ "url": r["canonical_url"],
59
+ "table_rows": int(r["rows"]),
60
+ }
61
+ return ts, dr
62
+
63
+
64
+ def norm_use(use):
65
+ use = (use or "").strip().lower()
66
+ return use if use in VALID_USE else "unspecified"
67
+
68
+
69
+ def resolve(source, ts, dr):
70
+ """Row source dict -> (upstream_id, config, license, license_use, url, notes)."""
71
+ dataset = source.get("dataset", "")
72
+ config = source.get("config") or ""
73
+ row_lic = source.get("license") or ""
74
+ row_use = norm_use(source.get("license_use"))
75
+
76
+ notes = []
77
+ if dataset == TASKSOURCE_DATASET:
78
+ t = ts.get(config)
79
+ if t is None:
80
+ notes.append("tasksource_config_not_in_table")
81
+ return dataset, config, row_lic, row_use, "", notes
82
+ upstream = t["dataset_id"]
83
+ lic = t["license"] or row_lic
84
+ table_use = norm_use(t["license_use"])
85
+ url = t["hf_url"]
86
+ else:
87
+ t = dr.get(dataset)
88
+ if t is None:
89
+ notes.append("direct_root_not_in_table")
90
+ return dataset, config, row_lic, row_use, "", notes
91
+ upstream = dataset
92
+ lic = t["license"] or row_lic
93
+ table_use = norm_use(t["license_use"])
94
+ url = t["url"]
95
+
96
+ use = row_use
97
+ if not (source.get("license_use") or "").strip():
98
+ # no embedded classification: fall back to dataset-level table
99
+ use = table_use
100
+ notes.append("license_use_from_table")
101
+ elif table_use not in (row_use, "") and table_use != row_use:
102
+ # embedded and table disagree: keep the (stricter) classification,
103
+ # retain the disagreement as explicit evidence
104
+ worse = sorted([row_use, table_use], key=["commercial", "unspecified",
105
+ "non-commercial"].index)[-1]
106
+ use = worse
107
+ notes.append(f"embedded={row_use},table={table_use},kept_stricter={worse}")
108
+ if row_lic and lic and row_lic.lower() != lic.lower():
109
+ notes.append(f"embedded_license={row_lic},table_license={lic}")
110
+ return upstream, config, lic, use, url, notes
111
+
112
+
113
+ def idl(f):
114
+ """Iterate (rowno, parsed) over a jsonl, 1-based."""
115
+ for i, line in enumerate(f, 1):
116
+ yield i, json.loads(line)
117
+
118
+
119
+ def main():
120
+ ap = argparse.ArgumentParser()
121
+ ap.add_argument("--data-root", default=DATA_ROOT_DEFAULT)
122
+ ap.add_argument("--sources-dir", default=SOURCES_DIR_DEFAULT)
123
+ ap.add_argument("--out-dir", default=None, help="default: this script's dir")
124
+ ap.add_argument("--row", type=int, default=None,
125
+ help="show upstream evidence for one 1-based row and exit")
126
+ ap.add_argument("--list-rows", type=int, default=None,
127
+ help="show a table of the first N rows and exit")
128
+ ap.add_argument("--filter", choices=sorted(VALID_USE), default=None,
129
+ help="full pass, print row counts per license_use")
130
+ args = ap.parse_args()
131
+
132
+ parent = os.path.join(args.data_root, "threemix-v1", "train.jsonl")
133
+ single = os.path.join(args.data_root, "single-record-v1", "train.jsonl")
134
+ out_dir = args.out_dir or os.path.dirname(os.path.abspath(__file__))
135
+ ts, dr = load_tables(args.sources_dir)
136
+
137
+ if args.row:
138
+ i, p = next(itertools_idl(parent, args.row))
139
+ s = read_single_row(single, args.row)
140
+ check_pair(i, p, s)
141
+ show_row(i, p, s, ts, dr)
142
+ return
143
+
144
+ if args.list_rows:
145
+ with open(parent) as fp, open(single) as fs:
146
+ print(f"{'row':>7} {'upstream':45.45} {'license_use':13} {'license':22.22} config")
147
+ for (i, p), (_, s) in zip(idl(fp), idl(fs)):
148
+ if i > args.list_rows:
149
+ break
150
+ check_pair(i, p, s)
151
+ up, cfg, lic, use, url, notes = resolve(p["source"], ts, dr)
152
+ print(f"{i:>7} {up:45.45} {use:13} {lic:22.22} {cfg}")
153
+ return
154
+
155
+ # full pass ------------------------------------------------------------
156
+ mismatches = 0
157
+ use_counter = Counter()
158
+ ds_counter = Counter() # upstream -> rows
159
+ ds_use = defaultdict(Counter) # upstream -> use -> rows
160
+ ds_license = {} # upstream -> license string(s)
161
+ noted = Counter()
162
+ cleaned_rows = 0
163
+ with open(parent) as fp, open(single) as fs, \
164
+ open(os.path.join(out_dir, "row_licenses.jsonl"), "w") as fout:
165
+ for (i, p), (_, s) in zip(idl(fp), idl(fs)):
166
+ mismatches += check_pair(i, p, s)
167
+ up, cfg, lic, use, url, notes = resolve(p["source"], ts, dr)
168
+ for n in notes:
169
+ noted[n] += 1
170
+ use_counter[use] += 1
171
+ ds_counter[up] += 1
172
+ ds_use[up][use] += 1
173
+ ds_license.setdefault(up, set()).add(lic)
174
+ fout.write(json.dumps({
175
+ "row": i, "id": s["id"],
176
+ "upstream_dataset": up, "config": cfg,
177
+ "license": lic, "license_use": use,
178
+ "url": url,
179
+ **({"notes": notes} if notes else {}),
180
+ }, ensure_ascii=False) + "\n")
181
+ cleaned_rows += 1
182
+
183
+ summary = {
184
+ "rows": cleaned_rows,
185
+ "payload_mismatches_vs_threemix": mismatches,
186
+ "rows_by_license_use": dict(use_counter),
187
+ "upstream_dataset_count": len(ds_counter),
188
+ "note_counts": dict(noted),
189
+ }
190
+ with open(os.path.join(out_dir, "summary.json"), "w") as f:
191
+ json.dump(summary, f, indent=2, ensure_ascii=False)
192
+
193
+ with open(os.path.join(out_dir, "upstream_aggregate.tsv"), "w", newline="") as f:
194
+ w = csv.writer(f, delimiter="\t", lineterminator="\n")
195
+ w.writerow(["upstream_dataset", "rows", "license", "license_use_rows",
196
+ "url"])
197
+ for up in sorted(ds_counter, key=lambda u: -ds_counter[u]):
198
+ use_mix = ", ".join(f"{k}:{v}" for k, v in sorted(ds_use[up].items()))
199
+ w.writerow([up, ds_counter[up], " | ".join(sorted(ds_license[up])),
200
+ use_mix,
201
+ next(iter(ds_license[up])) and ""])
202
+ print(json.dumps(summary, ensure_ascii=False, indent=2))
203
+
204
+ if args.filter:
205
+ print(f"\nfilter('{args.filter}') would keep "
206
+ f"{use_counter[args.filter]} of {cleaned_rows} rows")
207
+
208
+
209
+ def check_pair(i, p, s):
210
+ """Return 1 if parent row i and single row i disagree on payload, else 0."""
211
+ same = (p.get("state") == s.get("state")
212
+ and p.get("question") == s.get("question")
213
+ and p.get("target") == s.get("target")
214
+ and p.get("label") == s.get("label"))
215
+ if not same:
216
+ print(f"WARN: payload mismatch at parent/single row {i}", file=sys.stderr)
217
+ return 1
218
+ return 0
219
+
220
+
221
+ def show_row(i, p, s, ts, dr):
222
+ up, cfg, lic, use, url, notes = resolve(p["source"], ts, dr)
223
+ print(f"row {i} ({s['id']})")
224
+ print(f" upstream_dataset : {up}")
225
+ print(f" config : {cfg}")
226
+ print(f" license : {lic}")
227
+ print(f" license_use : {use}")
228
+ print(f" url : {url}")
229
+ if notes:
230
+ print(f" notes : {'; '.join(notes)}")
231
+ print(f" state[:120] : {str(s.get('state'))[:120]!r}")
232
+
233
+
234
+ def read_single_row(path, rowno):
235
+ with open(path) as f:
236
+ for i, line in enumerate(f, 1):
237
+ if i == rowno:
238
+ return json.loads(line)
239
+ raise SystemExit(f"row {rowno} out of range")
240
+
241
+
242
+ def itertools_idl(path, rowno):
243
+ with open(path) as f:
244
+ for i, line in enumerate(f, 1):
245
+ if i == rowno:
246
+ yield i, json.loads(line)
247
+ return
248
+
249
+
250
+ if __name__ == "__main__":
251
+ main()