File size: 14,332 Bytes
cadf371
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
"""ノイズ除去の第2パス(監査項目14〜21)。

第1パス(``run_shard.py``: 有害フィルタ → PII 置換)のクリーン済み出力
``<input-dir>/<shard>/<shard>.parquet`` を入力にし、``<output-root>/<shard>/`` に
``<shard>.parquet``(ノイズ除去後)、``noise/removed.jsonl``、``noise/summary.json``、
``noise_summary.json`` を書く。``--upload-repo`` を付けると HF データセットへ
バッチアップロードしてローカルを削除する(HF Jobs の一時ディスク対策)。

    uv run python abeja-cc-ja/src/run_noise_pass.py --input-dir <outputs/common_crawl_0> --output-root <out> --workers 7 \\
        --upload-repo Podtech/abeja-cc-ja-cleaned --upload-prefix outputs_v2/common_crawl_0 --delete-local-after-upload

トークン数の閾値を使う場合は ``--tokenizer <HFモデル名>`` と ``--min-tokens/--max-tokens`` を指定する
(transformers が必要。既定は文字数のみ)。
"""

from __future__ import annotations

import argparse
import json
import multiprocessing as mp
import os
import shutil
import time
import traceback
from datetime import datetime, timezone
from pathlib import Path
from typing import Any

import pyarrow as pa
import pyarrow.parquet as pq

from run_shard import Uploader, stage_input


NOISE_PASS_VERSION = "abeja-cc-ja-noise-pass/2026-09-04"
_WORKER: dict[str, Any] = {}


def _init_worker(config: dict[str, Any]) -> None:
    import sys

    sys.path.insert(0, str(Path(__file__).resolve().parent))
    from doc_features import DocFeaturizer, LanguageDetector
    from filter_noise import NoiseFilter

    _WORKER["config"] = config
    lid = LanguageDetector(Path(config["lid_model"])) if config.get("lid_model") else None
    _WORKER["filter"] = NoiseFilter(
        Path(config["patterns_dir"]),
        min_chars=config["min_chars"], max_chars=config["max_chars"], newline_policy=config["newline_policy"],
        tokenizer=config.get("tokenizer"), min_tokens=config.get("min_tokens"), max_tokens=config.get("max_tokens"),
        language_detector=lid, drop_non_japanese=config.get("drop_non_japanese", True),
    )
    featurizer = DocFeaturizer(Path(config["genre_rules"]), None)
    featurizer.lid = lid
    _WORKER["featurizer"] = featurizer


def process_shard(input_path: Path, output_root: Path, config: dict[str, Any]) -> dict[str, Any]:
    from filter_noise import run_noise_filter

    if not _WORKER:
        _init_worker(config)
    shard = input_path.stem
    out_dir = output_root / shard
    out_dir.mkdir(parents=True, exist_ok=True)
    started = time.perf_counter()
    started_at = datetime.now(timezone.utc).isoformat()
    input_rows = pq.ParquetFile(input_path).metadata.num_rows
    featurizer = _WORKER["featurizer"]
    feature_rows: list[dict[str, Any]] = []

    def on_record(row: dict[str, Any], result: Any, record_index: int) -> None:
        status = "retained" if result.deleted_reason is None else f"deleted_noise:{result.deleted_reason}"
        text = result.text if result.deleted_reason is None else (row.get("content") or "")
        lang = (result.lang, result.lang_prob) if result.lang is not None else None
        feature_rows.append(featurizer.features(row.get("url") or "", text, result.chars_before, status, record_index, row.get("perplexity"), lang))

    summary = run_noise_filter(input_path, out_dir / "noise", _WORKER["filter"], batch_size=config["batch_size"], output_name="cleaned.parquet", on_record=on_record)
    # 第1パスで有害フィルタにより削除された文書も、ジャンル別の削除率(項目27)のため特徴量を出す
    toxic_removed = Path(config.get("source_dir") or input_path.parent) / "toxic" / "distinct_terms_3plus" / "removed.jsonl"
    toxic_count = 0
    if toxic_removed.exists():
        with toxic_removed.open(encoding="utf-8") as handle:
            for line in handle:
                if not line.strip():
                    continue
                record = json.loads(line)
                content = record.get("content") or ""
                reasons = "+".join(record.get("_filter_deleted_by") or [])
                feature_rows.append(featurizer.features(record.get("url") or "", content, len(content), f"deleted_toxic:{reasons}", record.get("_filter_record_index", -1), record.get("perplexity")))
                toxic_count += 1
    if feature_rows:
        pq.write_table(pa.Table.from_pylist(feature_rows), out_dir / "features.parquet", compression="zstd")
    final_path = out_dir / f"{shard}.parquet"
    shutil.move(str(out_dir / "noise" / "cleaned.parquet"), str(final_path))
    shard_summary = {
        "pipeline_version": NOISE_PASS_VERSION,
        "stage": "noise",
        "shard": shard,
        "input_file": str(input_path),
        "input_rows": input_rows,
        "started_at_utc": started_at,
        "finished_at_utc": datetime.now(timezone.utc).isoformat(),
        "seconds": round(time.perf_counter() - started, 1),
        "noise": {
            "thresholds": summary["thresholds"],
            "records_scanned": summary["records_scanned"],
            "records_deleted": summary["records_deleted"],
            "records_retained": summary["records_retained"],
            "records_modified": summary["records_modified"],
            "records_newline_joined": summary["records_newline_joined"],
            "records_deleted_by_reason": summary["records_deleted_by_reason"],
            "chars_before": summary["chars_before"],
            "chars_after_retained": summary["chars_after_retained"],
            "tokens_after_retained": summary["tokens_after_retained"],
            "by_item": summary["by_item"],
            "patterns": [
                {k: p[k] for k in ("id", "item", "action", "records_detected", "occurrences", "lines_removed", "replacements")}
                for p in summary["patterns"]
            ],
        },
        "features": {
            "file": str(out_dir / "features.parquet"), "rows": len(feature_rows), "toxic_deleted_rows": toxic_count,
            "describe": featurizer.describe(),
        },
        "output": {"cleaned_parquet": str(final_path), "final_rows": summary["records_retained"], "removed_jsonl": str(out_dir / "noise" / "removed.jsonl")},
    }
    (out_dir / "noise_summary.json").write_text(json.dumps(shard_summary, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
    return shard_summary


def _worker_entry(args: tuple[str, str, dict[str, Any]]) -> dict[str, Any]:
    input_path, output_root, config = args
    staging_dir = Path(config["staging_dir"]) if config.get("staging_dir") else None
    local_input: Path | None = None
    last_error: Exception | None = None
    for attempt in range(1, 4):
        try:
            local_input = stage_input(Path(input_path), staging_dir)
            # 有害フィルタの removed.jsonl は元のディレクトリから読むため、入力の場所を config で渡す
            result = process_shard(local_input, Path(output_root), {**config, "source_dir": str(Path(input_path).parent)})
            result["input_file"] = input_path
            return result
        except OSError as error:
            last_error = error
            print(json.dumps({"event": "io_retry", "shard": Path(input_path).stem, "attempt": attempt, "error": repr(error)[:160]}), flush=True)
            time.sleep(30 * attempt)
        except Exception as error:  # noqa: BLE001
            return {"shard": Path(input_path).stem, "input_file": input_path, "error": repr(error), "traceback": traceback.format_exc()}
        finally:
            if local_input is not None and staging_dir is not None and local_input != Path(input_path):
                local_input.unlink(missing_ok=True)
    return {"shard": Path(input_path).stem, "input_file": input_path, "error": repr(last_error), "traceback": ""}


def discover_inputs(input_dir: Path) -> list[Path]:
    """``<dir>/<shard>/<shard>.parquet``(第1パス出力)か ``<dir>/*.parquet`` を列挙する。"""

    nested = sorted(p for p in input_dir.glob("*/*.parquet") if p.stem == p.parent.name)
    return nested or sorted(input_dir.glob("*.parquet"))


def main(argv: list[str] | None = None) -> None:
    source_dir = Path(__file__).resolve().parent
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("--input-dir", type=Path, required=True)
    parser.add_argument("--output-root", type=Path, required=True)
    parser.add_argument("--limit-shards", type=int, default=None)
    parser.add_argument("--workers", type=int, default=max(1, (os.cpu_count() or 2) - 1))
    parser.add_argument("--batch-size", type=int, default=2048)
    parser.add_argument("--patterns-dir", type=Path, default=source_dir / "noise")
    parser.add_argument("--min-chars", type=int, default=200)
    parser.add_argument("--max-chars", type=int, default=100_000)
    parser.add_argument("--newline-policy", choices=("join", "delete", "keep"), default="join")
    parser.add_argument("--tokenizer", default=None, help="トークン数を数える HF トークナイザ名(任意)")
    parser.add_argument("--lid-model", type=Path, default=source_dir.parent / "data" / "models" / "lid.176.ftz", help="fastText 言語判定モデル。無ければ言語判定を行わない")
    parser.add_argument("--keep-non-japanese", action="store_true", help="日本語以外と判定された文書を削除しない(記録のみ)")
    parser.add_argument("--genre-rules", type=Path, default=source_dir / "wordlists" / "genre" / "genre_rules.json")
    parser.add_argument("--min-tokens", type=int, default=None)
    parser.add_argument("--max-tokens", type=int, default=None)
    parser.add_argument("--upload-repo", default=None)
    parser.add_argument("--upload-prefix", default="outputs_v2")
    parser.add_argument("--upload-batch", type=int, default=5)
    parser.add_argument("--delete-local-after-upload", action="store_true")
    parser.add_argument("--skip-existing-in-repo", action="store_true")
    parser.add_argument("--staging-dir", type=Path, default=None, help="入力parquetを処理前にコピーするローカルディレクトリ(マウントの I/O エラー対策)")
    args = parser.parse_args(argv)

    inputs = discover_inputs(args.input_dir)
    if args.limit_shards is not None:
        inputs = inputs[: args.limit_shards]
    if not inputs:
        raise FileNotFoundError(f"入力parquetが見つかりません: {args.input_dir}")
    args.output_root.mkdir(parents=True, exist_ok=True)
    uploader = None
    skip: set[str] = set()
    if args.upload_repo:
        uploader = Uploader(args.upload_repo, args.upload_prefix, args.output_root, args.upload_batch, args.delete_local_after_upload)
        if args.skip_existing_in_repo:
            skip = uploader.existing_shards(marker="noise_summary.json")
    todo = []
    for path in inputs:
        if path.stem in skip or (args.output_root / path.stem / "noise_summary.json").exists():
            print(json.dumps({"event": "skip", "shard": path.stem}), flush=True)
            continue
        todo.append(path)
    config = {
        "patterns_dir": str(args.patterns_dir), "batch_size": args.batch_size,
        "min_chars": args.min_chars, "max_chars": args.max_chars, "newline_policy": args.newline_policy,
        "tokenizer": args.tokenizer, "min_tokens": args.min_tokens, "max_tokens": args.max_tokens,
        "lid_model": str(args.lid_model) if args.lid_model and args.lid_model.exists() else None,
        "drop_non_japanese": not args.keep_non_japanese, "genre_rules": str(args.genre_rules),
        "staging_dir": str(args.staging_dir) if args.staging_dir else None,
    }
    if config["lid_model"] is None:
        print(json.dumps({"event": "warning", "message": f"言語判定モデルが見つからないため項目25の判定を行いません: {args.lid_model}"}, ensure_ascii=False), flush=True)
    print(json.dumps({"event": "start", "stage": "noise", "shards": len(todo), "skipped": len(inputs) - len(todo), "workers": args.workers, "thresholds": config}, ensure_ascii=False), flush=True)
    jobs = [(str(p), str(args.output_root), config) for p in todo]
    if args.workers <= 1 or len(jobs) <= 1:
        _init_worker(config)
        iterator = map(_worker_entry, jobs)
    else:
        context = mp.get_context("spawn")
        pool = context.Pool(processes=min(args.workers, len(jobs)), initializer=_init_worker, initargs=(config,))
        iterator = pool.imap_unordered(_worker_entry, jobs)
    results: list[dict[str, Any]] = []
    run_started = time.perf_counter()
    for result in iterator:
        results.append(result)
        if "error" in result:
            print(json.dumps({"event": "error", "shard": result["shard"], "error": result["error"]}), flush=True)
            continue
        print(json.dumps({
            "event": "done", "shard": result["shard"], "input_rows": result["input_rows"],
            "noise_deleted": result["noise"]["records_deleted"], "modified": result["noise"]["records_modified"],
            "final_rows": result["output"]["final_rows"], "seconds": result["seconds"],
        }), flush=True)
        if uploader is not None:
            uploader.add(result["shard"])
    if uploader is not None:
        uploader.flush()
    errors = [r for r in results if "error" in r]
    run_summary = {
        "pipeline_version": NOISE_PASS_VERSION, "stage": "noise",
        "finished_at_utc": datetime.now(timezone.utc).isoformat(),
        "shards_processed": len(results) - len(errors),
        "shards_failed": [{"shard": r["shard"], "error": r["error"]} for r in errors],
        "shards_skipped": len(inputs) - len(todo),
        "seconds": round(time.perf_counter() - run_started, 1),
        "upload_repo": args.upload_repo, "upload_prefix": args.upload_prefix if args.upload_repo else None,
    }
    (args.output_root / f"run_summary_noise_{datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ')}.json").write_text(json.dumps(run_summary, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
    print(json.dumps({"event": "finish", **run_summary}, ensure_ascii=False), flush=True)
    if errors:
        raise SystemExit(1)


if __name__ == "__main__":
    main()