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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""abeja-cc-ja ハンドオフ版品質フィルター(abeja_cc_filter_handoff_20260909 の stage1〜stage8)を全シャードへ適用する。
|
| 2 |
+
|
| 3 |
+
判定は 3 値(keep / review / reject)。出力パーケットからは reject だけを除去し、keep と review は残す。
|
| 4 |
+
keep は 1.3% 程度しかない「高精度な学習候補」であり、コーパスフィルターではないため。
|
| 5 |
+
判定ロジックは配布物のスクリプトをそのまま import して使う(改変なし)。評価用の付随出力
|
| 6 |
+
(accepted/review/rejected/train_clean/blind_audit)は生成しない。
|
| 7 |
+
|
| 8 |
+
python tools/abeja_handoff.py --calibrate --files a.parquet --handoff-dir <配布物>
|
| 9 |
+
python tools/abeja_handoff.py --repo Podtech/abeja-cc-ja-cleaned --source-prefix outputs_v5 --dir common_crawl_0 \
|
| 10 |
+
--handoff-dir /work/handoff --output-root /work/out/common_crawl_0 --upload-repo ... --upload-prefix outputs_v6
|
| 11 |
+
# 原本(PII 未処理、data/<dir>/<shard>.parquet の平置き)に当てる場合
|
| 12 |
+
python tools/abeja_handoff.py --repo Podtech/abeja-cc-ja-filtered --source-prefix data --input-layout flat \
|
| 13 |
+
--redact-pii --dir common_crawl_0 --handoff-dir /work/handoff --output-root /work/out/common_crawl_0 \
|
| 14 |
+
--upload-repo Podtech/abeja-cc-ja-filtered --upload-prefix handoff
|
| 15 |
+
"""
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
import argparse
|
| 19 |
+
import collections
|
| 20 |
+
import importlib
|
| 21 |
+
import io
|
| 22 |
+
import json
|
| 23 |
+
import os
|
| 24 |
+
import shutil
|
| 25 |
+
import sys
|
| 26 |
+
import time
|
| 27 |
+
import traceback
|
| 28 |
+
from concurrent.futures import ProcessPoolExecutor
|
| 29 |
+
from contextlib import redirect_stdout
|
| 30 |
+
from datetime import datetime, timezone
|
| 31 |
+
from pathlib import Path
|
| 32 |
+
from typing import Any
|
| 33 |
+
|
| 34 |
+
VERSION = "abeja-handoff/2026-09-09"
|
| 35 |
+
STAGE_MODULES = (
|
| 36 |
+
"filter_podtech_quality",
|
| 37 |
+
"filter_podtech_stage2",
|
| 38 |
+
"filter_podtech_stage3",
|
| 39 |
+
"filter_podtech_stage4",
|
| 40 |
+
"filter_podtech_stage5",
|
| 41 |
+
"filter_podtech_stage6",
|
| 42 |
+
"filter_podtech_stage7",
|
| 43 |
+
"filter_podtech_stage8",
|
| 44 |
+
)
|
| 45 |
+
_MODS: dict[str, Any] = {}
|
| 46 |
+
_HANDOFF: dict[str, Path] = {}
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def _noop_int(*_args: Any, **_kwargs: Any) -> int:
|
| 50 |
+
"""write_full / write_train の差し替え。判定には影響しない付随出力を書かない。"""
|
| 51 |
+
return 0
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def _noop_counts(*_args: Any, **_kwargs: Any) -> dict[str, int]:
|
| 55 |
+
"""write_blind_audit の差し替え。評価用の層別標本は本番適用では使わない。"""
|
| 56 |
+
return {}
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def _load_stages(handoff_dir: Path) -> None:
|
| 60 |
+
"""配布物の scripts/ を import し、付随出力の書き出しだけを無効化する。"""
|
| 61 |
+
if _MODS:
|
| 62 |
+
return
|
| 63 |
+
scripts = handoff_dir / "scripts"
|
| 64 |
+
if not (scripts / "filter_podtech_stage8.py").exists():
|
| 65 |
+
raise FileNotFoundError(f"handoff scripts not found under {scripts}")
|
| 66 |
+
sys.path.insert(0, str(scripts))
|
| 67 |
+
for name in STAGE_MODULES:
|
| 68 |
+
_MODS[name] = importlib.import_module(name)
|
| 69 |
+
# 各モジュール名前空間の束縛を個別に差し替える(stage5 以降は stage4 から import しているため)
|
| 70 |
+
for mod in _MODS.values():
|
| 71 |
+
for attr, replacement in (
|
| 72 |
+
("write_full", _noop_int),
|
| 73 |
+
("write_train", _noop_int),
|
| 74 |
+
("write_blind_audit", _noop_counts),
|
| 75 |
+
):
|
| 76 |
+
if hasattr(mod, attr):
|
| 77 |
+
setattr(mod, attr, replacement)
|
| 78 |
+
_HANDOFF["dir"] = handoff_dir
|
| 79 |
+
_HANDOFF["v1"] = handoff_dir / "models" / "v1_multiclass" / "quality_char_ngram_model.joblib"
|
| 80 |
+
_HANDOFF["v2"] = handoff_dir / "models" / "v2_binary" / "quality_binary_model.joblib"
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def _run_stage(name: str, argv: list[str]) -> dict:
|
| 84 |
+
"""配布物の main() を argv 付きで呼び、書き出された summary.json を返す。"""
|
| 85 |
+
mod = _MODS[name]
|
| 86 |
+
saved = sys.argv
|
| 87 |
+
sys.argv = [name] + argv
|
| 88 |
+
try:
|
| 89 |
+
with redirect_stdout(io.StringIO()):
|
| 90 |
+
mod.main()
|
| 91 |
+
finally:
|
| 92 |
+
sys.argv = saved
|
| 93 |
+
out_dir = Path(argv[argv.index("--output-dir") + 1])
|
| 94 |
+
return json.loads((out_dir / "summary.json").read_text(encoding="utf-8"))
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def score_model(input_path: Path, model_path: Path, kind: str, output: Path, batch_size: int = 2000) -> None:
|
| 98 |
+
"""配布物の学習済みモデルで全件採点する(学習はしない)。列は配布物の ml_scores.parquet と同一。"""
|
| 99 |
+
import duckdb
|
| 100 |
+
import joblib
|
| 101 |
+
import numpy as np
|
| 102 |
+
import pyarrow as pa
|
| 103 |
+
import pyarrow.parquet as pq
|
| 104 |
+
|
| 105 |
+
limit = 6000 if kind == "v1" else 8000
|
| 106 |
+
model = joblib.load(model_path)
|
| 107 |
+
con = duckdb.connect()
|
| 108 |
+
sql = str(input_path.resolve()).replace("'", "''")
|
| 109 |
+
cursor = con.execute(f"SELECT row_number() OVER () - 1 AS row_id, url, content FROM read_parquet('{sql}')")
|
| 110 |
+
if kind == "v1":
|
| 111 |
+
schema = pa.schema([("row_id", pa.int64()), ("ml_prediction", pa.string()),
|
| 112 |
+
("prob_A", pa.float64()), ("prob_B", pa.float64()), ("prob_C", pa.float64())])
|
| 113 |
+
else:
|
| 114 |
+
schema = pa.schema([("row_id", pa.int64()), ("ml_v2_prediction", pa.string()),
|
| 115 |
+
("prob_non_C", pa.float64()), ("prob_C", pa.float64())])
|
| 116 |
+
writer = pq.ParquetWriter(output, schema, compression="zstd")
|
| 117 |
+
try:
|
| 118 |
+
while True:
|
| 119 |
+
rows = cursor.fetchmany(batch_size)
|
| 120 |
+
if not rows:
|
| 121 |
+
break
|
| 122 |
+
texts = [f"URL {u or ''}\n本文 {(c or '')[:limit]}" for _, u, c in rows]
|
| 123 |
+
probs = model.predict_proba(texts)
|
| 124 |
+
out: list[dict] = []
|
| 125 |
+
if kind == "v1":
|
| 126 |
+
classes = model.classes_
|
| 127 |
+
predictions = classes[np.argmax(probs, axis=1)]
|
| 128 |
+
for (row_id, _, _), prediction, probability in zip(rows, predictions, probs):
|
| 129 |
+
by_class = dict(zip(classes, probability))
|
| 130 |
+
out.append({"row_id": row_id, "ml_prediction": str(prediction),
|
| 131 |
+
"prob_A": float(by_class["A"]), "prob_B": float(by_class["B"]),
|
| 132 |
+
"prob_C": float(by_class["C"])})
|
| 133 |
+
else:
|
| 134 |
+
for (row_id, _, _), probability in zip(rows, probs[:, 1]):
|
| 135 |
+
out.append({"row_id": row_id, "ml_v2_prediction": "C" if probability >= 0.5 else "non_C",
|
| 136 |
+
"prob_non_C": float(1 - probability), "prob_C": float(probability)})
|
| 137 |
+
writer.write_table(pa.Table.from_pylist(out, schema=schema))
|
| 138 |
+
finally:
|
| 139 |
+
writer.close()
|
| 140 |
+
del model
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def run_chain(input_path: Path, work: Path) -> tuple[Path, dict[str, dict]]:
|
| 144 |
+
"""stage1〜stage8 を順に実行し、(stage8_audit.parquet, 段階別 summary) を返す。"""
|
| 145 |
+
work.mkdir(parents=True, exist_ok=True)
|
| 146 |
+
stages: dict[str, dict] = {}
|
| 147 |
+
inp = str(input_path)
|
| 148 |
+
|
| 149 |
+
stages["stage1"] = _run_stage("filter_podtech_quality", ["--input", inp, "--output-dir", str(work / "s1")])
|
| 150 |
+
for name in ("kept.parquet", "review.parquet", "rejected.parquet"):
|
| 151 |
+
(work / "s1" / name).unlink(missing_ok=True)
|
| 152 |
+
|
| 153 |
+
score_model(input_path, _HANDOFF["v1"], "v1", work / "ml1.parquet")
|
| 154 |
+
stages["stage2"] = _run_stage("filter_podtech_stage2", [
|
| 155 |
+
"--input", inp, "--stage1-audit", str(work / "s1" / "quality_audit.parquet"),
|
| 156 |
+
"--ml-scores", str(work / "ml1.parquet"), "--output-dir", str(work / "s2")])
|
| 157 |
+
|
| 158 |
+
score_model(input_path, _HANDOFF["v2"], "v2", work / "ml2.parquet")
|
| 159 |
+
stages["stage3"] = _run_stage("filter_podtech_stage3", [
|
| 160 |
+
"--input", inp, "--stage2-audit", str(work / "s2" / "stage2_audit.parquet"),
|
| 161 |
+
"--ml-v2-scores", str(work / "ml2.parquet"), "--output-dir", str(work / "s3")])
|
| 162 |
+
stages["stage4"] = _run_stage("filter_podtech_stage4", [
|
| 163 |
+
"--input", inp, "--stage2-audit", str(work / "s2" / "stage2_audit.parquet"),
|
| 164 |
+
"--stage3-audit", str(work / "s3" / "stage3_audit.parquet"), "--output-dir", str(work / "s4")])
|
| 165 |
+
stages["stage5"] = _run_stage("filter_podtech_stage5", [
|
| 166 |
+
"--input", inp, "--stage2-audit", str(work / "s2" / "stage2_audit.parquet"),
|
| 167 |
+
"--stage4-audit", str(work / "s4" / "stage4_audit.parquet"), "--output-dir", str(work / "s5")])
|
| 168 |
+
stages["stage6"] = _run_stage("filter_podtech_stage6", [
|
| 169 |
+
"--input", inp, "--stage5-audit", str(work / "s5" / "stage5_audit.parquet"), "--output-dir", str(work / "s6")])
|
| 170 |
+
stages["stage7"] = _run_stage("filter_podtech_stage7", [
|
| 171 |
+
"--input", inp, "--stage6-audit", str(work / "s6" / "stage6_audit.parquet"), "--output-dir", str(work / "s7")])
|
| 172 |
+
stages["stage8"] = _run_stage("filter_podtech_stage8", [
|
| 173 |
+
"--input", inp, "--stage7-audit", str(work / "s7" / "stage7_audit.parquet"), "--output-dir", str(work / "s8")])
|
| 174 |
+
return work / "s8" / "stage8_audit.parquet", stages
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def _fetch(repo: str, path_in_repo: str, local_dir: Path, attempts: int = 6) -> Path:
|
| 178 |
+
from huggingface_hub import hf_hub_download
|
| 179 |
+
for k in range(attempts):
|
| 180 |
+
try:
|
| 181 |
+
return Path(hf_hub_download(repo, path_in_repo, repo_type="dataset",
|
| 182 |
+
token=os.environ.get("HF_TOKEN"), local_dir=str(local_dir)))
|
| 183 |
+
except Exception: # noqa: BLE001
|
| 184 |
+
if k == attempts - 1:
|
| 185 |
+
raise
|
| 186 |
+
time.sleep(20 * (k + 1))
|
| 187 |
+
raise RuntimeError("unreachable")
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def process_shard(task: dict) -> dict:
|
| 191 |
+
import pyarrow as pa
|
| 192 |
+
import pyarrow.parquet as pq
|
| 193 |
+
|
| 194 |
+
started = time.perf_counter()
|
| 195 |
+
shard = task["shard"]
|
| 196 |
+
work = Path(task["staging_dir"]) / f"{shard}_work"
|
| 197 |
+
local: Path | None = None
|
| 198 |
+
try:
|
| 199 |
+
_load_stages(Path(task["handoff_dir"]))
|
| 200 |
+
local = _fetch(task["repo"], task["path"], Path(task["staging_dir"])) if task.get("repo") else Path(task["path"])
|
| 201 |
+
out_dir = Path(task["output_root"]) / shard
|
| 202 |
+
out_dir.mkdir(parents=True, exist_ok=True)
|
| 203 |
+
shutil.rmtree(work, ignore_errors=True)
|
| 204 |
+
audit_path, stages = run_chain(local, work)
|
| 205 |
+
|
| 206 |
+
audit = pq.read_table(audit_path, columns=["row_id", "decision", "reasons", "source_class", "prob_C"])
|
| 207 |
+
decision = dict(zip(audit.column("row_id").to_pylist(), audit.column("decision").to_pylist()))
|
| 208 |
+
reasons = dict(zip(audit.column("row_id").to_pylist(), audit.column("reasons").to_pylist()))
|
| 209 |
+
source = dict(zip(audit.column("row_id").to_pylist(), audit.column("source_class").to_pylist()))
|
| 210 |
+
pq.write_table(audit, out_dir / "handoff_decisions.parquet", compression="zstd")
|
| 211 |
+
|
| 212 |
+
redact = _MODS["filter_podtech_stage2"].redact_direct_pii if task.get("redact_pii") else None
|
| 213 |
+
pf = pq.ParquetFile(local)
|
| 214 |
+
codec = pf.metadata.row_group(0).column(0).compression if pf.metadata.num_row_groups else "SNAPPY"
|
| 215 |
+
writer = pq.ParquetWriter(out_dir / f"{shard}.parquet", pf.schema_arrow,
|
| 216 |
+
compression=codec.lower() if codec != "UNCOMPRESSED" else None)
|
| 217 |
+
removed_f = (out_dir / "handoff_removed.jsonl").open("w", encoding="utf-8")
|
| 218 |
+
counts: collections.Counter[str] = collections.Counter()
|
| 219 |
+
reject_reasons: collections.Counter[str] = collections.Counter()
|
| 220 |
+
rows_in = 0
|
| 221 |
+
written = 0
|
| 222 |
+
pii_replacements = 0
|
| 223 |
+
pii_docs = 0
|
| 224 |
+
try:
|
| 225 |
+
for batch in pf.iter_batches(batch_size=2048):
|
| 226 |
+
d = batch.to_pydict()
|
| 227 |
+
n = batch.num_rows
|
| 228 |
+
keep_idx = []
|
| 229 |
+
new_content = list(d["content"])
|
| 230 |
+
for i in range(n):
|
| 231 |
+
row = rows_in + i
|
| 232 |
+
verdict = decision.get(row)
|
| 233 |
+
if verdict is None:
|
| 234 |
+
raise ValueError(f"row_id {row} missing from stage8 audit")
|
| 235 |
+
counts[verdict] += 1
|
| 236 |
+
if verdict == "reject":
|
| 237 |
+
reject_reasons[reasons.get(row) or ""] += 1
|
| 238 |
+
removed_f.write(json.dumps({
|
| 239 |
+
"row_index": row, "decision": verdict, "reasons": reasons.get(row),
|
| 240 |
+
"source_class": source.get(row), "url": d["url"][i], "content": d["content"][i],
|
| 241 |
+
"perplexity": d.get("perplexity", [None] * n)[i],
|
| 242 |
+
}, ensure_ascii=False, default=str) + "\n")
|
| 243 |
+
else:
|
| 244 |
+
if redact is not None and new_content[i]:
|
| 245 |
+
new_content[i], replaced = redact(new_content[i])
|
| 246 |
+
if replaced:
|
| 247 |
+
pii_replacements += replaced
|
| 248 |
+
pii_docs += 1
|
| 249 |
+
keep_idx.append(i)
|
| 250 |
+
if keep_idx:
|
| 251 |
+
cols = {}
|
| 252 |
+
for name in pf.schema_arrow.names:
|
| 253 |
+
values = new_content if name == "content" else d[name]
|
| 254 |
+
cols[name] = pa.array([values[i] for i in keep_idx], type=pf.schema_arrow.field(name).type)
|
| 255 |
+
kept = pa.record_batch(cols, schema=pf.schema_arrow)
|
| 256 |
+
writer.write_batch(kept)
|
| 257 |
+
written += kept.num_rows
|
| 258 |
+
rows_in += n
|
| 259 |
+
finally:
|
| 260 |
+
writer.close()
|
| 261 |
+
removed_f.close()
|
| 262 |
+
check = pq.ParquetFile(out_dir / f"{shard}.parquet")
|
| 263 |
+
assert check.metadata.num_rows == written == rows_in - counts["reject"], "row count mismatch"
|
| 264 |
+
|
| 265 |
+
summary = {
|
| 266 |
+
"version": VERSION, "dir": task["config"], "shard": shard,
|
| 267 |
+
"source_prefix": task["source_prefix"],
|
| 268 |
+
"rows_in": rows_in, "rows_removed": counts["reject"], "rows_out": written,
|
| 269 |
+
"decisions": {k: counts[k] for k in ("keep", "review", "reject", "duplicate")},
|
| 270 |
+
"reject_reasons": dict(reject_reasons.most_common()),
|
| 271 |
+
"stage_decisions": {name: s.get("decisions", {}) for name, s in stages.items()},
|
| 272 |
+
"pii_redaction": {"applied": bool(redact), "detector": "handoff redact_direct_pii (email/phone/postcode)",
|
| 273 |
+
"documents": pii_docs, "replacements": pii_replacements},
|
| 274 |
+
"policy": {"removed": "reject", "kept": "keep+review", "content_rewritten": bool(redact)},
|
| 275 |
+
"compression": codec, "seconds": round(time.perf_counter() - started, 1),
|
| 276 |
+
"finished_at_utc": datetime.now(timezone.utc).isoformat(),
|
| 277 |
+
}
|
| 278 |
+
(out_dir / "handoff_summary.json").write_text(
|
| 279 |
+
json.dumps(summary, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
| 280 |
+
return summary
|
| 281 |
+
except Exception as error: # noqa: BLE001
|
| 282 |
+
return {"shard": shard, "error": repr(error), "traceback": traceback.format_exc()}
|
| 283 |
+
finally:
|
| 284 |
+
shutil.rmtree(work, ignore_errors=True)
|
| 285 |
+
if task.get("repo") and local is not None:
|
| 286 |
+
Path(local).unlink(missing_ok=True)
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
def upload_batch(api: Any, repo: str, prefix: str, output_root: Path, shards: list[str], delete_local: bool) -> None:
|
| 290 |
+
"""複数シャードを 1 コミットでまとめる(HF のコミット制限 320/時 対策)。429 は案内の待ち時間だけ待って再試行。"""
|
| 291 |
+
import re as _re
|
| 292 |
+
for attempt in range(12):
|
| 293 |
+
try:
|
| 294 |
+
api.upload_folder(repo_id=repo, repo_type="dataset", folder_path=str(output_root), path_in_repo=prefix,
|
| 295 |
+
allow_patterns=[f"{sh}/**" for sh in shards],
|
| 296 |
+
commit_message=f"{Path(prefix).name} {shards[0]}..{shards[-1]} ({len(shards)} shards)")
|
| 297 |
+
break
|
| 298 |
+
except Exception as e: # noqa: BLE001
|
| 299 |
+
msg = str(e)
|
| 300 |
+
m = _re.search(r"retry this action in (\d+) minutes", msg)
|
| 301 |
+
wait = (int(m.group(1)) * 60 + 90) if m else (120 * (attempt + 1))
|
| 302 |
+
print(json.dumps({"event": "upload_retry", "attempt": attempt + 1, "wait_s": wait, "error": msg[:160]}), flush=True)
|
| 303 |
+
if attempt == 11:
|
| 304 |
+
raise
|
| 305 |
+
time.sleep(wait)
|
| 306 |
+
if delete_local:
|
| 307 |
+
for sh in shards:
|
| 308 |
+
shutil.rmtree(output_root / sh, ignore_errors=True)
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
def calibrate(files: list[str], handoff_dir: Path, staging: Path, redact: bool = False) -> None:
|
| 312 |
+
_load_stages(handoff_dir)
|
| 313 |
+
for f in files:
|
| 314 |
+
work = staging / (Path(f).stem + "_work")
|
| 315 |
+
shutil.rmtree(work, ignore_errors=True)
|
| 316 |
+
started = time.perf_counter()
|
| 317 |
+
audit_path, stages = run_chain(Path(f), work)
|
| 318 |
+
import pyarrow.parquet as pq
|
| 319 |
+
audit = pq.read_table(audit_path, columns=["decision", "reasons"])
|
| 320 |
+
counts = collections.Counter(audit.column("decision").to_pylist())
|
| 321 |
+
rej = collections.Counter(r for r, d in zip(audit.column("reasons").to_pylist(),
|
| 322 |
+
audit.column("decision").to_pylist()) if d == "reject")
|
| 323 |
+
print(json.dumps({"file": f, "rows": sum(counts.values()), "decisions": dict(counts),
|
| 324 |
+
"reject_reasons": dict(rej.most_common(10)),
|
| 325 |
+
"stage_decisions": {k: v.get("decisions", {}) for k, v in stages.items()},
|
| 326 |
+
"seconds": round(time.perf_counter() - started, 1)}, ensure_ascii=False))
|
| 327 |
+
shutil.rmtree(work, ignore_errors=True)
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
def main(argv: list[str] | None = None) -> None:
|
| 331 |
+
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 332 |
+
parser.add_argument("--calibrate", action="store_true")
|
| 333 |
+
parser.add_argument("--files", default="")
|
| 334 |
+
parser.add_argument("--handoff-dir", type=Path, required=True, help="配布物のルート(scripts/ と models/ を含む)")
|
| 335 |
+
parser.add_argument("--repo", default=None)
|
| 336 |
+
parser.add_argument("--source-prefix", default="outputs_v5")
|
| 337 |
+
parser.add_argument("--input-layout", choices=("nested", "flat"), default="nested",
|
| 338 |
+
help="nested: <prefix>/<dir>/<shard>/<shard>.parquet、flat: <prefix>/<dir>/<shard>.parquet")
|
| 339 |
+
parser.add_argument("--redact-pii", action="store_true",
|
| 340 |
+
help="配布物の redact_direct_pii(メール・電話・郵便番号)を保持行の本文へ適用する")
|
| 341 |
+
parser.add_argument("--dir", default=None)
|
| 342 |
+
parser.add_argument("--output-root", type=Path, default=None)
|
| 343 |
+
parser.add_argument("--staging-dir", type=Path, default=Path("/work/staging"))
|
| 344 |
+
parser.add_argument("--limit-shards", type=int, default=None)
|
| 345 |
+
parser.add_argument("--shard-index", type=int, default=0, help="--shard-total 分割のうち何番目を担当するか")
|
| 346 |
+
parser.add_argument("--shard-total", type=int, default=1, help="1 ディレクトリを何ジョブに分割するか")
|
| 347 |
+
parser.add_argument("--upload-repo", default=None)
|
| 348 |
+
parser.add_argument("--upload-prefix", default="outputs_v6")
|
| 349 |
+
parser.add_argument("--upload-batch", type=int, default=10)
|
| 350 |
+
parser.add_argument("--skip-existing-in-repo", action="store_true")
|
| 351 |
+
parser.add_argument("--workers", type=int, default=max(1, int(os.environ.get("CPU_CORES") or os.cpu_count() or 2) - 1))
|
| 352 |
+
args = parser.parse_args(argv)
|
| 353 |
+
|
| 354 |
+
args.staging_dir.mkdir(parents=True, exist_ok=True)
|
| 355 |
+
if args.calibrate:
|
| 356 |
+
calibrate([f for f in args.files.split(",") if f], args.handoff_dir, args.staging_dir,
|
| 357 |
+
redact=args.redact_pii)
|
| 358 |
+
return
|
| 359 |
+
|
| 360 |
+
from huggingface_hub import HfApi
|
| 361 |
+
api = HfApi(token=os.environ.get("HF_TOKEN"))
|
| 362 |
+
entries = list(api.list_repo_tree(args.repo, path_in_repo=f"{args.source_prefix}/{args.dir}",
|
| 363 |
+
repo_type="dataset", recursive=False))
|
| 364 |
+
if args.input_layout == "flat":
|
| 365 |
+
# data/<dir>/<shard>.parquet。_DONE などの付随ファイルは除く
|
| 366 |
+
shards = sorted({e.path.split("/")[-1][: -len(".parquet")]
|
| 367 |
+
for e in entries if e.path.endswith(".parquet")})
|
| 368 |
+
else:
|
| 369 |
+
shards = sorted({e.path.split("/")[-1] for e in entries})
|
| 370 |
+
if args.limit_shards:
|
| 371 |
+
shards = shards[: args.limit_shards]
|
| 372 |
+
if args.shard_total > 1:
|
| 373 |
+
shards = shards[args.shard_index :: args.shard_total]
|
| 374 |
+
existing: set[str] = set()
|
| 375 |
+
if args.skip_existing_in_repo and args.upload_repo:
|
| 376 |
+
try:
|
| 377 |
+
existing = {e.path.split("/")[-1] for e in api.list_repo_tree(
|
| 378 |
+
args.upload_repo, path_in_repo=f"{args.upload_prefix}/{args.dir}", repo_type="dataset", recursive=False)}
|
| 379 |
+
except Exception: # noqa: BLE001
|
| 380 |
+
existing = set()
|
| 381 |
+
def source_path(sh: str) -> str:
|
| 382 |
+
if args.input_layout == "flat":
|
| 383 |
+
return f"{args.source_prefix}/{args.dir}/{sh}.parquet"
|
| 384 |
+
return f"{args.source_prefix}/{args.dir}/{sh}/{sh}.parquet"
|
| 385 |
+
|
| 386 |
+
tasks = [{"repo": args.repo, "path": source_path(sh),
|
| 387 |
+
"shard": sh, "config": args.dir, "source_prefix": args.source_prefix,
|
| 388 |
+
"output_root": str(args.output_root), "staging_dir": str(args.staging_dir),
|
| 389 |
+
"handoff_dir": str(args.handoff_dir), "redact_pii": args.redact_pii}
|
| 390 |
+
for sh in shards if sh not in existing]
|
| 391 |
+
print(json.dumps({"event": "start", "dir": args.dir, "shards": len(shards),
|
| 392 |
+
"shard_index": args.shard_index, "shard_total": args.shard_total,
|
| 393 |
+
"skipped_existing": len(shards) - len(tasks), "workers": args.workers}), flush=True)
|
| 394 |
+
pending: list[str] = []
|
| 395 |
+
failed: list[str] = []
|
| 396 |
+
with ProcessPoolExecutor(max_workers=args.workers) as ex:
|
| 397 |
+
for s in ex.map(process_shard, tasks):
|
| 398 |
+
if "error" in s:
|
| 399 |
+
failed.append(s["shard"])
|
| 400 |
+
print(json.dumps({"event": "error", **s}, ensure_ascii=False)[:800], flush=True)
|
| 401 |
+
continue
|
| 402 |
+
print(json.dumps({"event": "done", **{k: v for k, v in s.items()
|
| 403 |
+
if k not in ("version", "finished_at_utc", "compression", "stage_decisions")}},
|
| 404 |
+
ensure_ascii=False), flush=True)
|
| 405 |
+
if args.upload_repo:
|
| 406 |
+
pending.append(s["shard"])
|
| 407 |
+
if len(pending) >= args.upload_batch:
|
| 408 |
+
upload_batch(api, args.upload_repo, f"{args.upload_prefix}/{args.dir}", args.output_root, pending, True)
|
| 409 |
+
pending = []
|
| 410 |
+
if args.upload_repo and pending:
|
| 411 |
+
upload_batch(api, args.upload_repo, f"{args.upload_prefix}/{args.dir}", args.output_root, pending, True)
|
| 412 |
+
print(json.dumps({"event": "finish", "dir": args.dir, "shards": len(tasks), "failed": failed}), flush=True)
|
| 413 |
+
|
| 414 |
+
|
| 415 |
+
if __name__ == "__main__":
|
| 416 |
+
main()
|