Download code/3c1a8da/src/quality_report.py from Podtech/abeja-cc-ja-cleaned: direct link, hf CLI and curl.
- Browser
- Download file 18.4 kB
-
https://huggingface.co/datasets/Podtech/abeja-cc-ja-cleaned/resolve/main/code/3c1a8da/src/quality_report.py
- Command line
-
hf download hf://datasets/Podtech/abeja-cc-ja-cleaned/code/3c1a8da/src/quality_report.py
-
curl -L -o quality_report.py https://huggingface.co/datasets/Podtech/abeja-cc-ja-cleaned/resolve/main/code/3c1a8da/src/quality_report.py
18.4 kB
| """監査項目 E(22 重複)・F(25〜27 言語・品質)・G(28〜29 ドメイン適合)の報告書を生成する。 | |
| 第2パスが書く ``features.parquet``(文書ごとの言語・ジャンル・品質フラグ・文字数・perplexity・SHA-1)と | |
| ``noise_summary.json`` を DuckDB で集約し、JSON と Markdown を出力する。全件(約2.2億行)でも | |
| DuckDB がファイルを逐次読みするため、1台のジョブ(cpu-xl 等)で処理できる。 | |
| uv run python abeja-cc-ja/src/quality_report.py --features-glob "<root>/**/features.parquet" \\ | |
| --noise-summaries-glob "<root>/**/noise_summary.json" --output-dir <report_dir> \\ | |
| [--previous-low-quality-rate 0.35] [--exclude-genres none] | |
| 項目22の配布元重複除去の記録は本スクリプト内の定数(出典 URL 付き)に置き、完全一致(本文 SHA-1、URL)の | |
| 再確認結果を添える。 | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| from datetime import datetime, timezone | |
| from pathlib import Path | |
| from typing import Any | |
| UPSTREAM_DEDUP = { | |
| "performed_by": "ABEJA(配布元、ABEJA-CC-JA 構築時)", | |
| "methods": [ | |
| {"method": "URL 重複除去(同一 URL は最新のスナップショットを採用)", "threshold": "完全一致"}, | |
| {"method": "MinHash による近似重複除去(text-dedup、Dataproc 上で実行)", "threshold": "非公開(記事に閾値の記載なし)"}, | |
| ], | |
| "source_urls": [ | |
| "https://tech-blog.abeja.asia/entry/abeja-nedo-project-part2-202405", | |
| "https://tech-blog.abeja.asia/entry/abeja-cc-ja-202409", | |
| "https://registry.opendata.aws/abeja-cc-ja/", | |
| ], | |
| "decision_ja": "配布元で URL 重複除去と MinHash 近似重複除去が実施済みのため、近似重複除去は再実行しない。完全一致(本文 SHA-1、URL)の残存だけを全件で再確認して記録する。", | |
| } | |
| GENRE_LABELS_JA = { | |
| "diary_blog": "日記ブログ", "affiliate": "投資・美容・健康のアフィリエイト", "game": "ゲーム", | |
| "entertainment": "芸能", "ec_product": "EC 商品ページ", "other": "その他", | |
| } | |
| LOW_QUALITY_FLAGS_JA = { | |
| "short_lt500": "最終本文が500字未満", "symbol_digit_ratio_gt30": "記号・数字比率30%超", "line_repetition_gt30": "同一行の反復30%超", | |
| "avg_line_len_lt20": "平均行長20字未満", "template_commerce": "販促・商品ページの定型", "low_lid_confidence": "言語判定の確信度0.5未満", | |
| } | |
| def q(con, sql: str) -> list[tuple]: | |
| return con.execute(sql).fetchall() | |
| def q1(con, sql: str): | |
| return con.execute(sql).fetchone() | |
| def build(features_glob: str, noise_glob: str | None, previous_low_quality_rate: float | None, exclude_genres: list[str], sample_examples: int = 5) -> dict[str, Any]: | |
| import duckdb | |
| con = duckdb.connect() | |
| con.execute(f"CREATE VIEW f AS SELECT * FROM read_parquet('{features_glob}', union_by_name=true)") | |
| total = q1(con, "SELECT count(*) FROM f")[0] | |
| retained = q1(con, "SELECT count(*) FROM f WHERE status = 'retained'")[0] | |
| report: dict[str, Any] = {"generated_at_utc": datetime.now(timezone.utc).isoformat(), "features_glob": features_glob, | |
| "records_total": total, "records_retained": retained} | |
| # --- 22 重複 --- | |
| dup_sha = q1(con, "SELECT count(*) - count(DISTINCT content_sha1) FROM f WHERE status = 'retained' AND content_sha1 <> ''")[0] | |
| dup_url = q1(con, "SELECT count(*) - count(DISTINCT url) FROM f WHERE status = 'retained' AND url <> ''")[0] | |
| report["item22_dedup"] = { | |
| "upstream": UPSTREAM_DEDUP, | |
| "exact_duplicate_check": { | |
| "scope": "第2パス後の保持文書(全件)", | |
| "content_sha1_duplicates": dup_sha, "url_duplicates": dup_url, | |
| "content_sha1_duplicate_rate": round(dup_sha / max(1, retained), 6), "url_duplicate_rate": round(dup_url / max(1, retained), 6), | |
| }, | |
| } | |
| # --- 25 言語 --- | |
| langs = q(con, "SELECT lang, count(*) FROM f WHERE status NOT LIKE 'deleted_toxic%' GROUP BY lang ORDER BY 2 DESC") | |
| lang_total = sum(n for _, n in langs) | |
| mixed = q1(con, "SELECT count(*) FROM f WHERE status = 'retained' AND mixed_language")[0] | |
| non_ja_deleted = q1(con, "SELECT count(*) FROM f WHERE status = 'deleted_noise:non_japanese'")[0] | |
| report["item25_language"] = { | |
| "tool": "fastText lid.176(文書先頭1,000字。行判定は30字以上の行を最大50行)", | |
| "scope": "第1パス後の文書(有害フィルタ削除分を除く)", | |
| "distribution": [{"lang": l, "records": n, "ratio": round(n / max(1, lang_total), 5)} for l, n in langs[:15]], | |
| "japanese_ratio": round(next((n for l, n in langs if l == "ja"), 0) / max(1, lang_total), 5), | |
| "mixed_language_records": mixed, "mixed_definition": "文書は日本語判定だが、30字以上の行のうち非日本語判定が3割以上", | |
| "processing": {"non_japanese": f"削除({non_ja_deleted} 文書、確信度0.5以上)", "mixed": "保持し件数のみ記録(非日本語行は行単位で削除しない)"}, | |
| } | |
| # --- 26 perplexity --- | |
| has_ppl = q1(con, "SELECT count(*) FROM f WHERE perplexity IS NOT NULL")[0] > 0 | |
| if has_ppl: | |
| quant = q1(con, "SELECT min(perplexity), quantile_cont(perplexity, 0.05), quantile_cont(perplexity, 0.25), quantile_cont(perplexity, 0.5), quantile_cont(perplexity, 0.75), quantile_cont(perplexity, 0.95), max(perplexity) FROM f WHERE perplexity IS NOT NULL") | |
| hist = q(con, "SELECT floor(perplexity/5)*5 AS b, count(*) FROM f WHERE perplexity IS NOT NULL GROUP BY b ORDER BY b") | |
| near_threshold = q(con, f"SELECT url, perplexity, chars_final, genre FROM f WHERE status='retained' AND perplexity >= 38 ORDER BY perplexity DESC LIMIT {sample_examples}") | |
| low = q(con, f"SELECT url, perplexity, chars_final, genre FROM f WHERE status='retained' AND perplexity IS NOT NULL ORDER BY perplexity ASC LIMIT {sample_examples}") | |
| report["item26_perplexity"] = { | |
| "filter": {"applied_by": "Podtech(入力データセット abeja-cc-ja-filtered の作成時)", "model": "KenLM(lighttransport/japanese-scoring-model)", "threshold": "perplexity < 40 を保持", | |
| "source_url": "https://huggingface.co/datasets/Podtech/abeja-cc-ja-filtered"}, | |
| "distribution_retained": {"min": quant[0], "p5": quant[1], "p25": quant[2], "p50": quant[3], "p75": quant[4], "p95": quant[5], "max": quant[6]}, | |
| "histogram_bin5": [{"bin_start": int(b), "records": n} for b, n in hist], | |
| "examples_near_threshold_retained": [{"url": u, "perplexity": p, "chars": c, "genre": g} for u, p, c, g in near_threshold], | |
| "examples_lowest_perplexity": [{"url": u, "perplexity": p, "chars": c, "genre": g} for u, p, c, g in low], | |
| "note_ja": "閾値以上(除外側)の文書は入力データに含まれないため、除外例は配布元データ(S3 の原本)からの抽出が必要。ここでは保持側の分布と閾値付近の残存例を示す。", | |
| } | |
| else: | |
| report["item26_perplexity"] = {"note_ja": "perplexity 列が無いため未集計"} | |
| # --- 27 文書長の分布(前後) --- | |
| def dist(col: str, where: str) -> dict[str, Any]: | |
| r = q1(con, f"SELECT count(*), min({col}), quantile_cont({col}, 0.05), quantile_cont({col}, 0.5), quantile_cont({col}, 0.95), max({col}), avg({col}), sum({col}) FROM f WHERE {where}") | |
| return {"records": r[0], "min": r[1], "p5": r[2], "p50": r[3], "p95": r[4], "max": r[5], "mean": round(r[6], 1) if r[6] else None, "sum": r[7]} | |
| by_genre_status = q(con, "SELECT genre, split_part(status, ':', 1) AS st, count(*) FROM f GROUP BY genre, st ORDER BY genre, st") | |
| genre_rates: dict[str, dict[str, Any]] = {} | |
| for g, st, n in by_genre_status: | |
| genre_rates.setdefault(g, {"label_ja": GENRE_LABELS_JA.get(g, g), "records": 0}) | |
| genre_rates[g][st] = n | |
| genre_rates[g]["records"] += n | |
| for g, v in genre_rates.items(): | |
| v["deleted_rate"] = round((v.get("deleted_toxic", 0) + v.get("deleted_noise", 0)) / max(1, v["records"]), 5) | |
| report["item27_length"] = { | |
| "chars_input_all": dist("chars_input", "chars_input IS NOT NULL"), | |
| "chars_final_retained": dist("chars_final", "status = 'retained'"), | |
| "chars_input_deleted_toxic": dist("chars_input", "status LIKE 'deleted_toxic%'"), | |
| "chars_input_deleted_noise": dist("chars_input", "status LIKE 'deleted_noise%'"), | |
| "deletion_rate_by_genre": genre_rates, | |
| "tokens_note_ja": "トークン数は方針によりトークナイザを指定しないため未集計(文字数のみ)。", | |
| } | |
| # --- 28 低品質 --- | |
| lq = q1(con, "SELECT count(*) FROM f WHERE status = 'retained' AND is_low_quality")[0] | |
| flags = q(con, "SELECT flag, count(*) FROM (SELECT unnest(string_split(low_quality_flags, '|')) AS flag FROM f WHERE status = 'retained' AND low_quality_flags <> '') GROUP BY flag ORDER BY 2 DESC") | |
| lq_by_genre = q(con, "SELECT genre, count(*), sum(CASE WHEN is_low_quality THEN 1 ELSE 0 END) FROM f WHERE status = 'retained' GROUP BY genre ORDER BY 2 DESC") | |
| report["item28_low_quality"] = { | |
| "definition_ja": "保持文書のうち次のいずれかに該当: " + "、".join(f"{k}({v})" for k, v in LOW_QUALITY_FLAGS_JA.items()), | |
| "method_ja": "第2パスで文書ごとに決定的規則で判定(doc_features.py)。分類の妥当性はサンプルの目視で確認する。", | |
| "records_retained": retained, "low_quality_records": lq, "low_quality_rate": round(lq / max(1, retained), 5), | |
| "by_flag": [{"flag": f_, "label_ja": LOW_QUALITY_FLAGS_JA.get(f_, f_), "records": n, "ratio": round(n / max(1, retained), 5)} for f_, n in flags], | |
| "by_genre": [{"genre": g, "label_ja": GENRE_LABELS_JA.get(g, g), "records": n, "low_quality": m, "rate": round(m / max(1, n), 4)} for g, n, m in lq_by_genre], | |
| "previous_review_rate": previous_low_quality_rate, | |
| "comparison_ja": (f"前回レビュー指摘値 {previous_low_quality_rate:.1%} に対し今回 {lq / max(1, retained):.1%}" if previous_low_quality_rate is not None else "前回レビューの指摘値が未入力のため比較なし"), | |
| } | |
| # --- 29 ジャンル --- | |
| genres = q(con, "SELECT genre, count(*) FROM f WHERE status = 'retained' GROUP BY genre ORDER BY 2 DESC") | |
| manufacturing = q1(con, "SELECT count(*) FROM f WHERE status = 'retained' AND manufacturing_score >= 2.0")[0] | |
| report["item29_genre"] = { | |
| "method_ja": "wordlists/genre/genre_rules.json の URL 規則と手がかり語で、1,000字あたりの異なり手がかり語数をスコア化(しきい値2.0)。製造業・重工の適合スコアは独立に算出。", | |
| "distribution_retained": [{"genre": g, "label_ja": GENRE_LABELS_JA.get(g, g), "records": n, "ratio": round(n / max(1, retained), 5)} for g, n in genres], | |
| "manufacturing_relevant_records": manufacturing, "manufacturing_relevant_ratio": round(manufacturing / max(1, retained), 5), | |
| "exclusion_decision": {"excluded_genres": exclude_genres, "note_ja": "除外するジャンルは方針として決める。除外する場合は第3パスで genre 列を条件に削除し、件数を記録する。"}, | |
| } | |
| if noise_glob: | |
| report["noise_summaries_glob"] = noise_glob | |
| return report | |
| def to_markdown(r: dict[str, Any]) -> str: | |
| L: list[str] = [] | |
| L.append("# 品質監査報告(E 重複・F 言語/品質・G ドメイン適合)") | |
| L.append("") | |
| L.append(f"- 生成日時: {r['generated_at_utc']}") | |
| L.append(f"- 対象文書: {r['records_total']:,}(保持 {r['records_retained']:,})") | |
| L.append("") | |
| d = r["item22_dedup"] | |
| L.append("## 項目22: 重複除去") | |
| L.append("") | |
| L.append(f"- 配布元の実施: {d['upstream']['performed_by']}") | |
| for m in d["upstream"]["methods"]: | |
| L.append(f" - {m['method']}(閾値: {m['threshold']})") | |
| L.append("- 出典: " + ", ".join(d["upstream"]["source_urls"])) | |
| L.append(f"- 判断: {d['upstream']['decision_ja']}") | |
| e = d["exact_duplicate_check"] | |
| L.append(f"- 完全一致の再確認({e['scope']}): 本文 SHA-1 重複 {e['content_sha1_duplicates']:,}({e['content_sha1_duplicate_rate']:.4%})、URL 重複 {e['url_duplicates']:,}") | |
| L.append("") | |
| l = r["item25_language"] | |
| L.append("## 項目25: 言語判定") | |
| L.append("") | |
| L.append(f"- ツール: {l['tool']}。対象: {l['scope']}") | |
| L.append(f"- 日本語比率: {l['japanese_ratio']:.4%}。混在文書({l['mixed_definition']}): {l['mixed_language_records']:,}") | |
| L.append("- 処理: " + "、".join(f"{k}: {v}" for k, v in l["processing"].items())) | |
| L.append("") | |
| L.append("| 言語 | 文書数 | 比率 |") | |
| L.append("|---|---:|---:|") | |
| for x in l["distribution"][:8]: | |
| L.append(f"| {x['lang']} | {x['records']:,} | {x['ratio']:.4%} |") | |
| L.append("") | |
| p = r["item26_perplexity"] | |
| L.append("## 項目26: perplexity フィルタ") | |
| L.append("") | |
| if "filter" in p: | |
| L.append(f"- 適用者: {p['filter']['applied_by']}、モデル: {p['filter']['model']}、閾値: {p['filter']['threshold']}({p['filter']['source_url']})") | |
| ds = p["distribution_retained"] | |
| L.append(f"- 保持側の分布: min {ds['min']:.1f} / p5 {ds['p5']:.1f} / p50 {ds['p50']:.1f} / p95 {ds['p95']:.1f} / max {ds['max']:.1f}") | |
| L.append("- ヒストグラム(5刻み): " + ", ".join(f"{h['bin_start']}-{h['bin_start']+5}: {h['records']:,}" for h in p["histogram_bin5"])) | |
| L.append("- 閾値付近の残存例:") | |
| for x in p["examples_near_threshold_retained"]: | |
| L.append(f" - {x['url'][:90]} (ppl {x['perplexity']:.1f}, {x['chars']}字, {x['genre']})") | |
| L.append(f"- 注記: {p['note_ja']}") | |
| else: | |
| L.append(f"- {p['note_ja']}") | |
| L.append("") | |
| n = r["item27_length"] | |
| L.append("## 項目27: 文書長の分布(フィルタ前後)") | |
| L.append("") | |
| L.append("| 区分 | 文書数 | min | p5 | p50 | p95 | max | 平均 |") | |
| L.append("|---|---:|---:|---:|---:|---:|---:|---:|") | |
| for key, label in (("chars_input_all", "入力(全件)"), ("chars_final_retained", "最終(保持)"), ("chars_input_deleted_toxic", "有害フィルタで削除"), ("chars_input_deleted_noise", "ノイズで削除")): | |
| x = n[key] | |
| if x["records"]: | |
| L.append(f"| {label} | {x['records']:,} | {x['min']:.0f} | {x['p5']:.0f} | {x['p50']:.0f} | {x['p95']:.0f} | {x['max']:.0f} | {x['mean']} |") | |
| L.append("") | |
| L.append("ジャンル別の削除率(特定ジャンルだけが大量に落ちていないかの確認):") | |
| L.append("") | |
| L.append("| ジャンル | 文書数 | 有害で削除 | ノイズで削除 | 削除率 |") | |
| L.append("|---|---:|---:|---:|---:|") | |
| for g, v in sorted(n["deletion_rate_by_genre"].items(), key=lambda kv: -kv[1]["records"]): | |
| L.append(f"| {v['label_ja']} | {v['records']:,} | {v.get('deleted_toxic', 0):,} | {v.get('deleted_noise', 0):,} | {v['deleted_rate']:.2%} |") | |
| L.append(f"\n{n['tokens_note_ja']}") | |
| L.append("") | |
| lq = r["item28_low_quality"] | |
| L.append("## 項目28: 低品質ページ") | |
| L.append("") | |
| L.append(f"- 定義: {lq['definition_ja']}") | |
| L.append(f"- 方法: {lq['method_ja']}") | |
| L.append(f"- 比率: {lq['low_quality_records']:,} / {lq['records_retained']:,} = {lq['low_quality_rate']:.2%}。{lq['comparison_ja']}") | |
| L.append("") | |
| L.append("| 該当条件 | 文書数 | 比率 |") | |
| L.append("|---|---:|---:|") | |
| for x in lq["by_flag"]: | |
| L.append(f"| {x['label_ja']} | {x['records']:,} | {x['ratio']:.2%} |") | |
| L.append("") | |
| g = r["item29_genre"] | |
| L.append("## 項目29: 無関係ジャンルの比率") | |
| L.append("") | |
| L.append(f"- 方法: {g['method_ja']}") | |
| L.append("") | |
| L.append("| ジャンル | 文書数 | 比率 |") | |
| L.append("|---|---:|---:|") | |
| for x in g["distribution_retained"]: | |
| L.append(f"| {x['label_ja']} | {x['records']:,} | {x['ratio']:.2%} |") | |
| L.append("") | |
| L.append(f"- 製造業・重工に適合(スコア2.0以上): {g['manufacturing_relevant_records']:,}({g['manufacturing_relevant_ratio']:.2%})") | |
| L.append(f"- 除外の判断: 除外ジャンル = {g['exclusion_decision']['excluded_genres'] or 'なし'}。{g['exclusion_decision']['note_ja']}") | |
| L.append("") | |
| return "\n".join(L) + "\n" | |
| def main(argv: list[str] | None = None) -> None: | |
| parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) | |
| parser.add_argument("--features-glob", required=True, help="features.parquet の glob(DuckDB 形式、例: /cleaned/outputs_v2/**/features.parquet)") | |
| parser.add_argument("--noise-summaries-glob", default=None) | |
| parser.add_argument("--output-dir", type=Path, required=True) | |
| parser.add_argument("--previous-low-quality-rate", type=float, default=None, help="前回レビューの低品質比率(0〜1)") | |
| parser.add_argument("--exclude-genres", default="", help="除外を決めたジャンル(カンマ区切り、記録用)") | |
| args = parser.parse_args(argv) | |
| excluded = [x for x in args.exclude_genres.split(",") if x] | |
| report = build(args.features_glob, args.noise_summaries_glob, args.previous_low_quality_rate, excluded) | |
| args.output_dir.mkdir(parents=True, exist_ok=True) | |
| (args.output_dir / "quality_report.json").write_text(json.dumps(report, ensure_ascii=False, indent=2, default=str) + "\n", encoding="utf-8") | |
| (args.output_dir / "quality_report.md").write_text(to_markdown(report), encoding="utf-8") | |
| print(json.dumps({"records_total": report["records_total"], "retained": report["records_retained"], | |
| "japanese_ratio": report["item25_language"]["japanese_ratio"], "low_quality_rate": report["item28_low_quality"]["low_quality_rate"], | |
| "manufacturing_ratio": report["item29_genre"]["manufacturing_relevant_ratio"], "output": str(args.output_dir)}, ensure_ascii=False)) | |
| if __name__ == "__main__": | |
| main() | |