podtech-okamura commited on
Commit
843ae96
·
verified ·
1 Parent(s): 7daad2b

pass5 stats script 9f697e6f

Browse files
Files changed (1) hide show
  1. code/pass5/9f697e6f/abeja_v5_stats.py +121 -0
code/pass5/9f697e6f/abeja_v5_stats.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """第5パス出力(outputs_v5)のジャンル・製造業適合・ホスト分布の集計。
2
+
3
+ 各シャードの ``pass5_sha1.parquet``(保持文書の本文 SHA-1)と第2パスの ``features.parquet`` を
4
+ SHA-1 で突き合わせ、ジャンル別件数、製造業・重工の適合(manufacturing_score >= しきい値)、
5
+ 文字数を数える。マスク置換された文書は SHA-1 が変わるため未突合として件数を残す。
6
+ """
7
+ from __future__ import annotations
8
+ import argparse, collections, json, os, time
9
+ from concurrent.futures import ProcessPoolExecutor
10
+ from pathlib import Path
11
+
12
+ BUCKETS = [0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 5.0, 10.0]
13
+ CHAR_BUCKETS = [500, 1000, 2000, 4000, 8000, 16000, 32000]
14
+ PPL_BUCKETS = [10000, 20000, 30000, 40000, 60000, 100000]
15
+ HOST_TOPN = 5000
16
+
17
+
18
+ def _bucket(value: float, edges: list) -> str:
19
+ return next((f"<{e}" for e in edges if value < e), f">={edges[-1]}")
20
+
21
+
22
+ def _suffix(host: str) -> str:
23
+ """ホストの種別(co.jp / ne.jp / com など)。日本の属性型 JP ドメインは 2 段で見る。"""
24
+ parts = (host or "").lower().rstrip(".").split(".")
25
+ if len(parts) < 2: return "unknown"
26
+ if parts[-1] == "jp" and len(parts) >= 3 and parts[-2] in {"co", "ne", "or", "ac", "go", "ed", "gr", "lg", "ad"}: return ".".join(parts[-2:])
27
+ return parts[-1]
28
+
29
+
30
+ def _fetch(repo: str, path: str, staging: str) -> str:
31
+ from huggingface_hub import hf_hub_download
32
+ for k in range(6):
33
+ try: return hf_hub_download(repo, path, repo_type="dataset", token=os.environ.get("HF_TOKEN"), local_dir=staging)
34
+ except Exception: # noqa: BLE001
35
+ if k == 5: raise
36
+ time.sleep(20 * (k + 1))
37
+ raise RuntimeError("unreachable")
38
+
39
+
40
+ def one(task: dict) -> dict:
41
+ import pyarrow.parquet as pq
42
+ t0 = time.perf_counter(); sh = task["shard"]; thr = task["threshold"]
43
+ try:
44
+ sha_f = _fetch(task["repo"], task["sha1_path"], task["staging"])
45
+ rows_v5 = 0; remaining: collections.Counter = collections.Counter()
46
+ pf = pq.ParquetFile(sha_f)
47
+ for b in pf.iter_batches(batch_size=65536, columns=["sha1"]):
48
+ vals = b.column("sha1").to_pylist(); rows_v5 += len(vals); remaining.update(v.hex() for v in vals)
49
+ Path(sha_f).unlink(missing_ok=True)
50
+ feat_f = _fetch(task["repo"], task["features_path"], task["staging"])
51
+ genre = collections.Counter(); manu = collections.Counter(); hist = collections.Counter()
52
+ chars = 0; chars_manu = 0; matched = 0; low_quality = 0
53
+ hosts = collections.Counter(); suffixes = collections.Counter(); char_hist = collections.Counter(); ppl_hist = collections.Counter()
54
+ cols = ["content_sha1", "genre", "manufacturing_score", "chars_final", "is_low_quality", "host", "perplexity"]
55
+ for b in pq.ParquetFile(feat_f).iter_batches(batch_size=65536, columns=cols):
56
+ d = b.to_pydict()
57
+ for i in range(b.num_rows):
58
+ key = d["content_sha1"][i]
59
+ if not key or remaining.get(key, 0) <= 0: continue
60
+ remaining[key] -= 1; matched += 1
61
+ g = d["genre"][i] or "unknown"; genre[g] += 1
62
+ c = d["chars_final"][i] or 0; chars += c
63
+ h = (d["host"][i] or "").lower(); hosts[h] += 1; suffixes[_suffix(h)] += 1
64
+ char_hist[_bucket(c, CHAR_BUCKETS)] += 1
65
+ pp = d["perplexity"][i]; ppl_hist["null" if pp is None else _bucket(pp, PPL_BUCKETS)] += 1
66
+ if d["is_low_quality"][i]: low_quality += 1
67
+ m = d["manufacturing_score"][i]
68
+ if m is None: hist["null"] += 1; continue
69
+ hist[next((f"<{b_}" for b_ in BUCKETS if m < b_), ">=10.0")] += 1
70
+ if m >= thr: manu[g] += 1; chars_manu += c
71
+ Path(feat_f).unlink(missing_ok=True)
72
+ return {"shard": sh, "hosts": dict(hosts.most_common(HOST_TOPN)), "suffixes": dict(suffixes),
73
+ "chars_hist": dict(char_hist), "perplexity_hist": dict(ppl_hist), "rows_v5": rows_v5, "matched": matched, "unmatched": rows_v5 - matched, "by_genre": dict(genre),
74
+ "manufacturing_by_genre": dict(manu), "manufacturing_score_hist": dict(hist), "chars": chars,
75
+ "chars_manufacturing": chars_manu, "low_quality": low_quality, "seconds": round(time.perf_counter() - t0, 1)}
76
+ except Exception as error: # noqa: BLE001
77
+ return {"shard": sh, "error": repr(error)}
78
+
79
+
80
+ def main() -> None:
81
+ p = argparse.ArgumentParser(); p.add_argument("--repo", required=True); p.add_argument("--dir", required=True)
82
+ p.add_argument("--v5-prefix", default="outputs_v5"); p.add_argument("--features-prefix", default="outputs_v2")
83
+ p.add_argument("--threshold", type=float, default=2.0); p.add_argument("--out", type=Path, default=Path("/work/out"))
84
+ p.add_argument("--staging", default="/work/staging"); p.add_argument("--limit-shards", type=int, default=None)
85
+ p.add_argument("--upload-repo", default=None); p.add_argument("--upload-prefix", default="reports/v5_stats")
86
+ p.add_argument("--workers", type=int, default=max(1, int(os.environ.get("CPU_CORES") or os.cpu_count() or 2) - 1))
87
+ a = p.parse_args()
88
+ from huggingface_hub import HfApi
89
+ api = HfApi(token=os.environ.get("HF_TOKEN"))
90
+ shards = sorted({e.path.split("/")[-1] for e in api.list_repo_tree(a.repo, path_in_repo=f"{a.v5_prefix}/{a.dir}", repo_type="dataset", recursive=False)})
91
+ if a.limit_shards: shards = shards[: a.limit_shards]
92
+ tasks = [{"repo": a.repo, "shard": sh, "staging": a.staging, "threshold": a.threshold,
93
+ "sha1_path": f"{a.v5_prefix}/{a.dir}/{sh}/pass5_sha1.parquet",
94
+ "features_path": f"{a.features_prefix}/{a.dir}/{sh}/features.parquet"} for sh in shards]
95
+ tot = collections.Counter(); genre = collections.Counter(); manu = collections.Counter(); hist = collections.Counter(); failed = []; shard_rows = {}
96
+ hosts = collections.Counter(); suffixes = collections.Counter(); char_hist = collections.Counter(); ppl_hist = collections.Counter()
97
+ with ProcessPoolExecutor(max_workers=a.workers) as ex:
98
+ for r in ex.map(one, tasks):
99
+ if "error" in r: failed.append(r["shard"]); print(json.dumps({"event": "error", **r}), flush=True); continue
100
+ for k in ("rows_v5", "matched", "unmatched", "chars", "chars_manufacturing", "low_quality"): tot[k] += r[k]
101
+ genre.update(r["by_genre"]); manu.update(r["manufacturing_by_genre"]); hist.update(r["manufacturing_score_hist"])
102
+ hosts.update(r["hosts"]); suffixes.update(r["suffixes"]); char_hist.update(r["chars_hist"]); ppl_hist.update(r["perplexity_hist"])
103
+ shard_rows[r["shard"]] = r["rows_v5"]; print(json.dumps({"event": "done", "shard": r["shard"], "rows_v5": r["rows_v5"], "seconds": r["seconds"]}), flush=True)
104
+ result = {"dir": a.dir, "shards": len(tasks), "failed": failed, "threshold": a.threshold, "totals": dict(tot),
105
+ "by_genre": dict(genre), "manufacturing_by_genre": dict(manu), "manufacturing_total": sum(manu.values()),
106
+ "manufacturing_score_hist": dict(hist), "suffixes": dict(suffixes), "chars_hist": dict(char_hist),
107
+ "perplexity_hist": dict(ppl_hist), "hosts_top": dict(hosts.most_common(3000)), "hosts_distinct_seen": len(hosts),
108
+ "shard_rows": shard_rows}
109
+ out = a.out / a.dir; out.mkdir(parents=True, exist_ok=True)
110
+ (out / "v5_stats.json").write_text(json.dumps(result, ensure_ascii=False, indent=1) + "\n", encoding="utf-8")
111
+ if a.upload_repo:
112
+ for k in range(6):
113
+ try: api.upload_folder(repo_id=a.upload_repo, repo_type="dataset", folder_path=str(out), path_in_repo=f"{a.upload_prefix}/{a.dir}", commit_message=f"v5 stats {a.dir}"); break
114
+ except Exception: # noqa: BLE001
115
+ if k == 5: raise
116
+ time.sleep(60 * (k + 1))
117
+ print(json.dumps({"event": "finish", "dir": a.dir, "totals": dict(tot), "manufacturing_total": sum(manu.values()), "failed": failed}, ensure_ascii=False), flush=True)
118
+
119
+
120
+ if __name__ == "__main__":
121
+ main()