Add Common Corpus English filter and held-out split

This commit is contained in:
Daniel Samson committed 2026-11-21 12:15:58 +00:00
1 parent a7db571513
commit 6965ab25db
4 files changed
+249

No files matched your search

+42
View File
@@ -0,0 +1,42 @@
#!/usr/bin/env python3
"""Write a training corpus with the held-out eval documents removed.
Documents are matched by identifier, which is how the held-out sample was drawn.
The script fails if any held-out identifier is missing from the input, because that
would mean the held-out list and the corpus have drifted apart.
"""
import argparse
import json
from pathlib import Path
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--input-file", required=True, type=Path)
parser.add_argument("--heldout-ids", required=True, type=Path)
parser.add_argument("--output-file", required=True, type=Path)
args = parser.parse_args()
if args.output_file.exists():
parser.error(f"refusing to overwrite: {args.output_file}")
heldout = {line.strip() for line in args.heldout_ids.read_text(encoding="utf-8").splitlines()
if line.strip()}
found, kept, removed = set(), 0, 0
with args.input_file.open(encoding="utf-8") as source, \
args.output_file.open("x", encoding="utf-8") as target:
for line in source:
identifier = json.loads(line)["identifier"]
if identifier in heldout:
found.add(identifier)
removed += 1
continue
target.write(line)
kept += 1
missing = heldout - found
if missing:
args.output_file.unlink()
parser.error(f"{len(missing)} held-out identifiers not found in the corpus")
print(json.dumps({"kept": kept, "removed": removed, "heldout_ids": len(heldout)}, indent=2))
if __name__ == "__main__":
main()
+122
View File
@@ -0,0 +1,122 @@
#!/usr/bin/env python3
"""Filter Common Corpus Parquet shards to openly licensed English prose.
Every kept document keeps its identifier, collection and license, so provenance
travels with the text. A manifest records the inputs (SHA-256), the allowlists, and
how many documents each rule removed. Run with an environment that has pyarrow.
"""
import argparse
import hashlib
import json
import sys
from collections import Counter
from pathlib import Path
RESERVED = ("<|pad|>", "<|im_start|>", "<|im_end|>")
LICENSES = {"Public Domain", "CC0", "CC0-1.0", "CC-By", "CC-BY-4.0", "CC-By-SA"}
COLLECTIONS = {"Wikipedia", "English-PD", "US-PD-Books"}
SHARE_ALIKE = {"CC-By-SA"}
COLUMNS = ["identifier", "collection", "license", "language", "language_type", "text"]
def file_digest(path):
with Path(path).open("rb") as stream:
return hashlib.file_digest(stream, "sha256").hexdigest()
def prose_quality(text, min_words):
"""Reject short, symbol-heavy or OCR-garbled text."""
words = text.split()
if len(words) < min_words:
return "too_short"
compact = "".join(text.split())
letters = sum(char.isalpha() for char in compact)
if letters / max(len(compact), 1) < 0.7:
return "not_mostly_letters"
mean_length = sum(len(word) for word in words) / len(words)
if not 2.5 <= mean_length <= 12:
return "odd_word_length"
return None
def main():
import pyarrow.parquet as pq
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--input-file", action="append", required=True, type=Path)
parser.add_argument("--output-file", required=True, type=Path)
parser.add_argument("--manifest-file", required=True, type=Path)
parser.add_argument("--min-words", type=int, default=50)
args = parser.parse_args()
for path in (args.output_file, args.manifest_file):
if path.exists():
parser.error(f"refusing to overwrite: {path}")
reasons = Counter()
seen = set()
kept = Counter()
words = 0
shares = 0
args.output_file.parent.mkdir(parents=True, exist_ok=True)
with args.output_file.open("x", encoding="utf-8") as out:
for path in args.input_file:
parquet = pq.ParquetFile(path)
missing = [c for c in COLUMNS if c not in parquet.schema_arrow.names]
if missing:
parser.error(f"{path}: missing column(s): {', '.join(missing)}")
for batch in parquet.iter_batches(columns=COLUMNS):
for row in batch.to_pylist():
reasons["seen"] += 1
if row["language"] != "English" or row["language_type"] != "Written":
reasons["not_english_written"] += 1
continue
if row["collection"] not in COLLECTIONS:
reasons["collection_not_allowed"] += 1
continue
if row["license"] not in LICENSES:
reasons["license_not_allowed"] += 1
continue
text = row["text"] or ""
if any(token in text for token in RESERVED):
reasons["reserved_token"] += 1
continue
problem = prose_quality(text, args.min_words)
if problem:
reasons[problem] += 1
continue
digest = hashlib.sha256(" ".join(text.split()).lower().encode()).hexdigest()
if digest in seen:
reasons["duplicate"] += 1
continue
seen.add(digest)
record = {"text": text, "identifier": row["identifier"],
"collection": row["collection"], "license": row["license"]}
out.write(json.dumps(record, ensure_ascii=False) + "\n")
kept[row["license"]] += 1
words += len(text.split())
shares += row["license"] in SHARE_ALIKE
reasons["kept"] += 1
if not reasons["kept"]:
args.output_file.unlink()
parser.error("no documents passed the filters")
manifest = {
"inputs": [{"path": str(p), "sha256": file_digest(p)} for p in args.input_file],
"output": {"path": str(args.output_file), "sha256": file_digest(args.output_file)},
"allowlists": {"licenses": sorted(LICENSES), "collections": sorted(COLLECTIONS),
"language": "English", "language_type": "Written"},
"min_words": args.min_words,
"documents_kept": reasons["kept"],
"words_kept": words,
"kept_by_license": dict(kept),
"share_alike_documents": shares,
"removed_by_rule": {k: v for k, v in reasons.items() if k not in ("kept", "seen")},
"documents_seen": reasons["seen"],
}
args.manifest_file.write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
print(json.dumps({k: manifest[k] for k in ("documents_seen", "documents_kept", "words_kept",
"kept_by_license", "removed_by_rule")}, indent=2))
if __name__ == "__main__":
sys.exit(main())